mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into feat/cgm-open-place
This commit is contained in:
commit
3bf25bbf76
282 files changed
+16266
-1245
No files matched your search
@@ -18,6 +18,7 @@ pub mod colormgmt;
|
||||
pub mod colortheme;
|
||||
pub mod compositefonts;
|
||||
mod compoundshape;
|
||||
pub mod conceptvector;
|
||||
pub(crate) mod create;
|
||||
mod css;
|
||||
mod cut;
|
||||
@@ -365,6 +366,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(panelcmds::specs());
|
||||
v.extend(artboardalign::specs());
|
||||
v.extend(buildcmds::specs());
|
||||
v.extend(conceptvector::specs());
|
||||
v.extend(shaper::specs());
|
||||
v.extend(brushsym::specs());
|
||||
v.extend(patterncmds::specs());
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fix All Issues",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}",
|
||||
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents. An error, with nothing fixed, when the fixes would delete the artboard an open Create Font Sheet dialog uses → {scope, total, fixed: {kind: count}}",
|
||||
has_doc,
|
||||
fix
|
||||
),
|
||||
@@ -262,6 +262,13 @@ fn fix(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// With nothing to fix, the document and its undo history stay as they are.
|
||||
if total > 0 {
|
||||
if let Some(guard) = &s.artboard_deletion_guard {
|
||||
let st = s.doc()?;
|
||||
let protected = |doc: &Document| doc.artboards.iter().any(|a| a.id == guard.artboard);
|
||||
if (st.uid, st.reverts) == guard.document && protected(&st.doc) && !protected(&d) {
|
||||
return Err(EngineError::Other(guard.message.clone()));
|
||||
}
|
||||
}
|
||||
sel.prune(&d);
|
||||
s.edit("Fix Issues", |doc, selection| {
|
||||
*doc = d;
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Release Type on a Path
|
||||
//! splits type on a path into point type holding the same text and the plain path it was set on
|
||||
//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no
|
||||
//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
//! parity score. Create Font Sheet ([`font_sheet`]) sets a line of sample text in every font. Its
|
||||
//! submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
|
||||
pub mod font_sheet;
|
||||
pub mod numbers;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -76,6 +78,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
numbers::make_numbers
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(font_sheet::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Release Type on a Path's command (the id in [`specs`]).
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Create Font Sheet (`addon.type.fontSheet`; Object › Plug-ins › Type Tools › Create Font
|
||||
//! Sheet…): a line of sample text set once in each font the font menus list (or in the fonts a
|
||||
//! filter or a list names), each labeled with its font's name, flowed down columns on the active
|
||||
//! artboard and on new artboards to its right when it fills, as one group made in one undo step.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Shape};
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
use super::super::super::create::{new_type_para, new_type_style};
|
||||
use super::super::super::panelcmds::artboard_at;
|
||||
use super::super::super::typecmd::refresh_bounds;
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.type.fontSheet";
|
||||
/// The sample text when none is given.
|
||||
pub const DEFAULT_TEXT: &str = "The quick brown fox jumps over the lazy dog";
|
||||
/// Most fonts one sheet sets.
|
||||
pub const MAX_FONTS: usize = 5000;
|
||||
/// Most characters the sample text has.
|
||||
pub const MAX_CHARS: usize = 1000;
|
||||
/// The largest size a label is set at; a smaller sample's label is set at the sample's size.
|
||||
const LABEL_SIZE: f64 = 9.0;
|
||||
/// The space between the artboards the sheet adds, as `artboard.new` leaves it.
|
||||
const ARTBOARD_GAP: f64 = 20.0;
|
||||
/// The page a document without artboards lays the sheet out on (US Letter).
|
||||
const LETTER: Rect = Rect { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 };
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.type.fontSheet",
|
||||
"Create Font Sheet",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An entry whose font lacks a glyph needed by the sample stays on the sheet, and is listed in `fallback` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}",
|
||||
has_doc,
|
||||
font_sheet
|
||||
)]
|
||||
}
|
||||
|
||||
/// `key` of `p`: `default` when omitted, else a number in `range`.
|
||||
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && range.contains(n))
|
||||
.ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample text of `p`: one line, not empty, at most [`MAX_CHARS`] characters.
|
||||
fn sample_text(p: &Value) -> Result<String> {
|
||||
let text = match p.get("text") {
|
||||
None | Some(Value::Null) => return Ok(DEFAULT_TEXT.into()),
|
||||
Some(Value::String(t)) => t.clone(),
|
||||
Some(_) => return Err(bad(COMMAND, "`text` must be a string")),
|
||||
};
|
||||
if text.trim().is_empty() {
|
||||
return Err(bad(COMMAND, "`text` must not be empty"));
|
||||
}
|
||||
// The line and paragraph separators break a line too.
|
||||
if text.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) {
|
||||
return Err(bad(COMMAND, "`text` must be one line, without line breaks or other control characters"));
|
||||
}
|
||||
if text.chars().count() > MAX_CHARS {
|
||||
return Err(bad(COMMAND, format!("`text` must be at most {MAX_CHARS} characters")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// The families the sheet sets, in order: those `families` names, else those the font menus of
|
||||
/// `db` list whose name contains `filter`.
|
||||
fn families(p: &Value, db: &FontDb) -> Result<Vec<String>> {
|
||||
let filter = match p.get("filter") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(f)) => Some(f.trim().to_lowercase()).filter(|f| !f.is_empty()),
|
||||
Some(_) => return Err(bad(COMMAND, "`filter` must be a string")),
|
||||
};
|
||||
let listed = match p.get("families") {
|
||||
None | Some(Value::Null) => {
|
||||
let menu = db.menu_family_list();
|
||||
let wanted = |f: &&String| filter.as_ref().is_none_or(|w| f.to_lowercase().contains(w.as_str()));
|
||||
let found: Vec<String> = menu.iter().filter(wanted).cloned().collect();
|
||||
if found.is_empty() {
|
||||
return Err(bad(COMMAND, "no font family matches `filter`"));
|
||||
}
|
||||
return Ok(found);
|
||||
}
|
||||
Some(_) if p.get("filter").is_some_and(|f| !f.is_null()) => return Err(bad(COMMAND, "give `families` or `filter`, not both")),
|
||||
Some(Value::Array(a)) => a,
|
||||
Some(_) => return Err(bad(COMMAND, "`families` must be a list of font family names")),
|
||||
};
|
||||
if listed.is_empty() {
|
||||
return Err(bad(COMMAND, "`families` must name at least one family"));
|
||||
}
|
||||
let mut out: Vec<String> = Vec::with_capacity(listed.len());
|
||||
for f in listed {
|
||||
let f = f.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(COMMAND, "`families` must be a list of font family names"))?;
|
||||
if !db.has_family(f) {
|
||||
return Err(bad(COMMAND, format!("font family `{f}` is not available")));
|
||||
}
|
||||
// The name as the font menus spell it, looked up as the database compares names.
|
||||
let name = match db.composite_font(f) {
|
||||
Some(c) => c.name.clone(),
|
||||
None => db.canonical(f, "").0,
|
||||
};
|
||||
if out.iter().any(|o| o.to_lowercase() == name.to_lowercase()) {
|
||||
return Err(bad(COMMAND, format!("`families` names `{name}` twice")));
|
||||
}
|
||||
out.push(name);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The index of the artboard the view has active, else the one the document opened on, else the first.
|
||||
fn active_artboard(st: &crate::DocState) -> usize {
|
||||
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
|
||||
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn font_sheet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
font_sheet_in(s, p, FontDb::global())
|
||||
}
|
||||
|
||||
/// [`font_sheet`] over the fonts of `db`.
|
||||
fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let text = sample_text(p)?;
|
||||
let size = number(p, "size", 12.0, 1.0..=1296.0)?;
|
||||
let columns = number(p, "columns", 2.0, 1.0..=50.0)?;
|
||||
if columns.fract() != 0.0 {
|
||||
return Err(bad(C, "`columns` must be a whole number 1..50"));
|
||||
}
|
||||
let columns = columns as usize;
|
||||
let gap = number(p, "gap", 12.0, 0.0..=1000.0)?;
|
||||
let margin = number(p, "margin", 36.0, 0.0..=1000.0)?;
|
||||
let all_styles = switch_or(p, "allStyles", false, C)?;
|
||||
let labels = switch_or(p, "labels", true, C)?;
|
||||
let new_artboards = switch_or(p, "newArtboards", true, C)?;
|
||||
let families = families(p, db)?;
|
||||
|
||||
// Each entry's font: (family, style); no style for the family's Regular or closest style.
|
||||
let mut fonts: Vec<(String, Option<String>)> = vec![];
|
||||
for f in &families {
|
||||
let styles = if all_styles { db.styles(f) } else { vec![] };
|
||||
if styles.is_empty() {
|
||||
fonts.push((f.clone(), None));
|
||||
} else {
|
||||
fonts.extend(styles.into_iter().map(|st| (f.clone(), Some(st))));
|
||||
}
|
||||
if fonts.len() > MAX_FONTS {
|
||||
return Err(bad(C, format!("a sheet sets at most {MAX_FONTS} fonts: give `filter` or `families`")));
|
||||
}
|
||||
}
|
||||
|
||||
let label = size.min(LABEL_SIZE);
|
||||
// The artboard named, else `activeArtboard` (a replay of the journal), else the view's active
|
||||
// one, which the journal entry then records as `activeArtboard` so a replay uses the same artboard.
|
||||
let named = artboard_at(&s.doc()?.doc, p, "artboard", C)?;
|
||||
let active = match named.or(artboard_at(&s.doc()?.doc, p, "activeArtboard", C)?) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let st = s.doc()?;
|
||||
let i = active_artboard(st);
|
||||
if i < st.doc.artboards.len() {
|
||||
s.note_journal("activeArtboard", json!(i));
|
||||
}
|
||||
i
|
||||
}
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let template = d.artboards.get(active).cloned();
|
||||
let page = template.as_ref().map_or(LETTER, |a| a.rect);
|
||||
let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max);
|
||||
let system_layout = d.setup.system_layout;
|
||||
let parent = st.target_parent()?;
|
||||
// An entry's first baseline is at least one line's size below its top, and the entry at least
|
||||
// this tall; the fonts are only laid out when the page has room for that.
|
||||
let (least_above, least_height) = (if labels { label } else { size }, if labels { label } else { 0.0 } + size * 1.5);
|
||||
let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin);
|
||||
let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64;
|
||||
let no_room = || bad(C, "the margin, gap and columns leave no room for a font on the artboard");
|
||||
if column_w <= 0.0 || inner_h < least_height {
|
||||
return Err(no_room());
|
||||
}
|
||||
|
||||
let label_style = {
|
||||
let mut style = new_type_style(s, &json!({ "size": label }), C)?;
|
||||
style.leading = Some(label * 1.2);
|
||||
style
|
||||
};
|
||||
// Each entry laid out at the origin, and how far its laid-out ink reaches above and below its first baseline.
|
||||
let mut laid: Vec<(String, TextObject, (f64, f64))> = Vec::with_capacity(fonts.len());
|
||||
let mut skipped: Vec<String> = vec![];
|
||||
// The entries whose font lacks a glyph needed by the sample.
|
||||
let mut fallback: Vec<String> = vec![];
|
||||
for (family, style) in fonts {
|
||||
let mut sample = new_type_style(s, &json!({ "size": size, "font": family, "style": style }), C)?;
|
||||
sample.leading = Some(size * 1.2);
|
||||
let name = match &style {
|
||||
Some(st) => format!("{family} {st}"),
|
||||
None => family.clone(),
|
||||
};
|
||||
// A font that doesn't load is drawn in the fallback font, and a style that doesn't in the
|
||||
// family's closest style: either is left out. A composite font is left out when a part
|
||||
// that sets the sample names a font or style that doesn't load.
|
||||
let composite = db.composite_font(&family).is_some();
|
||||
// Layout picks a font for each character as typed, then draws All Caps type, and the
|
||||
// lowercase letters of Small Caps type, in capitals in that font, so coverage is checked on both.
|
||||
let caps = sample.all_caps || sample.small_caps.is_some();
|
||||
let (loads, covers) = if composite {
|
||||
// Glyph coverage is checked on the characters layout draws, in the sample's numeral system.
|
||||
let covers = db.composite_cased_coverage(&family, &[text.as_str()], sample.digits, caps).is_none_or(|c| c.lacking.is_empty());
|
||||
(db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), covers)
|
||||
} else {
|
||||
let wanted = db.canonical(&family, "").0;
|
||||
match db.face(&sample.font_family, &sample.font_style) {
|
||||
Some(face) if face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st)) => {
|
||||
let drawn = |t: &str| vectorcraft_text::drawn_chars(t, sample.digits).all(|c| face.covers(c));
|
||||
let capitals = || text.chars().flat_map(char::to_uppercase).collect::<String>();
|
||||
(true, drawn(&text) && (!caps || drawn(&capitals())))
|
||||
}
|
||||
_ => (false, true),
|
||||
}
|
||||
};
|
||||
if !loads {
|
||||
skipped.push(name);
|
||||
continue;
|
||||
}
|
||||
if !covers {
|
||||
fallback.push(name.clone());
|
||||
}
|
||||
let (first, more) = if labels {
|
||||
(TextRun::new(format!("{name}\n"), label_style.clone()), Some(TextRun::new(text.clone(), sample)))
|
||||
} else {
|
||||
(TextRun::new(text.clone(), sample), None)
|
||||
};
|
||||
let t = laid_out(first, more, system_layout);
|
||||
let extent = ink_extent(&t);
|
||||
laid.push((name, t, extent));
|
||||
}
|
||||
if laid.is_empty() {
|
||||
return Err(bad(C, "none of the fonts could be loaded"));
|
||||
}
|
||||
|
||||
// Each page's layout: each entry's first baseline as far below its top as its ink reaches above
|
||||
// it, a row as tall as the tallest entry with the gap below it, and the rows that fit inside the margin.
|
||||
let height = laid.iter().map(|(.., (a, b))| a.max(least_above) + b).fold(least_height, f64::max);
|
||||
let pitch = height + gap;
|
||||
if inner_h < height {
|
||||
return Err(no_room());
|
||||
}
|
||||
let rows = (((inner_h + gap) / pitch).floor() as usize).max(1);
|
||||
let per_page = rows * columns;
|
||||
// Where page `k` starts: the active artboard, then to the right of every artboard.
|
||||
let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) };
|
||||
let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(laid.len());
|
||||
for (i, (name, mut t, (above, _))) in laid.into_iter().enumerate() {
|
||||
let (k, j) = (i / per_page, i % per_page);
|
||||
let (col, row) = (j / rows, j % rows);
|
||||
let x = page_x(k) + margin + col as f64 * (column_w + gap);
|
||||
let baseline = page.y0 + margin + row as f64 * pitch + above.max(least_above);
|
||||
// The layout is in text space, so moving the type keeps it.
|
||||
t.xf = Affine::translate((x, baseline));
|
||||
entries.push((name, t));
|
||||
}
|
||||
let count = entries.len();
|
||||
let pages = count.div_ceil(per_page);
|
||||
let boards: Vec<Rect> = (1..pages).map(|k| Rect::new(page_x(k), page.y0, page_x(k) + page.width(), page.y1)).collect();
|
||||
let template = template.filter(|_| new_artboards);
|
||||
let (gid, added) = s.edit("Create Font Sheet", |d, sel| {
|
||||
let mut added = vec![];
|
||||
if let Some(template) = template {
|
||||
for rect in boards {
|
||||
let mut a = template.clone();
|
||||
a.id = d.next_artboard_id();
|
||||
a.name = format!("Artboard {}", d.artboards.len() + 1);
|
||||
a.rect = rect;
|
||||
a.locked = false;
|
||||
d.artboards.push(a);
|
||||
added.push(d.artboards.len() - 1);
|
||||
}
|
||||
}
|
||||
let children: Vec<Arc<Node>> = entries
|
||||
.into_iter()
|
||||
.map(|(name, t)| {
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
n.name = Some(name);
|
||||
Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::new(gid, NodeKind::Group { children, clip: false });
|
||||
g.name = Some("Font Sheet".into());
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok((gid, added))
|
||||
})?;
|
||||
let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "fallback": fallback, "artboards": added });
|
||||
let warnings: Vec<String> = skipped_warning(&skipped).into_iter().chain(fallback_warning(&fallback)).collect();
|
||||
if !warnings.is_empty() {
|
||||
out["warning"] = json!(warnings.join("; "));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The warning a sheet with entries whose font lacks a glyph of the sample gives, naming the first few.
|
||||
fn fallback_warning(fallback: &[String]) -> Option<String> {
|
||||
const NAMED: usize = 5;
|
||||
let (first, more) = (fallback.iter().take(NAMED).cloned().collect::<Vec<_>>(), fallback.len().saturating_sub(NAMED));
|
||||
match (first.is_empty(), more) {
|
||||
(true, _) => None,
|
||||
(false, 0) => Some(format!("{} font(s) lack glyphs for the sample: {}", fallback.len(), first.join(", "))),
|
||||
(false, more) => Some(format!("{} font(s) lack glyphs for the sample: {} and {more} more", fallback.len(), first.join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Point type set in `first` and then `more`, with its first baseline at the origin, laid out.
|
||||
fn laid_out(first: TextRun, more: Option<TextRun>, system_layout: bool) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "", first.style.clone());
|
||||
t.runs = std::iter::once(first).chain(more).collect();
|
||||
// Every paragraph is aligned left, right-to-left ones too, so each starts at the column's edge.
|
||||
t.para = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Left, ..new_type_para() };
|
||||
t.system_layout = system_layout;
|
||||
t.normalize_paras();
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
t.cached_bounds = Some(layout.bounds);
|
||||
t.cached_baselines = layout.baselines();
|
||||
let mut ink = layout.run_ink_bounds.clone();
|
||||
for (run, bar) in vectorcraft_text::decorations(&layout, FontDb::global(), &t) {
|
||||
if let Some(bounds) = ink.get_mut(run) {
|
||||
let bar = bar.bounding_box();
|
||||
*bounds = Some(bounds.map_or(bar, |bounds| bounds.union(bar)));
|
||||
}
|
||||
}
|
||||
t.cached_ink = Some((layout.bounds, ink.iter().copied().flatten().reduce(|a, b| a.union(b))));
|
||||
if t.runs.len() == 2
|
||||
&& let (Some(label), Some(sample)) = (ink[0], ink[1])
|
||||
{
|
||||
let overlap = label.y1 - sample.y0;
|
||||
if overlap > 0.0
|
||||
&& let Some(run) = t.runs.get_mut(1)
|
||||
{
|
||||
run.style.leading = Some(run.style.leading.unwrap_or(run.style.size * 1.2) + overlap);
|
||||
refresh_bounds(&mut t);
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// How far the ink of laid-out type `t` reaches above and below its first baseline, underline and
|
||||
/// strikethrough bars included; none when nothing draws.
|
||||
fn ink_extent(t: &TextObject) -> (f64, f64) {
|
||||
t.cached_ink.and_then(|(_, ink)| ink).map_or((0.0, 0.0), |b| ((-b.y0).max(0.0), b.y1.max(0.0)))
|
||||
}
|
||||
|
||||
/// The warning a sheet that left fonts out gives, naming the first few.
|
||||
fn skipped_warning(skipped: &[String]) -> Option<String> {
|
||||
const NAMED: usize = 5;
|
||||
let (first, more) = (skipped.iter().take(NAMED).cloned().collect::<Vec<_>>(), skipped.len().saturating_sub(NAMED));
|
||||
match (first.is_empty(), more) {
|
||||
(true, _) => None,
|
||||
(false, 0) => Some(format!("{} font(s) could not be loaded and were left out: {}", skipped.len(), first.join(", "))),
|
||||
(false, more) => Some(format!("{} font(s) could not be loaded and were left out: {} and {more} more", skipped.len(), first.join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,636 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::{COMMAND, DEFAULT_TEXT, MAX_CHARS};
|
||||
use crate::Session;
|
||||
|
||||
/// The bundled families, available on every platform.
|
||||
const BUNDLED: [&str; 3] = ["Inter", "Source Serif 4", "JetBrains Mono"];
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn group(s: &Session, r: &Value) -> Node {
|
||||
s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone()
|
||||
}
|
||||
|
||||
/// Each entry of the sheet `g`: its name and its type.
|
||||
fn entries(g: &Node) -> Vec<(String, TextObject)> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => (n.name.clone().unwrap_or_default(), (**t).clone()),
|
||||
_ => panic!("a font sheet holds only type"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the first baseline of `t` starts.
|
||||
fn origin(t: &TextObject) -> (f64, f64) {
|
||||
let [.., x, y] = t.xf.as_coeffs();
|
||||
(x, y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_sets_the_text_in_each_family_labeled_in_columns_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let undo = steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 2, "size": 12, "gap": 10, "margin": 20, "text": "Hamburgefonstiv"})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["artboards"], json!([]), "three entries fit on the artboard");
|
||||
assert_eq!(steps(&s), undo + 1, "one undo step");
|
||||
let g = group(&s, &r);
|
||||
assert_eq!(g.name.as_deref(), Some("Font Sheet"));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [g.id], "the sheet is selected");
|
||||
let e = entries(&g);
|
||||
assert_eq!(e.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), BUNDLED, "in the order given, each named after its font");
|
||||
for ((name, t), family) in e.iter().zip(BUNDLED) {
|
||||
assert_eq!(t.plain_text(), format!("{name}\nHamburgefonstiv"), "a label line, then the sample");
|
||||
let [label, sample] = &t.runs[..] else { panic!("a label run and a sample run: {:?}", t.runs.len()) };
|
||||
assert_eq!(sample.style.font_family, family);
|
||||
assert!((sample.style.size - 12.0).abs() < 1e-9 && (label.style.size - 9.0).abs() < 1e-9, "the label is set at 9 pt");
|
||||
assert_eq!(label.style.font_family, "Source Sans 3", "the label is in the normal type font");
|
||||
}
|
||||
// Down the first column, 9 + 18 + 10 pt apart, inside the 20 pt margin, the first baseline one label below the top.
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let (a, b) = (origin(&e[0].1), origin(&e[1].1));
|
||||
assert!((a.0 - board.x0 - 20.0).abs() < 1e-9 && (a.1 - board.y0 - 29.0).abs() < 1e-9, "{a:?}");
|
||||
assert!((b.0 - a.0).abs() < 1e-9 && (b.1 - a.1 - 37.0).abs() < 1e-9, "{b:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g.id).is_none(), "undo removes the sheet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_artboard_continues_on_new_artboards_to_the_right() {
|
||||
let mut s = session();
|
||||
let undo = steps(&s);
|
||||
// 400 pt tall less 2 × 100 pt of margin: 200 pt, room for two 72 pt entries (9 + 54 + 9).
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!(r["artboards"], json!([1]), "the third entry goes on a new artboard");
|
||||
assert_eq!(steps(&s), undo + 1, "the new artboard is in the same undo step");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let (first, added) = (doc.artboards[0].rect, doc.artboards[1].rect);
|
||||
assert!((added.x0 - first.x1 - 20.0).abs() < 1e-9 && (added.y0 - first.y0).abs() < 1e-9, "{added:?}");
|
||||
assert!((added.width() - first.width()).abs() < 1e-9 && (added.height() - first.height()).abs() < 1e-9, "the same size");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9, "inset by the margin on the new artboard");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "undo removes the artboard too");
|
||||
|
||||
// Without new artboards, the page after the first is laid out in the same place with none.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100, "newArtboards": false})).unwrap();
|
||||
assert_eq!(r["artboards"], json!([]));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_picks_families_and_all_styles_lists_each_style() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"filter": " sOURCE s ", "labels": false})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let names: Vec<&str> = e.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert!(e.len() >= 2 && names.len() == e.len(), "{names:?}");
|
||||
assert!(names.contains(&"Source Sans 3") && names.contains(&"Source Serif 4"), "{names:?}");
|
||||
assert!(names.iter().all(|n| n.to_lowercase().contains("source s")), "{names:?}");
|
||||
assert!(e.iter().all(|(_, t)| t.runs.len() == 1 && t.plain_text() == DEFAULT_TEXT), "no labels: the sample alone");
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Source Sans 3"], "allStyles": true})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let styles: Vec<String> = vectorcraft_text::FontDb::global().styles("Source Sans 3");
|
||||
assert!(styles.len() > 1, "{styles:?}");
|
||||
assert_eq!(e.len(), styles.len(), "one entry for each style");
|
||||
for ((name, t), style) in e.iter().zip(&styles) {
|
||||
assert_eq!(name, &format!("Source Sans 3 {style}"));
|
||||
assert_eq!(&t.runs[1].style.font_style, style);
|
||||
}
|
||||
}
|
||||
|
||||
/// Columns sit side by side, each `gap` apart and as wide as the room inside the margin allows.
|
||||
#[test]
|
||||
fn columns_share_the_room_inside_the_margin() {
|
||||
let mut s = session();
|
||||
// 400 pt less 2 × 50 pt of margin leaves 300 pt: eight 39 pt entries (9 + 18 + 12) fit in a column.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12})).unwrap();
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let e = entries(&group(&s, &r));
|
||||
// The first column fills before the second starts, so all three share it.
|
||||
let xs: Vec<f64> = e.iter().map(|(_, t)| origin(t).0).collect();
|
||||
assert!(!xs.is_empty(), "the sheet has entries");
|
||||
assert!(xs.iter().all(|x| (x - board.x0 - 50.0).abs() < 1e-9), "{xs:?}");
|
||||
// One row per column: each entry starts a column, (500 − 2 × 12) / 3 wide plus the gap apart.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "size": 150})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let step = (500.0 - 24.0) / 3.0 + 12.0;
|
||||
for (i, (_, t)) in e.iter().enumerate() {
|
||||
let (x, y) = origin(t);
|
||||
assert!((x - board.x0 - 50.0 - i as f64 * step).abs() < 1e-9 && (y - board.y0 - 59.0).abs() < 1e-9, "entry {i}: {x}, {y}");
|
||||
}
|
||||
assert_eq!(r["artboards"], json!([]));
|
||||
}
|
||||
|
||||
/// The journal records the active artboard, so a replay in a new session lays the sheet out on the
|
||||
/// same one; an action leaves it out, and a named artboard goes ahead of it.
|
||||
#[test]
|
||||
fn the_journal_records_the_artboard_the_sheet_was_laid_out_on() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].clone();
|
||||
s.doc_mut().unwrap().active_artboard = Some(second.id);
|
||||
let start = s.journal.len();
|
||||
let params = json!({"families": ["Inter"], "margin": 10});
|
||||
let r = s.execute(COMMAND, ¶ms).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "on the active artboard");
|
||||
let (id, recorded) = s.journal.last().unwrap().clone();
|
||||
assert_eq!((id.as_str(), &recorded["activeArtboard"]), (COMMAND, &json!(1)));
|
||||
assert_eq!(s.journal_for_action(start)[0].1.get("activeArtboard"), None, "an action uses the artboard active when it plays");
|
||||
|
||||
// A replay in a session whose view has no active artboard uses the recorded one.
|
||||
let mut fresh = session();
|
||||
fresh.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
|
||||
let r = fresh.replay(COMMAND, &recorded).unwrap();
|
||||
let e = entries(&group(&fresh, &r));
|
||||
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "the replay lays it out on the recorded artboard");
|
||||
// A named artboard goes ahead of the recorded one.
|
||||
let r = fresh.execute(COMMAND, &json!({"families": ["Inter"], "margin": 10, "artboard": 0, "activeArtboard": 1})).unwrap();
|
||||
let e = entries(&group(&fresh, &r));
|
||||
let first = fresh.doc().unwrap().doc.artboards[0].rect;
|
||||
assert!((origin(&e[0].1).0 - first.x0 - 10.0).abs() < 1e-9);
|
||||
assert!(fresh.execute(COMMAND, &json!({"families": ["Inter"], "artboard": 5})).is_err(), "no such artboard");
|
||||
}
|
||||
|
||||
/// A right-to-left sample starts at its column's left edge like any other, so it stays inside its column.
|
||||
#[test]
|
||||
fn a_right_to_left_sample_stays_inside_its_column() {
|
||||
let mut s = session();
|
||||
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
// Alone, and under a left-to-right label: each line starts at the column's left edge.
|
||||
for labels in [false, true] {
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(BUNDLED), "no bundled font has Hebrew glyphs, so each entry is named");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
|
||||
for (name, t) in &entries(&group(&s, &r)) {
|
||||
let x = origin(t).0;
|
||||
assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}");
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), t);
|
||||
for line in &layout.lines {
|
||||
let left = x + line.x0;
|
||||
assert!(left > board.x0 + 50.0 - 1e-6, "{name}, labels {labels}: a line starts at {left}, left of the column's edge");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variation_selector_does_not_require_a_separate_glyph() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
assert!(face.covers('A'));
|
||||
assert!(!face.covers('\u{fe0f}'));
|
||||
let text = "A\u{fe0f}";
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["fallback"], json!([]));
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 1);
|
||||
assert_eq!(e[0].1.plain_text(), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_uses_the_samples_numeral_system() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
assert!(face.covers('1'));
|
||||
assert!(!face.covers('\u{661}'));
|
||||
for (digits, text, missing) in [("hindi", "1", true), ("arabic", "\u{661}", false)] {
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": digits}}))
|
||||
.unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["fallback"], if missing { json!(["Inter"]) } else { json!([]) }, "{digits}: {r}");
|
||||
if missing {
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
|
||||
} else {
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
}
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 1);
|
||||
assert_eq!(e[0].1.plain_text(), text);
|
||||
assert_eq!(e[0].1.runs[0].style.digits.id(), digits);
|
||||
}
|
||||
}
|
||||
|
||||
/// All Caps in the normal character style draws the sample in capitals, so a font with a lowercase
|
||||
/// letter but not its capital is named in `fallback`, plain and composite fonts alike.
|
||||
#[test]
|
||||
fn coverage_checks_the_capitals_all_caps_draws() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
let lower = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let mut up = c.to_uppercase();
|
||||
face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
|
||||
let font = json!({"name": "CF Sheet Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let text = lower.to_string();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"all_caps": true}})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
assert_eq!(r["fallback"], json!(["Inter", "CF Sheet Caps"]), "{lower:?}: {r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs")), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!(e[0].1.runs[0].style.all_caps);
|
||||
assert_eq!(e[0].1.plain_text(), text, "the sample keeps its own case");
|
||||
// Layout picks the font for the character as typed, so one the font lacks still falls back
|
||||
// when the font has its capitals.
|
||||
let uncased = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let up: String = c.to_uppercase().collect();
|
||||
!face.covers(c) && up != c.to_string() && up.chars().all(|u| face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has every character whose capitals it has"));
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": uncased.to_string()})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(["Inter"]), "{uncased:?}: {r}");
|
||||
}
|
||||
|
||||
/// Small Caps in the normal character style draws lowercase letters as capitals too, so a font with
|
||||
/// a lowercase letter but not its capital is named in `fallback`, plain and composite fonts alike.
|
||||
#[test]
|
||||
fn coverage_checks_the_capitals_small_caps_draws() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
let lower = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let mut up = c.to_uppercase();
|
||||
c.is_lowercase() && face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
|
||||
let font = json!({"name": "CF Sheet Small Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let text = lower.to_string();
|
||||
let families = json!(["Inter", "CF Sheet Small Caps"]);
|
||||
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"small_caps": 70}})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 2);
|
||||
assert!(e[0].1.runs[0].style.small_caps.is_some());
|
||||
assert_eq!(r["fallback"], families, "{lower:?}: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
let long = "x".repeat(MAX_CHARS + 1);
|
||||
for bad in [
|
||||
json!({"text": ""}),
|
||||
json!({"text": " "}),
|
||||
json!({"text": "two\nlines"}),
|
||||
json!({"text": "two\u{2028}lines"}),
|
||||
json!({"text": "two\u{2029}paragraphs"}),
|
||||
json!({"text": long}),
|
||||
json!({"text": 5}),
|
||||
json!({"size": 0.5}),
|
||||
json!({"size": "12"}),
|
||||
json!({"columns": 0}),
|
||||
json!({"columns": 1.5}),
|
||||
json!({"gap": -1}),
|
||||
json!({"margin": 2000}),
|
||||
json!({"margin": 300}),
|
||||
json!({"columns": 50, "gap": 1000}),
|
||||
json!({"filter": "no family is called this"}),
|
||||
json!({"filter": 3}),
|
||||
json!({"families": []}),
|
||||
json!({"families": "Inter"}),
|
||||
json!({"families": ["Inter", "inter"]}),
|
||||
json!({"families": ["No Such Family Anywhere"]}),
|
||||
json!({"families": [""]}),
|
||||
json!({"families": ["Inter"], "filter": "Inter"}),
|
||||
json!({"families": ["Inter"], "filter": ""}),
|
||||
json!({"families": ["Inter"], "filter": " "}),
|
||||
json!({"labels": "yes"}),
|
||||
json!({"allStyles": 1}),
|
||||
json!({"newArtboards": "no"}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(steps(&s), before);
|
||||
let layers = &s.doc().unwrap().doc.layers;
|
||||
assert!(!layers.is_empty(), "the document keeps its layers");
|
||||
assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn");
|
||||
}
|
||||
|
||||
/// Fonts left out are named in the warning, the first five of them, with a count of the rest.
|
||||
#[test]
|
||||
fn fonts_left_out_are_named_in_a_warning() {
|
||||
let names = |n: usize| (1..=n).map(|i| format!("Font {i}")).collect::<Vec<_>>();
|
||||
assert_eq!(super::skipped_warning(&[]), None);
|
||||
assert_eq!(super::skipped_warning(&names(2)).as_deref(), Some("2 font(s) could not be loaded and were left out: Font 1, Font 2"));
|
||||
assert_eq!(
|
||||
super::skipped_warning(&names(7)).as_deref(),
|
||||
Some("7 font(s) could not be loaded and were left out: Font 1, Font 2, Font 3, Font 4, Font 5 and 2 more")
|
||||
);
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
|
||||
assert!(r.get("warning").is_none(), "nothing left out: no warning");
|
||||
}
|
||||
|
||||
/// A family the font menus list whose file no longer reads as a font is left out, as is a style
|
||||
/// that would be drawn in another style of its family; the rest of the sheet is made.
|
||||
#[test]
|
||||
fn fonts_that_do_not_load_are_left_out_and_named() {
|
||||
use vectorcraft_text::test_fonts::named_copy;
|
||||
let dir = vectorcraft_testkit::temp_dir("font-sheet-unreadable");
|
||||
let file = |family: &str, style: &str| dir.join(format!("{}-{style}.ttf", family.replace(' ', "")));
|
||||
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Regular"), ("Sheet Half", "Bold")] {
|
||||
let postscript = format!("{}-{style}", family.replace(' ', ""));
|
||||
std::fs::write(file(family, style), named_copy(false, (family, style, "Version 1.000", &postscript)).unwrap()).unwrap();
|
||||
}
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
// Cataloged while every file reads; then two of them stop reading as fonts.
|
||||
assert_eq!(db.styles("Sheet Half").len(), 2, "{:?}", db.styles("Sheet Half"));
|
||||
assert!(db.menu_family_list().iter().any(|f| f == "Sheet Gone"));
|
||||
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Bold")] {
|
||||
std::fs::write(file(family, style), b"not a font").unwrap();
|
||||
}
|
||||
let mut s = session();
|
||||
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone", "Inter"]}), &db).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["Sheet Gone"]), "drawn in the fallback font, it is left out: {r}");
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: Sheet Gone");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Half"], "allStyles": true}), &db).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["Sheet Half Bold"]), "drawn in its Regular, the Bold is left out: {r}");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Sheet Half Regular"]);
|
||||
// Nothing that loads: an error, with nothing changed.
|
||||
let before = steps(&s);
|
||||
assert!(super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone"]}), &db).is_err());
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
/// Where the ink of `t` starts and ends down the page.
|
||||
fn ink_rows(t: &TextObject) -> (f64, f64) {
|
||||
let (_, y) = origin(t);
|
||||
let b = vectorcraft_text::layout(FontDb::global(), t).ink_bounds().unwrap();
|
||||
(y + b.y0, y + b.y1)
|
||||
}
|
||||
|
||||
/// A composite font whose Roman part sets the sample at four times its size gets rows as tall as
|
||||
/// its laid-out ink: the first entry stays inside the margin, the second starts below the first,
|
||||
/// and each sample starts below its own label.
|
||||
#[test]
|
||||
fn rows_fit_the_laid_out_ink_of_a_composite_font() {
|
||||
let mut s = session();
|
||||
let big = |name: &str| json!({"name": name, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter", "size": 400}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [big("CF Sheet Big A"), big("CF Sheet Big B")]})).unwrap();
|
||||
let p = json!({"families": ["CF Sheet Big A", "CF Sheet Big B"], "columns": 1, "size": 12, "gap": 10, "margin": 20, "text": "Hamburg"});
|
||||
let r = s.execute(COMMAND, &p).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let e = entries(&group(&s, &r));
|
||||
let ((top0, bottom0), (top1, _)) = (ink_rows(&e[0].1), ink_rows(&e[1].1));
|
||||
assert!(top0 >= board.y0 + 20.0 - 1e-6, "the first entry reaches into the margin: {top0}");
|
||||
assert!(top1 >= bottom0 - 1e-6, "the second entry overlaps the first: {top1} < {bottom0}");
|
||||
for (name, t) in &e {
|
||||
let mut label = t.clone();
|
||||
label.runs.truncate(1);
|
||||
let mut sample = t.clone();
|
||||
sample.runs.remove(0);
|
||||
let (y0, y1) = (t.cached_baselines[0].0.y, t.cached_baselines[1].0.y);
|
||||
let label_bottom = y0 + vectorcraft_text::layout(FontDb::global(), &label).ink_bounds().unwrap().y1;
|
||||
let sample_top = y1 + vectorcraft_text::layout(FontDb::global(), &sample).ink_bounds().unwrap().y0;
|
||||
assert!(sample_top >= label_bottom - 1e-6, "{name}: the sample reaches into its label: {sample_top} < {label_bottom}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite font named in other letter case, accented letters included, is found by its own name.
|
||||
#[test]
|
||||
fn a_composite_font_named_in_other_case_is_set() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "\u{c9}preuve Sheet", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["\u{e9}preuve sheet"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!((r["skipped"].clone(), r["count"].clone()), (json!([]), json!(1)), "{r}");
|
||||
assert_eq!(entries(&group(&s, &r))[0].0, "\u{c9}preuve Sheet");
|
||||
let twice = s.execute(COMMAND, &json!({"families": ["\u{c9}preuve Sheet", "\u{e9}PREUVE SHEET"]})).unwrap_err().to_string();
|
||||
assert!(twice.contains("twice"), "{twice}");
|
||||
}
|
||||
|
||||
/// A composite font whose part setting the sample names a font that doesn't load is left out and
|
||||
/// named, as a family that doesn't load is.
|
||||
#[test]
|
||||
fn a_composite_font_with_a_missing_part_is_left_out() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "CF Sheet Gone", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Sheet Font"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Gone", "Inter"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["CF Sheet Gone"]), "{r}");
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composite_font_with_an_unavailable_part_style_is_left_out() {
|
||||
let mut s = session();
|
||||
let font = json!({
|
||||
"name": "CF Sheet Missing Style",
|
||||
"parts": {
|
||||
"kanji": {"font": "Source Sans 3"},
|
||||
"roman": {"font": "Inter", "style": "No Such Sheet Style"}
|
||||
}
|
||||
});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let coverage = FontDb::global().composite_coverage("CF Sheet Missing Style", &["Hamburg"]).unwrap();
|
||||
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Style);
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style", "Inter"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["CF Sheet Missing Style"]));
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: CF Sheet Missing Style");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
assert!(s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style"], "text": "Hamburg"})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc, before.0);
|
||||
assert_eq!(steps(&s), before.1);
|
||||
}
|
||||
|
||||
/// A composite font whose parts load but lack a glyph the sample needs stays on the sheet and is
|
||||
/// named in `fallback`, as a plain font is.
|
||||
#[test]
|
||||
fn a_composite_font_lacking_a_sample_glyph_is_named_as_a_fallback() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "CF Sheet Lacking", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
|
||||
let coverage = FontDb::global().composite_coverage("CF Sheet Lacking", &[rtl]).unwrap();
|
||||
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Exact);
|
||||
assert!(!coverage.lacking.is_empty());
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": rtl})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(1), &json!([])), "{r}");
|
||||
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("CF Sheet Lacking")), "{r}");
|
||||
// A variation selector needs no glyph of its own, and digits are checked in the sample's numeral system.
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "A\u{fe0f}"})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": "hindi"}}))
|
||||
.unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "1"})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_without_overlap_need_no_additional_layouts() {
|
||||
use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread};
|
||||
|
||||
let mut counts = vec![];
|
||||
for labels in [false, true] {
|
||||
let mut s = session();
|
||||
let before = layouts_on_this_thread();
|
||||
let ink_before = ink_work_on_this_thread();
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "text": "Hamburg", "labels": labels})).unwrap();
|
||||
let ink_after = ink_work_on_this_thread();
|
||||
counts.push(layouts_on_this_thread() - before);
|
||||
assert_eq!(r["count"], BUNDLED.len());
|
||||
let mut outlines = 0;
|
||||
for (_, t) in entries(&group(&s, &r)) {
|
||||
assert!(t.cached_ink.unwrap().1.is_some());
|
||||
assert_eq!(t.cached_baselines.len(), if labels { 2 } else { 1 });
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
outlines += layout.glyphs.iter().chain(&layout.ruby).filter(|glyph| !glyph.outline.elements().is_empty()).count() as u64;
|
||||
assert_eq!(t.cached_ink.unwrap().1, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
|
||||
}
|
||||
assert_eq!(ink_after.0 - ink_before.0, outlines, "each glyph outline is measured once");
|
||||
assert_eq!(ink_after.1 - ink_before.1, BUNDLED.len() as u64, "decorations are measured once per entry");
|
||||
}
|
||||
assert!(counts[0] > 0);
|
||||
assert_eq!(counts[1], counts[0], "labels that fit must not cause separate label and sample layouts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_font_sheet_ink_includes_decorations_and_handles_blank_runs() {
|
||||
use vectorcraft_doc::{CharStyle, TextRun};
|
||||
|
||||
for text in ["Hamburg", " "] {
|
||||
for labels in [false, true] {
|
||||
let style = CharStyle { font_family: "Inter".into(), size: 12.0, underline: true, strikethrough: true, ..Default::default() };
|
||||
let sample = TextRun::new(text, style.clone());
|
||||
let (first, more) = if labels { (TextRun::new("Font\n", style), Some(sample)) } else { (sample, None) };
|
||||
let t = super::laid_out(first, more, false);
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
let bars = vectorcraft_text::decorations(&layout, FontDb::global(), &t);
|
||||
assert!(!bars.is_empty(), "the entry includes underline and strikethrough bars");
|
||||
let ink = t.cached_ink.unwrap().1;
|
||||
assert_eq!(ink, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
|
||||
let ink = ink.unwrap();
|
||||
for (_, bar) in bars {
|
||||
let bounds = vectorcraft_geom::Shape::bounding_box(&bar);
|
||||
assert!(ink.x0 <= bounds.x0 && ink.y0 <= bounds.y0 && ink.x1 >= bounds.x1 && ink.y1 >= bounds.y1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"artboards": 3})).unwrap();
|
||||
let state = s.doc().unwrap();
|
||||
let document = (state.uid, state.reverts);
|
||||
let artboard = state.doc.artboards[1].id;
|
||||
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for params in [json!({"index": 0}), json!({"indices": [1, 0]})] {
|
||||
let error = s.execute("artboard.delete", ¶ms).unwrap_err();
|
||||
assert_eq!(error.to_string(), "The artboard is in use.");
|
||||
assert_eq!(s.doc().unwrap().doc, before.0);
|
||||
assert_eq!(steps(&s), before.1);
|
||||
}
|
||||
s.execute("file.new", &json!({"artboards": 2})).unwrap();
|
||||
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "another document is not protected");
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
s.doc_mut().unwrap().reverts += 1;
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected");
|
||||
}
|
||||
|
||||
/// Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards keep the guarded artboard too.
|
||||
#[test]
|
||||
fn an_artboard_deletion_guard_covers_every_command_that_deletes_artboards() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"artboards": 3})).unwrap();
|
||||
let state = s.doc().unwrap();
|
||||
let document = (state.uid, state.reverts);
|
||||
let artboard = state.doc.artboards[1].id;
|
||||
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for (command, params) in [
|
||||
("artboard.cut", json!({"index": 1})),
|
||||
("artboard.deleteEmpty", json!({})),
|
||||
("addon.cleanup.fix", json!({"kinds": ["emptyArtboards"], "scope": "document"})),
|
||||
] {
|
||||
let error = s.execute(command, ¶ms).unwrap_err();
|
||||
assert_eq!(error.to_string(), "The artboard is in use.", "{command}");
|
||||
assert_eq!(s.doc().unwrap().doc, before.0, "{command}");
|
||||
assert_eq!(steps(&s), before.1, "{command}");
|
||||
}
|
||||
s.execute("artboard.cut", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2, "another artboard is cut");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_needs_a_document() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.execute(COMMAND, &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_layer_takes_no_sheet() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err());
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_current_layer_sends_the_sheet_to_the_topmost_editable_layer() {
|
||||
let mut s = session();
|
||||
let editable = s.doc().unwrap().doc.layers[0].id;
|
||||
let locked = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
|
||||
let gid = NodeId(r["id"].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let holds = |layer: NodeId| doc.children(Some(layer)).is_some_and(|c| c.iter().any(|n| n.id == gid));
|
||||
assert!(holds(editable), "the sheet goes to the layer that is shown and unlocked");
|
||||
assert!(!holds(locked));
|
||||
}
|
||||
@@ -0,0 +1,830 @@
|
||||
//! Concept to Vector (`conceptVector.*`): vector variations of one selected image, made by a
|
||||
//! provider ([`crate::concept_vector`]), compared, and inserted beside the image.
|
||||
//!
|
||||
//! `conceptVector.generate` asks the named provider for one variation per style and keeps them as a
|
||||
//! job of this session; it changes nothing in the document. `conceptVector.insert` puts the chosen
|
||||
//! variations to the right of the image as one undo step. A job is kept until it is canceled, its
|
||||
//! document closes, or [`KEEP_JOBS`] newer ones replace it; it is never saved.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::buildcmds::TRACE_NAME;
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::shape_node;
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_id, cmd, has_doc, text_param};
|
||||
use crate::concept_vector::{self as cv, MAX_STYLES, Output, Provider, ProviderError, Request, Variation};
|
||||
|
||||
/// The most jobs a session keeps; a new one drops the oldest.
|
||||
pub const KEEP_JOBS: usize = 4;
|
||||
|
||||
/// The gap, in points, between the image and the first inserted variation, and between variations.
|
||||
pub const GAP: f64 = 24.0;
|
||||
|
||||
/// A job's variations, or that it was canceled.
|
||||
#[derive(Clone)]
|
||||
enum Outcome {
|
||||
Done(Arc<Vec<Variation>>),
|
||||
Canceled,
|
||||
}
|
||||
|
||||
/// What `conceptVector.generate` made, and what it was made of.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Job {
|
||||
id: u64,
|
||||
/// The document ([`crate::DocState::uid`]) and the object (an image or an Image Trace object).
|
||||
doc: u64,
|
||||
source: NodeId,
|
||||
image: ImageObject,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
provider: String,
|
||||
outcome: Outcome,
|
||||
}
|
||||
|
||||
/// The session's providers and jobs.
|
||||
pub(crate) struct ConceptState {
|
||||
pub(crate) registry: cv::Registry,
|
||||
jobs: VecDeque<Job>,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Default for ConceptState {
|
||||
fn default() -> Self {
|
||||
Self { registry: cv::Registry::default(), jobs: VecDeque::new(), next: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The Concept to Vector providers this session calls by id.
|
||||
pub fn concept_providers(&self) -> &cv::Registry {
|
||||
&self.concept.registry
|
||||
}
|
||||
|
||||
/// The providers, to register another ([`cv::Registry::register`]).
|
||||
pub fn concept_providers_mut(&mut self) -> &mut cv::Registry {
|
||||
&mut self.concept.registry
|
||||
}
|
||||
|
||||
/// Job `job`'s variations and the size in pixels of the image they were made of; `None` for a
|
||||
/// job this session does not keep, or one that was canceled.
|
||||
pub fn concept_variations(&self, job: u64) -> Option<(&[Variation], (u32, u32))> {
|
||||
let j = self.concept.jobs.iter().find(|j| j.id == job)?;
|
||||
match &j.outcome {
|
||||
Outcome::Done(v) => Some((v.as_slice(), (j.image.width, j.image.height))),
|
||||
Outcome::Canceled => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The document ([`crate::DocState::uid`]) job `job` was made in; `None` for a job this session
|
||||
/// does not keep.
|
||||
pub fn concept_job_doc(&self, job: u64) -> Option<u64> {
|
||||
self.concept.jobs.iter().find(|j| j.id == job).map(|j| j.doc)
|
||||
}
|
||||
|
||||
/// The jobs, for a batch to put back when a step fails. Job numbers are not reused.
|
||||
pub(crate) fn concept_jobs_snapshot(&self) -> VecDeque<Job> {
|
||||
self.concept.jobs.clone()
|
||||
}
|
||||
|
||||
/// Puts back the jobs that [`Self::concept_jobs_snapshot`] took.
|
||||
pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque<Job>) {
|
||||
self.concept.jobs = jobs;
|
||||
}
|
||||
|
||||
/// Exchanges the jobs with `jobs`: a script works on a copy of them, which becomes the
|
||||
/// session's only when the script ends without an error.
|
||||
pub(crate) fn swap_concept_jobs(&mut self, jobs: &mut VecDeque<Job>) {
|
||||
std::mem::swap(&mut self.concept.jobs, jobs);
|
||||
}
|
||||
|
||||
/// The number the next job gets.
|
||||
pub(crate) fn next_concept_job(&self) -> u64 {
|
||||
self.concept.next
|
||||
}
|
||||
|
||||
/// Takes in what the app did to the jobs while a script ran, `others` being the jobs as the app
|
||||
/// left them: a job canceled there is canceled here too, and the jobs numbered `from` or higher
|
||||
/// that this session does not keep (those the app made) are added. Then keeps the
|
||||
/// [`KEEP_JOBS`] newest of open documents.
|
||||
pub(crate) fn merge_concept_jobs(&mut self, others: VecDeque<Job>, from: u64) {
|
||||
for j in others {
|
||||
match self.concept.jobs.iter_mut().find(|k| k.id == j.id) {
|
||||
Some(k) if matches!(j.outcome, Outcome::Canceled) => k.outcome = Outcome::Canceled,
|
||||
Some(_) => {}
|
||||
None if j.id >= from => self.concept.jobs.push_back(j),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
self.concept.jobs.make_contiguous().sort_by_key(|j| j.id);
|
||||
self.prune_concept_jobs();
|
||||
while self.concept.jobs.len() > KEEP_JOBS {
|
||||
self.concept.jobs.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the jobs of document `doc` (its `uid`), when it closes.
|
||||
pub(crate) fn forget_concept_jobs(&mut self, doc: u64) {
|
||||
self.concept.jobs.retain(|j| j.doc != doc);
|
||||
}
|
||||
|
||||
/// Drops the jobs whose document is closed.
|
||||
/// In a batch, nothing is dropped until the batch ends without an error.
|
||||
pub(crate) fn prune_concept_jobs(&mut self) {
|
||||
if self.batch_stash.is_some() {
|
||||
return;
|
||||
}
|
||||
let open: Vec<u64> = self.documents().iter().map(|d| d.uid).collect();
|
||||
self.concept.jobs.retain(|j| open.contains(&j.doc));
|
||||
}
|
||||
}
|
||||
|
||||
/// The image `n` shows: its own, or the source image of an Image Trace object that wasn't expanded.
|
||||
fn shown_image(n: &Node) -> Option<&ImageObject> {
|
||||
match &shown_image_node(n)?.kind {
|
||||
NodeKind::Image(i) => Some(i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The image object [`shown_image`] reads: `n` itself, or the first member of its Image Trace object.
|
||||
fn shown_image_node(n: &Node) -> Option<&Node> {
|
||||
match &n.kind {
|
||||
NodeKind::Image(_) => Some(n),
|
||||
NodeKind::Group { clip: false, .. } if n.name.as_deref() == Some(TRACE_NAME) => {
|
||||
n.children()?.first().map(|i| &**i).filter(|i| matches!(i.kind, NodeKind::Image(_)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a group whose members are made or placed from data it holds (a graph, an Objects on
|
||||
/// Path, Shaper, dimension, flare or Live Paint group, a compound shape, a plug-in's generated
|
||||
/// art), so that a member added to it would be placed again, replaced or combined with the others?
|
||||
fn generated(n: &Node) -> bool {
|
||||
let e = n.extras();
|
||||
e.generated.is_some()
|
||||
|| e.graph.is_some()
|
||||
|| e.objects_on_path.is_some()
|
||||
|| e.shaper.is_some()
|
||||
|| e.dimension.is_some()
|
||||
|| e.flare.is_some()
|
||||
|| e.compound_shape
|
||||
|| vectorcraft_tools::builder::is_live_paint(n)
|
||||
}
|
||||
|
||||
const NO_SOURCE: &str = "select one image or an unexpanded Image Trace object";
|
||||
|
||||
const LOCKED: &str = "the image is locked or hidden";
|
||||
|
||||
/// The object `id` names, else the one selected: an image or an unexpanded Image Trace object,
|
||||
/// shown and unlocked with every layer and group around it, and not on a locked artboard → it, its
|
||||
/// image and the image's bytes.
|
||||
fn source(s: &Session, c: &str, p: &Value) -> Result<(NodeId, ImageObject, Arc<Vec<u8>>)> {
|
||||
let id = match p.get("id").filter(|v| !v.is_null()) {
|
||||
Some(v) => checked_id(s, v, c)?,
|
||||
None => match selected_roots(s)?.as_slice() {
|
||||
[one] => *one,
|
||||
_ => return Err(bad(c, NO_SOURCE)),
|
||||
},
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let image = shown_image(n).ok_or_else(|| bad(c, NO_SOURCE))?;
|
||||
if !d.is_editable(id) {
|
||||
return Err(bad(c, LOCKED));
|
||||
}
|
||||
let blob = d.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?;
|
||||
Ok((id, image.clone(), Arc::clone(&blob.bytes)))
|
||||
}
|
||||
|
||||
/// A generation prepared from the session, which runs without it ([`ConceptRun::run`]), on any
|
||||
/// thread, and is kept as a job with [`ConceptRun::finish`].
|
||||
pub struct ConceptRun {
|
||||
provider: Arc<dyn Provider>,
|
||||
/// The provider's id, as it was registered.
|
||||
provider_id: &'static str,
|
||||
request: Request,
|
||||
doc: u64,
|
||||
source: NodeId,
|
||||
image: ImageObject,
|
||||
}
|
||||
|
||||
impl ConceptRun {
|
||||
/// What `conceptVector.generate` with params `p` makes in the active document, checked as the
|
||||
/// command checks it.
|
||||
pub fn prepare(s: &Session, p: &Value) -> Result<ConceptRun> {
|
||||
const C: &str = "conceptVector.generate";
|
||||
let name = text_param(p, "provider", C)?.ok_or_else(|| bad(C, "missing `provider` (see conceptVector.providers)"))?;
|
||||
let found =
|
||||
s.concept.registry.get(name).ok_or_else(|| bad(C, format!("no Concept to Vector provider `{name}` (see conceptVector.providers)")))?;
|
||||
let (caps, pid, provider) = (&found.capabilities, found.id, Arc::clone(&found.provider));
|
||||
let styles_error = || bad(C, format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)"));
|
||||
// The count is checked before any id is copied or scanned for repeats.
|
||||
let styles: Vec<String> = match p.get("styles") {
|
||||
Some(Value::Array(a)) if (1..=MAX_STYLES).contains(&a.len()) => {
|
||||
a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<_>>().ok_or_else(styles_error)?
|
||||
}
|
||||
_ => return Err(styles_error()),
|
||||
};
|
||||
let known = |id: &String| caps.styles.iter().any(|st| st.id == id);
|
||||
let unique = styles.iter().enumerate().all(|(i, id)| !styles.get(..i).unwrap_or_default().contains(id));
|
||||
if !unique || !styles.iter().all(known) {
|
||||
return Err(styles_error());
|
||||
}
|
||||
let prompt = text_param(p, "prompt", C)?.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);
|
||||
// Results are vector paths, inserted as vector art, whatever else a provider makes.
|
||||
let output = match text_param(p, "output", C)? {
|
||||
None | Some("vector") => Output::Vector,
|
||||
Some(_) => return Err(bad(C, "`output` must be \"vector\"")),
|
||||
};
|
||||
if !caps.image_input {
|
||||
return Err(bad(C, format!("`{pid}` does not take an image")));
|
||||
}
|
||||
if !caps.vector_output {
|
||||
return Err(bad(C, format!("`{pid}` does not make vector art")));
|
||||
}
|
||||
if prompt.is_some() && !caps.prompt {
|
||||
return Err(bad(C, format!("`{pid}` takes no prompt")));
|
||||
}
|
||||
let detail = match p.get("detail") {
|
||||
None => 50,
|
||||
Some(v) => v.as_u64().filter(|d| *d <= 100).ok_or_else(|| bad(C, "`detail` must be a whole number from 0 to 100"))? as u8,
|
||||
};
|
||||
let (source, image, bytes) = source(s, C, p)?;
|
||||
let request = Request { image: bytes, width: image.width, height: image.height, prompt, styles, detail, output };
|
||||
Ok(ConceptRun { provider, provider_id: pid, request, doc: s.doc()?.uid, source, image })
|
||||
}
|
||||
|
||||
/// The document it was prepared in ([`crate::DocState::uid`]).
|
||||
pub fn doc(&self) -> u64 {
|
||||
self.doc
|
||||
}
|
||||
|
||||
/// The image or Image Trace object it makes variations of.
|
||||
pub fn source(&self) -> NodeId {
|
||||
self.source
|
||||
}
|
||||
|
||||
/// Asks the provider for the variations and checks them ([`cv::check_result`]), telling `steps`
|
||||
/// how far it has got; it touches no document. A panic in the provider is an error.
|
||||
pub fn run(&self, steps: cv::Steps) -> std::result::Result<Vec<Variation>, ProviderError> {
|
||||
let made = crate::guard::catch_panic(|| self.provider.generate(&self.request, steps)).map_err(ProviderError::Internal)??;
|
||||
cv::check_result(&self.request, &made)?;
|
||||
Ok(made)
|
||||
}
|
||||
|
||||
/// How many styles it makes.
|
||||
pub fn style_count(&self) -> usize {
|
||||
self.request.styles.len()
|
||||
}
|
||||
|
||||
/// Does the next part of the run kept in `run`, for a caller with no thread for
|
||||
/// [`ConceptRun::run`] (the web build), which can run other work, or stop, between the parts
|
||||
/// → whether every style is made ([`PartRun::made`]). A provider that makes parts
|
||||
/// ([`cv::Provider::parts`]) does one of its own; the others make one style alone, and the
|
||||
/// styles made so far are checked together ([`cv::check_result`]) after each one, so the
|
||||
/// totals stop the run as soon as they are passed. A panic in the provider is an error.
|
||||
pub fn run_part(&self, run: &mut PartRun, steps: cv::Steps) -> std::result::Result<bool, ProviderError> {
|
||||
let guard = ProviderError::Internal;
|
||||
if run.parts.is_none() {
|
||||
run.parts = Some(crate::guard::catch_panic(|| self.provider.parts(&self.request)).map_err(guard)?);
|
||||
}
|
||||
if let Some(Some(parts)) = &mut run.parts {
|
||||
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
|
||||
if !steps(run.done as u64, self.style_count() as u64) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
let Some(made) = crate::guard::catch_panic(|| parts.step()).map_err(guard)?? else {
|
||||
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
|
||||
return Ok(false);
|
||||
};
|
||||
cv::check_result(&self.request, &made)?;
|
||||
run.made = made;
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(style) = self.request.styles.get(run.made.len()) else { return Ok(true) };
|
||||
let one = Request { styles: vec![style.clone()], ..self.request.clone() };
|
||||
let next = crate::guard::catch_panic(|| self.provider.generate(&one, steps)).map_err(guard)??;
|
||||
cv::check_result(&one, &next)?;
|
||||
// A style that takes the totals past their limits is dropped, so `run` keeps only the
|
||||
// styles that passed.
|
||||
let kept = run.made.len();
|
||||
run.made.extend(next);
|
||||
let so_far = Request { styles: self.request.styles.get(..run.made.len()).unwrap_or_default().to_vec(), ..one };
|
||||
if let Err(e) = cv::check_result(&so_far, &run.made) {
|
||||
run.made.truncate(kept);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(run.made.len() == self.request.styles.len())
|
||||
}
|
||||
|
||||
/// Keeps `variations` as a new job of `s` → the job, as `conceptVector.results` gives it;
|
||||
/// `None`, keeping nothing, when the document it was prepared in has closed.
|
||||
pub fn finish(self, s: &mut Session, variations: Vec<Variation>) -> Option<Value> {
|
||||
s.prune_concept_jobs();
|
||||
if !s.documents().iter().any(|d| d.uid == self.doc) {
|
||||
return None;
|
||||
}
|
||||
let id = s.concept.next;
|
||||
s.concept.next += 1;
|
||||
let job = Job {
|
||||
id,
|
||||
doc: self.doc,
|
||||
source: self.source,
|
||||
image: self.image,
|
||||
bytes: self.request.image,
|
||||
provider: self.provider_id.to_string(),
|
||||
outcome: Outcome::Done(Arc::new(variations)),
|
||||
};
|
||||
let out = job_json(&s.concept.registry, &job);
|
||||
s.concept.jobs.push_back(job);
|
||||
while s.concept.jobs.len() > KEEP_JOBS {
|
||||
s.concept.jobs.pop_front();
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a run made a part at a time ([`ConceptRun::run_part`]) has got.
|
||||
#[derive(Default)]
|
||||
pub struct PartRun {
|
||||
/// The provider's parts, once asked for (`None` inside: it makes one style at a time).
|
||||
parts: Option<Option<Box<dyn cv::Parts>>>,
|
||||
/// The styles the provider's parts had made when last asked, inside the panic guard.
|
||||
done: usize,
|
||||
made: Vec<Variation>,
|
||||
}
|
||||
|
||||
impl PartRun {
|
||||
/// The styles made so far.
|
||||
pub fn styles_done(&self) -> usize {
|
||||
if self.made.is_empty() { self.done } else { self.made.len() }
|
||||
}
|
||||
|
||||
/// The variations made: all of them once [`ConceptRun::run_part`] has said so.
|
||||
pub fn made(self) -> Vec<Variation> {
|
||||
self.made
|
||||
}
|
||||
}
|
||||
|
||||
/// `e` as the engine's error.
|
||||
pub fn provider_error(e: ProviderError) -> EngineError {
|
||||
match e {
|
||||
ProviderError::Canceled => EngineError::Cancelled,
|
||||
e => EngineError::Other(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The English name of style `style` of provider `provider`, else the id.
|
||||
fn style_label(registry: &cv::Registry, provider: &str, style: &str) -> String {
|
||||
let caps = registry.get(provider).map(|p| &p.capabilities);
|
||||
caps.and_then(|c| c.styles.iter().find(|s| s.id == style).map(|s| s.label.to_string())).unwrap_or_else(|| style.to_string())
|
||||
}
|
||||
|
||||
/// Where `style` comes in the styles `provider` lists; after them when it lists no such style.
|
||||
fn style_rank(registry: &cv::Registry, provider: &str, style: &str) -> usize {
|
||||
let caps = registry.get(provider).map(|p| &p.capabilities);
|
||||
caps.and_then(|c| c.styles.iter().position(|s| s.id == style)).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// Where `image`'s pixels lie in the document.
|
||||
fn image_rect(image: &ImageObject) -> Option<Rect> {
|
||||
let r = Rect::new(0.0, 0.0, f64::from(image.width.max(1)), f64::from(image.height.max(1)));
|
||||
let pts = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| image.xf * kurbo::Point::new(x, y));
|
||||
let mut out = Rect::from_points(pts[0], pts[0]);
|
||||
for q in &pts[1..] {
|
||||
out = out.union_pt(*q);
|
||||
}
|
||||
[out.x0, out.y0, out.x1, out.y1].iter().all(|v| v.is_finite()).then_some(out)
|
||||
}
|
||||
|
||||
fn job_json(registry: &cv::Registry, j: &Job) -> Value {
|
||||
let (state, variations) = match &j.outcome {
|
||||
Outcome::Done(v) => ("done", v.as_slice()),
|
||||
Outcome::Canceled => ("canceled", &[][..]),
|
||||
};
|
||||
let variations: Vec<Value> = variations
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let bounds = v.paths.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b));
|
||||
json!({
|
||||
"style": v.style,
|
||||
"label": style_label(registry, &j.provider, &v.style),
|
||||
"paths": v.paths.len(),
|
||||
"anchors": v.anchors(),
|
||||
"bounds": bounds.map(|b| [b.x0, b.y0, b.x1, b.y1]),
|
||||
"warnings": v.warnings,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({ "job": j.id, "provider": j.provider, "source": j.source.0, "state": state, "variations": variations })
|
||||
}
|
||||
|
||||
/// The `job` param of command `c`.
|
||||
fn job_param(c: &str, p: &Value) -> Result<u64> {
|
||||
p.get("job").and_then(Value::as_u64).ok_or_else(|| bad(c, "`job` must be a job number from conceptVector.generate"))
|
||||
}
|
||||
|
||||
/// The error of command `c` for a job the session does not keep.
|
||||
fn no_job(c: &str, job: u64) -> EngineError {
|
||||
bad(c, format!("no Concept to Vector job {job}: it was never made, or was dropped (see conceptVector.results)"))
|
||||
}
|
||||
|
||||
/// The index of job `job` among those `s` keeps.
|
||||
fn job_index(s: &mut Session, c: &str, job: u64) -> Result<usize> {
|
||||
s.prune_concept_jobs();
|
||||
s.concept.jobs.iter().position(|j| j.id == job).ok_or_else(|| no_job(c, job))
|
||||
}
|
||||
|
||||
fn providers(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let list: Vec<Value> = s
|
||||
.concept
|
||||
.registry
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let c = &p.capabilities;
|
||||
json!({
|
||||
"id": p.id,
|
||||
"name": p.name,
|
||||
"available": true,
|
||||
"offline": c.offline,
|
||||
"imageInput": c.image_input,
|
||||
"vectorOutput": c.vector_output,
|
||||
"prompt": c.prompt,
|
||||
"rasterOutput": c.raster_output,
|
||||
"maxStyles": MAX_STYLES,
|
||||
"styles": c.styles,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let selected = s.concept.registry.iter().next().map(|p| p.id);
|
||||
Ok(json!({ "providers": list, "selected": selected }))
|
||||
}
|
||||
|
||||
fn generate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let run = ConceptRun::prepare(s, p)?;
|
||||
// A script's run stops when the script is asked to stop, and keeps no job.
|
||||
let stop = s.script_in_run.then(|| s.script_interrupt());
|
||||
let stopped = || stop.as_ref().is_some_and(|i| i.is_set());
|
||||
let made = run.run(&|_, _| !stopped()).map_err(provider_error)?;
|
||||
if stopped() {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
run.finish(s, made).ok_or(EngineError::NoDocument)
|
||||
}
|
||||
|
||||
fn results(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.results";
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
|
||||
Ok(job_json(&s.concept.registry, j))
|
||||
}
|
||||
|
||||
/// The error of an insert or cancel played from recorded steps: a job lives only in this session,
|
||||
/// and a job number from another one may name other results.
|
||||
const REPLAYED: &str = "Concept to Vector jobs are not saved, so a recorded insert or cancel does not play again: generate again";
|
||||
|
||||
fn cancel(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.cancel";
|
||||
if s.replaying() {
|
||||
return Err(bad(C, REPLAYED));
|
||||
}
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
if let Some(j) = s.concept.jobs.get_mut(at) {
|
||||
j.outcome = Outcome::Canceled;
|
||||
}
|
||||
Ok(json!({ "job": job, "state": "canceled" }))
|
||||
}
|
||||
|
||||
/// The appearance of variation path `p`, its widths scaled by `unit` (points per pixel).
|
||||
fn appearance_of(p: &cv::VectorPath, unit: f64) -> Appearance {
|
||||
let solid = |c: [u8; 3]| Paint::solid(Color::rgb8(c[0], c[1], c[2]));
|
||||
let mut items = vec![];
|
||||
if let Some(c) = p.fill {
|
||||
items.push(AppearanceItem::Fill(FillLayer::new(solid(c))));
|
||||
}
|
||||
if let Some((c, w)) = p.stroke {
|
||||
let cap = if p.square_caps { LineCap::Square } else { LineCap::Round };
|
||||
items.push(AppearanceItem::Stroke(StrokeLayer { cap, join: LineJoin::Round, ..StrokeLayer::new(solid(c), w * unit) }));
|
||||
}
|
||||
Appearance { items, ..Default::default() }
|
||||
}
|
||||
|
||||
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.insert";
|
||||
if s.replaying() {
|
||||
return Err(bad(C, REPLAYED));
|
||||
}
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
let list_error = || bad(C, format!("`variations` must list different style ids of job {job}"));
|
||||
let listed = match p.get("variations") {
|
||||
Some(Value::Array(a)) if !a.is_empty() => a,
|
||||
_ => return Err(list_error()),
|
||||
};
|
||||
let stale = || bad(C, format!("job {job} no longer applies: its document, image or image placement changed, so generate again"));
|
||||
let (doc, source, image, bytes, picked, label_of) = {
|
||||
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
|
||||
let Outcome::Done(all) = &j.outcome else { return Err(bad(C, format!("job {job} has no results to insert: it was canceled"))) };
|
||||
// The count is checked before the ids are read or scanned for repeats.
|
||||
if listed.len() > all.len() {
|
||||
return Err(list_error());
|
||||
}
|
||||
let chosen: Vec<&str> = listed.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(list_error)?;
|
||||
let unique = chosen.iter().enumerate().all(|(i, id)| !chosen.get(..i).unwrap_or_default().contains(id));
|
||||
let mut picked: Vec<Variation> = all.iter().filter(|v| chosen.contains(&v.style.as_str())).cloned().collect();
|
||||
if !unique || picked.len() != chosen.len() {
|
||||
return Err(list_error());
|
||||
}
|
||||
// In the provider's order, whatever order they were listed or generated in.
|
||||
picked.sort_by_key(|v| style_rank(&s.concept.registry, &j.provider, &v.style));
|
||||
let labels: Vec<String> = picked.iter().map(|v| style_label(&s.concept.registry, &j.provider, &v.style)).collect();
|
||||
(j.doc, j.source, j.image.clone(), Arc::clone(&j.bytes), picked, labels)
|
||||
};
|
||||
// The same document, the same object showing the same pixels where they were.
|
||||
let st = s.doc()?;
|
||||
let now = st.doc.node(source).and_then(shown_image);
|
||||
let same_pixels = || st.doc.images.get(&image.key).is_some_and(|b| Arc::ptr_eq(&b.bytes, &bytes) || *b.bytes == *bytes);
|
||||
let current = st.uid == doc && now.is_some_and(|i| i.key == image.key && i.xf == image.xf && i.width == image.width && i.height == image.height);
|
||||
if !current || !same_pixels() {
|
||||
return Err(stale());
|
||||
}
|
||||
if !st.doc.is_editable(source) {
|
||||
return Err(bad(C, LOCKED));
|
||||
}
|
||||
// The results go above the outermost group around the image that clips or masks it, so that
|
||||
// it hides none of them, and above the outermost envelope, blend, repeat or other live object,
|
||||
// the outermost group whose members it makes or places ([`generated`]), and the outermost
|
||||
// group with effects or fills and strokes of its own, so that its content and the place its
|
||||
// effects measure from stay as they are. A layer that clips or masks its art, or has effects,
|
||||
// fills or strokes of its own, leaves them nowhere to go. An effect that moves or reshapes
|
||||
// the image, its own or a group's around it, shows it away from its placement, which the
|
||||
// results are placed by.
|
||||
let ancestry = st.doc.ancestry(source).ok_or_else(stale)?;
|
||||
let moves = |id: &NodeId| st.doc.node(*id).is_some_and(|n| !n.is_layer() && vectorcraft_render::effects::has_geometry(&n.appearance.effects));
|
||||
if ancestry.iter().any(moves) {
|
||||
return Err(bad(C, "the image or a group around it has effects that move or reshape it, so the results would not go beside it"));
|
||||
}
|
||||
// A distorted image ([`Node::image_quad`]) is drawn at its corners, not by its transform.
|
||||
if st.doc.node(source).and_then(shown_image_node).is_some_and(Node::is_distorted_image) {
|
||||
return Err(bad(C, "the image is distorted, so the results would not go beside it"));
|
||||
}
|
||||
let mut anchor = source;
|
||||
for &id in ancestry.iter().rev().skip(1) {
|
||||
let n = st.doc.node(id).ok_or_else(stale)?;
|
||||
let masked = n.extras().mask.as_ref().is_some_and(|m| !m.disabled);
|
||||
if matches!(n.kind, NodeKind::Layer { clip: true, .. }) {
|
||||
return Err(bad(C, "the image is on a layer with a clipping mask, which would hide the results"));
|
||||
}
|
||||
if n.is_layer() && masked {
|
||||
return Err(bad(C, "the image is on a layer with an opacity mask, which would hide the results"));
|
||||
}
|
||||
let styled = !n.appearance.items.is_empty() || !n.appearance.effects.is_empty();
|
||||
if n.is_layer() && !n.appearance.effects.is_empty() {
|
||||
return Err(bad(C, "the image is on a layer with effects of its own, which would apply to the results"));
|
||||
}
|
||||
// A layer's fills and strokes paint over its members, the results included.
|
||||
if n.is_layer() && !n.appearance.items.is_empty() {
|
||||
return Err(bad(C, "the image is on a layer with fills or strokes of its own, which would apply to the results"));
|
||||
}
|
||||
let live = !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || generated(n);
|
||||
if !n.is_layer() && (masked || live || styled || matches!(n.kind, NodeKind::Group { clip: true, .. })) {
|
||||
anchor = id;
|
||||
}
|
||||
}
|
||||
let src = image_rect(&image).ok_or_else(stale)?;
|
||||
// A variation with no paths adds nothing: it is left out, and with none left nothing changes.
|
||||
let (picked, label_of): (Vec<Variation>, Vec<String>) = picked.into_iter().zip(label_of).filter(|(v, _)| !v.paths.is_empty()).unzip();
|
||||
if picked.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let unit = image.xf.determinant().abs().sqrt();
|
||||
// Each chosen variation's box over the image: the image's box and the variation's painted
|
||||
// bounds, which may reach past it. A square cap's corner lies half the width along the path
|
||||
// and half across it from the end, so up to √2 times half the width past it on an axis.
|
||||
let boxes: Vec<Rect> = picked
|
||||
.iter()
|
||||
.map(|v| {
|
||||
v.paths
|
||||
.iter()
|
||||
.filter_map(|vp| {
|
||||
let reach = if vp.square_caps { std::f64::consts::SQRT_2 } else { 1.0 };
|
||||
let half = vp.stroke.map_or(0.0, |(_, w)| w * unit / 2.0 * reach);
|
||||
vp.path.transformed(image.xf).bounds().map(|b| b.inflate(half, half))
|
||||
})
|
||||
.fold(src, |a, b| a.union(b))
|
||||
})
|
||||
.collect();
|
||||
// How far each variation's box is moved past the first's: each box starts GAP to the right of
|
||||
// the one before it (`width + GAP` further right for boxes the image's size).
|
||||
let mut offsets = Vec::with_capacity(boxes.len());
|
||||
let mut next = 0.0;
|
||||
for (k, b) in boxes.iter().enumerate() {
|
||||
if let Some(prev) = k.checked_sub(1).and_then(|j| boxes.get(j)) {
|
||||
next += prev.x1 - b.x0 + GAP;
|
||||
}
|
||||
offsets.push(next);
|
||||
}
|
||||
// The first box's left edge, which may lie left of the image's where its variation paints there.
|
||||
let first = boxes.first().map_or(src.x0, |b| b.x0);
|
||||
// The boxes with the first one's left edge moved to `x0`, the others after it.
|
||||
let row = |x0: f64| -> Vec<Rect> {
|
||||
boxes
|
||||
.iter()
|
||||
.zip(&offsets)
|
||||
.map(|(b, off)| {
|
||||
let dx = x0 + off - first;
|
||||
Rect::new(b.x0 + dx, b.y0, b.x1 + dx, b.y1)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The painted bounds of every visible object (the source's too: an Image Trace object's traced
|
||||
// art and effects can reach past the image), and the image's own box. A layer or group that
|
||||
// paints nothing of its own is measured by its members (an opacity mask only hides them); one
|
||||
// that clips, by its members after the clipping path, cut to what it paints.
|
||||
let mut obstacles: Vec<Rect> = vec![src];
|
||||
// One lookup of the symbols for the whole walk, so each symbol's art is measured once.
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let mut stack: Vec<(&Arc<Node>, Option<Rect>)> = st.doc.layers.iter().map(|l| (l, None)).collect();
|
||||
while let Some((node, within)) = stack.pop() {
|
||||
if !node.visible {
|
||||
continue;
|
||||
}
|
||||
let cut = |b: Rect| match within {
|
||||
Some(w) => Some(b.intersect(w)).filter(|i| i.width() > 0.0 && i.height() > 0.0),
|
||||
None => Some(b),
|
||||
};
|
||||
let painted = || vectorcraft_render::painted_bounds_with(&symbols, node).and_then(cut);
|
||||
if node.id == source {
|
||||
obstacles.extend(painted());
|
||||
continue;
|
||||
}
|
||||
let clips = matches!(node.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
let by_members = (node.is_layer() || matches!(node.kind, NodeKind::Group { .. }))
|
||||
&& node.appearance.items.is_empty()
|
||||
&& node.appearance.effects.is_empty();
|
||||
if by_members {
|
||||
// A clipping path paints its fills and strokes when they are set (`Node::clip_paint`),
|
||||
// its strokes outside the clip too, whether or not it is shown.
|
||||
if clips && let Some(path) = node.children().into_iter().flatten().next() {
|
||||
let paint = path.clip_paint();
|
||||
for part in [paint.fill, paint.stroke].into_iter().flatten() {
|
||||
if let Some(b) = vectorcraft_render::painted_bounds_with(&symbols, &part).and_then(cut) {
|
||||
obstacles.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
let within = if clips {
|
||||
// Nothing of a clipping group shows outside what it paints.
|
||||
let Some(shown) = painted() else { continue };
|
||||
Some(shown)
|
||||
} else {
|
||||
within
|
||||
};
|
||||
stack.extend(node.children().into_iter().flatten().skip(usize::from(clips)).map(|c| (c, within)));
|
||||
} else if let Some(b) = painted() {
|
||||
obstacles.push(b);
|
||||
}
|
||||
}
|
||||
let placed = place_row(&row, src.x1 + GAP, &obstacles);
|
||||
let room = || bad(C, "there is no room for the results to the right of the image");
|
||||
let Some(x0) = placed.filter(|x0| x0.is_finite()) else {
|
||||
return Err(room());
|
||||
};
|
||||
let right = row(x0).iter().map(|r| r.x1).fold(f64::NEG_INFINITY, f64::max);
|
||||
if right > crate::MAX_COORD {
|
||||
return Err(room());
|
||||
}
|
||||
let ids = s.edit("Concept to Vector", |d, sel| {
|
||||
let mut groups = vec![];
|
||||
for ((v, label), off) in picked.into_iter().zip(label_of).zip(&offsets) {
|
||||
let dx = x0 + off - first;
|
||||
let xf = Affine::translate((dx, 0.0)) * image.xf;
|
||||
let mut members = Vec::with_capacity(v.paths.len());
|
||||
for vp in &v.paths {
|
||||
let path = vp.path.transformed(xf);
|
||||
if path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().any(|c| c.abs() > crate::MAX_COORD)) {
|
||||
return Err(room());
|
||||
}
|
||||
let mut node = shape_node(d, path, None);
|
||||
node.appearance = appearance_of(vp, unit).into();
|
||||
members.push(Arc::new(node));
|
||||
}
|
||||
let mut g = Node::group(d.alloc_id(), members);
|
||||
g.name = Some(label);
|
||||
groups.push(g);
|
||||
}
|
||||
let ids: Vec<NodeId> = groups.iter().map(|g| g.id).collect();
|
||||
d.insert_beside(vec![(anchor, groups)], false)?;
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`place_row`] has looked at an object on this thread.
|
||||
pub(crate) static LOOKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Where the left edge of the row's first box goes, from `start` rightward, so that no box meets
|
||||
/// one of `obstacles`: a box in the way moves GAP past the rightmost object it meets. `row(x0)`
|
||||
/// gives the boxes with the first one's left edge at `x0`. `None` when the moves run out.
|
||||
pub(crate) fn place_row(row: &dyn Fn(f64) -> Vec<Rect>, start: f64, obstacles: &[Rect]) -> Option<f64> {
|
||||
// Each box's objects: those level with it, by their left edges. The row only moves right, so
|
||||
// each object joins its box's list once, when the box's right edge passes its left edge, and
|
||||
// stays: of those joined, only the rightmost right edge matters, and the box meets that object
|
||||
// exactly when the edge is right of the box's left edge.
|
||||
let lanes: Vec<Vec<Rect>> = row(start)
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let mut lane: Vec<Rect> = obstacles.iter().filter(|o| o.y0 < b.y1 && b.y0 < o.y1).copied().collect();
|
||||
lane.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||
lane
|
||||
})
|
||||
.collect();
|
||||
let mut joined = vec![0usize; lanes.len()];
|
||||
let mut reach = vec![f64::NEG_INFINITY; lanes.len()];
|
||||
let mut x0 = start;
|
||||
// Each move takes a box past every object joined to it, so another move of that box needs a
|
||||
// new object to join.
|
||||
for _ in 0..=lanes.iter().map(Vec::len).sum::<usize>() {
|
||||
let mut shift = None;
|
||||
for ((r, lane), (j, far)) in row(x0).iter().zip(&lanes).zip(joined.iter_mut().zip(reach.iter_mut())) {
|
||||
while let Some(o) = lane.get(*j).filter(|o| o.x0 < r.x1) {
|
||||
#[cfg(test)]
|
||||
LOOKS.with(|n| n.set(n.get() + 1));
|
||||
*far = far.max(o.x1);
|
||||
*j += 1;
|
||||
}
|
||||
// The first box in the way, moved past the rightmost object it meets.
|
||||
if shift.is_none() && *far > r.x0 {
|
||||
shift = Some(*far + GAP - r.x0);
|
||||
}
|
||||
}
|
||||
match shift {
|
||||
None => return Some(x0),
|
||||
Some(by) => x0 += by,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "conceptVector.providers",
|
||||
"Concept to Vector Providers",
|
||||
[],
|
||||
None,
|
||||
"{} → {providers: [{id, name, available, offline, imageInput, vectorOutput, prompt, rasterOutput, maxStyles: 8, styles: [{id, label}]}], selected: the id the panel uses} the providers conceptVector.generate can call by id; the built-in offline.traceStyles makes its styles with Image Trace on this computer (outline, inkLines, flatColor, detailedColor, grayTones), takes no prompt and makes vector art only",
|
||||
always,
|
||||
providers
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.generate",
|
||||
"Generate Concept to Vector Styles",
|
||||
[],
|
||||
None,
|
||||
"{id?: image or unexpanded Image Trace object (default: the one selected object), provider: id (conceptVector.providers; no other provider is used in its place), styles: [style id…] (1 to 8 different ids of that provider), detail?: 0-100 (50: how much of the image's detail each style keeps), prompt?: text (an error for a provider without prompts unless empty), output?: \"vector\" (the only output; any other value is an error)} one variation of the image for each style, kept by this session as a job and not put in the document; a provider that takes no image, makes no vector art or takes no prompt when one is given is refused with that reason; an object that is locked or hidden, itself or by a layer or group around it, or on a locked artboard, is refused → {job, provider, source: id, state: \"done\", variations: [{style, label, paths, anchors, bounds: [x0,y0,x1,y1] in the image's pixels, warnings: [text…]}]}",
|
||||
has_doc,
|
||||
generate
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.results",
|
||||
"Concept to Vector Results",
|
||||
[],
|
||||
None,
|
||||
"{job} a job conceptVector.generate made, as it returned it, or with state \"canceled\" and no variations; the session keeps the 4 newest jobs, until their document closes → {job, provider, source, state, variations}",
|
||||
has_doc,
|
||||
results
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.cancel",
|
||||
"Cancel Concept to Vector Job",
|
||||
[],
|
||||
None,
|
||||
"{job} drop a job's variations, so that it can't be inserted; canceling it again does the same; an error when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved → {job, state: \"canceled\"}",
|
||||
has_doc,
|
||||
cancel
|
||||
),
|
||||
cmd!(
|
||||
"conceptVector.insert",
|
||||
"Insert Concept to Vector Styles",
|
||||
[],
|
||||
None,
|
||||
"{job, variations: [style id…] (different styles of the job)} put a group of each chosen variation, named after its style and in the provider's order, in a row to the right of the job's image, each the image's size with 24 pt between them, moved further right past other visible art in their way, where a variation reaches past its box too (the next one then starts 24 pt past what it paints); the groups go above the outermost clip group or opacity-masked group around the image, and above the outermost envelope, blend, repeat or other live object, the outermost group whose members it makes or places (a graph, an Objects on Path, Shaper, dimension, flare or Live Paint group, a compound shape) and the outermost group with effects or fills and strokes of its own around it; the image and other art stay as they are; one undo step; a variation with no paths is left out, and when every chosen one has none nothing changes (no undo step, ids []); an error when the job's document is not the active one, the object, its image or its placement changed, the object is now locked or hidden, or it is on a layer with a clipping mask, an opacity mask, or effects, fills or strokes of its own, or it or a group around it has effects that move or reshape it, or its image is distorted (Perspective Distort or Free Distort), and when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved →{ids: the groups, selected}",
|
||||
has_doc,
|
||||
insert
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -174,7 +174,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill); type with a style's look also takes the style's opacity and blend mode and is linked to it (in the document the style was picked in; elsewhere it is not linked), and its placed gradients fit the frame text wrap gives it",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -255,6 +255,7 @@ fn insert_look_turned(
|
||||
}
|
||||
n.name = name;
|
||||
n.bbox_angle = bbox_angle;
|
||||
let pre = wrap_snapshot(d, &n, &look);
|
||||
let mut into = None;
|
||||
match (mode, inside) {
|
||||
(crate::DrawMode::Inside, Some(target)) if d.node(target).is_some() => {
|
||||
@@ -274,6 +275,7 @@ fn insert_look_turned(
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
}
|
||||
}
|
||||
place_after_wrap(d, pre, id, &look);
|
||||
if select {
|
||||
sel.set([id]);
|
||||
}
|
||||
@@ -988,20 +990,42 @@ fn text_parent(s: &Session, p: &Value) -> Result<Option<NodeId>> {
|
||||
}
|
||||
|
||||
/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected.
|
||||
fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result<Value> {
|
||||
fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, look: NewArt, bbox_angle: f64) -> Result<Value> {
|
||||
let id = s.edit("Type", |d, sel| {
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::new(id, kind);
|
||||
NewArt::plain(Appearance::default()).apply(d, &mut n);
|
||||
look.apply(d, &mut n);
|
||||
super::object::align_new_object(d, &mut n);
|
||||
n.bbox_angle = bbox_angle;
|
||||
let pre = wrap_snapshot(d, &n, &look);
|
||||
d.insert(Some(parent), usize::MAX, n)?;
|
||||
place_after_wrap(d, pre, id, &look);
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The document before new type `n` goes in, when `look` places gradients on it: text wrap can
|
||||
/// reflow the type once it is in ([`place_after_wrap`]).
|
||||
fn wrap_snapshot(d: &vectorcraft_doc::Document, n: &Node, look: &NewArt) -> Option<vectorcraft_doc::Document> {
|
||||
(matches!(n.kind, NodeKind::Text(_)) && look.places_gradients()).then(|| d.clone())
|
||||
}
|
||||
|
||||
/// New type `id` just inserted into `d` (`pre`: `d` before, from [`wrap_snapshot`]): text wrap
|
||||
/// reflows it now, and when that changes its bounds (an Auto Size frame below a wrap object grows),
|
||||
/// `look`'s gradients are placed on the bounds it ends with.
|
||||
fn place_after_wrap(d: &mut vectorcraft_doc::Document, pre: Option<vectorcraft_doc::Document>, id: NodeId, look: &NewArt) {
|
||||
let Some(pre) = pre else { return };
|
||||
let placed_on = d.node(id).and_then(Node::geometric_bounds);
|
||||
super::textwrap::refresh(&pre, d);
|
||||
if let Some(n) = d.node_mut(id)
|
||||
&& n.geometric_bounds() != placed_on
|
||||
{
|
||||
look.place(n);
|
||||
}
|
||||
}
|
||||
|
||||
fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let parent = text_parent(s, p)?;
|
||||
let x = f64_req(p, "x", "text.create")?;
|
||||
@@ -1040,11 +1064,16 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Lays the text out (and sizes an Auto Size frame).
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
}
|
||||
// New art's fills, strokes and effects (New Art Has Basic Appearance off, or a graphic style
|
||||
// picked with nothing selected), with the characters' paint under Override Character Color as
|
||||
// graphicStyle.apply gives type; a `color` given keeps the characters' fill.
|
||||
let look = s.new_type_look();
|
||||
if s.prefs.override_char_color {
|
||||
super::style::override_text_chars(&mut t, &look.appearance, p.get("color").and_then(color_value).is_none());
|
||||
}
|
||||
let made = match parent {
|
||||
Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?,
|
||||
None => {
|
||||
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?
|
||||
}
|
||||
Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), look, bbox_turn(rotation))?,
|
||||
None => insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), look, None, true, bbox_turn(rotation), true)?,
|
||||
};
|
||||
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
|
||||
let made = super::typecmd::with_bounds(s, id, made);
|
||||
|
||||
@@ -33,6 +33,6 @@ mod smooth;
|
||||
|
||||
pub(super) use anchors::{following_anchors, remove_anchors_of};
|
||||
pub use commands::specs;
|
||||
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
|
||||
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt, with_anchor_path};
|
||||
pub(super) use cut::{components, erase_outline};
|
||||
pub(super) use freehand::freehand_brushed;
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound};
|
||||
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, with_anchor_path, within_input_bound};
|
||||
use super::{
|
||||
Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2,
|
||||
add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or,
|
||||
@@ -111,6 +111,24 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ai = usize_req(p, "anchor", C)?;
|
||||
let curvature = switch_or(p, "curvature", false, C)?;
|
||||
let removed = s.edit("Delete Anchor Point", |d, sel| {
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
// Type on a path keeps its path: the anchor goes only while two or more stay.
|
||||
with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
}
|
||||
if curvature {
|
||||
vectorcraft_tools::draw2::curvature_remove(sp, ai);
|
||||
} else {
|
||||
po::remove_anchors(sp, &[ai]);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
return Ok(false);
|
||||
}
|
||||
let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
@@ -254,23 +272,24 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
s.edit("Convert Anchor Point", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if smooth && target.is_none() {
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if smooth && target.is_none() {
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
}
|
||||
// Without a handle position the anchor curves as the Curvature tool curves a point; one
|
||||
// with no direction to take stays as it is.
|
||||
vectorcraft_tools::draw2::curvature_smooth(sp, ai);
|
||||
return Ok(());
|
||||
}
|
||||
// Without a handle position the anchor curves as the Curvature tool curves a point; one
|
||||
// with no direction to take stays as it is.
|
||||
vectorcraft_tools::draw2::curvature_smooth(sp, ai);
|
||||
return Ok(());
|
||||
}
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
match target {
|
||||
Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t),
|
||||
_ => a.retract(),
|
||||
}
|
||||
Ok(())
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
match target {
|
||||
Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t),
|
||||
_ => a.retract(),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -287,13 +306,14 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let perpendicular = switch_or(p, "perpendicular", false, C)?;
|
||||
s.edit("Reshape", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) };
|
||||
if !bent {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(())
|
||||
with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) };
|
||||
if !bent {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points)",
|
||||
"{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least",
|
||||
has_doc,
|
||||
remove_anchor
|
||||
),
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)",
|
||||
"{id (a path, or type on a path), subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)",
|
||||
has_doc,
|
||||
convert_anchor
|
||||
),
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reshape Segment",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does",
|
||||
"{id (a path, or type on a path), subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does",
|
||||
has_doc,
|
||||
reshape_segment
|
||||
),
|
||||
|
||||
@@ -308,6 +308,29 @@ pub(super) fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` on the anchors the anchor tools edit on `id` ([`Node::anchor_path`]): a path's, as
|
||||
/// [`path_mut`] gives them, or type on a path's path in document space. The type keeps the edited
|
||||
/// path and lays out again; an edit that leaves a subpath with fewer than two anchors, or a path
|
||||
/// that is not finite or reaches past the canvas, is an error and changes nothing.
|
||||
pub(in super::super) fn with_anchor_path<R>(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result<R>) -> Result<R> {
|
||||
if !matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
return f(path_mut(d, id)?);
|
||||
}
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut path = n.anchor_path().map(std::borrow::Cow::into_owned).ok_or_else(|| EngineError::Other(format!("object {id} is not a path")))?;
|
||||
let r = f(&mut path)?;
|
||||
let within = path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD));
|
||||
if path.subpaths.is_empty() || path.subpaths.iter().any(|sp| sp.anchors.len() < 2) || !within {
|
||||
return Err(EngineError::Other(format!("type on a path keeps at least two anchors on its path, within the canvas (object {id})")));
|
||||
}
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::NoNode(id)) };
|
||||
if !t.set_type_path(&path) {
|
||||
return Err(EngineError::Other(format!("the path of object {id} would not be finite")));
|
||||
}
|
||||
crate::cmd::typecmd::refresh_bounds(t);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub(super) fn path_of(d: &Document, id: NodeId) -> Result<(PathData, FillRule)> {
|
||||
match d.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Path { path, rule, .. }) => Ok((path.clone(), *rule)),
|
||||
|
||||
@@ -151,9 +151,9 @@ mod formats;
|
||||
pub(crate) use access::FILES_READ;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub(crate) use access::{READ_TOO_LARGE, check_images_in, check_scripts_of, with_read_limit, with_readable_settings_folder};
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE};
|
||||
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
@@ -178,14 +178,14 @@ 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,
|
||||
export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions,
|
||||
open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions,
|
||||
readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
|
||||
open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters, places_with_importer,
|
||||
plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
|
||||
};
|
||||
pub(crate) use formats::{is_own_title, reads};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -289,6 +289,31 @@ thread_local! {
|
||||
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn regular_write_target(path: &str) -> Result<()> {
|
||||
if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static READ_LIMIT: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
pub(crate) const READ_TOO_LARGE: &str = "File exceeds scoped read limit";
|
||||
|
||||
pub(crate) fn with_read_limit<T>(max: usize, f: impl FnOnce() -> T) -> T {
|
||||
struct Restore(Option<usize>);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
READ_LIMIT.with(|limit| limit.set(self.0));
|
||||
}
|
||||
}
|
||||
let _restore = Restore(READ_LIMIT.with(|limit| limit.replace(Some(limit.get().map_or(max, |outer| outer.min(max))))));
|
||||
f()
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
@@ -299,27 +324,35 @@ pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
if crate::file_access::in_script_command() {
|
||||
let max = SCRIPT_OPEN_MAX_BYTES;
|
||||
let read = || -> std::io::Result<Vec<u8>> {
|
||||
let file = std::fs::File::open(path)?;
|
||||
let meta = file.metadata()?;
|
||||
if !meta.is_file() {
|
||||
return Err(std::io::Error::other("not a file"));
|
||||
}
|
||||
if meta.len() > max as u64 {
|
||||
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(max as u64 + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() > max {
|
||||
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
|
||||
}
|
||||
Ok(bytes)
|
||||
};
|
||||
read().map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
} else {
|
||||
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
// A script command reads at most `SCRIPT_OPEN_MAX_BYTES`, and a scoped limit
|
||||
// (`with_read_limit`) at most its own count, whichever is smaller.
|
||||
let script = crate::file_access::in_script_command().then_some(SCRIPT_OPEN_MAX_BYTES);
|
||||
let scoped = READ_LIMIT.with(std::cell::Cell::get);
|
||||
let Some(cap) = [script, scoped].into_iter().flatten().min() else {
|
||||
return std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")));
|
||||
};
|
||||
let too_large = |bytes: u64| {
|
||||
if script.is_some_and(|max| bytes > max as u64) {
|
||||
Some(EngineError::Other(format!("{path}: {SCRIPT_OPEN_TOO_LARGE}")))
|
||||
} else if scoped.is_some_and(|max| bytes > max as u64) {
|
||||
Some(EngineError::Other(READ_TOO_LARGE.into()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let file = std::fs::File::open(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let meta = file.metadata().map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
if !meta.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
if let Some(e) = too_large(meta.len()) {
|
||||
return Err(e);
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(cap as u64 + 1).read_to_end(&mut bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
match too_large(bytes.len() as u64) {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(bytes),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -748,6 +781,28 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
#[test]
|
||||
fn scoped_read_limit_bounds_reads_and_restores_the_previous_limit() {
|
||||
let path = std::env::temp_dir().join(format!("vc-access-read-limit-{}", std::process::id()));
|
||||
std::fs::write(&path, b"12345").unwrap();
|
||||
let path_text = path.to_str().unwrap();
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
with_read_limit(5, || {
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
with_read_limit(4, || {
|
||||
assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE);
|
||||
with_read_limit(6, || assert!(read_file(path_text).is_err()));
|
||||
});
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
std::fs::write(&path, b"123456").unwrap();
|
||||
assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE);
|
||||
});
|
||||
assert_eq!(read_file(path_text).unwrap(), b"123456");
|
||||
let _ = std::panic::catch_unwind(|| with_read_limit(0, || panic!("test unwind")));
|
||||
assert_eq!(read_file(path_text).unwrap(), b"123456");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
/// An error about a path the client did not give, under roots that don't let it be read: the
|
||||
/// path is named by its file name (after a `/` or a `\`), or as [`UNNAMED`] when it ends in no
|
||||
/// name or its name is not valid text, and every root and the reason stay whole. A path inside the
|
||||
|
||||
@@ -785,7 +785,7 @@ fn is_openable(path: &str) -> bool {
|
||||
if ext.is_empty() {
|
||||
return false;
|
||||
}
|
||||
open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| f.read && f.extensions.iter().any(|e| *e == ext))
|
||||
open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| super::formats::reads(f) && f.extensions.iter().any(|e| *e == ext))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -14,7 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The active artboard the app passes, for the steps that act on it.
|
||||
let artboard = p.get("artboard").and_then(Value::as_u64);
|
||||
// What an error rolls back besides the documents: session-level state a step may change
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group).
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group, the
|
||||
// Concept to Vector jobs).
|
||||
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
|
||||
// would otherwise run inside it and take its baseline as theirs (#1697).
|
||||
if s.active().is_some() && !s.previewing {
|
||||
@@ -24,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
let (clipboard_copied, copies) = (s.clipboard_copied, s.copies);
|
||||
let concept_jobs = s.concept_jobs_snapshot();
|
||||
// The documents as they are now, whole: what a failed step brings back. Their art, history,
|
||||
// file, format and saved state share their data with the open ones until a step changes them.
|
||||
let start = s.docs.clone();
|
||||
@@ -42,6 +44,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(results) => {
|
||||
s.notify_text_tool("batch.end");
|
||||
s.batch_steps = Some(grouped);
|
||||
s.prune_concept_jobs();
|
||||
results
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -59,6 +62,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
|
||||
(s.clipboard_copied, s.copies) = (clipboard_copied, copies);
|
||||
s.pending_paint = None;
|
||||
s.restore_concept_jobs(concept_jobs);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -389,7 +389,10 @@ impl RasterOptions {
|
||||
top_down: self.flip_rows.unwrap_or(false),
|
||||
gray: color_model == jpeg::ColorModel::Gray,
|
||||
},
|
||||
tga: tga::TgaOptions { depth: self.depth.unwrap_or(24) },
|
||||
tga: {
|
||||
let gray = color_model == jpeg::ColorModel::Gray;
|
||||
tga::TgaOptions { depth: self.depth.unwrap_or_else(|| tga::TgaOptions::default_depth(gray)), gray }
|
||||
},
|
||||
psd: psd::PsdOptions {
|
||||
color_model,
|
||||
layers: self.layers.unwrap_or(true),
|
||||
@@ -413,12 +416,12 @@ fn bmp_layout(s: &str) -> Option<bool> {
|
||||
}
|
||||
|
||||
/// Refuse options `format` can't write together: BMP and Targa depths and layouts, and colour
|
||||
/// models (BMP is RGB or grey, Targa RGB).
|
||||
/// models (BMP and Targa are RGB or grey).
|
||||
fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> {
|
||||
let model = o.jpeg.color_model;
|
||||
let r = match format {
|
||||
RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()),
|
||||
RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()),
|
||||
RasterFormat::Tga if model == jpeg::ColorModel::Cmyk => Err("Targa files are RGB or grayscale: colorModel rgb or gray".to_string()),
|
||||
RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()),
|
||||
RasterFormat::Bmp => o.bmp.check(),
|
||||
RasterFormat::Tga => o.tga.check(),
|
||||
|
||||
@@ -45,9 +45,10 @@ pub(crate) fn unique_file_names_keeping_dots<'a>(names: impl IntoIterator<Item =
|
||||
}))
|
||||
}
|
||||
|
||||
/// `names` with `-2`, `-3`… after a name already used (compared without case).
|
||||
/// `names` with `-2`, `-3`… after a name already used (compared without case, as
|
||||
/// [`super::screens::fold`] compares them).
|
||||
pub(super) fn distinct_names(names: impl IntoIterator<Item = String>) -> Vec<String> {
|
||||
distinct_names_by(names, str::to_lowercase)
|
||||
distinct_names_by(names, super::screens::fold)
|
||||
}
|
||||
|
||||
/// `names` with `-2`, `-3`… after a name already used, two names matching when `key` gives the same
|
||||
@@ -93,6 +94,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied)));
|
||||
}
|
||||
}
|
||||
distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
write_file(p, bytes)?;
|
||||
@@ -112,6 +114,62 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
Ok(merge(out, extra))
|
||||
}
|
||||
|
||||
/// An error when two of `paths` are the same file. A link that leads nowhere is compared by the file
|
||||
/// its write creates; another path whose real path cannot be found (a folder that may not be read)
|
||||
/// is compared as written, and its write then reports its own error. Two names in one folder that
|
||||
/// differ only in letter case are treated as the same file on every volume.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator<Item = &'a str>) -> Result<()> {
|
||||
let mut targets = std::collections::HashSet::new();
|
||||
for path in paths {
|
||||
let real = crate::file_access::resolve(path)
|
||||
.ok()
|
||||
.or_else(|| dangling_target(path))
|
||||
.or_else(|| std::path::absolute(path).ok())
|
||||
.unwrap_or_else(|| std::path::PathBuf::from(path));
|
||||
let key = match (real.parent(), real.file_name().and_then(|n| n.to_str())) {
|
||||
(Some(dir), Some(name)) => dir.join(super::screens::fold(name)),
|
||||
_ => real,
|
||||
};
|
||||
if !targets.insert(key) {
|
||||
return Err(EngineError::Other("output destinations resolve to the same file".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The file a write to `path` creates when `path` is a link (or a chain of at most 40 links) that
|
||||
/// leads to a file that does not exist yet.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn dangling_target(path: &str) -> Option<std::path::PathBuf> {
|
||||
let mut at = std::path::PathBuf::from(path);
|
||||
let mut followed = false;
|
||||
for _ in 0..40 {
|
||||
if !std::fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
break;
|
||||
}
|
||||
let next = std::fs::read_link(&at).ok()?;
|
||||
at = match at.parent() {
|
||||
Some(parent) if next.is_relative() => parent.join(next),
|
||||
_ => next,
|
||||
};
|
||||
followed = true;
|
||||
}
|
||||
if !followed {
|
||||
return None;
|
||||
}
|
||||
// Resolved as the primary destination is; a name that is not UTF-8 keeps its bytes, with its
|
||||
// folder's links followed.
|
||||
match at.to_str() {
|
||||
Some(text) => crate::file_access::resolve(text).ok(),
|
||||
None => {
|
||||
let folder = std::fs::canonicalize(at.parent()?).ok()?;
|
||||
Some(folder.join(at.file_name()?))
|
||||
}
|
||||
}
|
||||
.or_else(|| std::path::absolute(&at).ok())
|
||||
}
|
||||
|
||||
/// `a` with the fields of `b`.
|
||||
pub(crate) fn merge(mut a: Value, b: Value) -> Value {
|
||||
if let (Some(a), Value::Object(b)) = (a.as_object_mut(), b) {
|
||||
@@ -143,3 +201,37 @@ pub(crate) fn write_or_return(path: Option<&str>, bytes: &[u8], extra: Value) ->
|
||||
};
|
||||
Ok(merge(out, extra))
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn folder(tag: &str) -> std::io::Result<std::path::PathBuf> {
|
||||
let d = std::env::temp_dir().join(format!("vc-export-names-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d)?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_differing_only_in_case_are_one_file() {
|
||||
let d = folder("case").unwrap();
|
||||
let s = |n: &str| d.join(n).to_str().unwrap().to_string();
|
||||
assert!(distinct_write_targets([s("a.svg").as_str(), s("A.svg").as_str()]).is_err());
|
||||
assert!(distinct_write_targets([s("ας.svg").as_str(), s("ΑΣ.svg").as_str()]).is_err(), "a final sigma");
|
||||
assert!(distinct_write_targets([s("S.svg").as_str(), s("ſ.svg").as_str()]).is_err(), "a long s");
|
||||
assert_eq!(distinct_names(["ας".to_string(), "ασ".to_string()]), ["ας", "ασ-2"]);
|
||||
assert!(distinct_write_targets([s("a.svg").as_str(), s("b.svg").as_str()]).is_ok());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_dangling_link_to_a_case_variant_of_another_destination_is_the_same_file() {
|
||||
let d = folder("link").unwrap();
|
||||
std::os::unix::fs::symlink("A.svg", d.join("side.svg")).unwrap();
|
||||
let (a, side) = (d.join("a.svg"), d.join("side.svg"));
|
||||
assert!(distinct_write_targets([a.to_str().unwrap(), side.to_str().unwrap()]).is_err());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -315,14 +315,18 @@ const BMP_OPTIONS: &[FormatOption] = &[
|
||||
DITHER_AMOUNT,
|
||||
];
|
||||
|
||||
const TGA_COLOR_MODEL: FormatOption =
|
||||
FormatOption { name: "colorModel", ty: "string", default: "\"rgb\"", description: "rgb (true color) or gray (grayscale)" };
|
||||
|
||||
const TGA_DEPTH: FormatOption = FormatOption {
|
||||
name: "depth",
|
||||
ty: "integer",
|
||||
default: "24",
|
||||
description: "bits per pixel: 16 (one-bit alpha), 24 (flattened on white) or 32 (keeps transparency)",
|
||||
description: "bits per pixel: with rgb 16 (one-bit alpha), 24 (flattened on white) or 32 (keeps transparency); with gray 8 (the default, flattened on white) or 16 (keeps transparency)",
|
||||
};
|
||||
|
||||
const TGA_OPTIONS: &[FormatOption] = &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, TGA_DEPTH];
|
||||
const TGA_OPTIONS: &[FormatOption] =
|
||||
&[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, TGA_COLOR_MODEL, TGA_DEPTH];
|
||||
|
||||
const PSD_LAYERS: FormatOption = FormatOption {
|
||||
name: "layers",
|
||||
@@ -607,6 +611,7 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"pns",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"jpe",
|
||||
"gif",
|
||||
"webp",
|
||||
"tif",
|
||||
@@ -662,15 +667,16 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
|
||||
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib`, `.rle` and `.jpe`
|
||||
/// names of PNG, BMP and JPEG files (File › Open and Place still read them all). On Linux the desktop
|
||||
/// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers
|
||||
/// offer VectorCraft for them.
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. CGM files are added here
|
||||
/// when the `cgm` feature is turned on (craft-libs#5410).
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c",
|
||||
"jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
|
||||
];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
@@ -715,6 +721,7 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"pns",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"jpe",
|
||||
"gif",
|
||||
"webp",
|
||||
"tif",
|
||||
@@ -772,13 +779,14 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"doc",
|
||||
];
|
||||
|
||||
/// The extensions File › Open and Place read PNG, BMP and Photoshop files by: the format's own,
|
||||
/// then the other names its files have (`.pns`, `.dib` and `.rle`, `.pdd`). Exports write only
|
||||
/// the format's own extension.
|
||||
const READ_ALIASES: &[(&str, &[&str])] = &[("png", &["png", "pns"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])];
|
||||
/// The extensions File › Open and Place read PNG, JPEG, BMP and Photoshop files by: the format's
|
||||
/// own, then the other names its files have (`.pns`, `.jpe`, `.dib` and `.rle`, `.pdd`). Exports
|
||||
/// write only the format's own extensions.
|
||||
const READ_ALIASES: &[(&str, &[&str])] =
|
||||
&[("png", &["png", "pns"]), ("jpg", &["jpg", "jpeg", "jpe"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])];
|
||||
|
||||
/// The extensions File › Open and Place read format `f` by: its own, and for PNG, BMP and PSD
|
||||
/// those of [`READ_ALIASES`].
|
||||
/// The extensions File › Open and Place read format `f` by: its own, and for PNG, JPEG, BMP and
|
||||
/// PSD those of [`READ_ALIASES`].
|
||||
pub fn read_extensions(f: &Format) -> &'static [&'static str] {
|
||||
READ_ALIASES.iter().find(|(id, _)| *id == f.id).map_or(f.extensions, |(_, exts)| *exts)
|
||||
}
|
||||
@@ -786,9 +794,52 @@ pub fn read_extensions(f: &Format) -> &'static [&'static str] {
|
||||
/// The built-in readable format of extension `ext` (any case, leading dot allowed): [`format`]'s
|
||||
/// when it reads, else the one [`READ_ALIASES`] gives it (`.dib` is BMP). Importer plug-ins are
|
||||
/// not looked at ([`importer_formats`]).
|
||||
/// DWG drawings are readable only in a build with a DWG decoder ([`vectorcraft_cad::dwg::DECODES`]).
|
||||
pub fn readable_format(ext: &str) -> Option<&'static Format> {
|
||||
readable_format_in(ext, vectorcraft_cad::dwg::DECODES)
|
||||
}
|
||||
|
||||
/// The built-in format a file of extension `ext` is taken for ([`super::load::detect`]): [`readable_format`]'s,
|
||||
/// with DWG also in a build without a DWG decoder.
|
||||
pub(crate) fn recognized_format(ext: &str) -> Option<&'static Format> {
|
||||
readable_format_in(ext, true)
|
||||
}
|
||||
|
||||
/// [`readable_format`] in a build that decodes DWG drawings when `dwg`.
|
||||
fn readable_format_in(ext: &str, dwg: bool) -> Option<&'static Format> {
|
||||
let k = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
builtin(&k).filter(|f| f.read).or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id)))
|
||||
builtin(&k)
|
||||
.filter(|f| reads_in(f, dwg))
|
||||
.or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id)))
|
||||
}
|
||||
|
||||
/// Whether format `f` reads in this build: DWG drawings only where a DWG decoder is built in.
|
||||
pub(crate) fn reads(f: &Format) -> bool {
|
||||
reads_in(f, vectorcraft_cad::dwg::DECODES)
|
||||
}
|
||||
|
||||
/// Whether format `f` reads in a build that decodes DWG drawings when `dwg`.
|
||||
fn reads_in(f: &Format, dwg: bool) -> bool {
|
||||
f.read && (dwg || !reads_as_dwg(f.id))
|
||||
}
|
||||
|
||||
/// `exts` less `.dwg`, `.dws` and `.dwt` in a build without a DWG decoder (`dwg` false).
|
||||
fn listed_in(exts: &[&'static str], dwg: bool) -> Vec<&'static str> {
|
||||
exts.iter().copied().filter(|e| dwg || !matches!(*e, "dwg" | "dws" | "dwt")).collect()
|
||||
}
|
||||
|
||||
/// The extensions File › Open reads as a document in this build: [`OPEN_EXTS`], less `.dwg`, `.dws` and `.dwt` where
|
||||
/// no DWG decoder is built in ([`vectorcraft_cad::dwg::DECODES`]).
|
||||
pub fn open_exts() -> &'static [&'static str] {
|
||||
static EXTS: std::sync::LazyLock<Vec<&'static str>> = std::sync::LazyLock::new(|| listed_in(OPEN_EXTS, vectorcraft_cad::dwg::DECODES));
|
||||
&EXTS
|
||||
}
|
||||
|
||||
/// The extensions File › Place reads in this build: [`PLACE_EXTS`], less `.dwg` where no DWG
|
||||
/// decoder is built in ([`vectorcraft_cad::dwg::DECODES`]).
|
||||
pub fn place_exts() -> &'static [&'static str] {
|
||||
static EXTS: std::sync::LazyLock<Vec<&'static str>> = std::sync::LazyLock::new(|| listed_in(PLACE_EXTS, vectorcraft_cad::dwg::DECODES));
|
||||
&EXTS
|
||||
}
|
||||
|
||||
/// The readable format a file name's extension names ([`readable_format`]).
|
||||
@@ -798,7 +849,12 @@ pub fn readable_format_for_name(name: &str) -> Option<&'static Format> {
|
||||
|
||||
/// One dialog filter per readable format.
|
||||
fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f)))
|
||||
format_filters_in(vectorcraft_cad::dwg::DECODES)
|
||||
}
|
||||
|
||||
/// [`format_filters`] in a build that decodes DWG drawings when `dwg`.
|
||||
fn format_filters_in(dwg: bool) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
FORMATS.iter().filter(move |f| reads_in(f, dwg)).map(|f| (f.label, read_extensions(f)))
|
||||
}
|
||||
|
||||
/// Whether a file named `name` can only be opened, by an importer plug-in: an installed importer lists
|
||||
@@ -807,7 +863,7 @@ fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static st
|
||||
pub fn opens_with_importer(name: &str) -> bool {
|
||||
let ext = extension(name);
|
||||
!ext.is_empty()
|
||||
&& !PLACE_EXTS.contains(&ext.as_str())
|
||||
&& !place_exts().contains(&ext.as_str())
|
||||
&& !vectorcraft_plugins::import::for_extension(&ext).is_empty()
|
||||
&& !places_with_importer(name)
|
||||
}
|
||||
@@ -819,7 +875,7 @@ pub fn places_with_importer(name: &str) -> bool {
|
||||
let ext = extension(name);
|
||||
!ext.is_empty()
|
||||
&& readable_format(&ext).is_none()
|
||||
&& !PLACE_EXTS.contains(&ext.as_str())
|
||||
&& !place_exts().contains(&ext.as_str())
|
||||
&& !vectorcraft_plugins::import::placing(&ext).is_empty()
|
||||
}
|
||||
|
||||
@@ -865,7 +921,7 @@ fn importer_open_part() -> ImporterPart {
|
||||
{
|
||||
return part.clone();
|
||||
}
|
||||
let mut exts: Vec<&'static str> = OPEN_EXTS.to_vec();
|
||||
let mut exts: Vec<&'static str> = open_exts().to_vec();
|
||||
let mut filters = Vec::new();
|
||||
for f in importer_formats() {
|
||||
let own: Vec<&'static str> = f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !opens_as_other(e)).collect();
|
||||
@@ -880,7 +936,7 @@ fn importer_open_part() -> ImporterPart {
|
||||
let own: &'static [&'static str] = if own.len() == f.extensions.len() { f.extensions } else { Box::leak(own.into_boxed_slice()) };
|
||||
filters.push((f.label, own));
|
||||
}
|
||||
let exts: &'static [&'static str] = if exts.len() == OPEN_EXTS.len() { OPEN_EXTS } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let exts: &'static [&'static str] = if exts.len() == open_exts().len() { open_exts() } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let part = (exts, filters);
|
||||
*made = Some((revision, part.clone()));
|
||||
part
|
||||
@@ -907,7 +963,7 @@ pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static
|
||||
/// open dialogs whose files the built-in readers read (New from Template, Load Styles, a document
|
||||
/// picked for its swatches, symbols, brushes or graphic styles).
|
||||
pub fn builtin_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters())
|
||||
std::iter::once(("All readable files", open_exts())).chain(format_filters()).chain(other_open_filters())
|
||||
}
|
||||
|
||||
/// The open-dialog filters after the document formats: swatch and graphic style libraries,
|
||||
@@ -943,7 +999,7 @@ pub fn library_open_filters(
|
||||
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
|
||||
/// RTF and Word (`.docx` and `.doc`).
|
||||
pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All placeable files", PLACE_EXTS))
|
||||
std::iter::once(("All placeable files", place_exts()))
|
||||
.chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext))))
|
||||
.chain(std::iter::once(("Text", TEXT_EXTS)))
|
||||
.chain(std::iter::once(("RTF", RTF_EXTS)))
|
||||
@@ -965,12 +1021,16 @@ fn importer_place_part() -> ImporterPart {
|
||||
{
|
||||
return part.clone();
|
||||
}
|
||||
let mut exts: Vec<&'static str> = PLACE_EXTS.to_vec();
|
||||
let mut exts: Vec<&'static str> = place_exts().to_vec();
|
||||
let mut filters = Vec::new();
|
||||
for p in import::installed().into_iter().filter(|p| p.manifest().place) {
|
||||
let m = p.manifest();
|
||||
let own: Vec<&'static str> =
|
||||
m.extensions.iter().filter(|e| readable_format(e).is_none() && !PLACE_EXTS.contains(&e.as_str())).map(|e| registry::intern(e)).collect();
|
||||
let own: Vec<&'static str> = m
|
||||
.extensions
|
||||
.iter()
|
||||
.filter(|e| readable_format(e).is_none() && !place_exts().contains(&e.as_str()))
|
||||
.map(|e| registry::intern(e))
|
||||
.collect();
|
||||
if own.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -982,7 +1042,7 @@ fn importer_place_part() -> ImporterPart {
|
||||
let own: &'static [&'static str] = Box::leak(own.into_boxed_slice());
|
||||
filters.push((registry::intern(&m.name), own));
|
||||
}
|
||||
let exts: &'static [&'static str] = if exts.len() == PLACE_EXTS.len() { PLACE_EXTS } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let exts: &'static [&'static str] = if exts.len() == place_exts().len() { place_exts() } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let part = (exts, filters);
|
||||
*made = Some((revision, part.clone()));
|
||||
part
|
||||
@@ -1147,6 +1207,9 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = |pick: fn(&Format) -> bool| all().filter(|f| pick(f)).map(|f| f.id).collect::<Vec<_>>();
|
||||
let listed = |f: &Format| {
|
||||
let mut v = f.to_json();
|
||||
if f.read && !reads(f) {
|
||||
v["read"] = json!(false);
|
||||
}
|
||||
if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) {
|
||||
v["plugin"] = json!(id);
|
||||
if vectorcraft_plugins::import::by_format(f.id).is_some_and(|p| p.manifest().place) {
|
||||
@@ -1157,9 +1220,37 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
};
|
||||
Ok(json!({
|
||||
"formats": all().map(listed).collect::<Vec<_>>(),
|
||||
"readable": ids(|f| f.read),
|
||||
"readable": ids(reads),
|
||||
"writable": ids(|f| f.write),
|
||||
"openExtensions": open_extensions(),
|
||||
"unsupported": UNSUPPORTED.iter().map(Unsupported::to_json).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dwg_listing_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dwg_is_listed_only_in_a_build_that_decodes_it() {
|
||||
assert_eq!(readable_format_in("dwg", true).map(|f| f.id), Some("dwg"));
|
||||
assert_eq!(listed_in(OPEN_EXTS, true), OPEN_EXTS);
|
||||
assert_eq!(listed_in(PLACE_EXTS, true), PLACE_EXTS);
|
||||
assert!(format_filters_in(true).any(|(_, exts)| exts.contains(&"dwg")));
|
||||
// Without a decoder, nothing offers DWG drawings, standards files or templates.
|
||||
for e in ["dwg", "dws", "dwt"] {
|
||||
assert!(readable_format_in(e, false).is_none(), ".{e} is not readable");
|
||||
assert!(!listed_in(OPEN_EXTS, false).contains(&e), "File › Open does not list .{e}");
|
||||
assert!(!listed_in(PLACE_EXTS, false).contains(&e), "File › Place does not list .{e}");
|
||||
assert!(format_filters_in(false).all(|(_, exts)| !exts.contains(&e)), "no filter lists .{e}");
|
||||
}
|
||||
assert!(readable_format_in("dxf", false).is_some(), "DXF still is");
|
||||
let drawing_exts = OPEN_EXTS.iter().filter(|e| matches!(**e, "dwg" | "dws" | "dwt")).count();
|
||||
assert_eq!(listed_in(OPEN_EXTS, false).len(), OPEN_EXTS.len() - drawing_exts, "every other extension stays");
|
||||
// This build lists DWG exactly when it decodes it.
|
||||
let dwg = vectorcraft_cad::dwg::DECODES;
|
||||
assert_eq!(open_exts().contains(&"dwg"), dwg);
|
||||
assert_eq!(place_exts().contains(&"dwg"), dwg);
|
||||
assert_eq!(readable_format("dwg").is_some(), dwg);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one
|
||||
//! around the art of a new document, and File › Place leaves them out.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
@@ -61,7 +62,7 @@ pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result<Option<Arc<Plu
|
||||
check_extension(C, plugin.manifest(), name)?;
|
||||
return Ok(Some(plugin));
|
||||
}
|
||||
if detect(name, bytes).is_some() {
|
||||
if detect(name, bytes).is_some_and(super::formats::reads) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(import::for_extension(&extension(name)).into_iter().next())
|
||||
@@ -97,7 +98,7 @@ fn importer_reads(ext: &str, mode: Mode) -> bool {
|
||||
super::readable_format(ext).is_none()
|
||||
&& match mode {
|
||||
Mode::Import => !import::for_extension(ext).is_empty(),
|
||||
Mode::Place => !super::PLACE_EXTS.contains(&ext) && !import::placing(ext).is_empty(),
|
||||
Mode::Place => !super::place_exts().contains(&ext) && !import::placing(ext).is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,7 +141,7 @@ fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> {
|
||||
if !explicit {
|
||||
let start: Vec<u8> = b64.bytes().filter(|b| !b.is_ascii_whitespace()).take(SNIFF_BYTES / 3 * 4).collect();
|
||||
let head = std::str::from_utf8(&start).ok().and_then(vectorcraft_format::base64_decode);
|
||||
if head.is_some_and(|head| detect(name, &head).is_some()) {
|
||||
if head.is_some_and(|head| detect(name, &head).is_some_and(super::formats::reads)) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -171,7 +172,7 @@ fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result<Vec<u8>
|
||||
if head.len() < SNIFF_BYTES {
|
||||
return Ok(head);
|
||||
}
|
||||
if detect(path, &head).is_some() {
|
||||
if detect(path, &head).is_some_and(super::formats::reads) {
|
||||
return super::read_file(path);
|
||||
}
|
||||
read_for_importer(path, mode)
|
||||
@@ -202,17 +203,43 @@ fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result<Vec<u8>> {
|
||||
/// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except
|
||||
/// that a file an importer would place (one `importer` names, or an extension no built-in format
|
||||
/// reads that an importer which places its files lists) is read, or decoded, only when it is at
|
||||
/// most [`import::MAX_INPUT_BYTES`] long.
|
||||
pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result<Source<'a>> {
|
||||
/// most [`import::MAX_INPUT_BYTES`] long. `given`: the bytes of the file `path` names, read already,
|
||||
/// which are borrowed instead of reading the path again (by the same size rule).
|
||||
pub(crate) fn place_source<'a, 'b>(p: &'a Value, cmd: &str, given: Option<&'b [u8]>) -> Result<PlaceSource<'a, 'b>> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }),
|
||||
Some(path) => {
|
||||
let bytes: Cow<'b, [u8]> = match given {
|
||||
Some(bytes) => {
|
||||
// The roots in force now still apply to the path, though it is not read again.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
super::may_read(path)?;
|
||||
let explicit = named(p, cmd)?.is_some();
|
||||
let importer = explicit || importer_reads(&extension(path), Mode::Place);
|
||||
let built_in = !explicit && detect(path, bytes.get(..SNIFF_BYTES).unwrap_or(bytes)).is_some();
|
||||
if importer && !built_in && bytes.len() > import::MAX_INPUT_BYTES {
|
||||
return Err(too_large(path, Mode::Place));
|
||||
}
|
||||
Cow::Borrowed(bytes)
|
||||
}
|
||||
None => Cow::Owned(read_path_for(path, p, Mode::Place, cmd)?),
|
||||
};
|
||||
Ok(PlaceSource { name: path, bytes, path: Some(path) })
|
||||
}
|
||||
None => {
|
||||
check_data_for(p, Mode::Place, cmd)?;
|
||||
super::source(p, cmd)
|
||||
let Source { name, bytes, path } = super::source(p, cmd)?;
|
||||
Ok(PlaceSource { name, bytes: Cow::Owned(bytes), path })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file [`place_source`] gives: as [`Source`], its bytes borrowed when they were given.
|
||||
pub(crate) struct PlaceSource<'a, 'b> {
|
||||
pub name: &'a str,
|
||||
pub bytes: Cow<'b, [u8]>,
|
||||
pub path: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// What [`read`] gives: the importer's format, the new document, its objects' ids, the artboards
|
||||
/// the importer returned and its warnings.
|
||||
type Read = (&'static Format, Document, Vec<NodeId>, Vec<import::OutArtboard>, Vec<String>);
|
||||
|
||||
@@ -8,7 +8,7 @@ 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};
|
||||
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file};
|
||||
use crate::cmd::links::Resolved;
|
||||
use crate::{EngineError, Prefs};
|
||||
|
||||
@@ -93,7 +93,7 @@ pub fn file_name(name: &str) -> String {
|
||||
/// The readable format of a file: from its content (magic bytes) when that tells, else from the
|
||||
/// extension of `name`.
|
||||
pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
let by_name = readable_format_for_name(name);
|
||||
let by_name = super::formats::recognized_format(&super::extension(name));
|
||||
if vectorcraft_affinity::is_affinity(bytes) {
|
||||
return format("affinity");
|
||||
}
|
||||
@@ -311,10 +311,12 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool {
|
||||
|
||||
/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part
|
||||
/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages'
|
||||
/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its
|
||||
/// type as text?
|
||||
/// trim boxes by default, with its type as text?
|
||||
fn reads_layers_alone(opts: &LoadOptions) -> bool {
|
||||
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
reads_editing_copy(opts)
|
||||
&& !opts.explicit_crop_box
|
||||
&& opts.crop == vectorcraft_pdf::CropTo::Crop
|
||||
&& opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
}
|
||||
|
||||
/// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts`
|
||||
@@ -478,8 +480,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// The file is read and checked once, for the document it carries, its pages, the
|
||||
// editor's copy and its File Info.
|
||||
let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref());
|
||||
// Saved with Preserve Editing: the document it carries, unless some pages are picked.
|
||||
let editing = (opts.pages.is_none() && opts.native)
|
||||
// Restore the preserved document when opening all pages at their original size.
|
||||
let editing = (opts.pages.is_none() && opts.native && !opts.explicit_crop_box)
|
||||
.then(|| opened.as_ref().ok().and_then(|o| o.editing()))
|
||||
.flatten()
|
||||
.map(|e| (e.intact, move || Some(e.data)));
|
||||
@@ -527,7 +529,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let alone = (r.only_text || empty)
|
||||
let alone = (!opts.explicit_crop_box && (r.only_text || empty))
|
||||
.then(copy_alone)
|
||||
.flatten()
|
||||
.and_then(|read| read.ok())
|
||||
|
||||
@@ -173,7 +173,13 @@ impl LoadOptions {
|
||||
/// box, a password, without its hidden layers, without the VectorCraft document it carries, its
|
||||
/// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name).
|
||||
pub fn is_partial(&self) -> bool {
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
|
||||
self.pages.is_some()
|
||||
|| self.crop != CropTo::default()
|
||||
|| self.explicit_crop_box
|
||||
|| self.password.is_some()
|
||||
|| !self.layers
|
||||
|| !self.native
|
||||
|| self.link_pages
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible
|
||||
|
||||
@@ -85,6 +85,7 @@ pub struct SavePlan {
|
||||
/// Where to write. `None` when no path is known (never saved, converted from an older version,
|
||||
/// restored by Data Recovery, or a format other than the document's own): the caller asks for one or takes the bytes.
|
||||
pub path: Option<String>,
|
||||
pub path_given: bool,
|
||||
pub format: &'static Format,
|
||||
/// The format's options (only those its encoder reads).
|
||||
pub options: Map<String, Value>,
|
||||
@@ -348,7 +349,8 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
}
|
||||
}
|
||||
let lossy_source = super::lossy_source(st, p);
|
||||
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source, kept })
|
||||
let path_given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
Ok(SavePlan { mode, path, path_given, format, options, name, folder, modified, notes, lossy_source, kept })
|
||||
}
|
||||
|
||||
/// The native save options, which a save also takes beside the path.
|
||||
@@ -602,8 +604,9 @@ pub struct SaveJob {
|
||||
stamped: Option<i64>,
|
||||
/// The artboards also saved to files of their own (`separateArtboards`).
|
||||
boards: Vec<usize>,
|
||||
/// The client did not give the path: a file the file access refuses before anything is
|
||||
/// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]).
|
||||
/// The client did not give the path ([`SavePlan::path_given`]): a file the file access refuses
|
||||
/// before anything is written is named as [`super::access::naming_in_error`] names it
|
||||
/// ([`SaveJob::naming_refusals`]).
|
||||
redact_paths: bool,
|
||||
}
|
||||
|
||||
@@ -966,7 +969,8 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
};
|
||||
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
|
||||
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards, redact_paths: false })
|
||||
let redact_paths = !plan.path_given;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards, redact_paths })
|
||||
}
|
||||
|
||||
impl SaveJob {
|
||||
@@ -1081,32 +1085,29 @@ impl SaveJob {
|
||||
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
|
||||
return Ok(stopped);
|
||||
}
|
||||
// Every path is checked against the file access in force before the first file is
|
||||
// written. A refused file, or a folder at a file's path, is not handed to `write`, so a
|
||||
// writer that does not check the file access writes none of the files; the error is the
|
||||
// file access's own refusal, as the writers that check it give.
|
||||
// Every path is checked against the file access in force, and as a write target, before
|
||||
// the first file is written. A refused file is not handed to `write`, so a writer that does
|
||||
// not check the file access writes none of the files; the error is the file access's own
|
||||
// refusal, as the writers that check it give.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1
|
||||
&& let Some(refused) = files.iter().find_map(|(p, _)| {
|
||||
super::access::may_write_file(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })
|
||||
})
|
||||
{
|
||||
return Err(refused);
|
||||
if files.len() > 1 {
|
||||
let named = |e, p: &str| if self.redact_paths { super::access::naming_in_error(e, p) } else { e };
|
||||
for (p, _) in &files {
|
||||
super::may_write(p).map_err(|e| named(e, p))?;
|
||||
}
|
||||
for (p, _) in &files {
|
||||
super::access::regular_write_target(p).map_err(|e| named(e, p))?;
|
||||
}
|
||||
super::export_names::distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
|
||||
}
|
||||
// An existing destination that is a folder or a read-only file is refused before any file
|
||||
// is written too.
|
||||
// An existing destination that is a read-only file is refused before any file is written too.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1 {
|
||||
for (p, _) in &files {
|
||||
let Ok(meta) = std::fs::metadata(p) else { continue };
|
||||
let refused = if meta.is_dir() {
|
||||
crate::EngineError::Other(format!("{p}: is a folder, not a file"))
|
||||
} else if meta.is_file() && meta.permissions().readonly() {
|
||||
super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
return Err(if self.redact_paths { super::access::naming_in_error(refused, p) } else { refused });
|
||||
if std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().readonly()) {
|
||||
let refused = super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied));
|
||||
return Err(if self.redact_paths { super::access::naming_in_error(refused, p) } else { refused });
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, (p, bytes)) in files.iter().enumerate() {
|
||||
@@ -1271,8 +1272,8 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8])
|
||||
/// A save command: plan, then write with the file system (a native file as it is encoded).
|
||||
pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
|
||||
let plan = save_plan(s, mode, p)?;
|
||||
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
let job = save_job(s, plan)?;
|
||||
let given = job.plan.path_given;
|
||||
let job = if given { job } else { job.naming_refusals() };
|
||||
let uid = s.doc()?.uid;
|
||||
// Without a path, the files written are the document's own file and those beside it.
|
||||
@@ -1416,7 +1417,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when access to one of a save's files is refused, or it is a directory or an existing read-only file, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; an access-rule, file-type (a directory), read-only (an existing read-only file) or destination-collision failure found before writing leaves every file unchanged; a later write failure can leave earlier files written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; r
Line truncated
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -626,7 +626,7 @@ pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> {
|
||||
/// same key, and so do `ΟΣ`, `ος` and `οσ` (`ΟΣ`); `ᾈ` and `ᾀ` give `ᾀ`, and `ß` stays `ß`.
|
||||
/// Dotless `ı` stays `ı`, as NTFS and Unicode case folding outside Turkic languages keep it apart
|
||||
/// from `i` and `I`.
|
||||
fn fold(name: &str) -> String {
|
||||
pub(super) fn fold(name: &str) -> String {
|
||||
name.to_lowercase()
|
||||
.chars()
|
||||
.map(|c| {
|
||||
|
||||
@@ -453,14 +453,14 @@ fn open_exts_cover_every_readable_format() {
|
||||
assert!(OPEN_EXTS.contains(e), "OPEN_EXTS lacks .{e} ({})", f.label);
|
||||
}
|
||||
}
|
||||
for e in OPEN_EXTS {
|
||||
assert!(readable_format(e).is_some(), ".{e} in OPEN_EXTS is no readable format");
|
||||
for e in open_exts() {
|
||||
assert!(readable_format(e).is_some(), ".{e} in open_exts() is no readable format");
|
||||
}
|
||||
let filters: Vec<_> = open_filters().collect();
|
||||
assert_eq!(filters[0], ("All readable files", OPEN_EXTS));
|
||||
assert_eq!(filters[0], ("All readable files", open_exts()));
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
13 + FORMATS.iter().filter(|f| f.read).count(),
|
||||
13 + FORMATS.iter().filter(|f| formats::reads(f)).count(),
|
||||
"and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \
|
||||
fonts, shortcut sets, scripts, plug-ins"
|
||||
);
|
||||
@@ -484,7 +484,7 @@ fn library_open_filters_list_library_formats_first() {
|
||||
let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS).collect();
|
||||
assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS));
|
||||
assert!(filters[0].1.contains(&"ase"));
|
||||
assert_eq!(filters[1], ("All readable files", OPEN_EXTS));
|
||||
assert_eq!(filters[1], ("All readable files", open_exts()));
|
||||
let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT);
|
||||
for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] {
|
||||
let filters: Vec<_> = library_open_filters(label, exts).collect();
|
||||
@@ -576,7 +576,7 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
|
||||
let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap();
|
||||
assert_eq!(png["options"]["scale"]["default"], Value::Null);
|
||||
assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len());
|
||||
assert_eq!(r["openExtensions"].as_array().unwrap().len(), open_exts().len());
|
||||
}
|
||||
|
||||
/// The format ids `command`'s params text lists for `format` (`a|b (default)|c (…)`, up to the
|
||||
|
||||
@@ -1395,8 +1395,7 @@ fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
|
||||
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
|
||||
/// Linked pages default to the trim box with the bleed and honor an explicit Crop Box.
|
||||
#[test]
|
||||
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
|
||||
@@ -1416,6 +1415,13 @@ fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
|
||||
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
|
||||
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true, "cropTo": "crop"})).unwrap();
|
||||
let cropped = &s.doc().unwrap().doc;
|
||||
assert!(cropped.artboards[0].rect.width() > board.width());
|
||||
let placed = &cropped.layers[0].children().unwrap()[0];
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!(p.page_box, vectorcraft_doc::PageBox::Crop);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! JPEG Options: colour model, coding method, scans, profile and image maps.
|
||||
//! JPEG Options: colour model, coding method, scans, profile and image maps; JPEG files named
|
||||
//! `.jpe` open and place.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -87,3 +88,28 @@ fn image_maps_list_the_objects_with_a_url() {
|
||||
// One file only: Export for Screens can't add the map.
|
||||
assert!(s.execute("document.exportForScreens", &json!({"formats": [{"format": "jpg", "imageMap": "client"}]})).is_err());
|
||||
}
|
||||
|
||||
/// JPEG files named `.jpe` open and place as JPEG, in any case; the dialogs and a drop on the
|
||||
/// window take them by their extension, the desktop packaging doesn't associate them, and exports
|
||||
/// still write `.jpg`.
|
||||
#[test]
|
||||
fn jpe_files_open_and_place() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
|
||||
let jpg = b64(&s.execute("document.export", &json!({"format": "jpg"})).unwrap());
|
||||
let data = vectorcraft_format::base64_encode(&jpg);
|
||||
for name in ["art.jpe", "ART.JPE"] {
|
||||
assert_eq!(readable_format_for_name(name).map(|f| f.id), Some("jpg"), "{name}");
|
||||
let r = s.execute("document.open", &json!({"name": name, "dataBase64": data})).unwrap();
|
||||
assert_eq!((&r["format"], &r["warnings"]), (&json!("jpg"), &json!([])), "{name}: {r}");
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": name, "dataBase64": data})).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("jpg"), Some(1)), "{name}: {r}");
|
||||
}
|
||||
assert!(OPEN_EXTS.contains(&"jpe") && PLACE_EXTS.contains(&"jpe") && UNASSOCIATED_EXTS.contains(&"jpe"));
|
||||
let jpeg = ("JPEG", &["jpg", "jpeg", "jpe"][..]);
|
||||
assert!(open_filters().any(|f| f == jpeg) && place_filters().any(|f| f == jpeg));
|
||||
assert!(!export_extensions().contains(&"jpe"));
|
||||
assert!(format_for_name("x.jpe").is_none() && writable_format(None, Some("x.jpe")).is_err());
|
||||
assert!(s.execute("document.export", &json!({"path": "x.jpe"})).is_err());
|
||||
}
|
||||
@@ -138,8 +138,38 @@ fn targa_depth_reaches_the_file() {
|
||||
}
|
||||
let tga = export(&mut s, json!({"format": "tga"}));
|
||||
assert_eq!(tga[16], 24, "24 bits by default");
|
||||
for bad in [json!({"depth": 8}), json!({"colorModel": "gray"})] {
|
||||
assert!(s.execute("document.export", &merge(json!({"format": "tga"}), bad.clone())).is_err(), "{bad}");
|
||||
for bad in [
|
||||
json!({"depth": 8}),
|
||||
json!({"colorModel": "cmyk"}),
|
||||
json!({"colorModel": "lab"}),
|
||||
json!({"colorModel": "gray", "depth": 24}),
|
||||
json!({"colorModel": "gray", "depth": 32}),
|
||||
] {
|
||||
let e = s.execute("document.export", &merge(json!({"format": "tga"}), bad.clone())).unwrap_err();
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targa_color_model_gray_writes_grayscale() {
|
||||
let mut s = session();
|
||||
let gray = export(&mut s, json!({"format": "tga", "colorModel": "gray"}));
|
||||
assert_eq!((gray[2], gray[16], gray[17]), (3, 8, 0), "grayscale, 8 bits by default, no alpha");
|
||||
let img = image::load_from_memory_with_format(&gray, image::ImageFormat::Tga).unwrap().to_rgba8();
|
||||
assert_eq!(img.dimensions(), (60, 40));
|
||||
assert_eq!(img.get_pixel(5, 5).0, [255; 4], "flattened on white");
|
||||
let black = img.get_pixel(40, 20).0;
|
||||
assert!(black[0] == black[1] && black[1] == black[2] && black[0] < 80, "{black:?}");
|
||||
|
||||
let alpha = export(&mut s, json!({"format": "tga", "colorModel": "gray", "depth": 16}));
|
||||
assert_eq!((alpha[2], alpha[16], alpha[17]), (3, 16, 8), "grayscale with an 8-bit alpha");
|
||||
let img = image::load_from_memory_with_format(&alpha, image::ImageFormat::Tga).unwrap().to_rgba8();
|
||||
assert_eq!(img.get_pixel(5, 5).0[3], 0, "transparent where nothing is drawn");
|
||||
assert_eq!(img.get_pixel(40, 20).0[3], 255);
|
||||
|
||||
for file in [gray, alpha] {
|
||||
let r = s.execute("document.open", &json!({"name": "back.tga", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap();
|
||||
assert_eq!(r["format"], "tga");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one is an error",
|
||||
"{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one, or the one an open Create Font Sheet dialog uses, is an error",
|
||||
has_doc,
|
||||
artboard_delete
|
||||
),
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Empty Artboards",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go) → {deleted: [index…]} (the indices before deleting)",
|
||||
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go); an error, with nothing deleted, when one of them is the artboard an open Create Font Sheet dialog uses → {deleted: [index…]} (the indices before deleting)",
|
||||
has_empty_artboards,
|
||||
artboard_delete_empty
|
||||
),
|
||||
@@ -1225,11 +1225,25 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn artboard_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let indices = super::panelcmds::artboard_indices(&s.doc()?.doc, p, "artboard.delete")?;
|
||||
refuse_guarded(s, &indices)?;
|
||||
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
|
||||
s.edit("Delete Artboard", |d, sel| remove_artboards(d, sel, &indices))?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The session's artboard deletion guard's message when deleting artboards `indices` of the
|
||||
/// active document would delete the artboard it protects.
|
||||
pub(crate) fn refuse_guarded(s: &Session, indices: &[usize]) -> Result<()> {
|
||||
let Some(guard) = &s.artboard_deletion_guard else { return Ok(()) };
|
||||
let state = s.doc()?;
|
||||
if (state.uid, state.reverts) == guard.document
|
||||
&& indices.iter().any(|&index| state.doc.artboards.get(index).is_some_and(|a| a.id == guard.artboard))
|
||||
{
|
||||
return Err(EngineError::Other(guard.message.clone()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete artboards `indices` (sorted, each once) of `d` with their guides; at least one must be
|
||||
/// left. The other artboards keep their order, no later artboard takes a deleted one's id, and
|
||||
/// `sel` forgets the deleted guides. One walk over the artboards and one over the ruler guides,
|
||||
@@ -1306,6 +1320,7 @@ fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if indices.is_empty() {
|
||||
return Err(EngineError::Other("no empty artboards to delete".into()));
|
||||
}
|
||||
refuse_guarded(s, &indices)?;
|
||||
s.edit("Delete Empty Artboards", |d, sel| remove_artboards(d, sel, &indices))?;
|
||||
Ok(json!({ "deleted": indices }))
|
||||
}
|
||||
|
||||
@@ -3061,6 +3061,22 @@ fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::R
|
||||
if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) }
|
||||
}
|
||||
|
||||
/// `path` with `.ext` added when it has no extension: the file Unembed writes for a `path` given.
|
||||
fn with_unembed_extension(path: &str, ext: &str) -> String {
|
||||
if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() }
|
||||
}
|
||||
|
||||
/// The file `links.unembed {id, path}` writes embedded image `id` of the active document to: `path`
|
||||
/// with the extension of the format the image is stored in added when `path` has none. `None` when
|
||||
/// `id` is not an embedded image there.
|
||||
pub fn unembed_path(s: &Session, id: u64, path: &str) -> Option<String> {
|
||||
let st = s.doc().ok()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let im = image_of(&doc, NodeId(id)).filter(|im| im.link.is_none())?;
|
||||
let blob = st.doc.images.get(&im.key)?;
|
||||
Some(with_unembed_extension(path, stored_extension(blob)))
|
||||
}
|
||||
|
||||
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
|
||||
@@ -3097,7 +3113,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());
|
||||
return Ok(json!({ "name": format!("{stem}.{ext}"), "dataBase64": vectorcraft_format::base64_encode(&bytes) }));
|
||||
};
|
||||
let path = absolute_path(&if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() });
|
||||
let path = absolute_path(&with_unembed_extension(path, &ext));
|
||||
// Read before writing: pixels that can't be read leave no file behind.
|
||||
let img = linked_image(&bytes, Some(&path))?;
|
||||
write_file(&path, &bytes)?;
|
||||
|
||||
@@ -273,6 +273,12 @@ fn unplace_all(mut ap: Appearance) -> Appearance {
|
||||
ap
|
||||
}
|
||||
|
||||
/// The fills, strokes and effects new art takes from graphic style `g`, placed gradients relative
|
||||
/// to the unit box.
|
||||
fn style_look(g: &GraphicStyle) -> Appearance {
|
||||
if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) }
|
||||
}
|
||||
|
||||
/// How a new object looks ([`Session::new_art_look`]): its appearance and transparency and the
|
||||
/// graphic style it is linked to.
|
||||
pub(crate) struct NewArt {
|
||||
@@ -280,6 +286,8 @@ pub(crate) struct NewArt {
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
style: Option<String>,
|
||||
/// Taken from a graphic style, linked to it or not (a style from another document is not).
|
||||
styled: bool,
|
||||
/// From the template: placed gradients are relative to the unit box.
|
||||
unit_box: bool,
|
||||
}
|
||||
@@ -287,24 +295,47 @@ pub(crate) struct NewArt {
|
||||
impl NewArt {
|
||||
/// A plain look: `appearance`, full opacity, no link.
|
||||
pub(crate) fn plain(appearance: Appearance) -> Self {
|
||||
Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, unit_box: false }
|
||||
Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, styled: false, unit_box: false }
|
||||
}
|
||||
|
||||
/// Give new object `n` (in `d`) this look: its placed gradients land relative to its bounds, and
|
||||
/// it links to the style (type keeps its own transparency).
|
||||
/// it links to the style, taking its isolate and knockout too (type keeps its own transparency
|
||||
/// unless the look is a graphic style's). A look that no longer matches the style's definition
|
||||
/// (the style was redefined after it was picked) is given unlinked ([`NewArt::linked_style`]).
|
||||
pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) {
|
||||
self.place(n);
|
||||
if matches!(n.kind, NodeKind::Text(_)) && !self.styled {
|
||||
return;
|
||||
}
|
||||
(n.opacity, n.blend) = (self.opacity, self.blend);
|
||||
let style = self.linked_style(d);
|
||||
if let Some(g) = style.and_then(|i| d.graphic_styles.get(i)) {
|
||||
(n.isolate, n.knockout) = (g.isolate, g.knockout);
|
||||
}
|
||||
n.extras_mut().graphic_style = style.map(|i| d.graphic_style_id(i));
|
||||
}
|
||||
|
||||
/// The index in `d` of the graphic style this look links to: its style, while the style's
|
||||
/// fills, strokes, effects, opacity and blend mode are still the ones this look has.
|
||||
pub(crate) fn linked_style(&self, d: &Document) -> Option<usize> {
|
||||
let i = d.graphic_style_index(self.style.as_deref()?)?;
|
||||
let g = d.graphic_styles.get(i)?;
|
||||
((g.opacity, g.blend) == (self.opacity, self.blend) && style_look(g).approx_eq(&self.appearance)).then_some(i)
|
||||
}
|
||||
|
||||
/// Give `n` this look's appearance, its placed gradients relative to `n`'s bounds now.
|
||||
pub(crate) fn place(&self, n: &mut Node) {
|
||||
n.appearance = self.appearance.clone().into();
|
||||
if self.unit_box
|
||||
&& n.appearance.has_placed_gradient()
|
||||
if self.places_gradients()
|
||||
&& let Some(b) = n.geometric_bounds()
|
||||
{
|
||||
n.appearance.rebase_gradients(GraphicStyle::UNIT_BOX, b);
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
return;
|
||||
}
|
||||
(n.opacity, n.blend) = (self.opacity, self.blend);
|
||||
n.extras_mut().graphic_style = self.style.as_deref().and_then(|name| d.graphic_style_index(name)).map(|i| d.graphic_style_id(i));
|
||||
}
|
||||
|
||||
/// Does this look place gradients on the bounds of the object it is given to?
|
||||
pub(crate) fn places_gradients(&self) -> bool {
|
||||
self.unit_box && self.appearance.has_placed_gradient()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +363,32 @@ impl Session {
|
||||
st.width = width;
|
||||
}
|
||||
let (opacity, blend, style) = self.new_art_transparency();
|
||||
NewArt { appearance, opacity, blend, style: style.map(str::to_string), unit_box: true }
|
||||
NewArt { appearance, opacity, blend, style: style.map(str::to_string), styled: self.new_art_styled(), unit_box: true }
|
||||
}
|
||||
|
||||
/// The look of new type (`text.create`): the template's fills, strokes and effects when it is
|
||||
/// more than one plain fill and stroke or comes from a graphic style (of this document or
|
||||
/// another), else none of its own, so the characters' fill and stroke show. The document's own
|
||||
/// default look (its redefined Default Graphic Style, which [`reset`] gives new art) leaves type
|
||||
/// plain as the shipped default does; the same look taken from the selection does not. The
|
||||
/// template is not repainted with the fill and stroke proxies.
|
||||
pub(crate) fn new_type_look(&self) -> NewArt {
|
||||
let plain = || NewArt::plain(Appearance::default());
|
||||
let Some(t) = self.template() else { return plain() };
|
||||
let styled = self.new_art_styled();
|
||||
let default_look =
|
||||
|| !self.paint.inherited && self.active().and_then(|st| redefined_default_style(&st.doc)).is_some_and(|g| style_look(g).approx_eq(&t));
|
||||
if !styled && (t.is_basic() || default_look()) {
|
||||
return plain();
|
||||
}
|
||||
let (opacity, blend, style) = self.new_art_transparency();
|
||||
NewArt { appearance: t.into_owned(), opacity, blend, style: style.map(str::to_string), styled, unit_box: true }
|
||||
}
|
||||
|
||||
/// Does the next object drawn take its look from a graphic style, in this document or the one
|
||||
/// the style was taken from?
|
||||
fn new_art_styled(&self) -> bool {
|
||||
!self.basic_only() && self.paint.style.is_some()
|
||||
}
|
||||
|
||||
/// The appearance of the next object drawn (the Appearance panel shows it with nothing
|
||||
@@ -341,9 +397,16 @@ impl Session {
|
||||
self.new_art_look(self.paint.fill.clone(), self.paint.stroke.clone(), self.paint.stroke_width).appearance
|
||||
}
|
||||
|
||||
/// The opacity, blend mode and graphic style (name) of the next object drawn.
|
||||
/// The opacity, blend mode and graphic style (name) of the next object drawn. The style is
|
||||
/// left out in a document other than the one it was taken from, so new art there is not
|
||||
/// linked to a style of the same name.
|
||||
pub fn new_art_transparency(&self) -> (f32, BlendMode, Option<&str>) {
|
||||
if self.basic_only() { (1.0, BlendMode::Normal, None) } else { (self.paint.opacity, self.paint.blend, self.paint.style.as_deref()) }
|
||||
if self.basic_only() {
|
||||
return (1.0, BlendMode::Normal, None);
|
||||
}
|
||||
let here = self.active().map(|st| st.uid);
|
||||
let style = self.paint.style.as_deref().filter(|_| self.paint.style_doc.is_some() && self.paint.style_doc == here);
|
||||
(self.paint.opacity, self.paint.blend, style)
|
||||
}
|
||||
|
||||
/// The stroke of the next object drawn (the Stroke panel shows it with nothing selected).
|
||||
@@ -378,7 +441,7 @@ impl Session {
|
||||
/// A graphic style clicked with nothing selected: new art takes it (`add`: its fills, strokes
|
||||
/// and effects on top of the template's, unlinked).
|
||||
pub(crate) fn new_art_style(&mut self, g: &GraphicStyle, add: bool) {
|
||||
let ap = if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) };
|
||||
let ap = style_look(g);
|
||||
if add {
|
||||
let t = self.new_art_template_mut();
|
||||
t.items.extend(ap.items);
|
||||
@@ -390,14 +453,16 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Make `ap` (placed gradients relative to the unit box) and this transparency the template,
|
||||
/// and its top fill, stroke and weight the proxies.
|
||||
/// and its top fill, stroke and weight the proxies. `style` is a graphic style of the
|
||||
/// document in front.
|
||||
fn take_new_art(&mut self, ap: Appearance, opacity: f32, blend: BlendMode, style: Option<String>, inherited: bool) {
|
||||
let style_doc = style.as_ref().and_then(|_| self.active().map(|st| st.uid));
|
||||
let p = &mut self.paint;
|
||||
(p.fill, p.stroke) = (unplaced(&ap.fill_paint()), unplaced(&ap.stroke_paint()));
|
||||
if let Some(st) = ap.stroke() {
|
||||
p.stroke_width = st.width;
|
||||
}
|
||||
(p.appearance, p.opacity, p.blend, p.style, p.inherited) = (Some(ap), opacity, blend, style, inherited);
|
||||
(p.appearance, p.opacity, p.blend, p.style, p.style_doc, p.inherited) = (Some(ap), opacity, blend, style, style_doc, inherited);
|
||||
}
|
||||
|
||||
/// After each command: with New Art Has Basic Appearance off, new art takes the appearance of
|
||||
@@ -522,7 +587,9 @@ fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn describe(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let (opacity, blend, style) = s.new_art_transparency();
|
||||
let (opacity, blend, _) = s.new_art_transparency();
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let style = s.doc().ok().and_then(|st| look.linked_style(&st.doc)).and_then(|i| s.doc().ok()?.doc.graphic_styles.get(i)).map(|g| g.name.clone());
|
||||
Ok(json!({
|
||||
"basic": s.prefs.new_art_basic,
|
||||
"appearance": s.new_art(),
|
||||
@@ -540,8 +607,7 @@ pub(crate) fn reset(s: &mut Session) {
|
||||
s.paint = PaintDefaults::default();
|
||||
let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned();
|
||||
if let Some(g) = style {
|
||||
let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) };
|
||||
s.take_new_art(ap, 1.0, BlendMode::Normal, None, false);
|
||||
s.take_new_art(style_look(&g), 1.0, BlendMode::Normal, None, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.cut")?;
|
||||
@@ -366,6 +366,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
|
||||
return Err(EngineError::Other("a document needs at least one artboard".into()));
|
||||
}
|
||||
if cut {
|
||||
super::layer::refuse_guarded(s, &indices)?;
|
||||
refuse_locked(&st.doc, &indices)?;
|
||||
}
|
||||
let art = st.doc.paint_order(arts.into_iter().flat_map(|(_, a)| a));
|
||||
|
||||
+169
-93
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
"{id (a path, or type on a path), subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
has_doc,
|
||||
set_handle
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
|
||||
"{id (a path, or type on a path), subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
|
||||
has_doc,
|
||||
move_anchor
|
||||
),
|
||||
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected",
|
||||
"{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection)",
|
||||
has_doc,
|
||||
insert_anchor
|
||||
),
|
||||
@@ -719,39 +719,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Reshape", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let old_point = a.p;
|
||||
let old_handle = if out { a.h_out } else { a.h_in };
|
||||
if let Some(to) = at {
|
||||
a.translate(to - a.p);
|
||||
}
|
||||
let handle = if out { a.h_out } else { a.h_in };
|
||||
let kind_changes = independent && a.kind != AnchorKind::Corner;
|
||||
// Ordinary decimal moves can round `at - old_point` differently from the handle's
|
||||
// translation. Within that calculation's roundoff, place the selected point exactly
|
||||
// without realigning the other stored Smooth handle. Real edits still use set_handle.
|
||||
let translation_roundoff = at.is_some_and(|to| {
|
||||
let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| {
|
||||
let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0);
|
||||
(actual - requested).abs() <= 4.0 * f64::EPSILON * scale
|
||||
};
|
||||
to != old_point && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y)
|
||||
});
|
||||
if !kind_changes && (handle == pos || translation_roundoff) {
|
||||
if out {
|
||||
a.h_out = pos;
|
||||
} else {
|
||||
a.h_in = pos;
|
||||
super::draw2::with_anchor_path(d, id, |path| {
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let old_point = a.p;
|
||||
let old_handle = if out { a.h_out } else { a.h_in };
|
||||
if let Some(to) = at {
|
||||
a.translate(to - a.p);
|
||||
}
|
||||
} else {
|
||||
a.set_handle(out, pos, independent);
|
||||
}
|
||||
if symmetric {
|
||||
let opposite = a.p - (pos - a.p);
|
||||
if out { a.h_in = opposite } else { a.h_out = opposite }
|
||||
}
|
||||
Ok(())
|
||||
let handle = if out { a.h_out } else { a.h_in };
|
||||
let kind_changes = independent && a.kind != AnchorKind::Corner;
|
||||
// Ordinary decimal moves can round `at - old_point` differently from the handle's
|
||||
// translation. Within that calculation's roundoff, place the selected point exactly
|
||||
// without realigning the other stored Smooth handle. Real edits still use set_handle.
|
||||
let translation_roundoff = at.is_some_and(|to| {
|
||||
let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| {
|
||||
let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0);
|
||||
(actual - requested).abs() <= 4.0 * f64::EPSILON * scale
|
||||
};
|
||||
to != old_point
|
||||
&& matches(handle.x, pos.x, old_point.x, old_handle.x, to.x)
|
||||
&& matches(handle.y, pos.y, old_point.y, old_handle.y, to.y)
|
||||
});
|
||||
if !kind_changes && (handle == pos || translation_roundoff) {
|
||||
if out {
|
||||
a.h_out = pos;
|
||||
} else {
|
||||
a.h_in = pos;
|
||||
}
|
||||
} else {
|
||||
a.set_handle(out, pos, independent);
|
||||
}
|
||||
if symmetric {
|
||||
let opposite = a.p - (pos - a.p);
|
||||
if out { a.h_in = opposite } else { a.h_out = opposite }
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -852,22 +855,26 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| {
|
||||
sp.anchors.get(ai).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, pos, sp.has_segment(ai, !out));
|
||||
linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos))
|
||||
let unchanged = s.doc()?.doc.node(id).and_then(Node::anchor_path).is_some_and(|pd| {
|
||||
pd.subpaths.get(si).is_some_and(|sp| {
|
||||
sp.anchors.get(ai).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, pos, sp.has_segment(ai, !out));
|
||||
linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos))
|
||||
})
|
||||
})
|
||||
});
|
||||
if unchanged {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Reshape", |d, _| {
|
||||
let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let pull_out = sp.has_segment(ai, !out);
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
a.link_handle(out, pos, pull_out);
|
||||
Ok(())
|
||||
super::draw2::with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let pull_out = sp.has_segment(ai, !out);
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
a.link_handle(out, pos, pull_out);
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -958,6 +965,13 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Move", |d, sel| {
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
return super::draw2::with_anchor_path(d, id, |path| {
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p);
|
||||
let before = corner_sources(d, id);
|
||||
let moved = BTreeSet::from([(si, ai)]);
|
||||
@@ -975,24 +989,25 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path that has it.
|
||||
/// Busy while a script runs, as [`Session::edit`] is.
|
||||
/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path, or type
|
||||
/// on a path ([`Node::anchor_path`], in document space), that has it. Busy while a script runs, as
|
||||
/// [`Session::edit`] is.
|
||||
fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anchor>> {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
|
||||
Ok(d.node(id).and_then(Node::anchor_path).and_then(|path| path.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).copied()))
|
||||
}
|
||||
|
||||
/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or
|
||||
/// incoming side; false when the path, subpath or anchor is not there.
|
||||
/// Whether anchor `ai` of subpath `si` of path `id` (or of type on a path's path) has a segment on
|
||||
/// its outgoing (`out`) or incoming side; false when the path, subpath or anchor is not there.
|
||||
fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result<bool> {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
|
||||
Ok(d.node(id).and_then(Node::anchor_path).is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, out))))
|
||||
}
|
||||
|
||||
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1089,45 +1104,82 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(),
|
||||
}
|
||||
};
|
||||
let changed = super::overprint::edit_counted(s, "Reverse Path Direction", |d| {
|
||||
// A compound path's own strokes run along its members' subpaths in order, so they turn
|
||||
// with them, read before any member turns.
|
||||
let compounds: BTreeSet<NodeId> = ids.iter().map(|id| compound_or_self(d, *id)).filter(|c| ids.binary_search(c).is_err()).collect();
|
||||
for c in compounds {
|
||||
let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue };
|
||||
let flip: Vec<bool> = children
|
||||
.iter()
|
||||
.filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] }))
|
||||
.flatten()
|
||||
.collect();
|
||||
if flip.contains(&true)
|
||||
&& let Some(n) = d.node_mut(c)
|
||||
{
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
let mut d = (*s.doc()?.doc).clone();
|
||||
// A compound path's own strokes run along its members' subpaths in order, so they turn
|
||||
// with them, read before any member turns.
|
||||
let compounds: BTreeSet<NodeId> = ids.iter().map(|id| compound_or_self(&d, *id)).filter(|c| ids.binary_search(c).is_err()).collect();
|
||||
for c in compounds {
|
||||
let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue };
|
||||
let flip: Vec<bool> = children
|
||||
.iter()
|
||||
.filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] }))
|
||||
.flatten()
|
||||
.collect();
|
||||
if flip.contains(&true)
|
||||
&& let Some(n) = d.node_mut(c)
|
||||
{
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
}
|
||||
}
|
||||
let mut turned = Vec::new();
|
||||
for id in &ids {
|
||||
let path = path_mut(&mut d, *id)?;
|
||||
let flip = flip_of(path);
|
||||
if !flip.contains(&true) {
|
||||
continue;
|
||||
}
|
||||
// The stroke's width profile and pen recordings turn with the path, read before it turns.
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
}
|
||||
let path = path_mut(&mut d, *id)?;
|
||||
for (sp, f) in path.subpaths.iter_mut().zip(&flip) {
|
||||
if *f {
|
||||
sp.reverse();
|
||||
}
|
||||
}
|
||||
let mut changed = 0;
|
||||
for id in &ids {
|
||||
let path = path_mut(d, *id)?;
|
||||
let flip = flip_of(path);
|
||||
if !flip.contains(&true) {
|
||||
continue;
|
||||
}
|
||||
// The stroke's width profile and pen recordings turn with the path, read before it turns.
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
}
|
||||
let path = path_mut(d, *id)?;
|
||||
for (sp, f) in path.subpaths.iter_mut().zip(flip) {
|
||||
if f {
|
||||
sp.reverse();
|
||||
turned.push((*id, flip));
|
||||
}
|
||||
if !turned.is_empty() {
|
||||
s.edit("Reverse Path Direction", |doc, sel| {
|
||||
*doc = d;
|
||||
for (id, flip) in &turned {
|
||||
if let Some(path) = doc.node(*id).and_then(Node::path_data) {
|
||||
reverse_selected_anchors(sel, *id, path, flip);
|
||||
}
|
||||
}
|
||||
changed += 1;
|
||||
}
|
||||
Ok(changed)
|
||||
})?;
|
||||
Ok(json!({ "changed": changed }))
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "changed": turned.len() }))
|
||||
}
|
||||
|
||||
/// Point the selected anchors, selected segments and key anchor of `sel` on path `id` at the same
|
||||
/// points after the subpaths of `path` marked in `flip` were reversed ([`SubPath::reverse`]). In a
|
||||
/// reversed subpath of `n` anchors, anchor `i` becomes anchor `n - 1 - i` and segment `j` becomes
|
||||
/// segment `n - 2 - j`; a closed subpath's closing segment (`n - 1`) stays its closing segment.
|
||||
fn reverse_selected_anchors(sel: &mut Selection, id: NodeId, path: &PathData, flip: &[bool]) {
|
||||
let reversed = |si: usize| path.subpaths.get(si).filter(|_| flip.get(si) == Some(&true)).map(|sp| (sp.anchors.len(), sp.closed));
|
||||
let anchor = |(si, ai): AnchorRef| match reversed(si) {
|
||||
Some((n, _)) if ai < n => (si, n - 1 - ai),
|
||||
_ => (si, ai),
|
||||
};
|
||||
let segment = |(si, j): SegmentRef| match reversed(si) {
|
||||
Some((n, true)) if j < n => (si, (2 * n - 2 - j) % n),
|
||||
Some((n, false)) if j < n.saturating_sub(1) => (si, n - 2 - j),
|
||||
_ => (si, j),
|
||||
};
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
*set = set.iter().map(|r| anchor(*r)).collect();
|
||||
}
|
||||
if let Some(set) = sel.segments.get_mut(&id) {
|
||||
*set = set.iter().map(|r| segment(*r)).collect();
|
||||
}
|
||||
if let Some((key, r)) = sel.key_anchor
|
||||
&& key == id
|
||||
{
|
||||
sel.key_anchor = Some((id, anchor(r)));
|
||||
}
|
||||
}
|
||||
|
||||
/// First and last anchor points of a subpath.
|
||||
@@ -2409,8 +2461,9 @@ fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f
|
||||
shares
|
||||
}
|
||||
|
||||
/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors and
|
||||
/// selected segments after it on that subpath one higher, so the selection keeps the same points.
|
||||
/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors,
|
||||
/// selected segments and key anchor after it on that subpath one higher, so the selection keeps
|
||||
/// the same points.
|
||||
/// A selected segment that the new anchor splits stays selected as its two halves, and the new
|
||||
/// anchor joins its ends in the anchors that move with it.
|
||||
fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) {
|
||||
@@ -2419,6 +2472,14 @@ fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usiz
|
||||
// renumbering saturates instead of overflowing.
|
||||
*set = set.iter().map(|&(s, a)| if s == si && a >= added { (s, a.saturating_add(1)) } else { (s, a) }).collect();
|
||||
}
|
||||
// The key anchor moves along with the anchors after the new one.
|
||||
if let Some((key, (s, a))) = sel.key_anchor
|
||||
&& key == id
|
||||
&& s == si
|
||||
&& a >= added
|
||||
{
|
||||
sel.key_anchor = Some((id, (s, a.saturating_add(1))));
|
||||
}
|
||||
let split = added.checked_sub(1);
|
||||
if sel.segments.get(&id).is_some_and(|set| split.is_some_and(|g| set.contains(&(si, g)))) {
|
||||
sel.anchors.entry(id).or_default().insert((si, added));
|
||||
@@ -2564,12 +2625,27 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
|
||||
let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?;
|
||||
let idx = s.edit("Add Anchor Point", |d, sel| {
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
let idx = super::draw2::with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(sp.insert_anchor(seg, t))
|
||||
})?;
|
||||
// Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor`
|
||||
// leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only.
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
if select_anchor || !sel.contains(id) {
|
||||
sel.clear();
|
||||
}
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
if sel.key_anchor.is_some_and(|(k, _)| k == id) {
|
||||
sel.key_anchor = None;
|
||||
}
|
||||
sel.add(id);
|
||||
return Ok(idx);
|
||||
}
|
||||
let idx = sp.insert_anchor(seg, t);
|
||||
renumber_after_insert(sel, id, si, idx);
|
||||
// A path that wasn't selected becomes the selection, its new anchor direct-selected, so
|
||||
// the point added shows and can be edited at once (#4237). `selectAnchor` does the same
|
||||
|
||||
@@ -183,13 +183,13 @@ pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) {
|
||||
|
||||
/// [`load_sliced`] without the slices.
|
||||
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
|
||||
load_into(p, cmd, board, link_pdf, &mut vec![])
|
||||
load_into(p, cmd, board, link_pdf, None, &mut vec![])
|
||||
}
|
||||
|
||||
/// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in.
|
||||
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<(Loaded, Slices)> {
|
||||
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: Option<&[u8]>) -> Result<(Loaded, Slices)> {
|
||||
let mut slices = vec![];
|
||||
let l = load_into(p, cmd, board, link_pdf, &mut slices)?;
|
||||
let l = load_into(p, cmd, board, link_pdf, given, &mut slices)?;
|
||||
Ok((l, slices))
|
||||
}
|
||||
|
||||
@@ -197,9 +197,10 @@ fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Res
|
||||
/// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed
|
||||
/// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB
|
||||
/// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one
|
||||
/// no built-in format reads) is read by it ([`plugin_art`]).
|
||||
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_out: &mut Slices) -> Result<Loaded> {
|
||||
let src = fileio::importer::place_source(p, cmd)?;
|
||||
/// no built-in format reads) is read by it ([`plugin_art`]). `given`: the bytes of the file `p`'s
|
||||
/// `path` names, read already ([`PlaceJob::with_bytes`]).
|
||||
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: Option<&[u8]>, slices_out: &mut Slices) -> Result<Loaded> {
|
||||
let src = fileio::importer::place_source(p, cmd, given)?;
|
||||
let name = fileio::file_name(src.name);
|
||||
if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? {
|
||||
return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd);
|
||||
@@ -238,11 +239,14 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
|
||||
}
|
||||
return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None });
|
||||
}
|
||||
let Some(format) = fileio::detect(src.name, &src.bytes) else {
|
||||
return match fileio::importer::for_place(src.name) {
|
||||
Some(plugin) => plugin_art(name, src.name, &src.bytes, &plugin, p, cmd),
|
||||
None => Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))),
|
||||
};
|
||||
let format = fileio::detect(src.name, &src.bytes);
|
||||
if format.is_none_or(|f| !fileio::reads(f))
|
||||
&& let Some(plugin) = fileio::importer::for_place(src.name)
|
||||
{
|
||||
return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd);
|
||||
}
|
||||
let Some(format) = format else {
|
||||
return Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")));
|
||||
};
|
||||
let page = match p.get("page") {
|
||||
None => 1,
|
||||
@@ -760,8 +764,13 @@ pub struct PlaceJob {
|
||||
/// The object Replace swaps as it was when Place started.
|
||||
replaced: Option<Node>,
|
||||
target: Option<Rect>,
|
||||
/// The bytes of the file `path` names, read already ([`PlaceJob::with_bytes`]).
|
||||
bytes: Option<GivenBytes>,
|
||||
}
|
||||
|
||||
/// The bytes of a file read already, shared with whoever read them ([`PlaceJob::with_bytes`]).
|
||||
pub type GivenBytes = Arc<dyn AsRef<[u8]> + Send + Sync>;
|
||||
|
||||
/// A file [`PlaceJob::read`] read, which [`Session::place_read`] places.
|
||||
pub struct PlaceRead {
|
||||
job: PlaceJob,
|
||||
@@ -775,6 +784,14 @@ impl PlaceJob {
|
||||
str_param(&self.params, "path").or_else(|| str_param(&self.params, "name")).map(fileio::file_name).unwrap_or_else(|| "Untitled".into())
|
||||
}
|
||||
|
||||
/// The job placing `bytes` as the file its `path` names, which [`PlaceJob::read`] then does not
|
||||
/// read again: the placed object's link and the journaled params keep the path. Without a
|
||||
/// `path` the bytes are not used.
|
||||
pub fn with_bytes(mut self, bytes: GivenBytes) -> Self {
|
||||
self.bytes = Some(bytes);
|
||||
self
|
||||
}
|
||||
|
||||
/// Read and decode the file, as `file.place` does, without the session. The pixels of a PNG,
|
||||
/// JPEG, GIF or WebP file are decoded here to check that they can be read (an error when they
|
||||
/// can't), a linked image's preview is made from that decode, and the decoded pixels are kept in
|
||||
@@ -782,7 +799,7 @@ impl PlaceJob {
|
||||
/// ([`super::links::readable_and_kept`]).
|
||||
pub fn read(self) -> Result<PlaceRead> {
|
||||
crate::cancel::check()?;
|
||||
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?;
|
||||
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true, self.bytes.as_deref().map(AsRef::as_ref))?;
|
||||
let linked = loaded.link.is_some() && bool_or(&self.params, "link", true);
|
||||
match &mut loaded.art {
|
||||
Art::Image(img, _) => {
|
||||
@@ -941,12 +958,12 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
|
||||
};
|
||||
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
|
||||
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
|
||||
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at), bytes: None })
|
||||
}
|
||||
|
||||
/// Place the file `read` holds in the active document.
|
||||
fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read;
|
||||
let PlaceRead { job: PlaceJob { params, old, target: read_for, bytes, .. }, mut loaded, slices: read_slices } = read;
|
||||
let p = ¶ms;
|
||||
let template = bool_or(p, "template", false);
|
||||
let at = at_param(p)?;
|
||||
@@ -957,10 +974,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
// The artboard under `at` as it is now, as a replay of the journal finds it: a DXF drawing laid
|
||||
// out on the artboard it was read for is read again when that artboard changed meanwhile.
|
||||
// out on the artboard it was read for is read again when that artboard changed meanwhile, from
|
||||
// the same bytes when the job was given them.
|
||||
let target = board_at(&st.doc, at);
|
||||
if loaded.board.is_some() && target != read_for {
|
||||
loaded = load(p, PLACE, target, true)?;
|
||||
loaded = load_into(p, PLACE, target, true, bytes.as_deref().map(AsRef::as_ref), &mut vec![])?;
|
||||
}
|
||||
// Type reflows rather than scales: its frame takes the size it is placed at.
|
||||
let is_text = matches!(loaded.art, Art::Text(_));
|
||||
@@ -1347,7 +1365,7 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["link"], "file.place.info")?;
|
||||
check_numbers(p, &["thumbnail"], "file.place.info")?;
|
||||
// A PDF/.ai page linked or not has the same size and art.
|
||||
let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?;
|
||||
let (mut l, slices) = load_sliced(p, "file.place.info", None, false, None)?;
|
||||
let natural = l.natural;
|
||||
let mut out = json!({
|
||||
"name": l.name,
|
||||
|
||||
@@ -895,6 +895,7 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[
|
||||
(&["Object"], "Perspective"),
|
||||
(&["Object"], "Live Paint"),
|
||||
(&["Object"], "Image Trace"),
|
||||
(&["Object"], "Concept to Vector…"),
|
||||
(&["Object"], "Text Wrap"),
|
||||
(&["Object"], "Clipping Mask"),
|
||||
(&["Object"], "Compound Path"),
|
||||
|
||||
@@ -762,13 +762,20 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and
|
||||
/// report where it is on disk, or edit text once per match with no limit on the matches in one call.
|
||||
/// report where it is on disk, edit text once per match with no limit on the matches in one call,
|
||||
/// or hand an image to a Concept to Vector provider and its results.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
"addon.pen.nextSegment",
|
||||
"addon.type.fontSheet",
|
||||
"addon.type.numbers",
|
||||
"color.contrast",
|
||||
"conceptVector.cancel",
|
||||
"conceptVector.generate",
|
||||
"conceptVector.insert",
|
||||
"conceptVector.providers",
|
||||
"conceptVector.results",
|
||||
"effect.refreshDeferred",
|
||||
"graphicStyle.setOptions",
|
||||
"object.blend.createSpine",
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Setup",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or pre
Line truncated
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at bitmapResolution, or lower for a page larger than 64 Mpx or 32,768 px a side, with a warning when bitmapResolution was given), bitmapResolution: 0 (ppi Print as Bitmap prints at on paper, so a print scale above 100% renders more pixels, 1–9600; 0: the document's raster effects resolution; other output leaves it unused), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {pla
Line truncated
|
||||
has_doc,
|
||||
setup
|
||||
),
|
||||
@@ -138,6 +138,12 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let set = preset_or_saved(C, s, doc, p)?;
|
||||
super::printadvanced::flattener(C, &set, &s.prefs.flattener_presets)?;
|
||||
let mut pv = vectorcraft_pdf::preview(doc, &set).map_err(|e| pdf_error(C, e))?;
|
||||
if set.advanced.print_as_bitmap && set.advanced.bitmap_resolution > 0.0 {
|
||||
// Print as Bitmap renders placed documents' art and the artboards' background colors too.
|
||||
let (full, _) = super::place::document::full_documents(doc);
|
||||
let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(C, e))?;
|
||||
pv.setting_notes.extend(super::printadvanced::bitmap_notes(C, &filled, &set)?);
|
||||
}
|
||||
pv.warnings.extend(type_warnings(doc, set.print_layers, &areas(&pv)));
|
||||
// What the job loses comes first, then the notes on the options.
|
||||
let settings = std::mem::take(&mut pv.setting_notes);
|
||||
@@ -275,7 +281,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tile_images =
|
||||
postscript && !bitmap && flattener.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o));
|
||||
// Print as Bitmap and the flattener preset (Advanced) render and flatten it first.
|
||||
let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?;
|
||||
let mut bitmap_notes = vec![];
|
||||
let prepared =
|
||||
super::printadvanced::prepare_noting(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich", &mut bitmap_notes)?;
|
||||
let path = str_param(p, "path");
|
||||
// The type is read before raster effects and Print as Bitmap turn it into images.
|
||||
let which = set.print_layers;
|
||||
@@ -293,10 +301,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// What the job loses comes first, then the notes on the options.
|
||||
r.warnings.extend(typed);
|
||||
r.warnings.extend(r.setting_notes);
|
||||
r.warnings.extend(bitmap_notes);
|
||||
return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings }));
|
||||
}
|
||||
// What the job loses, then the notes on the options: a reply lists them in that order.
|
||||
let (mut warnings, mut setting_notes) = (vec![], vec![]);
|
||||
let (mut warnings, mut setting_notes) = (vec![], bitmap_notes);
|
||||
if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) {
|
||||
warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! File → Print › Advanced, what needs the renderer and the flattener (the PDF writer does the
|
||||
//! rest): Print as Bitmap renders each printed region as one image, and a flattener preset
|
||||
//! rest): Print as Bitmap renders each printed region as one image (at `advanced.bitmapResolution`,
|
||||
//! or the document's raster effects resolution), and a flattener preset
|
||||
//! flattens transparency, both on the document as it prints (only the layers that print,
|
||||
//! overprints discarded or simulated in composite output) before it is laid out on paper.
|
||||
|
||||
@@ -31,7 +32,21 @@ pub(crate) fn flattener(cmd: &str, set: &PrintSettings, saved: &[FlattenerPreset
|
||||
/// `doc` as Print as Bitmap and the flattener preset of `set` print it (from `saved` presets), or
|
||||
/// `None` when neither applies. Print as Bitmap is for composite output.
|
||||
/// `rich_black`: Appearance of Black › Printing / Exporting › Output All Blacks as Rich Black.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn prepare(cmd: &str, doc: &Document, set: &PrintSettings, saved: &[FlattenerPreset], rich_black: bool) -> Result<Option<Document>> {
|
||||
prepare_noting(cmd, doc, set, saved, rich_black, &mut vec![])
|
||||
}
|
||||
|
||||
/// [`prepare`], with the note on an image Print as Bitmap prints below `advanced.bitmapResolution`
|
||||
/// added to `notes`.
|
||||
pub(crate) fn prepare_noting(
|
||||
cmd: &str,
|
||||
doc: &Document,
|
||||
set: &PrintSettings,
|
||||
saved: &[FlattenerPreset],
|
||||
rich_black: bool,
|
||||
notes: &mut Vec<String>,
|
||||
) -> Result<Option<Document>> {
|
||||
let composite = set.output.mode == OutputMode::Composite;
|
||||
let bitmap = set.advanced.print_as_bitmap && composite;
|
||||
let flattener = flattener(cmd, set, saved)?;
|
||||
@@ -40,7 +55,9 @@ pub(crate) fn prepare(cmd: &str, doc: &Document, set: &PrintSettings, saved: &[F
|
||||
}
|
||||
let printed = vectorcraft_pdf::printed_document(doc, set);
|
||||
if bitmap {
|
||||
return bitmap_document(cmd, &printed, set, rich_black).map(Some);
|
||||
let (out, lowest) = bitmap_document(cmd, &printed, set, rich_black)?;
|
||||
notes.extend(capped_note(set, lowest));
|
||||
return Ok(Some(out));
|
||||
}
|
||||
let Some(mut o) = flattener else { return Ok(None) };
|
||||
// Composite overprints that were discarded or simulated aren't preserved either.
|
||||
@@ -62,12 +79,81 @@ fn drop_guides(nodes: &mut Vec<Arc<Node>>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The resolution Print as Bitmap renders `doc` at with `set` (ppi): `advanced.bitmapResolution`,
|
||||
/// or the document's raster effects resolution when that is 0.
|
||||
fn bitmap_ppi(doc: &Document, set: &PrintSettings) -> f64 {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
if asked > 0.0 { asked } else { doc.raster_effects_ppi }
|
||||
}
|
||||
|
||||
/// The pixels per document point Print as Bitmap renders `area` at so that it prints at `ppi` on
|
||||
/// paper when the page scales it by `placed` on each axis (1 = 100%): at most MAX_PIXELS, and
|
||||
/// no side longer than the renderer draws (rounded up to whole pixels when it renders).
|
||||
fn bitmap_scale(area: Rect, ppi: f64, placed: (f64, f64)) -> (f64, f64) {
|
||||
let (w, h) = (area.width() * ppi / 72.0 * placed.0, area.height() * ppi / 72.0 * placed.1);
|
||||
let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0;
|
||||
let limit = 1.0_f64.min((MAX_PIXELS / (w * h).max(1.0)).sqrt()).min(longest / w.max(1.0)).min(longest / h.max(1.0));
|
||||
let (w, h) = (w * limit, h * limit);
|
||||
let rounding = if whole_pixels(w) * whole_pixels(h) > MAX_PIXELS { ((MAX_PIXELS - w - h - 1.0) / (w * h)).sqrt() } else { 1.0 };
|
||||
(w * rounding / area.width(), h * rounding / area.height())
|
||||
}
|
||||
|
||||
/// The whole pixels Print as Bitmap renders `len` pixels of art as: rounded up, at least 1, with
|
||||
/// the rounding error of `len` scaled down and up again left out.
|
||||
fn whole_pixels(len: f64) -> f64 {
|
||||
(len - 1e-6).ceil().max(1.0)
|
||||
}
|
||||
|
||||
/// The horizontal and vertical scales (1 = 100%) the page prints the region `r` of `printed`
|
||||
/// at with `set`, both 1 when it prints on no page.
|
||||
fn placed_scale(printed: &Document, set: &PrintSettings, r: Rect) -> (f64, f64) {
|
||||
vectorcraft_pdf::print_region_scale(printed, set, r).filter(|(x, y)| x.is_finite() && *x > 0.0 && y.is_finite() && *y > 0.0).unwrap_or((1.0, 1.0))
|
||||
}
|
||||
|
||||
/// The note on Print as Bitmap printing below the `advanced.bitmapResolution` of `set`, when the
|
||||
/// `lowest` resolution (ppi) an image prints at is lower. None when the job leaves the resolution
|
||||
/// to the document.
|
||||
fn capped_note(set: &PrintSettings, lowest: Option<f64>) -> Option<String> {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
let lowest = lowest.filter(|l| asked > 0.0 && l.is_finite() && *l < asked - 1e-6)?;
|
||||
Some(format!(
|
||||
"Print as Bitmap prints at {} ppi, not the {asked} ppi bitmapResolution asks for: a page prints as at most 64 million pixels and 32,768 pixels a side",
|
||||
lowest.floor()
|
||||
))
|
||||
}
|
||||
|
||||
/// What [`prepare`] notes on Print as Bitmap for `doc` printed with `set`, without rendering it,
|
||||
/// for the preview: a page with art that prints whose image the pixel limits keep below
|
||||
/// `advanced.bitmapResolution`. The art is judged by its bounds, so a page holding only art that
|
||||
/// draws nothing (fully transparent) is counted, while the print itself leaves its image out.
|
||||
pub(crate) fn bitmap_notes(cmd: &str, doc: &Document, set: &PrintSettings) -> Result<Vec<String>> {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
if !(set.advanced.print_as_bitmap && set.output.mode == OutputMode::Composite && asked > 0.0) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let printed = vectorcraft_pdf::printed_document(doc, set);
|
||||
let regions = vectorcraft_pdf::print_regions(&printed, set).map_err(|e| pdf_error(cmd, e))?;
|
||||
let bleed = vectorcraft_pdf::page_bleed(&set.bleed, &printed);
|
||||
let lowest = regions
|
||||
.iter()
|
||||
.map(|(_, r)| (outset(*r, bleed), placed_scale(&printed, set, *r)))
|
||||
.filter(|(area, _)| vectorcraft_pdf::prints_art_in(&printed, *area))
|
||||
.map(|(area, placed)| {
|
||||
let (x, y) = bitmap_scale(area, asked, placed);
|
||||
(x / placed.0).min(y / placed.1) * 72.0
|
||||
})
|
||||
.reduce(f64::min);
|
||||
Ok(capped_note(set, lowest).into_iter().collect())
|
||||
}
|
||||
|
||||
/// `doc` (as it prints) with its art replaced by one image of each printed region (an artboard
|
||||
/// with its bleed, or all the art), at the document's raster effects resolution; regions where
|
||||
/// nothing is drawn get none.
|
||||
fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<Document> {
|
||||
/// with its bleed, or all the art), at [`bitmap_ppi`] within [`bitmap_scale`]'s limits; regions
|
||||
/// where nothing is drawn get none. Also the lowest resolution an image prints at (ppi), `None`
|
||||
/// without images.
|
||||
fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<(Document, Option<f64>)> {
|
||||
let regions = vectorcraft_pdf::print_regions(doc, set).map_err(|e| pdf_error(cmd, e))?;
|
||||
let bleed = vectorcraft_pdf::page_bleed(&set.bleed, doc);
|
||||
let ppi = bitmap_ppi(doc, set);
|
||||
let mut art = doc.clone();
|
||||
drop_guides(&mut art.layers);
|
||||
let anti_alias = if doc.raster_effects.anti_alias { AntiAlias::Art } else { AntiAlias::None };
|
||||
@@ -75,37 +161,34 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b
|
||||
let mut out = doc.clone();
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let mut images = vec![];
|
||||
let mut lowest: Option<f64> = None;
|
||||
for (_, r) in regions {
|
||||
let area = outset(r, bleed);
|
||||
// At most MAX_PIXELS, and no side longer than the renderer draws (rounded up to whole
|
||||
// pixels below).
|
||||
let side = area.width().max(area.height()).max(1.0);
|
||||
let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0;
|
||||
let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side);
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
let placed = placed_scale(doc, set, r);
|
||||
let scale = bitmap_scale(area, ppi, placed);
|
||||
if !(scale.0.is_finite() && scale.0 > 0.0 && scale.1.is_finite() && scale.1 > 0.0) {
|
||||
continue;
|
||||
}
|
||||
// Whole pixels.
|
||||
let region = Rect::new(
|
||||
area.x0,
|
||||
area.y0,
|
||||
area.x0 + (area.width() * scale).ceil().max(1.0) / scale,
|
||||
area.y0 + (area.height() * scale).ceil().max(1.0) / scale,
|
||||
);
|
||||
let img = renderer.render_region_with(&art, region, scale, &opts);
|
||||
let width = whole_pixels(area.width() * scale.0) as u32;
|
||||
let height = whole_pixels(area.height() * scale.1) as u32;
|
||||
let view = Affine::scale_non_uniform(scale.0, scale.1) * Affine::translate((-area.x0, -area.y0));
|
||||
let img = renderer.render(&art, width, height, view, &opts);
|
||||
if img.pixels.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {
|
||||
continue;
|
||||
}
|
||||
let key = unique_key(&out, "print-bitmap");
|
||||
out.images.insert(key.clone(), ImageBlob::new("image/png", img.to_png().map_err(EngineError::Other)?));
|
||||
let xf = Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale);
|
||||
let xf = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(1.0 / scale.0, 1.0 / scale.1);
|
||||
let image = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None };
|
||||
images.push(Arc::new(Node::new(out.alloc_id(), NodeKind::Image(Box::new(image)))));
|
||||
let printed_ppi = (scale.0 / placed.0).min(scale.1 / placed.1) * 72.0;
|
||||
lowest = Some(lowest.map_or(printed_ppi, |l| l.min(printed_ppi)));
|
||||
}
|
||||
let mut layer = Node::layer(out.alloc_id(), "Bitmap", LayerColor::Preset(0));
|
||||
if let Some(children) = layer.children_mut() {
|
||||
*children = images;
|
||||
}
|
||||
out.layers = vec![Arc::new(layer)];
|
||||
Ok(out)
|
||||
Ok((out, lowest))
|
||||
}
|
||||
@@ -1197,6 +1197,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
|
||||
let plan = SavePlan {
|
||||
mode: SaveMode::Copy,
|
||||
path: st.path.clone(),
|
||||
path_given: false,
|
||||
format: native,
|
||||
options: serde_json::Map::from_iter([("pdfCompatible".into(), json!(false))]),
|
||||
name: format!("{file}{DOC_EXT}"),
|
||||
|
||||
@@ -257,7 +257,12 @@ pub(crate) fn captured(n: &Node) -> Appearance {
|
||||
/// fills, and their stroke when it has strokes.
|
||||
fn override_chars(n: &mut Node, ap: &Appearance) {
|
||||
let NodeKind::Text(t) = &mut n.kind else { return };
|
||||
let (fills, strokes) = (ap.items.iter().any(|i| i.is_fill()), ap.items.iter().any(|i| !i.is_fill()));
|
||||
override_text_chars(t, ap, true);
|
||||
}
|
||||
|
||||
/// [`override_chars`] for type `t`; with `fill` false its characters keep their fill.
|
||||
pub(crate) fn override_text_chars(t: &mut vectorcraft_doc::TextObject, ap: &Appearance, fill: bool) {
|
||||
let (fills, strokes) = (fill && ap.items.iter().any(|i| i.is_fill()), ap.items.iter().any(|i| !i.is_fill()));
|
||||
for r in &mut t.runs {
|
||||
if fills {
|
||||
r.style.fill = Paint::None;
|
||||
|
||||
@@ -39,7 +39,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 39] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
@@ -70,6 +70,7 @@ const REPLAY_ONLY: [(&str, &str); 39] = [
|
||||
("artboard.distribute", "activeArtboard"),
|
||||
("artboard.distributeSpacing", "selectedArtboards"),
|
||||
("artboard.distributeSpacing", "activeArtboard"),
|
||||
("addon.type.fontSheet", "activeArtboard"),
|
||||
("addon.document.floodFillArtboards", "activeArtboard"),
|
||||
("edit.copy", "selectedArtboards"),
|
||||
("edit.copy", "art"),
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
//! Concept to Vector providers: what makes vector variations of a selected image.
|
||||
//!
|
||||
//! A provider ([`Provider`]) takes one image's encoded pixels and up to [`MAX_STYLES`] of its own
|
||||
//! style ids ([`Request`]), and returns one [`Variation`] per style, in the order asked, as paths
|
||||
//! in the image's pixel space with explicit paints. It sees nothing else of the session or the
|
||||
//! document. The session keeps the providers in a [`Registry`] and calls one only by its id: an
|
||||
//! unknown or incapable provider is an error, never a substitute.
|
||||
//!
|
||||
//! The host checks every result again ([`check_result`]) before it keeps it, whatever provider
|
||||
//! made it: the number and order of the variations, finite coordinates and widths within bounds,
|
||||
//! and the totals [`MAX_ANCHORS`] and [`MAX_PATHS`] across all styles.
|
||||
//!
|
||||
//! The one built-in provider ([`offline::ID`]) makes its styles with Image Trace, on this
|
||||
//! computer: it takes no prompt and makes vector art only.
|
||||
|
||||
pub mod offline;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
|
||||
/// The most styles one request may ask for.
|
||||
pub const MAX_STYLES: usize = 8;
|
||||
|
||||
/// The most anchor points all the variations of one request may hold together.
|
||||
pub const MAX_ANCHORS: usize = 1_000_000;
|
||||
|
||||
/// The most paths all the variations of one request may hold together, each subpath of a compound
|
||||
/// path counted as one.
|
||||
pub const MAX_PATHS: usize = 250_000;
|
||||
|
||||
/// The most warnings a variation may carry, and the most characters in each.
|
||||
pub const MAX_WARNINGS: usize = 16;
|
||||
const MAX_WARNING_CHARS: usize = 500;
|
||||
|
||||
/// One of a provider's styles: its stable id and its English name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
pub struct Style {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
}
|
||||
|
||||
/// What a provider takes and makes.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Capabilities {
|
||||
/// It takes an image as its input.
|
||||
pub image_input: bool,
|
||||
/// It makes editable vector paths.
|
||||
pub vector_output: bool,
|
||||
/// It takes a text prompt.
|
||||
pub prompt: bool,
|
||||
/// It makes raster images.
|
||||
pub raster_output: bool,
|
||||
/// It runs on this computer without a network.
|
||||
pub offline: bool,
|
||||
/// Its styles, in the order it lists them.
|
||||
pub styles: Vec<Style>,
|
||||
}
|
||||
|
||||
/// The kind of result a request asks for. `conceptVector.generate` asks only for
|
||||
/// [`Output::Vector`]: a [`Variation`] holds vector paths.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Output {
|
||||
Vector,
|
||||
Raster,
|
||||
}
|
||||
|
||||
/// One request: the encoded pixels of an image, and how to make its variations.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Request {
|
||||
/// The image's encoded bytes (PNG, JPEG, WebP or GIF), as the document holds them.
|
||||
pub image: Arc<Vec<u8>>,
|
||||
/// The image's size in pixels: the space the variations' paths are in.
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// The prompt, trimmed; `None` when there is none.
|
||||
pub prompt: Option<String>,
|
||||
/// The provider's style ids, 1 to [`MAX_STYLES`] of them, each once.
|
||||
pub styles: Vec<String>,
|
||||
/// How much of the image's detail to keep, 0 (least) to 100 (most).
|
||||
pub detail: u8,
|
||||
pub output: Output,
|
||||
}
|
||||
|
||||
/// One path of a variation, in the image's pixel space (`(0, 0)` top left, `(width, height)` bottom
|
||||
/// right).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VectorPath {
|
||||
pub path: PathData,
|
||||
/// The fill color (sRGB), if it is filled.
|
||||
pub fill: Option<[u8; 3]>,
|
||||
/// The stroke color (sRGB) and width in pixels, if it is stroked.
|
||||
pub stroke: Option<([u8; 3], f64)>,
|
||||
/// Stroked: the stroke's ends are square (cut straight half the width past the path's end);
|
||||
/// otherwise round.
|
||||
pub square_caps: bool,
|
||||
}
|
||||
|
||||
/// The variation a provider made for one style.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Variation {
|
||||
/// The style id it was made for.
|
||||
pub style: String,
|
||||
/// Its paths, bottom-most first.
|
||||
pub paths: Vec<VectorPath>,
|
||||
/// Notes for the person who asked (a scaled-down image, nothing traced).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Variation {
|
||||
/// Its anchor points, every path counted.
|
||||
pub fn anchors(&self) -> usize {
|
||||
self.paths.iter().map(|p| p.path.anchor_count()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a provider made nothing.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
pub enum ProviderError {
|
||||
/// The image or the request cannot be used.
|
||||
#[error("{0}")]
|
||||
InvalidInput(String),
|
||||
/// The provider does not do what the request asks.
|
||||
#[error("{0}")]
|
||||
Unsupported(String),
|
||||
/// The provider cannot run now.
|
||||
#[error("{0}")]
|
||||
Unavailable(String),
|
||||
/// The caller stopped it.
|
||||
#[error("cancelled; nothing was changed")]
|
||||
Canceled,
|
||||
/// The results would pass a limit.
|
||||
#[error("the results would have more than {0} anchor points: lower Detail or choose fewer styles")]
|
||||
ResourceLimit(usize),
|
||||
/// The provider's results do not match the request, or are out of bounds.
|
||||
#[error("the provider's results do not match the request or are malformed")]
|
||||
InvalidResult,
|
||||
/// The provider stopped on a fault of its own.
|
||||
#[error("the provider stopped with an internal error: {0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
/// How far a provider has got: `steps(done, total)`; it stops with [`ProviderError::Canceled`]
|
||||
/// once this answers `false`.
|
||||
pub type Steps<'a> = &'a (dyn Fn(u64, u64) -> bool + Sync);
|
||||
|
||||
/// Something that makes vector variations of an image.
|
||||
pub trait Provider: Send + Sync {
|
||||
/// Its stable id, such as `offline.traceStyles`.
|
||||
fn id(&self) -> &'static str;
|
||||
/// Its English name.
|
||||
fn name(&self) -> &'static str;
|
||||
fn capabilities(&self) -> Capabilities;
|
||||
/// One variation for each of `request.styles`, in that order. A style's variation depends only
|
||||
/// on the image, the prompt, the detail and that style, not on the other styles asked for: a
|
||||
/// caller with no thread to wait on asks for one style at a time when [`Provider::parts`] gives
|
||||
/// `None` (`ConceptRun::run_part`, which the web build uses).
|
||||
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError>;
|
||||
/// What [`Provider::generate`] makes, made a part at a time ([`Parts`]), for a caller with no
|
||||
/// thread to wait on; `None` (the default) when it makes no parts smaller than one style.
|
||||
fn parts(&self, _request: &Request) -> Option<Box<dyn Parts>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A request's variations made a part at a time: each call of [`Parts::step`] does a part and
|
||||
/// returns, so that the caller can run other work, or stop, between parts.
|
||||
pub trait Parts: Send {
|
||||
/// Does the next part → the variations once the last part is done, `None` before it.
|
||||
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError>;
|
||||
/// The styles made so far.
|
||||
fn styles_done(&self) -> usize;
|
||||
}
|
||||
|
||||
/// The providers a session can call, by id.
|
||||
#[derive(Clone)]
|
||||
pub struct Registry {
|
||||
providers: Vec<Registered>,
|
||||
}
|
||||
|
||||
/// A provider in a [`Registry`], with the id, name and capabilities it gave when it was
|
||||
/// registered.
|
||||
#[derive(Clone)]
|
||||
pub struct Registered {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
pub capabilities: Capabilities,
|
||||
pub provider: Arc<dyn Provider>,
|
||||
}
|
||||
|
||||
impl Default for Registry {
|
||||
/// The built-in provider only.
|
||||
fn default() -> Self {
|
||||
let p = offline::TraceStyles;
|
||||
Self { providers: vec![Registered { id: p.id(), name: p.name(), capabilities: p.capabilities(), provider: Arc::new(p) }] }
|
||||
}
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// A registry with no provider.
|
||||
pub fn empty() -> Self {
|
||||
Self { providers: vec![] }
|
||||
}
|
||||
|
||||
/// Add `provider`, reading its id, name and capabilities once; an error when one with its id
|
||||
/// is registered already, or when the provider panics while giving them.
|
||||
pub fn register(&mut self, provider: Arc<dyn Provider>) -> Result<(), String> {
|
||||
let (id, name, capabilities) = crate::guard::catch_panic(|| (provider.id(), provider.name(), provider.capabilities()))
|
||||
.map_err(|e| ProviderError::Internal(e).to_string())?;
|
||||
if self.get(id).is_some() {
|
||||
return Err(format!("a provider with the id `{id}` is registered already"));
|
||||
}
|
||||
self.providers.push(Registered { id, name, capabilities, provider });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The provider `id` (exactly so spelled).
|
||||
pub fn get(&self, id: &str) -> Option<&Registered> {
|
||||
self.providers.iter().find(|p| p.id == id)
|
||||
}
|
||||
|
||||
/// The providers in the order they were registered.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Registered> {
|
||||
self.providers.iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `p` is a finite point within `limit` of the image's pixel space.
|
||||
fn within(p: Point, limit: f64, size: (f64, f64)) -> bool {
|
||||
p.x.is_finite() && p.y.is_finite() && p.x >= -limit && p.y >= -limit && p.x <= size.0 + limit && p.y <= size.1 + limit
|
||||
}
|
||||
|
||||
/// Checks the variations a provider returned for `request`: one per style in the order asked, at
|
||||
/// most [`MAX_PATHS`] paths (each subpath of a compound path counted as one) and [`MAX_ANCHORS`]
|
||||
/// anchors together, each path with a fill or a stroke and with subpaths that each have an anchor,
|
||||
/// every anchor and handle finite and within one image side of the image, every
|
||||
/// stroke width finite, over 0 and at most the image's larger side, and at most [`MAX_WARNINGS`]
|
||||
/// warnings of at most 500 characters on each variation.
|
||||
pub fn check_result(request: &Request, variations: &[Variation]) -> Result<(), ProviderError> {
|
||||
if variations.len() != request.styles.len() || variations.iter().zip(&request.styles).any(|(v, s)| v.style != *s) {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
let size = (f64::from(request.width.max(1)), f64::from(request.height.max(1)));
|
||||
let side = size.0.max(size.1);
|
||||
let (mut paths, mut anchors) = (0usize, 0usize);
|
||||
for v in variations {
|
||||
// Each subpath of a compound path becomes an object of its own when it is inserted.
|
||||
paths = v.paths.iter().fold(paths, |n, p| n.saturating_add(p.path.subpaths.len().max(1)));
|
||||
anchors += v.anchors();
|
||||
if anchors > MAX_ANCHORS {
|
||||
return Err(ProviderError::ResourceLimit(MAX_ANCHORS));
|
||||
}
|
||||
if paths > MAX_PATHS || v.warnings.len() > MAX_WARNINGS || v.warnings.iter().any(|w| w.chars().count() > MAX_WARNING_CHARS) {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
for p in &v.paths {
|
||||
let width_ok = p.stroke.is_none_or(|(_, w)| w.is_finite() && w > 0.0 && w <= side);
|
||||
let painted = p.fill.is_some() || p.stroke.is_some();
|
||||
let points_ok = p.path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].into_iter().all(|q| within(q, side, size)));
|
||||
let no_empty_subpath = !p.path.subpaths.is_empty() && p.path.subpaths.iter().all(|sp| !sp.anchors.is_empty());
|
||||
if !width_ok || !painted || !no_empty_subpath || !points_ok {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
//! The built-in provider: Concept to Vector styles made with Image Trace on this computer.
|
||||
//!
|
||||
//! Each style is a fixed set of Image Trace settings of VectorCraft's own, and Detail (0 to 100)
|
||||
//! moves its Paths, Noise and color count within that style's range. The image is decoded once and
|
||||
//! traced once per style; an image over [`MAX_PIXELS`] is scaled down first, aspect kept, and
|
||||
//! each variation says so. The paths are mapped back to the image's own pixel size.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::kurbo::common::solve_cubic;
|
||||
use vectorcraft_geom::{Affine, Anchor, CubicBez, ParamCurve, PathData, Point, SubPath};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
use super::{Capabilities, MAX_ANCHORS, MAX_PATHS, Output, Parts, ProviderError, Request, Steps, Style, Variation, VectorPath};
|
||||
|
||||
/// The built-in provider's id.
|
||||
pub const ID: &str = "offline.traceStyles";
|
||||
|
||||
/// The most pixels the built-in provider traces an image at (16 megapixels).
|
||||
pub const MAX_PIXELS: u64 = 16 << 20;
|
||||
|
||||
/// The built-in provider's styles, in the order it lists them.
|
||||
pub const STYLES: [Style; 5] = [
|
||||
Style { id: "outline", label: "Outline" },
|
||||
Style { id: "inkLines", label: "Ink Lines" },
|
||||
Style { id: "flatColor", label: "Flat Color" },
|
||||
Style { id: "detailedColor", label: "Detailed Color" },
|
||||
Style { id: "grayTones", label: "Gray Tones" },
|
||||
];
|
||||
|
||||
/// Concept to Vector styles made with Image Trace ([`ID`]).
|
||||
pub struct TraceStyles;
|
||||
|
||||
/// `lo` at Detail 0 to `hi` at Detail 100.
|
||||
fn between(lo: f64, hi: f64, t: f64) -> f64 {
|
||||
lo + (hi - lo) * t
|
||||
}
|
||||
|
||||
/// The trace settings of style `id` at Detail `detail` (0 to 100); `None` for an id that isn't one
|
||||
/// of [`STYLES`].
|
||||
pub fn style_params(id: &str, detail: u8) -> Option<tr::TraceParams> {
|
||||
let t = f64::from(detail.min(100)) / 100.0;
|
||||
let noise = |lo: f64, hi: f64| between(hi, lo, t).round().max(1.0) as u32;
|
||||
let count = |lo: f64, hi: f64| between(lo, hi, t).round() as u32;
|
||||
let base = tr::TraceParams { shapes: false, gradients: false, auto_grouping: false, ..tr::TraceParams::default() };
|
||||
Some(match id {
|
||||
// Black stroked lines only: thin lines as center lines, wider areas as outlines.
|
||||
"outline" => {
|
||||
tr::TraceParams { fills: false, strokes: true, ignore_white: true, paths: between(50.0, 90.0, t), noise: noise(4.0, 40.0), ..base }
|
||||
}
|
||||
// Black filled ink on no background, the straight runs straightened.
|
||||
"inkLines" => tr::TraceParams {
|
||||
ignore_white: true,
|
||||
snap_curves_to_lines: true,
|
||||
paths: between(50.0, 95.0, t),
|
||||
corners: 80.0,
|
||||
noise: noise(4.0, 30.0),
|
||||
..base
|
||||
},
|
||||
// A few flat colors, abutting.
|
||||
"flatColor" => tr::TraceParams {
|
||||
mode: tr::Mode::Color,
|
||||
colors: count(3.0, 8.0),
|
||||
paths: between(40.0, 80.0, t),
|
||||
corners: 60.0,
|
||||
noise: noise(8.0, 40.0),
|
||||
snap_curves_to_lines: true,
|
||||
..base
|
||||
},
|
||||
// Many colors, stacked so no hairline gaps show.
|
||||
"detailedColor" => tr::TraceParams {
|
||||
mode: tr::Mode::Color,
|
||||
colors: count(12.0, 32.0),
|
||||
paths: between(70.0, 95.0, t),
|
||||
corners: 40.0,
|
||||
noise: noise(2.0, 12.0),
|
||||
method: tr::Method::Overlapping,
|
||||
..base
|
||||
},
|
||||
// Grays, stacked.
|
||||
"grayTones" => tr::TraceParams {
|
||||
mode: tr::Mode::Grayscale,
|
||||
colors: count(4.0, 12.0),
|
||||
paths: between(55.0, 90.0, t),
|
||||
corners: 50.0,
|
||||
noise: noise(4.0, 20.0),
|
||||
method: tr::Method::Overlapping,
|
||||
..base
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `img` box-filtered down to at most [`MAX_PIXELS`], aspect kept; `img` itself when it fits.
|
||||
fn fit(img: tr::Raster) -> tr::Raster {
|
||||
fit_within(img, MAX_PIXELS)
|
||||
}
|
||||
|
||||
/// `img` box-filtered down to at most `max` pixels (at least 1), aspect kept as far as a side of
|
||||
/// at least one pixel allows; `img` itself when it fits.
|
||||
pub(super) fn fit_within(img: tr::Raster, max: u64) -> tr::Raster {
|
||||
let (w, h) = (u64::from(img.width), u64::from(img.height));
|
||||
let max = max.max(1);
|
||||
if w * h <= max || w == 0 || h == 0 {
|
||||
return img;
|
||||
}
|
||||
let k = (max as f64 / (w * h) as f64).sqrt();
|
||||
// A side that rounds down to one pixel leaves the other side the whole budget, no more.
|
||||
let nh = ((h as f64 * k).floor() as u64).clamp(1, h.min(max));
|
||||
let nw = ((w as f64 * k).floor() as u64).clamp(1, w.min(max / nh)) as u32;
|
||||
let nh = nh as u32;
|
||||
let mut rgba = Vec::with_capacity(nw as usize * nh as usize * 4);
|
||||
for y in 0..nh {
|
||||
let (y0, y1) = (u64::from(y) * h / u64::from(nh), (u64::from(y + 1) * h / u64::from(nh)).max(u64::from(y) * h / u64::from(nh) + 1));
|
||||
for x in 0..nw {
|
||||
let (x0, x1) = (u64::from(x) * w / u64::from(nw), (u64::from(x + 1) * w / u64::from(nw)).max(u64::from(x) * w / u64::from(nw) + 1));
|
||||
// Each pixel's color is weighted by its alpha. A box with nothing opaque in it is clear black.
|
||||
let mut sum = [0u64; 4];
|
||||
for sy in y0..y1.min(h) {
|
||||
for sx in x0..x1.min(w) {
|
||||
let [r, g, b, a] = img.pixel(sx as u32, sy as u32).map(u64::from);
|
||||
sum = [sum[0] + r * a, sum[1] + g * a, sum[2] + b * a, sum[3] + a];
|
||||
}
|
||||
}
|
||||
let n = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1);
|
||||
let alpha = sum[3];
|
||||
let color = |s: u64| s.checked_div(alpha).map_or(0, |c| c.min(255) as u8);
|
||||
rgba.extend([color(sum[0]), color(sum[1]), color(sum[2]), (alpha / n) as u8]);
|
||||
}
|
||||
}
|
||||
tr::Raster { width: nw, height: nh, rgba }
|
||||
}
|
||||
|
||||
impl super::Provider for TraceStyles {
|
||||
fn id(&self) -> &'static str {
|
||||
ID
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"Offline Image Trace Styles"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities { image_input: true, vector_output: true, prompt: false, raster_output: false, offline: true, styles: STYLES.to_vec() }
|
||||
}
|
||||
|
||||
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError> {
|
||||
let params = checked(request)?;
|
||||
let total = params.len() as u64;
|
||||
if !steps(0, total) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
let image = Decoded::new(request)?;
|
||||
let mut left = MAX_ANCHORS;
|
||||
let mut out = Vec::with_capacity(params.len());
|
||||
for (i, (style, p)) in request.styles.iter().zip(¶ms).enumerate() {
|
||||
let go_on = |_: u64, _: u64| steps(i as u64, total);
|
||||
let res = tr::trace_watched(&image.raster, p, left, &go_on).map_err(trace_error)?;
|
||||
left = left.saturating_sub(res.anchor_count());
|
||||
out.push(image.variation(style, p, res));
|
||||
}
|
||||
if !steps(total, total) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
Ok(with_seams(out))
|
||||
}
|
||||
|
||||
/// The image decoded in the first part; then for each style, its color layers found in one
|
||||
/// part and each layer traced in a part of its own ([`tr::TraceSteps`]), or all of them in
|
||||
/// one part where the style stacks them (Overlapping with Fills).
|
||||
fn parts(&self, request: &Request) -> Option<Box<dyn Parts>> {
|
||||
Some(Box::new(TraceParts { request: request.clone(), image: None, trace: None, left: MAX_ANCHORS, out: vec![], ended: false }))
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace settings of each of `request`'s styles; an error for a prompt, an output other than
|
||||
/// vector art, or a style that isn't one of [`STYLES`]. The host refuses these first; a direct
|
||||
/// caller gets the same answer.
|
||||
fn checked(request: &Request) -> Result<Vec<tr::TraceParams>, ProviderError> {
|
||||
let pid = ID;
|
||||
if request.prompt.is_some() || request.output != Output::Vector {
|
||||
return Err(ProviderError::Unsupported(format!("`{pid}` takes no prompt and makes vector art only")));
|
||||
}
|
||||
request
|
||||
.styles
|
||||
.iter()
|
||||
.map(|s| style_params(s, request.detail))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(|| ProviderError::InvalidInput(format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)")))
|
||||
}
|
||||
|
||||
fn trace_error(e: tr::TraceError) -> ProviderError {
|
||||
match e {
|
||||
tr::TraceError::Cancelled => ProviderError::Canceled,
|
||||
tr::TraceError::TooComplex { .. } => ProviderError::ResourceLimit(MAX_ANCHORS),
|
||||
e => ProviderError::InvalidInput(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A request's image decoded for tracing, with what maps its traced paths back.
|
||||
struct Decoded {
|
||||
raster: Arc<tr::Raster>,
|
||||
/// The decoded raster's pixels → the image's own pixel space.
|
||||
back: Affine,
|
||||
unit: f64,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Decoded {
|
||||
/// `request`'s image decoded, scaled down to at most [`MAX_PIXELS`].
|
||||
fn new(request: &Request) -> Result<Self, ProviderError> {
|
||||
let raster = fit(tr::Raster::decode_to_fit(&request.image).map_err(|e| ProviderError::InvalidInput(e.to_string()))?);
|
||||
let mut warnings = vec![];
|
||||
let (iw, ih) = (request.width.max(1), request.height.max(1));
|
||||
if u64::from(raster.width) * u64::from(raster.height) < u64::from(iw) * u64::from(ih) {
|
||||
warnings.push(format!("The image was traced at {} × {} pixels, scaled down from {iw} × {ih}.", raster.width, raster.height));
|
||||
}
|
||||
let back = Affine::scale_non_uniform(f64::from(iw) / f64::from(raster.width.max(1)), f64::from(ih) / f64::from(raster.height.max(1)));
|
||||
let unit = back.determinant().abs().sqrt();
|
||||
Ok(Self { raster: Arc::new(raster), back, unit, warnings })
|
||||
}
|
||||
|
||||
/// The variation of `style` that the trace `res` of this image, made with `params`, makes, and
|
||||
/// the seam fills of an Abutting trace with fills ([`tr::seam_fills`]) trimmed inside the
|
||||
/// image ([`within_image`]) and outlined in raster pixels before mapping them back, for
|
||||
/// [`with_seams`] to lay under its paths.
|
||||
fn variation(&self, style: &str, params: &tr::TraceParams, res: tr::TraceResult) -> Made {
|
||||
let size = (self.raster.width, self.raster.height);
|
||||
let seams = tr::seam_fills(&res.paths, params, size).map_or_else(Vec::new, |s| {
|
||||
s.strokes
|
||||
.into_iter()
|
||||
.map(|tp| {
|
||||
let mut tp = within_image(tp, size);
|
||||
if let Some(width) = tp.stroke.take() {
|
||||
tp.path = vectorcraft_pathops::outline_stroke(
|
||||
&tp.path,
|
||||
width,
|
||||
vectorcraft_pathops::Cap::Butt,
|
||||
vectorcraft_pathops::Join::Round,
|
||||
4.0,
|
||||
);
|
||||
}
|
||||
tp
|
||||
})
|
||||
.filter(|tp| !tp.path.subpaths.is_empty())
|
||||
.map(|tp| self.vector_path(tp))
|
||||
.collect()
|
||||
});
|
||||
let paths = res.paths.into_iter().map(|tp| self.vector_path(tp)).collect();
|
||||
Made { variation: Variation { style: style.to_string(), paths, warnings: self.warnings.clone() }, seams }
|
||||
}
|
||||
|
||||
/// Traced path `tp` in the image's own pixels.
|
||||
fn vector_path(&self, tp: tr::TracedPath) -> VectorPath {
|
||||
let path = tp.path.transformed(self.back);
|
||||
match tp.stroke {
|
||||
Some(w) => VectorPath { path, fill: None, stroke: Some((tp.color, w * self.unit)), square_caps: tp.square_caps },
|
||||
None => VectorPath { path, fill: Some(tp.color), stroke: None, square_caps: false },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A variation made, and the outlined seam fills to lay under its paths.
|
||||
pub(super) struct Made {
|
||||
pub(super) variation: Variation,
|
||||
pub(super) seams: Vec<VectorPath>,
|
||||
}
|
||||
|
||||
/// [`with_seams_within`] [`MAX_ANCHORS`] and [`MAX_PATHS`].
|
||||
fn with_seams(made: Vec<Made>) -> Vec<Variation> {
|
||||
with_seams_within(made, MAX_ANCHORS, MAX_PATHS)
|
||||
}
|
||||
|
||||
/// The variations `made`, each with its seam fills under its paths, in order, while they fit in
|
||||
/// the `max_anchors` anchors and `max_paths` paths (each subpath counted as one) left once every
|
||||
/// variation is counted: the traced paths of every style come first, and a style whose seam fills
|
||||
/// do not fit goes without them.
|
||||
pub(super) fn with_seams_within(made: Vec<Made>, max_anchors: usize, max_paths: usize) -> Vec<Variation> {
|
||||
let subpaths = |paths: &[VectorPath]| paths.iter().map(|p| p.path.subpaths.len().max(1)).sum::<usize>();
|
||||
let mut anchors = made.iter().map(|m| m.variation.anchors()).sum::<usize>();
|
||||
let mut paths = made.iter().map(|m| subpaths(&m.variation.paths)).sum::<usize>();
|
||||
made.into_iter()
|
||||
.map(|Made { mut variation, seams }| {
|
||||
let (more_anchors, more_paths) = (seams.iter().map(|p| p.path.anchor_count()).sum::<usize>(), subpaths(&seams));
|
||||
if !seams.is_empty() && anchors.saturating_add(more_anchors) <= max_anchors && paths.saturating_add(more_paths) <= max_paths {
|
||||
anchors += more_anchors;
|
||||
paths += more_paths;
|
||||
variation.paths.splice(0..0, seams);
|
||||
}
|
||||
variation
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Seam stroke `tp` of a `size` raster trimmed to half its width inside the raster's border,
|
||||
/// so that its outline with butt caps and round joins stays inside the image. The pieces left form
|
||||
/// open runs; a closed subpath left whole stays closed.
|
||||
fn within_image(mut tp: tr::TracedPath, size: (u32, u32)) -> tr::TracedPath {
|
||||
let half = tp.stroke.unwrap_or_default() / 2.0;
|
||||
let (w, h) = (f64::from(size.0), f64::from(size.1));
|
||||
let mut runs: Vec<SubPath> = vec![];
|
||||
if !half.is_finite() || half < 0.0 || half * 2.0 > w || half * 2.0 > h {
|
||||
tp.path = PathData::new(runs);
|
||||
return tp;
|
||||
}
|
||||
let inside = |p: Point| p.x >= half && p.y >= half && p.x <= w - half && p.y <= h - half;
|
||||
let clamp = |p: Point| Point::new(p.x.clamp(half, w - half), p.y.clamp(half, h - half));
|
||||
for sp in &tp.path.subpaths {
|
||||
let count = sp.segment_count();
|
||||
let mut pieces = vec![];
|
||||
for k in 0..count {
|
||||
let c = sp.segment(k);
|
||||
let mut cuts = vec![0.0, 1.0];
|
||||
if ![c.p0, c.p1, c.p2, c.p3].into_iter().all(inside) {
|
||||
for (p0, p1, p2, p3, side) in [
|
||||
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, half),
|
||||
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, w - half),
|
||||
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, half),
|
||||
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, h - half),
|
||||
] {
|
||||
// Intersections with the sides' supporting lines also cover corner crossings.
|
||||
cuts.extend(
|
||||
solve_cubic(p0 - side, 3.0 * (p1 - p0), 3.0 * (p0 - 2.0 * p1 + p2), p3 - p0 + 3.0 * (p1 - p2))
|
||||
.into_iter()
|
||||
.filter(|&t| t > 0.0 && t < 1.0),
|
||||
);
|
||||
}
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
cuts.dedup();
|
||||
}
|
||||
for pair in cuts.windows(2) {
|
||||
let (t0, t1) = (pair[0], pair[1]);
|
||||
pieces.push((k, t0, t1, inside(c.eval(t0 + (t1 - t0) / 2.0))));
|
||||
}
|
||||
}
|
||||
if pieces.iter().all(|&(_, _, _, kept)| kept) {
|
||||
if count > 0 {
|
||||
runs.push(sp.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Start after a piece left out, so that a run across a closed subpath's first anchor
|
||||
// stays one run.
|
||||
let start = if sp.closed { pieces.iter().position(|&(_, _, _, kept)| !kept).map_or(0, |k| k + 1) } else { 0 };
|
||||
let mut run: Vec<Anchor> = vec![];
|
||||
for j in 0..pieces.len() {
|
||||
let (k, t0, t1, kept) = pieces[(start + j) % pieces.len()];
|
||||
if kept {
|
||||
let (Some(&a), Some(&b)) = (sp.anchors.get(k), sp.anchors.get((k + 1) % sp.anchors.len())) else { continue };
|
||||
let c = sp.segment(k);
|
||||
let mut c = if t0 == 0.0 && t1 == 1.0 { c } else { c.subsegment(t0..t1) };
|
||||
// Remove roundoff at the cut endpoints without constraining the curve's handles.
|
||||
c.p0 = clamp(c.p0);
|
||||
c.p3 = clamp(c.p3);
|
||||
if sp.segment_is_line(k) {
|
||||
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
|
||||
}
|
||||
if let Some(last) = run.last_mut() {
|
||||
last.h_out = c.p1;
|
||||
} else {
|
||||
let a = if t0 == 0.0 { a } else { Anchor::corner(c.p0) };
|
||||
run.push(Anchor { p: c.p0, h_in: c.p0, h_out: c.p1, ..a });
|
||||
}
|
||||
let b = if t1 == 1.0 { b } else { Anchor::corner(c.p3) };
|
||||
run.push(Anchor { p: c.p3, h_in: c.p2, h_out: c.p3, ..b });
|
||||
} else if !run.is_empty() {
|
||||
runs.push(open_run(std::mem::take(&mut run)));
|
||||
}
|
||||
}
|
||||
if !run.is_empty() {
|
||||
runs.push(open_run(run));
|
||||
}
|
||||
}
|
||||
tp.path = PathData::new(runs);
|
||||
tp
|
||||
}
|
||||
|
||||
/// An open run of anchors: the last one has no handle out.
|
||||
fn open_run(mut run: Vec<Anchor>) -> SubPath {
|
||||
if let Some(last) = run.last_mut() {
|
||||
last.h_out = last.p;
|
||||
}
|
||||
SubPath::new(run, false)
|
||||
}
|
||||
|
||||
/// [`TraceStyles`]' variations made a part at a time.
|
||||
struct TraceParts {
|
||||
request: Request,
|
||||
image: Option<Decoded>,
|
||||
/// The trace of the style after those in `out`, once started.
|
||||
trace: Option<tr::TraceSteps>,
|
||||
/// The anchor points the styles not made yet may have.
|
||||
left: usize,
|
||||
out: Vec<Made>,
|
||||
/// The variations or an error have been given.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
impl Parts for TraceParts {
|
||||
/// After the variations or an error, each call gives `None`.
|
||||
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
|
||||
if self.ended {
|
||||
return Ok(None);
|
||||
}
|
||||
let part = self.next_part();
|
||||
self.ended = !matches!(part, Ok(None));
|
||||
part
|
||||
}
|
||||
|
||||
fn styles_done(&self) -> usize {
|
||||
self.out.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl TraceParts {
|
||||
fn next_part(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
|
||||
let Some(image) = &self.image else {
|
||||
checked(&self.request)?;
|
||||
self.image = Some(Decoded::new(&self.request)?);
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(style) = self.request.styles.get(self.out.len()) else { return Ok(Some(with_seams(std::mem::take(&mut self.out)))) };
|
||||
let trace = match &mut self.trace {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
|
||||
self.trace.insert(tr::TraceSteps::new(Arc::clone(&image.raster), params, self.left))
|
||||
}
|
||||
};
|
||||
let Some(res) = trace.step().map_err(trace_error)? else { return Ok(None) };
|
||||
self.trace = None;
|
||||
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
|
||||
self.left = self.left.saturating_sub(res.anchor_count());
|
||||
self.out.push(image.variation(style, ¶ms, res));
|
||||
if self.out.len() < self.request.styles.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(with_seams(std::mem::take(&mut self.out))))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -118,7 +118,7 @@ pub struct DocState {
|
||||
/// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not
|
||||
/// change it, and a batch that fails puts it back with the document.
|
||||
pub reverts: u64,
|
||||
/// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects
|
||||
/// Advances when Undo, Redo or a canceled undo group restores an older document snapshot. The same node ID can name different objects
|
||||
/// across that boundary.
|
||||
pub history_restores: u64,
|
||||
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
|
||||
|
||||
@@ -647,7 +647,7 @@ pub(crate) fn finish_recording_writes(succeeded: bool) -> Vec<String> {
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
pub(crate) fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
if path.is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ pub struct Interaction {
|
||||
/// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an
|
||||
/// interaction runs its commands inside it.
|
||||
pub(crate) tool: bool,
|
||||
/// A dialog's live preview began it: a command from outside the dialog runs as a step of its
|
||||
/// own under it, as it does under a drag, so the next preview, OK and Cancel keep its edit
|
||||
/// (a `file.*` command still runs inside it).
|
||||
pub dialog: bool,
|
||||
/// A tool began or joined this interaction through `Action::Begin`.
|
||||
pub(crate) tool_joined: bool,
|
||||
/// A replaced or canceled preview restores these new-art paints from before the interaction.
|
||||
@@ -100,6 +104,10 @@ pub(crate) struct HeldInteraction {
|
||||
/// The new-art paints when the command began: a change the command makes to them stays when
|
||||
/// the interaction's next preview or a cancel puts back the paints it began with.
|
||||
pub(crate) paint: vectorcraft_tools::PaintDefaults,
|
||||
/// The command's own selection steps went into the journal before it ran.
|
||||
pub(crate) journaled: bool,
|
||||
/// The command returned an error.
|
||||
pub(crate) refused: bool,
|
||||
}
|
||||
|
||||
/// The per-document state an interaction puts back when it is canceled, besides the document and
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod cmd;
|
||||
pub mod concept_vector;
|
||||
pub mod file_access;
|
||||
pub mod guard;
|
||||
pub mod inspect;
|
||||
@@ -58,6 +59,12 @@ pub use vectorcraft_tools as tools;
|
||||
pub use vectorcraft_doc::MAX_COORD;
|
||||
const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap");
|
||||
|
||||
pub struct ArtboardDeletionGuard {
|
||||
pub document: (u64, u64),
|
||||
pub artboard: u32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// The maximum number of newest swatch renames a session keeps until they are taken.
|
||||
pub(crate) const MAX_SWATCH_RENAMES: usize = 64;
|
||||
|
||||
@@ -67,6 +74,7 @@ pub struct Session {
|
||||
pub prefs: Prefs,
|
||||
/// Whether Caps Lock is on, as the desktop host reports it; never saved with the preferences.
|
||||
pub caps_lock: bool,
|
||||
pub artboard_deletion_guard: Option<ArtboardDeletionGuard>,
|
||||
/// Fill/stroke for new art (the toolbar proxy).
|
||||
pub paint: PaintDefaults,
|
||||
/// Which proxy is in front (true = Fill, false = Stroke) — the X key toggles.
|
||||
@@ -352,6 +360,9 @@ pub struct Session {
|
||||
/// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or
|
||||
/// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]).
|
||||
pub(crate) trace_hand_off: Option<cmd::Traced>,
|
||||
/// The Concept to Vector providers and the jobs made with them ([`cmd::conceptvector`]); not
|
||||
/// saved.
|
||||
pub(crate) concept: cmd::conceptvector::ConceptState,
|
||||
/// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or
|
||||
/// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]).
|
||||
pub(crate) retype_hand_off: Option<cmd::RetypeFound>,
|
||||
|
||||
@@ -98,6 +98,10 @@ pub struct ScriptDialog {
|
||||
/// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app
|
||||
/// gives an RGB pick back as CMYK. False for the other dialogs.
|
||||
pub cmyk_document: bool,
|
||||
/// `showColorPicker`: the RGB and CMYK profiles the run's active document is assigned (`None`:
|
||||
/// none) when the picker opens, which the app converts the pick through. `(None, None)` for the
|
||||
/// other dialogs.
|
||||
pub profiles: (Option<String>, Option<String>),
|
||||
}
|
||||
|
||||
/// The answer to a [`ScriptDialog`].
|
||||
@@ -705,7 +709,10 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
if preset.len() > MAX_PROMPT_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
|
||||
}
|
||||
wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false })
|
||||
wait_or_answer(
|
||||
host,
|
||||
ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false, profiles: (None, None) },
|
||||
)
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK,
|
||||
@@ -713,7 +720,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostError> {
|
||||
// During a slice the session holds the run's working copy, whose active document may be one
|
||||
// the script made; between slices the app sees the documents as they were before the run.
|
||||
let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk);
|
||||
let (cmyk_document, profiles) = host
|
||||
.session
|
||||
.borrow()
|
||||
.active()
|
||||
.map_or((false, (None, None)), |s| (s.doc.color_mode == crate::doc::ColorMode::Cmyk, crate::cmd::colormgmt::doc_profiles(&s.doc)));
|
||||
let dialog = ScriptDialog {
|
||||
kind: DialogKind::ColorPicker,
|
||||
message: String::new(),
|
||||
@@ -723,6 +734,7 @@ pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostE
|
||||
preset: String::new(),
|
||||
color: Some(color),
|
||||
cmyk_document,
|
||||
profiles,
|
||||
};
|
||||
wait_or_answer(host, dialog)
|
||||
}
|
||||
|
||||
@@ -123,7 +123,11 @@ pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS};
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS, REMOVE_ALL_VISITS};
|
||||
#[cfg(test)]
|
||||
pub(crate) use print::postscript_name;
|
||||
#[cfg(test)]
|
||||
pub(crate) use save_open::with_extension;
|
||||
|
||||
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
@@ -707,13 +707,19 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many objects [`items_remove_all`] walked on this thread, for the tests.
|
||||
pub(crate) static REMOVE_ALL_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or
|
||||
/// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it
|
||||
/// before anything is deleted, as `PageItems.removeAll()` does. A compound path's
|
||||
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
|
||||
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path
|
||||
/// or visible type that lays out glyphs to clip by.
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path,
|
||||
/// image, placed document or visible type that lays out glyphs to clip by.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
|
||||
@@ -727,9 +733,42 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect();
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
let mut next: Vec<_> = d.layers.iter().collect();
|
||||
// The document's list is checked against every object. A layer's or group's list is checked
|
||||
// against the container's subtree, or, when the container lies in the clipping path of a
|
||||
// clipping group above it, against the subtree of the highest such clipping path and the
|
||||
// group it clips; no other outline holds its paths. An empty list is not walked.
|
||||
let mut next: Vec<&Arc<crate::doc::Node>> = Vec::new();
|
||||
let mut nodes = Vec::new();
|
||||
if !ids.is_empty() {
|
||||
match c.and_then(|c| d.index_path(c)) {
|
||||
None => next.extend(d.layers.iter()),
|
||||
Some(at) => {
|
||||
// A damaged file can give two objects one id; a path that the id finds outside
|
||||
// the container would be deleted in place of the container's own.
|
||||
if let Some(id) = ids.iter().find(|i| d.index_path(**i).is_none_or(|p| p.len() != at.len() + 1 || !p.starts_with(&at))) {
|
||||
return Err(HostError::Error(format!("cannot delete PathItem {}: its id also names another object", id.0)));
|
||||
}
|
||||
let mut line: Vec<&Arc<crate::doc::Node>> = Vec::with_capacity(at.len());
|
||||
let mut kids = d.layers.as_slice();
|
||||
for &i in &at {
|
||||
let Some(n) = kids.get(i) else { break };
|
||||
line.push(n);
|
||||
kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
}
|
||||
// A clipping path is its group's first child, found by place, not by id.
|
||||
let clip = (1..line.len()).find(|&k| line[k - 1].clips() && at[k] == 0);
|
||||
if let Some(k) = clip {
|
||||
#[cfg(test)]
|
||||
REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1));
|
||||
nodes.push(line[k - 1]);
|
||||
}
|
||||
next.extend(line.get(clip.unwrap_or(line.len().saturating_sub(1))).copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
while let Some(n) = next.pop() {
|
||||
#[cfg(test)]
|
||||
REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1));
|
||||
nodes.push(n);
|
||||
next.extend(n.children().into_iter().flatten());
|
||||
}
|
||||
@@ -768,12 +807,15 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
{
|
||||
going.insert(n.id);
|
||||
}
|
||||
// A clip outline takes in visible paths and the glyphs of visible type, as
|
||||
// `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no
|
||||
// outline. A list marker is a glyph too, so whitespace-only type is laid out as well.
|
||||
// A clip outline takes in visible paths, the frames of visible images and placed
|
||||
// documents that enclose an area, and the glyphs of visible type, as `push_clip_shapes` does; type that lays
|
||||
// out no glyphs (blank, or overset) gives no outline. A list marker is a glyph too, so
|
||||
// whitespace-only type is laid out as well.
|
||||
let shape = n.visible
|
||||
&& match &n.kind {
|
||||
NodeKind::Path { .. } => true,
|
||||
// A frame collapsed to a line or a point encloses nothing to clip by.
|
||||
NodeKind::Image(_) | NodeKind::PlacedDocument(_) => n.clip_shapes(None).iter().any(|(frame, _)| encloses(frame)),
|
||||
NodeKind::Text(t) => {
|
||||
in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty()
|
||||
}
|
||||
@@ -785,10 +827,18 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if n.visible && ((shape && !going.contains(&n.id)) || inner) {
|
||||
geometry.insert(n.id);
|
||||
}
|
||||
// The live geometry effects of what stays in the clipping path reshape the region it
|
||||
// clips by, as the renderer draws it; deleting paths that lets an effect shrink the
|
||||
// region to nothing leaves no outline. A region that was empty before is left as it is.
|
||||
// The region is the area the outline fills under its fill rule, so outlines that run
|
||||
// opposite ways over the same area under nonzero fill nothing.
|
||||
let reshaped_empty = |m: &vectorcraft_doc::Node| {
|
||||
vectorcraft_render::effects::reshaped_clip_outline(m).is_some_and(|o| !o.is_some_and(|(bp, rule)| fills(&bp, rule)))
|
||||
};
|
||||
if n.clips()
|
||||
&& let Some(mask) = kids.first()
|
||||
&& affected.contains(&mask.id)
|
||||
&& !geometry.contains(&mask.id)
|
||||
&& (!geometry.contains(&mask.id) || (reshaped_empty(&without(mask, &going, &affected)) && !reshaped_empty(mask)))
|
||||
&& kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
&& masks.len() < 20
|
||||
{
|
||||
@@ -819,6 +869,57 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// Whether a subpath of `outline` encloses an area. Each subpath's area is measured from its first
|
||||
/// point, so its position does not change the result, and an area within roundoff of its own
|
||||
/// bounding box's is counted as none.
|
||||
fn encloses(outline: &kurbo::BezPath) -> bool {
|
||||
let mut subpaths: Vec<kurbo::BezPath> = Vec::new();
|
||||
for el in outline.elements() {
|
||||
if matches!(el, kurbo::PathEl::MoveTo(_)) || subpaths.is_empty() {
|
||||
subpaths.push(kurbo::BezPath::new());
|
||||
}
|
||||
if let Some(last) = subpaths.last_mut() {
|
||||
last.push(*el);
|
||||
}
|
||||
}
|
||||
subpaths.into_iter().any(|mut sub| {
|
||||
let Some(start) = sub.elements().iter().find_map(|e| e.end_point()) else { return false };
|
||||
sub.apply_affine(kurbo::Affine::translate(-start.to_vec2()));
|
||||
let area = kurbo::Shape::area(&sub).abs();
|
||||
area > 0.0 && area > 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area()
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `outline` fills an area under `rule`: a subpath encloses an area ([`encloses`]) and the
|
||||
/// outline with its overlaps resolved, thin strips included, has an area. An outline the path
|
||||
/// operations refuse is judged by [`encloses`] alone.
|
||||
fn fills(outline: &kurbo::BezPath, rule: vectorcraft_geom::FillRule) -> bool {
|
||||
if !encloses(outline) {
|
||||
return false;
|
||||
}
|
||||
match vectorcraft_pathops::try_area(&vectorcraft_geom::PathData::from_bezpath(outline), rule) {
|
||||
Ok(area) => area > 0.0,
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` without the members in `going`, at every depth. Only the members in `affected` (those that
|
||||
/// hold a member in `going`) are copied; the others are shared.
|
||||
fn without(
|
||||
n: &vectorcraft_doc::Node,
|
||||
going: &std::collections::HashSet<NodeId>,
|
||||
affected: &std::collections::HashSet<NodeId>,
|
||||
) -> vectorcraft_doc::Node {
|
||||
let mut m = n.clone();
|
||||
if let Some(kids) = m.children_mut() {
|
||||
kids.retain(|k| !going.contains(&k.id));
|
||||
for k in kids.iter_mut().filter(|k| affected.contains(&k.id)) {
|
||||
*k = Arc::new(without(k, going, affected));
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
|
||||
/// read it.
|
||||
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
|
||||
@@ -281,6 +281,7 @@ fn set_warning(h: &Host, on: bool) -> Answer {
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
profiles: (None, None),
|
||||
};
|
||||
if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) {
|
||||
return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into()));
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
//! - `print` with `jobOptions.file` writes a file, a `File` the script may write
|
||||
//! ([`super::super::files`]), and `printerName` does not apply. PostScript is written when the
|
||||
//! name ends with `.ps` or `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise.
|
||||
//! The PostScript is level 2 when `postScriptLevel` is not assigned, the default it reads as.
|
||||
//! - `print` without a file prepares a job for the printer `printerName` names, or for the
|
||||
//! system's default printer when it is empty or not assigned ([`super::super::printing`]): a
|
||||
//! print-ready PDF composed when `print` is called, which the run keeps until it ends. A name
|
||||
@@ -36,6 +37,7 @@
|
||||
//! - A property the help pages list that is not mapped accepts the default its help page gives
|
||||
//! and throws an error that says it is not available yet at any other value.
|
||||
//! - `fitToPage` set to true wins over the scale factors and the tiling mode.
|
||||
//! With no scale or tiling assigned, false clears a base fit mode and preserves other base scaling modes.
|
||||
//! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range
|
||||
//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange`
|
||||
//! replaces the range of the settings `print` starts from, which prints when those settings
|
||||
@@ -46,6 +48,9 @@
|
||||
//! with another extension.
|
||||
//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps its value in the
|
||||
//! settings `print` starts from.
|
||||
//! - `bitmapResolution` is `file.print`'s `advanced.bitmapResolution`: 0 prints at the document's
|
||||
//! raster effects resolution, and 1 to 9600 ppi at that resolution; `print` throws, before
|
||||
//! anything is written, for a value between 0 and 1.
|
||||
//! - `print` throws, before anything is written, when an assigned `artboardRange` names an artboard
|
||||
//! the document does not have, also with `printAllArtboards` true; when `printPreset` or
|
||||
//! `flattenerPreset` is not the name of a preset (any case); when `colorManagementOptions.name` is
|
||||
@@ -54,6 +59,7 @@
|
||||
//! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces,
|
||||
//! or that holds `/`, `\` or a control character (also at either end), throws too. Each checked
|
||||
//! name goes to `file.print` without the spaces around it. `PPDName` takes only the empty string.
|
||||
//! Paper `width` and `height` take 0 (not assigned) or 72 to 14,400 pt.
|
||||
//! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects.
|
||||
//! - `app.printerList` lists the printers the frontend listed for the run as `Printer` objects,
|
||||
//! whose `name` is read-only and whose `printerInfo` is not available yet. It throws with no
|
||||
@@ -150,8 +156,8 @@ const PDF_OVERPRINT: &[&str] = &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"];
|
||||
const POSTSCRIPT_IMAGE_COMPRESSION: &[&str] = &["IMAGECOMPRESSIONNONE", "JPEG", "RLE"];
|
||||
const POSTSCRIPT_LEVEL: &[&str] = &["PSLEVEL1", "PSLEVEL2", "PSLEVEL3"];
|
||||
|
||||
/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` comes from
|
||||
/// [`super::save_open::ENUMS`].
|
||||
/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` and `PageMarksTypes`
|
||||
/// come from [`super::save_open::ENUMS`].
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("PrintColorProfile", PRINT_COLOR_PROFILE),
|
||||
("PrintColorIntent", PRINT_COLOR_INTENT),
|
||||
@@ -163,7 +169,6 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("PrintingBounds", PRINTING_BOUNDS),
|
||||
("PrintFontDownloadMode", PRINT_FONT_DOWNLOAD_MODE),
|
||||
("FontSubstitutionPolicy", FONT_SUBSTITUTION_POLICY),
|
||||
("PageMarksTypes", PAGE_MARKS_TYPES),
|
||||
("PostScriptImageCompressionType", POSTSCRIPT_IMAGE_COMPRESSION),
|
||||
("PrinterPostScriptLevelEnum", POSTSCRIPT_LEVEL),
|
||||
];
|
||||
@@ -176,6 +181,8 @@ enum Kind {
|
||||
Number(f64, f64),
|
||||
/// A whole number from the first to the second.
|
||||
Whole(u64, u64),
|
||||
/// A paper side in points: 0 (not assigned) or a custom size from 72 to 14,400.
|
||||
PaperSize,
|
||||
Text,
|
||||
/// A value of the enumeration (its name and members); only the members in the last list are
|
||||
/// available.
|
||||
@@ -209,7 +216,7 @@ impl Start {
|
||||
|
||||
fn matches(self, kind: Kind, d: &Data) -> bool {
|
||||
match (self, d) {
|
||||
(Start::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9,
|
||||
(Start::Num(a), Data::Number(b)) => a == *b,
|
||||
(Start::None, _) => false,
|
||||
_ => self.value(kind) == *d,
|
||||
}
|
||||
@@ -264,7 +271,7 @@ const JOB: Class = Class {
|
||||
name: "PrintJobOptions",
|
||||
fields: &[
|
||||
f("artboardRange", Kind::Text, Start::Text("1-")),
|
||||
kept("bitmapResolution", Kind::Number(0.0, f64::MAX), Start::Num(0.0)),
|
||||
f("bitmapResolution", Kind::Number(0.0, vectorcraft_pdf::MAX_BITMAP_RESOLUTION), Start::Num(0.0)),
|
||||
f("collate", Kind::Bool, Start::Bool(false)),
|
||||
f("copies", Kind::Whole(1, 999), Start::Num(1.0)),
|
||||
f(
|
||||
@@ -355,14 +362,18 @@ const MARKS: Class = Class {
|
||||
const PAPER: Class = Class {
|
||||
name: "PrintPaperOptions",
|
||||
fields: &[
|
||||
f("height", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("height", Kind::PaperSize, Start::Num(0.0)),
|
||||
f("name", Kind::Text, Start::None),
|
||||
kept("offset", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("transverse", Kind::Bool, Start::Bool(false)),
|
||||
f("width", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("width", Kind::PaperSize, Start::Num(0.0)),
|
||||
],
|
||||
};
|
||||
|
||||
/// The custom paper sizes `file.print` takes, in points.
|
||||
const MIN_PAPER: f64 = 72.0;
|
||||
const MAX_PAPER: f64 = 14_400.0;
|
||||
|
||||
const POSTSCRIPT: Class = Class {
|
||||
name: "PrintPostScriptOptions",
|
||||
fields: &[
|
||||
@@ -440,6 +451,14 @@ fn checked(h: &Host, class: &Class, field: &Field, d: &Data) -> std::result::Res
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
},
|
||||
Kind::PaperSize => match d {
|
||||
Data::Number(n) if n.is_finite() => {
|
||||
if *n != 0.0 && !(MIN_PAPER..=MAX_PAPER).contains(n) {
|
||||
return Err(HostError::Range(format!("{what} must be 0 or from {MIN_PAPER} to {MAX_PAPER}")));
|
||||
}
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
},
|
||||
Kind::Whole(lo, hi) => match d {
|
||||
Data::Number(n) => {
|
||||
if !whole(*n).is_some_and(|n| (lo..=hi).contains(&n)) {
|
||||
@@ -529,6 +548,7 @@ fn property(link: &Link, class: usize, field: usize) -> HostMember {
|
||||
/// What a `PrintOptions` asks `file.print` for.
|
||||
#[derive(Default)]
|
||||
struct Job {
|
||||
clear_fit: bool,
|
||||
preset: Option<String>,
|
||||
file: Option<Data>,
|
||||
/// The assigned `printerName`.
|
||||
@@ -545,10 +565,12 @@ struct Job {
|
||||
paper_size: bool,
|
||||
/// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says.
|
||||
source: bool,
|
||||
/// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` must name the profile.
|
||||
/// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` or the base settings must name the profile.
|
||||
custom: bool,
|
||||
/// `printArea` is assigned: the artboards print even when the base settings ignore them.
|
||||
print_area: bool,
|
||||
/// `position` is assigned: an untiled job does not use the saved Print Tiling origin.
|
||||
position: bool,
|
||||
/// The groups of `settings`: the top level and each nested object by its key.
|
||||
top: Map<String, Value>,
|
||||
groups: Vec<(&'static str, Map<String, Value>)>,
|
||||
@@ -675,6 +697,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) {
|
||||
"printAsBitmap" => {
|
||||
job.group("advanced").insert("printAsBitmap".into(), json!(flag(v)));
|
||||
}
|
||||
"bitmapResolution" => {
|
||||
job.group("advanced").insert("bitmapResolution".into(), json!(number_of(v)));
|
||||
}
|
||||
"file" => job.file = Some(v.clone()),
|
||||
"artboardRange" => {
|
||||
job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty());
|
||||
@@ -683,6 +708,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) {
|
||||
if let Some(range) = job.range.as_ref().filter(|_| value("printAllArtboards").is_none()) {
|
||||
s.insert("range".into(), json!(range));
|
||||
}
|
||||
if job.range.is_none() && value("printAllArtboards").is_none() {
|
||||
s.insert("artboards".into(), json!("all"));
|
||||
}
|
||||
}
|
||||
"printArea" => job.print_area = true,
|
||||
_ => {}
|
||||
@@ -756,11 +784,12 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(
|
||||
Some(t)
|
||||
} else if scaled {
|
||||
Some("custom")
|
||||
} else if fit.is_some() || tiling.is_some() {
|
||||
} else if tiling.is_some() {
|
||||
Some("none")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
job.clear_fit = fit == Some(false) && scaling.is_none();
|
||||
if let Some(scaling) = scaling {
|
||||
job.top.insert("scaling".into(), json!(scaling));
|
||||
}
|
||||
@@ -809,6 +838,7 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(
|
||||
_ => "center",
|
||||
};
|
||||
job.group("placement").insert("origin".into(), json!(origin));
|
||||
job.position = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -874,6 +904,10 @@ fn map_postscript(h: &Host, slot: usize, job: &mut Job) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn postscript_name(path: &str, windows: bool) -> bool {
|
||||
super::save_open::filename_for_suffix(path, windows).to_lowercase().ends_with(".ps")
|
||||
}
|
||||
|
||||
/// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names,
|
||||
/// with the assigned options over the document's print settings, or without a file the job for a
|
||||
/// printer ([`prepare`]).
|
||||
@@ -890,11 +924,15 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some(file) = job.file.take() else { return prepare(h, doc, job) };
|
||||
check_names(h, doc, &mut job)?;
|
||||
let path = file_path(&file, "print")?;
|
||||
// The format follows the name `jobOptions.file` gives, not the real path a link leads to.
|
||||
let postscript = job.level.is_some() || postscript_name(path, cfg!(windows));
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
let mut p = print_params(&mut job);
|
||||
// The format follows the name `jobOptions.file` gives, not the real path a link leads to.
|
||||
let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps";
|
||||
p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" }));
|
||||
// PostScript prints at the level the options read as: an unassigned `postScriptLevel` is `PSLEVEL2`.
|
||||
if postscript {
|
||||
p.insert("level".into(), json!(job.level.unwrap_or(2)));
|
||||
}
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command(h, PRINT, &Value::Object(p)))))?;
|
||||
// What the job lost or how its options apply: one Script Console line each.
|
||||
@@ -997,21 +1035,38 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
|
||||
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`.
|
||||
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
|
||||
let (count, saved_ignore) = with_doc(h, doc, |_, st| {
|
||||
let (count, saved_ignore, saved_fit, saved_tiled, mut base_profile) = with_doc(h, doc, |_, st| {
|
||||
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
|
||||
(st.doc.artboards.len(), mode == Some("ignore"))
|
||||
let scaling = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str);
|
||||
let profile = st.doc.print_setup.as_ref().and_then(|v| v.get("color")).and_then(|v| v.get("profile")).and_then(Value::as_str);
|
||||
let tiled = matches!(scaling, Some("tileFull" | "tileImageable"));
|
||||
(st.doc.artboards.len(), mode == Some("ignore"), scaling == Some("fit"), tiled, profile.unwrap_or("").to_string())
|
||||
});
|
||||
if let Some(range) = &job.range {
|
||||
vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut base_ignore = saved_ignore;
|
||||
let mut base_fit = saved_fit;
|
||||
let mut base_tiled = saved_tiled;
|
||||
if let Some(name) = job.preset.take() {
|
||||
let n = plain_name("PrintOptions.printPreset", "print preset", &name)?;
|
||||
let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?;
|
||||
base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore);
|
||||
base_fit = matches!(preset.scaling, vectorcraft_pdf::PrintScaling::Fit);
|
||||
base_tiled = preset.scaling.tiles();
|
||||
base_profile.clone_from(&preset.color.profile);
|
||||
job.preset = Some(n.to_string());
|
||||
}
|
||||
if job.clear_fit && base_fit {
|
||||
job.top.insert("scaling".into(), json!("none"));
|
||||
}
|
||||
// A placed Print Tiling origin replaces the placement, so an assigned `position` clears it
|
||||
// for this job when the job does not tile; the saved settings keep it.
|
||||
let tiled = job.top.get("scaling").and_then(Value::as_str).map_or(base_tiled, |s| matches!(s, "tileFull" | "tileImageable"));
|
||||
if job.position && !tiled {
|
||||
job.group("tileOrigin").insert("placed".into(), json!(false));
|
||||
}
|
||||
// An assigned `printArea` prints by artboard when the base settings ignore the artboards: the
|
||||
// assigned `artboardRange` when there is one, otherwise every artboard.
|
||||
if job.print_area && base_ignore && !job.top.contains_key("artboards") {
|
||||
@@ -1025,9 +1080,6 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
}
|
||||
job.group("advanced").insert("flattenerPreset".into(), json!(n));
|
||||
}
|
||||
if job.custom && job.profile.is_none() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.profile.take() {
|
||||
let what = "PrintColorManagementOptions.name";
|
||||
let n = plain_name(what, "color profile", &name)?;
|
||||
@@ -1039,6 +1091,8 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
if !job.source {
|
||||
job.group("color").insert("profile".into(), json!(profile.name));
|
||||
}
|
||||
} else if job.custom && base_profile.trim().is_empty() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.paper.take() {
|
||||
let n = plain_name("PrintPaperOptions.name", "paper", &name)?;
|
||||
@@ -1155,10 +1209,16 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
fn field_info(field: &Field) -> MemberInfo {
|
||||
match field.kind {
|
||||
Kind::Bool => typed("boolean"),
|
||||
// A field with no upper limit, such as `bitmapResolution`, reports no maximum.
|
||||
// A field with no upper limit reports no maximum.
|
||||
Kind::Number(min, max) => MemberInfo { min: Some(min), max: (max < f64::MAX).then_some(max), ..typed("number") },
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
Kind::Whole(min, max) => MemberInfo { min: Some(min as f64), max: Some(max as f64), ..typed("number") },
|
||||
Kind::PaperSize => MemberInfo {
|
||||
min: Some(0.0),
|
||||
max: Some(MAX_PAPER),
|
||||
description: Some(format!("0 (not assigned) or a custom size from {MIN_PAPER} to {MAX_PAPER} pt")),
|
||||
..typed("number")
|
||||
},
|
||||
Kind::Text => typed("string"),
|
||||
Kind::Choice(name, _, _) | Kind::Child(name) => typed(name),
|
||||
Kind::File => typed("File"),
|
||||
|
||||
@@ -67,6 +67,7 @@
|
||||
//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files.
|
||||
//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte.
|
||||
//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error.
|
||||
//! - Each method sends command warnings to the Script Console with its name as the prefix.
|
||||
//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The
|
||||
//! commands a script runs never show a dialog, so the level does not change what they do, and it
|
||||
//! never allows a file the script's grants do not.
|
||||
@@ -919,7 +920,7 @@ pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) {
|
||||
/// a linked image an open could not read. → the command's answer.
|
||||
fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
|
||||
let (answer, value) = super::super::command_value(h, id, p)?;
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().take(super::MAX_LISTED).filter_map(Value::as_str) {
|
||||
super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
|
||||
}
|
||||
Ok(answer)
|
||||
@@ -963,8 +964,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
let given_options = given(arg(a, 2));
|
||||
// Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options
|
||||
// object of that format's class holds.
|
||||
let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase());
|
||||
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c));
|
||||
let named_format = save_format_for_name(path, cfg!(windows)).map(|f| f.id);
|
||||
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == named_format).map(|(c, _)| fresh(c));
|
||||
if let Some(o) = given_options.or(by_extension.as_ref()) {
|
||||
let name = typename(o);
|
||||
let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else {
|
||||
@@ -982,20 +983,38 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
} else if !q.is_empty() {
|
||||
p.insert("options".into(), Value::Object(q));
|
||||
}
|
||||
} else {
|
||||
let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id);
|
||||
}
|
||||
// Without options, the format of the file name as the platform reads it (on Windows, without
|
||||
// trailing dots and spaces), else the document's own.
|
||||
if !p.contains_key("format") {
|
||||
let format = named_format.unwrap_or_else(|| super::with_doc(h, doc, |_, st| st.format));
|
||||
p.insert("format".into(), json!(format));
|
||||
}
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.saveAs", "file.saveAs", &Value::Object(p))))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `path` with the extension of `kind` added, unless its name already ends with one of them.
|
||||
fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String {
|
||||
let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions };
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase();
|
||||
fn save_format_for_name(path: &str, windows: bool) -> Option<&'static crate::cmd::fileio::Format> {
|
||||
let name = filename_for_suffix(path, windows);
|
||||
// A name that is only a dot and an extension, such as `.pdf`, picks its format only for the
|
||||
// `.ai`, `.eps` and `.pdf` options classes; any other name takes the usual extension rule.
|
||||
match name.rsplit_once('.') {
|
||||
Some(("", extension)) if SAVE_CLASSES.iter().any(|(_, f)| extension.eq_ignore_ascii_case(f)) => {
|
||||
crate::cmd::fileio::format_for_name(&format!("x.{extension}"))
|
||||
}
|
||||
_ => crate::cmd::fileio::format_for_name(name),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn filename_for_suffix(path: &str, windows: bool) -> &str {
|
||||
let name = if windows { path.rsplit(['/', '\\']).next() } else { path.rsplit('/').next() }.unwrap_or(path);
|
||||
if windows { name.trim_end_matches(['.', ' ']) } else { name }
|
||||
}
|
||||
|
||||
pub(crate) fn with_extension(path: &str, extensions: &[&str], windows: bool) -> String {
|
||||
let name = filename_for_suffix(path, windows).to_lowercase();
|
||||
match extensions.first() {
|
||||
Some(first) if !extensions.iter().any(|e| name.ends_with(&format!(".{e}"))) => format!("{path}.{first}"),
|
||||
_ => path.to_string(),
|
||||
@@ -1058,10 +1077,10 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
} else {
|
||||
p.insert("useArtboards".into(), json!(false));
|
||||
}
|
||||
let named = with_extension(path, &kind, svgz);
|
||||
let named = with_extension(path, if svgz { &["svgz"] } else { kind.extensions }, cfg!(windows));
|
||||
let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?;
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.exportFile", "document.export", &Value::Object(p))))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1110,9 +1129,19 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
// The command opens the given path; a real path that is not valid UTF-8 is still refused.
|
||||
let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
|
||||
// The document's size is read before any of it is; a placed image keeps its own limit and message.
|
||||
if std::fs::metadata(&real).is_ok_and(|m| m.len() > super::super::files::MAX_OPEN_BYTES) {
|
||||
return Err(refused(super::super::files::OPEN_TOO_LARGE, path));
|
||||
}
|
||||
plain(real)?;
|
||||
p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?));
|
||||
let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?;
|
||||
let r = crate::cmd::fileio::with_read_limit(super::super::files::MAX_OPEN_BYTES as usize, || {
|
||||
exactly(h, || warned(h, "app.open", "document.open", &Value::Object(p)))
|
||||
})
|
||||
.map_err(|e| match e {
|
||||
HostError::Error(message) if message == crate::cmd::fileio::READ_TOO_LARGE => refused(super::super::files::OPEN_TOO_LARGE, path),
|
||||
e => e,
|
||||
})?;
|
||||
let index = match &r {
|
||||
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
|
||||
("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()),
|
||||
@@ -1283,7 +1312,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer {
|
||||
let name = super::with_doc(h, doc, |_, st| st.title());
|
||||
let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?;
|
||||
let p = json!({"path": plain(real)?, "format": format});
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.close", "file.saveAs", &p)))?;
|
||||
}
|
||||
_ => return Err(HostError::Error(UNSAVED_CHANGES.into())),
|
||||
}
|
||||
@@ -1340,3 +1369,37 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
.chain(screens::classes(link))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod save_format_tests {
|
||||
use super::save_format_for_name;
|
||||
|
||||
#[test]
|
||||
fn save_as_selects_the_format_from_windows_filename_aliases() {
|
||||
for extension in ["svg", "svgz", "ai", "eps", "pdf"] {
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase());
|
||||
assert_eq!(save_format_for_name(&name, true).map(|f| f.id), Some(extension), "{name}");
|
||||
assert!(save_format_for_name(&name, false).is_none(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in ["drawing", "drawing. . ", "drawing.svg\t", "drawing.svg\u{a0}", "folder.svg/drawing", "folder.svg\\drawing"] {
|
||||
assert!(save_format_for_name(name, true).is_none(), "{name}");
|
||||
}
|
||||
// Production passes `cfg!(windows)`; a Windows host still splits this name at the backslash.
|
||||
#[cfg(unix)]
|
||||
assert_eq!(save_format_for_name("proof\\.svg", false).map(|f| f.id), Some("svg"));
|
||||
#[cfg(windows)]
|
||||
assert!(save_format_for_name("proof\\.svg", false).is_none());
|
||||
for windows in [false, true] {
|
||||
assert_eq!(save_format_for_name(".pdf", windows).map(|f| f.id), Some("pdf"));
|
||||
assert!(save_format_for_name(".svg", windows).is_none());
|
||||
assert!(save_format_for_name("/exports/.png", windows).is_none());
|
||||
assert_eq!(save_format_for_name("/exports/.eps", windows).map(|f| f.id), Some("eps"));
|
||||
assert_eq!(save_format_for_name("drawing.svg", windows).map(|f| f.id), Some("svg"));
|
||||
assert_eq!(save_format_for_name("drawing.svgz", windows).map(|f| f.id), Some("svgz"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -478,7 +478,7 @@ fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer {
|
||||
for items in exports {
|
||||
let mut p = base.clone();
|
||||
p.extend(items);
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
|
||||
@@ -108,6 +108,9 @@ pub const MAX_MASK_STEPS: usize = 1 << 24;
|
||||
|
||||
pub(crate) const ACCESS_DENIED: &str = "Script file access denied";
|
||||
pub(crate) const TOO_LARGE: &str = "Script file exceeds 8 MiB";
|
||||
/// The largest document `app.open` reads, checked before the file is read.
|
||||
pub(crate) const MAX_OPEN_BYTES: u64 = 256 << 20;
|
||||
pub(crate) const OPEN_TOO_LARGE: &str = "Script document exceeds 256 MiB";
|
||||
pub(crate) const NOT_OPEN: &str = "Script file is not open";
|
||||
pub(crate) const UNDECODABLE: &str = "Script file cannot be decoded";
|
||||
pub(crate) const NOT_REGULAR: &str = "Script file is not a regular file";
|
||||
@@ -750,7 +753,7 @@ impl Disk {
|
||||
Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED),
|
||||
Err(ScriptRead::Failed(_)) => return Err(READ_FAILED),
|
||||
};
|
||||
if !real.is_file() {
|
||||
if !std::fs::metadata(&real).map_err(|_| READ_FAILED)?.is_file() {
|
||||
return Err(NOT_REGULAR);
|
||||
}
|
||||
Ok(real)
|
||||
|
||||
@@ -501,6 +501,9 @@ struct World {
|
||||
pending_paint: Option<crate::Paint>,
|
||||
choices: Choices,
|
||||
journal: Journal,
|
||||
/// The Concept to Vector jobs, and the number of the first job made after the run started.
|
||||
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
|
||||
concept_from: u64,
|
||||
/// The preferences when the run started.
|
||||
start_prefs: crate::Prefs,
|
||||
/// The Caps Lock state when the run started.
|
||||
@@ -631,6 +634,8 @@ impl World {
|
||||
pending_paint: s.pending_paint.clone(),
|
||||
choices: Choices::of(s),
|
||||
journal: Journal::default(),
|
||||
concept_jobs: s.concept_jobs_snapshot(),
|
||||
concept_from: s.next_concept_job(),
|
||||
start_prefs: s.prefs.clone(),
|
||||
start_caps_lock: s.caps_lock,
|
||||
}
|
||||
@@ -655,6 +660,7 @@ impl World {
|
||||
swap(&mut self.pending_paint, &mut s.pending_paint);
|
||||
self.choices.swap(s);
|
||||
swap(&mut self.journal, &mut s.journal);
|
||||
s.swap_concept_jobs(&mut self.concept_jobs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -696,6 +702,7 @@ pub(crate) struct Savepoint {
|
||||
pending_paint: Option<crate::Paint>,
|
||||
choices: Choices,
|
||||
journal: usize,
|
||||
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
|
||||
/// The plug-in events queued before the command ([`Session::plugin_events_mark`]).
|
||||
plugin_events: u64,
|
||||
}
|
||||
@@ -732,6 +739,7 @@ impl Savepoint {
|
||||
pending_paint: s.pending_paint.clone(),
|
||||
choices: Choices::of(s),
|
||||
journal: s.journal.len(),
|
||||
concept_jobs: s.concept_jobs_snapshot(),
|
||||
plugin_events: s.plugin_events_mark(),
|
||||
}
|
||||
}
|
||||
@@ -787,6 +795,7 @@ impl Savepoint {
|
||||
s.pending_paint = self.pending_paint;
|
||||
self.choices.put(s);
|
||||
s.journal.truncate(self.journal);
|
||||
s.restore_concept_jobs(self.concept_jobs);
|
||||
// The documents the command opened are closed again: plug-ins are not told of them.
|
||||
s.forget_plugin_opens_since(self.plugin_events);
|
||||
s.sync_front_profiles();
|
||||
@@ -2842,6 +2851,9 @@ impl Session {
|
||||
for st in start.iter().filter(|b| !job.start_uids.contains(&b.uid)) {
|
||||
self.docs.push(st.clone());
|
||||
}
|
||||
// So do the Concept to Vector jobs the app made while the run went on.
|
||||
let others = std::mem::take(&mut job.world.concept_jobs);
|
||||
self.merge_concept_jobs(others, job.world.concept_from);
|
||||
// A document the script closed is gone now, with its recovery copy.
|
||||
for b in start.iter().filter(|b| job.start_uids.contains(&b.uid) && !self.docs.iter().any(|d| d.uid == b.uid)) {
|
||||
cmd::recovery::forget_closed(self, b);
|
||||
|
||||
@@ -51,6 +51,7 @@ impl Session {
|
||||
active: None,
|
||||
prefs: Prefs::default(),
|
||||
caps_lock: false,
|
||||
artboard_deletion_guard: None,
|
||||
paint: PaintDefaults::default(),
|
||||
fill_active: true,
|
||||
clipboard: Clipboard::default(),
|
||||
@@ -149,6 +150,7 @@ impl Session {
|
||||
place_queue_loads: 0,
|
||||
image_hand_off: None,
|
||||
trace_hand_off: None,
|
||||
concept: Default::default(),
|
||||
retype_hand_off: None,
|
||||
place_cursor_requests: false,
|
||||
package_hand_off: None,
|
||||
@@ -567,6 +569,10 @@ impl Session {
|
||||
// Closed (saved or discarded): nothing left to recover.
|
||||
let uid = self.docs[index].uid;
|
||||
cmd::recovery::forget(self, uid);
|
||||
// In a batch, the jobs are dropped when the batch ends without an error.
|
||||
if self.batch_stash.is_none() {
|
||||
self.forget_concept_jobs(uid);
|
||||
}
|
||||
let old = self.docs.remove(index);
|
||||
if let Some(stash) = &mut self.batch_stash {
|
||||
stash.push(old);
|
||||
|
||||
@@ -343,19 +343,26 @@ impl Session {
|
||||
/// it updates Recent Colors and converts or remaps the new-art paints at once, as it does with
|
||||
/// no drag in progress.
|
||||
///
|
||||
/// The interaction stays as it is, and the command runs inside it, for an interaction a dialog
|
||||
/// or a panel began (it builds its preview from commands), for typing in progress
|
||||
/// A dialog's live preview ([`crate::Interaction::dialog`]) is set aside the same way, except
|
||||
/// for a command that acts on the drawing on show ([`reads_preview`]). Outside commands use
|
||||
/// the shown selection with objects absent from the base document removed, and without a path
|
||||
/// whose selected anchors the preview renumbered. A selection of only preview objects becomes
|
||||
/// empty. The journal records that selection before the command, and records the dialog's
|
||||
/// own selection again when the command is refused. The interaction stays as it is, and the command runs
|
||||
/// inside it, for an interaction a panel or
|
||||
/// another dialog began (it builds its preview from commands), for typing in progress
|
||||
/// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside
|
||||
/// it ends the path it draws), and for a copy made with `object.transform` during a drag that
|
||||
/// copies (it copies the document as the drag's move left it). A command that settles,
|
||||
/// commits or cancels the interaction, or that hands the active tool actions to apply, gets it
|
||||
/// back first ([`Session::put_back_interaction`]), as it found it.
|
||||
pub(crate) fn outside_interaction(&mut self, id: &str, params: &Value, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
if cmd::typing_in_progress(self) || self.tool_id() == vectorcraft_tools::quickpen::ID {
|
||||
let dialog = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.dialog);
|
||||
if cmd::typing_in_progress(self) || (!dialog && self.tool_id() == vectorcraft_tools::quickpen::ID) {
|
||||
return f(self);
|
||||
}
|
||||
let Some(st) = self.active_mut() else { return f(self) };
|
||||
let Some(it) = st.interaction.as_ref().filter(|it| it.tool) else { return f(self) };
|
||||
let Some(it) = st.interaction.as_ref().filter(|it| it.tool || (it.dialog && !reads_preview(id))) else { return f(self) };
|
||||
// A drag that copies: its latest preview, applied or held back by Real-time Drawing off, copies.
|
||||
let copying = it.preview.as_ref().is_some_and(|(c, p)| c == "object.transform" && p.get("copy").and_then(Value::as_bool) == Some(true));
|
||||
if copying && id == "object.transform" && params.get("copy").and_then(Value::as_bool) == Some(true) {
|
||||
@@ -367,36 +374,57 @@ impl Session {
|
||||
let shown = previewed.then(|| (st.doc.clone(), st.selection.clone()));
|
||||
if previewed {
|
||||
st.doc = interaction.doc.clone();
|
||||
st.selection.clone_from(&interaction.selection);
|
||||
if let Some((shown_doc, _)) = shown.as_ref().filter(|_| interaction.dialog) {
|
||||
shown_base_selection(&mut st.selection, shown_doc, &st.doc);
|
||||
} else {
|
||||
st.selection.clone_from(&interaction.selection);
|
||||
}
|
||||
st.revision += 1;
|
||||
cmd::globaledit::follow_history(st);
|
||||
}
|
||||
// The journal holds the dialog's base selection, so the command replays on the one it acts on.
|
||||
let reselect = (interaction.dialog && st.selection != *interaction.selection)
|
||||
.then(|| selection_steps(&st.selection, &interaction.selection, &st.doc, st.active_layer, &st.highlighted_rows()));
|
||||
let (uid, state) = (st.uid, crate::interaction::ViewState::of(st));
|
||||
let paint = self.paint.clone();
|
||||
self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint });
|
||||
let journaled = reselect.is_some();
|
||||
if let Some(steps) = reselect {
|
||||
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
|
||||
for step in steps {
|
||||
self.journal.push(step);
|
||||
}
|
||||
self.journal_in_undo_groups(Some(uid), &grouped, from);
|
||||
}
|
||||
self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint, journaled, refused: false });
|
||||
if previewed {
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
let r = f(self);
|
||||
if let Some(held) = self.held_interaction.as_mut().filter(|_| r.is_err()) {
|
||||
held.refused = true;
|
||||
}
|
||||
self.put_back_interaction();
|
||||
r
|
||||
}
|
||||
|
||||
/// Put back the interaction [`Session::outside_interaction`] set aside. When the command left
|
||||
/// the document and the selection as it found them, the preview on show before it is on show
|
||||
/// again. Otherwise the interaction starts from the document the command left and from its
|
||||
/// own selection, without the objects the command removed, hid or locked, and the preview that Real-time
|
||||
/// Drawing showed is applied to it again. The warning or the error of that preview goes to
|
||||
/// again. Otherwise a tool drag starts from the document the command left and from its own
|
||||
/// selection, without the objects the command removed, hid or locked. The preview that
|
||||
/// Real-time Drawing showed is applied to it again. The warning or the error of that preview goes to
|
||||
/// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the
|
||||
/// interaction with nothing to commit. An interaction whose document the command closed ends,
|
||||
/// and so does one with anchors or segments selected on a path the command changed in more
|
||||
/// than a move. A document
|
||||
/// the command left an interaction of its own on keeps that one.
|
||||
/// than a move. A document the command left an interaction of its own on keeps that one.
|
||||
/// A dialog adopts the command's selection and paints and reruns its preview on its next pass.
|
||||
pub(crate) fn put_back_interaction(&mut self) {
|
||||
let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return };
|
||||
let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint, journaled, refused }) = self.held_interaction.take() else {
|
||||
return;
|
||||
};
|
||||
// A selection command loaded the paints of the selection it made into the fill and stroke
|
||||
// proxies. The drag goes on with its own selection, so they show its paints again.
|
||||
if self.paint != paint
|
||||
if !it.dialog
|
||||
&& self.paint != paint
|
||||
&& let Some(st) = self.active_mut().filter(|d| d.uid == uid && d.interaction.is_none())
|
||||
{
|
||||
let own = drag_selection(&it.selection, &st.doc);
|
||||
@@ -414,7 +442,7 @@ impl Session {
|
||||
// parts it left alone keep the interaction's. The pattern lists every field, so a field
|
||||
// added to `PaintDefaults` does not compile until it is handled here. The paints a preview
|
||||
// took its new-art paints over from take the change as well.
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint;
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, style_doc, inherited } = &self.paint;
|
||||
for start in std::iter::once(&mut it.paint).chain(it.inherited_preview_paint.as_mut()) {
|
||||
if *fill != paint.fill {
|
||||
start.fill.clone_from(fill);
|
||||
@@ -434,8 +462,9 @@ impl Session {
|
||||
if *blend != paint.blend {
|
||||
start.blend = *blend;
|
||||
}
|
||||
if *style != paint.style {
|
||||
if *style != paint.style || *style_doc != paint.style_doc {
|
||||
start.style.clone_from(style);
|
||||
start.style_doc = *style_doc;
|
||||
}
|
||||
if *inherited != paint.inherited {
|
||||
start.inherited = *inherited;
|
||||
@@ -450,7 +479,19 @@ impl Session {
|
||||
// isolation stays when the interaction is canceled.
|
||||
state.rebase(crate::interaction::ViewState::of(st), &mut it);
|
||||
let previewed = shown.is_some();
|
||||
if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == *it.selection {
|
||||
// A refused command leaves the selection it was given: a dialog's is the one on show without
|
||||
// preview objects. A command that ran (Deselect) and left that selection keeps it.
|
||||
let given = match shown.as_ref().filter(|_| it.dialog && refused) {
|
||||
Some((shown_doc, selection)) => {
|
||||
let mut given = selection.clone();
|
||||
shown_base_selection(&mut given, shown_doc, &it.doc);
|
||||
given
|
||||
}
|
||||
None => (*it.selection).clone(),
|
||||
};
|
||||
if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == given {
|
||||
// The journal goes back to the dialog's base selection, as the preview on show again holds it.
|
||||
let back = (journaled && active).then(|| selection_steps(&it.selection, &given, &st.doc, st.active_layer, &st.highlighted_rows()));
|
||||
if let Some((doc, selection)) = shown {
|
||||
st.doc = doc;
|
||||
st.selection = selection;
|
||||
@@ -458,6 +499,13 @@ impl Session {
|
||||
cmd::globaledit::follow_history(st);
|
||||
}
|
||||
st.interaction = Some(it);
|
||||
if let Some(steps) = back {
|
||||
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
|
||||
for step in steps {
|
||||
self.journal.push(step);
|
||||
}
|
||||
self.journal_in_undo_groups(Some(uid), &grouped, from);
|
||||
}
|
||||
if previewed {
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
@@ -472,8 +520,17 @@ impl Session {
|
||||
}
|
||||
let began = std::mem::replace(&mut it.doc, st.doc.clone());
|
||||
// The drag acts on the objects it began with: a selection the command made (a paste, a
|
||||
// duplicate, Select All) does not change what the drag moves.
|
||||
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
|
||||
// duplicate, Select All) does not change what the drag moves. A dialog's preview acts on
|
||||
// the selection the command left, and its dialog previews again on its next pass, from the
|
||||
// values it shows then, so nothing is applied here.
|
||||
if it.dialog {
|
||||
if st.selection != *it.selection {
|
||||
it.selection = Arc::new(st.selection.clone());
|
||||
}
|
||||
it.preview = None;
|
||||
} else {
|
||||
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
|
||||
}
|
||||
// The journal holds the selection the command left. The drag's own selection is journaled
|
||||
// after it, so the drag and the commands after it replay on the objects they act on.
|
||||
let reselect = (active && st.selection != *it.selection)
|
||||
@@ -569,6 +626,7 @@ impl Session {
|
||||
revision: st.revision,
|
||||
preview: None,
|
||||
tool: false,
|
||||
dialog: false,
|
||||
tool_joined: false,
|
||||
paint,
|
||||
used_defaults_only: false,
|
||||
@@ -917,7 +975,7 @@ fn take_changed_paints(
|
||||
left: &vectorcraft_tools::PaintDefaults,
|
||||
now: &vectorcraft_tools::PaintDefaults,
|
||||
) {
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = now;
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, style_doc, inherited } = now;
|
||||
if left.fill != *fill {
|
||||
target.fill.clone_from(fill);
|
||||
}
|
||||
@@ -936,14 +994,48 @@ fn take_changed_paints(
|
||||
if left.blend != *blend {
|
||||
target.blend = *blend;
|
||||
}
|
||||
if left.style != *style {
|
||||
if left.style != *style || left.style_doc != *style_doc {
|
||||
target.style.clone_from(style);
|
||||
target.style_doc = *style_doc;
|
||||
}
|
||||
if left.inherited != *inherited {
|
||||
target.inherited = *inherited;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether command `id` acts on the drawing as a dialog's preview shows it (a copy, a save, a
|
||||
/// revert), so it runs inside that preview rather than as a step of its own.
|
||||
fn reads_preview(id: &str) -> bool {
|
||||
id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode")
|
||||
}
|
||||
|
||||
/// The selection on show in a dialog's preview `shown`, as a command from outside the dialog acts
|
||||
/// on it in the base document `base`: without the objects the preview made, and without a path
|
||||
/// whose selected anchors or segments are numbered in a shape the preview changed in more than a
|
||||
/// move (Set Corners recut it), since those numbers can name other points in `base`.
|
||||
fn shown_base_selection(selection: &mut Selection, shown: &Document, base: &Document) {
|
||||
selection.prune(base);
|
||||
let recut: Vec<_> = selection
|
||||
.anchors
|
||||
.keys()
|
||||
.chain(selection.segments.keys())
|
||||
.copied()
|
||||
.filter(|&id| {
|
||||
let path = |d: &Document| d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.clone());
|
||||
match (path(shown), path(base)) {
|
||||
(Some(now), Some(was)) => !moved_whole(&was, &now),
|
||||
(now, was) => now.is_some() != was.is_some(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
for id in recut {
|
||||
selection.objects.retain(|o| *o != id);
|
||||
selection.anchors.remove(&id);
|
||||
selection.segments.remove(&id);
|
||||
}
|
||||
selection.prune(base);
|
||||
}
|
||||
|
||||
/// The selection a drag began with, without the objects that a command run during it removed,
|
||||
/// hid or locked in `doc`.
|
||||
fn drag_selection(began: &Selection, doc: &Document) -> Selection {
|
||||
|
||||
@@ -123,6 +123,7 @@ impl Session {
|
||||
st.sync_new_art();
|
||||
cmd::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
st.history_restores += 1;
|
||||
st.revision += 1;
|
||||
// The journal drops only the canceled groups' own entries and keeps the ones made in other documents meanwhile.
|
||||
journal.extend(g.journal);
|
||||
@@ -280,6 +281,9 @@ impl Session {
|
||||
st.drop_stale_variables_highlight();
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
st.history.recost_last(&st.doc);
|
||||
if !Arc::ptr_eq(&undone, &st.doc) {
|
||||
st.history_restores += 1;
|
||||
}
|
||||
st.revision += 1;
|
||||
if colors_changed {
|
||||
self.paint = scope.paint;
|
||||
|
||||
@@ -180,6 +180,106 @@ fn reverse_path_direction_on_and_off_set_the_winding() {
|
||||
assert!(s.execute("path.reverse", &json!({})).is_err(), "nothing to reverse");
|
||||
}
|
||||
|
||||
/// Points of what is direct-selected on one path, rounded to whole points.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Picked {
|
||||
/// The selected anchors' points, sorted.
|
||||
anchors: Vec<(i64, i64)>,
|
||||
/// The end points of the selected segments, each pair and the list sorted.
|
||||
segments: Vec<[(i64, i64); 2]>,
|
||||
/// The key anchor's point, when the key anchor is on the path.
|
||||
key: Option<(i64, i64)>,
|
||||
}
|
||||
|
||||
/// What is direct-selected on path `id`, as points.
|
||||
fn picked_points(s: &Session, id: NodeId) -> Picked {
|
||||
let st = s.doc().unwrap();
|
||||
let sp = &st.doc.node(id).unwrap().path_data().unwrap().subpaths;
|
||||
let at = |(si, ai): (usize, usize)| {
|
||||
let p = sp[si].anchors[ai].p;
|
||||
(p.x.round() as i64, p.y.round() as i64)
|
||||
};
|
||||
let mut anchors: Vec<_> = st.selection.anchors.get(&id).into_iter().flatten().map(|r| at(*r)).collect();
|
||||
anchors.sort_unstable();
|
||||
let mut segments: Vec<_> = st
|
||||
.selection
|
||||
.segments
|
||||
.get(&id)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|&(si, j)| {
|
||||
let mut ends = [at((si, j)), at((si, (j + 1) % sp[si].anchors.len()))];
|
||||
ends.sort_unstable();
|
||||
ends
|
||||
})
|
||||
.collect();
|
||||
segments.sort_unstable();
|
||||
let key = st.selection.key_anchor.filter(|(k, _)| *k == id).map(|(_, r)| at(r));
|
||||
Picked { anchors, segments, key }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_path_direction_keeps_the_same_anchors_and_segments_direct_selected() {
|
||||
let mut s = session();
|
||||
let path = |s: &mut Session, anchors: Value, closed: bool| {
|
||||
NodeId(run(s, "path.create", json!({"anchors": anchors, "closed": closed}))["id"].as_u64().unwrap())
|
||||
};
|
||||
let open = path(&mut s, json!([{"x": 0, "y": 50}, {"x": 40, "y": 50}, {"x": 100, "y": 50}]), false);
|
||||
let closed = path(&mut s, json!([{"x": 10, "y": 10}, {"x": 90, "y": 10}, {"x": 90, "y": 90}, {"x": 10, "y": 90}]), true);
|
||||
run(&mut s, "select.anchorsMany", json!({"items": [{"id": open.0, "anchors": [[0, 0]]}, {"id": closed.0, "anchors": [[0, 1], [0, 2]]}]}));
|
||||
run(&mut s, "select.key", json!({"id": closed.0, "anchor": [0, 1]}));
|
||||
let before = [picked_points(&s, open), picked_points(&s, closed)];
|
||||
assert_eq!(before[0].anchors, [(0, 50)]);
|
||||
assert_eq!((before[1].anchors.clone(), before[1].key), (vec![(90, 10), (90, 90)], Some((90, 10))));
|
||||
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2);
|
||||
let first = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[0].p;
|
||||
assert_eq!((first(&s, open).x, first(&s, closed).y), (100.0, 90.0), "both paths turned");
|
||||
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same points stay direct-selected after Reverse Path Direction");
|
||||
// Undo turns the paths back with the selection they had.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(first(&s, open).x, 0.0);
|
||||
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "undo");
|
||||
|
||||
// Selected segments, the closing segment of a closed path included, stay the same segments.
|
||||
run(&mut s, "select.segments", json!({"id": closed.0, "segments": [[0, 0], [0, 3]], "mode": "set"}));
|
||||
run(&mut s, "select.segments", json!({"id": open.0, "segments": [[0, 0]], "mode": "add"}));
|
||||
let before = [picked_points(&s, open), picked_points(&s, closed)];
|
||||
assert_eq!(before[0].segments, [[(0, 50), (40, 50)]]);
|
||||
assert_eq!(before[1].segments, [[(10, 10), (10, 90)], [(10, 10), (90, 10)]]);
|
||||
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2);
|
||||
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same segments stay selected after Reverse Path Direction");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_path_direction_of_one_subpath_leaves_the_others_selection_as_it_is() {
|
||||
let mut s = session();
|
||||
let id = NodeId(run(&mut s, "path.create", json!({"d": "M0 0 L40 0 L100 0 M0 200 L40 200 L100 200"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 0], [1, 0]]}]}));
|
||||
run(&mut s, "select.key", json!({"id": id.0, "anchor": [0, 0]}));
|
||||
let before = picked_points(&s, id);
|
||||
assert_eq!((before.anchors.clone(), before.key), (vec![(0, 0), (0, 200)], Some((0, 0))));
|
||||
assert_eq!(run(&mut s, "path.reverse", json!({"subpath": 1}))["changed"], 1);
|
||||
let first = |s: &Session, si: usize| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[si].anchors[0].p;
|
||||
assert_eq!((first(&s, 0).x, first(&s, 1).x), (0.0, 100.0), "only the second subpath turned");
|
||||
assert_eq!(picked_points(&s, id), before, "the same points stay direct-selected on both subpaths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_anchor_point_keeps_the_key_anchor_on_its_point() {
|
||||
let mut s = session();
|
||||
let anchors = json!([{"x": 10, "y": 10}, {"x": 90, "y": 10}, {"x": 90, "y": 90}, {"x": 10, "y": 90}]);
|
||||
let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors, "closed": true}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 1], [0, 2]]}]}));
|
||||
run(&mut s, "select.key", json!({"id": id.0, "anchor": [0, 2]}));
|
||||
let before = picked_points(&s, id);
|
||||
assert_eq!((before.anchors.clone(), before.key), (vec![(90, 10), (90, 90)], Some((90, 90))));
|
||||
run(&mut s, "path.insertAnchor", json!({"id": id.0, "segment": 0}));
|
||||
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.len(), 5);
|
||||
assert_eq!(picked_points(&s, id), before, "the key anchor and the selected anchors stay on their points after Add Anchor Point");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(picked_points(&s, id), before, "undo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path() {
|
||||
use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile};
|
||||
|
||||
@@ -175,6 +175,32 @@ fn an_undo_group_lets_no_other_documents_steps_go_until_it_ends() {
|
||||
assert!(history_bytes(&s) <= s.history_budget);
|
||||
}
|
||||
|
||||
/// A canceled undo group, and a canceled undo scope that joined one, put back an older snapshot:
|
||||
/// both advance the document's history restores, as Undo does, and a kept one does not.
|
||||
#[test]
|
||||
fn canceled_undo_groups_and_scopes_count_as_history_restores() {
|
||||
let mut s = session_with_rects(2);
|
||||
let restores = |s: &Session| s.docs[0].history_restores;
|
||||
s.begin_undo_group();
|
||||
moves(&mut s, 2);
|
||||
s.end_undo_group(false);
|
||||
assert_eq!(restores(&s), 0, "a kept group restores nothing");
|
||||
s.begin_undo_group();
|
||||
moves(&mut s, 2);
|
||||
s.end_undo_group(true);
|
||||
assert_eq!(restores(&s), 1, "a canceled group");
|
||||
s.begin_undo_group();
|
||||
moves(&mut s, 1);
|
||||
let scope = s.begin_undo_scope().unwrap();
|
||||
moves(&mut s, 2);
|
||||
s.end_undo_scope(scope, true);
|
||||
assert_eq!(restores(&s), 2, "a canceled scope that joined the open group");
|
||||
let scope = s.begin_undo_scope().unwrap();
|
||||
s.end_undo_scope(scope, true);
|
||||
assert_eq!(restores(&s), 2, "a canceled scope that made no edit puts back the same snapshot");
|
||||
s.end_undo_group(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_kept_outside_a_command_keep_to_the_shared_budget() {
|
||||
let mut s = session_with_rects(50);
|
||||
|
||||
@@ -474,3 +474,249 @@ fn set_new_art_refuses_while_new_art_takes_the_selected_look() {
|
||||
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 7})), json!({"changed": true}));
|
||||
assert_eq!(s.new_art().stroke().unwrap().width, 7.0);
|
||||
}
|
||||
|
||||
fn new_type(s: &mut Session, p: Value) -> Node {
|
||||
let id = NodeId(run(s, "text.create", p)["id"].as_u64().unwrap());
|
||||
node(s, id)
|
||||
}
|
||||
|
||||
/// The fill of `n`'s first run of characters.
|
||||
fn char_fill(n: &Node) -> Paint {
|
||||
match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.runs[0].style.fill.clone(),
|
||||
_ => panic!("{} is not type", n.id.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Type with a second fill and a drop shadow on the object, selected.
|
||||
fn styled_type(s: &mut Session) -> NodeId {
|
||||
let id = NodeId(run(s, "text.create", json!({"x": 20, "y": 60, "text": "RIP", "size": 30}))["id"].as_u64().unwrap());
|
||||
run(s, "appearance.addFill", json!({}));
|
||||
run(s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(s, "effect.apply", json!({"effect": "stylize.dropShadow"}));
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects() {
|
||||
let mut s = session();
|
||||
let group = run(&mut s, "object.newGroup", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let src = styled_type(&mut s);
|
||||
let from = node(&s, src).appearance;
|
||||
assert_eq!(from.effects.len(), 1);
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [src.0]}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "new"}));
|
||||
assert_eq!(n.appearance.effects.len(), 1, "the drop shadow");
|
||||
assert_eq!(n.appearance.items.iter().filter(|i| i.is_fill()).count(), from.items.iter().filter(|i| i.is_fill()).count());
|
||||
assert_eq!(n.appearance.fill_paint(), from.fill_paint(), "the template keeps its own fill");
|
||||
// Override Character Color: the object's fill shows instead of the characters' own.
|
||||
assert_eq!(char_fill(&n), Paint::None);
|
||||
// Type placed in a group takes it too, and a color given keeps the characters' fill.
|
||||
run(&mut s, "select.set", json!({"ids": [src.0]}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let g = new_type(&mut s, json!({"x": 200, "y": 250, "text": "in", "parent": group, "color": "#00ff00"}));
|
||||
assert_eq!(g.appearance.effects.len(), 1);
|
||||
assert_ne!(char_fill(&g), Paint::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke() {
|
||||
let mut s = session();
|
||||
let plain = new_type(&mut s, json!({"x": 20, "y": 60, "text": "a"}));
|
||||
assert!(plain.appearance.items.is_empty() && plain.appearance.effects.is_empty());
|
||||
// Option on: a styled selection gives new type only its basic paints, so it stays plain.
|
||||
let src = styled_type(&mut s);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "b"}));
|
||||
assert_eq!((n.appearance.items.len(), n.appearance.effects.len(), char_fill(&n)), (0, 0, char_fill(&plain)));
|
||||
// Option off with plain type last selected: its characters' basic look, no fills of the object.
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [n.id.0]}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let m = new_type(&mut s, json!({"x": 200, "y": 250, "text": "c"}));
|
||||
assert_eq!((m.appearance.items.len(), char_fill(&m)), (0, char_fill(&plain)));
|
||||
assert!(node(&s, src).appearance.effects.len() == 1, "the source keeps its look");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_style_clicked_with_nothing_selected_styles_the_next_type() {
|
||||
let mut s = session();
|
||||
fancy(&mut s);
|
||||
let name = run(&mut s, "graphicStyle.new", json!({"name": "Fancy"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": name}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "styled"}));
|
||||
assert_eq!((n.appearance.items.iter().filter(|i| i.is_fill()).count(), n.appearance.effects.len()), (2, 1));
|
||||
assert_eq!(char_fill(&n), Paint::None);
|
||||
// With Override Character Color off the characters keep their fill under the style's.
|
||||
run(&mut s, "graphicStyle.setOptions", json!({"overrideCharColor": false}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let kept = new_type(&mut s, json!({"x": 200, "y": 250, "text": "kept"}));
|
||||
assert_eq!(kept.appearance.effects.len(), 1);
|
||||
assert_ne!(char_fill(&kept), Paint::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_art_and_type_from_a_knockout_style_stay_linked_to_it() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 20.0);
|
||||
run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true}));
|
||||
let name = run(&mut s, "graphicStyle.new", json!({"name": "Knockout"}))["name"].as_str().unwrap().to_string();
|
||||
for (make, p) in
|
||||
[("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))]
|
||||
{
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": name}));
|
||||
run(&mut s, make, p);
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name.clone(), true)), "{make}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type() {
|
||||
let mut s = session();
|
||||
let src = painted(&mut s, 20.0, "#ff0000", "#0000ff", 2.0);
|
||||
let red = node(&s, src).appearance.fill_paint();
|
||||
let name = run(&mut s, "graphicStyle.new", json!({"name": "Plain"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": name}));
|
||||
// The first type is linked to the style, so the next one, taking its look, gets it too.
|
||||
for (y, text) in [(200, "one"), (250, "two")] {
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": y, "text": text}));
|
||||
assert_eq!(n.appearance.fill_paint(), red, "{text}");
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name.clone(), true)), "{text}");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_type_that_text_wrap_moves_takes_the_styles_gradient_on_the_frame_it_ends_with() {
|
||||
let mut s = session();
|
||||
let group = run(&mut s, "object.newGroup", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 80}));
|
||||
// A placed vertical gradient, top to bottom of the rectangle.
|
||||
let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]);
|
||||
run(&mut s, "paint.setFill", json!({"gradient": {"stops": stops, "start": [50, 0], "end": [50, 80]}}));
|
||||
let name = run(&mut s, "graphicStyle.new", json!({"name": "Vertical"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "object.textWrap.make", json!({"offset": 0}));
|
||||
let style = s.doc().unwrap().doc.graphic_styles.iter().find(|g| g.name == name).unwrap().clone();
|
||||
assert!(style.unit_box && style.appearance.has_placed_gradient());
|
||||
let area = json!({"width": 100, "height": 20, "fit": "autoHeight"});
|
||||
// Drawn behind the wrap object, and placed into a group below it.
|
||||
for p in [
|
||||
json!({"x": 0, "y": 0, "text": "a", "size": 12, "area": area}),
|
||||
json!({"x": 0, "y": 0, "text": "a", "size": 12, "area": area, "parent": group}),
|
||||
] {
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "view.drawMode", json!({"mode": if p.get("parent").is_some() { "normal" } else { "behind" }}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": name}));
|
||||
let n = new_type(&mut s, p.clone());
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(b.height() > 80.0, "the frame grows below the wrap object: {b:?} ({p})");
|
||||
let mut placed = style.appearance.clone();
|
||||
placed.rebase_gradients(vectorcraft_doc::GraphicStyle::UNIT_BOX, b);
|
||||
assert_eq!(*n.appearance, placed, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name() {
|
||||
let mut s = session();
|
||||
fancy(&mut s);
|
||||
run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true}));
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Shared"}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": "Shared"}));
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
rect(&mut s, 20.0);
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Shared"}));
|
||||
for (make, p) in
|
||||
[("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))]
|
||||
{
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let id = NodeId(run(&mut s, make, p)["id"].as_u64().unwrap());
|
||||
let n = node(&s, id);
|
||||
assert_eq!((n.extras().graphic_style, n.isolate), (None, false), "{make}");
|
||||
assert_eq!(n.appearance.effects.len(), 1, "{make} keeps the template's look");
|
||||
}
|
||||
// Back in the document the style came from, new art is linked to it again.
|
||||
s.set_active(0);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "text.create", json!({"x": 200, "y": 200, "text": "k"}));
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Shared".to_string(), true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_type_in_another_document_takes_a_basic_styles_look_and_transparency() {
|
||||
let mut s = session();
|
||||
let src = painted(&mut s, 20.0, "#ff0000", "#0000ff", 2.0);
|
||||
let red = node(&s, src).appearance.fill_paint();
|
||||
run(&mut s, "transparency.set", json!({"opacity": 50, "blend": "multiply"}));
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Red"}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": "Red"}));
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "k"}));
|
||||
assert_eq!(n.appearance.fill_paint(), red, "the style's fill");
|
||||
assert_eq!((n.opacity, n.blend), (0.5, BlendMode::Multiply), "the style's transparency");
|
||||
assert_eq!(n.extras().graphic_style, None, "no link to a style of another document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_art_and_type_from_a_style_redefined_after_it_was_picked_keep_the_picked_look_unlinked() {
|
||||
let mut s = session();
|
||||
fancy(&mut s);
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Picked"}));
|
||||
let other = painted(&mut s, 120.0, "#00ff00", "#000000", 3.0);
|
||||
run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": "Picked"}));
|
||||
let picked = s.new_art();
|
||||
let redefine = |s: &mut Session| run(s, "graphicStyle.redefine", json!({"name": "Picked", "id": other.0}));
|
||||
let linked = |s: &mut Session| run(s, "appearance.newArt", json!({}))["graphicStyle"].clone();
|
||||
let make =
|
||||
[("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))];
|
||||
redefine(&mut s);
|
||||
assert_eq!(linked(&mut s), Value::Null);
|
||||
// Undone, the style has the picked look again, and new art links to it.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(linked(&mut s), json!("Picked"));
|
||||
for (cmd, p) in &make {
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, cmd, p.clone());
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Picked".to_string(), true)), "{cmd}");
|
||||
}
|
||||
redefine(&mut s);
|
||||
assert_eq!(linked(&mut s), Value::Null);
|
||||
for (cmd, p) in &make {
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let id = NodeId(run(&mut s, cmd, p.clone())["id"].as_u64().unwrap());
|
||||
let n = node(&s, id);
|
||||
assert_eq!((n.extras().graphic_style, n.isolate, n.opacity), (None, false, 0.5), "{cmd}: the picked transparency, unlinked");
|
||||
assert_eq!((n.appearance.effects.len(), n.appearance.fill_paint()), (1, picked.fill_paint()), "{cmd}: the picked look");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_type_takes_a_selected_look_that_matches_the_redefined_default_style() {
|
||||
let mut s = session();
|
||||
let src = fancy(&mut s);
|
||||
run(&mut s, "graphicStyle.redefine", json!({"name": "Default Graphic Style", "id": src.0}));
|
||||
run(&mut s, "graphicStyle.breakLink", json!({"ids": [src.0]}));
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [src.0]}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "in"}));
|
||||
assert_eq!(n.appearance.items.iter().filter(|i| i.is_fill()).count(), 2, "both fills from the selection");
|
||||
assert_eq!(n.appearance.effects.len(), 1, "the drop shadow from the selection");
|
||||
// The same look from paint.default is the document's default, so new type stays plain.
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "paint.default", json!({}));
|
||||
let d = new_type(&mut s, json!({"x": 200, "y": 260, "text": "df"}));
|
||||
assert!(d.appearance.items.is_empty() && d.appearance.effects.is_empty(), "plain type");
|
||||
assert_ne!(char_fill(&d), Paint::None);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -211,6 +211,33 @@ fn exclude_makes_compound() {
|
||||
assert!((area_of(&s, r[0]) - 15000.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divide_over_work_budget_preserves_art_and_selection() {
|
||||
let mut s = session();
|
||||
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let line = s.execute("shape.line", &json!({"x1": -10, "y1": -10, "x2": 110, "y2": 110})).unwrap();
|
||||
let cutter = NodeId(line["id"].as_u64().unwrap());
|
||||
// The existing pathops work-budget fixture uses 1,500 overlapping lines.
|
||||
// Put them in one open path so the setup only makes two document objects.
|
||||
let line = SubPath::polyline(&[Point::new(-10.0, -10.0), Point::new(110.0, 110.0)], false);
|
||||
s.edit("complex cutter", |d, _| {
|
||||
let NodeKind::Path { path, .. } = &mut d.node_mut(cutter).unwrap().kind else { panic!("expected a path") };
|
||||
*path = PathData::new(vec![line; 1_500]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [square.0, cutter.0]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let error = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("too many segments or pieces"), "{error}");
|
||||
let state = s.doc().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&state.doc, &before), "the original document must be restored");
|
||||
assert_eq!(state.selection, selection);
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divide_produces_group_of_faces() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -519,3 +519,138 @@ fn type_on_a_path_made_with_the_type_tool_has_brackets_at_once() {
|
||||
assert!(ink(&s, id).y0 > 299.0, "{tool}: below the path");
|
||||
}
|
||||
}
|
||||
|
||||
/// Press and release `tool` at `p`.
|
||||
fn click(s: &mut Session, tool: &str, p: Point) {
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool(tool, v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap();
|
||||
}
|
||||
assert!(!s.in_interaction());
|
||||
}
|
||||
|
||||
/// Type along "M100 300 L300 300 L500 300" turned a quarter turn, so a document-space edit isn't
|
||||
/// the path's own, and selected; with its path in document space.
|
||||
fn turned_path_type(s: &mut Session) -> NodeId {
|
||||
let id = path_type(s, "M100 300 L300 300 L500 300", [100.0, 310.0], "Reshaped type");
|
||||
s.execute("object.transform", &json!({"ids": [id.0], "matrix": [0, 1, -1, 0, 600, 0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn type_path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
|
||||
text(s, id).type_path().unwrap()
|
||||
}
|
||||
|
||||
fn close(a: Point, b: Point) -> bool {
|
||||
near(a.x, b.x) && near(a.y, b.y)
|
||||
}
|
||||
|
||||
/// #10862: the Anchor Point tool drags handles out of an anchor of selected type on a path's path,
|
||||
/// in document space through the type's transform, as one undo step, and the type reflows.
|
||||
#[test]
|
||||
fn anchor_point_tool_pulls_handles_out_of_type_on_a_path() {
|
||||
let mut s = session();
|
||||
let id = turned_path_type(&mut s);
|
||||
let middle = type_path(&s, id).subpaths[0].anchors[1].p;
|
||||
let (glyphs, n) = (origins(&s, id), undo_len(&s));
|
||||
let to = middle + vectorcraft_geom::Vec2::new(40.0, 0.0);
|
||||
drag(&mut s, "anchorPoint", middle, to, Mods::default());
|
||||
let a = type_path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(close(a.p, middle) && close(a.h_out, to) && close(a.h_in, middle - (to - middle)), "{a:?}");
|
||||
assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth);
|
||||
assert_ne!(origins(&s, id), glyphs, "the type reflows along the curved path");
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!type_path(&s, id).subpaths[0].anchors[1].has_out());
|
||||
}
|
||||
|
||||
/// #10862: the rest of the Anchor Point tool's gestures on type on a path's path: a click makes a
|
||||
/// smooth anchor a corner, a handle drag moves that handle alone, Shift at the press moves the
|
||||
/// anchor, and a segment drag bends the segment.
|
||||
#[test]
|
||||
fn anchor_point_tool_reshapes_type_on_a_path() {
|
||||
let mut s = session();
|
||||
let id = turned_path_type(&mut s);
|
||||
let [first, middle, last] = [0, 1, 2].map(|i| type_path(&s, id).subpaths[0].anchors[i].p);
|
||||
let up = vectorcraft_geom::Vec2::new(40.0, 0.0);
|
||||
drag(&mut s, "anchorPoint", middle, middle + up, Mods::default());
|
||||
// A handle end, dragged, moves alone and makes the anchor a corner.
|
||||
let handle = middle + vectorcraft_geom::Vec2::new(40.0, 30.0);
|
||||
drag(&mut s, "anchorPoint", middle + up, handle, Mods::default());
|
||||
let a = type_path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(close(a.h_out, handle) && close(a.h_in, middle - up) && a.kind == vectorcraft_geom::AnchorKind::Corner, "{a:?}");
|
||||
// A click on the anchor takes its handles back.
|
||||
click(&mut s, "anchorPoint", middle);
|
||||
let a = type_path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(!a.has_in() && !a.has_out(), "{a:?}");
|
||||
// Shift at the press moves the anchor.
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
drag(&mut s, "anchorPoint", middle, middle + up, shift);
|
||||
assert!(close(type_path(&s, id).subpaths[0].anchors[1].p, middle + up));
|
||||
// A drag on the first segment bends it; its anchors stay.
|
||||
let on_segment = first.midpoint(middle + up);
|
||||
drag(&mut s, "anchorPoint", on_segment, on_segment + vectorcraft_geom::Vec2::new(0.0, 30.0), Mods::default());
|
||||
let sp = &type_path(&s, id).subpaths[0];
|
||||
assert!(close(sp.anchors[0].p, first) && close(sp.anchors[2].p, last));
|
||||
assert!(sp.anchors[0].has_out() && sp.anchors[1].has_in(), "the segment curves: {sp:?}");
|
||||
}
|
||||
|
||||
/// #10862: the Add and Delete Anchor Point tools add an anchor to type on a path's path and delete
|
||||
/// one, and Pen + Alt pulls handles out of one; Delete leaves the path two anchors at least, and
|
||||
/// Scissors does not cut the type.
|
||||
#[test]
|
||||
fn add_delete_and_pen_alt_edit_type_on_a_path() {
|
||||
let mut s = session();
|
||||
let id = turned_path_type(&mut s);
|
||||
let [first, middle] = [0, 1].map(|i| type_path(&s, id).subpaths[0].anchors[i].p);
|
||||
let quarter = first.midpoint(middle);
|
||||
click(&mut s, "addAnchor", quarter);
|
||||
let sp = type_path(&s, id).subpaths[0].clone();
|
||||
assert_eq!(sp.anchors.len(), 4);
|
||||
assert!(close(sp.anchors[1].p, quarter), "{sp:?}");
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let to = quarter + vectorcraft_geom::Vec2::new(0.0, 25.0);
|
||||
drag(&mut s, "pen", quarter, to, alt);
|
||||
let a = type_path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(close(a.p, quarter) && close(a.h_out, to) && a.kind == vectorcraft_geom::AnchorKind::Smooth, "{a:?}");
|
||||
// The Pen's Auto Add/Delete adds an anchor on a segment and deletes it again.
|
||||
let last = type_path(&s, id).subpaths[0].anchors[3].p;
|
||||
let three_quarters = middle.midpoint(last);
|
||||
click(&mut s, "pen", three_quarters);
|
||||
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 5);
|
||||
click(&mut s, "pen", three_quarters);
|
||||
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 4);
|
||||
click(&mut s, "deleteAnchor", quarter);
|
||||
click(&mut s, "deleteAnchor", middle);
|
||||
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 2);
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": 0}));
|
||||
assert!(r.is_err(), "type on a path keeps two anchors: {r:?}");
|
||||
assert_eq!((type_path(&s, id).subpaths[0].anchors.len(), undo_len(&s)), (2, n));
|
||||
let end = type_path(&s, id).subpaths[0].anchors[1].p;
|
||||
click(&mut s, "scissors", first.midpoint(end));
|
||||
assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. }));
|
||||
assert_eq!(undo_len(&s), n, "Scissors leaves the type whole");
|
||||
}
|
||||
|
||||
/// #10862: `path.insertAnchor` on type on a path, unselected or with `selectAnchor`, leaves the type
|
||||
/// selected whole with no direct-selected anchors, so `path.moveAnchors` (the arrow keys) moves
|
||||
/// the type instead of failing on an anchor that is not a path's.
|
||||
#[test]
|
||||
fn an_anchor_added_to_type_on_a_path_leaves_it_selected_whole() {
|
||||
let mut s = session();
|
||||
let id = turned_path_type(&mut s);
|
||||
for select_anchor in [false, true] {
|
||||
if !select_anchor {
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
}
|
||||
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5, "selectAnchor": select_anchor})).unwrap();
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert!(sel.contains(id) && sel.partial(id).is_none() && !sel.anchors.contains_key(&id), "selectAnchor {select_anchor}");
|
||||
let before = type_path(&s, id).subpaths[0].anchors[0].p;
|
||||
s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 0})).unwrap();
|
||||
assert!(close(type_path(&s, id).subpaths[0].anchors[0].p, before + vectorcraft_geom::Vec2::new(10.0, 0.0)));
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,211 @@ fn print_as_bitmap_prints_all_of_a_long_artboard() {
|
||||
assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}");
|
||||
}
|
||||
|
||||
/// The images `file.print` prints with `settings`: their pixel sizes and their places on the page
|
||||
/// in the print-ready PDF (read back), their pixel sizes in the PostScript file (its image
|
||||
/// dictionaries, each size once), and the warnings of both.
|
||||
struct Printed {
|
||||
pdf: Vec<(u32, u32)>,
|
||||
placed: Vec<Rect>,
|
||||
ps: Vec<(u32, u32)>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
fn printed_images(s: &mut Session, settings: &Value) -> Printed {
|
||||
let warnings = |v: &Value| -> Vec<String> { v["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect() };
|
||||
let v = s.execute("file.print", &json!({ "settings": settings })).unwrap();
|
||||
let back = vectorcraft_pdf::import(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let (mut pdf, mut placed) = (vec![], vec![]);
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
pdf.push((im.width, im.height));
|
||||
placed.push(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))));
|
||||
}
|
||||
});
|
||||
let mut all = warnings(&v);
|
||||
let v = s.execute("file.print", &json!({ "settings": settings, "format": "postscript" })).unwrap();
|
||||
let ps = String::from_utf8_lossy(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).into_owned();
|
||||
let mut sizes = vec![];
|
||||
for part in ps.split("<< /ImageType ").skip(1) {
|
||||
let after = |key: &str| part.split_once(key).and_then(|(_, r)| r.split_whitespace().next()).and_then(|n| n.parse::<u32>().ok());
|
||||
if let (Some(w), Some(h)) = (after("/Width "), after("/Height ")) {
|
||||
sizes.push((w, h));
|
||||
}
|
||||
}
|
||||
sizes.sort_unstable();
|
||||
sizes.dedup();
|
||||
all.extend(warnings(&v));
|
||||
Printed { pdf, placed, ps: sizes, warnings: all }
|
||||
}
|
||||
|
||||
const CAPPED: &str = "Print as Bitmap prints at";
|
||||
|
||||
/// `advanced.bitmapResolution` sets how many pixels Print as Bitmap prints the art with, in a
|
||||
/// print-ready PDF and in PostScript, on the same place of the page; 0 or none keeps the
|
||||
/// document's raster effects resolution.
|
||||
#[test]
|
||||
fn bitmap_resolution_sets_the_printed_image_size() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let mut places = vec![];
|
||||
for (ppi, size) in [(Value::Null, (200, 100)), (json!(0), (200, 100)), (json!(144), (400, 200)), (json!(36), (100, 50)), (json!(1), (3, 2))] {
|
||||
let mut advanced = json!({"printAsBitmap": true});
|
||||
if !ppi.is_null() {
|
||||
advanced["bitmapResolution"] = ppi.clone();
|
||||
}
|
||||
let p = printed_images(&mut s, &json!({ "advanced": advanced }));
|
||||
assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([size].as_slice(), [size].as_slice()), "{ppi}");
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{ppi}: {:?}", p.warnings);
|
||||
// At 1 ppi the image is rounded up to whole pixels past the artboard.
|
||||
if ppi != json!(1) {
|
||||
places.extend(p.placed);
|
||||
}
|
||||
}
|
||||
let first = places[0];
|
||||
for r in &places {
|
||||
let apart = (r.x0 - first.x0).abs() + (r.y0 - first.y0).abs() + (r.width() - first.width()).abs() + (r.height() - first.height()).abs();
|
||||
assert!(apart < 1.0, "the image covers the same part of the page: {r:?} vs {first:?}");
|
||||
}
|
||||
// Art that does not print as a bitmap leaves it unused.
|
||||
let p = printed_images(&mut s, &json!({"advanced": {"bitmapResolution": 144}}));
|
||||
assert!(p.pdf.is_empty(), "{:?}", p.pdf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_as_bitmap_keeps_its_resolution_at_unlinked_print_scales() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let set = json!({
|
||||
"advanced": {"printAsBitmap": true, "bitmapResolution": 144},
|
||||
"scaling": "custom", "scale": {"width": 200, "height": 100, "linked": false}
|
||||
});
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([(800, 200)].as_slice(), [(800, 200)].as_slice()));
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings);
|
||||
let [placed] = p.placed[..] else { panic!("one image: {:?}", p.placed) };
|
||||
assert!((placed.width() - 400.0).abs() < 0.01 && (placed.height() - 100.0).abs() < 0.01, "{placed:?}");
|
||||
}
|
||||
|
||||
/// Print as Bitmap prints at `bitmapResolution` on paper: a job printed at 200% renders twice the
|
||||
/// pixels, and so does one that Fit to Page enlarges, so the image keeps its resolution.
|
||||
#[test]
|
||||
fn print_as_bitmap_keeps_its_resolution_at_a_print_scale() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let advanced = json!({"printAsBitmap": true, "bitmapResolution": 144});
|
||||
let p = printed_images(&mut s, &json!({"advanced": advanced, "scaling": "custom", "scale": {"width": 200}}));
|
||||
assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([(800, 400)].as_slice(), [(800, 400)].as_slice()));
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings);
|
||||
let fit = printed_images(&mut s, &json!({"advanced": advanced, "scaling": "fit"}));
|
||||
let [(w, _)] = fit.pdf[..] else { panic!("one image: {:?}", fit.pdf) };
|
||||
let [placed] = fit.placed[..] else { panic!("one image: {:?}", fit.placed) };
|
||||
let ppi = f64::from(w) / placed.width() * 72.0;
|
||||
assert!((ppi - 144.0).abs() < 2.0, "{w} pixels across {} pt: {ppi} ppi", placed.width());
|
||||
}
|
||||
|
||||
/// A `bitmapResolution` given to `file.print` applies to that job alone; `print.setup` saves it.
|
||||
#[test]
|
||||
fn a_bitmap_resolution_given_to_file_print_applies_to_that_job() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let undo = s.active().unwrap().history.undo.len();
|
||||
let p = printed_images(&mut s, &json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 144}}));
|
||||
assert_eq!(p.pdf, [(400, 200)]);
|
||||
assert!(doc(&s).print_setup.is_none(), "the saved settings stay as they are");
|
||||
assert_eq!(doc(&s).raster_effects_ppi, 72.0, "and so does the raster effects resolution");
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), undo, "printing adds no undo step");
|
||||
let v = s.execute("print.setup", &json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": 144}}})).unwrap();
|
||||
assert_eq!(v["settings"]["advanced"]["bitmapResolution"], 144.0);
|
||||
assert_eq!(printed_images(&mut s, &json!({})).pdf, [(400, 200)], "a job without settings prints at the saved one");
|
||||
assert_eq!(printed_images(&mut s, &json!({"advanced": {"bitmapResolution": 0}})).pdf, [(200, 100)], "0 over it: the document's");
|
||||
// A saved 0 is left out of the settings, which read it back as 0.
|
||||
let v = s.execute("print.setup", &json!({"settings": {"advanced": {"bitmapResolution": 0}}})).unwrap();
|
||||
assert!(v["settings"]["advanced"].get("bitmapResolution").is_none(), "{}", v["settings"]["advanced"]);
|
||||
}
|
||||
|
||||
/// A `bitmapResolution` outside 0 and 1–9600 ppi, or that is not a number, is refused by
|
||||
/// `print.setup`, `print.preview` and `file.print` alike, and nothing is saved.
|
||||
#[test]
|
||||
fn a_bitmap_resolution_out_of_range_is_refused() {
|
||||
let (mut s, _) = session();
|
||||
let undo = s.active().unwrap().history.undo.len();
|
||||
for bad in [json!(0.5), json!(-1), json!(-0.001), json!(9600.5), json!(1e300), json!("high"), json!(true), json!([300])] {
|
||||
let p = json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": bad}}});
|
||||
for cmd in ["print.setup", "print.preview", "file.print"] {
|
||||
let e = s.execute(cmd, &p).map(|v| panic!("{cmd} {bad}: {v}")).unwrap_err().to_string();
|
||||
assert!(!bad.is_number() || e.contains("advanced.bitmapResolution must be 1–9600 ppi"), "{cmd} {bad}: {e}");
|
||||
}
|
||||
}
|
||||
assert!(doc(&s).print_setup.is_none());
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), undo);
|
||||
for ok in [1.0, 9600.0] {
|
||||
s.execute("print.preview", &json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": ok}}})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A page the pixel limits print below the `bitmapResolution` asked for gets a warning that names
|
||||
/// the resolution it prints at, in `file.print`'s PDF and PostScript replies and in
|
||||
/// `print.preview`.
|
||||
#[test]
|
||||
fn a_bitmap_resolution_the_pixel_limits_lower_is_named() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 9000, "height": 2})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 2})).unwrap();
|
||||
let set = json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}});
|
||||
let p = printed_images(&mut s, &set);
|
||||
// 32,766 pixels across 9,000 pt: 262.1 ppi.
|
||||
let note = "Print as Bitmap prints at 262 ppi, not the 600 ppi bitmapResolution asks for";
|
||||
assert_eq!(p.warnings.iter().filter(|w| w.starts_with(note)).count(), 2, "{:?}", p.warnings);
|
||||
let [(w, _)] = p.pdf[..] else { panic!("one image: {:?}", p.pdf) };
|
||||
assert!((32_000..=vectorcraft_render::MAX_RASTER_SIDE).contains(&w), "{w} pixels");
|
||||
assert_eq!(p.ps, p.pdf);
|
||||
let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap();
|
||||
assert!(pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(note)), "{}", pv["warnings"]);
|
||||
// A resolution that fits, the document's resolution, and output that is not a bitmap: no note.
|
||||
for set in [
|
||||
json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 200}}),
|
||||
json!({"advanced": {"printAsBitmap": true}}),
|
||||
json!({"advanced": {"bitmapResolution": 600}}),
|
||||
json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}, "output": {"mode": "separations"}}),
|
||||
] {
|
||||
let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap();
|
||||
assert!(!pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{set}: {}", pv["warnings"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// An artboard with no art prints no image, so the pixel limits a bitmap of it would meet name no
|
||||
/// lower resolution, also with only art that draws nothing on it in `file.print`; once a background
|
||||
/// color or art that draws is on it, they do.
|
||||
#[test]
|
||||
fn an_empty_artboard_does_not_name_a_lower_bitmap_resolution() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("artboard.new", &json!({"x": 0, "y": 500, "width": 9000, "height": 2})).unwrap();
|
||||
let set = json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}});
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!(p.pdf.len(), 1, "only the artboard with art prints an image: {:?}", p.pdf);
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings);
|
||||
let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap();
|
||||
assert!(!pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{}", pv["warnings"]);
|
||||
// A background color prints, in file.print and in what print.preview says alike.
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "color": "#336699"})).unwrap();
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!(p.pdf.len(), 2, "{:?}", p.pdf);
|
||||
assert_eq!(p.warnings.iter().filter(|w| w.starts_with(CAPPED)).count(), 2, "{:?}", p.warnings);
|
||||
let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap();
|
||||
assert!(pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{}", pv["warnings"]);
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "color": null})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 500, "width": 9000, "height": 2})).unwrap()["id"].clone();
|
||||
// Art that draws nothing prints no image either.
|
||||
s.execute("object.setProps", &json!({"ids": [id], "opacity": 0})).unwrap();
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!(p.pdf.len(), 1, "{:?}", p.pdf);
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings);
|
||||
s.execute("object.setProps", &json!({"ids": [id], "opacity": 100})).unwrap();
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!(p.pdf.len(), 2, "{:?}", p.pdf);
|
||||
assert_eq!(p.warnings.iter().filter(|w| w.starts_with(CAPPED)).count(), 2, "{:?}", p.warnings);
|
||||
}
|
||||
|
||||
/// Appearance of Black › Printing / Exporting (#394): Print as Bitmap draws pure CMYK black as RGB
|
||||
/// black when `rich_black` is on.
|
||||
#[test]
|
||||
|
||||
@@ -133,6 +133,118 @@ fn pathless_save_rejection_hides_document_folder() {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_file_save_directory_errors_hide_paths_the_caller_did_not_give() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let d = dir("multi-file-directory-error");
|
||||
let (inside, outside) = (d.join("in"), d.join("kept-out"));
|
||||
for folder in [&inside, &outside] {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let own = path(&outside, "doc.vectorcraft");
|
||||
let saved = s.execute("document.save", &json!({"path": own, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = saved["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert!(files.len() > 1, "{saved}");
|
||||
let primary = std::fs::read(&own).unwrap();
|
||||
rect(&mut s);
|
||||
let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap();
|
||||
for target in [&files[0], &files[1]] {
|
||||
let original = std::fs::read(target).unwrap();
|
||||
std::fs::remove_file(target).unwrap();
|
||||
std::fs::create_dir(target).unwrap();
|
||||
let name = std::path::Path::new(target).file_name().unwrap().to_string_lossy();
|
||||
for (roots, params, shown) in [
|
||||
(&write_only, json!({"separateArtboards": true}), name.as_ref()),
|
||||
(&write_only, json!({"path": null, "separateArtboards": true}), name.as_ref()),
|
||||
(&write_only, json!({"path": own, "separateArtboards": true}), target.as_str()),
|
||||
(&both, json!({"separateArtboards": true}), target.as_str()),
|
||||
] {
|
||||
let error = confine(roots.as_ref(), || s.execute("document.save", ¶ms)).unwrap_err().to_string();
|
||||
assert_eq!(error, format!("{shown}: not a file"), "{params}");
|
||||
assert!(std::path::Path::new(target).is_dir());
|
||||
if target != &own {
|
||||
assert_eq!(std::fs::read(&own).unwrap(), primary);
|
||||
}
|
||||
assert!(s.doc().unwrap().is_dirty());
|
||||
}
|
||||
std::fs::remove_dir(target).unwrap();
|
||||
std::fs::write(target, original).unwrap();
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_multi_file_save_never_calls_the_writer() {
|
||||
use crate::cmd::fileio::save_job;
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let d = dir("refused-writer");
|
||||
let inside = d.join("in");
|
||||
let outside = d.join("out");
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let own = path(&outside, "doc.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": own})).unwrap();
|
||||
let original = std::fs::read(&own).unwrap();
|
||||
let roots = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
|
||||
for explicit in [false, true] {
|
||||
let p = if explicit { json!({"path": own, "separateArtboards": true}) } else { json!({"separateArtboards": true}) };
|
||||
let plan = save_plan(&s, SaveMode::Save, &p).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let mut calls = 0;
|
||||
let error = confine(roots.as_ref(), || {
|
||||
job.write_unless(
|
||||
|_| None,
|
||||
|_, _| {
|
||||
calls += 1;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert_eq!(calls, 0);
|
||||
assert!(error.contains("outside the write root"), "{error}");
|
||||
assert_eq!(error.contains(&outside.to_string_lossy().to_string()), explicit, "{error}");
|
||||
assert_eq!(std::fs::read(&own).unwrap(), original);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A save of several files into a folder that may not be read fails as a write there fails, with
|
||||
/// READ_ONLY_LOCATION, and not because the files' real paths could not be compared.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_multi_file_save_into_a_locked_folder_is_read_only() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let d = dir("locked-multi");
|
||||
let locked = d.join("locked");
|
||||
std::fs::create_dir_all(&locked).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let own = path(&locked, "doc.vectorcraft");
|
||||
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
|
||||
// Where permissions don't hold (root), the folder reads as any other.
|
||||
let enforced = std::fs::read_dir(&locked).is_err();
|
||||
let r = s.execute("document.save", &json!({"path": own, "separateArtboards": true}));
|
||||
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
if enforced {
|
||||
let e = r.unwrap_err();
|
||||
assert!(matches!(e, EngineError::ReadOnlyLocation(_)), "{e}");
|
||||
assert!(std::fs::read_dir(&locked).unwrap().next().is_none());
|
||||
} else {
|
||||
assert!(r.is_ok(), "{r:?}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_svg_path_writes_svg_and_save_writes_it_back() {
|
||||
let d = dir("svg");
|
||||
|
||||
@@ -179,6 +179,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() {
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
profiles: (None, None),
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
|
||||
@@ -4095,6 +4095,55 @@ const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m =
|
||||
try { p.removeAll(); } catch (e) { m = e.message; }\
|
||||
vc.log(m); vc.log(p.length);";
|
||||
|
||||
/// A group's `pathItems.removeAll()` walks the group, not the document: emptying a group of two
|
||||
/// paths beside 500 other paths looks at a handful of objects, and an empty group's looks at none.
|
||||
#[test]
|
||||
fn group_path_items_remove_all_walks_only_the_group() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
for i in 0..500 {
|
||||
rect(&mut s, f64::from(i % 25) * 10.0, f64::from(i / 25) * 10.0, 5.0, 5.0);
|
||||
}
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let start = crate::script::dom::REMOVE_ALL_VISITS.with(|n| n.get());
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var g = app.activeDocument.groupItems[0]; g.pathItems.removeAll(); g.pathItems.removeAll();\
|
||||
vc.log(g.pathItems.length); vc.log(app.activeDocument.pathItems.length);",
|
||||
);
|
||||
let visits = crate::script::dom::REMOVE_ALL_VISITS.with(|n| n.get()) - start;
|
||||
assert_eq!(out, vec![json!(0), json!(500)]);
|
||||
assert!(visits <= 3, "{visits} objects walked to empty a group of two paths");
|
||||
}
|
||||
|
||||
/// In a damaged document where a path outside a group has the same id as a path in it, the
|
||||
/// group's `pathItems.removeAll()` throws and deletes nothing, instead of deleting the outside path.
|
||||
#[test]
|
||||
fn group_path_items_remove_all_refuses_an_id_found_outside_the_group() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("object.arrange.sendToBack", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
|
||||
d.node_mut(c).unwrap().id = a;
|
||||
d.drop_lookup_cache();
|
||||
// The first object in tree order with the id is the one outside the group.
|
||||
assert_eq!(d.index_path(a).map(|p| p.len()), Some(2));
|
||||
let n = d.layers[0].children().map_or(0, Vec::len);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, m = ''; try { d.groupItems[0].pathItems.removeAll(); } catch (e) { m = e.message; }\
|
||||
vc.log(m); vc.log(d.groupItems[0].pathItems.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(format!("cannot delete PathItem {}: its id also names another object", a.0)), json!(2)]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.layers[0].children().map_or(0, Vec::len), n, "the path outside the group is kept");
|
||||
}
|
||||
|
||||
/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the
|
||||
/// group keeps other art, and deletes nothing, as the scoped collections do.
|
||||
#[test]
|
||||
@@ -4420,6 +4469,103 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empt
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// An image's frame clips as a clipping path does, so a clipping group whose clipping path keeps
|
||||
/// an image still has an outline after its paths are deleted.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_keeps_a_clipping_group_whose_clipping_path_keeps_an_image() {
|
||||
for frame in [Frame::Square, Frame::Line, Frame::Far, Frame::Inset, Frame::Mirrored, Frame::Strip] {
|
||||
remove_all_beside_an_image(frame);
|
||||
}
|
||||
}
|
||||
|
||||
/// The image frame of [`remove_all_beside_an_image`].
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Frame {
|
||||
/// 40 pt square.
|
||||
Square,
|
||||
/// Collapsed to a line.
|
||||
Line,
|
||||
/// 1/64 pt square 3,500,000 pt from the origin.
|
||||
Far,
|
||||
/// 40 pt square with a live Offset Path of -30 pt, which leaves nothing.
|
||||
Inset,
|
||||
/// 40 pt square with a live Transform effect that adds one copy reflected about its center:
|
||||
/// the two outlines run opposite ways over the same area and fill nothing under nonzero.
|
||||
Mirrored,
|
||||
/// 40 pt square with a live Transform effect that scales it to 0.004 pt high, which still
|
||||
/// clips to a thin strip.
|
||||
Strip,
|
||||
}
|
||||
|
||||
/// A clipping group whose clipping path is a group of one path and an image with `frame`, then the
|
||||
/// document's `pathItems.removeAll()`.
|
||||
fn remove_all_beside_an_image(frame: Frame) {
|
||||
let flat = matches!(frame, Frame::Line | Frame::Inset | Frame::Mirrored);
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let image = s
|
||||
.edit("Place", |d, _| {
|
||||
let id = d.alloc_id();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "pic".into(),
|
||||
width: 4,
|
||||
height: 4,
|
||||
xf: match frame {
|
||||
Frame::Square | Frame::Inset | Frame::Mirrored | Frame::Strip => kurbo::Affine::scale(10.0),
|
||||
Frame::Line => kurbo::Affine::scale_non_uniform(10.0, 0.0),
|
||||
Frame::Far => kurbo::Affine::translate((3_500_000.0, 3_500_000.0)) * kurbo::Affine::scale(1.0 / 256.0),
|
||||
},
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(Some(mask), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
if frame == Frame::Inset {
|
||||
s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": -30}, "ids": [image.0], "item": null})).unwrap();
|
||||
}
|
||||
if frame == Frame::Mirrored {
|
||||
s.execute(
|
||||
"effect.apply",
|
||||
&json!({"effect": "distort.transform", "params": {"reflectX": true, "copies": 1, "reference": 4}, "ids": [image.0], "item": null}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
if frame == Frame::Strip {
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleV": 0.01}, "ids": [image.0], "item": null})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
if flat {
|
||||
assert_eq!(
|
||||
out[0],
|
||||
json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0))
|
||||
);
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
return;
|
||||
}
|
||||
assert_eq!(out, [json!(""), json!(0)]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(a).is_none() && d.node(b).is_none());
|
||||
assert!(d.node(outer).unwrap().clips());
|
||||
assert_eq!(d.parent_of(image), Some(mask));
|
||||
assert!(d.node(t).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() {
|
||||
for compound in [false, true] {
|
||||
|
||||
@@ -106,6 +106,7 @@ fn yes_to_the_confirm_turns_the_warning_off() {
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
profiles: (None, None),
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(s.script_dialog_turns_warning_off());
|
||||
|
||||
@@ -19,7 +19,7 @@ fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::canonicalize(&base).unwrap()
|
||||
crate::cmd::findfiles::plain(std::fs::canonicalize(&base).unwrap())
|
||||
}
|
||||
|
||||
fn write(path: &Path, bytes: &[u8]) {
|
||||
|
||||
@@ -10,6 +10,23 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[test]
|
||||
fn postscript_suffix_recognizes_windows_filename_aliases() {
|
||||
use crate::script::dom::postscript_name;
|
||||
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}proof.PS{suffix}");
|
||||
assert!(postscript_name(&name, true), "{name}");
|
||||
assert!(!postscript_name(&name, false), "{name}");
|
||||
}
|
||||
}
|
||||
for name in ["proof.pdf", "proof.ps\t", "proof.ps\u{a0}", "folder.ps/proof", "folder.ps\\proof"] {
|
||||
assert!(!postscript_name(name, true), "{name}");
|
||||
}
|
||||
assert!(postscript_name("proof.ps", false));
|
||||
}
|
||||
|
||||
/// A test's folder, removed when the test ends, a failed assertion included.
|
||||
struct Workspace(PathBuf);
|
||||
|
||||
@@ -42,6 +59,20 @@ fn folder(name: &str) -> Workspace {
|
||||
Workspace(std::fs::canonicalize(&base).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_is_removed_when_its_test_panics() {
|
||||
let base = folder("removed-on-panic");
|
||||
let path = base.to_path_buf();
|
||||
assert!(
|
||||
std::panic::catch_unwind(move || {
|
||||
let _held = base;
|
||||
panic!("a failed assertion");
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
/// A session whose scripts keep their data folders in `base/settings/Script Data`, with a
|
||||
/// 300 × 200 document of two artboards holding a rectangle.
|
||||
fn session(base: &Path) -> Session {
|
||||
@@ -81,6 +112,95 @@ fn pages(path: &Path) -> Vec<(f64, f64)> {
|
||||
info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_blank_assigned_range_clears_the_saved_range() {
|
||||
let base = folder("blank-range");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap();
|
||||
for (name, range) in [("empty.pdf", ""), ("spaces.pdf", " ")] {
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
o.jobOptions.artboardRange = '{}'; app.activeDocument.print(o);",
|
||||
quoted(&dir.join(name)),
|
||||
range
|
||||
),
|
||||
);
|
||||
assert_eq!(pages(&dir.join(name)).len(), s.active().unwrap().doc.artboards.len());
|
||||
}
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["range"], json!("1"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_uses_the_assigned_file_object_after_its_path_changes() {
|
||||
let base = folder("file-reference");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(), f = new File({}); o.jobOptions.file = f;
|
||||
vc.log(o.jobOptions.file === f); vc.log(f.changePath({}));
|
||||
app.activeDocument.print(o); vc.log(o.jobOptions.file === f);
|
||||
vc.log(f.rename('renamed.pdf')); app.activeDocument.print(o);
|
||||
o.jobOptions.file = null; vc.log(o.jobOptions.file == null);",
|
||||
quoted(&dir.join("old.pdf")),
|
||||
quoted(&dir.join("new.ps"))
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([true, true, true, true, true]));
|
||||
assert!(!dir.join("old.pdf").exists());
|
||||
assert!(!dir.join("new.ps").exists());
|
||||
assert!(std::fs::read(dir.join("renamed.pdf")).unwrap().starts_with(b"%PDF"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_custom_profile_requires_an_assigned_or_base_profile() {
|
||||
let base = folder("custom-profile-required");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let path = dir.join("custom.pdf");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
let script = format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
o.colorManagementOptions.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; app.activeDocument.print(o);",
|
||||
quoted(&path)
|
||||
);
|
||||
let error = failure(&mut s, &base, &script);
|
||||
assert!(error.contains("must name a color profile for CUSTOMPROFILE"), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
s.execute("print.setup", &json!({"settings": {"color": {"profile": "sRGB IEC61966-2.1"}}})).unwrap();
|
||||
logged(&mut s, &base, &script);
|
||||
assert!(std::fs::read(&path).unwrap().starts_with(b"%PDF"));
|
||||
let preset_script = script.replace("app.activeDocument.print(o);", "o.printPreset = '[Default]'; app.activeDocument.print(o);");
|
||||
let error = failure(&mut s, &base, &preset_script);
|
||||
assert!(error.contains("must name a color profile for CUSTOMPROFILE"), "{error}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_dot_ps_file_names_write_postscript() {
|
||||
let base = folder("dot-ps");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
for name in [".ps", ".PS"] {
|
||||
let path = dir.join(name);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&path)),
|
||||
);
|
||||
assert!(std::fs::read(&path).unwrap().starts_with(b"%!PS"));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
let base = folder("happy");
|
||||
@@ -108,6 +228,8 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
j.file = new File(dir + '/c.ps'); doc.print(o);\n\
|
||||
o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/level2.prn');\n\
|
||||
doc.print(o);\n\
|
||||
o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL3; j.file = new File(dir + '/level3.ps');\n\
|
||||
doc.print(o);\n\
|
||||
vc.log([app.printPresetsList[0], app.PPDFileList.length]);"
|
||||
),
|
||||
);
|
||||
@@ -120,9 +242,11 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies");
|
||||
assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4");
|
||||
let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap();
|
||||
assert!(ps.starts_with("%!PS") && !ps.contains("%%LanguageLevel: 2"), "a .ps name alone: {}", &ps[..ps.len().min(200)]);
|
||||
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a .ps name alone prints at PSLEVEL2: {}", &ps[..ps.len().min(200)]);
|
||||
let ps = std::fs::read_to_string(dir.join("level2.prn")).unwrap();
|
||||
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a level alone: {}", &ps[..ps.len().min(200)]);
|
||||
let ps = std::fs::read_to_string(dir.join("level3.ps")).unwrap();
|
||||
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 3"), "an assigned PSLEVEL3: {}", &ps[..ps.len().min(200)]);
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are");
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step");
|
||||
// The commands stay closed to vc.run, before and after a print.
|
||||
@@ -389,6 +513,92 @@ fn file_print_max_pages_composes_only_what_fits() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_print_job_file_can_be_read_and_assigned_to_another_job() {
|
||||
let base = folder("file-getter");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let path = dir.join("proof 100%.pdf");
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var first = new PrintJobOptions(), second = new PrintJobOptions();
|
||||
first.file = new File({}); second.file = first.file;
|
||||
vc.log([second.file instanceof File, second.file.fsName === first.file.fsName]);
|
||||
var o = new PrintOptions(); o.jobOptions = second; app.activeDocument.print(o);",
|
||||
quoted(&path)
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!([true, true]));
|
||||
assert!(!pages(&path).is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_scale_assignment_and_reflection_share_the_supported_range() {
|
||||
let base = folder("scale-range");
|
||||
let mut s = session(&base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var c = new PrintCoordinateOptions();
|
||||
var names = ['horizontalScale', 'verticalScale'];
|
||||
for (var i = 0; i < names.length; i++) {
|
||||
var name = names[i], info = c.reflect.find(name);
|
||||
c[name] = info.max;
|
||||
try { c[name] = info.max + 0.01; vc.log('accepted'); }
|
||||
catch (e) { vc.log([e.name, c[name] === info.max, info.max === 10000]); }
|
||||
}",
|
||||
);
|
||||
assert_eq!(out, json!([["RangeError", true, true], ["RangeError", true, true]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_fit_preserves_other_base_scaling_modes() {
|
||||
let base = folder("fit-false");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let boxes = |path: &Path| {
|
||||
let mut boxes = Vec::new();
|
||||
vectorcraft_pdf::import(&std::fs::read(path).unwrap()).unwrap().walk(|node| {
|
||||
if let Some(bounds) = node.path_data().and_then(|p| p.bounds()) {
|
||||
boxes.push(bounds);
|
||||
}
|
||||
});
|
||||
boxes
|
||||
};
|
||||
for mode in ["tileFull", "tileImageable", "custom", "fit"] {
|
||||
let settings = json!({"scaling": mode, "scale": {"width": 500, "height": 500}});
|
||||
s.execute("print.setup", &json!({"settings": settings})).unwrap();
|
||||
s.execute("print.presets.save", &json!({"name": "Base", "settings": settings})).unwrap();
|
||||
let override_settings = if mode == "fit" { json!({"scaling": "none"}) } else { json!({}) };
|
||||
let want = s.execute("file.print", &json!({"settings": override_settings, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
|
||||
for preset in [false, true] {
|
||||
if preset {
|
||||
s.execute("print.setup", &json!({"settings": {"scaling": "none"}})).unwrap();
|
||||
}
|
||||
let out = dir.join(format!("{mode}-{preset}.pdf"));
|
||||
let select = if preset { "o.printPreset = 'Base';" } else { "" };
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
{select} o.coordinateOptions.fitToPage = false; app.activeDocument.print(o);",
|
||||
quoted(&out)
|
||||
),
|
||||
);
|
||||
let expected = boxes(&dir.join("want.pdf"));
|
||||
assert!(!expected.is_empty());
|
||||
assert_eq!(boxes(&out), expected, "{mode}, preset: {preset}");
|
||||
assert_eq!(pages(&out).len() as u64, want["pages"].as_u64().unwrap());
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A job past `maxPages` is turned away before its raster effects are flattened.
|
||||
#[test]
|
||||
fn file_print_max_pages_turns_a_job_away_before_raster_effects_are_flattened() {
|
||||
@@ -439,6 +649,9 @@ fn print_options_refuse_bad_values() {
|
||||
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"),
|
||||
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"),
|
||||
("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"),
|
||||
("o.paperOptions.width = 36;", "RangeError", "width must be 0 or from 72 to 14400"),
|
||||
("o.paperOptions.height = 71.9;", "RangeError", "height must be 0 or from 72 to 14400"),
|
||||
("o.paperOptions.width = 72; o.paperOptions.width = 0; o.paperOptions.width = 1;", "RangeError", "width must be 0 or from 72"),
|
||||
("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"),
|
||||
("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"),
|
||||
("j.file = 'C:/out.pdf';", "TypeError", "file must be a File"),
|
||||
@@ -590,6 +803,68 @@ fn one_assigned_scale_factor_keeps_the_saved_other() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The pixel sizes of the images in the PDF at `path`.
|
||||
fn image_sizes(path: &Path) -> Vec<(u32, u32)> {
|
||||
let back = vectorcraft_pdf::import(&std::fs::read(path).unwrap()).unwrap();
|
||||
let mut sizes = vec![];
|
||||
back.walk(|n| {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
sizes.push((im.width, im.height));
|
||||
}
|
||||
});
|
||||
sizes
|
||||
}
|
||||
|
||||
/// `PrintJobOptions.bitmapResolution` sets the resolution Print as Bitmap prints at, as
|
||||
/// `advanced.bitmapResolution` does; 0 keeps the document's raster effects resolution.
|
||||
#[test]
|
||||
fn bitmap_resolution_sets_the_printed_image_size() {
|
||||
let base = folder("bitmap");
|
||||
let mut s = session(&base);
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let saved = s.execute("print.setup", &json!({})).unwrap()["settings"].clone();
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(), j = o.jobOptions;\n\
|
||||
vc.log(j.bitmapResolution);\n\
|
||||
j.printAsBitmap = true; j.printAllArtboards = false; j.artboardRange = '1';\n\
|
||||
j.bitmapResolution = 144; j.file = new File({}); app.activeDocument.print(o);\n\
|
||||
j.bitmapResolution = 0; j.file = new File({}); app.activeDocument.print(o);\n\
|
||||
vc.log(j.bitmapResolution);",
|
||||
quoted(&dir.join("a.pdf")),
|
||||
quoted(&dir.join("b.pdf"))
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([0, 0]));
|
||||
assert_eq!(image_sizes(&dir.join("a.pdf")), [(600, 400)], "a 300 by 200 pt artboard at 144 ppi");
|
||||
assert_eq!(image_sizes(&dir.join("b.pdf")), [(300, 200)], "at the raster effects resolution, 72 ppi");
|
||||
let settings = json!({"artboards": "range", "range": "1", "advanced": {"printAsBitmap": true, "bitmapResolution": 144}});
|
||||
s.execute("file.print", &json!({"settings": settings, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
|
||||
assert_eq!(image_sizes(&dir.join("want.pdf")), image_sizes(&dir.join("a.pdf")), "the same image as the command prints");
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "the saved settings stay as they are");
|
||||
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
|
||||
for (case, kind, part) in [
|
||||
("j.bitmapResolution = 9601;", "RangeError", "bitmapResolution must be from 0 to 9600"),
|
||||
("j.bitmapResolution = -1;", "RangeError", "bitmapResolution must be from 0 to 9600"),
|
||||
("j.bitmapResolution = NaN;", "TypeError", "bitmapResolution"),
|
||||
("j.bitmapResolution = Infinity;", "TypeError", "bitmapResolution"),
|
||||
("j.bitmapResolution = '300';", "TypeError", "bitmapResolution must be a finite number"),
|
||||
(
|
||||
&format!("{file} j.printAsBitmap = true; j.bitmapResolution = 0.5; app.activeDocument.print(o);"),
|
||||
"",
|
||||
"advanced.bitmapResolution must be 1–9600 ppi",
|
||||
),
|
||||
] {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions; {case}"));
|
||||
assert!(e.contains(kind) && e.contains(part), "{case}: {e}");
|
||||
}
|
||||
assert!(!dir.join("x.pdf").exists(), "nothing printed");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An assigned `artboardRange` replaces a saved range, an assigned `printArea` prints by artboard over
|
||||
/// saved settings that ignore the artboards, and two scale factors that differ by any amount print
|
||||
/// unlinked.
|
||||
@@ -614,14 +889,46 @@ fn assigned_job_and_scale_options_apply_over_the_saved_settings() {
|
||||
assert_eq!(print(&mut s, "ignore.pdf", ""), 1, "all the art as one page");
|
||||
assert_eq!(print(&mut s, "area.pdf", "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS;"), 2, "each artboard prints");
|
||||
assert_eq!(print(&mut s, "range-ignored.pdf", "o.jobOptions.artboardRange = '2';"), 1, "a range alone keeps ignoring the artboards");
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "width": 150})).unwrap();
|
||||
let area_range = "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS; o.jobOptions.artboardRange = '2';";
|
||||
assert_eq!(print(&mut s, "area-range.pdf", area_range), 1, "printArea with a range prints the range");
|
||||
let info = vectorcraft_pdf::info(&std::fs::read(dir.join("area-range.pdf")).unwrap(), None).unwrap();
|
||||
let trim = info.pages[0].boxes.iter().find(|(k, _)| *k == vectorcraft_pdf::CropTo::Trim).map(|(_, r)| *r).unwrap();
|
||||
assert_eq!((trim.width().round(), trim.height().round()), (150.0, 200.0), "the page is artboard 2");
|
||||
let scaled = "o.coordinateOptions.horizontalScale = 100; o.coordinateOptions.verticalScale = 100.0000000005;";
|
||||
assert!(print(&mut s, "scale.pdf", scaled) >= 1, "factors that differ by a tiny amount print unlinked");
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["artboards"], json!("ignore"), "the saved settings stay");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An assigned `position` places an untiled print even when the saved Print Tiling origin is
|
||||
/// placed; the saved origin stays.
|
||||
#[test]
|
||||
fn an_assigned_position_replaces_a_placed_tile_origin() {
|
||||
let base = folder("position");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let trim = |s: &mut Session, name: &str, body: &str| {
|
||||
let file = quoted(&dir.join(name));
|
||||
logged(
|
||||
s,
|
||||
&base,
|
||||
&format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({file}); {body} app.activeDocument.print(o);"),
|
||||
);
|
||||
let info = vectorcraft_pdf::info(&std::fs::read(dir.join(name)).unwrap(), None).unwrap();
|
||||
let b = info.pages[0].boxes.iter().find(|(k, _)| *k == vectorcraft_pdf::CropTo::Trim).map(|(_, r)| *r).unwrap();
|
||||
[b.x0, b.y0, b.x1, b.y1].map(f64::round)
|
||||
};
|
||||
let top_left = "o.coordinateOptions.position = PrintPosition.TRANSLATETOPLEFT;";
|
||||
s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap();
|
||||
let plain = trim(&mut s, "plain.pdf", top_left);
|
||||
s.execute("print.setup", &json!({"settings": {"tileOrigin": {"placed": true, "x": 100, "y": 0}}})).unwrap();
|
||||
assert_ne!(trim(&mut s, "placed.pdf", ""), plain, "the placed origin moves the art");
|
||||
assert_eq!(trim(&mut s, "assigned.pdf", top_left), plain, "the assigned position wins");
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["tileOrigin"]["placed"], json!(true), "the saved origin stays");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Each option group prints the PostScript `file.print` writes for the settings it maps to, and
|
||||
/// each of those settings changes the file.
|
||||
#[test]
|
||||
@@ -644,7 +951,8 @@ fn option_groups_print_what_their_settings_print() {
|
||||
assert!(text.starts_with("%!PS"), "{}: {}", path.display(), &text[..text.len().min(40)]);
|
||||
text.lines().filter(|l| !l.starts_with("%%CreationDate:")).collect::<Vec<_>>().join("\n")
|
||||
};
|
||||
s.execute("file.print", &json!({"format": "postscript", "path": dir.join("plain.ps").to_string_lossy()})).unwrap();
|
||||
// A script prints PostScript at level 2 unless `postScriptLevel` is assigned.
|
||||
s.execute("file.print", &json!({"format": "postscript", "level": 2, "path": dir.join("plain.ps").to_string_lossy()})).unwrap();
|
||||
let plain = undated(&dir.join("plain.ps"));
|
||||
let mut wrong = Vec::new();
|
||||
let cases = [
|
||||
@@ -667,7 +975,7 @@ fn option_groups_print_what_their_settings_print() {
|
||||
];
|
||||
for (i, (body, settings)) in cases.iter().enumerate() {
|
||||
let [want, got] = ["want", "got"].map(|name| dir.join(format!("{name}{i}.ps")));
|
||||
s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": want.to_string_lossy()})).unwrap();
|
||||
s.execute("file.print", &json!({"format": "postscript", "level": 2, "settings": settings, "path": want.to_string_lossy()})).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
|
||||
@@ -10,6 +10,41 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[test]
|
||||
fn export_extension_recognizes_windows_filename_aliases() {
|
||||
use crate::script::dom::with_extension;
|
||||
|
||||
for extension in ["svg", "svgz", "jpg", "jpeg", "png"] {
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase());
|
||||
assert_eq!(with_extension(&name, &[extension], true), name);
|
||||
assert_eq!(with_extension(&name, &[extension], false), format!("{name}.{extension}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(with_extension("drawing.JPEG ", &["jpg", "jpeg"], true), "drawing.JPEG ");
|
||||
assert_eq!(with_extension("drawing.svg ", &["svgz"], true), "drawing.svg .svgz");
|
||||
for name in ["drawing", "drawing.png\t", "drawing.png\u{a0}", "folder.png/drawing", "folder.png\\drawing"] {
|
||||
assert_eq!(with_extension(name, &["png"], true), format!("{name}.png"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_open_refuses_an_oversized_document() {
|
||||
let base = folder("oversized-open");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let input = dir.join("huge.svg");
|
||||
std::fs::File::create(&input).unwrap().set_len(crate::script::files::MAX_OPEN_BYTES + 1).unwrap();
|
||||
let before = s.documents().len();
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&input)));
|
||||
assert!(error.contains(crate::script::files::OPEN_TOO_LARGE), "{error}");
|
||||
assert_eq!(s.documents().len(), before);
|
||||
let out = logged(&mut s, &base, &format!("Folder.userData; var f = new File({}); vc.log([f.open('r'), f.error]);", quoted(&input)));
|
||||
assert_eq!(out, json!([[false, crate::script::files::TOO_LARGE]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_wrappers_report_encoder_warnings_without_changing_their_return_values() {
|
||||
for method in ["exportFile", "saveAs", "exportForScreens"] {
|
||||
@@ -209,6 +244,76 @@ fn quoted(p: &Path) -> String {
|
||||
serde_json::to_string(&p.to_string_lossy()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_description_limits_the_preflight_guarantee() {
|
||||
let params = crate::cmd::find_command("document.save").unwrap().params;
|
||||
assert!(params.contains("failure found before writing leaves every file unchanged"));
|
||||
assert!(params.contains("a later write failure can leave earlier files written"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn svg_save_and_export_refuse_resolved_destination_collisions() {
|
||||
let base = folder("svg-collision");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let pic = base.join("outside/pic.png");
|
||||
std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap();
|
||||
let svg = dir.join("a.svg");
|
||||
let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&svg));
|
||||
logged(&mut s, &base, &format!("Folder.userData; {export}"));
|
||||
s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap();
|
||||
let images: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect();
|
||||
assert_eq!(images.len(), 1);
|
||||
std::fs::remove_file(&images[0]).unwrap();
|
||||
std::os::unix::fs::symlink(&svg, &images[0]).unwrap();
|
||||
for call in [export.clone(), format!("app.activeDocument.saveAs(new File({}));", quoted(&svg))] {
|
||||
std::fs::write(&svg, "original").unwrap();
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; {call}"));
|
||||
assert!(error.contains("resolve to the same file"), "{error}");
|
||||
assert_eq!(std::fs::read(&svg).unwrap(), b"original");
|
||||
assert!(std::fs::symlink_metadata(&images[0]).unwrap().file_type().is_symlink());
|
||||
}
|
||||
// With no primary file yet, the image's link leads nowhere but still names the primary.
|
||||
std::fs::remove_file(&svg).unwrap();
|
||||
let error = s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap_err().to_string();
|
||||
assert!(error.contains("resolve to the same file"), "{error}");
|
||||
assert!(!svg.exists());
|
||||
// A script may not write through a link that leads nowhere at all.
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; {export}"));
|
||||
assert!(error.contains("resolve to the same file") || error.contains("access denied"), "{error}");
|
||||
assert!(!svg.exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn open_template_link_creates_an_untitled_copy() {
|
||||
let base = folder("template-link");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let target = dir.join("drawing.vectorcraft");
|
||||
s.execute("file.saveAs", &json!({"path": target.to_string_lossy()})).unwrap();
|
||||
let link = dir.join("drawing.vctemplate");
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let count = s.documents().len();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&link)));
|
||||
assert_eq!(s.documents().len(), count + 1);
|
||||
assert!(s.active().unwrap().path.is_none());
|
||||
assert_ne!(s.active().unwrap().title(), "drawing.vectorcraft");
|
||||
assert!(!s.active().unwrap().doc.template);
|
||||
let template = dir.join("source.vctemplate");
|
||||
std::fs::write(&template, std::fs::read(&target).unwrap()).unwrap();
|
||||
let document = dir.join("alias.vectorcraft");
|
||||
std::os::unix::fs::symlink(&template, &document).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&document)));
|
||||
assert!(s.active().unwrap().path.is_some());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
|
||||
let base = folder("happy");
|
||||
@@ -251,6 +356,99 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_as_selects_the_format_before_resolving_a_link() {
|
||||
let base = folder("save-link-format");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
for extension in ["svg", "svgz"] {
|
||||
let target = dir.join(format!("{extension}.vectorcraft"));
|
||||
let link = dir.join(format!("drawing.{extension}"));
|
||||
std::fs::write(&target, "original").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&link)));
|
||||
let bytes = std::fs::read(&target).unwrap();
|
||||
if extension == "svgz" {
|
||||
assert!(bytes.starts_with(&[0x1f, 0x8b]));
|
||||
} else {
|
||||
assert!(String::from_utf8(bytes).unwrap().contains("<svg"));
|
||||
}
|
||||
}
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let link = dir.join("drawing");
|
||||
std::fs::write(dir.join("target.svg"), "original").unwrap();
|
||||
std::os::unix::fs::symlink(dir.join("target.svg"), &link).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&link)));
|
||||
assert_eq!(s.active().unwrap().format, "vectorcraft");
|
||||
assert!(dir.join("target.svg").is_file());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_sidecar_directories_are_refused_before_any_output_changes() {
|
||||
let base = folder("svg-directory");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let pic = base.join("outside/pic.png");
|
||||
std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap();
|
||||
let svg = dir.join("a.svg");
|
||||
let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&svg));
|
||||
logged(&mut s, &base, &format!("Folder.userData; {export}"));
|
||||
s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap();
|
||||
let images: Vec<PathBuf> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect();
|
||||
assert_eq!(images.len(), 1);
|
||||
let image = &images[0];
|
||||
std::fs::remove_file(image).unwrap();
|
||||
std::fs::create_dir(image).unwrap();
|
||||
for save in [false, true] {
|
||||
std::fs::write(&svg, "original SVG").unwrap();
|
||||
let call = if save { format!("app.activeDocument.saveAs(new File({}));", quoted(&svg)) } else { export.clone() };
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; {call}"));
|
||||
assert!(error.contains("not a file"), "{call}: {error}");
|
||||
assert_eq!(std::fs::read_to_string(&svg).unwrap(), "original SVG");
|
||||
assert!(image.is_dir());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_export_and_open_report_command_warnings_in_the_console() {
|
||||
let base = folder("command-warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"app.documents.add(DocumentColorSpace.RGB, 100, 100);
|
||||
vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 50});
|
||||
vc.run('transparency.set', {opacity: 0.5}); app.activeDocument.pageItems[0].name = 'bad\\u0001name';",
|
||||
);
|
||||
for (command, format, method, call) in [
|
||||
("file.saveAs", "eps", "Document.saveAs", "app.activeDocument.saveAs(f);"),
|
||||
("document.export", "svg", "Document.exportFile", "app.activeDocument.exportFile(f, ExportType.SVG);"),
|
||||
] {
|
||||
let path = dir.join(format!("warnings.{format}"));
|
||||
let want = s.execute(command, &json!({"path": path.to_string_lossy(), "format": format})).unwrap();
|
||||
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("{method}: {}", w.as_str().unwrap())).collect();
|
||||
assert!(!warnings.is_empty(), "{command}: {want}");
|
||||
let report = run(&mut s, &base, &format!("Folder.userData; var f = new File({}); {call}", quoted(&path))).unwrap();
|
||||
assert_eq!(report["console"]["lines"], json!(warnings));
|
||||
}
|
||||
let svg = dir.join("missing-image.svg");
|
||||
std::fs::write(&svg, "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><image href='missing.png' width='50' height='50'/></svg>")
|
||||
.unwrap();
|
||||
let want = s.execute("document.open", &json!({"path": svg.to_string_lossy()})).unwrap();
|
||||
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("app.open: {}", w.as_str().unwrap())).collect();
|
||||
assert!(!warnings.is_empty(), "{want}");
|
||||
let report = run(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&svg))).unwrap();
|
||||
assert_eq!(report["console"]["lines"], json!(warnings));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripted_file_writes_log_command_warnings() {
|
||||
for (method, extension, call) in [("saveAs", "pdf", "d.saveAs(file)"), ("exportFile", "png", "d.exportFile(file, ExportType.PNG24)")] {
|
||||
@@ -262,7 +460,7 @@ fn scripted_file_writes_log_command_warnings() {
|
||||
let path = dir.join(format!("output.{extension}"));
|
||||
let out = run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument, file = new File({}); {call};", quoted(&path))).unwrap();
|
||||
assert!(path.is_file(), "{method}");
|
||||
let prefix = format!("{method}: ");
|
||||
let prefix = format!("Document.{method}: ");
|
||||
let lines = out["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|s| s.starts_with(&prefix) && s.contains("couldn't be decoded")), "{method}: {out}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
@@ -319,7 +517,7 @@ fn export_file_logs_encoder_warnings() {
|
||||
assert_eq!(r["log"], json!(["undefined"]));
|
||||
assert!(dir.join("warnings.svg").is_file());
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
let warning = "exportFile: Object names containing invalid XML characters were left out of SVG name attributes";
|
||||
let warning = "Document.exportFile: Object names containing invalid XML characters were left out of SVG name attributes";
|
||||
assert!(lines.iter().any(|line| line.as_str() == Some(warning)), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -338,7 +536,7 @@ fn save_as_logs_the_saves_warnings() {
|
||||
let r = run(&mut s, &base, &text).unwrap_or_else(|e| panic!("{text}: {e}"));
|
||||
assert_eq!(r["log"], json!(["undefined"]));
|
||||
let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default();
|
||||
let warned = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ") && l.contains("keeps the artwork"));
|
||||
let warned = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("Document.saveAs: ") && l.contains("keeps the artwork"));
|
||||
assert!(warned, "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -359,7 +557,7 @@ fn open_logs_warnings_for_an_unreadable_linked_image() {
|
||||
let r = run(&mut s, &base, &text).unwrap();
|
||||
assert_eq!(r["log"], json!(["Document"]));
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("open: ") && l.contains("missing.png")), "{lines:?}");
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("app.open: ") && l.contains("missing.png")), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
@@ -410,6 +608,27 @@ fn save_as_uses_the_link_name_extension_for_the_encoder() {
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_file_save_refuses_a_directory_before_replacing_the_primary_file() {
|
||||
let base = folder("save-directory");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
let path = dir.join("drawing.vectorcraft");
|
||||
let saved = s.execute("file.saveAs", &json!({"path": path.to_string_lossy(), "format": "vectorcraft", "separateArtboards": true})).unwrap();
|
||||
let files = saved["files"].as_array().unwrap();
|
||||
assert!(files.len() > 1, "{saved}");
|
||||
let primary = std::fs::read(&path).unwrap();
|
||||
let sidecar = files.iter().map(|v| PathBuf::from(v.as_str().unwrap())).find(|p| *p != path).unwrap();
|
||||
std::fs::remove_file(&sidecar).unwrap();
|
||||
std::fs::create_dir(&sidecar).unwrap();
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&path)));
|
||||
assert!(error.contains("not a file"), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), primary);
|
||||
assert!(sidecar.is_dir());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_template_preserves_the_document_file_and_saved_state() {
|
||||
let base = folder("templatecopy");
|
||||
@@ -1267,6 +1486,23 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
assert_eq!(s.active().unwrap().path, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logging_files_and_folders_reads_only_enumerable_own_properties() {
|
||||
let base = folder("log-file-folder");
|
||||
let mut s = session(&base);
|
||||
let text = "var f = new File('kept.svg'), d = new Folder('kept');\n\
|
||||
vc.log(f); vc.log(d); vc.log([f, {folder: d}]);\n\
|
||||
File.prototype.inherited = 'omit'; Folder.prototype.inherited = 'omit';\n\
|
||||
Object.defineProperty(f, 'hidden', {value: 'omit', enumerable: false});\n\
|
||||
Object.defineProperty(d, 'hidden', {value: 'omit', enumerable: false});\n\
|
||||
f.label = 'drawing'; d.count = 2;\n\
|
||||
vc.log(f); vc.log(d); vc.log([f, {folder: d}]);";
|
||||
let log = logged(&mut s, &base, text);
|
||||
let nested = json!([{"label": "drawing"}, {"folder": {"count": 2}}]);
|
||||
assert_eq!(log, json!([{}, {}, [{}, {"folder": {}}], {"label": "drawing"}, {"count": 2}, nested]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a
|
||||
/// plain object throw a `TypeError`, and a `File` whose hidden path property a script set keeps its
|
||||
/// own path, so nothing is written or opened at the path the script put there.
|
||||
@@ -1649,7 +1885,7 @@ fn a_saves_warnings_go_to_the_console() {
|
||||
);
|
||||
let r = run(&mut s, &base, &save).unwrap();
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("saveAs: "))), "{lines:?}");
|
||||
assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("Document.saveAs: "))), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
@@ -1989,7 +2225,7 @@ fn save_as_writes_its_warnings_to_the_console() {
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap();
|
||||
let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap();
|
||||
let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}");
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("Document.saveAs: ")), "{lines:?}");
|
||||
drop(base);
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ impl AsRef<Path> for Folder {
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path.
|
||||
fn folder(name: &str) -> Folder {
|
||||
let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}"));
|
||||
let base = std::fs::canonicalize(&*guard).unwrap();
|
||||
let base = crate::cmd::findfiles::plain(std::fs::canonicalize(&*guard).unwrap());
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
Folder { _guard: guard, path: base }
|
||||
}
|
||||
|
||||
@@ -1160,7 +1160,7 @@ fn place_reads_what_open_reads_and_text_files() {
|
||||
assert_eq!(PLACE_EXTS, [OPEN_EXTS, TEXT_EXTS, RTF_EXTS, DOCX_EXTS, DOC_EXTS].concat());
|
||||
let filters: Vec<_> = cmd::fileio::place_filters().collect();
|
||||
let word: (&str, &[&str]) = ("Word", &["docx", "doc"]);
|
||||
assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", PLACE_EXTS)), Some(&word)));
|
||||
assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", cmd::fileio::place_exts())), Some(&word)));
|
||||
assert_eq!(filters.get(filters.len() - 3..), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..]));
|
||||
assert!(
|
||||
!cmd::fileio::open_filters().any(|(_, exts)| ["txt", "rtf", "docx", "doc"].iter().any(|e| exts.contains(e))),
|
||||
|
||||
@@ -3712,12 +3712,20 @@ fn arb_dxf_entity() -> impl Strategy<Value = Vec<(i32, String)>> {
|
||||
"ATTRIB",
|
||||
"DIMENSION",
|
||||
"VIEWPORT",
|
||||
"REGION",
|
||||
]);
|
||||
let code = prop::sample::select(vec![
|
||||
2, 6, 7, 8, 10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 48, 50, 51, 60, 62, 66, 67, 70, 71, 72, 73, 74, 75, 76, 90, 91, 92, 93,
|
||||
94, 95, 96, 97, 210, 220, 230, 370, 420, 440, 450,
|
||||
1, 2, 3, 6, 7, 8, 10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 48, 50, 51, 60, 62, 66, 67, 70, 71, 72, 73, 74, 75, 76, 90, 91, 92,
|
||||
93, 94, 95, 96, 97, 210, 220, 230, 370, 420, 440, 450,
|
||||
]);
|
||||
let value = prop_oneof![arb_num(), Just("B".to_string()), Just("*U1".to_string()), Just(r"{\fA;x}\P%%c^".to_string())];
|
||||
let value = prop_oneof![
|
||||
arb_num(),
|
||||
Just("B".to_string()),
|
||||
Just("*U1".to_string()),
|
||||
Just(r"{\fA;x}\P%%c^".to_string()),
|
||||
Just("700 0 1 0".to_string()),
|
||||
Just("body $-1 -1 $-1 $0 $-1 $-1 #".to_string()),
|
||||
];
|
||||
(kind, prop::collection::vec((code, value), 0..24)).prop_map(|(k, g)| std::iter::once((0, k.to_string())).chain(g).collect())
|
||||
}
|
||||
|
||||
@@ -3731,6 +3739,107 @@ fn hostile_dxf(block: &[Vec<(i32, String)>], body: &[Vec<(i32, String)>]) -> Vec
|
||||
dxf_text(&all).into_bytes()
|
||||
}
|
||||
|
||||
/// A region's solid-modeler text data: one face whose loop is two lines and a quarter circle,
|
||||
/// (0, 0) to (100, 0), round to (0, 100) and back.
|
||||
const REGION_SAT: &str = "700 0 1 0
|
||||
4 Fuzz 3 ASM 4 none
|
||||
1 9.9999999999999995e-07 1e-10
|
||||
body $-1 -1 $-1 $1 $-1 $-1 #
|
||||
lump $-1 -1 $-1 $-1 $2 $0 #
|
||||
shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1 #
|
||||
face $-1 -1 $-1 $-1 $4 $2 $-1 $-1 forward single #
|
||||
loop $-1 -1 $-1 $-1 $5 $3 #
|
||||
coedge $-1 -1 $-1 $6 $7 $-1 $8 forward $4 $-1 #
|
||||
coedge $-1 -1 $-1 $7 $5 $-1 $9 forward $4 $-1 #
|
||||
coedge $-1 -1 $-1 $5 $6 $-1 $10 forward $4 $-1 #
|
||||
edge $-1 -1 $-1 $11 0 $12 1 $5 $-1 forward @7 unknown #
|
||||
edge $-1 -1 $-1 $12 0 $13 1 $6 $17 forward @7 unknown #
|
||||
edge $-1 -1 $-1 $13 0 $11 1 $7 $-1 forward @7 unknown #
|
||||
vertex $-1 -1 $-1 $8 $14 #
|
||||
vertex $-1 -1 $-1 $9 $15 #
|
||||
vertex $-1 -1 $-1 $10 $16 #
|
||||
point $-1 -1 $-1 0 0 0 #
|
||||
point $-1 -1 $-1 100 0 0 #
|
||||
point $-1 -1 $-1 0 100 0 #
|
||||
ellipse-curve $-1 -1 $-1 0 0 0 0 0 1 100 0 0 1 I I #
|
||||
End-of-ACIS-data
|
||||
";
|
||||
|
||||
/// [`REGION_SAT`]'s records as binary data: tagged values, type names in parts.
|
||||
fn region_sab() -> Vec<u8> {
|
||||
let mut b = b"ACIS BinaryFile".to_vec();
|
||||
for v in [700u32, 0, 1, 0] {
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
let string = |b: &mut Vec<u8>, tag: u8, s: &str| {
|
||||
b.push(tag);
|
||||
b.push(u8::try_from(s.len()).unwrap_or(0));
|
||||
b.extend(s.as_bytes());
|
||||
};
|
||||
for line in REGION_SAT.lines().skip(3).take_while(|l| !l.starts_with("End-of")) {
|
||||
let mut words = line.split_whitespace();
|
||||
let parts: Vec<&str> = words.next().unwrap_or_default().split('-').collect();
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
string(&mut b, if i + 1 == parts.len() { 0x0D } else { 0x0E }, p);
|
||||
}
|
||||
while let Some(w) = words.next() {
|
||||
match w {
|
||||
"#" => {}
|
||||
"forward" => b.push(0x0B),
|
||||
"reversed" => b.push(0x0A),
|
||||
w if w.starts_with('$') => {
|
||||
b.push(0x0C);
|
||||
b.extend(w[1..].parse::<i32>().unwrap_or(-1).to_le_bytes());
|
||||
}
|
||||
w if w.starts_with('@') => string(&mut b, 0x07, words.next().unwrap_or_default()),
|
||||
w => match w.parse::<f64>() {
|
||||
Ok(v) => {
|
||||
b.push(0x06);
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
Err(_) => string(&mut b, 0x07, w),
|
||||
},
|
||||
}
|
||||
}
|
||||
b.push(0x11);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A drawing with one REGION: `text` as its data in groups 1 (DXF 2000), or `binary` in the
|
||||
/// ACDSDATA section (DXF 2013).
|
||||
fn region_dxf(text: &str, binary: Option<&[u8]>) -> Vec<u8> {
|
||||
let version = if binary.is_some() { "AC1027" } else { "AC1015" };
|
||||
let mut p: Vec<(i32, String)> =
|
||||
[(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, version), (0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES"), (0, "REGION"), (5, "2A")]
|
||||
.iter()
|
||||
.map(|(c, v)| (*c, v.to_string()))
|
||||
.collect();
|
||||
p.extend([(8, "0".to_string()), (100, "AcDbEntity".into()), (100, "AcDbModelerGeometry".into()), (70, "1".into())]);
|
||||
p.extend(text.lines().map(|l| (1, l.to_string())));
|
||||
p.push((0, "ENDSEC".into()));
|
||||
if let Some(bytes) = binary {
|
||||
p.extend([(0, "SECTION"), (2, "ACDSDATA"), (0, "ACDSRECORD"), (320, "2A"), (2, "ASM_Data")].iter().map(|(c, v)| (*c, v.to_string())));
|
||||
p.push((94, bytes.len().to_string()));
|
||||
p.extend(bytes.chunks(127).map(|c| (310, c.iter().map(|b| format!("{b:02X}")).collect())));
|
||||
p.push((0, "ENDSEC".into()));
|
||||
}
|
||||
p.push((0, "EOF".into()));
|
||||
dxf_text(&p).into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_seeds_open_as_a_filled_path() {
|
||||
let o = vectorcraft_cad::ImportOptions::default();
|
||||
for bytes in [region_dxf(REGION_SAT, None), region_dxf("", Some(®ion_sab()))] {
|
||||
let r = vectorcraft_cad::import(&bytes, &o).expect("opens");
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("REGION")), "{:?}", r.warnings);
|
||||
let mut paths = 0;
|
||||
r.document.walk(|n: &vectorcraft_doc::Node| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })));
|
||||
assert_eq!(paths, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Import with every option at once, and place it; whatever comes back must render and export.
|
||||
fn survive_dxf(what: &str, bytes: &[u8], fit: bool) -> Result<(), TestCaseError> {
|
||||
let o = vectorcraft_cad::ImportOptions { fit, center: !fit, merge_layers: fit, ..Default::default() };
|
||||
@@ -3784,6 +3893,23 @@ proptest! {
|
||||
bytes.truncate(cut.max(8));
|
||||
survive_dxf("mutated dxf", &bytes, cut % 2 == 0)?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxf_mutated_regions_never_panic(
|
||||
binary in any::<bool>(),
|
||||
cut in 0usize..2_000,
|
||||
edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec![b'0', b'1', b'9', b'-', b'.', b'e', b'$', b'#', b' ', b'@', 0xFF, 0x0C])), 0..12),
|
||||
) {
|
||||
let mut data = if binary { region_sab() } else { REGION_SAT.as_bytes().to_vec() };
|
||||
for &(at, b) in &edits {
|
||||
let n = data.len();
|
||||
// Text stays ASCII, as group values are.
|
||||
data[at % n] = if binary || (b' '..0x80).contains(&b) { b } else { b' ' };
|
||||
}
|
||||
data.truncate(cut.max(8));
|
||||
let bytes = if binary { region_dxf("", Some(&data)) } else { region_dxf(&String::from_utf8_lossy(&data), None) };
|
||||
survive_dxf("mutated region", &bytes, cut % 2 == 0)?;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Windows metafiles: opened, placed and pasted ----------
|
||||
|
||||
@@ -401,7 +401,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
// The print option classes and the enumerations of printing.
|
||||
(
|
||||
"",
|
||||
"FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
|
||||
"FontSubstitutionPolicy PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
|
||||
PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \
|
||||
PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \
|
||||
PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \
|
||||
@@ -464,7 +464,6 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
postScriptLevel= shadingResolution shadingResolution= typename",
|
||||
),
|
||||
("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"),
|
||||
("PageMarksTypes.", "Japanese Roman"),
|
||||
("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"),
|
||||
("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"),
|
||||
("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"),
|
||||
|
||||
Reference in new issue
Block a user