mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 02:44:24 +01:00
Merge main into fix/batch-override-export-for-screens-folder
This commit is contained in:
commit
33ea3f5300
1615 files changed
+291763
-130963
No files matched your search
@@ -3,13 +3,14 @@
|
||||
pub(crate) mod appearance;
|
||||
mod assets;
|
||||
mod attributes;
|
||||
pub mod brushlib;
|
||||
mod brushsym;
|
||||
mod buildcmds;
|
||||
pub mod clipboard;
|
||||
mod colorcmds;
|
||||
pub mod colormgmt;
|
||||
pub mod colortheme;
|
||||
mod create;
|
||||
pub(crate) mod create;
|
||||
mod css;
|
||||
mod cut;
|
||||
pub(crate) mod dimension;
|
||||
@@ -28,6 +29,7 @@ pub mod flatten;
|
||||
pub mod fontfiles;
|
||||
mod fonts;
|
||||
pub(crate) mod freeform;
|
||||
pub mod globaledit;
|
||||
pub(crate) mod gradient;
|
||||
pub(crate) mod graph;
|
||||
mod halftone;
|
||||
@@ -47,18 +49,19 @@ pub(crate) mod menucmds;
|
||||
pub(crate) mod newart;
|
||||
pub mod newdoc;
|
||||
mod object;
|
||||
pub(crate) mod objects_on_path;
|
||||
mod opacitymask;
|
||||
mod overprint;
|
||||
mod package;
|
||||
pub mod package;
|
||||
mod paint;
|
||||
mod panelcmds;
|
||||
pub mod params;
|
||||
mod path;
|
||||
mod pathops;
|
||||
pub(crate) mod pathops;
|
||||
mod patterncmds;
|
||||
pub mod pdfcmds;
|
||||
pub mod perspgrid;
|
||||
pub(crate) mod place;
|
||||
pub mod place;
|
||||
pub mod plugin;
|
||||
pub mod prefscmds;
|
||||
pub mod print;
|
||||
@@ -78,6 +81,7 @@ mod style;
|
||||
pub mod stylelib;
|
||||
mod swatch;
|
||||
pub mod swatchlib;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
mod textedit;
|
||||
pub mod textstyles;
|
||||
@@ -181,6 +185,10 @@ pub fn can_undo(s: &Session) -> std::result::Result<(), String> {
|
||||
pub fn can_redo(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().filter(|d| !d.history.redo.is_empty()).map(|_| ()).ok_or_else(|| "nothing to redo".into())
|
||||
}
|
||||
/// The active document has a step to undo or to redo (Clear History).
|
||||
pub fn can_clear_history(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().filter(|d| !d.history.undo.is_empty() || !d.history.redo.is_empty()).map(|_| ()).ok_or_else(|| "no history to clear".into())
|
||||
}
|
||||
pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if s.clipboard.is_empty() { Err("clipboard is empty".into()) } else { Ok(()) }
|
||||
@@ -209,6 +217,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(object::specs());
|
||||
v.extend(path::specs());
|
||||
v.extend(select::specs());
|
||||
v.extend(globaledit::specs());
|
||||
v.extend(wand::specs());
|
||||
v.extend(paint::specs());
|
||||
// Split out of `paint` (M3.8); kept next to it so lists in registry order (the command
|
||||
@@ -253,6 +262,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(brushsym::specs());
|
||||
v.extend(patterncmds::specs());
|
||||
v.extend(intertwine::specs());
|
||||
v.extend(objects_on_path::specs());
|
||||
v.extend(prefscmds::specs());
|
||||
v.extend(distortcmds::specs());
|
||||
v.extend(paint::proxy_specs());
|
||||
@@ -261,6 +271,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(freeform::specs());
|
||||
v.extend(flatten::specs());
|
||||
v.extend(stylelib::specs());
|
||||
v.extend(symbollib::specs());
|
||||
v.extend(brushlib::specs());
|
||||
v.extend(library::specs());
|
||||
v.extend(expand::specs());
|
||||
v.extend(attributes::specs());
|
||||
@@ -312,20 +324,42 @@ pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 {
|
||||
pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
|
||||
p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`")))
|
||||
}
|
||||
/// Error unless each of `keys` that `p` gives is a number (or null): an optional number read with
|
||||
/// [`f64_or`] would otherwise fall back to its default for a string such as `"60 mm"` (#1952).
|
||||
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other
|
||||
/// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}".
|
||||
pub(crate) fn number_or(p: &Value, key: &str, default: f64, cmd: &str) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
}
|
||||
}
|
||||
/// Error unless each of `keys` that `p` gives is a number (or null), as [`number_or`] reads them: an
|
||||
/// optional number read with [`f64_or`] would otherwise fall back to its default for a string such as
|
||||
/// `"60 mm"` (#1952).
|
||||
pub(crate) fn check_numbers(p: &Value, keys: &[&str], cmd: &str) -> Result<()> {
|
||||
for key in keys {
|
||||
match p.get(*key) {
|
||||
None | Some(Value::Null) | Some(Value::Number(_)) => {}
|
||||
Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
}
|
||||
number_or(p, key, 0.0, cmd)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn bool_or(p: &Value, key: &str, default: bool) -> bool {
|
||||
p.get(key).and_then(Value::as_bool).unwrap_or(default)
|
||||
}
|
||||
/// The true or false `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any
|
||||
/// other value, such as `"false"`, is an error: "`{key}` must be true or false".
|
||||
pub(crate) fn switch_or(p: &Value, key: &str, default: bool, cmd: &str) -> Result<bool> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, format!("`{key}` must be true or false"))),
|
||||
}
|
||||
}
|
||||
/// Error unless each of `keys` that `p` gives is true or false (or null), as [`switch_or`] reads
|
||||
/// them.
|
||||
pub(crate) fn check_switches(p: &Value, keys: &[&str], cmd: &str) -> Result<()> {
|
||||
for key in keys {
|
||||
switch_or(p, key, false, cmd)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> {
|
||||
p.get(key).and_then(Value::as_str)
|
||||
}
|
||||
@@ -335,6 +369,26 @@ pub(crate) fn id_param(p: &Value, key: &str) -> Option<NodeId> {
|
||||
pub(crate) fn ids_param(p: &Value, key: &str) -> Option<Vec<NodeId>> {
|
||||
p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(NodeId).collect())
|
||||
}
|
||||
/// The objects `p` gives `command`: its `ids`, else its `id` as `ids` of one (as [`targets`] reads
|
||||
/// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error,
|
||||
/// never the selection. `None` when it gives neither (or gives them as `null`).
|
||||
pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> {
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
return checked_ids_param(s, p, "ids", command).map(Some);
|
||||
}
|
||||
match p.get("id").filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
// A step reference a batch couldn't resolve, as `targets` reports it, under the command.
|
||||
Some(Value::String(r)) if r.starts_with('$') => {
|
||||
Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
|
||||
}
|
||||
Some(v) => Ok(Some(vec![checked_id(s, v, command)?])),
|
||||
}
|
||||
}
|
||||
/// `v` as an index, a count or a byte offset: past `usize::MAX` reads as `usize::MAX`, past the end of any list.
|
||||
pub(crate) fn index(v: u64) -> usize {
|
||||
usize::try_from(v).unwrap_or(usize::MAX)
|
||||
}
|
||||
/// Validate all explicit targets before a command changes the document or selection.
|
||||
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
|
||||
let values =
|
||||
@@ -445,10 +499,12 @@ pub(crate) fn ok() -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Leaves whose appearance a paint command changes: groups and layers expand to their contents,
|
||||
/// and compound paths own their children's appearance.
|
||||
/// and compound paths own their children's appearance, so a member stands for its compound path
|
||||
/// (#3692), which is listed once.
|
||||
pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let d = &s.doc()?.doc;
|
||||
let compound = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
@@ -458,11 +514,13 @@ pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
out.push(c.id)
|
||||
}
|
||||
}),
|
||||
_ => out.push(*id),
|
||||
_ => out.push(compound(*id).unwrap_or(*id)),
|
||||
}
|
||||
}
|
||||
let comp: Vec<NodeId> = out.iter().filter(|id| matches!(d.node(**id).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).copied().collect();
|
||||
out.retain(|id| !comp.iter().any(|c| d.parent_of(*id) == Some(*c)));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
out.retain(|id| seen.insert(*id));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -480,6 +538,7 @@ pub(crate) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String {
|
||||
}
|
||||
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
@@ -496,7 +555,7 @@ pub(crate) fn date_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Optio
|
||||
/// no clock). It joins the running command's journal entry as `key`, so a replay of the journal
|
||||
/// gives the same date whenever it runs (an action leaves it out: [`crate::Session::journal_for_action`]).
|
||||
pub(crate) fn clock_date(s: &mut Session, key: &str, given: Option<Option<i64>>) -> Option<i64> {
|
||||
let t = given.unwrap_or_else(vectorcraft_doc::metadata::now_unix);
|
||||
let t = given.unwrap_or_else(vectorcraft_doc::metadata::output_time);
|
||||
s.note_journal(key, serde_json::json!(t));
|
||||
t
|
||||
}
|
||||
@@ -507,6 +566,9 @@ pub use opacitymask::TransparencyInfo;
|
||||
/// Eyedropper Options (`Prefs::eyedropper`).
|
||||
pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, StrokeAttrs};
|
||||
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]).
|
||||
pub use overprint::AttributesInfo;
|
||||
|
||||
@@ -519,6 +581,9 @@ pub use flatten::FlattenerPreset;
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
|
||||
pub use buildcmds::live_paint_gaps;
|
||||
|
||||
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
|
||||
/// They run as before but the command palette leaves them out (it lists the command once).
|
||||
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
|
||||
@@ -15,10 +15,13 @@
|
||||
//! layer's own fills and strokes paint its members' geometry and its effects apply to them as one
|
||||
//! piece; the Contents row (type: Characters) is the slot that says which of its fills and strokes
|
||||
//! paint below the members and which above ([`Appearance::contents_at`], moved by
|
||||
//! `appearance.moveItem {from: "contents"}`).
|
||||
//! `appearance.moveItem {from: "contents"}`). An image's own fills and strokes paint only the
|
||||
//! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the
|
||||
//! image as its Contents row says; new ones go right below that row.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::appearance::SharedStack;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
@@ -35,8 +38,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"appearance.addFill",
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack (a copy of its top fill; type without one: its characters' fill; else the default fill)",
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -44,8 +47,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"appearance.addStroke",
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack (a copy of its top stroke, else the default stroke)",
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row (a copy of its top stroke, else the default stroke)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -72,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} edit one fill/stroke of each target object's own appearance stack",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -81,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?} remove those fills/strokes from each target object's own stack",
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -99,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (one `index` only; default: right above it, as Alt-dragging a row places it), ids?|id?, target?} copy fills/strokes with their effects",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (one `index` only; default: right above it, as Alt-dragging a row places it; not with aligned rows of a mixed selection), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -108,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", to, contents?: count, ids?|id?, target?} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -117,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: the selection), the fill, stroke and weight also to the paint defaults; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead; `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead; `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -201,8 +204,11 @@ pub(crate) enum ItemTarget {
|
||||
/// The topmost fill or stroke (for effects: the object-level effects).
|
||||
Top,
|
||||
/// Item `index`. `explicit`: named by the `item` param, so it must exist and be of the edited
|
||||
/// kind; otherwise it is the panel's active item, which applies only where it fits.
|
||||
Item { index: usize, explicit: bool },
|
||||
/// kind; otherwise it is the panel's active item, which applies only where it fits. `aligned`:
|
||||
/// `index` is a row of the first target's stack, and each other target edits the item equal to
|
||||
/// it there ([`ItemTarget::per_target`]): the active item always is (it is a row of the first
|
||||
/// selected object's stack), an explicit one with `aligned: true`.
|
||||
Item { index: usize, explicit: bool, aligned: bool },
|
||||
}
|
||||
|
||||
/// Parse the `item` param of `cmd` (see the module docs).
|
||||
@@ -216,11 +222,11 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re
|
||||
Some(Value::Null) => Ok(ItemTarget::Top),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.map(|i| ItemTarget::Item { index: i as usize, explicit: true })
|
||||
.map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned: aligned(p) })
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))),
|
||||
// The active item is a row of the first selected object's own stack.
|
||||
None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top),
|
||||
None => Ok(s.appearance_item().map_or(ItemTarget::Top, |index| ItemTarget::Item { index, explicit: false })),
|
||||
None => Ok(s.appearance_item().map_or(ItemTarget::Top, |index| ItemTarget::Item { index, explicit: false, aligned: true })),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,17 +244,30 @@ impl ItemTarget {
|
||||
/// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted
|
||||
/// leaves (as without an active item) and vice versa. Explicit items are kept (and checked).
|
||||
pub(crate) fn of_kind(self, s: &Session, fill: bool) -> Self {
|
||||
let ItemTarget::Item { index, explicit: false } = self else { return self };
|
||||
let ItemTarget::Item { index, explicit: false, .. } = self else { return self };
|
||||
let fits =
|
||||
s.active().and_then(|st| st.doc.node(*st.selection.subjects().first()?)?.appearance.items.get(index).map(|it| it.is_fill() == fill));
|
||||
if fits == Some(true) { self } else { ItemTarget::Top }
|
||||
}
|
||||
|
||||
/// This target for each of `ids` in `d` (in their order): an aligned item (a row of the first
|
||||
/// target's stack) is, in each other target, the item equal to it there (see
|
||||
/// [`SharedStack`]); `None` for a target that has none, which the edit leaves alone. A row the
|
||||
/// targets don't share, and any other target, stands for itself in every target.
|
||||
pub(crate) fn per_target(self, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] };
|
||||
let Some(shared) = shared_stack(d, ids) else { return vec![Some(self); ids.len()] };
|
||||
if !shared.has_item(index) {
|
||||
return vec![Some(self); ids.len()];
|
||||
}
|
||||
(0..ids.len()).map(|k| shared.item_in(index, k).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect()
|
||||
}
|
||||
|
||||
/// The item of `ap` a fill (`fill`) or stroke edit changes; `None` = the topmost one.
|
||||
pub(crate) fn resolve(self, ap: &Appearance, fill: bool, cmd: &str) -> Result<Option<usize>> {
|
||||
match self {
|
||||
ItemTarget::Top => Ok(None),
|
||||
ItemTarget::Item { index, explicit } => match ap.item_of_kind(Some(index), fill) {
|
||||
ItemTarget::Item { index, explicit, .. } => match ap.item_of_kind(Some(index), fill) {
|
||||
None if explicit => Err(bad(
|
||||
cmd,
|
||||
match ap.items.get(index) {
|
||||
@@ -266,12 +285,45 @@ impl ItemTarget {
|
||||
match self {
|
||||
ItemTarget::Top => Ok(None),
|
||||
ItemTarget::Item { index, .. } if index < ap.items.len() => Ok(Some(index)),
|
||||
ItemTarget::Item { index, explicit: true } => Err(bad(cmd, format!("no appearance item {index}"))),
|
||||
ItemTarget::Item { index, explicit: true, .. } => Err(bad(cmd, format!("no appearance item {index}"))),
|
||||
ItemTarget::Item { explicit: false, .. } => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`),
|
||||
/// which each other target edits where it has them (see [`ItemTarget::per_target`])?
|
||||
pub(crate) fn aligned(p: &Value) -> bool {
|
||||
p.get("aligned").and_then(Value::as_bool).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// What the appearances of `ids` share, when there are several of them and they all exist.
|
||||
pub(crate) fn shared_stack(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Option<SharedStack> {
|
||||
if ids.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let aps: Vec<&Appearance> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect::<Option<_>>()?;
|
||||
Some(SharedStack::of(&aps))
|
||||
}
|
||||
|
||||
/// Do the appearances of `ids` differ (several objects whose stacks aren't all equal)?
|
||||
pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> bool {
|
||||
let mut aps = ids.iter().filter_map(|id| d.node(*id)).map(|n| &n.appearance);
|
||||
let Some(first) = aps.next() else { return false };
|
||||
aps.any(|a| a != first)
|
||||
}
|
||||
|
||||
/// Indices `idx` of the first target's items (aligned with `aligned`) in each of `ids`: the first
|
||||
/// target's own, and in each other one the items equal to them there (see [`SharedStack`]), each
|
||||
/// index on its own: one the targets don't share is left out of the others (never taken as the
|
||||
/// same index there). Not aligned, or one target: the same indices in each.
|
||||
pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec<Vec<usize>> {
|
||||
match shared_stack(d, ids).filter(|_| aligned) {
|
||||
Some(sh) => (0..ids.len()).map(|k| if k == 0 { idx.to_vec() } else { idx.iter().filter_map(|i| sh.item_in(*i, k)).collect() }).collect(),
|
||||
None => vec![idx.to_vec(); ids.len()],
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the `target` param asks for the contents of groups and layers (see the module docs).
|
||||
fn targets_contents(p: &Value) -> Result<bool> {
|
||||
match p.get("target") {
|
||||
@@ -350,9 +402,11 @@ pub(crate) fn edit_items_then(
|
||||
return Ok(());
|
||||
}
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = item.per_target(&before, ids);
|
||||
super::overprint::edit_counted(s, label, |d| {
|
||||
let mut edited = Vec::new();
|
||||
for id in ids {
|
||||
for (id, item) in ids.iter().zip(&per) {
|
||||
let Some(item) = item else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let index = item.resolve(&n.appearance, fill, cmd)?;
|
||||
f(n, index)?;
|
||||
@@ -370,8 +424,10 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_
|
||||
}
|
||||
|
||||
/// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the
|
||||
/// targeted item (on the first target object), else `default`.
|
||||
pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool) -> Result<bool> {
|
||||
/// targeted item (on the first target object), else `default`. A `stroke` other than true, false or
|
||||
/// null is an error of command `cmd`.
|
||||
pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result<bool> {
|
||||
check_switches(p, &["stroke"], cmd)?;
|
||||
if let Some(b) = p.get("stroke").and_then(Value::as_bool) {
|
||||
return Ok(b);
|
||||
}
|
||||
@@ -381,8 +437,9 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
|
||||
Ok(ids.first().and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, read with [`index`].
|
||||
pub(crate) fn index_param(p: &Value, key: &str, cmd: &str) -> Result<usize> {
|
||||
p.get(key).and_then(Value::as_u64).map(|i| i as usize).ok_or_else(|| bad(cmd, format!("missing integer `{key}`")))
|
||||
p.get(key).and_then(Value::as_u64).map(index).ok_or_else(|| bad(cmd, format!("missing integer `{key}`")))
|
||||
}
|
||||
|
||||
fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -408,6 +465,9 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
|
||||
let defaults = s.paint.clone();
|
||||
// Where the new item went in on the active item's object, when it is an image.
|
||||
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
|
||||
let mut inserted = None;
|
||||
s.edit(if fill { "Add New Fill" } else { "Add New Stroke" }, |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
@@ -429,11 +489,23 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
} else {
|
||||
AppearanceItem::Stroke(StrokeLayer::new(paint, n.appearance.stroke_width().max(1.0)))
|
||||
};
|
||||
n.appearance.items.push(item);
|
||||
if matches!(n.kind, NodeKind::Image(_)) {
|
||||
// On an image it goes right below the Contents row (the image).
|
||||
let k = n.appearance.contents_at();
|
||||
n.appearance.items.insert(k, item);
|
||||
n.appearance.set_contents_at(k + 1);
|
||||
if active == Some(*id) {
|
||||
inserted = Some(k);
|
||||
}
|
||||
} else {
|
||||
n.appearance.items.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
// The rows above the new item move up by one.
|
||||
s.remap_appearance_item(&ids, |a| Some(a + usize::from(inserted.is_some_and(|k| k <= a))));
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -468,7 +540,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if source == target {
|
||||
return Err(bad(C, "`source` and `target` are the same object"));
|
||||
}
|
||||
let copy = bool_or(p, "copy", false);
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
// When both objects come out as they were, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, if copy { "Copy Appearance" } else { "Move Appearance" }, |d| {
|
||||
@@ -478,7 +550,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
|
||||
ap.rebase_gradients(f, t);
|
||||
}
|
||||
// Only groups, layers and type have a Contents (Characters) row to keep a slot for.
|
||||
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
|
||||
if to.contents_label().is_none() {
|
||||
ap.contents_index = None;
|
||||
}
|
||||
@@ -530,6 +602,9 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let idx = index_param(p, "index", "appearance.setItem")?;
|
||||
super::paint::check_keep_model(p, "appearance.setItem")?;
|
||||
check_numbers(p, &["weight", "opacity"], "appearance.setItem")?;
|
||||
check_switches(p, &["visible"], "appearance.setItem")?;
|
||||
let paint = paint_from(s, p)?;
|
||||
let ids = appearance_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
@@ -539,8 +614,10 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When every object comes out as it was (for example, when none has item `index`), the document
|
||||
// and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &[idx], aligned(p));
|
||||
super::overprint::edit_counted(s, "Appearance", |d| {
|
||||
for id in &ids {
|
||||
for (id, at) in ids.iter().zip(&per) {
|
||||
let Some(&idx) = at.first() else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
if p.get("weight").is_none()
|
||||
&& let Some(pa) = &paint
|
||||
@@ -586,7 +663,7 @@ fn item_indices(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
let mut v = match p.get("indices") {
|
||||
Some(a) => a
|
||||
.as_array()
|
||||
.and_then(|a| a.iter().map(|x| x.as_u64().map(|i| i as usize)).collect::<Option<Vec<_>>>())
|
||||
.and_then(|a| a.iter().map(|x| x.as_u64().map(index)).collect::<Option<Vec<_>>>())
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or_else(|| bad(cmd, "`indices` must be a non-empty array of item indices"))?,
|
||||
None => vec![index_param(p, "index", cmd)?],
|
||||
@@ -602,9 +679,12 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When no object has an item at any of the indices, the document and its undo history stay as
|
||||
// they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &idx, aligned(p));
|
||||
super::overprint::edit_counted(s, "Remove Item", |d| {
|
||||
for id in &ids {
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
let mut idx = idx.clone();
|
||||
idx.sort_unstable();
|
||||
// From the top down, so the lower indices stay valid.
|
||||
for &i in idx.iter().rev() {
|
||||
n.appearance.remove_item(i);
|
||||
@@ -627,11 +707,18 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_targets(s, p, C)?;
|
||||
// Where the first object's copy landed (the active item lives in the first object's stack).
|
||||
let mut first_at = None;
|
||||
// Aligned rows of a mixed selection are copied right above themselves in each object.
|
||||
if aligned(p) && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() {
|
||||
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
|
||||
}
|
||||
let per = items_per_target(&s.doc()?.doc, &ids, &idx, aligned(p));
|
||||
s.edit("Duplicate Item", |d, _| {
|
||||
let mut any = false;
|
||||
for id in &ids {
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let ap = &mut n.appearance;
|
||||
let mut idx = idx.clone();
|
||||
idx.sort_unstable();
|
||||
// From the top down, so the lower indices stay valid.
|
||||
for &i in idx.iter().rev() {
|
||||
if let Some(item) = ap.items.get(i).cloned() {
|
||||
@@ -674,6 +761,10 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return move_contents(s, &ids, to);
|
||||
}
|
||||
let from = index_param(p, "from", C)?;
|
||||
// Where an aligned row would go in each of several different stacks isn't one place.
|
||||
if aligned(p) && appearances_differ(&s.doc()?.doc, &ids) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
}
|
||||
let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?;
|
||||
let mut landed = to;
|
||||
// When every object's stack comes out as it was, the document and its undo history stay as they
|
||||
@@ -717,7 +808,7 @@ fn move_contents(s: &mut Session, ids: &[NodeId], to: usize) -> Result<Value> {
|
||||
n.appearance.set_contents_at(to);
|
||||
slot.get_or_insert(n.appearance.contents_at());
|
||||
}
|
||||
slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers and type have a Contents (Characters) row"))?;
|
||||
slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?;
|
||||
Ok(count_changed(d, &before, ids))
|
||||
})?;
|
||||
Ok(json!({ "contents": slot }))
|
||||
@@ -739,11 +830,13 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// Sample enabled attributes, refusing object transparency that a text range cannot store.
|
||||
fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.copyFrom";
|
||||
let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let (reverse, append) = (bool_or(p, "reverse", false), bool_or(p, "append", false));
|
||||
let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?);
|
||||
let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?;
|
||||
let range = if !reverse && !append && p.get("ids").is_none() { super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b) } else { None };
|
||||
let selected = match ids_param(p, "ids") {
|
||||
Some(v) => outermost(&s.doc()?.doc, v),
|
||||
None => selected_roots(s)?,
|
||||
@@ -757,12 +850,38 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
targets.retain(|id| *id != src_id);
|
||||
let picked = Picked::of(s.doc()?.doc.node(src_id).ok_or(EngineError::NoNode(src_id))?);
|
||||
let range = range.filter(|(id, _, _)| targets.contains(id));
|
||||
// Character styles cannot represent object transparency. Refuse before even changing
|
||||
// paint defaults; applying it to the object would also alter the unselected characters.
|
||||
if let Some((id, _, _)) = range.filter(|_| attrs.appearance.transparency) {
|
||||
let target = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
if picked.opacity != 1.0 || picked.blend != BlendMode::Normal || target.opacity != 1.0 || target.blend != BlendMode::Normal {
|
||||
return Err(bad(
|
||||
C,
|
||||
"object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object",
|
||||
));
|
||||
}
|
||||
}
|
||||
if !reverse {
|
||||
picked.to_defaults(s, &attrs.appearance);
|
||||
}
|
||||
if targets.is_empty() || attrs.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
if let Some((id, start, end)) = range {
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, "Eyedropper", |d| {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
|
||||
let placed = picked.placed(Some(t.local_bounds()));
|
||||
vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs));
|
||||
if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) {
|
||||
t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone());
|
||||
}
|
||||
super::typecmd::refresh_bounds(t);
|
||||
Ok(count_changed(d, &before, &[id]))
|
||||
})?;
|
||||
return Ok(json!({ "ids": [id.0] }));
|
||||
}
|
||||
// When every target comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, "Eyedropper", |d| {
|
||||
@@ -824,6 +943,22 @@ impl Picked {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy character attributes and the enabled paint attributes through the same path for
|
||||
/// whole text objects and highlighted character ranges.
|
||||
fn run(&self, st: &mut CharStyle, placed: &Appearance, a: &EyedropperAttrs) {
|
||||
if let Some((cs, _)) = self.text.as_ref().filter(|_| a.character) {
|
||||
*st = CharStyle {
|
||||
fill: std::mem::take(&mut st.fill),
|
||||
stroke: std::mem::take(&mut st.stroke),
|
||||
stroke_width: st.stroke_width,
|
||||
overprint_fill: st.overprint_fill,
|
||||
overprint_stroke: st.overprint_stroke,
|
||||
..cs.clone()
|
||||
};
|
||||
}
|
||||
run_attrs(st, placed, &a.appearance);
|
||||
}
|
||||
|
||||
/// Apply attributes `a` to `n`. `append` adds the fills and strokes (and effects) on top of its
|
||||
/// stack instead. Type takes the paints on its characters, and character and paragraph
|
||||
/// attributes from type.
|
||||
@@ -843,19 +978,7 @@ impl Picked {
|
||||
let placed = self.placed(Some(t.local_bounds()));
|
||||
let text = self.text.as_ref();
|
||||
for r in &mut t.runs {
|
||||
if let Some((cs, _)) = text.filter(|_| a.character) {
|
||||
// The character attributes; the paints follow the appearance attributes.
|
||||
let st = &mut r.style;
|
||||
*st = CharStyle {
|
||||
fill: std::mem::take(&mut st.fill),
|
||||
stroke: std::mem::take(&mut st.stroke),
|
||||
stroke_width: st.stroke_width,
|
||||
overprint_fill: st.overprint_fill,
|
||||
overprint_stroke: st.overprint_stroke,
|
||||
..cs.clone()
|
||||
};
|
||||
}
|
||||
run_attrs(&mut r.style, &placed, ap);
|
||||
self.run(&mut r.style, &placed, a);
|
||||
}
|
||||
if let Some((_, para)) = text.filter(|_| a.paragraph) {
|
||||
// The source's first paragraph's attributes, on every paragraph.
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// `e` as an error of command `cmd` (for errors of the export underneath).
|
||||
fn of_cmd(cmd: &str, e: EngineError) -> EngineError {
|
||||
pub(crate) fn of_cmd(cmd: &str, e: EngineError) -> EngineError {
|
||||
match e {
|
||||
EngineError::BadParams { msg, .. } => bad(cmd, msg),
|
||||
e => e,
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
//! Brush libraries (Window → Brush Libraries, the Brushes panel's library button): read-only sets
|
||||
//! of brushes the library panel shows. A library is a document holding the brushes with the
|
||||
//! resources their art uses (patterns, symbols, swatches, graphic styles, images); saved, it is a
|
||||
//! native `.vectorcraft` file, which File › Open also opens. The built-in libraries are generated
|
||||
//! here ([`BUILTIN`]); User Defined ones are the `.vectorcraft` files in the user library folder
|
||||
//! ([`Libraries`]), and Other Library… loads the brushes of any document VectorCraft opens.
|
||||
//! `brush.addFromLibrary` copies brushes into the document; `brush.saveLibrary` writes the
|
||||
//! document's.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{self as brush, ArtBrush, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::brushsym::{apply_brush, brush_targets, roots, stroke_paint};
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::patterncmds::add_pattern;
|
||||
use super::swatch::str_list;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem};
|
||||
use super::*;
|
||||
|
||||
/// The extension of saved brush libraries: native documents.
|
||||
pub const BRUSHES_EXT: &str = vectorcraft_format::EXTENSION;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "brush.libraries",
|
||||
"Brush Libraries",
|
||||
[],
|
||||
None,
|
||||
"{} → {libraries: [{id, name, category: \"builtIn\"|\"user\" (User Defined: the .vectorcraft files in the user library folder, rescanned now)|\"loaded\" (brush.loadLibrary), count, path?}], userFolder} every brush library the library panel opens, in menu order",
|
||||
always,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
query "brush.library",
|
||||
"Brush Library",
|
||||
[],
|
||||
None,
|
||||
"{library: id or name} → {id, name, category, brushes: [{name, type}] (as brush.list)}",
|
||||
always,
|
||||
get
|
||||
),
|
||||
cmd!(
|
||||
"brush.addFromLibrary",
|
||||
"Add to Brushes",
|
||||
["Window", "Brush Libraries"],
|
||||
None,
|
||||
"{library: id or name, name? | names?: [brush names in the library] (default: all of it), apply?: false (also apply the first one to paths, as brush.apply does), ids?|id? (the paths apply takes; default the selected ones), swatchConflict? (as edit.paste)} copy library brushes into the document's Brushes as one undo step (with the apply; named Apply Brush when no brush is added and it only applies one), with the resources their art uses (patterns, symbols, swatches, graphic styles, images). A brush the document already has (same name and definition) isn't added again; a name another brush has gets a number (\"Ribbon 2\"). The first one becomes the current brush → {library, names: [each brush's name in the document], added: [names added], existing: [names already there], applied: [ids of the paths it was applied to]}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
cmd!(
|
||||
"brush.saveLibrary",
|
||||
"Save Brush Library…",
|
||||
["Window", "Brushes"],
|
||||
None,
|
||||
"{path?, names?: [brush names] (default: all), name?: library name (default: the document's), user?: false (save into the user library folder, listed under User Defined)} save the document's brushes, with the resources their art uses, as a brush library: a .vectorcraft document holding only them → {path, count, library?: id when saved to the user folder}; without path or user → {dataBase64: the file's bytes, count}",
|
||||
has_doc,
|
||||
save
|
||||
),
|
||||
cmd!(
|
||||
"brush.loadLibrary",
|
||||
"Other Library…",
|
||||
["Window", "Brush Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load the brushes of any document VectorCraft opens (see document.formats; one without brushes of its own has the default ones), a saved brush library included, for the library panel (Window → Brush Libraries lists it until the app quits; a file of the user library folder, or a file with the same bytes as one there, opens as that User Defined library) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// A brush library: its name, its brushes (in panel order) and a document holding them with the
|
||||
/// resources their art uses; the document has no art of its own.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BrushLibrary {
|
||||
pub name: String,
|
||||
pub brushes: Vec<Brush>,
|
||||
pub doc: Document,
|
||||
}
|
||||
|
||||
impl Default for BrushLibrary {
|
||||
fn default() -> Self {
|
||||
Self { name: String::new(), brushes: vec![], doc: Document::new(100.0, 100.0) }
|
||||
}
|
||||
}
|
||||
|
||||
impl BrushLibrary {
|
||||
pub fn len(&self) -> usize {
|
||||
self.brushes.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.brushes.is_empty()
|
||||
}
|
||||
pub fn brush(&self, name: &str) -> Option<&Brush> {
|
||||
self.brushes.iter().find(|b| b.name == name)
|
||||
}
|
||||
|
||||
/// Document `src`'s brushes `names` (empty: all of them, in panel order) as a library named
|
||||
/// `name`: the brushes and every resource their art uses.
|
||||
pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result<Self, String> {
|
||||
let all = brush::library(src);
|
||||
if let Some(n) = names.iter().find(|n| !all.iter().any(|b| b.name == **n)) {
|
||||
return Err(format!("no brush `{n}`"));
|
||||
}
|
||||
let picked = all.iter().filter(|b| names.is_empty() || names.contains(&b.name));
|
||||
let clip = Clipboard::gather(src, picked.map(|b| stroke(&b.name)).collect());
|
||||
let mut doc = clip.to_document();
|
||||
for l in &mut doc.layers {
|
||||
if let Some(ch) = Arc::make_mut(l).children_mut() {
|
||||
ch.clear();
|
||||
}
|
||||
}
|
||||
// The brushes picked and those their art paints with, in the panel order of the document
|
||||
// they came from.
|
||||
let brushes: Vec<Brush> = all.into_iter().filter(|b| clip.brushes.iter().any(|c| c.name == b.name)).collect();
|
||||
brush::store(&mut doc, &brushes);
|
||||
doc.title = name.clone();
|
||||
Ok(Self { name, brushes, doc })
|
||||
}
|
||||
}
|
||||
|
||||
impl LibraryFile for BrushLibrary {
|
||||
const EXTS: &'static [&'static str] = &[BRUSHES_EXT];
|
||||
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String> {
|
||||
let doc = vectorcraft_format::load(bytes).map_err(|e| e.to_string())?;
|
||||
BrushLibrary::from_document(&doc, &[], stem.to_string())
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
/// User Defined and loaded brush libraries.
|
||||
pub type Libraries = super::swatchlib::Libraries<BrushLibrary>;
|
||||
|
||||
/// A path stroked with brush `name` (what the resource gathering follows).
|
||||
fn stroke(name: &str) -> Node {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
if let Some(st) = ap.stroke_mut() {
|
||||
st.brush = Some(name.into());
|
||||
}
|
||||
let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false);
|
||||
Node::path(NodeId(0), PathData::single(line), ap)
|
||||
}
|
||||
|
||||
// ---------- built-in libraries ----------
|
||||
|
||||
/// A library generated in code.
|
||||
pub struct BuiltinBrushLibrary {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
make: fn() -> BrushLibrary,
|
||||
}
|
||||
|
||||
/// The built-in brush libraries, in menu order: original brushes generated in code, one library
|
||||
/// per kind of brush.
|
||||
pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
|
||||
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
fn builtin_library(id: &str) -> Option<Arc<BrushLibrary>> {
|
||||
static MADE: LazyLock<Vec<Arc<BrushLibrary>>> = LazyLock::new(|| BUILTIN.iter().map(|b| Arc::new((b.make)())).collect());
|
||||
BUILTIN.iter().position(|b| b.id == id).and_then(|i| MADE.get(i).cloned())
|
||||
}
|
||||
|
||||
/// Library `name` of `brushes`, `doc` holding the resources their art uses.
|
||||
fn built(name: &str, mut doc: Document, brushes: Vec<Brush>) -> BrushLibrary {
|
||||
brush::store(&mut doc, &brushes);
|
||||
doc.title = name.into();
|
||||
BrushLibrary { name: name.into(), brushes, doc }
|
||||
}
|
||||
|
||||
fn filled(p: PathData, paint: Paint) -> Node {
|
||||
Node::path(NodeId(0), p, Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(paint))], ..Default::default() })
|
||||
}
|
||||
|
||||
fn black(p: PathData) -> Node {
|
||||
filled(p, Paint::solid(Color::BLACK))
|
||||
}
|
||||
|
||||
fn group(children: Vec<Node>) -> Node {
|
||||
Node::group(NodeId(0), children.into_iter().map(Arc::new).collect())
|
||||
}
|
||||
|
||||
fn polygon(pts: &[(f64, f64)]) -> PathData {
|
||||
let pts: Vec<Point> = pts.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
}
|
||||
|
||||
/// A band along y = `f(x)` for x in 0..`len`, `thick` pt thick, in `n` steps.
|
||||
fn band(len: f64, thick: f64, n: usize, f: impl Fn(f64) -> f64) -> PathData {
|
||||
let xs: Vec<f64> = (0..=n).map(|i| len * i as f64 / n as f64).collect();
|
||||
let mut pts: Vec<Point> = xs.iter().map(|&x| Point::new(x, f(x) - thick / 2.0)).collect();
|
||||
pts.extend(xs.iter().rev().map(|&x| Point::new(x, f(x) + thick / 2.0)));
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
}
|
||||
|
||||
/// An even-odd ring of radii `outer` and `inner` around `c`.
|
||||
fn ring(c: Point, outer: f64, inner: f64) -> Node {
|
||||
let disc = |r: f64| shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r));
|
||||
let children = [disc(outer), disc(inner)].into_iter().map(|p| Arc::new(Node::path(NodeId(0), p, Appearance::default()))).collect();
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Compound { children, rule: FillRule::EvenOdd });
|
||||
n.appearance = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK)))], ..Default::default() }.into();
|
||||
n
|
||||
}
|
||||
|
||||
fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's
|
||||
/// own pattern, Pinstripes.
|
||||
fn art_ribbons() -> BrushLibrary {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let stripe = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 1.5)), {
|
||||
let mut a = Appearance::default();
|
||||
a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::from_hex("#2f80c9").unwrap_or(Color::BLACK)))));
|
||||
a
|
||||
});
|
||||
add_pattern(&mut doc, PatternDef { tile: Rect::new(0.0, 0.0, 6.0, 3.0), ..PatternDef::new("Pinstripes", vec![Arc::new(stripe)]) });
|
||||
let notched = polygon(&[(0.0, -3.0), (100.0, -3.0), (95.0, 0.0), (100.0, 3.0), (0.0, 3.0), (5.0, 0.0)]);
|
||||
let double = group(vec![black(shapes::rectangle(Rect::new(0.0, -2.5, 100.0, -1.5))), black(shapes::rectangle(Rect::new(0.0, 1.5, 100.0, 2.5)))]);
|
||||
let wave = band(100.0, 1.6, 64, |x| 2.5 * (x / 100.0 * 4.0 * std::f64::consts::TAU).sin());
|
||||
// Round and thick at the start, tapering to a point.
|
||||
let teardrop = {
|
||||
let n = 48;
|
||||
let half = |x: f64| 3.5 * (1.0 - x / 100.0).powf(0.8) * (x / 4.0).min(1.0).sqrt();
|
||||
let xs = |i: usize| 100.0 * i as f64 / n as f64;
|
||||
let mut pts: Vec<Point> = (0..=n).map(xs).map(|x| Point::new(x, -half(x))).collect();
|
||||
pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, half(x))));
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
};
|
||||
let striped = {
|
||||
let mut n =
|
||||
filled(shapes::rectangle(Rect::new(0.0, -4.0, 100.0, 4.0)), Paint::Pattern { pattern: "Pinstripes".into(), xf: Default::default() });
|
||||
n.appearance.set_stroke(Paint::solid(Color::from_hex("#1d4f7c").unwrap_or(Color::BLACK)));
|
||||
n
|
||||
};
|
||||
let brushes = vec![
|
||||
art("Notched Ribbon", black(notched), Colorization::Tints),
|
||||
art("Double Line", double, Colorization::Tints),
|
||||
art("Wave", black(wave), Colorization::Tints),
|
||||
art("Teardrop", black(teardrop), Colorization::Tints),
|
||||
art("Striped Ribbon", striped, Colorization::None),
|
||||
];
|
||||
built("Art Ribbons", doc, brushes)
|
||||
}
|
||||
|
||||
fn nib(name: &str, angle: f64, roundness: f64, size: f64) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Calligraphic(Calligraphic { angle, roundness, size, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// Calligraphic Nibs: pen nibs of several shapes; Pressure Pen's size follows the pen pressure.
|
||||
fn calligraphic_nibs() -> BrushLibrary {
|
||||
let pressure = Brush {
|
||||
name: "Pressure Pen".into(),
|
||||
kind: BrushKind::Calligraphic(Calligraphic {
|
||||
angle: 30.0,
|
||||
roundness: 60.0,
|
||||
size: 5.0,
|
||||
variation: [0.0, 0.0, 4.0],
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
|
||||
}),
|
||||
};
|
||||
let brushes = vec![
|
||||
nib("Fine Nib", 45.0, 25.0, 2.0),
|
||||
nib("Broad Nib", 45.0, 15.0, 9.0),
|
||||
nib("Chisel", 0.0, 8.0, 6.0),
|
||||
nib("Round Pen", 0.0, 100.0, 4.0),
|
||||
pressure,
|
||||
];
|
||||
built("Calligraphic Nibs", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
fn border(name: &str, side: Node, corner: Option<Node>, fit: PatternFit) -> Brush {
|
||||
let kind = BrushKind::Pattern(PatternBrush { side, outer_corner: corner.clone(), inner_corner: corner, fit, ..Default::default() });
|
||||
Brush { name: name.into(), kind }
|
||||
}
|
||||
|
||||
/// An invisible rectangle that fixes a tile's width.
|
||||
fn spacer(r: Rect) -> Node {
|
||||
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
|
||||
}
|
||||
|
||||
/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles.
|
||||
fn pattern_borders() -> BrushLibrary {
|
||||
let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)]));
|
||||
let beads = group(vec![black(shapes::rectangle(Rect::new(0.0, -0.3, 8.0, 0.3))), black(shapes::ellipse(Rect::new(1.5, -2.5, 6.5, 2.5)))]);
|
||||
let dash_dot = group(vec![
|
||||
spacer(Rect::new(0.0, -1.0, 12.0, 1.0)),
|
||||
black(shapes::rounded_rectangle(Rect::new(0.5, -0.75, 6.5, 0.75), 0.75)),
|
||||
black(shapes::ellipse(Rect::new(8.5, -1.0, 10.5, 1.0))),
|
||||
]);
|
||||
let scallops = black(band(10.0, 1.0, 20, |x| -3.0 * (x / 10.0 * std::f64::consts::PI).sin()));
|
||||
let brushes = vec![
|
||||
border("Zigzag", zigzag, None, PatternFit::Stretch),
|
||||
border("Beads", beads, Some(ring(Point::ZERO, 3.5, 1.5)), PatternFit::Stretch),
|
||||
border("Dash Dot", dash_dot, None, PatternFit::AddSpace),
|
||||
border("Scallops", scallops, None, PatternFit::Stretch),
|
||||
];
|
||||
built("Pattern Borders", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
|
||||
}
|
||||
|
||||
/// Scatter Shapes: scatter brushes of shapes drawn here; Sparkles scatters the library's own
|
||||
/// symbol, Sparkle.
|
||||
fn scatter_shapes() -> BrushLibrary {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
// A four-pointed gold sparkle in the ±10 pt box symbol instances assume.
|
||||
let points: Vec<Point> = (0..8)
|
||||
.map(|i| {
|
||||
let r = if i % 2 == 0 { 10.0 } else { 2.5 };
|
||||
let a = std::f64::consts::FRAC_PI_4 * i as f64;
|
||||
Point::new(r * a.cos(), r * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let gold = Color::from_hex("#e0a526").unwrap_or(Color::BLACK);
|
||||
let sparkle = Node::path(doc.alloc_id(), PathData::single(SubPath::polyline(&points, true)), {
|
||||
let mut a = Appearance::default();
|
||||
a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(gold))));
|
||||
a
|
||||
});
|
||||
doc.symbols.push(Symbol { name: "Sparkle".into(), art: Arc::new(sparkle) });
|
||||
let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Sparkle".into(), xf: Affine::scale(0.3) });
|
||||
let random = |a: f64, b: f64| (a, b);
|
||||
let base = Scatter { colorization: Colorization::Tints, ..Default::default() };
|
||||
let brushes = vec![
|
||||
scatter(
|
||||
"Stars",
|
||||
black(shapes::star(Point::ZERO, 4.0, 1.7, 5, 0.0)),
|
||||
Scatter {
|
||||
size: random(70.0, 130.0),
|
||||
spacing: random(150.0, 220.0),
|
||||
scatter: random(-80.0, 80.0),
|
||||
rotation: random(-180.0, 180.0),
|
||||
..base.clone()
|
||||
},
|
||||
),
|
||||
scatter("Rings", ring(Point::ZERO, 2.5, 1.5), Scatter { spacing: (140.0, 140.0), ..base.clone() }),
|
||||
scatter(
|
||||
"Triangles",
|
||||
black(shapes::polygon(Point::ZERO, 3.0, 3, 0.0)),
|
||||
Scatter { spacing: (120.0, 120.0), rotation: (90.0, 90.0), rotation_relative_to_path: true, ..base.clone() },
|
||||
),
|
||||
scatter(
|
||||
"Sparkles",
|
||||
instance,
|
||||
Scatter {
|
||||
size: random(60.0, 140.0),
|
||||
spacing: random(110.0, 180.0),
|
||||
scatter: random(-60.0, 60.0),
|
||||
rotation: random(-45.0, 45.0),
|
||||
colorization: Colorization::None,
|
||||
..base
|
||||
},
|
||||
),
|
||||
];
|
||||
built("Scatter Shapes", doc, brushes)
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
|
||||
LibraryInfo { id: b.id.into(), name: b.name.into(), category: "builtIn" }
|
||||
}
|
||||
|
||||
/// Every brush library, in menu order: built-in, User Defined, loaded.
|
||||
pub fn libraries(s: &Session) -> Vec<LibraryInfo> {
|
||||
BUILTIN.iter().map(builtin_info).chain(s.brush_libraries.infos().cloned()).collect()
|
||||
}
|
||||
|
||||
/// Library `key` (an id, or a name in any case) with its info.
|
||||
pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>)> {
|
||||
if let Some(found) = s.brush_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
}
|
||||
let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id;
|
||||
library(s, &id)
|
||||
}
|
||||
|
||||
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<BrushLibrary>)> {
|
||||
let key = str_param(p, "library").ok_or_else(|| bad(cmd, "missing `library` (see brush.libraries)"))?;
|
||||
library(s, key).ok_or_else(|| bad(cmd, format!("no brush library `{key}` (see brush.libraries)")))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.brush_libraries.rescan();
|
||||
let libs: Vec<Value> = libraries(s)
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len());
|
||||
json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.brush_libraries.path(&l.id)})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.user_dir() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "brush.library")?;
|
||||
let brushes: Vec<Value> = lib.brushes.iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect();
|
||||
Ok(json!({"id": info.id, "name": info.name, "category": info.category, "brushes": brushes}))
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.addFromLibrary";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
let mut names = str_list(p, "names");
|
||||
names.extend(str_param(p, "name").map(str::to_string));
|
||||
if let Some(n) = names.iter().find(|n| lib.brush(n).is_none()) {
|
||||
return Err(bad(C, format!("no brush `{n}` in `{}`", lib.name)));
|
||||
}
|
||||
let mut picked: Vec<String> = if names.is_empty() { lib.brushes.iter().map(|b| b.name.clone()).collect() } else { names };
|
||||
// Each once, in the order asked for.
|
||||
let mut seen = HashSet::new();
|
||||
picked.retain(|n| seen.insert(n.clone()));
|
||||
let apply = bool_or(p, "apply", false);
|
||||
if apply && picked.is_empty() {
|
||||
return Err(bad(C, format!("`{}` has no brushes to apply", lib.name)));
|
||||
}
|
||||
let choices = SwatchChoices::parse(C, p)?;
|
||||
let clip = Clipboard::gather(&lib.doc, picked.iter().map(|n| stroke(n)).collect());
|
||||
// The typing `s.edit` would settle first is settled before the probe below, so the document
|
||||
// the edit installs is the one it starts from.
|
||||
if !s.previewing && super::typing_in_progress(s) {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let before: HashSet<String> = brush::library(&st.doc).into_iter().map(|b| b.name).collect();
|
||||
// A library brush's name in the document: its own, or the one the import gave it.
|
||||
let target = |renamed: &[Value], n: &str| -> String {
|
||||
let to = renamed.iter().find(|r| r["kind"] == "brush" && r["from"] == n).and_then(|r| r["to"].as_str());
|
||||
to.unwrap_or(n).to_string()
|
||||
};
|
||||
// Where the brushes land, worked out on a copy that the edit then installs: nothing to add and
|
||||
// nothing to apply is no edit, and a click that only applies brushes the document has is
|
||||
// named for that.
|
||||
let mut probe = (*st.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false);
|
||||
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
|
||||
let paths = if apply { brush_targets(&st.doc, &roots(s, p)?) } else { vec![] };
|
||||
let paint = stroke_paint(s);
|
||||
if imported.added > 0 || !paths.is_empty() {
|
||||
let label = if imported.added > 0 { "Add to Brushes" } else { "Apply Brush" };
|
||||
s.edit(label, |d, _| {
|
||||
*d = probe;
|
||||
if let Some(first) = doc_names.first() {
|
||||
d.unknown.insert(brush::CURRENT_KEY.into(), json!(first));
|
||||
apply_brush(d, &paths, first, &paint);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
} else if let Some(first) = doc_names.first() {
|
||||
s.execute("brush.setCurrent", &json!({ "name": first }))?;
|
||||
}
|
||||
let (added, existing): (Vec<&String>, Vec<&String>) = doc_names.iter().partition(|n| !before.contains(*n));
|
||||
let applied: Vec<u64> = paths.iter().map(|id| id.0).collect();
|
||||
Ok(json!({"library": info.id, "names": doc_names, "added": added, "existing": existing, "applied": applied}))
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.saveLibrary";
|
||||
let st = s.doc()?;
|
||||
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let lib = BrushLibrary::from_document(&st.doc, &str_list(p, "names"), name).map_err(|e| bad(C, e))?;
|
||||
if lib.is_empty() {
|
||||
return Err(bad(C, "the document has no brushes to save"));
|
||||
}
|
||||
let mut out = json!({ "count": lib.len() });
|
||||
let bytes = vectorcraft_format::save_file(&lib.doc);
|
||||
s.brush_libraries.write(p, &lib.name, BRUSHES_EXT, FileData::Binary(bytes), &mut out, C)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.loadLibrary";
|
||||
let (info, lib) = s.brush_libraries.load(p, C, |bytes, file| {
|
||||
let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
BrushLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e))
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,447 @@
|
||||
use super::*;
|
||||
|
||||
// ---------- brushes ----------
|
||||
|
||||
/// Brushable nodes (paths and compound paths) under `ids`.
|
||||
pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
n.walk(&mut |c| {
|
||||
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
|
||||
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
if own && !in_compound && !out.contains(&c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let list: Vec<Value> = brush::library(d).iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect();
|
||||
Ok(json!({ "brushes": list, "current": brush::current(d) }))
|
||||
}
|
||||
|
||||
pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = name_param(p, "brush.get")?;
|
||||
let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?;
|
||||
Ok(serde_json::to_value(b).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]).
|
||||
pub(super) fn brush_selection_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let art = selection_art(s, p)?;
|
||||
Ok(json!({ "art": art.map(|n| serde_json::to_value(&n).unwrap_or_default()) }))
|
||||
}
|
||||
|
||||
/// The stroke paint a brush gives paths without one: the current stroke colour, else black.
|
||||
pub(crate) fn stroke_paint(s: &Session) -> Paint {
|
||||
if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }
|
||||
}
|
||||
|
||||
/// Paint paths `ids` of `d` with brush `name` (a path without a stroke takes `stroke`).
|
||||
pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke: &Paint) {
|
||||
for id in ids {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
if n.appearance.stroke().is_none_or(|st| st.paint.is_none()) {
|
||||
n.appearance.set_stroke(stroke.clone());
|
||||
}
|
||||
if let Some(st) = n.appearance.stroke_mut() {
|
||||
if st.width <= 0.0 {
|
||||
st.width = 1.0;
|
||||
}
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn brush_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.apply";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
if brush::find(&s.doc()?.doc, &name).is_none() {
|
||||
return Err(bad(C, format!("no brush named `{name}`")));
|
||||
}
|
||||
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
|
||||
let stroke = stroke_paint(s);
|
||||
s.edit("Apply Brush", |d, _| {
|
||||
d.unknown.insert(brush::CURRENT_KEY.into(), json!(name));
|
||||
apply_brush(d, &ids, &name, &stroke);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
|
||||
s.edit("Remove Brush Stroke", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
for it in &mut n.appearance.items {
|
||||
if let AppearanceItem::Stroke(st) = it {
|
||||
st.brush = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
pub(super) fn brush_set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match str_param(p, "name") {
|
||||
Some(n) => {
|
||||
if brush::find(&s.doc()?.doc, n).is_none() {
|
||||
return Err(bad("brush.setCurrent", format!("no brush named `{n}`")));
|
||||
}
|
||||
set_unknown(s, brush::CURRENT_KEY, Some(json!(n)))?;
|
||||
}
|
||||
None => set_unknown(s, brush::CURRENT_KEY, None)?,
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The definition fields that `params` change field by field when the brush has them as objects:
|
||||
/// `{colorization: {method: "hueShift"}}` keeps the key color, and an art brush's `scale` with only
|
||||
/// `start` keeps `end`.
|
||||
const MERGED_FIELDS: [&str; 2] = ["colorization", "scale"];
|
||||
|
||||
fn merge(base: &mut Value, patch: &Value) {
|
||||
if let (Some(b), Some(pt)) = (base.as_object_mut(), patch.as_object()) {
|
||||
for (k, v) in pt {
|
||||
match (b.get_mut(k).and_then(Value::as_object_mut), v.as_object()) {
|
||||
(Some(inner), Some(fields)) if MERGED_FIELDS.contains(&k.as_str()) => {
|
||||
for (f, fv) in fields {
|
||||
inner.insert(f.clone(), fv.clone());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
b.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets brush `to` on the strokes in `items` that paint with brush `from`.
|
||||
fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) {
|
||||
for it in items {
|
||||
if let AppearanceItem::Stroke(st) = it
|
||||
&& st.brush.as_deref() == Some(from)
|
||||
{
|
||||
st.brush = to.map(str::to_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a stroke in `n` (its opacity masks included) paints with brush `name`.
|
||||
fn paints_with(n: &Node, name: &str) -> bool {
|
||||
let mut hit = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
hit |= m.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if st.brush.as_deref() == Some(name)));
|
||||
});
|
||||
hit
|
||||
}
|
||||
|
||||
/// Applies [`set_stroke_brush`] to every stroke in `n` and its opacity masks. Only the objects that
|
||||
/// hold such a stroke, and those that hold them, are copied.
|
||||
fn set_brush_in(n: &mut Node, from: &str, to: Option<&str>) {
|
||||
set_stroke_brush(&mut n.appearance.items, from, to);
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& paints_with(&mask.art, from)
|
||||
{
|
||||
set_brush_in(Arc::make_mut(&mut mask.art), from, to);
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if paints_with(c, from) {
|
||||
set_brush_in(Arc::make_mut(c), from, to);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the art a brush is made of ([`Brush::art`]) for editing.
|
||||
fn brush_art_mut(b: &mut Brush) -> Vec<&mut Node> {
|
||||
use vectorcraft_brush::BrushKind;
|
||||
match &mut b.kind {
|
||||
BrushKind::Scatter(s) => vec![&mut s.art],
|
||||
BrushKind::Art(a) => vec![&mut a.art],
|
||||
BrushKind::Pattern(p) => {
|
||||
std::iter::once(&mut p.side).chain([&mut p.outer_corner, &mut p.inner_corner, &mut p.start, &mut p.end].into_iter().flatten()).collect()
|
||||
}
|
||||
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets brush `to` (`None`: no brush) on every stroke that paints with brush `from`: in the art
|
||||
/// (opacity masks included), symbols, graph designs, pattern tiles and the tiles that pattern
|
||||
/// editing's Cancel puts back, graphic styles and the art of the brushes in `lib`.
|
||||
fn rename_brush_strokes(d: &mut Document, lib: &mut [Brush], from: &str, to: Option<&str>) {
|
||||
let trees = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.graph_designs.iter_mut().map(|g| &mut g.art));
|
||||
let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()));
|
||||
for n in trees.chain(patterns.flat_map(|p| &mut p.art)) {
|
||||
if paints_with(n, from) {
|
||||
set_brush_in(Arc::make_mut(n), from, to);
|
||||
}
|
||||
}
|
||||
for g in &mut d.graphic_styles {
|
||||
set_stroke_brush(&mut g.appearance.items, from, to);
|
||||
}
|
||||
for n in lib.iter_mut().flat_map(brush_art_mut) {
|
||||
set_brush_in(n, from, to);
|
||||
}
|
||||
}
|
||||
|
||||
fn save_library(s: &mut Session, label: &str, mut lib: Vec<Brush>, renames: &[(String, Option<String>)]) -> Result<()> {
|
||||
s.edit(label, |d, _| {
|
||||
for (from, to) in renames {
|
||||
rename_brush_strokes(d, &mut lib, from, to.as_deref());
|
||||
if brush::current(d).as_deref() == Some(from.as_str()) {
|
||||
match to {
|
||||
Some(t) => d.unknown.insert(brush::CURRENT_KEY.into(), json!(t)),
|
||||
None => d.unknown.remove(brush::CURRENT_KEY),
|
||||
};
|
||||
}
|
||||
}
|
||||
brush::store(d, &lib);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.new";
|
||||
let ty = str_param(p, "type").ok_or_else(|| bad(C, "missing `type`"))?;
|
||||
let art_key = match ty {
|
||||
"calligraphic" | "bristle" => None,
|
||||
"scatter" | "art" => Some("art"),
|
||||
"pattern" => Some("side"),
|
||||
o => return Err(bad(C, format!("unknown brush type `{o}`"))),
|
||||
};
|
||||
let mut lib = brush::library(&s.doc()?.doc);
|
||||
let given = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty());
|
||||
let base_name = given.map_or_else(|| format!("New {} Brush", ty[..1].to_uppercase() + &ty[1..]), str::to_string);
|
||||
let name = brush::unique_name(&lib, &base_name);
|
||||
if ty == "bristle" {
|
||||
bristle_name_fits(C, &name)?;
|
||||
}
|
||||
let mut v = json!({"name": name, "type": ty});
|
||||
if let Some(params) = p.get("params") {
|
||||
merge(&mut v, params);
|
||||
v["name"] = json!(name);
|
||||
v["type"] = json!(ty);
|
||||
}
|
||||
if let Some(k) = art_key
|
||||
&& v.get(k).is_none()
|
||||
{
|
||||
let art = selection_art(s, p)?.ok_or_else(|| bad(C, format!("{ty} brushes need selected art (or params.{k})")))?;
|
||||
if art.geometric_bounds().is_none_or(|b| b.width() <= 1e-6) {
|
||||
return Err(bad(C, "the selected art has no width"));
|
||||
}
|
||||
v[k] = serde_json::to_value(&art).unwrap_or_default();
|
||||
}
|
||||
lib.push(parse_brush(C, v)?);
|
||||
save_library(s, "New Brush", lib, &[])?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Refuses `name` for a bristle brush when it has more than [`Bristle::MAX_NAME_CHARS`] characters.
|
||||
fn bristle_name_fits(cmd: &str, name: &str) -> Result<()> {
|
||||
let (count, max) = (name.chars().count(), Bristle::MAX_NAME_CHARS);
|
||||
if count > max {
|
||||
return Err(bad(cmd, format!("a bristle brush name can have at most {max} characters: `{name}` has {count}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A brush definition from command params, its values kept within their ranges ([`Brush::from_json`]).
|
||||
fn parse_brush(cmd: &str, v: Value) -> Result<Brush> {
|
||||
Brush::from_json(v).map_err(|e| bad(cmd, format!("invalid brush: {e}")))
|
||||
}
|
||||
|
||||
pub(super) fn brush_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.delete";
|
||||
let names = names_param(p, C)?;
|
||||
let mut lib = brush::library(&s.doc()?.doc);
|
||||
if let Some(name) = names.iter().find(|n| !lib.iter().any(|b| &b.name == *n)) {
|
||||
return Err(bad(C, format!("no brush named `{name}`")));
|
||||
}
|
||||
lib.retain(|b| !names.contains(&b.name));
|
||||
let renames: Vec<(String, Option<String>)> = names.into_iter().map(|n| (n, None)).collect();
|
||||
save_library(s, "Delete Brush", lib, &renames)?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Moves the brushes in `name` or `names`, in that order, to index `to` among the brushes of their
|
||||
/// type in library order: before the first brush of that type at or after `to` that isn't moving,
|
||||
/// else after the last brush of that type that isn't moving. Brushes of different types, or a `type`
|
||||
/// that isn't theirs, are an error. A move that leaves the order as it was records no undo step.
|
||||
pub(super) fn brush_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.move";
|
||||
const WITHIN: &str = "brushes move only within their type";
|
||||
let names = names_param(p, C)?;
|
||||
check_numbers(p, &["to"], C)?;
|
||||
let to = match p.get("to").filter(|v| !v.is_null()) {
|
||||
Some(v) => Some(v.as_u64().map(|i| usize::try_from(i).unwrap_or(usize::MAX)).ok_or_else(|| bad(C, "`to` must be a whole number"))?),
|
||||
None => None,
|
||||
};
|
||||
let old = brush::library(&s.doc()?.doc);
|
||||
let mut lib = old.clone();
|
||||
// `names_param` refuses an empty list, so the loop sets `kind`.
|
||||
let mut kind = "";
|
||||
for name in &names {
|
||||
let b = lib.iter().find(|b| &b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
|
||||
if !kind.is_empty() && kind != b.kind.type_id() {
|
||||
return Err(bad(C, WITHIN));
|
||||
}
|
||||
kind = b.kind.type_id();
|
||||
}
|
||||
if p.get("type").filter(|v| !v.is_null()).is_some_and(|t| t.as_str() != Some(kind)) {
|
||||
return Err(bad(C, WITHIN));
|
||||
}
|
||||
let same: Vec<&Brush> = lib.iter().filter(|b| b.kind.type_id() == kind).collect();
|
||||
let before = anchor(&same, to, &names, |b| &b.name);
|
||||
let first = lib.iter().position(|b| names.contains(&b.name)).unwrap_or(lib.len());
|
||||
let mut items = vec![];
|
||||
for name in &names {
|
||||
if let Some(i) = lib.iter().position(|b| &b.name == name) {
|
||||
items.push(lib.remove(i));
|
||||
}
|
||||
}
|
||||
let at = match before {
|
||||
Some(a) => lib.iter().position(|b| b.name == a),
|
||||
None => lib.iter().rposition(|b| b.kind.type_id() == kind).map(|i| i + 1),
|
||||
};
|
||||
let at = at.unwrap_or(first).min(lib.len());
|
||||
lib.splice(at..at, items);
|
||||
if lib != old {
|
||||
save_library(s, "Move Brush", lib, &[])?;
|
||||
}
|
||||
Ok(json!({ "moved": names.len() }))
|
||||
}
|
||||
|
||||
/// Adds a copy of each brush in `name` or `names` at the end of the library. `newName`, given
|
||||
/// without `names`, names the copy.
|
||||
pub(super) fn brush_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.duplicate";
|
||||
let names = names_param(p, C)?;
|
||||
let before = brush::library(&s.doc()?.doc);
|
||||
let mut lib = before.clone();
|
||||
let mut out = vec![];
|
||||
for name in &names {
|
||||
let mut b = before.iter().find(|b| &b.name == name).cloned().ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
|
||||
let given = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && p.get("names").is_none());
|
||||
let new_name = given.map_or_else(|| format!("{} copy", name.trim()), str::to_string);
|
||||
b.name = brush::unique_name(&lib, &new_name);
|
||||
out.push(b.name.clone());
|
||||
lib.push(b);
|
||||
}
|
||||
save_library(s, "Duplicate Brush", lib, &[])?;
|
||||
Ok(if p.get("names").is_some() { json!({ "names": out }) } else { json!({ "name": out.first() }) })
|
||||
}
|
||||
|
||||
/// Adds the names of the brushes the strokes of `items` paint with to `out`.
|
||||
fn stroke_brushes(items: &[AppearanceItem], out: &mut Vec<String>) {
|
||||
for it in items {
|
||||
if let AppearanceItem::Stroke(st) = it
|
||||
&& let Some(b) = &st.brush
|
||||
{
|
||||
out.push(b.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the names of the brushes the strokes in `n` (its opacity masks included) paint with to
|
||||
/// `out`.
|
||||
fn art_brushes(n: &Node, out: &mut Vec<String>) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| stroke_brushes(&m.appearance.items, out));
|
||||
}
|
||||
|
||||
/// The brushes no stroke paints with. Strokes in the art (opacity masks included), symbols, graph
|
||||
/// designs, pattern tiles and graphic styles count, and so do the strokes in the art of every brush
|
||||
/// that a counted stroke paints with.
|
||||
pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let lib = brush::library(d);
|
||||
let mut todo = vec![];
|
||||
let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art));
|
||||
trees.chain(d.patterns.iter().flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo));
|
||||
d.graphic_styles.iter().for_each(|g| stroke_brushes(&g.appearance.items, &mut todo));
|
||||
let mut used = BTreeSet::new();
|
||||
while let Some(name) = todo.pop() {
|
||||
if !used.contains(&name) {
|
||||
lib.iter().filter(|b| b.name == name).flat_map(Brush::art).for_each(|n| art_brushes(n, &mut todo));
|
||||
used.insert(name);
|
||||
}
|
||||
}
|
||||
let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).filter(|n| !used.contains(*n)).collect();
|
||||
Ok(json!({ "names": names }))
|
||||
}
|
||||
|
||||
pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.options";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
let mut lib = brush::library(&s.doc()?.doc);
|
||||
let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
|
||||
let mut v = serde_json::to_value(&lib[i]).unwrap_or_default();
|
||||
if let Some(params) = p.get("params") {
|
||||
merge(&mut v, params);
|
||||
}
|
||||
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string);
|
||||
if let Some(nn) = &new_name {
|
||||
if lib.iter().any(|b| &b.name == nn) {
|
||||
return Err(bad(C, format!("a brush named `{nn}` exists")));
|
||||
}
|
||||
// A `newName` that only trims the white space around the saved name is taken at any length.
|
||||
if matches!(lib[i].kind, BrushKind::Bristle(_)) && nn != name.trim() {
|
||||
bristle_name_fits(C, nn)?;
|
||||
}
|
||||
v["name"] = json!(nn);
|
||||
} else {
|
||||
v["name"] = json!(name);
|
||||
}
|
||||
v["type"] = json!(lib[i].kind.type_id());
|
||||
lib[i] = parse_brush(C, v)?;
|
||||
let out = lib[i].name.clone();
|
||||
let rename = new_name.map(|nn| (name, Some(nn)));
|
||||
save_library(s, "Brush Options", lib, rename.as_slice())?;
|
||||
Ok(json!({ "name": out }))
|
||||
}
|
||||
|
||||
pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("Expand: no brush strokes selected".into()));
|
||||
}
|
||||
let out = s.edit("Expand", |d, sel| {
|
||||
let mut out = vec![];
|
||||
for id in &ids {
|
||||
let Some(n) = d.node(*id).cloned() else { continue };
|
||||
let Some(g) = brush::expand(d, &n) else { continue };
|
||||
let g = d.reid(&g);
|
||||
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
let gid = g.id;
|
||||
d.remove(*id)?;
|
||||
d.insert(par, idx, g)?;
|
||||
out.push(gid);
|
||||
}
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&out) }))
|
||||
}
|
||||
|
||||
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some()));
|
||||
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
|
||||
let r = (spec.run)(s, p)?;
|
||||
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
st.brush = Some(name.clone());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(r)
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
use super::*;
|
||||
|
||||
// ---------- symbols ----------
|
||||
|
||||
pub(crate) fn natural_size(d: &Document, name: &str) -> (f64, f64) {
|
||||
d.unknown
|
||||
.get(SIZES_KEY)
|
||||
.and_then(|m| m.get(name))
|
||||
.and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)))
|
||||
.unwrap_or((2.0 * HALF, 2.0 * HALF))
|
||||
}
|
||||
|
||||
pub(crate) fn set_natural_size(d: &mut Document, name: &str, size: Option<(f64, f64)>) {
|
||||
let m = d.unknown.entry(SIZES_KEY.to_string()).or_insert_with(|| json!({}));
|
||||
if let Some(o) = m.as_object_mut() {
|
||||
match size {
|
||||
Some((w, h)) => o.insert(name.into(), json!([w, h])),
|
||||
None => o.remove(name),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Instance transform for a symbol of natural size `(w, h)` whose registration point is at `at`.
|
||||
pub(crate) fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) -> Affine {
|
||||
let c = at - reg.offset_from_center(w, h);
|
||||
Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF))
|
||||
}
|
||||
|
||||
fn registration_param(p: &Value, cmd: &str) -> Result<Option<SymbolRegistration>> {
|
||||
match p.get("registration") {
|
||||
None => Ok(None),
|
||||
Some(v) => v.as_u64().and_then(SymbolRegistration::from_u64).map(Some).ok_or_else(|| bad(cmd, "registration must be 0..8")),
|
||||
}
|
||||
}
|
||||
|
||||
fn export_type_param(p: &Value, cmd: &str) -> Result<Option<SymbolExportType>> {
|
||||
match str_param(p, "exportType") {
|
||||
None => Ok(None),
|
||||
Some(s) => SymbolExportType::from_id(s).map(Some).ok_or_else(|| bad(cmd, format!("exportType must be movieClip or graphic, not `{s}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `nineSlice` (bool) and `nineSliceGuides` ([left, top, right, bottom] fractions of the natural
|
||||
/// size): `None` leaves the symbol alone, `Some(None)` turns 9-slice off, `Some(Some(g))` turns it
|
||||
/// on with guides `g` (the symbol's current ones, else the centre third, when none are given).
|
||||
fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> Result<Option<Option<SymbolNineSlice>>> {
|
||||
let on = match p.get("nineSlice") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_bool().ok_or_else(|| bad(cmd, "nineSlice must be true or false"))?),
|
||||
};
|
||||
let guides =
|
||||
match p.get("nineSliceGuides") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| {
|
||||
bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1")
|
||||
})?),
|
||||
};
|
||||
Ok(match (on, guides) {
|
||||
(Some(false), _) => Some(None),
|
||||
(None, None) => None,
|
||||
(_, Some(g)) => Some(Some(g)),
|
||||
(Some(true), None) => Some(Some(current.unwrap_or_default())),
|
||||
})
|
||||
}
|
||||
|
||||
fn nine_slice_json(d: &Document, name: &str) -> Value {
|
||||
d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value)
|
||||
}
|
||||
|
||||
fn rename_natural_size(d: &mut Document, from: &str, to: &str) {
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
let size = d.unknown.get(SIZES_KEY).and_then(|m| m.get(from)).cloned();
|
||||
set_natural_size(d, from, None);
|
||||
if let Some(v) = size
|
||||
&& let (Some(w), Some(h)) = (v.get(0).and_then(Value::as_f64), v.get(1).and_then(Value::as_f64))
|
||||
{
|
||||
set_natural_size(d, to, Some((w, h)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalise art for a symbol definition: returns (art, natural size, centre in the document).
|
||||
pub(crate) fn normalize(mut art: Node) -> Result<(Node, (f64, f64), Point)> {
|
||||
let b = art.geometric_bounds().ok_or_else(|| EngineError::Other("the art has no bounds".into()))?;
|
||||
let (w, h) = (b.width().max(1.0), b.height().max(1.0));
|
||||
let c = b.center();
|
||||
let n = Affine::scale_non_uniform(2.0 * HALF / w, 2.0 * HALF / h) * Affine::translate(-c.to_vec2());
|
||||
art.transform(n, false);
|
||||
Ok((art, (w, h), c))
|
||||
}
|
||||
|
||||
fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& name.is_none_or(|x| x == symbol)
|
||||
{
|
||||
v.push(n.id);
|
||||
}
|
||||
});
|
||||
v
|
||||
}
|
||||
|
||||
fn symbol_names(d: &Document) -> Vec<String> {
|
||||
d.symbols.iter().map(|s| s.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn current_symbol(d: &Document) -> Option<String> {
|
||||
d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string)
|
||||
}
|
||||
|
||||
pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let list: Vec<Value> = d
|
||||
.symbols
|
||||
.iter()
|
||||
.map(|sym| {
|
||||
let (w, h) = natural_size(d, &sym.name);
|
||||
json!({
|
||||
"name": sym.name,
|
||||
"instances": instances_of(d, Some(&sym.name)).len(),
|
||||
"size": [w, h],
|
||||
"registration": d.symbol_registration(&sym.name).0,
|
||||
"exportType": d.symbol_export_type(&sym.name).id(),
|
||||
"nineSlice": nine_slice_json(d, &sym.name),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) }))
|
||||
}
|
||||
|
||||
/// Replace the root nodes `ids` with one instance of `name` (art already stored). Returns the id.
|
||||
fn replace_with_instance(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result<NodeId> {
|
||||
let top = *ids.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?;
|
||||
if separate(d, ids) {
|
||||
let id = d.alloc_id();
|
||||
return Ok(d.wrap(ids, |_| Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }))?);
|
||||
}
|
||||
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
|
||||
let id = d.alloc_id();
|
||||
d.insert(par, idx + 1, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }))?;
|
||||
for r in ids {
|
||||
d.remove(*r)?;
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.new";
|
||||
let ids = roots(s, p)?;
|
||||
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
|
||||
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
|
||||
let (art, size, c) = normalize(art)?;
|
||||
let name = s.doc()?.doc.unique_symbol_name(str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("New Symbol"));
|
||||
let reg = registration_param(p, C)?.unwrap_or(SymbolRegistration::CENTER);
|
||||
let export = export_type_param(p, C)?.unwrap_or_default();
|
||||
let nine = nine_slice_param(p, C, None)?.flatten();
|
||||
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
|
||||
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
|
||||
let id = s.edit("New Symbol", |d, sel| {
|
||||
let art = d.reid(&art);
|
||||
d.symbols.push(Symbol { name: name.clone(), art: Arc::new(art) });
|
||||
set_natural_size(d, &name, Some(size));
|
||||
d.set_symbol_registration(&name, reg);
|
||||
d.set_symbol_export_type(&name, export);
|
||||
d.set_symbol_nine_slice(&name, nine);
|
||||
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
|
||||
let threaded = crate::cmd::threads::frames(d);
|
||||
let id = replace_with_instance(d, &ids, &name, place)?;
|
||||
// Frames of threaded text in the symbol leave their threads with the text they show.
|
||||
crate::cmd::threads::leave_threads(d, &threaded);
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(
|
||||
json!({ "name": name, "id": id.0, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.options";
|
||||
let name = resolve_symbol(&s.doc()?.doc, p, C)?;
|
||||
let export = export_type_param(p, C)?;
|
||||
let reg = registration_param(p, C)?;
|
||||
let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?;
|
||||
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() {
|
||||
return Err(bad(C, "pass newName, registration, exportType and/or nineSlice"));
|
||||
}
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
&& s.doc()?.doc.symbols.iter().any(|x| x.name == *n)
|
||||
{
|
||||
return Err(bad(C, format!("a symbol named `{n}` already exists")));
|
||||
}
|
||||
let final_name = new_name.clone().unwrap_or_else(|| name.clone());
|
||||
s.edit("Symbol Options", |d, _| {
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
{
|
||||
if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) {
|
||||
sym.name = n.clone();
|
||||
}
|
||||
for id in instances_of(d, Some(&name)) {
|
||||
if let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node_mut(id).map(|node| &mut node.kind) {
|
||||
*symbol = n.clone();
|
||||
}
|
||||
}
|
||||
rename_natural_size(d, &name, n);
|
||||
d.rename_symbol_registration(&name, n);
|
||||
d.rename_symbol_export_type(&name, n);
|
||||
d.rename_symbol_nine_slice(&name, n);
|
||||
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
|
||||
d.unknown.insert(CURRENT_SYMBOL.into(), json!(n));
|
||||
}
|
||||
}
|
||||
if let Some(r) = reg {
|
||||
d.set_symbol_registration(&final_name, r);
|
||||
}
|
||||
if let Some(kind) = export {
|
||||
d.set_symbol_export_type(&final_name, kind);
|
||||
}
|
||||
if let Some(g) = nine {
|
||||
d.set_symbol_nine_slice(&final_name, g);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(json!({
|
||||
"name": final_name,
|
||||
"registration": d.symbol_registration(&final_name).0,
|
||||
"exportType": d.symbol_export_type(&final_name).id(),
|
||||
"nineSlice": nine_slice_json(d, &final_name),
|
||||
}))
|
||||
}
|
||||
|
||||
fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
|
||||
match str_param(p, "name") {
|
||||
Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()),
|
||||
Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))),
|
||||
None => {
|
||||
current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let name = resolve_symbol(d, p, "symbol.place")?;
|
||||
let centre = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = Point::new(number_or(p, "x", centre.x, "symbol.place")?, number_or(p, "y", centre.y, "symbol.place")?);
|
||||
let size = natural_size(d, &name);
|
||||
let reg = d.symbol_registration(&name);
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Place Symbol Instance", |d, sel| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The plain art of instance `inst` in document space (fresh ids).
|
||||
fn expanded_instance(d: &mut Document, inst: &Node) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
|
||||
let sym = d.symbols.iter().find(|s| &s.name == symbol)?;
|
||||
let mut art = (*sym.art).clone();
|
||||
if let Some(f) = inst.appearance.fill()
|
||||
&& let Some(c) = f.paint.color()
|
||||
{
|
||||
brush::tint_node(&mut art, &c, f.opacity);
|
||||
}
|
||||
art.transform(*xf, false);
|
||||
let mut art = d.reid(&art);
|
||||
if inst.opacity < 1.0 || inst.blend != vectorcraft_color::BlendMode::Normal {
|
||||
if !matches!(art.kind, NodeKind::Group { .. }) {
|
||||
let id = d.alloc_id();
|
||||
art = Node::group(id, vec![Arc::new(art)]);
|
||||
}
|
||||
art.opacity *= inst.opacity;
|
||||
art.blend = inst.blend;
|
||||
}
|
||||
Some(art)
|
||||
}
|
||||
|
||||
fn break_links(d: &mut Document, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(inst) = d.node(*id).cloned() else { continue };
|
||||
let Some(art) = expanded_instance(d, &inst) else { continue };
|
||||
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
let aid = art.id;
|
||||
d.remove(*id)?;
|
||||
d.insert(par, idx, art)?;
|
||||
out.push(aid);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut out = vec![];
|
||||
for id in roots(s, p)? {
|
||||
if let Some(n) = d.node(id) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_instances(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no symbol instances selected".into()));
|
||||
}
|
||||
let out = s.edit("Break Link to Symbol", |d, sel| {
|
||||
let out = break_links(d, &ids)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&out) }))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_instances(s, p)?;
|
||||
let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?;
|
||||
let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(),
|
||||
_ => return Err(EngineError::Other("select a symbol instance".into())),
|
||||
};
|
||||
let out = s.edit("Edit Symbol", |d, sel| {
|
||||
let out = break_links(d, &[first])?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "name": name, "ids": ids_json(&out) }))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.update";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) {
|
||||
return Err(bad(C, format!("no symbol named `{name}`")));
|
||||
}
|
||||
let ids = roots(s, p)?;
|
||||
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
|
||||
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
|
||||
let (art, size, c) = normalize(art)?;
|
||||
let old = natural_size(&s.doc()?.doc, &name);
|
||||
let id = s.edit("Redefine Symbol", |d, sel| {
|
||||
let art = d.reid(&art);
|
||||
if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) {
|
||||
sym.art = Arc::new(art);
|
||||
}
|
||||
set_natural_size(d, &name, Some(size));
|
||||
let fix = Affine::scale_non_uniform(size.0 / old.0, size.1 / old.1);
|
||||
for i in instances_of(d, Some(&name)) {
|
||||
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(i).map(|n| &mut n.kind) {
|
||||
*xf *= fix;
|
||||
}
|
||||
}
|
||||
let reg = d.symbol_registration(&name);
|
||||
let threaded = crate::cmd::threads::frames(d);
|
||||
let id = replace_with_instance(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?;
|
||||
// Frames of threaded text in the symbol leave their threads with the text they show.
|
||||
crate::cmd::threads::leave_threads(d, &threaded);
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "name": name, "id": id.0 }))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.delete";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) {
|
||||
return Err(bad(C, format!("no symbol named `{name}`")));
|
||||
}
|
||||
let expand = switch_or(p, "expandInstances", true, C)?;
|
||||
s.edit("Delete Symbol", |d, _| {
|
||||
let inst = instances_of(d, Some(&name));
|
||||
if expand {
|
||||
break_links(d, &inst)?;
|
||||
} else {
|
||||
remove_each(d, &inst)?;
|
||||
}
|
||||
d.symbols.retain(|x| x.name != name);
|
||||
set_natural_size(d, &name, None);
|
||||
d.set_symbol_registration(&name, SymbolRegistration::CENTER);
|
||||
d.clear_symbol_export_type(&name);
|
||||
d.set_symbol_nine_slice(&name, None);
|
||||
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
|
||||
d.unknown.remove(CURRENT_SYMBOL);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.duplicate";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
let d = &s.doc()?.doc;
|
||||
let sym = d.symbols.iter().find(|x| x.name == name).cloned().ok_or_else(|| bad(C, format!("no symbol named `{name}`")))?;
|
||||
let given = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty());
|
||||
let new = d.unique_symbol_name(&given.map_or_else(|| format!("{} copy", name.trim()), str::to_string));
|
||||
let size = natural_size(d, &name);
|
||||
let reg = d.symbol_registration(&name);
|
||||
let export = d.symbol_export_type(&name);
|
||||
let nine = d.symbol_nine_slice(&name);
|
||||
s.edit("Duplicate Symbol", |d, _| {
|
||||
let art = d.reid(&sym.art);
|
||||
d.symbols.push(Symbol { name: new.clone(), art: Arc::new(art) });
|
||||
set_natural_size(d, &new, Some(size));
|
||||
d.set_symbol_registration(&new, reg);
|
||||
d.set_symbol_export_type(&new, export);
|
||||
d.set_symbol_nine_slice(&new, nine);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.replace";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) {
|
||||
return Err(bad(C, format!("no symbol named `{name}`")));
|
||||
}
|
||||
let ids = selected_instances(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no symbol instances selected".into()));
|
||||
}
|
||||
s.edit("Replace Symbol", |d, _| {
|
||||
let new = natural_size(d, &name);
|
||||
for id in &ids {
|
||||
let old = match d.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => natural_size(d, symbol),
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(NodeKind::SymbolInstance { symbol, xf }) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
*symbol = name.clone();
|
||||
*xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = resolve_symbol(&s.doc()?.doc, p, "symbol.setCurrent")?;
|
||||
set_unknown(s, CURRENT_SYMBOL, Some(json!(name)))?;
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(super) fn symbol_select_instances(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = resolve_symbol(&s.doc()?.doc, p, "symbol.selectInstances")?;
|
||||
let ids = instances_of(&s.doc()?.doc, Some(&name));
|
||||
let n = ids.len();
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
Ok(json!({ "count": n }))
|
||||
}
|
||||
|
||||
// ---------- symbolism tools ----------
|
||||
|
||||
fn points(p: &Value, cmd: &str) -> Result<Vec<Point>> {
|
||||
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?;
|
||||
let v: Vec<Point> = a.iter().filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect();
|
||||
if v.is_empty() || v.iter().any(|q| !q.x.is_finite() || !q.y.is_finite()) {
|
||||
return Err(bad(cmd, "points must be finite [x,y] pairs"));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree).
|
||||
fn jitter(i: usize, q: Point) -> (f64, f64, f64) {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ i as u64;
|
||||
for v in [(q.x * 16.0).round() as i64 as u64, (q.y * 16.0).round() as i64 as u64] {
|
||||
h ^= v;
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
h ^= h >> 29;
|
||||
}
|
||||
let f = |k: u32| ((h.rotate_left(k * 21) & 0xffff) as f64 / 65535.0) * 2.0 - 1.0;
|
||||
(f(0), f(1), f(2))
|
||||
}
|
||||
|
||||
fn is_symbol_set(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some("Symbol Set")
|
||||
}
|
||||
|
||||
pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.spray";
|
||||
let pts = points(p, C)?;
|
||||
let st = s.doc()?;
|
||||
let name = resolve_symbol(&st.doc, p, C)?;
|
||||
let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0);
|
||||
let density = number_or(p, "density", 5.0, C)?.clamp(1.0, 10.0);
|
||||
let scale = number_or(p, "scale", 1.0, C)?.clamp(0.01, 100.0);
|
||||
let alt = switch_or(p, "alt", false, C)?;
|
||||
let size = natural_size(&st.doc, &name);
|
||||
let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set));
|
||||
// Only a new Symbol Set needs a layer that takes new art.
|
||||
let parent = if alt || set.is_some() { st.insertion_parent() } else { st.target_parent()? };
|
||||
if alt {
|
||||
// Remove instances of this symbol under the brush (within the set, or anywhere).
|
||||
let d = &st.doc;
|
||||
let scope: Vec<NodeId> = match set {
|
||||
Some(g) => d.node(g).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default(),
|
||||
None => instances_of(d, Some(&name)),
|
||||
};
|
||||
let doomed: Vec<NodeId> = scope
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
d.node(*id).is_some_and(|n| {
|
||||
matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if *symbol == name)
|
||||
&& n.geometric_bounds().is_some_and(|b| pts.iter().any(|q| q.distance(b.center()) <= radius))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let n = doomed.len();
|
||||
if n > 0 {
|
||||
s.edit("Symbol Sprayer", |d, _| remove_each(d, &doomed))?;
|
||||
}
|
||||
return Ok(json!({ "count": n }));
|
||||
}
|
||||
// Keep instances at least this far apart along the stroke (denser = closer).
|
||||
let min_gap = size.0.max(size.1) * scale * (1.15 - density * 0.1).max(0.1);
|
||||
let mut placed: Vec<Point> = vec![];
|
||||
for (i, q) in pts.iter().enumerate() {
|
||||
let (jx, jy, _) = jitter(i, *q);
|
||||
let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5);
|
||||
if placed.last().is_some_and(|l| l.distance(c) < min_gap) && i > 0 {
|
||||
continue;
|
||||
}
|
||||
placed.push(c);
|
||||
}
|
||||
let count = placed.len();
|
||||
let reg = s.doc()?.doc.symbol_registration(&name);
|
||||
let id = s.edit("Symbol Sprayer", |d, sel| {
|
||||
let mut nodes = vec![];
|
||||
for (i, c) in placed.iter().enumerate() {
|
||||
let (_, _, js) = jitter(i + 7, *c);
|
||||
let k = scale * (1.0 + js * 0.1);
|
||||
let id = d.alloc_id();
|
||||
nodes.push(Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(*c, size, reg) * Affine::scale(k) }));
|
||||
}
|
||||
let gid = match set {
|
||||
Some(g) => {
|
||||
for n in nodes {
|
||||
d.insert(Some(g), usize::MAX, n)?;
|
||||
}
|
||||
g
|
||||
}
|
||||
None => {
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, nodes.into_iter().map(Arc::new).collect());
|
||||
g.name = Some("Symbol Set".into());
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
gid
|
||||
}
|
||||
};
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "count": count }))
|
||||
}
|
||||
|
||||
fn instance_center(n: &Node) -> Option<Point> {
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.adjust";
|
||||
let tool = str_param(p, "tool").ok_or_else(|| bad(C, "missing `tool`"))?.to_string();
|
||||
if !["shift", "scrunch", "size", "spin", "stain", "screen", "style"].contains(&tool.as_str()) {
|
||||
return Err(bad(C, format!("unknown tool `{tool}`")));
|
||||
}
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let pts = points(p, C)?;
|
||||
let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0);
|
||||
let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0;
|
||||
let alt = switch_or(p, "alt", false, C)?;
|
||||
let st = s.doc()?;
|
||||
let color = match p.get("color").and_then(color_value) {
|
||||
Some(c) => crate::cmd::paint::new_color(s, p, c),
|
||||
None => s.paint.fill.color().unwrap_or(Color::BLACK),
|
||||
};
|
||||
let style_paint = match str_param(p, "style") {
|
||||
Some(n) => st.doc.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()),
|
||||
None => st.doc.graphic_styles.get(1).or(st.doc.graphic_styles.first()).map(|g| g.appearance.fill_paint()),
|
||||
};
|
||||
let candidates: Vec<NodeId> = {
|
||||
let d = &st.doc;
|
||||
let mut v = vec![];
|
||||
if st.selection.is_empty() {
|
||||
v = instances_of(d, None);
|
||||
} else {
|
||||
for id in &st.selection.objects {
|
||||
if let Some(n) = d.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let editable = d.editable();
|
||||
v.retain(|id| editable(*id));
|
||||
v
|
||||
};
|
||||
let label = match tool.as_str() {
|
||||
"shift" => "Symbol Shifter",
|
||||
"scrunch" => "Symbol Scruncher",
|
||||
"size" => "Symbol Sizer",
|
||||
"spin" => "Symbol Spinner",
|
||||
"stain" => "Symbol Stainer",
|
||||
"screen" => "Symbol Screener",
|
||||
_ => "Symbol Styler",
|
||||
};
|
||||
let count = s.edit(label, |d, _| {
|
||||
let mut touched = std::collections::BTreeSet::new();
|
||||
for (j, q) in pts.iter().enumerate() {
|
||||
let delta = if j > 0 { *q - pts[j - 1] } else { Vec2::ZERO };
|
||||
for id in &candidates {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let Some(c) = instance_center(n) else { continue };
|
||||
let dist = c.distance(*q);
|
||||
if dist > radius {
|
||||
continue;
|
||||
}
|
||||
let w = intensity * (1.0 - dist / radius).max(0.0);
|
||||
if w <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
touched.insert(*id);
|
||||
let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2());
|
||||
match tool.as_str() {
|
||||
"shift" => n.transform(Affine::translate(delta * w.min(1.0)), false),
|
||||
"scrunch" => {
|
||||
let v = (*q - c) * (0.15 * w) * if alt { -1.0 } else { 1.0 };
|
||||
n.transform(Affine::translate(v), false);
|
||||
}
|
||||
"size" => {
|
||||
let k = 1.0 + 0.08 * w;
|
||||
n.transform(about(Affine::scale(if alt { 1.0 / k } else { k })), false);
|
||||
}
|
||||
"spin" => {
|
||||
// Turn towards the drag direction; a click spins a little.
|
||||
let a = if delta.hypot() > 1e-9 { (c - *q).cross(delta).signum() * 0.1 * w } else { 0.05 * w };
|
||||
n.transform(about(Affine::rotate(if alt { -a } else { a })), false);
|
||||
}
|
||||
"stain" | "style" => {
|
||||
let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) };
|
||||
if tool == "style" && alt {
|
||||
n.appearance.items.clear();
|
||||
continue;
|
||||
}
|
||||
let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0);
|
||||
let step = if tool == "style" { 1.0 } else { 0.15 * w as f32 };
|
||||
let o = if alt { (cur - step).max(0.0) } else { (cur + step).min(1.0) };
|
||||
n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_)));
|
||||
if o > 0.0 {
|
||||
let mut f = FillLayer::new(paint);
|
||||
f.opacity = o;
|
||||
n.appearance.items.insert(0, AppearanceItem::Fill(f));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let step = (0.1 * w) as f32;
|
||||
n.opacity = if alt { (n.opacity + step).min(1.0) } else { (n.opacity - step).max(0.05) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(touched.len())
|
||||
})?;
|
||||
Ok(json!({ "count": count }))
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Shape Builder (`shapeBuilder.*`), Live Paint (`livePaint.*`) and Image Trace (`imageTrace.*`).
|
||||
//!
|
||||
//! **Live Paint groups** need no special node kind: a Live Paint group is a plain group whose name
|
||||
//! starts with "Live Paint". Its first child is a hidden group named "Live Paint Sources" holding
|
||||
//! the original paths (the planar map's inputs, used by Release, Merge and re-computation); then
|
||||
//! come the faces (paths named "Face", fill only) and the edges (open paths named "Edge", stroke
|
||||
//! only). See `vectorcraft_tools::builder` for the shared helpers.
|
||||
//! starts with "Live Paint" and that holds a group named "Live Paint Sources". That group is its
|
||||
//! first child, hidden, and holds the original paths (the planar map's inputs, used by Release,
|
||||
//! Merge and re-computation); then come the faces (paths named "Face", fill only) and the edges
|
||||
//! (open paths named "Edge", stroke only). See `vectorcraft_tools::builder` for the shared helpers.
|
||||
//!
|
||||
//! **Image Trace** makes a group named "Image Trace" holding the source image (hidden, bottom)
|
||||
//! and the traced filled paths above it, mapped with the image's transform. Expand drops the
|
||||
@@ -19,16 +19,25 @@ use vectorcraft_doc::{Appearance, Document, GapOptions, GapSize, LiveShape, Node
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::builder::{
|
||||
self as b, BuilderMap, EDGE_NAME, FACE_NAME, LIVE_PAINT_NAME, SOURCES_NAME, Touched, edge_near, face_at, is_live_paint, sample_polyline,
|
||||
sorted_roots,
|
||||
self as b, BuilderMap, EDGE_NAME, FACE_NAME, LIVE_PAINT_NAME, SOURCES_NAME, Touched, edge_near, face_at, is_live_paint, sorted_roots,
|
||||
};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
use super::draw2::replace_with_pieces;
|
||||
use super::edit::{outermost, selected_roots};
|
||||
use super::paint::paint_from;
|
||||
use super::pathops::{Beside, shape_node};
|
||||
use super::*;
|
||||
|
||||
mod live_paint;
|
||||
mod shape_builder;
|
||||
mod trace;
|
||||
|
||||
pub use live_paint::live_paint_gaps;
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
use trace::{trace_expand, trace_make, trace_release, trace_set_view};
|
||||
|
||||
/// Name of an Image Trace group.
|
||||
pub const TRACE_NAME: &str = "Image Trace";
|
||||
|
||||
@@ -39,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Builder",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of unfilled open paths and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance; a deleted edge opens its path there, and edges bounding a deleted region go with it), tolerance?: pt (2, erase only), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the fill of the object under the first point; the current fill for an area only lines enclose)} → {ids, merged, regions, lines, edges} (counts deleted or merged)",
|
||||
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} → {ids, merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
|
||||
has_selection_or_ids,
|
||||
sb_merge
|
||||
),
|
||||
@@ -48,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Builder Regions",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} → {regions: [{bounds: [x0,y0,x1,y1], area, sources: [id…]}], lines: [{bounds, source: id}], edges: [{bounds, source: id}]} faces of the planar arrangement (unfilled open paths cut them; sources is empty for an area only they enclose), the pieces of those open paths and the edges (the other paths' outlines cut where paths meet; source: the front-most path along it), which erasing deletes",
|
||||
"{ids?|id?, gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (as shapeBuilder.merge)} → {regions: [{bounds: [x0,y0,x1,y1], area, sources: [id…]}], lines: [{bounds, source: id}], edges: [{bounds, source: id}]} faces of the planar arrangement (unfilled open paths cut them, and filled ones too with openFilledAsClosed false; sources is empty for an area only they enclose), the pieces of those open paths and the edges (the other paths' outlines cut where paths meet; source: the front-most path along it), which erasing deletes",
|
||||
has_selection_or_ids,
|
||||
sb_regions
|
||||
),
|
||||
@@ -57,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Live Paint"],
|
||||
Some("Cmd+Alt+X"),
|
||||
"{ids?|id?} build a Live Paint group from the selected paths → {id, faces, edges}",
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}",
|
||||
has_selection_or_ids,
|
||||
lp_make
|
||||
),
|
||||
@@ -66,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Merge",
|
||||
["Object", "Live Paint"],
|
||||
None,
|
||||
"{ids?|id?} add the other selected paths (and Live Paint groups) to the first Live Paint group, keeping its paint → {id, faces, edges}",
|
||||
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link) → {id, faces, edges}",
|
||||
has_multi_or_ids,
|
||||
lp_merge
|
||||
),
|
||||
@@ -102,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket",
|
||||
[],
|
||||
None,
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point → {group, face}",
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
|
||||
has_doc,
|
||||
lp_fill
|
||||
),
|
||||
@@ -129,7 +138,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, white is always its own colour, at most ten; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white unless ignoreWhite makes them holes; fills/strokes are ignored; gradients and photos are refused)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, white is always its own colour, at most ten; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white unless ignoreWhite makes them holes; fills/strokes are ignored; gradients and photos are refused)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -232,119 +241,25 @@ fn fill_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Paint>> {
|
||||
Some(v @ Value::Object(o)) if o.contains_key("color") || o.contains_key("swatch") || o.contains_key("gradient") || o.contains_key("none") => {
|
||||
paint_from(s, v)
|
||||
}
|
||||
Some(v) => color_value(v).map(|c| Some(Paint::solid(c))).ok_or_else(|| bad(cmd, format!("bad fill {v}"))),
|
||||
Some(v) => color_value(v).map(|c| Some(Paint::solid(super::paint::new_color(s, p, c)))).ok_or_else(|| bad(cmd, format!("bad fill {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shapeBuilder.merge";
|
||||
let pts = points_param(p, "points").ok_or_else(|| bad(C, "missing points [[x,y]…]"))?;
|
||||
if pts.is_empty() || !pts.iter().all(|q| finite(*q)) {
|
||||
return Err(bad(C, "points must be a non-empty list of finite [x,y]"));
|
||||
/// Gap Detection length in points, bounded like Live Paint's custom gap size.
|
||||
fn gap_param(p: &Value) -> f64 {
|
||||
let gap = f64_or(p, "gap", 0.0);
|
||||
if gap.is_finite() { gap.clamp(0.0, po::SHAPE_BUILDER_MAX_GAP) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The Shift-drag marquee `rect: [x, y, width, height]`, as the point where the drag started
|
||||
/// (`x`, `y`) and the opposite corner; the width and height may be negative.
|
||||
fn marquee_param(p: &Value, cmd: &str) -> Result<Option<(Point, Point)>> {
|
||||
let Some(v) = p.get("rect").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let corners = finite_numbers(v).map(|[x, y, w, h]| (Point::new(x, y), Point::new(x + w, y + h)));
|
||||
match corners {
|
||||
Some((a, b)) if finite(a) && finite(b) => Ok(Some((a, b))),
|
||||
_ => Err(bad(cmd, "rect must be [x, y, width, height]")),
|
||||
}
|
||||
let erase = bool_or(p, "erase", false);
|
||||
// Line pieces and edges are only deleted (erase mode), never merged.
|
||||
let piece_tol = erase.then(|| f64_or(p, "tolerance", 2.0).clamp(0.0, 1000.0));
|
||||
let fill = fill_param(s, p, C)?;
|
||||
let current_fill = s.paint.fill.clone();
|
||||
let roots = root_ids(s, p)?;
|
||||
let label = if erase { "Shape Builder Delete" } else { "Shape Builder" };
|
||||
let (ids, merged, touched) = s.edit(label, |d, sel| {
|
||||
let (map, leaves) = BuilderMap::new(d, &roots, erase);
|
||||
let leaves: Vec<Node> = leaves.into_iter().cloned().collect();
|
||||
if map.shapes.is_empty() {
|
||||
return Err(EngineError::Other("Shape Builder: select paths or compound paths".into()));
|
||||
}
|
||||
let step = (d.bounds_of(&roots, false).map(|r| r.width().max(r.height())).unwrap_or(100.0) / 2000.0).max(0.25);
|
||||
let mut touched = Touched::default();
|
||||
for q in sample_polyline(&pts, step) {
|
||||
touched.add(map.hit(q, piece_tol));
|
||||
}
|
||||
touched.edges = map.erased_edges(&touched);
|
||||
if touched.is_empty() {
|
||||
return Err(EngineError::Other("Shape Builder: no region under the pointer".into()));
|
||||
}
|
||||
let cuts: Vec<&SubPath> = touched.edges.iter().filter_map(|&k| map.edges.get(k)?.0.path.subpaths.first()).collect();
|
||||
// Edges come back from the planar map within a few hundredths of the outlines they follow.
|
||||
let cut_tol = step * 0.2;
|
||||
let picked: Vec<&po::Region> = touched.regions.iter().filter_map(|&i| map.regions.get(i).map(|r| &r.0)).collect();
|
||||
let faces = po::FaceMerger::new(&map.shapes);
|
||||
let union = if picked.is_empty() { PathData::default() } else { faces.merge(&picked) };
|
||||
// The merged shape takes the look of the front-most object over the first region, or (for an
|
||||
// area only lines enclose) of the front-most object and the current fill.
|
||||
let covered = picked.iter().find_map(|r| r.top());
|
||||
let style_src = covered.or(map.shapes.len().checked_sub(1));
|
||||
let merged_fill = fill.or_else(|| covered.is_none().then_some(current_fill));
|
||||
let mut new_nodes: Vec<Node> = vec![];
|
||||
let mut merged_id = None;
|
||||
for (i, (sh, leaf)) in map.shapes.iter().zip(&leaves).enumerate() {
|
||||
let pieces: Vec<usize> = map.lines.iter().enumerate().filter(|(_, (l, _))| l.key == i as u64).map(|(k, _)| k).collect();
|
||||
if !pieces.is_empty() {
|
||||
// An open path loses the pieces deleted and those between merged (or deleted) regions.
|
||||
let keep: Vec<usize> =
|
||||
pieces.iter().copied().filter(|k| !touched.lines.contains(k) && !map.line_between(*k, &touched.regions)).collect();
|
||||
if keep.len() == pieces.len() {
|
||||
new_nodes.push(d.reid(leaf));
|
||||
} else {
|
||||
for k in keep {
|
||||
if let Some((l, _)) = map.lines.get(k) {
|
||||
new_nodes.push(shape_node(d, l.path.clone(), Some(leaf)));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// A shape loses the regions deleted or merged, then the edges deleted (each one on
|
||||
// its outline, shared edges from every shape along them).
|
||||
let in_union = picked.iter().any(|r| r.sources.contains(&i));
|
||||
let mut rest = if in_union {
|
||||
// What is left of it: its faces not merged or deleted, united. They share their
|
||||
// edges with the merged faces exactly, where subtracting the merged shape left
|
||||
// slivers of the outline along them (#569).
|
||||
let kept: Vec<&po::Region> = map
|
||||
.regions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(k, (r, ..))| r.sources.contains(&i) && !touched.regions.contains(k))
|
||||
.map(|(_, (r, ..))| r)
|
||||
.collect();
|
||||
if kept.is_empty() { PathData::default() } else { faces.merge(&kept) }
|
||||
} else {
|
||||
b::node_outline(leaf).map_or_else(|| sh.path.clone(), |o| o.0)
|
||||
};
|
||||
let fill_closes = !leaf.appearance.fill_paint().is_none();
|
||||
let mut cut = false;
|
||||
for piece in &cuts {
|
||||
if let Some(r) = po::cut_out(&rest, piece, fill_closes, cut_tol) {
|
||||
rest = r;
|
||||
cut = true;
|
||||
}
|
||||
}
|
||||
if !in_union && !cut {
|
||||
new_nodes.push(d.reid(leaf));
|
||||
} else if !rest.is_empty() {
|
||||
new_nodes.push(shape_node(d, rest, Some(leaf)));
|
||||
}
|
||||
}
|
||||
if !erase && !union.is_empty() && Some(i) == style_src {
|
||||
let mut m = shape_node(d, union.clone(), Some(leaf));
|
||||
if let Some(f) = &merged_fill {
|
||||
m.appearance.set_fill(f.clone());
|
||||
}
|
||||
merged_id = Some(m.id);
|
||||
new_nodes.push(m);
|
||||
}
|
||||
}
|
||||
let new_ids = replace_roots(d, &roots, new_nodes)?;
|
||||
sel.set(new_ids.iter().copied());
|
||||
Ok((new_ids, merged_id, touched))
|
||||
})?;
|
||||
Ok(json!({
|
||||
"ids": ids_json(&ids),
|
||||
"merged": merged.map(|m| m.0),
|
||||
"regions": touched.regions.len(),
|
||||
"lines": touched.lines.len(),
|
||||
"edges": touched.edges.len(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Remove the roots and insert `nodes` where the front-most root was. Returns the new ids.
|
||||
@@ -363,26 +278,24 @@ fn replace_roots(d: &mut Document, roots: &[NodeId], nodes: Vec<Node>) -> Result
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn sb_regions(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (map, leaves) = BuilderMap::new(d, &roots, true);
|
||||
let id_of = |i: usize| leaves.get(i).map(|n| n.id.0);
|
||||
let regions: Vec<Value> = map
|
||||
.regions
|
||||
.iter()
|
||||
.map(|(r, _, bb)| {
|
||||
json!({
|
||||
"bounds": [bb.x0, bb.y0, bb.x1, bb.y1],
|
||||
"area": po::area(&r.path, FillRule::NonZero),
|
||||
"sources": r.sources.iter().filter_map(|&i| id_of(i)).collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let pieces = |list: &[(po::Shape, Rect)]| -> Vec<Value> {
|
||||
list.iter().map(|(l, bb)| json!({ "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], "source": id_of(l.key as usize) })).collect()
|
||||
/// What is left of path or compound path `src`: a copy of it with a fresh id and the geometry `path`
|
||||
/// (a path for one subpath, else a compound path, as [`shape_node`] makes them). It keeps the rest
|
||||
/// of `src`: its look, with gradients fitted to its bounds kept where they were on it, its name,
|
||||
/// opacity mask and attributes, and its fill rule unless `rule` is given.
|
||||
fn remnant(d: &mut Document, src: &Node, path: PathData, rule: Option<FillRule>) -> Node {
|
||||
let own = match &src.kind {
|
||||
NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule,
|
||||
_ => FillRule::NonZero,
|
||||
};
|
||||
Ok(json!({ "regions": regions, "lines": pieces(&map.lines), "edges": pieces(&map.edges) }))
|
||||
let shaped = shape_node(d, path, None);
|
||||
let mut n = src.clone();
|
||||
n.pin_gradients();
|
||||
n.id = shaped.id;
|
||||
n.kind = shaped.kind;
|
||||
if let NodeKind::Path { rule: r, .. } | NodeKind::Compound { rule: r, .. } = &mut n.kind {
|
||||
*r = rule.unwrap_or(own);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
// ---------- Live Paint ----------
|
||||
@@ -487,682 +400,3 @@ fn repaint_from(g: &mut Node, old: &Node) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
fn stored_gap_options(options: GapOptions) -> Option<Box<GapOptions>> {
|
||||
(options != GapOptions::default()).then(|| Box::new(options))
|
||||
}
|
||||
|
||||
/// The Gap Options of Live Paint groups merged into one, given bottom-most first: the bottom-most
|
||||
/// group's when its Gap Detection is on; else Gap Detection on with Small Gaps when another
|
||||
/// group's is on; else the bottom-most group's.
|
||||
fn merged_gap_options(groups: &[GapOptions]) -> GapOptions {
|
||||
let Some(&bottom) = groups.first() else { return GapOptions::default() };
|
||||
if !bottom.detect && groups.iter().any(|g| g.detect) { GapOptions { detect: true, size: GapSize::Small, ..bottom } } else { bottom }
|
||||
}
|
||||
|
||||
/// Make a Live Paint group from `roots`; returns (group, faces, edges).
|
||||
fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> {
|
||||
let mut sources = vec![];
|
||||
for r in roots {
|
||||
let n = d.node(*r).ok_or(EngineError::NoNode(*r))?;
|
||||
sources.extend(source_nodes(n));
|
||||
}
|
||||
let (children, nf, ne) = build_children(d, sources, None)?;
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = Some(LIVE_PAINT_NAME.into());
|
||||
replace_roots(d, roots, vec![g])?;
|
||||
sel.set([gid]);
|
||||
Ok((gid, nf, ne))
|
||||
}
|
||||
|
||||
fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let (id, faces, edges) = s.edit("Make Live Paint", |d, sel| make_live(d, sel, &roots))?;
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| {
|
||||
let target = roots
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|r| d.node(*r).is_some_and(is_live_paint))
|
||||
.ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?;
|
||||
let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
// Paint to carry over: (point inside face, fill) and (point on edge, stroke).
|
||||
let keep_faces: Vec<(Point, Paint)> = b::faces(&old)
|
||||
.iter()
|
||||
.filter(|f| !f.appearance.fill_paint().is_none())
|
||||
.filter_map(|f| Some((po::interior_point(f.path_data()?)?, f.appearance.fill_paint())))
|
||||
.collect();
|
||||
let keep_edges: Vec<(Point, Appearance)> = b::edges(&old)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let pd = e.path_data()?;
|
||||
let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?;
|
||||
Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), (*e.appearance).clone()))
|
||||
})
|
||||
.collect();
|
||||
let mut sources = source_nodes(&old);
|
||||
for r in &roots {
|
||||
if *r != target {
|
||||
sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?));
|
||||
}
|
||||
}
|
||||
// Merge applies the Gap Options' merge rules to the groups' options, bottom-most first.
|
||||
let groups: Vec<GapOptions> = roots.iter().filter_map(|r| d.node(*r)).filter(|n| is_live_paint(n)).map(Node::gap_options).collect();
|
||||
let options = merged_gap_options(&groups);
|
||||
let (children, nf, ne) = build_children(d, sources, options.max_gap())?;
|
||||
let mut g = Node::group(target, children);
|
||||
g.name = old.name.clone();
|
||||
g.opacity = old.opacity;
|
||||
g.blend = old.blend;
|
||||
g.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
for (pt, paint) in keep_faces {
|
||||
if let Some(fid) = face_at(&g, pt).map(|f| f.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(f) = ch.iter_mut().find(|c| c.id == fid)
|
||||
{
|
||||
Arc::make_mut(f).appearance.set_fill(paint);
|
||||
}
|
||||
}
|
||||
for (pt, app) in keep_edges {
|
||||
if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(e) = ch.iter_mut().find(|c| c.id == eid)
|
||||
{
|
||||
Arc::make_mut(e).appearance = app.into();
|
||||
}
|
||||
}
|
||||
let mut merged = Beside::replacing(d, &roots);
|
||||
for r in roots.iter().filter(|r| **r != target) {
|
||||
if d.node(*r).is_some() {
|
||||
merged.put(d, *r, vec![])?;
|
||||
}
|
||||
}
|
||||
merged.put(d, target, vec![g])?;
|
||||
merged.finish(d)?;
|
||||
sel.set([target]);
|
||||
Ok((target, nf, ne))
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = root_ids(s, p)?;
|
||||
let v: Vec<NodeId> = ids.into_iter().filter(|i| d.node(*i).is_some_and(is_live_paint)).collect();
|
||||
if v.is_empty() {
|
||||
return Err(EngineError::Other("select a Live Paint group".into()));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = live_targets(s, p)?;
|
||||
let ids = s.edit("Release Live Paint", |d, sel| {
|
||||
let mut out = vec![];
|
||||
let mut released = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let srcs: Vec<Node> = source_nodes(&n).iter().map(|c| (**c).clone()).collect();
|
||||
out.extend(srcs.iter().map(|c| c.id));
|
||||
released.put(d, *g, srcs)?;
|
||||
}
|
||||
released.finish(d)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = live_targets(s, p)?;
|
||||
s.edit("Expand Live Paint", |d, sel| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
n.name = None;
|
||||
{
|
||||
let mut e = n.extras_mut();
|
||||
e.trace = None;
|
||||
e.live_paint_gaps = None;
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| match c.name.as_deref() {
|
||||
Some(SOURCES_NAME) => false,
|
||||
Some(FACE_NAME) => !c.appearance.fill_paint().is_none(),
|
||||
Some(EDGE_NAME) => !c.appearance.stroke_paint().is_none() && c.appearance.stroke_width() > 0.0,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
}
|
||||
sel.set(targets.iter().copied());
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets) }))
|
||||
}
|
||||
|
||||
/// Gaps as `[x0, y0, x1, y1]` (the loose end, then where it closes to).
|
||||
fn gaps_json(gaps: &[[Point; 2]]) -> Value {
|
||||
json!(gaps.iter().map(|[a, b]| [a.x, a.y, b.x, b.y]).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// A group's Gap Options as `livePaint.info` gives them.
|
||||
fn gap_options_json(o: GapOptions) -> Value {
|
||||
let [r, g, b] = o.color;
|
||||
let size = o.size.id().map_or_else(|| json!(o.size.points()), |id| json!(id));
|
||||
json!({ "detect": o.detect, "size": size, "points": o.size.points(), "color": format!("#{r:02x}{g:02x}{b:02x}") })
|
||||
}
|
||||
|
||||
/// The gaps up to `options`' size wide among a Live Paint group's sources.
|
||||
fn open_gaps(group: &Node, options: GapOptions) -> Vec<[Point; 2]> {
|
||||
po::find_gaps(&source_shapes(&source_nodes(group)).0, options.size.points())
|
||||
}
|
||||
|
||||
fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.gapOptions";
|
||||
let detect = match p.get("detect").filter(|v| !v.is_null()) {
|
||||
Some(v) => Some(v.as_bool().ok_or_else(|| bad(C, "detect must be true or false"))?),
|
||||
None => None,
|
||||
};
|
||||
let size =
|
||||
match p.get("size").filter(|v| !v.is_null()) {
|
||||
Some(v) => Some(GapSize::parse(v).ok_or_else(|| {
|
||||
bad(C, format!("size must be \"small\", \"medium\", \"large\" or a number of points over 0 up to {}", GapSize::MAX))
|
||||
})?),
|
||||
None => None,
|
||||
};
|
||||
let color = match p.get("color").filter(|v| !v.is_null()) {
|
||||
Some(v) => Some(super::layer::layer_color_param(v).map_err(|e| bad(C, e))?.rgb()),
|
||||
None => None,
|
||||
};
|
||||
let close = bool_or(p, "closeGaps", false);
|
||||
let targets = live_targets(s, p)?;
|
||||
let (faces, gaps, closed) = s.edit("Gap Options", |d, sel| {
|
||||
let (mut faces, mut gaps, mut closed) = (0, vec![], 0);
|
||||
let mut changed = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let old = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let mut options = old.gap_options();
|
||||
options.detect = detect.unwrap_or(options.detect);
|
||||
options.size = size.unwrap_or(options.size);
|
||||
options.color = color.unwrap_or(options.color);
|
||||
let mut sources = source_nodes(&old);
|
||||
if close {
|
||||
// Close Gaps With Paths adds an unpainted line across each gap to the group's paths.
|
||||
for gap in po::find_gaps(&source_shapes(&sources).0, options.size.points()) {
|
||||
let line = PathData::single(SubPath::polyline(&gap, false));
|
||||
sources.push(Arc::new(Node::path(d.alloc_id(), line, Appearance::default())));
|
||||
closed += 1;
|
||||
}
|
||||
}
|
||||
let mut n = old.clone();
|
||||
// The faces change only with what paint stops at, or with new paths.
|
||||
if close || options.max_gap() != old.gap_options().max_gap() {
|
||||
let (children, _, _) = build_children(d, sources, options.max_gap())?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
repaint_from(&mut n, &old);
|
||||
}
|
||||
n.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
faces += b::faces(&n).len();
|
||||
gaps.extend(open_gaps(&n, options));
|
||||
changed.put(d, *g, vec![n])?;
|
||||
}
|
||||
changed.finish(d)?;
|
||||
sel.set(targets.iter().copied());
|
||||
Ok((faces, gaps, closed))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed }))
|
||||
}
|
||||
|
||||
fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.fill";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
|
||||
let group = id_param(p, "group");
|
||||
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
|
||||
let (g, face) = s.edit("Live Paint Bucket", |d, sel| {
|
||||
let gid = match group {
|
||||
Some(g) => {
|
||||
if !d.node(g).is_some_and(is_live_paint) {
|
||||
return Err(bad(C, format!("{g} is not a Live Paint group")));
|
||||
}
|
||||
g
|
||||
}
|
||||
None => match roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face_at(n, pt).is_some())) {
|
||||
Some(g) => g,
|
||||
None => make_live(d, sel, &roots)?.0,
|
||||
},
|
||||
};
|
||||
let fid =
|
||||
d.node(gid).and_then(|n| face_at(n, pt)).map(|f| f.id).ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?;
|
||||
d.node_mut(fid).ok_or(EngineError::NoNode(fid))?.appearance.set_fill(paint.clone());
|
||||
Ok((gid, fid))
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "face": face.0 }))
|
||||
}
|
||||
|
||||
fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.strokeEdge";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let g = id_param(p, "group").ok_or_else(|| bad(C, "missing group"))?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.stroke.clone());
|
||||
let width = p.get("width").and_then(Value::as_f64).unwrap_or(s.paint.stroke_width.max(0.0));
|
||||
if !(0.0..=1000.0).contains(&width) {
|
||||
return Err(bad(C, "width out of range"));
|
||||
}
|
||||
let tol = f64_or(p, "tolerance", 4.0).clamp(0.0, 1000.0);
|
||||
let edge = s.edit("Live Paint Bucket", |d, _| {
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
|
||||
let eid = edge_near(n, pt, tol).map(|e| e.id).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
|
||||
let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
|
||||
e.appearance.set_stroke(paint.clone());
|
||||
if let Some(st) = e.appearance.stroke_mut() {
|
||||
st.width = width;
|
||||
}
|
||||
Ok(eid)
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "edge": edge.0 }))
|
||||
}
|
||||
|
||||
fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let g = id_param(p, "group").or_else(|| id_param(p, "id")).ok_or_else(|| bad("livePaint.info", "missing group"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad("livePaint.info", format!("{g} is not a Live Paint group")))?;
|
||||
let faces: Vec<Value> = b::faces(n)
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let bb = f.geometric_bounds().unwrap_or(Rect::ZERO);
|
||||
json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] })
|
||||
})
|
||||
.collect();
|
||||
let edges: Vec<Value> = b::edges(n)
|
||||
.iter()
|
||||
.map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() }))
|
||||
.collect();
|
||||
let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0);
|
||||
let options = n.gap_options();
|
||||
Ok(json!({
|
||||
"faces": faces,
|
||||
"edges": edges,
|
||||
"sources": sources,
|
||||
"gapOptions": gap_options_json(options),
|
||||
"gaps": gaps_json(&open_gaps(n, options)),
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
|
||||
fn is_trace_group(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& n.name.as_deref() == Some(TRACE_NAME)
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// The `view` param ([`TraceView`] id), if given.
|
||||
fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let ids = || TraceView::ALL.map(TraceView::id).join(", ");
|
||||
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
|
||||
}
|
||||
|
||||
fn trace_params(p: &Value) -> Result<tr::TraceParams> {
|
||||
let name = str_param(p, "preset").unwrap_or("Default");
|
||||
let enhanced = p.get("enhanced").and_then(Value::as_bool).unwrap_or(false);
|
||||
// (A preset without an enhanced version is traced as it is.)
|
||||
let base = enhanced.then(|| tr::enhanced_preset(name)).flatten().or_else(|| tr::preset(name));
|
||||
let base = base.ok_or_else(|| bad("imageTrace.make", format!("unknown preset `{name}` (see imageTrace.presets)")))?;
|
||||
let Some(over) = p.get("params").filter(|v| !v.is_null()) else { return Ok(base) };
|
||||
let mut v = serde_json::to_value(&base).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let (Some(o), Some(src)) = (v.as_object_mut(), over.as_object()) else { return Err(bad("imageTrace.make", "params must be an object")) };
|
||||
for (k, val) in src {
|
||||
o.insert(k.clone(), val.clone());
|
||||
}
|
||||
let params: tr::TraceParams = serde_json::from_value(v).map_err(|e| bad("imageTrace.make", e.to_string()))?;
|
||||
if !params.fills && !params.strokes {
|
||||
return Err(bad("imageTrace.make", "Create needs fills, strokes or both"));
|
||||
}
|
||||
if !(params.stroke_width.is_finite() && params.stroke_width > 0.0) {
|
||||
return Err(bad("imageTrace.make", "strokeWidth must be a positive number of pixels"));
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
|
||||
/// Document Library in Color mode: look the library's colours up into `params.swatches` → each
|
||||
/// one as traced (sRGB) with the colour to fill with.
|
||||
fn trace_library(s: &Session, params: &mut tr::TraceParams) -> Result<Vec<([u8; 3], Color)>> {
|
||||
const C: &str = "imageTrace.make";
|
||||
if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let key = params.library.as_str();
|
||||
let colors = super::swatchlib::library_colors(s, key)
|
||||
.ok_or_else(|| bad(C, format!("no swatch library `{key}` (see swatch.library.list; \"document\": the document's swatches)")))?;
|
||||
if colors.is_empty() {
|
||||
return Err(bad(C, format!("`{key}` has no colours")));
|
||||
}
|
||||
let library: Vec<([u8; 3], Color)> = colors
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
([r, g, b], c)
|
||||
})
|
||||
.collect();
|
||||
params.swatches = library.iter().map(|l| l.0).collect();
|
||||
Ok(library)
|
||||
}
|
||||
|
||||
/// The most anchor points an Image Trace may make, a guard for memory: a trace past it is refused
|
||||
/// with advice instead (#525). A trace keeps about 90 bytes an anchor in the document (measured on
|
||||
/// code-drawn photos of 2000 × 2000 to 6000 × 4000 pixels), so 8,000,000 anchors are about
|
||||
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at High Fidelity Photo
|
||||
/// makes about 1.9 million, and even at Paths 100, Noise 1 and every tone about 7.9 million. On the
|
||||
/// web, where a page has at most 4 GB of memory, the limit stays at 2,000,000.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub const MAX_TRACE_ANCHORS: usize = 8_000_000;
|
||||
/// The most anchor points an Image Trace may make on the web (see the native limit).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub const MAX_TRACE_ANCHORS: usize = 2_000_000;
|
||||
|
||||
/// The live shape for a shape the tracer found (in the image's pixels), placed in the document by `xf`.
|
||||
fn traced_shape(shape: tr::TracedShape, xf: vectorcraft_geom::Affine) -> LiveShape {
|
||||
use vectorcraft_geom::Affine;
|
||||
let about = |c: Point, deg: f64| Affine::translate(c.to_vec2()) * Affine::rotate(deg.to_radians());
|
||||
let mut live = match shape {
|
||||
tr::TracedShape::Rectangle { center, width, height, radius, rotation } => LiveShape::Rectangle {
|
||||
w: width,
|
||||
h: height,
|
||||
radii: [radius; 4],
|
||||
kinds: Default::default(),
|
||||
xf: about(center, rotation) * Affine::translate((-width / 2.0, -height / 2.0)),
|
||||
},
|
||||
tr::TracedShape::Ellipse { center, rx, ry, rotation } => {
|
||||
LiveShape::Ellipse { w: 2.0 * rx, h: 2.0 * ry, pie: (0.0, 360.0), xf: about(center, rotation) * Affine::translate((-rx, -ry)) }
|
||||
}
|
||||
tr::TracedShape::Polygon { center, radius, sides, rotation } => {
|
||||
LiveShape::Polygon { radius, sides, xf: about(center, rotation), radii: vec![], kinds: vec![] }
|
||||
}
|
||||
};
|
||||
// (Whether the move changed the shape's own numbers does not matter: its path is made from them next.)
|
||||
let _ = live.transform(xf);
|
||||
live
|
||||
}
|
||||
|
||||
/// The gradient fill for a linear gradient the tracer found (in the image's pixels), placed in the
|
||||
/// document by `xf`.
|
||||
fn traced_gradient(g: &tr::TracedGradient, xf: vectorcraft_geom::Affine) -> Paint {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = g.stops.iter().map(|&(at, c)| GradientStop::new(at as f32, Color::rgb8(c[0], c[1], c[2]))).collect();
|
||||
let mut paint = GradientPaint::new(Gradient { kind: GradientKind::Linear, stops });
|
||||
paint.geom = Some(GradientGeom { start: xf * g.start, end: xf * g.end, aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(paint))
|
||||
}
|
||||
|
||||
/// Auto Grouping: `nodes` (one per traced path, bottom-most first) with each path that has others
|
||||
/// inside it (`parents`, as the tracer gives them) in a group with them, in the order they had:
|
||||
/// abutting paths painted in another order would show a seam where they meet. Without parents,
|
||||
/// the nodes as they are.
|
||||
fn grouped(d: &mut Document, nodes: Vec<Node>, parents: &[Option<usize>]) -> Vec<Arc<Node>> {
|
||||
let n = nodes.len();
|
||||
let mut inside: Vec<Vec<usize>> = vec![vec![]; n];
|
||||
let mut roots = vec![];
|
||||
for i in 0..n {
|
||||
match parents.get(i).copied().flatten().and_then(|p| inside.get_mut(p).filter(|_| p != i)) {
|
||||
Some(of) => of.push(i),
|
||||
None => roots.push(i),
|
||||
}
|
||||
}
|
||||
// Outermost first, so that backwards each path comes after those inside it.
|
||||
let mut order = roots.clone();
|
||||
let mut at = 0;
|
||||
while let Some(&i) = order.get(at) {
|
||||
order.extend(inside.get(i).into_iter().flatten());
|
||||
at += 1;
|
||||
}
|
||||
let mut nodes: Vec<Option<Node>> = nodes.into_iter().map(Some).collect();
|
||||
let mut built: Vec<Option<Arc<Node>>> = vec![None; n];
|
||||
for &i in order.iter().rev() {
|
||||
let Some(node) = nodes.get_mut(i).and_then(Option::take) else { continue };
|
||||
let mut within: Vec<(usize, Arc<Node>)> = inside.get(i).into_iter().flatten().filter_map(|&c| Some((c, built.get_mut(c)?.take()?))).collect();
|
||||
let made = if within.is_empty() {
|
||||
node
|
||||
} else {
|
||||
within.push((i, Arc::new(node)));
|
||||
within.sort_by_key(|m| m.0);
|
||||
Node::group(d.alloc_id(), within.into_iter().map(|m| m.1).collect())
|
||||
};
|
||||
if let Some(slot) = built.get_mut(i) {
|
||||
*slot = Some(Arc::new(made));
|
||||
}
|
||||
}
|
||||
// (Paths that are inside each other in a ring are reached from no root: the tracer makes none,
|
||||
// and they are kept all the same.)
|
||||
let ring = nodes.into_iter().flatten().map(Arc::new).collect::<Vec<_>>();
|
||||
roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect()
|
||||
}
|
||||
|
||||
fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
const C: &str = "imageTrace.make";
|
||||
let mut params = trace_params(p)?;
|
||||
let view = view_param(C, p)?;
|
||||
let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
// The preset's name if the parameters are exactly that preset's or its enhanced version's,
|
||||
// else "Custom".
|
||||
let named = str_param(p, "preset").unwrap_or("Default");
|
||||
let is = |b: Option<tr::TraceParams>| b.and_then(|b| serde_json::to_value(&b).ok()).as_ref() == Some(¶ms_json);
|
||||
let preset_label = if is(tr::preset(named)) || is(tr::enhanced_preset(named)) { named.to_string() } else { "Custom".to_string() };
|
||||
let roots = root_ids(s, p)?;
|
||||
// The image (inside a trace group, or selected directly).
|
||||
let (target, img) = {
|
||||
let d = &s.doc()?.doc;
|
||||
roots
|
||||
.iter()
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ if is_trace_group(n) => match &n.children()?.first()?.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(C, "select an image (or an Image Trace group)"))?
|
||||
};
|
||||
let blob = s.doc()?.doc.images.get(&img.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", img.key)))?;
|
||||
// An image over the tracer's size is traced scaled down (the paths are scaled back below).
|
||||
let raster = tr::Raster::decode_to_fit(&blob.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let library = trace_library(s, &mut params)?;
|
||||
let res = tr::trace_within(&raster, ¶ms, MAX_TRACE_ANCHORS).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let warnings = trace_warnings((img.width, img.height), (raster.width, raster.height));
|
||||
// Pixel space of the decoded raster → the image object's pixel space → document.
|
||||
let sx = img.width.max(1) as f64 / raster.width.max(1) as f64;
|
||||
let sy = img.height.max(1) as f64 / raster.height.max(1) as f64;
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
let id = s.edit(label, |d, sel| {
|
||||
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut image = if is_trace_group(&src) {
|
||||
src.children()
|
||||
.and_then(|c| c.first())
|
||||
.map(|c| (**c).clone())
|
||||
.ok_or_else(|| EngineError::Other("Image Trace: the traced image is missing".into()))?
|
||||
} else {
|
||||
src.clone()
|
||||
};
|
||||
image.visible = true;
|
||||
let mut children: Vec<Arc<Node>> = vec![];
|
||||
if !expand {
|
||||
let mut hidden = image.clone();
|
||||
hidden.visible = false;
|
||||
children.push(Arc::new(hidden));
|
||||
}
|
||||
let mut traced = Vec::with_capacity(res.paths.len());
|
||||
for tp in res.paths {
|
||||
let path = tp.path.transformed(xf);
|
||||
let mut n = shape_node(d, path, None);
|
||||
// Shapes: a path the tracer found to be a shape is that live shape.
|
||||
if let (Some(shape), NodeKind::Path { path, live, .. }) = (tp.shape, &mut n.kind) {
|
||||
let shape = traced_shape(shape, xf);
|
||||
*path = shape.to_path();
|
||||
*live = Some(Box::new(shape));
|
||||
}
|
||||
// A library colour fills with the swatch's own colour (its model kept).
|
||||
let color = library.iter().find(|(rgb, _)| *rgb == tp.color).map_or_else(|| Color::rgb8(tp.color[0], tp.color[1], tp.color[2]), |l| l.1);
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
let paint = tp.gradient.as_ref().map_or_else(|| Paint::solid(color), |g| traced_gradient(g, xf));
|
||||
n.appearance = match tp.stroke {
|
||||
// Traced lines: round corners, and ends round or square as the tracer found them.
|
||||
Some(width) => Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: if tp.square_caps { LineCap::Square } else { LineCap::Round },
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint, width * unit)
|
||||
})],
|
||||
..Default::default()
|
||||
}
|
||||
.into(),
|
||||
None => fill_only(paint).into(),
|
||||
};
|
||||
traced.push(n);
|
||||
}
|
||||
children.extend(grouped(d, traced, &res.parents));
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for.
|
||||
let view = view.unwrap_or_else(|| src.trace_view());
|
||||
g.extras_mut().trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json, "view": view.id() })));
|
||||
}
|
||||
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
|
||||
d.remove(target)?;
|
||||
d.insert(par, idx, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "paths": npaths, "anchors": anchors, "colors": colors, "warnings": warnings }))
|
||||
}
|
||||
|
||||
/// Images larger than this on a side are traced, but more slowly: the trace says so.
|
||||
pub const LARGE_TRACE_SIDE: u32 = 1500;
|
||||
|
||||
/// What a trace of an image of `size` pixels, traced at `traced` pixels, tells the user: that a
|
||||
/// large image takes longer (the public documentation's warning for images over 1500 px), and that
|
||||
/// one over the tracer's [`tr::MAX_PIXELS`] was traced scaled down.
|
||||
pub(crate) fn trace_warnings(size: (u32, u32), traced: (u32, u32)) -> Vec<String> {
|
||||
let mut out = vec![];
|
||||
if size.0.max(size.1) > LARGE_TRACE_SIDE {
|
||||
out.push(format!(
|
||||
"The image is {} × {} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster.",
|
||||
size.0, size.1
|
||||
));
|
||||
}
|
||||
if u64::from(traced.0) * u64::from(traced.1) < u64::from(size.0) * u64::from(size.1) {
|
||||
out.push(format!(
|
||||
"The image was traced at {} × {} pixels, scaled down from {} × {} ({} megapixels at most).",
|
||||
traced.0,
|
||||
traced.1,
|
||||
size.0,
|
||||
size.1,
|
||||
tr::MAX_PIXELS >> 20
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn trace_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let v: Vec<NodeId> = root_ids(s, p)?.into_iter().filter(|i| d.node(*i).is_some_and(is_trace_group)).collect();
|
||||
if v.is_empty() {
|
||||
return Err(EngineError::Other("select an Image Trace object".into()));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn trace_set_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.setView";
|
||||
let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?;
|
||||
let targets = trace_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) {
|
||||
return Ok(json!({ "ids": ids_json(&targets), "view": view.id() }));
|
||||
}
|
||||
s.edit("Image Trace View", |d, _| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) {
|
||||
t.insert("view".into(), json!(view.id()));
|
||||
} else {
|
||||
n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() })));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets), "view": view.id() }))
|
||||
}
|
||||
|
||||
fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = trace_targets(s, p)?;
|
||||
let ids = s.edit("Release Image Trace", |d, sel| {
|
||||
let mut out = vec![];
|
||||
let mut released = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let mut img = (**n.children().and_then(|c| c.first()).ok_or(EngineError::NoNode(*g))?).clone();
|
||||
img.visible = true;
|
||||
out.push(img.id);
|
||||
released.put(d, *g, vec![img])?;
|
||||
}
|
||||
released.finish(d)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = trace_targets(s, p)?;
|
||||
s.edit("Expand Image Trace", |d, sel| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
n.name = None;
|
||||
n.extras_mut().trace = None;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| !matches!(c.kind, NodeKind::Image(_)));
|
||||
}
|
||||
}
|
||||
sel.set(targets.iter().copied());
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets) }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, trace_warnings};
|
||||
|
||||
#[test]
|
||||
fn trace_warnings_name_a_large_or_scaled_down_image() {
|
||||
assert!(trace_warnings((1500, 1500), (1500, 1500)).is_empty());
|
||||
assert_eq!(trace_warnings((1501, 10), (1501, 10)).len(), 1);
|
||||
let w = trace_warnings((16000, 12000), (9459, 7094));
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!(w[0].contains("16000 × 12000") && w[1].contains("9459 × 7094") && w[1].contains("64 megapixels"), "{w:?}");
|
||||
}
|
||||
|
||||
// A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit;
|
||||
// the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
|
||||
const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000);
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
use super::*;
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
fn stored_gap_options(options: GapOptions) -> Option<Box<GapOptions>> {
|
||||
(options != GapOptions::default()).then(|| Box::new(options))
|
||||
}
|
||||
|
||||
/// The Gap Options of Live Paint groups merged into one, given bottom-most first: the bottom-most
|
||||
/// group's when its Gap Detection is on; else Gap Detection on with Small Gaps when another
|
||||
/// group's is on; else the bottom-most group's.
|
||||
fn merged_gap_options(groups: &[GapOptions]) -> GapOptions {
|
||||
let Some(&bottom) = groups.first() else { return GapOptions::default() };
|
||||
if !bottom.detect && groups.iter().any(|g| g.detect) { GapOptions { detect: true, size: GapSize::Small, ..bottom } } else { bottom }
|
||||
}
|
||||
|
||||
/// Refuse `roots` when one of them is something Live Paint can't take ([`b::live_paint_takes`]):
|
||||
/// its faces and edges come from path outlines alone, so type or an image would vanish among the
|
||||
/// group's hidden sources. Checked before anything changes.
|
||||
fn check_live_paint_takes(d: &Document, roots: &[NodeId]) -> Result<()> {
|
||||
for r in roots {
|
||||
if !b::live_paint_takes(d.node(*r).ok_or(EngineError::NoNode(*r))?) {
|
||||
return Err(EngineError::Other(
|
||||
"Live Paint takes paths and compound paths: convert type, images and other objects to paths first".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make a Live Paint group from `roots`, or add them to the first Live Paint group among them
|
||||
/// as Merge does; returns (group, faces, edges).
|
||||
fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> {
|
||||
check_live_paint_takes(d, roots)?;
|
||||
if roots.iter().any(|r| d.node(*r).is_some_and(is_live_paint)) {
|
||||
return merge_live(d, sel, roots);
|
||||
}
|
||||
let mut sources = vec![];
|
||||
for r in roots {
|
||||
let n = d.node(*r).ok_or(EngineError::NoNode(*r))?;
|
||||
sources.extend(source_nodes(n));
|
||||
}
|
||||
let (children, nf, ne) = build_children(d, sources, None)?;
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = Some(LIVE_PAINT_NAME.into());
|
||||
replace_roots(d, roots, vec![g])?;
|
||||
sel.set([gid]);
|
||||
Ok((gid, nf, ne))
|
||||
}
|
||||
|
||||
pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let (id, faces, edges) = s.edit("Make Live Paint", |d, sel| make_live(d, sel, &roots))?;
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// Add the other `roots` (back → front) to the first Live Paint group among them, which keeps its
|
||||
/// id, the paint of its faces and edges, and its own properties apart from the Gap Options, which
|
||||
/// are merged; returns (group, faces, edges).
|
||||
fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> {
|
||||
let target = roots
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|r| d.node(*r).is_some_and(is_live_paint))
|
||||
.ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?;
|
||||
check_live_paint_takes(d, roots)?;
|
||||
let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
// Paint to carry over: (point inside face, fill) and (point on edge, stroke).
|
||||
let keep_faces: Vec<(Point, Paint)> = b::faces(&old)
|
||||
.iter()
|
||||
.filter(|f| !f.appearance.fill_paint().is_none())
|
||||
.filter_map(|f| Some((po::interior_point(f.path_data()?)?, f.appearance.fill_paint())))
|
||||
.collect();
|
||||
let keep_edges: Vec<(Point, Appearance)> = b::edges(&old)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let pd = e.path_data()?;
|
||||
let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?;
|
||||
Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), (*e.appearance).clone()))
|
||||
})
|
||||
.collect();
|
||||
let mut sources = source_nodes(&old);
|
||||
for r in roots {
|
||||
if *r != target {
|
||||
sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?));
|
||||
}
|
||||
}
|
||||
// Merge applies the Gap Options' merge rules to the groups' options, bottom-most first.
|
||||
let groups: Vec<GapOptions> = roots.iter().filter_map(|r| d.node(*r)).filter(|n| is_live_paint(n)).map(Node::gap_options).collect();
|
||||
let options = merged_gap_options(&groups);
|
||||
let (children, nf, ne) = build_children(d, sources, options.max_gap())?;
|
||||
// The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic
|
||||
// style link and the rest; its children are made again and its Gap Options set to the merged ones.
|
||||
let mut g = old;
|
||||
if let Some(ch) = g.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
g.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
for (pt, paint) in keep_faces {
|
||||
if let Some(fid) = face_at(&g, pt).map(|f| f.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(f) = ch.iter_mut().find(|c| c.id == fid)
|
||||
{
|
||||
Arc::make_mut(f).appearance.set_fill(paint);
|
||||
}
|
||||
}
|
||||
for (pt, app) in keep_edges {
|
||||
if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(e) = ch.iter_mut().find(|c| c.id == eid)
|
||||
{
|
||||
Arc::make_mut(e).appearance = app.into();
|
||||
}
|
||||
}
|
||||
let mut merged = Beside::replacing(d, roots);
|
||||
for r in roots.iter().filter(|r| **r != target) {
|
||||
if d.node(*r).is_some() {
|
||||
merged.put(d, *r, vec![])?;
|
||||
}
|
||||
}
|
||||
merged.put(d, target, vec![g])?;
|
||||
merged.finish(d)?;
|
||||
sel.set([target]);
|
||||
Ok((target, nf, ne))
|
||||
}
|
||||
|
||||
pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = root_ids(s, p)?;
|
||||
let v: Vec<NodeId> = ids.into_iter().filter(|i| d.node(*i).is_some_and(is_live_paint)).collect();
|
||||
if v.is_empty() {
|
||||
return Err(EngineError::Other("select a Live Paint group".into()));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = live_targets(s, p)?;
|
||||
let ids = s.edit("Release Live Paint", |d, sel| {
|
||||
let mut out = vec![];
|
||||
let mut released = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let srcs: Vec<Node> = source_nodes(&n).iter().map(|c| (**c).clone()).collect();
|
||||
out.extend(srcs.iter().map(|c| c.id));
|
||||
released.put(d, *g, srcs)?;
|
||||
}
|
||||
released.finish(d)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = live_targets(s, p)?;
|
||||
s.edit("Expand Live Paint", |d, sel| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
n.name = None;
|
||||
{
|
||||
let mut e = n.extras_mut();
|
||||
e.trace = None;
|
||||
e.live_paint_gaps = None;
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| match c.name.as_deref() {
|
||||
Some(SOURCES_NAME) => false,
|
||||
Some(FACE_NAME) => !c.appearance.fill_paint().is_none(),
|
||||
Some(EDGE_NAME) => !c.appearance.stroke_paint().is_none() && c.appearance.stroke_width() > 0.0,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
}
|
||||
sel.set(targets.iter().copied());
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets) }))
|
||||
}
|
||||
|
||||
/// Gaps as `[x0, y0, x1, y1]` (the loose end, then where it closes to).
|
||||
fn gaps_json(gaps: &[[Point; 2]]) -> Value {
|
||||
json!(gaps.iter().map(|[a, b]| [a.x, a.y, b.x, b.y]).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// A group's Gap Options as `livePaint.info` gives them.
|
||||
fn gap_options_json(o: GapOptions) -> Value {
|
||||
let [r, g, b] = o.color;
|
||||
let size = o.size.id().map_or_else(|| json!(o.size.points()), |id| json!(id));
|
||||
json!({ "detect": o.detect, "size": size, "points": o.size.points(), "color": format!("#{r:02x}{g:02x}{b:02x}") })
|
||||
}
|
||||
|
||||
/// The gaps up to `options`' size wide among a Live Paint group's sources.
|
||||
fn open_gaps(group: &Node, options: GapOptions) -> Vec<[Point; 2]> {
|
||||
po::find_gaps(&source_shapes(&source_nodes(group)).0, options.size.points())
|
||||
}
|
||||
|
||||
/// The gaps View › Show Live Paint Gaps shows on `group`: those up to its Gap Options' size wide,
|
||||
/// as `livePaint.info` lists them. None when `group` is not a Live Paint group.
|
||||
pub fn live_paint_gaps(group: &Node) -> Vec<[Point; 2]> {
|
||||
if is_live_paint(group) { open_gaps(group, group.gap_options()) } else { vec![] }
|
||||
}
|
||||
|
||||
pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.gapOptions";
|
||||
let detect = match p.get("detect").filter(|v| !v.is_null()) {
|
||||
Some(v) => Some(v.as_bool().ok_or_else(|| bad(C, "detect must be true or false"))?),
|
||||
None => None,
|
||||
};
|
||||
let size =
|
||||
match p.get("size").filter(|v| !v.is_null()) {
|
||||
Some(v) => Some(GapSize::parse(v).ok_or_else(|| {
|
||||
bad(C, format!("size must be \"small\", \"medium\", \"large\" or a number of points over 0 up to {}", GapSize::MAX))
|
||||
})?),
|
||||
None => None,
|
||||
};
|
||||
let color = match p.get("color").filter(|v| !v.is_null()) {
|
||||
Some(v) => Some(crate::cmd::layer::layer_color_param(v).map_err(|e| bad(C, e))?.rgb()),
|
||||
None => None,
|
||||
};
|
||||
let close = switch_or(p, "closeGaps", false, C)?;
|
||||
let targets = live_targets(s, p)?;
|
||||
let (faces, gaps, closed) = s.edit("Gap Options", |d, sel| {
|
||||
let (mut faces, mut gaps, mut closed) = (0, vec![], 0);
|
||||
let mut changed = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let old = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let mut options = old.gap_options();
|
||||
options.detect = detect.unwrap_or(options.detect);
|
||||
options.size = size.unwrap_or(options.size);
|
||||
options.color = color.unwrap_or(options.color);
|
||||
let mut sources = source_nodes(&old);
|
||||
if close {
|
||||
// Close Gaps With Paths adds an unpainted line across each gap to the group's paths.
|
||||
for gap in po::find_gaps(&source_shapes(&sources).0, options.size.points()) {
|
||||
let line = PathData::single(SubPath::polyline(&gap, false));
|
||||
sources.push(Arc::new(Node::path(d.alloc_id(), line, Appearance::default())));
|
||||
closed += 1;
|
||||
}
|
||||
}
|
||||
let mut n = old.clone();
|
||||
// The faces change only with what paint stops at, or with new paths.
|
||||
if close || options.max_gap() != old.gap_options().max_gap() {
|
||||
let (children, _, _) = build_children(d, sources, options.max_gap())?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
repaint_from(&mut n, &old);
|
||||
}
|
||||
n.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
faces += b::faces(&n).len();
|
||||
gaps.extend(open_gaps(&n, options));
|
||||
changed.put(d, *g, vec![n])?;
|
||||
}
|
||||
changed.finish(d)?;
|
||||
sel.set(targets.iter().copied());
|
||||
Ok((faces, gaps, closed))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed }))
|
||||
}
|
||||
|
||||
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.fill";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
|
||||
let group = id_param(p, "group");
|
||||
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
|
||||
let (g, face) = s.edit("Live Paint Bucket", |d, sel| {
|
||||
let gid = match group {
|
||||
Some(g) => {
|
||||
if !d.node(g).is_some_and(is_live_paint) {
|
||||
return Err(bad(C, format!("{g} is not a Live Paint group")));
|
||||
}
|
||||
g
|
||||
}
|
||||
None => {
|
||||
let live_at = |face: fn(&Node, Point) -> Option<&Arc<Node>>| {
|
||||
roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face(n, pt).is_some()))
|
||||
};
|
||||
match (live_at(b::visible_face_at), live_at(face_at)) {
|
||||
(Some(g), _) => g,
|
||||
// At a point on a hidden face of a Live Paint group among the objects, the command returns an error
|
||||
// and does not merge the objects.
|
||||
(None, Some(_)) => return Err(EngineError::Other("no Live Paint face at that point".into())),
|
||||
(None, None) => make_live(d, sel, &roots)?.0,
|
||||
}
|
||||
}
|
||||
};
|
||||
let fid = d
|
||||
.node(gid)
|
||||
.and_then(|n| b::visible_face_at(n, pt))
|
||||
.map(|f| f.id)
|
||||
.ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?;
|
||||
d.node_mut(fid).ok_or(EngineError::NoNode(fid))?.appearance.set_fill(paint.clone());
|
||||
Ok((gid, fid))
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "face": face.0 }))
|
||||
}
|
||||
|
||||
pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.strokeEdge";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let g = id_param(p, "group").ok_or_else(|| bad(C, "missing group"))?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.stroke.clone());
|
||||
let width = number_or(p, "width", s.paint.stroke_width.max(0.0), C)?;
|
||||
if !(0.0..=1000.0).contains(&width) {
|
||||
return Err(bad(C, "width out of range"));
|
||||
}
|
||||
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
|
||||
let edge = s.edit("Live Paint Bucket", |d, _| {
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
|
||||
let eid = b::visible_edge_near(n, pt, tol).map(|e| e.id).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
|
||||
let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
|
||||
e.appearance.set_stroke(paint.clone());
|
||||
if let Some(st) = e.appearance.stroke_mut() {
|
||||
st.width = width;
|
||||
}
|
||||
Ok(eid)
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "edge": edge.0 }))
|
||||
}
|
||||
|
||||
pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let g = id_param(p, "group").or_else(|| id_param(p, "id")).ok_or_else(|| bad("livePaint.info", "missing group"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad("livePaint.info", format!("{g} is not a Live Paint group")))?;
|
||||
let faces: Vec<Value> = b::faces(n)
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let bb = f.geometric_bounds().unwrap_or(Rect::ZERO);
|
||||
json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] })
|
||||
})
|
||||
.collect();
|
||||
let edges: Vec<Value> = b::edges(n)
|
||||
.iter()
|
||||
.map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() }))
|
||||
.collect();
|
||||
let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0);
|
||||
let options = n.gap_options();
|
||||
Ok(json!({
|
||||
"faces": faces,
|
||||
"edges": edges,
|
||||
"sources": sources,
|
||||
"gapOptions": gap_options_json(options),
|
||||
"gaps": gaps_json(&open_gaps(n, options)),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shapeBuilder.merge";
|
||||
let marquee = marquee_param(p, C)?;
|
||||
let pts = match points_param(p, "points") {
|
||||
Some(pts) => pts,
|
||||
// A marquee needs no drag path.
|
||||
None if marquee.is_some() && p.get("points").is_none_or(Value::is_null) => vec![],
|
||||
None => return Err(bad(C, "missing points [[x,y]…]")),
|
||||
};
|
||||
if (pts.is_empty() && marquee.is_none()) || !pts.iter().all(|q| finite(*q)) {
|
||||
return Err(bad(C, "points must be a non-empty list of finite [x,y]"));
|
||||
}
|
||||
let erase = switch_or(p, "erase", false, C)?;
|
||||
check_numbers(p, &["tolerance", "gap"], C)?;
|
||||
// Line pieces and edges are only deleted (erase mode), never merged.
|
||||
let piece_tol = erase.then(|| f64_or(p, "tolerance", 2.0).clamp(0.0, 1000.0));
|
||||
// In Merge Mode, Clicking Stroke Splits the Path: a click (one point) on a stroke splits it; a
|
||||
// marquee does not.
|
||||
let split_tol = (switch_or(p, "splitStroke", false, C)? && !erase && pts.len() == 1 && marquee.is_none())
|
||||
.then(|| f64_or(p, "tolerance", 2.0).clamp(0.0, 1000.0));
|
||||
let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, C)?;
|
||||
let swatches = match p.get("pickColorFrom") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => match v.as_str() {
|
||||
Some("artwork") => false,
|
||||
Some("swatches") => true,
|
||||
_ => return Err(bad(C, format!("pickColorFrom is \"artwork\" or \"swatches\", not {v}"))),
|
||||
},
|
||||
};
|
||||
let fill = match fill_param(s, p, C)? {
|
||||
None if swatches => Some(s.paint.fill.clone()),
|
||||
f => f,
|
||||
};
|
||||
let roots = root_ids(s, p)?;
|
||||
let gap = gap_param(p);
|
||||
// The map the Shape Builder tool already has, which a click or drag of it is made over.
|
||||
let shared = s.tool.shape_builder_map().filter(|(_, g)| *g == gap);
|
||||
let label = if erase { "Shape Builder Delete" } else { "Shape Builder" };
|
||||
let (ids, merged, touched, split) = s.edit(label, |d, sel| {
|
||||
let (shapes, leaves) = b::shape_builder_shapes(d, &roots, open_filled_as_closed);
|
||||
let built;
|
||||
let map = match &shared {
|
||||
// The tool's map has the outline edges, which erasing and splitting need.
|
||||
Some((m, _)) if m.shapes == shapes => m.as_ref(),
|
||||
_ => {
|
||||
built = BuilderMap::of_shapes(shapes, erase || split_tol.is_some(), gap);
|
||||
&built
|
||||
}
|
||||
};
|
||||
let outlines = b::drawn_outlines(d, &leaves);
|
||||
let leaves: Vec<Node> = leaves.into_iter().cloned().collect();
|
||||
if map.shapes.is_empty() {
|
||||
return Err(EngineError::Other("Shape Builder: select paths or compound paths".into()));
|
||||
}
|
||||
if let Some(tol) = split_tol
|
||||
&& let Some(&q) = pts.first()
|
||||
&& let Some((i, run)) = map.stroke_at(&outlines, q, tol)
|
||||
&& let (Some(leaf), Some(drawn)) = (leaves.get(i), outlines.get(i))
|
||||
&& let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && !leaf.appearance.fill_paint().is_none(), b::outline_snap(drawn))
|
||||
&& rest.length() > b::outline_snap(drawn)
|
||||
{
|
||||
// The path keeps the rest of it, and a copy of it with the run under the click goes
|
||||
// directly above it; the other objects stay as they are. Gradients fitted to the
|
||||
// path's bounds keep that fit on both.
|
||||
if let Some(n) = d.node_mut(leaf.id) {
|
||||
n.pin_gradients();
|
||||
}
|
||||
let pieces = [rest, PathData::single(run)].into_iter().filter(|pd| !pd.is_empty()).collect();
|
||||
let mut replaced = Beside::replacing(d, &[leaf.id]);
|
||||
let new_ids = replace_with_pieces(d, &mut replaced, leaf.id, pieces)?;
|
||||
replaced.finish(d)?;
|
||||
let split = *new_ids.last().ok_or(EngineError::NoNode(leaf.id))?;
|
||||
// Pick Color From Color Swatches (or `fill`): the stroke takes that paint.
|
||||
if let Some(f) = &fill
|
||||
&& let Some(n) = d.node_mut(split)
|
||||
{
|
||||
n.appearance.set_stroke(f.clone());
|
||||
}
|
||||
// The roots stay selected, with the two paths in place of the path when it was one.
|
||||
let ids: Vec<NodeId> = roots.iter().flat_map(|r| if *r == leaf.id { new_ids.clone() } else { vec![*r] }).collect();
|
||||
sel.set(ids.iter().copied());
|
||||
let mut touched = Touched::default();
|
||||
touched.add(map.hit(q, Some(tol)));
|
||||
return Ok((ids, None, touched, Some(split)));
|
||||
}
|
||||
let mut touched = Touched { regions: marquee.map(|(a, b)| map.regions_in_marquee(a, b)).unwrap_or_default(), ..Default::default() };
|
||||
touched.extend(&map.builder_hits_along(&pts, piece_tol));
|
||||
touched.edges = map.erased_edges(&touched);
|
||||
if touched.is_empty() {
|
||||
return Err(EngineError::Other("Shape Builder: no region under the pointer".into()));
|
||||
}
|
||||
let cuts: Vec<&SubPath> = touched.edges.iter().filter_map(|&k| map.edges.get(k)?.0.path.subpaths.first()).collect();
|
||||
let picked: Vec<&po::Region> = touched.regions.iter().filter_map(|&i| map.regions.get(i).map(|r| &r.0)).collect();
|
||||
let faces = po::FaceMerger::with_gap(&map.shapes, gap_param(p));
|
||||
let union = if picked.is_empty() { PathData::default() } else { faces.merge(&picked) };
|
||||
// Pick Color From Artwork: the merged shape takes the look of the front-most object under the
|
||||
// drag's first point, else under its last point, else of the front-most object. Color
|
||||
// Swatches: the current fill, with the rest of the look of the front-most object over the
|
||||
// first region the drag touched that an object covers, else of the front-most object. A
|
||||
// marquee's drag starts at its first corner and ends at the opposite one.
|
||||
let top_at = |q: &Point| map.region_at(*q).and_then(|k| map.regions.get(k)).and_then(|(r, ..)| r.top());
|
||||
let (first, last) = match marquee {
|
||||
Some((a, b)) => (Some(a), Some(b)),
|
||||
None => (pts.first().copied(), pts.last().copied()),
|
||||
};
|
||||
let covered =
|
||||
if swatches { picked.iter().find_map(|r| r.top()) } else { first.as_ref().and_then(top_at).or_else(|| last.as_ref().and_then(top_at)) };
|
||||
let style_src = covered.or(map.shapes.len().checked_sub(1));
|
||||
let mut new_nodes: Vec<Node> = vec![];
|
||||
let mut merged_id = None;
|
||||
for (i, (sh, leaf)) in map.shapes.iter().zip(&leaves).enumerate() {
|
||||
let pieces: Vec<usize> = map.lines.iter().enumerate().filter(|(_, (l, _))| l.key == i as u64).map(|(k, _)| k).collect();
|
||||
if !pieces.is_empty() {
|
||||
// An open path loses the pieces deleted and those between two merged (or deleted) regions.
|
||||
let keep: Vec<usize> =
|
||||
pieces.iter().copied().filter(|k| !touched.lines.contains(k) && !map.line_between(*k, &touched.regions)).collect();
|
||||
if keep.len() == pieces.len() {
|
||||
new_nodes.push(d.reid(leaf));
|
||||
} else {
|
||||
for k in keep {
|
||||
if let Some((l, _)) = map.lines.get(k) {
|
||||
new_nodes.push(remnant(d, leaf, l.path.clone(), None));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// A shape loses the regions deleted or merged, then the edges deleted (each one on
|
||||
// its outline, shared edges from every shape along them).
|
||||
let in_union = picked.iter().any(|r| r.sources.contains(&i));
|
||||
let mut rest = if in_union {
|
||||
// What is left of it: its faces not merged or deleted, united. They share their
|
||||
// edges with the merged faces exactly, where subtracting the merged shape left
|
||||
// slivers of the outline along them (#569). A sliver goes in only where the
|
||||
// shape covers it and the merged shape does not take it in.
|
||||
let kept: Vec<&po::Region> = map
|
||||
.regions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(k, (r, ..))| r.sources.contains(&i) && !touched.regions.contains(k))
|
||||
.map(|(_, (r, ..))| r)
|
||||
.collect();
|
||||
if kept.is_empty() { PathData::default() } else { faces.merge_rest(i, &kept, &picked) }
|
||||
} else {
|
||||
b::node_outline(leaf).map_or_else(|| sh.path.clone(), |o| o.0)
|
||||
};
|
||||
let fill_closes = open_filled_as_closed && !leaf.appearance.fill_paint().is_none();
|
||||
// Edges come back from the planar map within a few hundredths of the outlines they
|
||||
// follow, whatever else is selected.
|
||||
let cut_tol = b::outline_snap(&sh.path);
|
||||
let mut cut = false;
|
||||
for piece in &cuts {
|
||||
if let Some(r) = po::cut_out(&rest, piece, fill_closes, cut_tol) {
|
||||
rest = r;
|
||||
cut = true;
|
||||
}
|
||||
}
|
||||
if !in_union && !cut {
|
||||
new_nodes.push(d.reid(leaf));
|
||||
} else if !rest.is_empty() {
|
||||
// What is left of its own outline keeps its fill rule; united faces fill with non-zero.
|
||||
new_nodes.push(remnant(d, leaf, rest, in_union.then_some(FillRule::NonZero)));
|
||||
}
|
||||
}
|
||||
if !erase && !union.is_empty() && Some(i) == style_src {
|
||||
let mut m = shape_node(d, union.clone(), Some(leaf));
|
||||
if let Some(f) = &fill {
|
||||
m.appearance.set_fill(f.clone());
|
||||
}
|
||||
merged_id = Some(m.id);
|
||||
new_nodes.push(m);
|
||||
}
|
||||
}
|
||||
let new_ids = replace_roots(d, &roots, new_nodes)?;
|
||||
sel.set(new_ids.iter().copied());
|
||||
Ok((new_ids, merged_id, touched, None))
|
||||
})?;
|
||||
let mut out = json!({
|
||||
"ids": ids_json(&ids),
|
||||
"merged": merged.map(|m| m.0),
|
||||
"regions": touched.regions.len(),
|
||||
"lines": touched.lines.len(),
|
||||
"edges": touched.edges.len(),
|
||||
});
|
||||
if let Some(e) = split {
|
||||
out["split"] = json!(e.0);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(super) fn sb_regions(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, "shapeBuilder.regions")?;
|
||||
check_numbers(p, &["gap"], "shapeBuilder.regions")?;
|
||||
let roots = root_ids(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (map, leaves) = BuilderMap::with_gap(d, &roots, true, open_filled_as_closed, gap_param(p));
|
||||
let id_of = |i: usize| leaves.get(i).map(|n| n.id.0);
|
||||
let regions: Vec<Value> = map
|
||||
.regions
|
||||
.iter()
|
||||
.map(|(r, _, bb)| {
|
||||
json!({
|
||||
"bounds": [bb.x0, bb.y0, bb.x1, bb.y1],
|
||||
"area": po::area(&r.path, FillRule::NonZero),
|
||||
"sources": r.sources.iter().filter_map(|&i| id_of(i)).collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let pieces = |list: &[(po::Shape, Rect)]| -> Vec<Value> {
|
||||
list.iter().map(|(l, bb)| json!({ "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], "source": id_of(l.key as usize) })).collect()
|
||||
};
|
||||
Ok(json!({ "regions": regions, "lines": pieces(&map.lines), "edges": pieces(&map.edges) }))
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
use super::*;
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
|
||||
fn is_trace_group(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& n.name.as_deref() == Some(TRACE_NAME)
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// The `view` param ([`TraceView`] id), if given.
|
||||
fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let ids = || TraceView::ALL.map(TraceView::id).join(", ");
|
||||
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
|
||||
}
|
||||
|
||||
/// The parameters command `c` traces with: the preset's, with `params` over them.
|
||||
fn trace_params(c: &str, p: &Value) -> Result<tr::TraceParams> {
|
||||
let name = str_param(p, "preset").unwrap_or("Default");
|
||||
let enhanced = switch_or(p, "enhanced", false, c)?;
|
||||
// (A preset without an enhanced version is traced as it is.)
|
||||
let base = enhanced.then(|| tr::enhanced_preset(name)).flatten().or_else(|| tr::preset(name));
|
||||
let base = base.ok_or_else(|| bad(c, format!("unknown preset `{name}` (see imageTrace.presets)")))?;
|
||||
let Some(over) = p.get("params").filter(|v| !v.is_null()) else { return Ok(base) };
|
||||
let mut v = serde_json::to_value(&base).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let (Some(o), Some(src)) = (v.as_object_mut(), over.as_object()) else { return Err(bad(c, "params must be an object")) };
|
||||
// A key that isn't one of the settings is an error, with the nearest setting.
|
||||
if let Some(key) = src.keys().find(|k| !o.contains_key(k.as_str())) {
|
||||
return Err(crate::cmd::params::unknown(c, key, &o.keys().map(String::as_str).collect::<Vec<_>>()));
|
||||
}
|
||||
for (k, val) in src {
|
||||
o.insert(k.clone(), val.clone());
|
||||
}
|
||||
let params: tr::TraceParams = serde_json::from_value(v).map_err(|e| bad(c, e.to_string()))?;
|
||||
if !params.fills && !params.strokes {
|
||||
return Err(bad(c, "Create needs fills, strokes or both"));
|
||||
}
|
||||
if !(params.stroke_width.is_finite() && params.stroke_width > 0.0) {
|
||||
return Err(bad(c, "strokeWidth must be a positive number of pixels"));
|
||||
}
|
||||
// A color group is refused unless the trace uses it: Color mode with Document Library and the
|
||||
// document's swatches.
|
||||
if params.color_group.as_deref().is_some_and(|g| !g.is_empty()) {
|
||||
if params.palette != tr::Palette::DocumentLibrary {
|
||||
return Err(bad(c, "`colorGroup` needs `palette: \"documentLibrary\"`"));
|
||||
}
|
||||
if params.library != crate::cmd::swatchlib::DOCUMENT_SWATCHES {
|
||||
return Err(bad(c, "`colorGroup` needs `library: \"document\"`"));
|
||||
}
|
||||
if params.mode != tr::Mode::Color {
|
||||
return Err(bad(c, "`colorGroup` needs `mode: \"color\"`"));
|
||||
}
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
|
||||
/// Document Library with `colorGroup`: the solid colors of the active document's color group
|
||||
/// `name` (so named exactly, else ignoring case). Errors name command `c`.
|
||||
/// ([`trace_params`] has checked that the library is the document's swatches.)
|
||||
fn trace_group_colors(c: &str, s: &Session, name: &str) -> Result<Vec<Color>> {
|
||||
let groups = &s.doc()?.doc.swatch_groups;
|
||||
let lower = name.to_lowercase();
|
||||
let group = groups
|
||||
.iter()
|
||||
.find(|g| g.name == name)
|
||||
.or_else(|| groups.iter().find(|g| g.name.to_lowercase() == lower))
|
||||
.ok_or_else(|| bad(c, format!("no color group `{name}` in the document (see swatch.list)")))?;
|
||||
Ok(group.swatches.iter().filter_map(|w| w.paint.color()).collect())
|
||||
}
|
||||
|
||||
/// Document Library in Color mode: look the library's colors (or its color group's) up into
|
||||
/// `params.swatches` → each one as traced (sRGB) with the color to fill with. Errors name command `c`.
|
||||
fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result<Vec<([u8; 3], Color)>> {
|
||||
if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let group = params.color_group.as_deref().filter(|g| !g.is_empty());
|
||||
let key = group.unwrap_or(params.library.as_str());
|
||||
let colors = match group {
|
||||
Some(name) => trace_group_colors(c, s, name)?,
|
||||
None => crate::cmd::swatchlib::library_colors(s, key)
|
||||
.ok_or_else(|| bad(c, format!("no swatch library `{key}` (see swatch.library.list; \"document\": the document's swatches)")))?,
|
||||
};
|
||||
if colors.is_empty() {
|
||||
return Err(bad(c, format!("`{key}` has no colours")));
|
||||
}
|
||||
let library: Vec<([u8; 3], Color)> = colors
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
([r, g, b], c)
|
||||
})
|
||||
.collect();
|
||||
params.swatches = library.iter().map(|l| l.0).collect();
|
||||
Ok(library)
|
||||
}
|
||||
|
||||
/// The most anchor points an Image Trace may make, a guard for memory: a trace past it is refused
|
||||
/// with advice instead (#525). A trace keeps about 90 bytes an anchor in the document (measured on
|
||||
/// code-drawn photos of 2000 × 2000 to 6000 × 4000 pixels), so 8,000,000 anchors are about
|
||||
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at High Fidelity Photo
|
||||
/// makes about 1.9 million, and even at Paths 100, Noise 1 and every tone about 7.9 million. On the
|
||||
/// web, where a page has at most 4 GB of memory, the limit stays at 2,000,000.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub const MAX_TRACE_ANCHORS: usize = 8_000_000;
|
||||
|
||||
/// The most anchor points an Image Trace may make on the web (see the native limit).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub const MAX_TRACE_ANCHORS: usize = 2_000_000;
|
||||
|
||||
/// The live shape for a shape the tracer found (in the image's pixels), placed in the document by `xf`.
|
||||
fn traced_shape(shape: tr::TracedShape, xf: vectorcraft_geom::Affine) -> LiveShape {
|
||||
use vectorcraft_geom::Affine;
|
||||
let about = |c: Point, deg: f64| Affine::translate(c.to_vec2()) * Affine::rotate(deg.to_radians());
|
||||
let mut live = match shape {
|
||||
tr::TracedShape::Rectangle { center, width, height, radius, rotation } => LiveShape::Rectangle {
|
||||
w: width,
|
||||
h: height,
|
||||
radii: [radius; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: about(center, rotation) * Affine::translate((-width / 2.0, -height / 2.0)),
|
||||
},
|
||||
tr::TracedShape::Ellipse { center, rx, ry, rotation } => {
|
||||
LiveShape::Ellipse { w: 2.0 * rx, h: 2.0 * ry, pie: (0.0, 360.0), xf: about(center, rotation) * Affine::translate((-rx, -ry)) }
|
||||
}
|
||||
tr::TracedShape::Polygon { center, radius, sides, rotation } => {
|
||||
LiveShape::Polygon { radius, sides, xf: about(center, rotation), radii: vec![], kinds: vec![], radii_relative: false }
|
||||
}
|
||||
};
|
||||
// (Whether the move changed the shape's own numbers does not matter: its path is made from them next.)
|
||||
let _ = live.transform(xf);
|
||||
live
|
||||
}
|
||||
|
||||
/// The gradient fill for a linear gradient the tracer found (in the image's pixels), placed in the
|
||||
/// document by `xf`.
|
||||
fn traced_gradient(g: &tr::TracedGradient, xf: vectorcraft_geom::Affine) -> Paint {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = g.stops.iter().map(|&(at, c)| GradientStop::new(at as f32, Color::rgb8(c[0], c[1], c[2]))).collect();
|
||||
let mut paint = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
paint.geom = Some(GradientGeom { start: xf * g.start, end: xf * g.end, aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(paint))
|
||||
}
|
||||
|
||||
/// Auto Grouping: `nodes` (one per traced path, bottom-most first) with each path that has others
|
||||
/// inside it (`parents`, as the tracer gives them) in a group with them, in the order they had:
|
||||
/// abutting paths painted in another order would show a seam where they meet. Without parents,
|
||||
/// the nodes as they are.
|
||||
fn grouped(d: &mut Document, nodes: Vec<Node>, parents: &[Option<usize>]) -> Vec<Arc<Node>> {
|
||||
let n = nodes.len();
|
||||
let mut inside: Vec<Vec<usize>> = vec![vec![]; n];
|
||||
let mut roots = vec![];
|
||||
for i in 0..n {
|
||||
match parents.get(i).copied().flatten().and_then(|p| inside.get_mut(p).filter(|_| p != i)) {
|
||||
Some(of) => of.push(i),
|
||||
None => roots.push(i),
|
||||
}
|
||||
}
|
||||
// Outermost first, so that backwards each path comes after those inside it.
|
||||
let mut order = roots.clone();
|
||||
let mut at = 0;
|
||||
while let Some(&i) = order.get(at) {
|
||||
order.extend(inside.get(i).into_iter().flatten());
|
||||
at += 1;
|
||||
}
|
||||
let mut nodes: Vec<Option<Node>> = nodes.into_iter().map(Some).collect();
|
||||
let mut built: Vec<Option<Arc<Node>>> = vec![None; n];
|
||||
for &i in order.iter().rev() {
|
||||
let Some(node) = nodes.get_mut(i).and_then(Option::take) else { continue };
|
||||
let mut within: Vec<(usize, Arc<Node>)> = inside.get(i).into_iter().flatten().filter_map(|&c| Some((c, built.get_mut(c)?.take()?))).collect();
|
||||
let made = if within.is_empty() {
|
||||
node
|
||||
} else {
|
||||
within.push((i, Arc::new(node)));
|
||||
within.sort_by_key(|m| m.0);
|
||||
Node::group(d.alloc_id(), within.into_iter().map(|m| m.1).collect())
|
||||
};
|
||||
if let Some(slot) = built.get_mut(i) {
|
||||
*slot = Some(Arc::new(made));
|
||||
}
|
||||
}
|
||||
// (Paths that are inside each other in a ring are reached from no root: the tracer makes none,
|
||||
// and they are kept all the same.)
|
||||
let ring = nodes.into_iter().flatten().map(Arc::new).collect::<Vec<_>>();
|
||||
roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect()
|
||||
}
|
||||
|
||||
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
let mut params = trace_params(c, p)?;
|
||||
let view = view_param(c, p)?;
|
||||
let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
// The preset's name if the parameters are exactly that preset's or its enhanced version's,
|
||||
// else "Custom".
|
||||
let named = str_param(p, "preset").unwrap_or("Default");
|
||||
let is = |b: Option<tr::TraceParams>| b.and_then(|b| serde_json::to_value(&b).ok()).as_ref() == Some(¶ms_json);
|
||||
let preset_label = if is(tr::preset(named)) || is(tr::enhanced_preset(named)) { named.to_string() } else { "Custom".to_string() };
|
||||
let roots = root_ids(s, p)?;
|
||||
// The image (inside a trace group, or selected directly).
|
||||
let (target, img) = {
|
||||
let d = &s.doc()?.doc;
|
||||
roots
|
||||
.iter()
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ if is_trace_group(n) => match &n.children()?.first()?.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))?
|
||||
};
|
||||
let blob = s.doc()?.doc.images.get(&img.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", img.key)))?;
|
||||
// An image over the tracer's size is traced scaled down (the paths are scaled back below).
|
||||
let raster = tr::Raster::decode_to_fit(&blob.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
let res = tr::trace_within(&raster, ¶ms, MAX_TRACE_ANCHORS).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let warnings = trace_warnings((img.width, img.height), (raster.width, raster.height), res.worked_at);
|
||||
// Pixel space of the decoded raster → the image object's pixel space → document.
|
||||
let sx = img.width.max(1) as f64 / raster.width.max(1) as f64;
|
||||
let sy = img.height.max(1) as f64 / raster.height.max(1) as f64;
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
let id = s.edit(label, |d, sel| {
|
||||
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut image = if is_trace_group(&src) {
|
||||
src.children()
|
||||
.and_then(|c| c.first())
|
||||
.map(|c| (**c).clone())
|
||||
.ok_or_else(|| EngineError::Other("Image Trace: the traced image is missing".into()))?
|
||||
} else {
|
||||
src.clone()
|
||||
};
|
||||
image.visible = true;
|
||||
let mut children: Vec<Arc<Node>> = vec![];
|
||||
if !expand {
|
||||
let mut hidden = image.clone();
|
||||
hidden.visible = false;
|
||||
children.push(Arc::new(hidden));
|
||||
}
|
||||
let mut traced = Vec::with_capacity(res.paths.len());
|
||||
for tp in res.paths {
|
||||
let path = tp.path.transformed(xf);
|
||||
let mut n = shape_node(d, path, None);
|
||||
// Shapes: a path the tracer found to be a shape is that live shape.
|
||||
if let (Some(shape), NodeKind::Path { path, live, .. }) = (tp.shape, &mut n.kind) {
|
||||
let shape = traced_shape(shape, xf);
|
||||
*path = shape.to_path();
|
||||
*live = Some(Box::new(shape));
|
||||
}
|
||||
// A library colour fills with the swatch's own colour (its model kept).
|
||||
let color = library.iter().find(|(rgb, _)| *rgb == tp.color).map_or_else(|| Color::rgb8(tp.color[0], tp.color[1], tp.color[2]), |l| l.1);
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
let paint = tp.gradient.as_ref().map_or_else(|| Paint::solid(color), |g| traced_gradient(g, xf));
|
||||
n.appearance = match tp.stroke {
|
||||
// Traced lines: round corners, and ends round or square as the tracer found them.
|
||||
Some(width) => Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: if tp.square_caps { LineCap::Square } else { LineCap::Round },
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint, width * unit)
|
||||
})],
|
||||
..Default::default()
|
||||
}
|
||||
.into(),
|
||||
None => fill_only(paint).into(),
|
||||
};
|
||||
traced.push(n);
|
||||
}
|
||||
children.extend(grouped(d, traced, &res.parents));
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for.
|
||||
let view = view.unwrap_or_else(|| src.trace_view());
|
||||
g.extras_mut().trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json, "view": view.id() })));
|
||||
}
|
||||
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
|
||||
d.remove(target)?;
|
||||
d.insert(par, idx, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "paths": npaths, "anchors": anchors, "colors": colors, "warnings": warnings }))
|
||||
}
|
||||
|
||||
/// Images larger than this on a side are traced, but more slowly: the trace says so.
|
||||
pub const LARGE_TRACE_SIDE: u32 = 1500;
|
||||
|
||||
/// What a trace of an image of `size` pixels, traced at `traced` pixels, tells the user: that
|
||||
/// Flat Logo averaged it down to `worked` pixels first, or else that a large image takes longer
|
||||
/// (the public documentation's warning for images over 1500 px) and that one over the tracer's
|
||||
/// [`tr::MAX_PIXELS`] was traced scaled down.
|
||||
pub(crate) fn trace_warnings(size: (u32, u32), traced: (u32, u32), worked: Option<(u32, u32)>) -> Vec<String> {
|
||||
let mut out = vec![];
|
||||
if worked.is_none() && size.0.max(size.1) > LARGE_TRACE_SIDE {
|
||||
out.push(format!(
|
||||
"The image is {} × {} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster.",
|
||||
size.0, size.1
|
||||
));
|
||||
}
|
||||
if let Some(worked) = worked {
|
||||
out.push(format!("Flat Logo traced the image at {} × {} pixels, averaged down from {} × {}.", worked.0, worked.1, size.0, size.1));
|
||||
} else if u64::from(traced.0) * u64::from(traced.1) < u64::from(size.0) * u64::from(size.1) {
|
||||
out.push(format!(
|
||||
"The image was traced at {} × {} pixels, scaled down from {} × {} ({} megapixels at most).",
|
||||
traced.0,
|
||||
traced.1,
|
||||
size.0,
|
||||
size.1,
|
||||
tr::MAX_PIXELS >> 20
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn trace_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let v: Vec<NodeId> = root_ids(s, p)?.into_iter().filter(|i| d.node(*i).is_some_and(is_trace_group)).collect();
|
||||
if v.is_empty() {
|
||||
return Err(EngineError::Other("select an Image Trace object".into()));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
pub(super) fn trace_set_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.setView";
|
||||
let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?;
|
||||
let targets = trace_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) {
|
||||
return Ok(json!({ "ids": ids_json(&targets), "view": view.id() }));
|
||||
}
|
||||
s.edit("Image Trace View", |d, _| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) {
|
||||
t.insert("view".into(), json!(view.id()));
|
||||
} else {
|
||||
n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() })));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets), "view": view.id() }))
|
||||
}
|
||||
|
||||
pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = trace_targets(s, p)?;
|
||||
let ids = s.edit("Release Image Trace", |d, sel| {
|
||||
let mut out = vec![];
|
||||
let mut released = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let mut img = (**n.children().and_then(|c| c.first()).ok_or(EngineError::NoNode(*g))?).clone();
|
||||
img.visible = true;
|
||||
out.push(img.id);
|
||||
released.put(d, *g, vec![img])?;
|
||||
}
|
||||
released.finish(d)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = trace_targets(s, p)?;
|
||||
s.edit("Expand Image Trace", |d, sel| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
n.name = None;
|
||||
n.extras_mut().trace = None;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| !matches!(c.kind, NodeKind::Image(_)));
|
||||
}
|
||||
}
|
||||
sel.set(targets.iter().copied());
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets) }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, trace_warnings};
|
||||
|
||||
#[test]
|
||||
fn trace_warnings_name_a_large_or_scaled_down_image() {
|
||||
assert!(trace_warnings((1500, 1500), (1500, 1500), None).is_empty());
|
||||
assert_eq!(trace_warnings((1501, 10), (1501, 10), None).len(), 1);
|
||||
let w = trace_warnings((16000, 12000), (9459, 7094), None);
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!(w[0].contains("16000 × 12000") && w[1].contains("9459 × 7094") && w[1].contains("64 megapixels"), "{w:?}");
|
||||
// Flat Logo's own working size is named instead of the megapixel limit.
|
||||
let w = trace_warnings((1025, 1025), (1025, 1025), Some((513, 513)));
|
||||
assert_eq!(w, ["Flat Logo traced the image at 513 × 513 pixels, averaged down from 1025 × 1025."]);
|
||||
// Flat Logo traces a large image at its reduced size, so it gives no slow-trace warning.
|
||||
let w = trace_warnings((1600, 1600), (1600, 1600), Some((800, 800)));
|
||||
assert_eq!(w, ["Flat Logo traced the image at 800 × 800 pixels, averaged down from 1600 × 1600."]);
|
||||
let w = trace_warnings((16000, 12000), (9459, 7094), Some((946, 710)));
|
||||
assert_eq!(w, ["Flat Logo traced the image at 946 × 710 pixels, averaged down from 16000 × 12000."]);
|
||||
}
|
||||
|
||||
// A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit;
|
||||
// the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
|
||||
const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000);
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
//! text besides it (see `flavours`).
|
||||
|
||||
mod flavours;
|
||||
mod resources;
|
||||
pub(crate) mod resources;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
@@ -21,8 +21,9 @@ use vectorcraft_color::Swatch;
|
||||
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
pub use flavours::{BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
|
||||
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
|
||||
pub(crate) use resources::SwatchChoices;
|
||||
pub use resources::{ArtResources, art_resources};
|
||||
|
||||
use super::*;
|
||||
use crate::DocState;
|
||||
|
||||
@@ -30,6 +30,10 @@ pub const EMF: &str = "image/emf";
|
||||
/// An EPS (or other PostScript) picture: what drawing and typesetting apps copy as vector art
|
||||
/// beside, or instead of, a PDF (#1499).
|
||||
pub const EPS: &str = "application/postscript";
|
||||
/// A `.ai` or `.ait` file whose bytes are a PDF, copied in a file manager ([`file_flavour`]): Paste
|
||||
/// reads it as `document.open` does, from its editing data. The type is VectorCraft's own: no
|
||||
/// system clipboard carries it, and Paste asks for [`PDF`] to get it.
|
||||
pub const AI: &str = "application/x-ai";
|
||||
/// What Paste reads from other apps, best first: vector art before text, text before bitmaps
|
||||
/// (word processors offer a picture of copied text too).
|
||||
pub const PASTE_ORDER: [&str; 6] = [SVG, PDF, EPS, EMF, TEXT, BITMAP];
|
||||
@@ -71,8 +75,9 @@ pub const FILE_HEAD: usize = 4096;
|
||||
|
||||
/// What a file copied in a file manager pastes as, if one of `mimes` (`image/*`: any bitmap):
|
||||
/// SVG, PDF, EPS, a Windows metafile or a bitmap (its own `image/…` type), told from its first
|
||||
/// [`FILE_HEAD`] bytes and its name. A `.ai` or `.ait` file pastes as PDF when its bytes are a
|
||||
/// PDF and as EPS when they are PostScript. The file's bytes are that flavour's data.
|
||||
/// [`FILE_HEAD`] bytes and its name. A `.ai` or `.ait` file is [`AI`] when its bytes are a PDF (it
|
||||
/// pastes when PDF is asked for) and EPS when they are PostScript. The file's bytes are that
|
||||
/// flavour's data.
|
||||
pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static str> {
|
||||
let f = fileio::detect(name, head)?;
|
||||
let (asked, mime) = match f.id {
|
||||
@@ -83,7 +88,7 @@ pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static
|
||||
"pdf" => (PDF, PDF),
|
||||
"ps" => (EPS, EPS),
|
||||
"eps" => (EPS, EPS),
|
||||
"ai" | "ait" if head.starts_with(b"%PDF") => (PDF, PDF),
|
||||
"ai" | "ait" if head.starts_with(b"%PDF") => (PDF, AI),
|
||||
"ai" | "ait" if vectorcraft_pdf::is_postscript(head) => (EPS, EPS),
|
||||
"emf" | "wmf" => (EMF, EMF),
|
||||
_ if f.raster => (BITMAP, f.mime),
|
||||
@@ -122,6 +127,13 @@ pub struct Flavour {
|
||||
const COPY_PNG_SIDE: f64 = 4096.0;
|
||||
/// Most bytes of text `clipboard.importText` takes.
|
||||
const MAX_TEXT: usize = 1 << 20;
|
||||
/// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the
|
||||
/// clipboard's text first (eframe reads it on every paste key; on Linux and macOS it is the one
|
||||
/// format the app writes, and checking that the clipboard still holds our copy reads it again), so
|
||||
/// a placed photo in it made each paste move megabytes of base64 through the system clipboard on
|
||||
/// the UI thread, and on a GNOME desktop the app stopped responding (#2213). A copy with more image
|
||||
/// data than this offers its SVG under its own type and its PNG, not as text.
|
||||
const COPY_TEXT_IMAGE_BYTES: usize = 1 << 20;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -157,7 +169,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clipboard Formats",
|
||||
[],
|
||||
None,
|
||||
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut",
|
||||
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut",
|
||||
always,
|
||||
flavours
|
||||
),
|
||||
@@ -184,7 +196,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load PDF into Clipboard",
|
||||
[],
|
||||
None,
|
||||
"{dataBase64, page?: 1, password? (an encrypted PDF), center?: [x, y]} replace the clipboard with the objects of one PDF page (with the images, patterns and swatches they use), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste",
|
||||
"{dataBase64, page?: 1, password? (an encrypted PDF), editingData?: false (true: the data is a .ai or .ait file, read as document.open reads it; when document.open would use its editing data, every object of that data comes in, each layer's objects in stacking order and a hidden layer's objects hidden; else page `page`), center?: [x, y]} replace the clipboard with the objects of one PDF page, or of a .ai file's editing data (with the images, patterns and swatches they use; a .ai saved without PDF compatibility: every object of its editing data, as document.open reads it, with or without editingData), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste",
|
||||
has_doc,
|
||||
import_pdf
|
||||
),
|
||||
@@ -202,7 +214,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load EPS into Clipboard",
|
||||
[],
|
||||
None,
|
||||
"{dataBase64 (EPS or other PostScript bytes), center?: [x, y]} replace the clipboard with the picture's objects as document.open reads an EPS (editable paths, type and images, with the images, patterns and swatches they use), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste",
|
||||
"{dataBase64 (EPS or other PostScript bytes), center?: [x, y]} replace the clipboard with the picture's objects as document.open reads an EPS (editable paths, type and images, with the images, patterns and swatches they use; a hidden layer's objects hidden), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste",
|
||||
has_doc,
|
||||
import_eps
|
||||
),
|
||||
@@ -263,12 +275,17 @@ impl Clipboard {
|
||||
fileio::encode_with_warnings(&doc, "pdf", &json!({ "preserveEditing": false })).map(Some)
|
||||
}
|
||||
|
||||
/// Bytes of the encoded images the objects show (what their SVG embeds as base64).
|
||||
fn image_bytes(&self) -> usize {
|
||||
self.images.values().fold(0usize, |sum, b| sum.saturating_add(b.bytes.len()))
|
||||
}
|
||||
|
||||
/// The MIME types of [`Self::flavours`], without making them.
|
||||
pub fn flavour_types(&self, svg: bool, pdf: bool) -> Vec<&'static str> {
|
||||
if self.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let text = svg || self.nodes.iter().all(type_only);
|
||||
let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only);
|
||||
// Art without an area (a lone guide-like line) has no page or picture.
|
||||
let area = self.bounds().is_some_and(|b| b.width() > 0.0 && b.height() > 0.0);
|
||||
[(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area)].into_iter().filter_map(|(m, on)| on.then_some(m)).collect()
|
||||
@@ -404,8 +421,15 @@ fn import_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let img = fileio::raster_image(&data_param(p, C)?).map_err(|e| bad(C, e.to_string()))?;
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
let (w, h) = (img.width, img.height);
|
||||
let image =
|
||||
ImageObject { key: img.key.clone(), width: w, height: h, xf: Affine::scale_non_uniform(sx, sy), link: None, placement: Default::default() };
|
||||
let image = ImageObject {
|
||||
key: img.key.clone(),
|
||||
width: w,
|
||||
height: h,
|
||||
xf: Affine::scale_non_uniform(sx, sy),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let mut clip = Clipboard { nodes: vec![Node::new(NodeId(1), NodeKind::Image(Box::new(image)))], ..Default::default() };
|
||||
clip.images.insert(img.key, img.blob);
|
||||
let count = s.load_clipboard(clip, p)?;
|
||||
@@ -424,6 +448,7 @@ fn import_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "the text is empty"));
|
||||
}
|
||||
let mut t = TextObject::point(Point::ZERO, text, super::super::create::new_type_style(s, &Value::Null));
|
||||
t.system_layout = s.doc()?.doc.setup.system_layout;
|
||||
crate::cmd::typecmd::refresh_bounds(&mut t);
|
||||
let n = Node::new(NodeId(1), NodeKind::Text(Box::new(t)));
|
||||
let count = s.load_clipboard(Clipboard { nodes: vec![n], ..Default::default() }, p)?;
|
||||
@@ -452,8 +477,19 @@ fn import_eps(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Replace the clipboard with the objects of the picture `bytes`, read as the file `name` is
|
||||
/// opened (command `cmd`).
|
||||
fn import_picture(s: &mut Session, p: &Value, cmd: &str, name: &str, bytes: &[u8]) -> Result<Value> {
|
||||
let mut loaded = fileio::load(name, bytes).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let loaded = fileio::load(name, bytes).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
import_loaded(s, p, cmd, loaded)
|
||||
}
|
||||
|
||||
/// Replace the clipboard with every object of `loaded`, a file read as `document.open` reads it
|
||||
/// (command `cmd`). The layers are left out, and the objects of a hidden layer come in hidden.
|
||||
fn import_loaded(s: &mut Session, p: &Value, cmd: &str, mut loaded: fileio::Loaded) -> Result<Value> {
|
||||
loaded.doc.drop_edit_modes();
|
||||
for layer in loaded.doc.layers.iter_mut().filter(|l| !l.visible) {
|
||||
for object in std::sync::Arc::make_mut(layer).children_mut().into_iter().flatten() {
|
||||
std::sync::Arc::make_mut(object).visible = false;
|
||||
}
|
||||
}
|
||||
let clip = Clipboard::from_document(&loaded.doc);
|
||||
if clip.is_empty() {
|
||||
return Err(bad(cmd, "the picture has no objects"));
|
||||
@@ -469,8 +505,28 @@ fn import_pdf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => 1,
|
||||
Some(v) => v.as_u64().filter(|n| (1..=100_000).contains(n)).ok_or_else(|| bad(C, "page must be a whole number from 1"))? as usize,
|
||||
};
|
||||
let editing = match p.get("editingData").filter(|v| !v.is_null()) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(C, "editingData must be true or false"))?,
|
||||
};
|
||||
let opts = fileio::LoadOptions { password: str_param(p, "password").map(str::to_string), ..Default::default() };
|
||||
let (mut doc, warnings) = fileio::page_document(&bytes, page - 1, &opts).map_err(|e| bad(C, e.to_string()))?;
|
||||
// A copied .ai file pastes every object of its editing data, as document.open reads the file.
|
||||
// When document.open would not use that copy, the file pastes its page, as a PDF does.
|
||||
if editing
|
||||
&& let Ok(loaded) = fileio::load_with("Clipboard.ai", &bytes, &opts)
|
||||
&& (loaded.editing_data || loaded.restored)
|
||||
{
|
||||
return import_loaded(s, p, C, loaded);
|
||||
}
|
||||
let (mut doc, warnings) = match fileio::page_document(&bytes, page - 1, &opts) {
|
||||
// For a .ai saved without PDF compatibility, the clipboard takes every object of its
|
||||
// editing data, as document.open reads it.
|
||||
Err(e) if fileio::is_placeholder(&e) => {
|
||||
let loaded = fileio::load_with("Clipboard.ai", &bytes, &opts).map_err(|e| bad(C, e.to_string()))?;
|
||||
return import_loaded(s, p, C, loaded);
|
||||
}
|
||||
read => read.map_err(|e| bad(C, e.to_string()))?,
|
||||
};
|
||||
doc.drop_edit_modes();
|
||||
let clip = Clipboard::from_document(&doc);
|
||||
if clip.is_empty() {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and
|
||||
//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also
|
||||
//! through the symbols, patterns and styles it finds, and keeps what they lead to.
|
||||
//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to.
|
||||
//!
|
||||
//! Pasting matches each resource by name: an identical one in the document is used, a missing one
|
||||
//! is added, and a different one of the same name is added under a free name, which the pasted
|
||||
@@ -13,6 +13,7 @@
|
||||
//! the document's Spot Colors option says. Pasting back into the document the objects came from
|
||||
//! uses its resources as they are now.
|
||||
|
||||
use std::cell::OnceCell;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -147,10 +148,28 @@ struct Defs<'a> {
|
||||
styles: &'a [GraphicStyle],
|
||||
char_styles: &'a [TextStyleDef],
|
||||
para_styles: &'a [TextStyleDef],
|
||||
brushes: Brushes<'a>,
|
||||
}
|
||||
|
||||
/// The brushes references lead to: a document's library, read the first time a brush is used
|
||||
/// (`vectorcraft_brush::library` parses it), or the clipboard's own.
|
||||
enum Brushes<'a> {
|
||||
Lazy(&'a Document, &'a OnceCell<Vec<Brush>>),
|
||||
Ready(&'a [Brush]),
|
||||
}
|
||||
|
||||
impl<'a> Brushes<'a> {
|
||||
fn get(&self) -> &'a [Brush] {
|
||||
match *self {
|
||||
Brushes::Lazy(d, cell) => cell.get_or_init(|| vectorcraft_brush::library(d)),
|
||||
Brushes::Ready(list) => list,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Defs<'a> {
|
||||
fn of(d: &'a Document) -> Self {
|
||||
/// `d`'s definitions; `brushes` holds its brush library once a brush is used.
|
||||
fn of(d: &'a Document, brushes: &'a OnceCell<Vec<Brush>>) -> Self {
|
||||
Self {
|
||||
swatches: d.swatches_iter().collect(),
|
||||
symbols: &d.symbols,
|
||||
@@ -158,6 +177,7 @@ impl<'a> Defs<'a> {
|
||||
styles: &d.graphic_styles,
|
||||
char_styles: &d.char_styles,
|
||||
para_styles: &d.para_styles,
|
||||
brushes: Brushes::Lazy(d, brushes),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,9 +200,9 @@ pub(super) struct Used {
|
||||
}
|
||||
|
||||
impl Used {
|
||||
fn of<'a>(defs: &Defs<'a>, nodes: &'a [Node]) -> Self {
|
||||
fn of<'a>(defs: &Defs<'a>, nodes: impl IntoIterator<Item = &'a Node>) -> Self {
|
||||
let mut used = Used::default();
|
||||
let mut todo: Vec<Source<'a>> = nodes.iter().map(Source::Node).collect();
|
||||
let mut todo: Vec<Source<'a>> = nodes.into_iter().map(Source::Node).collect();
|
||||
while let Some(src) = todo.pop() {
|
||||
let mut found = |r: Ref<'_>| used.note(defs, r, &mut todo);
|
||||
match src {
|
||||
@@ -224,6 +244,8 @@ impl Used {
|
||||
Res::Pattern => todo.extend(defs.patterns.iter().filter(|p| p.name == name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))),
|
||||
Res::CharStyle => todo.extend(defs.char_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))),
|
||||
Res::ParaStyle => todo.extend(defs.para_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))),
|
||||
// A scatter or art brush's art, a pattern brush's tiles.
|
||||
Res::Brush => todo.extend(defs.brushes.get().iter().filter(|b| b.name == name).flat_map(|b| b.art().into_iter().map(Source::Node))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -242,6 +264,80 @@ impl Used {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a preview of some art shows besides the art itself ([`art_resources`]).
|
||||
pub struct ArtResources {
|
||||
/// Changes when any resource the art uses changes, and only then.
|
||||
pub key: u64,
|
||||
/// The art and image bytes counted in `key` by their address, held weakly: their allocations
|
||||
/// stay theirs (no other art can take an address) for as long as the key is kept.
|
||||
_kept: (Vec<std::sync::Weak<Node>>, Vec<std::sync::Weak<Vec<u8>>>),
|
||||
}
|
||||
|
||||
/// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them
|
||||
/// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked
|
||||
/// colours, tints, gradient swatches; colour groups' included), character and paragraph styles,
|
||||
/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count
|
||||
/// by identity, the other definitions by their saved form: working the key out walks `art` and
|
||||
/// the definitions it leads to, and never reads an image's bytes.
|
||||
pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a Node>) -> ArtResources {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let library = OnceCell::new();
|
||||
let defs = Defs::of(doc, &library);
|
||||
// The art's references shortened to the brush library's life.
|
||||
let mut nodes: Vec<&Node> = vec![];
|
||||
for n in art {
|
||||
nodes.push(n);
|
||||
}
|
||||
let used = Used::of(&defs, nodes);
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
let mut kept = (vec![], vec![]);
|
||||
fn saved(h: &mut impl Hasher, v: &impl serde::Serialize) {
|
||||
serde_json::to_vec(v).unwrap_or_default().hash(h);
|
||||
}
|
||||
fn node(h: &mut impl Hasher, kept: &mut Vec<std::sync::Weak<Node>>, a: &Arc<Node>) {
|
||||
(Arc::as_ptr(a) as usize).hash(h);
|
||||
kept.push(Arc::downgrade(a));
|
||||
}
|
||||
for (res, names) in &used.names {
|
||||
for name in names {
|
||||
(*res as u8, name).hash(&mut h);
|
||||
match res {
|
||||
Res::Image => {
|
||||
if let Some(b) = doc.images.get(name) {
|
||||
b.mime.hash(&mut h);
|
||||
for bytes in std::iter::once(&b.bytes).chain(&b.proxy) {
|
||||
(Arc::as_ptr(bytes) as usize).hash(&mut h);
|
||||
kept.1.push(Arc::downgrade(bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
Res::Symbol => doc.symbols.iter().filter(|s| s.name == *name).for_each(|s| node(&mut h, &mut kept.0, &s.art)),
|
||||
Res::Pattern => {
|
||||
for p in doc.patterns.iter().filter(|p| p.name == *name) {
|
||||
saved(&mut h, &PatternDef { art: vec![], ..p.clone() });
|
||||
p.art.iter().for_each(|a| node(&mut h, &mut kept.0, a));
|
||||
}
|
||||
}
|
||||
Res::CharStyle => doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)),
|
||||
// Swatches below (tints count too); graphic styles go by id.
|
||||
Res::Swatch | Res::GraphicStyle => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for w in doc.swatches_iter().filter(|w| used.carries(w) || used.has(Res::Swatch, &w.name)) {
|
||||
saved(&mut h, w);
|
||||
}
|
||||
for g in doc.graphic_styles.iter().filter(|g| g.id != 0 && used.styles.contains(&g.id)) {
|
||||
saved(&mut h, g);
|
||||
}
|
||||
if used.names.contains_key(&Res::Swatch) {
|
||||
doc.spot_use_lab.hash(&mut h);
|
||||
}
|
||||
ArtResources { key: h.finish(), _kept: kept }
|
||||
}
|
||||
|
||||
/// A resource list entry known by its name.
|
||||
trait Named: Clone {
|
||||
fn name(&self) -> &str;
|
||||
@@ -469,6 +565,26 @@ fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
|
||||
ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b))
|
||||
}
|
||||
|
||||
/// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by
|
||||
/// `r`? Graphic style links don't count, as in [`same_art`].
|
||||
fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
|
||||
let relinked = |r: &Relink, b: &Brush| {
|
||||
let mut b = b.clone();
|
||||
b.art_mut().into_iter().for_each(|a| r.node(a));
|
||||
b
|
||||
};
|
||||
relinked(&Relink::default(), ours) == relinked(r, theirs)
|
||||
}
|
||||
|
||||
/// Does brush `b`'s art show symbols or patterns?
|
||||
fn shows_definitions(b: &Brush) -> bool {
|
||||
let mut found = false;
|
||||
for a in b.art() {
|
||||
node_refs(a, &mut |r| found |= matches!(r, Ref::Name(Res::Symbol | Res::Pattern, _)));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// What pasting did to the document's resources (part of the paste result).
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Imported {
|
||||
@@ -500,12 +616,14 @@ impl Imported {
|
||||
|
||||
impl Clipboard {
|
||||
/// `nodes` (from `src`) and the resources of `src` they use.
|
||||
pub(super) fn gather(src: &Document, nodes: Vec<Node>) -> Self {
|
||||
let used = Used::of(&Defs::of(src), &nodes);
|
||||
pub(crate) fn gather(src: &Document, nodes: Vec<Node>) -> Self {
|
||||
let library = OnceCell::new();
|
||||
let used = Used::of(&Defs::of(src, &library), &nodes);
|
||||
let pick = |r: Res, list: &[TextStyleDef]| list.iter().filter(|s| used.has(r, &s.name)).cloned().collect::<Vec<_>>();
|
||||
let brushes = match used.names.get(&Res::Brush) {
|
||||
Some(names) => vectorcraft_brush::library(src).into_iter().filter(|b| names.contains(&b.name)).collect(),
|
||||
None => vec![],
|
||||
// Read when a brush was used.
|
||||
let brushes = match (used.names.get(&Res::Brush), library.get()) {
|
||||
(Some(names), Some(library)) => library.iter().filter(|b| names.contains(&b.name)).cloned().collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
Self {
|
||||
images: src.images.iter().filter(|(k, _)| used.has(Res::Image, k)).map(|(k, b)| (k.clone(), b.clone())).collect(),
|
||||
@@ -530,6 +648,7 @@ impl Clipboard {
|
||||
styles: &self.graphic_styles,
|
||||
char_styles: &self.char_styles,
|
||||
para_styles: &self.para_styles,
|
||||
brushes: Brushes::Ready(&self.brushes),
|
||||
};
|
||||
Used::of(&defs, &self.nodes)
|
||||
}
|
||||
@@ -549,8 +668,10 @@ impl Clipboard {
|
||||
let used = self.used();
|
||||
let mut out = Imported::default();
|
||||
self.import_images(d, &used, same_doc, &mut out);
|
||||
self.import_brushes(d, &used, same_doc, &mut out);
|
||||
self.import_swatches(d, &used, choices, same_doc, &mut out);
|
||||
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
|
||||
// they may brush; the others once those are in.
|
||||
let mut added_brushes = self.import_brushes(d, &used, same_doc, false, &mut out);
|
||||
// Character and paragraph styles (their colours relinked first).
|
||||
for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] {
|
||||
for def in mine.iter().filter(|s| used.has(r, &s.name)) {
|
||||
@@ -583,6 +704,7 @@ impl Clipboard {
|
||||
added_patterns.extend(p.new_name(&def.name));
|
||||
out.placed(Res::Pattern, &def.name, &p);
|
||||
}
|
||||
added_brushes.extend(self.import_brushes(d, &used, same_doc, true, &mut out));
|
||||
self.import_graphic_styles(d, &used, same_doc, &mut out);
|
||||
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
|
||||
out.relink.node(Arc::make_mut(&mut s.art));
|
||||
@@ -592,6 +714,13 @@ impl Clipboard {
|
||||
out.relink.node(Arc::make_mut(a));
|
||||
}
|
||||
}
|
||||
if !added_brushes.is_empty() {
|
||||
let mut lib = vectorcraft_brush::library(d);
|
||||
for b in lib.iter_mut().filter(|b| added_brushes.contains(&b.name)) {
|
||||
b.art_mut().into_iter().for_each(|a| out.relink.node(a));
|
||||
}
|
||||
vectorcraft_brush::store(d, &lib);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -607,20 +736,26 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
|
||||
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).collect();
|
||||
/// The brushes whose art shows symbols or patterns (`late`), or the others: each one the
|
||||
/// document has (its art compared once relinked) is used, the others are added. → the names of
|
||||
/// those added, whose art is relinked at the end.
|
||||
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, late: bool, out: &mut Imported) -> Vec<String> {
|
||||
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name) && shows_definitions(b) == late).collect();
|
||||
if brushes.is_empty() {
|
||||
return;
|
||||
return vec![];
|
||||
}
|
||||
let mut lib = vectorcraft_brush::library(d);
|
||||
let before = lib.len();
|
||||
let mut added = vec![];
|
||||
for b in brushes {
|
||||
let p = place(&mut lib, b, same_doc, PartialEq::eq);
|
||||
let r = &out.relink;
|
||||
let p = place(&mut lib, b, same_doc, |ours, theirs| same_brush(r, ours, theirs));
|
||||
added.extend(p.new_name(&b.name));
|
||||
out.placed(Res::Brush, &b.name, &p);
|
||||
}
|
||||
if lib.len() != before {
|
||||
if !added.is_empty() {
|
||||
vectorcraft_brush::store(d, &lib);
|
||||
}
|
||||
added
|
||||
}
|
||||
|
||||
/// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint
|
||||
|
||||
@@ -195,6 +195,12 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?;
|
||||
// The bytes are kept, not the path: the file may move or go away.
|
||||
let remembered = s.store_profile(&info.name, &bytes);
|
||||
// A new file of a working space: the active settings still hold the old one.
|
||||
let working = cms::active_settings();
|
||||
if working.rgb == info.name || working.cmyk == info.name {
|
||||
cms::set_active(&working).map_err(|e| bad(C, e.to_string()))?;
|
||||
touch_all(s);
|
||||
}
|
||||
Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered}))
|
||||
}
|
||||
|
||||
|
||||
@@ -142,7 +142,8 @@ fn add_to_swatches(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "colorTheme.addToSwatches";
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
|
||||
let t = &s.prefs.color_themes[find(s, name, C)?];
|
||||
let params = json!({ "name": t.name, "colors": t.colors.iter().map(color_json).collect::<Vec<_>>() });
|
||||
// The theme's colors keep their model, in a CMYK document too.
|
||||
let params = json!({ "name": t.name, "colors": t.colors.iter().map(color_json).collect::<Vec<_>>(), "keepModel": true });
|
||||
let r = s.execute("swatch.newGroup", ¶ms)?;
|
||||
Ok(json!({ "name": r["name"], "swatches": r["swatches"] }))
|
||||
}
|
||||
+293
-70
@@ -30,15 +30,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
flare
|
||||
),
|
||||
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2} → {id}", has_doc, line),
|
||||
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line),
|
||||
cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral),
|
||||
cmd!("shape.arc", "Arc", [], None, "{x1, y1, x2, y2, closed?} → {id}", has_doc, arc),
|
||||
cmd!(
|
||||
"shape.arc",
|
||||
"Arc",
|
||||
[],
|
||||
None,
|
||||
"{x1, y1, x2, y2, closed?, slope?} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?} → {id}",
|
||||
has_doc,
|
||||
arc
|
||||
),
|
||||
cmd!(
|
||||
"shape.rectangularGrid",
|
||||
"Rectangular Grid",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none)} → {id}",
|
||||
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}",
|
||||
has_doc,
|
||||
rect_grid
|
||||
),
|
||||
@@ -47,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Polar Grid",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none)} → {id}",
|
||||
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}",
|
||||
has_doc,
|
||||
polar_grid
|
||||
),
|
||||
@@ -65,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Drawing Mode",
|
||||
[],
|
||||
Some("Shift+D"),
|
||||
"{mode?: normal|behind|inside} (no param cycles; inside needs one selected path)",
|
||||
"{mode?: normal|behind|inside} (inside needs one selected path, compound path or type; no param cycles normal → behind → inside → normal, going from behind back to normal when Draw Inside can't draw into the selection; when the Draw Inside target is isolated, drawing or pasting into it moves isolation to its clip group)",
|
||||
has_doc,
|
||||
draw_mode
|
||||
),
|
||||
@@ -74,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, vertical?: bool = false, size?: pt, font?: family, style?, color?, area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, 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)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, 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)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -88,11 +96,6 @@ pub(crate) fn add_art(s: &mut Session, label: &str, kind: NodeKind, name: Option
|
||||
add_look(s, label, kind, look, name)
|
||||
}
|
||||
|
||||
/// [`add_look`] with just `appearance`.
|
||||
pub(crate) fn add_node(s: &mut Session, label: &str, kind: NodeKind, appearance: Appearance, name: Option<String>) -> Result<Value> {
|
||||
add_look(s, label, kind, NewArt::plain(appearance), name)
|
||||
}
|
||||
|
||||
/// Insert a new object looking like `look` (drawing modes apply); select it.
|
||||
pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>) -> Result<Value> {
|
||||
insert_look(s, label, kind, look, name, true)
|
||||
@@ -101,35 +104,63 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr
|
||||
/// [`add_look`] that selects the new object only when `select` is set; otherwise the selection
|
||||
/// stays as it was.
|
||||
pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>, select: bool) -> Result<Value> {
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page):
|
||||
/// its bounding box turns with it, as after the Rotate tool.
|
||||
fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation))
|
||||
}
|
||||
|
||||
/// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it)
|
||||
/// of an object made with the clockwise `rotation` param: 0 exactly for none, a whole turn or a
|
||||
/// non-finite angle, so such objects are as they were.
|
||||
fn bbox_turn(rotation: f64) -> f64 {
|
||||
if !rotation.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
let a = vectorcraft_geom::normalize_deg(-rotation);
|
||||
if a == 0.0 { 0.0 } else { a }
|
||||
}
|
||||
|
||||
/// A polygon's or star's `rotation` when it is the base orientation turned by General › Constrain
|
||||
/// Angle (a Shift-drawn or click-made one), so its bounding box turns with it; else 0: a polygon
|
||||
/// turned by the drag's direction keeps its box on the page's axes, as before.
|
||||
fn constrained_turn(s: &Session, rotation: f64) -> f64 {
|
||||
match vectorcraft_geom::constrain_rotation(s.prefs.constrain_angle) {
|
||||
Some(r) if rotation.is_finite() && vectorcraft_geom::normalize_deg(r - rotation).abs() < 1e-9 => rotation,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`.
|
||||
fn insert_look_turned(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
kind: NodeKind,
|
||||
look: NewArt,
|
||||
name: Option<String>,
|
||||
select: bool,
|
||||
bbox_angle: f64,
|
||||
) -> Result<Value> {
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let mode = s.draw_mode;
|
||||
let inside = s.draw_inside;
|
||||
let behind_of = s.doc()?.selection.in_paint_order(&s.doc()?.doc).first().copied();
|
||||
let id = s.edit(label, |d, sel| {
|
||||
let (id, into) = s.edit(label, |d, sel| {
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::new(id, kind);
|
||||
look.apply(d, &mut n);
|
||||
n.name = name;
|
||||
n.bbox_angle = bbox_angle;
|
||||
let mut into = None;
|
||||
match (mode, inside) {
|
||||
(crate::DrawMode::Inside, Some(target)) if d.node(target).is_some() => {
|
||||
// Wrap the target once in a clip group [mask copy, target, …new art].
|
||||
let group = match d.parent_of(target).and_then(|p| d.node(p).map(|pn| (p, pn.kind.clone()))) {
|
||||
Some((p, NodeKind::Group { clip: true, children })) if children.get(1).is_some_and(|c| c.id == target) => p,
|
||||
_ => {
|
||||
let (par, idx, _) = d.position(target).ok_or(crate::EngineError::NoNode(target))?;
|
||||
let mut mask = d.node(target).cloned().ok_or(crate::EngineError::NoNode(target))?;
|
||||
mask.id = d.alloc_id();
|
||||
mask.appearance = Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0).into();
|
||||
if let NodeKind::Path { clipping, .. } = &mut mask.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
d.insert(par, idx + 1, Node::new(gid, NodeKind::Group { children: vec![std::sync::Arc::new(mask)], clip: true }))?;
|
||||
d.move_node(target, Some(gid), usize::MAX)?;
|
||||
gid
|
||||
}
|
||||
};
|
||||
let group = draw_inside_group(d, target)?;
|
||||
d.insert(Some(group), usize::MAX, n)?;
|
||||
into = Some((target, group));
|
||||
}
|
||||
(crate::DrawMode::Behind, _) => match behind_of.and_then(|b| d.position(b)) {
|
||||
Some((par, idx, _)) => {
|
||||
@@ -146,32 +177,82 @@ pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: Ne
|
||||
if select {
|
||||
sel.set([id]);
|
||||
}
|
||||
Ok(id)
|
||||
Ok((id, into))
|
||||
})?;
|
||||
if let Some((target, group)) = into {
|
||||
isolate_draw_inside_group(s, target, group)?;
|
||||
}
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// Draw Inside's clip group for `target`, the object new art goes inside: the clip group
|
||||
/// [mask copy, target, …] `target` already is the clipped object of, else one made where `target`
|
||||
/// was, holding an unpainted clipping copy of it and then `target`. New art and pastes go on top
|
||||
/// of its children.
|
||||
pub(crate) fn draw_inside_group(d: &mut vectorcraft_doc::Document, target: NodeId) -> Result<NodeId> {
|
||||
if let Some(p) = d.parent_of(target)
|
||||
&& d.node(p).is_some_and(|pn| matches!(&pn.kind, NodeKind::Group { clip: true, children } if children.get(1).is_some_and(|c| c.id == target)))
|
||||
{
|
||||
return Ok(p);
|
||||
}
|
||||
let (par, idx, _) = d.position(target).ok_or(crate::EngineError::NoNode(target))?;
|
||||
// The mask is a copy with ids of its own, its subpaths' too (a compound path's).
|
||||
let original = d.node(target).cloned().ok_or(crate::EngineError::NoNode(target))?;
|
||||
let mut mask = d.reid(&original);
|
||||
mask.appearance = Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0).into();
|
||||
if let NodeKind::Path { clipping, .. } = &mut mask.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
d.insert(par, idx + 1, Node::new(gid, NodeKind::Group { children: vec![std::sync::Arc::new(mask)], clip: true }))?;
|
||||
d.move_node(target, Some(gid), usize::MAX)?;
|
||||
// Copied type whose layout caches `reid` dropped has them again.
|
||||
super::typecmd::refresh_bounds_of(d, &[gid]);
|
||||
Ok(gid)
|
||||
}
|
||||
|
||||
/// Draw Inside into the isolated object (#3705): isolation mode moves to the clip group the art
|
||||
/// went into ([`draw_inside_group`]), so what is drawn or pasted inside the object is in isolation
|
||||
/// mode with it, shown undimmed and picked by clicks, instead of locked beside it. Art added in
|
||||
/// isolation mode belongs with what is isolated: it takes the isolated art's place when the mode
|
||||
/// ends (<https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html>).
|
||||
/// A drag's next preview, replayed on the drag's snapshot, makes the group again under the same
|
||||
/// id, so isolation stays on it; cancelling the drag restores the isolation it began with.
|
||||
pub(crate) fn isolate_draw_inside_group(s: &mut Session, target: NodeId, group: NodeId) -> Result<()> {
|
||||
let st = s.doc_mut()?;
|
||||
if st.isolation == Some(target) {
|
||||
st.isolation = Some(group);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The object Draw Inside would draw into: the one selected object, when it is a path, a compound
|
||||
/// path or type.
|
||||
fn inside_target(st: &crate::DocState) -> Option<NodeId> {
|
||||
let first = st.selection.objects.first().copied()?;
|
||||
let fits = matches!(st.doc.node(first).map(|n| &n.kind), Some(NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)));
|
||||
(fits && st.selection.len() == 1).then_some(first)
|
||||
}
|
||||
|
||||
fn draw_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mode = match str_param(p, "mode") {
|
||||
Some("behind") => crate::DrawMode::Behind,
|
||||
Some("inside") => crate::DrawMode::Inside,
|
||||
Some("normal") => crate::DrawMode::Normal,
|
||||
// Cycling (Shift+D): Draw Behind goes on to Draw Inside only when it can draw inside the
|
||||
// selection, else back to Draw Normal (#3705: with one group selected it stayed in Draw
|
||||
// Behind).
|
||||
None => match s.draw_mode {
|
||||
crate::DrawMode::Normal => crate::DrawMode::Behind,
|
||||
crate::DrawMode::Behind if s.doc()?.selection.len() == 1 => crate::DrawMode::Inside,
|
||||
crate::DrawMode::Behind if inside_target(s.doc()?).is_some() => crate::DrawMode::Inside,
|
||||
_ => crate::DrawMode::Normal,
|
||||
},
|
||||
Some(o) => return Err(bad("view.drawMode", format!("unknown mode `{o}`"))),
|
||||
};
|
||||
if mode == crate::DrawMode::Inside {
|
||||
let st = s.doc()?;
|
||||
let target =
|
||||
st.selection.objects.first().copied().filter(|id| {
|
||||
matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)))
|
||||
});
|
||||
match target {
|
||||
Some(t) if st.selection.len() == 1 => s.draw_inside = Some(t),
|
||||
_ => return Err(bad("view.drawMode", "Draw Inside needs exactly one selected path, compound path or text")),
|
||||
match inside_target(s.doc()?) {
|
||||
Some(t) => s.draw_inside = Some(t),
|
||||
None => return Err(bad("view.drawMode", "Draw Inside needs exactly one selected path, compound path or text")),
|
||||
}
|
||||
} else {
|
||||
s.draw_inside = None;
|
||||
@@ -184,6 +265,35 @@ fn path_kind(path: PathData, live: Option<LiveShape>) -> NodeKind {
|
||||
NodeKind::Path { path, rule: FillRule::NonZero, live: live.map(Box::new), clipping: false, guide: false }
|
||||
}
|
||||
|
||||
/// A click-to-size shape dialog's command `cmd` with `params` drawn along General › Constrain
|
||||
/// Angle, as the reference app draws new objects along it
|
||||
/// (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>):
|
||||
/// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog
|
||||
/// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays
|
||||
/// put; a polygon or star turns its base orientation about its centre. The params as they are at
|
||||
/// 0° or a whole turn, for other commands and when they already carry a `rotation`.
|
||||
pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value {
|
||||
let base = s.prefs.constrain_angle;
|
||||
let (Some(rotation), Some(axes)) = (vectorcraft_geom::constrain_rotation(base), vectorcraft_geom::constrain_axes(base)) else { return params };
|
||||
let Some(o) = params.as_object_mut().filter(|o| !o.contains_key("rotation")) else { return params };
|
||||
match cmd {
|
||||
"shape.rectangle" | "shape.ellipse" | "shape.rectangularGrid" | "shape.polarGrid" => {
|
||||
let num = |k: &str| o.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());
|
||||
let (Some(x), Some(y), Some(w), Some(h)) = (num("x"), num("y"), num("width"), num("height")) else { return params };
|
||||
// The box's centre along the turned axes from the pivot; the command turns it there.
|
||||
let c = pivot + (axes * Point::new(x + w / 2.0 - pivot.x, y + h / 2.0 - pivot.y)).to_vec2();
|
||||
o.insert("x".into(), json!(c.x - w / 2.0));
|
||||
o.insert("y".into(), json!(c.y - h / 2.0));
|
||||
o.insert("rotation".into(), json!(rotation));
|
||||
}
|
||||
"shape.polygon" | "shape.star" => {
|
||||
o.insert("rotation".into(), json!(rotation));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
fn rect_of(p: &Value, cmd: &str) -> Result<Rect> {
|
||||
let x = f64_req(p, "x", cmd)?;
|
||||
let y = f64_req(p, "y", cmd)?;
|
||||
@@ -203,10 +313,12 @@ fn rect_transform(r: Rect, p: &Value, cmd: &str) -> Result<Affine> {
|
||||
if rotation == 0.0 {
|
||||
return Ok(Affine::translate(r.origin().to_vec2()));
|
||||
}
|
||||
Ok(Affine::translate(r.center().to_vec2()) * Affine::rotate(rotation.to_radians()) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0)))
|
||||
// Exact at quarter turns (a Constrain Angle of 90°).
|
||||
Ok(Affine::translate(r.center().to_vec2()) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0)))
|
||||
}
|
||||
|
||||
fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["radius"], "shape.rectangle")?;
|
||||
let r = rect_of(p, "shape.rectangle")?;
|
||||
let radius = f64_or(p, "radius", 0.0).max(0.0);
|
||||
let live = LiveShape::Rectangle {
|
||||
@@ -214,35 +326,56 @@ fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
h: r.height(),
|
||||
radii: [radius; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: rect_transform(r, p, "shape.rectangle")?,
|
||||
};
|
||||
let label = if radius > 0.0 { "Rounded Rectangle" } else { "Rectangle" };
|
||||
add_art(s, label, path_kind(live.to_path(), Some(live)), None)
|
||||
add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
|
||||
}
|
||||
|
||||
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = rect_of(p, "shape.ellipse")?;
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? };
|
||||
add_art(s, "Ellipse", path_kind(live.to_path(), Some(live)), None)
|
||||
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
|
||||
}
|
||||
|
||||
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
|
||||
/// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default.
|
||||
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
let n = number_or(p, key, default as f64, cmd)?;
|
||||
if n.is_finite() && n >= 0.0 && n.fract() == 0.0 {
|
||||
Ok(n as u64)
|
||||
} else {
|
||||
Err(bad(cmd, format!("`{key}` must be a whole number of at least 0, not {n}")))
|
||||
}
|
||||
}
|
||||
|
||||
fn polygon(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = Point::new(f64_req(p, "cx", "shape.polygon")?, f64_req(p, "cy", "shape.polygon")?);
|
||||
let r = f64_req(p, "radius", "shape.polygon")?.abs();
|
||||
let sides = p.get("sides").and_then(Value::as_u64).unwrap_or(6).clamp(3, 1000) as u32;
|
||||
check_numbers(p, &["rotation"], "shape.polygon")?;
|
||||
let sides = count_or(p, "sides", 6, "shape.polygon")?.clamp(3, 1000) as u32;
|
||||
let rot = f64_or(p, "rotation", 0.0);
|
||||
let xf = Affine::translate(c.to_vec2()) * Affine::rotate(rot.to_radians());
|
||||
let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![] };
|
||||
add_art(s, "Polygon", path_kind(live.to_path(), Some(live)), None)
|
||||
let xf = Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
|
||||
let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false };
|
||||
add_art_turned(s, "Polygon", path_kind(live.to_path(), Some(live)), constrained_turn(s, rot))
|
||||
}
|
||||
|
||||
fn star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = Point::new(f64_req(p, "cx", "shape.star")?, f64_req(p, "cy", "shape.star")?);
|
||||
let r1 = f64_req(p, "radius1", "shape.star")?.abs();
|
||||
check_numbers(p, &["radius2", "rotation"], "shape.star")?;
|
||||
let r2 = f64_or(p, "radius2", r1 / 2.0).abs();
|
||||
let n = p.get("points").and_then(Value::as_u64).unwrap_or(5).clamp(2, 1000) as u32;
|
||||
let path = shapes::star(c, r1, r2, n, f64_or(p, "rotation", 0.0));
|
||||
add_art(s, "Star", path_kind(path, None), None)
|
||||
let n = count_or(p, "points", 5, "shape.star")?.clamp(2, 1000) as u32;
|
||||
let rot = f64_or(p, "rotation", 0.0);
|
||||
let turn = vectorcraft_geom::rotate_deg(rot);
|
||||
// A quarter or whole turn (a Constrain Angle of 90°, say) turns the upright star exactly.
|
||||
let path = if rot != 0.0 && turn.as_coeffs()[..4].iter().all(|c| c.fract() == 0.0) {
|
||||
shapes::star(Point::ZERO, r1, r2, n, 0.0).transformed(Affine::translate(c.to_vec2()) * turn)
|
||||
} else {
|
||||
shapes::star(c, r1, r2, n, rot)
|
||||
};
|
||||
add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot))
|
||||
}
|
||||
|
||||
/// Flare tool: a lens flare built from radial-gradient paths in Screen mode — a bright centre, a halo
|
||||
@@ -250,6 +383,24 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_color::{BlendMode, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let c = Point::new(f64_req(p, "cx", "shape.flare")?, f64_req(p, "cy", "shape.flare")?);
|
||||
let numbers = [
|
||||
"diameter",
|
||||
"opacity",
|
||||
"brightness",
|
||||
"growth",
|
||||
"fuzziness",
|
||||
"rays",
|
||||
"longest",
|
||||
"rayFuzziness",
|
||||
"rings",
|
||||
"largest",
|
||||
"x2",
|
||||
"y2",
|
||||
"direction",
|
||||
"pathLength",
|
||||
"seed",
|
||||
];
|
||||
check_numbers(p, &numbers, "shape.flare")?;
|
||||
let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0);
|
||||
let r = (f64_or(p, "diameter", 100.0) / 2.0).max(0.5);
|
||||
let opacity = pct("opacity", 50.0).min(1.0) as f32;
|
||||
@@ -278,7 +429,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient { kind: GradientKind::Radial, stops });
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
g.geom = Some(GradientGeom { start: centre, end: centre + vectorcraft_geom::Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
@@ -348,9 +499,10 @@ fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Point::new(f64_req(p, "x1", "shape.line")?, f64_req(p, "y1", "shape.line")?);
|
||||
let b = Point::new(f64_req(p, "x2", "shape.line")?, f64_req(p, "y2", "shape.line")?);
|
||||
let live = LiveShape::Line { a, b };
|
||||
// Lines are stroked, never filled (Illustrator ignores the fill for new open lines).
|
||||
// Lines are stroked and, unless Fill Line asks for the current fill, not filled.
|
||||
let fill = if switch_or(p, "fill", false, "shape.line")? { s.paint.fill.clone() } else { vectorcraft_color::Paint::None };
|
||||
let look = s.new_art_look(
|
||||
vectorcraft_color::Paint::None,
|
||||
fill,
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
s.paint.stroke_width.max(0.1),
|
||||
);
|
||||
@@ -359,25 +511,52 @@ fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = Point::new(f64_req(p, "cx", "shape.spiral")?, f64_req(p, "cy", "shape.spiral")?);
|
||||
let segments = count_or(p, "segments", 10, "shape.spiral")?.clamp(2, 1000) as u32;
|
||||
let path = shapes::spiral(
|
||||
c,
|
||||
f64_req(p, "radius", "shape.spiral")?,
|
||||
f64_or(p, "decay", 80.0),
|
||||
p.get("segments").and_then(Value::as_u64).unwrap_or(10).clamp(2, 1000) as u32,
|
||||
bool_or(p, "clockwise", true),
|
||||
number_or(p, "decay", 80.0, "shape.spiral")?,
|
||||
segments,
|
||||
switch_or(p, "clockwise", true, "shape.spiral")?,
|
||||
);
|
||||
add_art(s, "Spiral", path_kind(path, None), None)
|
||||
}
|
||||
|
||||
fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?);
|
||||
let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?);
|
||||
add_art(s, "Arc", path_kind(shapes::arc(a, b, 0.0, bool_or(p, "closed", false)), None), None)
|
||||
let closed = switch_or(p, "closed", false, "shape.arc")?;
|
||||
let fill_arc = switch_or(p, "fillArc", false, "shape.arc")?;
|
||||
let base_x = !matches!(p.get("baseAlong").and_then(Value::as_str), Some("y" | "Y"));
|
||||
let path = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
|
||||
let anchor = Point::new(f64_req(p, "x", "shape.arc")?, f64_req(p, "y", "shape.arc")?);
|
||||
let reference = p.get("reference").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
shapes::arc_segment(
|
||||
anchor,
|
||||
reference,
|
||||
number_or(p, "lengthX", 100.0, "shape.arc")?,
|
||||
number_or(p, "lengthY", 100.0, "shape.arc")?,
|
||||
base_x,
|
||||
number_or(p, "slope", 50.0, "shape.arc")?,
|
||||
closed,
|
||||
)
|
||||
} else {
|
||||
let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?);
|
||||
let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?);
|
||||
let slope = number_or(p, "slope", 100.0, "shape.arc")?;
|
||||
shapes::arc(a, b, slope, closed, base_x)
|
||||
};
|
||||
let fill = if fill_arc { s.paint.fill.clone() } else { vectorcraft_color::Paint::None };
|
||||
let look = s.new_art_look(
|
||||
fill,
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
s.paint.stroke_width.max(0.1),
|
||||
);
|
||||
add_look(s, "Arc", path_kind(path, None), look, None)
|
||||
}
|
||||
|
||||
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
|
||||
/// current fill when `fill`; a path of several subpaths becomes a compound path of them.
|
||||
fn grid_group(s: &mut Session, label: &str, paths: Vec<PathData>, fill: bool) -> Result<Value> {
|
||||
/// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group
|
||||
/// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle).
|
||||
fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec<PathData>, f64), fill: bool) -> Result<Value> {
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let fill = if fill { s.paint.fill.clone() } else { vectorcraft_color::Paint::None };
|
||||
let look = s.new_art_look(fill, s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
@@ -394,20 +573,25 @@ fn grid_group(s: &mut Session, label: &str, paths: Vec<PathData>, fill: bool) ->
|
||||
Node::path(d.alloc_id(), pd, Appearance::default())
|
||||
};
|
||||
look.apply(d, &mut n);
|
||||
n.bbox_angle = bbox_angle;
|
||||
std::sync::Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::group(gid, children))?;
|
||||
let mut g = Node::group(gid, children);
|
||||
g.bbox_angle = bbox_angle;
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// A grid's divider count `count` with its skew `key` in percent (0 when absent, clamped to
|
||||
/// ±[`shapes::GRID_SKEW_MAX`]).
|
||||
/// A grid's divider count `count` (an error unless it is a number or null; 5 unless it is a JSON
|
||||
/// integer of 0 or more, so 4.0 and 2.5 give 5; at most 999) with its skew `key` in percent (0 when
|
||||
/// absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
|
||||
fn dividers(p: &Value, count: &str, key: &str, cmd: &str) -> Result<(u32, f64)> {
|
||||
check_numbers(p, &[count], cmd)?;
|
||||
let n = p.get(count).and_then(Value::as_u64).unwrap_or(5).min(999) as u32;
|
||||
let skew = match p.get(key) {
|
||||
None | Some(Value::Null) => 0.0,
|
||||
@@ -429,7 +613,7 @@ fn rect_grid(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = rect_of(p, CMD)?;
|
||||
let paths =
|
||||
shapes::rectangular_grid(r, dividers(p, "rows", "rowSkew", CMD)?, dividers(p, "columns", "columnSkew", CMD)?, switch(p, "frame", true, CMD)?);
|
||||
grid_group(s, "Rectangular Grid", paths, switch(p, "fill", false, CMD)?)
|
||||
grid_group(s, "Rectangular Grid", turned_grid(p, r, paths, CMD)?, switch(p, "fill", false, CMD)?)
|
||||
}
|
||||
|
||||
fn polar_grid(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -441,7 +625,24 @@ fn polar_grid(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
dividers(p, "radial", "radialSkew", CMD)?,
|
||||
switch(p, "compound", false, CMD)?,
|
||||
);
|
||||
grid_group(s, "Polar Grid", paths, switch(p, "fill", false, CMD)?)
|
||||
grid_group(s, "Polar Grid", turned_grid(p, r, paths, CMD)?, switch(p, "fill", false, CMD)?)
|
||||
}
|
||||
|
||||
/// A grid's paths in `r` turned by the `rotation` param about the centre of `r` (a grid drawn
|
||||
/// along a Constrain Angle), and their bounding-box angle; as they are without it or at 0.
|
||||
fn turned_grid(p: &Value, r: Rect, mut paths: Vec<PathData>, cmd: &str) -> Result<(Vec<PathData>, f64)> {
|
||||
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", cmd)? } else { 0.0 };
|
||||
if !rotation.is_finite() {
|
||||
return Err(bad(cmd, "rotation must be finite"));
|
||||
}
|
||||
if rotation != 0.0 {
|
||||
let c = r.center().to_vec2();
|
||||
let m = Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c);
|
||||
for path in &mut paths {
|
||||
path.transform(m);
|
||||
}
|
||||
}
|
||||
Ok((paths, bbox_turn(rotation)))
|
||||
}
|
||||
|
||||
/// An anchor `{x, y, in?, out?, smooth?}` given to `cmd` (handles `[x, y]`, at the anchor when
|
||||
@@ -465,6 +666,8 @@ pub(crate) fn anchor_from_json(v: &Value, cmd: &str) -> Result<Anchor> {
|
||||
}
|
||||
|
||||
fn path_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Checked with `d` too, where the path data alone decides whether the path is closed.
|
||||
let closed = switch_or(p, "closed", false, "path.create")?;
|
||||
let path = if let Some(d) = str_param(p, "d") {
|
||||
let bp = vectorcraft_geom::BezPath::from_svg(d).map_err(|e| bad("path.create", format!("bad path data: {e}")))?;
|
||||
PathData::from_bezpath(&bp)
|
||||
@@ -479,7 +682,7 @@ fn path_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if anchors.is_empty() {
|
||||
return Err(bad("path.create", "need at least one anchor"));
|
||||
}
|
||||
PathData::single(SubPath::new(anchors, bool_or(p, "closed", false)))
|
||||
PathData::single(SubPath::new(anchors, closed))
|
||||
};
|
||||
let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
// Open paths drawn with a stroke of None would be invisible: mimic Illustrator and keep what the user set.
|
||||
@@ -493,8 +696,23 @@ fn path_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let x = f64_req(p, "x", "text.create")?;
|
||||
let y = f64_req(p, "y", "text.create")?;
|
||||
super::paint::check_keep_model(p, "text.create")?;
|
||||
check_numbers(p, &["size"], "text.create")?;
|
||||
check_switches(p, &["vertical", "placeholder"], "text.create")?;
|
||||
if let Some(a) = p.get("area") {
|
||||
check_numbers(a, &["width", "height"], "text.create")?;
|
||||
}
|
||||
let text = str_param(p, "text").unwrap_or("");
|
||||
let mut t = TextObject::point(Point::new(x, y), text, new_type_style(s, p));
|
||||
// Turned about the point (the first baseline's start, an area's top-left corner): type set
|
||||
// along a Constrain Angle.
|
||||
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "text.create")? } else { 0.0 };
|
||||
if !rotation.is_finite() {
|
||||
return Err(bad("text.create", "rotation must be finite"));
|
||||
}
|
||||
if rotation != 0.0 {
|
||||
t.xf *= vectorcraft_geom::rotate_deg(rotation);
|
||||
}
|
||||
t.vertical = p.get("vertical").and_then(Value::as_bool).unwrap_or(false);
|
||||
t.para = new_type_para();
|
||||
new_type_alignment(s, p, "text.create", &mut t)?;
|
||||
@@ -504,13 +722,14 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) };
|
||||
t.area.fit = new_area_fit(s, a, "text.create")?;
|
||||
}
|
||||
t.system_layout = s.doc()?.doc.setup.system_layout;
|
||||
if bool_or(p, "placeholder", false) {
|
||||
super::typemenu::fill_with_placeholder(&mut t);
|
||||
} else {
|
||||
// Lays the text out (and sizes an Auto Size frame).
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
}
|
||||
let made = add_node(s, "Type", NodeKind::Text(Box::new(t)), Appearance::default(), None)?;
|
||||
let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?;
|
||||
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
|
||||
let made = super::typecmd::with_bounds(s, id, made);
|
||||
Ok(super::typecmd::with_overflow(s, id.as_slice(), made))
|
||||
@@ -573,8 +792,9 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result<vectorcraf
|
||||
Ok(super::typecmd::fit_param(p, default, c)?.unwrap_or(default))
|
||||
}
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p`, else the
|
||||
/// defaults, filled with the current fill unless that is None or white (black then).
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
|
||||
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
|
||||
/// filled with the current fill unless that is None or white (black then).
|
||||
pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
|
||||
let mut style = CharStyle::default();
|
||||
if let Some(sz) = p.get("size").and_then(Value::as_f64) {
|
||||
@@ -585,9 +805,12 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
|
||||
}
|
||||
if let Some(f) = str_param(p, "style") {
|
||||
style.font_style = f.to_string();
|
||||
} else if str_param(p, "font").is_some() {
|
||||
// A family without a Regular (#4128): its closest style, as text.setRangeStyle takes.
|
||||
super::textedit::fit_font_style(&mut style);
|
||||
}
|
||||
style.fill = match p.get("color").and_then(color_value) {
|
||||
Some(c) => vectorcraft_color::Paint::solid(c),
|
||||
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
|
||||
None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(),
|
||||
None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK),
|
||||
};
|
||||
|
||||
@@ -130,7 +130,8 @@ fn cut_targets(s: &Session) -> Result<Vec<NodeId>> {
|
||||
}
|
||||
}
|
||||
out.dedup();
|
||||
out.retain(|id| doc.is_editable(*id));
|
||||
let editable = doc.editable();
|
||||
out.retain(|id| editable(*id));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -208,8 +209,8 @@ fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Option<Vec<PathD
|
||||
return Some(components(&a).into_iter().chain(components(&b)).collect());
|
||||
}
|
||||
// Open paths: the parts on each side (each pass removes the other side).
|
||||
let a = erase_outline(pd, &|q| axis.side(q) < 0.0)?;
|
||||
let b = erase_outline(pd, &|q| axis.side(q) >= 0.0)?;
|
||||
let a = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0)?;
|
||||
let b = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0)?;
|
||||
Some(if pd.subpaths.len() == 1 {
|
||||
a.into_iter().chain(b).collect()
|
||||
} else {
|
||||
@@ -248,7 +249,9 @@ fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Option<Vec<PathData>> {
|
||||
return Some(if r.is_empty() { vec![] } else { vec![r] });
|
||||
}
|
||||
let inside = rect.inflate(1e-9, 1e-9);
|
||||
let pieces = erase_outline(pd, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1))?;
|
||||
// Sampled at least every half of the rectangle's shorter side, so a line through it is found.
|
||||
let step = rect.width().min(rect.height()) / 2.0;
|
||||
let pieces = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1))?;
|
||||
Some(if pd.subpaths.len() == 1 || pieces.is_empty() {
|
||||
pieces
|
||||
} else {
|
||||
@@ -316,7 +319,7 @@ fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> Vec<PathData
|
||||
let joined = po::boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union);
|
||||
return if joined.is_empty() { vec![] } else { vec![joined] };
|
||||
}
|
||||
let kept = match erase_outline(pd, &|q| axis.side(q) * sign < 0.0) {
|
||||
let kept = match erase_outline(pd, f64::INFINITY, &|q| axis.side(q) * sign < 0.0) {
|
||||
Some(pieces) => pieces.into_iter().flat_map(|p| p.subpaths).collect(),
|
||||
None => pd.subpaths.clone(),
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::dimension::{ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, TextAlignment, TextPosition};
|
||||
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -165,11 +165,13 @@ fn apply_to_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let o = dimension_of(&st.doc, from)?.options;
|
||||
let mut ids = vec![];
|
||||
let editable = st.doc.editable();
|
||||
st.doc.walk(|n| {
|
||||
if n.extras().dimension.is_some() && st.doc.is_editable(n.id) {
|
||||
if n.extras().dimension.is_some() && editable(n.id) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
});
|
||||
drop(editable);
|
||||
s.edit("Apply to All", |doc, _| {
|
||||
for id in &ids {
|
||||
let mut dim = dimension_of(doc, *id)?;
|
||||
@@ -225,15 +227,64 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<()> {
|
||||
next.moved = None;
|
||||
}
|
||||
}
|
||||
if next != old || before.node(id).and_then(|n| n.extras().dimension.as_deref()).is_some_and(|d| d != &next) {
|
||||
// A new document colour mode (Document Color Mode) redraws every dimension in it.
|
||||
if next != old
|
||||
|| before.color_mode != doc.color_mode
|
||||
|| before.node(id).and_then(|n| n.extras().dimension.as_deref()).is_some_and(|d| d != &next)
|
||||
{
|
||||
replace(doc, id, next)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn paint(c: [u8; 3]) -> Paint {
|
||||
Paint::solid(Color::rgb8(c[0], c[1], c[2]))
|
||||
/// Redraw the dimensions of an opened document whose art isn't in its colour mode: files saved
|
||||
/// before dimensions followed the colour mode have RGB dimensions in CMYK documents. A dimension
|
||||
/// that can't be redrawn keeps the art it has.
|
||||
pub(crate) fn conform(doc: &mut Document) {
|
||||
if !doc.dimensions {
|
||||
return;
|
||||
}
|
||||
let mode = doc.color_mode;
|
||||
let off_mode = |c: &Color| match mode {
|
||||
ColorMode::Rgb => matches!(c, Color::Cmyk { .. }),
|
||||
ColorMode::Cmyk => matches!(c, Color::Rgb { .. }),
|
||||
};
|
||||
let mut stale = Vec::new();
|
||||
doc.walk(|n| {
|
||||
if let Some(d) = &n.extras().dimension {
|
||||
let mut off = false;
|
||||
n.walk(&mut |c| {
|
||||
off |= [c.appearance.fill_paint(), c.appearance.stroke_paint()].iter().filter_map(|p| p.color()).any(|c| off_mode(&c));
|
||||
// The label's characters carry their own fill.
|
||||
if let NodeKind::Text(t) = &c.kind {
|
||||
off |= t.runs.iter().filter_map(|r| r.style.fill.color()).any(|c| off_mode(&c));
|
||||
}
|
||||
});
|
||||
if off {
|
||||
stale.push((n.id, (**d).clone()));
|
||||
}
|
||||
}
|
||||
});
|
||||
for (id, d) in stale {
|
||||
// An error leaves this dimension as it was; the others are still redrawn.
|
||||
let _ = replace(doc, id, d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Option colour `c` as a paint in the document's colour model: in a CMYK document black is K
|
||||
/// only (a rich four-ink black would print a black dimension in every plate) and other colours
|
||||
/// convert through the active colour settings.
|
||||
fn paint(c: [u8; 3], mode: ColorMode) -> Paint {
|
||||
let rgb = Color::rgb8(c[0], c[1], c[2]);
|
||||
Paint::solid(match mode {
|
||||
ColorMode::Rgb => rgb,
|
||||
ColorMode::Cmyk if c == [0, 0, 0] => Color::cmyk(0.0, 0.0, 0.0, 1.0),
|
||||
ColorMode::Cmyk => {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
cms.convert(&rgb, vectorcraft_color::cms::Model::Cmyk, cms.settings().intent)
|
||||
}
|
||||
})
|
||||
}
|
||||
fn line(a: Point, b: Point) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
@@ -242,10 +293,10 @@ fn line(a: Point, b: Point) -> BezPath {
|
||||
p
|
||||
}
|
||||
|
||||
fn appearance(o: &DimensionOptions, ext: bool, arrows: bool) -> Appearance {
|
||||
fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> Appearance {
|
||||
let (color, width, kind) =
|
||||
if ext { (o.extension_color, o.extension_weight, o.extension_type) } else { (o.line_color, o.line_weight, o.line_type) };
|
||||
let mut a = Appearance::basic(Paint::None, paint(color), width);
|
||||
let mut a = Appearance::basic(Paint::None, paint(color, mode), width);
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
st.dash = match kind {
|
||||
LineType::Dashed => Some(Dash { pattern: vec![width * 5.0, width * 3.0], ..Default::default() }),
|
||||
@@ -283,6 +334,7 @@ fn along(o: &DimensionOptions) -> f64 {
|
||||
fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<Node>>> {
|
||||
d.validate().map_err(error)?;
|
||||
let o = &d.options;
|
||||
let mode = doc.color_mode;
|
||||
let label = d.label().map_err(error)?;
|
||||
let mut paths: Vec<(BezPath, Appearance)> = Vec::new();
|
||||
let mut angle = 0.0;
|
||||
@@ -299,11 +351,11 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
for i in 1..=64 {
|
||||
arc.line_to(on(i as f64 / 64.0));
|
||||
}
|
||||
paths.push((arc, appearance(o, false, true)));
|
||||
paths.push((arc, appearance(o, mode, false, true)));
|
||||
if !o.hide_extensions {
|
||||
for p in [d.a, d.b] {
|
||||
let dir = (p - d.vertex) / (p - d.vertex).hypot();
|
||||
paths.push((line(d.vertex + dir * o.extension_offset, d.vertex + dir * (r + o.extension_length)), appearance(o, true, false)));
|
||||
paths.push((line(d.vertex + dir * o.extension_offset, d.vertex + dir * (r + o.extension_length)), appearance(o, mode, true, false)));
|
||||
}
|
||||
}
|
||||
let dir = Vec2::from_angle(start + sweep * along(o));
|
||||
@@ -331,7 +383,7 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
};
|
||||
if d.mode == DimensionMode::Linear && !o.hide_extensions {
|
||||
for (p, q) in [(d.a, a), (d.b, b)] {
|
||||
paths.push((line(p + outward * o.extension_offset, q + outward * o.extension_length), appearance(o, true, false)));
|
||||
paths.push((line(p + outward * o.extension_offset, q + outward * o.extension_length), appearance(o, mode, true, false)));
|
||||
}
|
||||
}
|
||||
angle = u.atan2();
|
||||
@@ -340,17 +392,18 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
}
|
||||
let shift = o.text_offset + o.font_size * 0.5;
|
||||
text_at = a.lerp(b, along(o)) + outward * if away { shift } else { -shift };
|
||||
paths.push((line(a, b), appearance(o, false, true)));
|
||||
paths.push((line(a, b), appearance(o, mode, false, true)));
|
||||
}
|
||||
let style = CharStyle {
|
||||
font_family: o.font_family.clone(),
|
||||
font_style: o.font_style.clone(),
|
||||
size: o.font_size,
|
||||
fill: paint(o.text_color),
|
||||
fill: paint(o.text_color, mode),
|
||||
..Default::default()
|
||||
};
|
||||
let mut text = TextObject::point(Point::ZERO, &label, style);
|
||||
text.para.justify = vectorcraft_doc::Justify::Center;
|
||||
text.system_layout = doc.setup.system_layout;
|
||||
super::typecmd::refresh_bounds(&mut text);
|
||||
// Centre the label's box on its anchor point, along the line.
|
||||
let bounds = text.cached_bounds.unwrap_or_else(|| text.estimate_bounds());
|
||||
@@ -363,7 +416,7 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
}
|
||||
let id = old.get(children.len()).copied().unwrap_or_else(|| doc.alloc_id());
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(text)));
|
||||
node.appearance = Appearance::basic(paint(o.text_color), Paint::None, 0.0).into();
|
||||
node.appearance = Appearance::basic(paint(o.text_color, mode), Paint::None, 0.0).into();
|
||||
children.push(Arc::new(node));
|
||||
Ok(children)
|
||||
}
|
||||
@@ -17,6 +17,14 @@ use super::edit::{duplicate_in, outermost, selected_roots};
|
||||
use super::*;
|
||||
use crate::EngineError;
|
||||
|
||||
mod perspective;
|
||||
|
||||
pub use perspective::perspective_click;
|
||||
use perspective::{
|
||||
attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release,
|
||||
};
|
||||
pub(crate) use perspective::{finish_edit_text, grid_of, perspective_rewrite, silent, store_grid, transform_again};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -60,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Liquify",
|
||||
[],
|
||||
None,
|
||||
"{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle?, intensity? (0..1 or %), usePressure? (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut? (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}",
|
||||
"{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle?, intensity? (0..1 or %), usePressure?: bool (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut?: bool (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}",
|
||||
has_doc,
|
||||
liquify
|
||||
),
|
||||
@@ -300,7 +308,7 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !(left.is_finite() && right.is_finite()) || left < 0.0 || right < 0.0 || left.max(right) > 1.0e5 {
|
||||
return Err(bad(C, "left/right must be non-negative widths"));
|
||||
}
|
||||
let adjust = bool_or(p, "adjustAdjoining", false);
|
||||
let adjust = switch_or(p, "adjustAdjoining", false, C)?;
|
||||
// When the profile comes out as it was, within a rounding error (1e-9), the document and its undo
|
||||
// history stay as they are.
|
||||
let mut pos = 0;
|
||||
@@ -405,7 +413,7 @@ fn width_profile_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(a)) => {
|
||||
let mut pts = vec![];
|
||||
for q in a {
|
||||
let v: Vec<f64> = q.as_array().map(|x| x.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
|
||||
let v: Vec<f64> = q.as_array().and_then(|x| x.iter().map(Value::as_f64).collect()).unwrap_or_default();
|
||||
if v.len() != 3 || v.iter().any(|x| !x.is_finite()) || v[1] < 0.0 || v[2] < 0.0 {
|
||||
return Err(bad(C, "points must be [t, left, right] with non-negative widths"));
|
||||
}
|
||||
@@ -455,7 +463,8 @@ fn samples_of(p: &Value, key: &str) -> Option<Vec<Sample>> {
|
||||
/// What a liquify stroke may reach: the paths it can edit, each with the box no dab outside
|
||||
/// changes it ([`reach_bounds`]), and the objects it leaves as they are (type, symbols, images,
|
||||
/// graphs, meshes, and envelopes, repeats and blends with their contents), each with its bounds
|
||||
/// and what it is. Hidden and locked objects, and guides, are neither.
|
||||
/// and what it is. Hidden and locked objects, the art on a locked artboard, and guides are
|
||||
/// neither.
|
||||
#[derive(Default)]
|
||||
struct Targets {
|
||||
paths: Vec<(NodeId, Rect)>,
|
||||
@@ -484,19 +493,21 @@ impl Targets {
|
||||
/// The targets under `roots` (the selection), or with none every visible object.
|
||||
fn of(d: &Document, roots: &[NodeId]) -> Self {
|
||||
let mut t = Self::default();
|
||||
let locks = d.locked_artboards();
|
||||
if roots.is_empty() {
|
||||
d.layers.iter().for_each(|l| t.visit(l));
|
||||
d.layers.iter().for_each(|l| t.visit(l, &locks));
|
||||
return t;
|
||||
}
|
||||
let editable = |id| d.is_editable_with(&locks, id);
|
||||
for r in roots {
|
||||
let (Some(n), Some(chain)) = (d.node(*r), d.ancestry(*r)) else { continue };
|
||||
if !d.is_editable(*r) {
|
||||
if !editable(*r) {
|
||||
continue;
|
||||
}
|
||||
// Inside a graph, an envelope, a repeat or a blend: that object is what is left alone.
|
||||
match chain.iter().filter_map(|a| d.node(*a)).find_map(|a| Some((a, not_liquified(a)?))) {
|
||||
Some((a, what)) => t.block(a, what),
|
||||
None => t.visit(n),
|
||||
None => t.visit(n, &locks),
|
||||
}
|
||||
}
|
||||
t
|
||||
@@ -510,7 +521,7 @@ impl Targets {
|
||||
}
|
||||
}
|
||||
|
||||
fn visit(&mut self, n: &Node) {
|
||||
fn visit(&mut self, n: &Node, locks: &vectorcraft_doc::LockedArtboards) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
}
|
||||
@@ -525,7 +536,8 @@ impl Targets {
|
||||
self.paths.push((n.id, b));
|
||||
}
|
||||
}
|
||||
_ => n.children().into_iter().flatten().for_each(|c| self.visit(c)),
|
||||
// The objects of a layer on a locked artboard, members and all, are left out.
|
||||
_ => n.children().into_iter().flatten().filter(|c| !(n.is_layer() && locks.holds(c))).for_each(|c| self.visit(c, locks)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -628,9 +640,17 @@ impl LiquifyStroke {
|
||||
}
|
||||
}
|
||||
|
||||
/// The number keys of `object.liquify`. [`LiquifyParams::from_json`] reads a value that is not a
|
||||
/// number as the key left out.
|
||||
const LIQUIFY_NUMBERS: &[&str] =
|
||||
&["diameter", "width", "height", "angle", "intensity", "detail", "simplify", "rate", "complexity", "horizontal", "vertical"];
|
||||
|
||||
fn liquify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.liquify";
|
||||
check_numbers(p, LIQUIFY_NUMBERS, C)?;
|
||||
let prm = LiquifyParams::from_json(p).ok_or_else(|| bad(C, "missing or unknown `tool`"))?;
|
||||
// `LiquifyParams::from_json` uses a key's default for a value that is not true or false.
|
||||
check_switches(p, &["usePressure", "simplifyOn", "affectAnchors", "affectIn", "affectOut"], C)?;
|
||||
let pts = samples_of(p, "points").filter(|v| !v.is_empty()).ok_or_else(|| bad(C, "points must be a non-empty [[x,y,pressure?]…] list"))?;
|
||||
if pts.iter().any(|(q, f)| !q.x.is_finite() || !q.y.is_finite() || !f.is_finite()) {
|
||||
return Err(bad(C, "points must be finite"));
|
||||
@@ -697,9 +717,10 @@ fn puppet_ids(p: &Value, default: impl FnOnce() -> Result<Vec<NodeId>>) -> Resul
|
||||
|
||||
fn puppet_warp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.puppetWarp";
|
||||
check_numbers(p, &["expand"], C)?;
|
||||
let pins = points_of(p, "pins").ok_or_else(|| bad(C, "pins must be [[x,y]…]"))?;
|
||||
let moved = points_of(p, "moved").ok_or_else(|| bad(C, "moved must be [[x,y]…]"))?;
|
||||
let rest = bool_or(p, "rest", false);
|
||||
let rest = switch_or(p, "rest", false, C)?;
|
||||
if (pins.is_empty() && !rest) || pins.len() != moved.len() {
|
||||
return Err(bad(C, "pins and moved must be non-empty lists of the same length"));
|
||||
}
|
||||
@@ -711,7 +732,9 @@ fn puppet_warp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let expand = f64_or(p, "expand", 3.0).clamp(0.0, 1000.0);
|
||||
let angles: Vec<Option<f64>> = match p.get("angles") {
|
||||
None | Some(Value::Null) => vec![None; pins.len()],
|
||||
Some(Value::Array(a)) if a.len() == pins.len() => a.iter().map(|v| v.as_f64().filter(|d| d.is_finite()).map(f64::to_radians)).collect(),
|
||||
Some(Value::Array(a)) if a.len() == pins.len() && a.iter().all(|v| v.is_null() || v.is_number()) => {
|
||||
a.iter().map(|v| v.as_f64().filter(|d| d.is_finite()).map(f64::to_radians)).collect()
|
||||
}
|
||||
Some(_) => return Err(bad(C, "angles must be a list as long as pins (degrees or null)")),
|
||||
};
|
||||
let ids_json = json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() });
|
||||
@@ -752,6 +775,7 @@ pub(crate) fn drop_puppet_pins(st: &mut crate::DocState) {
|
||||
}
|
||||
|
||||
fn puppet_pins(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["expand"], "object.puppetWarp.pins")?;
|
||||
let ids = puppet_ids(p, || Ok(s.doc()?.selection.objects.clone()))?;
|
||||
let expand = f64_or(p, "expand", 3.0).clamp(0.0, 1000.0);
|
||||
let set = PinSet::of(&s.doc()?.doc, &ids, expand).ok_or_else(|| EngineError::Other("nothing to warp".into()))?;
|
||||
@@ -759,601 +783,3 @@ fn puppet_pins(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
v["auto"] = json!(set.auto);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
// ---------- perspective grid ----------
|
||||
|
||||
/// The document's perspective grid (the default preset when none was defined).
|
||||
pub(crate) fn grid_of(d: &Document) -> PerspectiveGrid {
|
||||
PerspectiveGrid::effective(d)
|
||||
}
|
||||
|
||||
/// Write the grid into the document (`Document.unknown["perspectiveGrid"]`).
|
||||
pub(crate) fn store_grid(d: &mut Document, g: &PerspectiveGrid) {
|
||||
g.store(d);
|
||||
}
|
||||
|
||||
/// Whether `d` holds `g` as [`store_grid`] writes it (with `attached` cleared): then storing `g`
|
||||
/// leaves `d` as it is.
|
||||
fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
|
||||
let mut g = g.clone();
|
||||
g.attached.clear();
|
||||
serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v))
|
||||
}
|
||||
|
||||
/// Change view state of the grid without an undo step.
|
||||
pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result<PerspectiveGrid> {
|
||||
let st = s.doc_mut()?;
|
||||
let mut g = grid_of(&st.doc);
|
||||
f(&mut g);
|
||||
store_grid(Arc::make_mut(&mut st.doc), &g);
|
||||
if let Some(it) = &mut st.interaction {
|
||||
store_grid(Arc::make_mut(&mut it.doc), &g);
|
||||
}
|
||||
st.revision += 1;
|
||||
Ok(g)
|
||||
}
|
||||
|
||||
fn grid_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let old = grid_of(&s.doc()?.doc);
|
||||
let g = old.merged(p).map_err(|e| bad("perspective.grid.set", e))?;
|
||||
let reproject = bool_or(p, "reproject", false);
|
||||
// When the document holds this grid already, no object moves, and the document and its undo
|
||||
// history stay as they are.
|
||||
if grid_kept(&s.doc()?.doc, &g) {
|
||||
return Ok(g.definition_json());
|
||||
}
|
||||
s.edit("Define Perspective Grid", |d, _| {
|
||||
if reproject {
|
||||
old.adopt_stored_attachments(d);
|
||||
for (id, plane, depth) in persp::attached_roots(d) {
|
||||
let h = old.homography_at(plane, depth).and_then(|h| h.inverse()).zip(g.homography_at(plane, depth));
|
||||
let (hi, h) = h.ok_or_else(|| EngineError::Other("an object in perspective would leave the edited grid".into()))?;
|
||||
let m = h.then_after(&hi);
|
||||
warp_checked(d, id, &m)?;
|
||||
}
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(g.definition_json())
|
||||
}
|
||||
|
||||
fn grid_show(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let want = p.get("visible").and_then(Value::as_bool);
|
||||
let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?;
|
||||
Ok(json!({ "visible": g.visible }))
|
||||
}
|
||||
|
||||
fn plane_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?;
|
||||
silent(s, |g| g.plane = plane)?;
|
||||
Ok(json!({ "plane": plane.id() }))
|
||||
}
|
||||
|
||||
fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result<Plane> {
|
||||
let plane = match str_param(p, "plane") {
|
||||
Some(v) => Plane::parse(v).ok_or_else(|| bad(cmd, "plane must be left|right|ground"))?,
|
||||
None => g.plane,
|
||||
};
|
||||
if plane == Plane::None {
|
||||
return Err(EngineError::Other("no active perspective plane".into()));
|
||||
}
|
||||
Ok(plane)
|
||||
}
|
||||
|
||||
fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) {
|
||||
Some(v) => Ok(outermost(&s.doc()?.doc, v)),
|
||||
None => selected_roots(s),
|
||||
}
|
||||
}
|
||||
|
||||
/// Map `n` with `f`, failing if any point would leave the plane's visible side.
|
||||
/// Map `n` with `h` (type and symbols in perspective keep their art and are drawn through it),
|
||||
/// failing if any point would leave the plane's visible side.
|
||||
fn warp_checked(d: &mut Document, id: NodeId, h: &Homography) -> Result<()> {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut pts = vec![];
|
||||
collect_points(n, &mut pts);
|
||||
if pts.iter().any(|q| h.apply(*q).is_none()) {
|
||||
return Err(EngineError::Other("the object would cross the horizon of the perspective plane".into()));
|
||||
}
|
||||
project_node(n, h);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Attach `id` to `plane`: projected by `map`, else by the map that keeps its bounds' corners
|
||||
/// (on the nearest gridlines with `snap`).
|
||||
fn attach_in(d: &mut Document, g: &mut PerspectiveGrid, id: NodeId, plane: Plane, snap: bool, map: Option<Homography>) -> Result<()> {
|
||||
let b = d.node(id).ok_or(EngineError::NoNode(id))?.geometric_bounds().ok_or_else(|| EngineError::Other("the object has no geometry".into()))?;
|
||||
let m =
|
||||
map.or_else(|| g.attach_homography(plane, b, snap)).ok_or_else(|| EngineError::Other("the object is beyond the plane's horizon".into()))?;
|
||||
warp_checked(d, id, &m)?;
|
||||
persp::set_attachment(d.node_mut(id).ok_or(EngineError::NoNode(id))?, plane, g.offset(plane));
|
||||
g.attached.insert(id.0.to_string(), plane);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn attach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = roots(s, p)?;
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
let plane = plane_param(&g, p, "perspective.attach")?;
|
||||
// With no object to attach, when the document holds the grid already, the document and its undo
|
||||
// history stay as they are.
|
||||
if ids.is_empty() && grid_kept(&s.doc()?.doc, &g) {
|
||||
return Ok(json!({ "ids": [], "plane": plane.id() }));
|
||||
}
|
||||
s.edit("Attach to Active Plane", |d, _| {
|
||||
for id in &ids {
|
||||
attach_in(d, &mut g, *id, plane, false, None)?;
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "plane": plane.id() }))
|
||||
}
|
||||
|
||||
fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = roots(s, p)?;
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
// When releasing leaves every object as it is (none is in perspective) and the document holds
|
||||
// the grid already, the document and its undo history stay as they are.
|
||||
let d = &s.doc()?.doc;
|
||||
let unchanged = |id: &NodeId| {
|
||||
d.node(*id).is_none_or(|n| {
|
||||
let mut released = n.clone();
|
||||
persp::release(&mut released);
|
||||
released == *n
|
||||
})
|
||||
};
|
||||
if ids.iter().all(unchanged) && grid_kept(d, &g) {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Release with Perspective", |d, _| {
|
||||
for id in &ids {
|
||||
g.attached.remove(&id.0.to_string());
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
persp::release(n);
|
||||
}
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// One object's share of a perspective edit: the page map for an object on `plane` at `depth`, and
|
||||
/// the depth it ends at.
|
||||
type PerspStep<'a> = &'a dyn Fn(&PerspectiveGrid, Plane, f64) -> Result<(Homography, f64)>;
|
||||
|
||||
/// Where an object is in perspective: its plane and depth.
|
||||
type Attached = (Plane, f64);
|
||||
|
||||
fn beyond_horizon() -> EngineError {
|
||||
EngineError::Other("the pointer is beyond the plane's horizon".into())
|
||||
}
|
||||
|
||||
/// Whether the grid stored in `d` lists attachments of its own, as grids stored before attachments
|
||||
/// were kept on the objects do ([`PerspectiveGrid::adopt_stored_attachments`]).
|
||||
fn stores_attachments(d: &Document) -> bool {
|
||||
!PerspectiveGrid::current(d).attached.is_empty()
|
||||
}
|
||||
|
||||
/// Edit objects in perspective (one undo step `label`): with `copy` their duplicates (which stay
|
||||
/// attached), each mapped by `step` for its own plane and depth; objects not in perspective attach
|
||||
/// to `fallback` first. → the edited objects and where the first one was (plane, depth). In an
|
||||
/// interaction whose document is still its snapshot, the duplicates are the copies the interaction
|
||||
/// keeps ([`super::object::preview_copies`]), unless the snapshot's grid lists attachments of its
|
||||
/// own ([`stores_attachments`]).
|
||||
fn persp_edit(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
ids: &[NodeId],
|
||||
fallback: Option<Plane>,
|
||||
copy: bool,
|
||||
step: PerspStep,
|
||||
) -> Result<(Vec<NodeId>, Option<Attached>)> {
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("select the objects to transform in perspective".into()));
|
||||
}
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
let kept = if copy && !stores_attachments(&s.doc()?.doc) { super::object::preview_copies(s, ids, false)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
g.adopt_stored_attachments(d);
|
||||
let targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, not yet mapped, and the loop
|
||||
// below maps only the copies.
|
||||
Some(k) => {
|
||||
*d = Document::clone(&k.doc);
|
||||
sel.clone_from(&k.selection);
|
||||
k.ids.clone()
|
||||
}
|
||||
None if copy => duplicate_in(d, sel, ids, Affine::IDENTITY)?,
|
||||
None => ids.to_vec(),
|
||||
};
|
||||
let mut first = None;
|
||||
for id in &targets {
|
||||
let (plane, depth) = match g.attachment_of(d, *id) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
let pl = fallback.ok_or_else(|| EngineError::Other("the object isn't on a perspective plane".into()))?;
|
||||
attach_in(d, &mut g, *id, pl, false, None)?;
|
||||
(pl, g.offset(pl))
|
||||
}
|
||||
};
|
||||
first.get_or_insert((plane, depth));
|
||||
let (h, depth) = step(&g, plane, depth)?;
|
||||
warp_checked(d, *id, &h)?;
|
||||
persp::set_attachment(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, plane, depth);
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok((targets, first))
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one
|
||||
/// of them is in perspective already, `still` holds for each one's plane and depth, and the document
|
||||
/// holds the grid already; None otherwise.
|
||||
fn unmoved(s: &Session, ids: &[NodeId], still: impl Fn(&PerspectiveGrid, Plane, f64) -> bool) -> Result<Option<Attached>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let g = grid_of(d);
|
||||
if ids.is_empty() || !grid_kept(d, &g) {
|
||||
return Ok(None);
|
||||
}
|
||||
let at: Option<Vec<Attached>> = ids.iter().map(|id| g.attachment_of(d, *id).filter(|(pl, depth)| still(&g, *pl, *depth))).collect();
|
||||
Ok(at.and_then(|at| at.first().copied()))
|
||||
}
|
||||
|
||||
/// Remember `again` (`perspective.transform` params) for Object › Transform › Transform Again, once
|
||||
/// the drag that made it is committed.
|
||||
fn record_again(s: &mut Session, again: Value) -> Result<()> {
|
||||
let st = s.doc_mut()?;
|
||||
match &mut st.interaction {
|
||||
Some(it) => it.perspective_again = Some(again),
|
||||
None => st.last_perspective = Some(again),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
|
||||
}
|
||||
|
||||
/// A plane-space affine map as `perspective.transform`'s `matrix` param.
|
||||
fn matrix_json(m: Affine) -> Value {
|
||||
json!(m.as_coeffs())
|
||||
}
|
||||
|
||||
fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.move";
|
||||
let ids = roots(s, p)?;
|
||||
let from = point_param(p, "from").ok_or_else(|| bad(C, "missing from"))?;
|
||||
let to = point_param(p, "to").ok_or_else(|| bad(C, "missing to"))?;
|
||||
if ![from.x, from.y, to.x, to.y].iter().all(|v| v.is_finite()) {
|
||||
return Err(bad(C, "from and to must be finite"));
|
||||
}
|
||||
let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok();
|
||||
let (perp, copy) = (bool_or(p, "perpendicular", false), bool_or(p, "copy", false));
|
||||
// Snap to Grid: a correction for the objects on the first one's plane and depth.
|
||||
let fix = if perp { None } else { super::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, to)) };
|
||||
let snapped = move |pl: Plane, depth: f64, dv: vectorcraft_geom::Vec2| {
|
||||
dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| f.2)
|
||||
};
|
||||
// In-plane: the plane-space offset under the pointer; perpendicular: the depth it reaches.
|
||||
let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> {
|
||||
if perp {
|
||||
let to_depth = g.depth_at(pl, depth, from, to).ok_or_else(beyond_horizon)?;
|
||||
Ok((g.transform_map(pl, depth, Affine::IDENTITY, to_depth - depth).ok_or_else(beyond_horizon)?, to_depth))
|
||||
} else {
|
||||
let dv = snapped(pl, depth, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?);
|
||||
Ok((g.transform_map(pl, depth, Affine::translate(dv), 0.0).ok_or_else(beyond_horizon)?, depth))
|
||||
}
|
||||
};
|
||||
let label = if copy { "Copy in Perspective" } else { "Move in Perspective" };
|
||||
// When no object moves more than 1e-9 pt along its plane's axes or its normal (Snap to Grid
|
||||
// included) and there is no copy, the document and its undo history stay as they are.
|
||||
let still = |g: &PerspectiveGrid, pl: Plane, depth: f64| {
|
||||
if perp {
|
||||
g.depth_at(pl, depth, from, to).is_some_and(|d| (d - depth).abs() <= 1e-9)
|
||||
} else {
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, depth, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9)
|
||||
}
|
||||
};
|
||||
let first_still = if copy { None } else { unmoved(s, &ids, still)? };
|
||||
let (targets, first) = match first_still {
|
||||
Some(at) => (ids, Some(at)),
|
||||
None => persp_edit(s, label, &ids, fallback, copy, &step)?,
|
||||
};
|
||||
// Transform Again repeats the first object's move, and the identity when no object moved.
|
||||
if let Some((pl, depth)) = first {
|
||||
let g = grid_of(&s.doc()?.doc);
|
||||
let again = match perp {
|
||||
_ if first_still.is_some() => Some(json!({"matrix": matrix_json(Affine::IDENTITY), "copy": copy})),
|
||||
true => g.depth_at(pl, depth, from, to).map(|d| json!({"matrix": matrix_json(Affine::IDENTITY), "depth": d - depth, "copy": copy})),
|
||||
false => {
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, depth, dv))), "copy": copy}))
|
||||
}
|
||||
};
|
||||
if let Some(a) = again {
|
||||
record_again(s, a)?;
|
||||
}
|
||||
}
|
||||
Ok(ids_json(&targets))
|
||||
}
|
||||
|
||||
fn persp_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.transform";
|
||||
let m = matrix_param(p, "matrix").ok_or_else(|| bad(C, "missing matrix [a,b,c,d,e,f]"))?;
|
||||
let dz = f64_or(p, "depth", 0.0);
|
||||
if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 || !dz.is_finite() {
|
||||
return Err(bad(C, "matrix must be finite and invertible, depth finite"));
|
||||
}
|
||||
let ids = roots(s, p)?;
|
||||
let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok();
|
||||
let copy = bool_or(p, "copy", false);
|
||||
let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> {
|
||||
let to = depth + dz;
|
||||
if to.abs() > persp::MAX_DEPTH {
|
||||
return Err(EngineError::Other("the objects would leave the grid".into()));
|
||||
}
|
||||
Ok((g.transform_map(pl, depth, m, dz).ok_or_else(beyond_horizon)?, to))
|
||||
};
|
||||
// An identity without a copy moves no object that is in perspective already: then the document
|
||||
// and its undo history stay as they are, and Transform Again repeats the identity.
|
||||
let identity = !copy && m == Affine::IDENTITY && dz == 0.0;
|
||||
let targets = if identity && unmoved(s, &ids, |g, pl, depth| g.transform_map(pl, depth, m, dz).is_some())?.is_some() {
|
||||
ids
|
||||
} else {
|
||||
persp_edit(s, if copy { "Copy in Perspective" } else { "Transform in Perspective" }, &ids, fallback, copy, &step)?.0
|
||||
};
|
||||
record_again(s, json!({"matrix": matrix_json(m), "depth": dz, "copy": copy}))?;
|
||||
Ok(ids_json(&targets))
|
||||
}
|
||||
|
||||
/// Object › Transform › Transform Again after a perspective move or scale: the same plane-space
|
||||
/// transform on the selection.
|
||||
pub(crate) fn transform_again(s: &mut Session, again: &Value) -> Result<Value> {
|
||||
let mut p = again.clone();
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.remove("ids");
|
||||
}
|
||||
persp_transform(s, &p)
|
||||
}
|
||||
|
||||
fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.plane.move";
|
||||
let old = grid_of(&s.doc()?.doc);
|
||||
let plane = plane_param(&old, p, C)?;
|
||||
let from = old.offset(plane);
|
||||
let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) {
|
||||
(Some(o), _) => o,
|
||||
(None, Some(b)) => from + b,
|
||||
(None, None) => return Err(bad(C, "give offset or by")),
|
||||
};
|
||||
let objects = str_param(p, "objects").unwrap_or("none");
|
||||
if !matches!(objects, "none" | "move" | "copy") {
|
||||
return Err(bad(C, "objects must be none, move or copy"));
|
||||
}
|
||||
let mut g = old.clone();
|
||||
g.set_offset(plane, to);
|
||||
g.validate().map_err(|e| bad(C, e))?;
|
||||
let label = match objects {
|
||||
"copy" => "Move Plane and Copy Objects",
|
||||
"move" => "Move Plane and Objects",
|
||||
_ => "Move Plane",
|
||||
};
|
||||
// The objects on the plane where it was (not those moved off it along its normal).
|
||||
let on_plane = |d: &Document| -> Vec<NodeId> {
|
||||
persp::attached_roots(d)
|
||||
.into_iter()
|
||||
.filter(|(id, pl, depth)| *pl == plane && (depth - from).abs() < 1e-6 && d.is_editable(*id))
|
||||
.map(|(id, ..)| id)
|
||||
.collect()
|
||||
};
|
||||
// A plane moved to where it is, with its objects or without them, moves nothing: when the
|
||||
// document holds the grid already, the document and its undo history stay as they are.
|
||||
if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) {
|
||||
let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] };
|
||||
return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
|
||||
}
|
||||
// In an interaction whose document is still its snapshot, the copies of the objects on the
|
||||
// plane are the copies the interaction keeps (`preview_copies`), unless the snapshot's grid
|
||||
// lists attachments of its own (`stores_attachments`).
|
||||
let kept = if objects == "copy" && s.in_interaction() && !stores_attachments(&s.doc()?.doc) {
|
||||
let on = on_plane(&s.doc()?.doc);
|
||||
super::object::preview_copies(s, &on, false)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
old.adopt_stored_attachments(d);
|
||||
let mut ids = vec![];
|
||||
if objects != "none" {
|
||||
ids = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, not yet moved, and the
|
||||
// loop below moves only the copies.
|
||||
Some(k) => {
|
||||
*d = Document::clone(&k.doc);
|
||||
sel.clone_from(&k.selection);
|
||||
k.ids.clone()
|
||||
}
|
||||
None => {
|
||||
let on = on_plane(d);
|
||||
if objects == "copy" { duplicate_in(d, sel, &on, Affine::IDENTITY)? } else { on }
|
||||
}
|
||||
};
|
||||
let m = old.transform_map(plane, from, Affine::IDENTITY, to - from).ok_or_else(beyond_horizon)?;
|
||||
for id in &ids {
|
||||
warp_checked(d, *id, &m)?;
|
||||
persp::set_attachment(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, plane, to);
|
||||
}
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
fn plane_match(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id = id_param(p, "id")
|
||||
.or_else(|| st.selection.objects.first().copied())
|
||||
.ok_or_else(|| EngineError::Other("select an object in perspective".into()))?;
|
||||
let mut g = grid_of(&st.doc);
|
||||
let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?;
|
||||
g.set_offset(plane, depth);
|
||||
g.plane = plane;
|
||||
g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?;
|
||||
// When the plane is at the object and active already, and the document holds that grid, the
|
||||
// document and its undo history stay as they are.
|
||||
if grid_kept(&st.doc, &g) {
|
||||
return Ok(json!({ "plane": plane.id(), "offset": depth }));
|
||||
}
|
||||
s.edit("Move Plane to Match Object", |d, _| {
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "plane": plane.id(), "offset": depth }))
|
||||
}
|
||||
|
||||
fn persp_nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.nudge";
|
||||
let (dx, dy) = (f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0));
|
||||
if !(dx.is_finite() && dy.is_finite()) || (dx == 0.0 && dy == 0.0) {
|
||||
return Err(bad(C, "dx and dy give the arrow's direction"));
|
||||
}
|
||||
let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 };
|
||||
let ids = selected_roots(s)?;
|
||||
// The step is measured on the page at the centre of the selection's perspective box.
|
||||
let st = s.doc()?;
|
||||
let g = grid_of(&st.doc);
|
||||
let (plane, depth, rect) = g.plane_bounds(&st.doc, &ids).ok_or_else(|| EngineError::Other("the selection isn't in perspective".into()))?;
|
||||
let from = g.homography_at(plane, depth).and_then(|h| h.apply(rect.center())).ok_or_else(beyond_horizon)?;
|
||||
let to = from + vectorcraft_geom::Vec2::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)) * k;
|
||||
persp_move(
|
||||
s,
|
||||
&json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": bool_or(p, "copy", false)}),
|
||||
)
|
||||
}
|
||||
|
||||
fn persp_draw(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.draw";
|
||||
let command = str_param(p, "command").filter(|c| c.starts_with("shape.")).ok_or_else(|| bad(C, "command must be a shape.* command"))?.to_string();
|
||||
let params = p.get("params").cloned().unwrap_or_else(|| json!({}));
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
let plane = plane_param(&g, p, C)?;
|
||||
let snap = bool_or(p, "snap", g.snap);
|
||||
// A click-to-size dialog's shape keeps its sizes in plane units from the click.
|
||||
let map = match point_param(p, "at") {
|
||||
Some(at) => Some(g.size_homography(plane, at, snap).ok_or_else(beyond_horizon)?),
|
||||
None => None,
|
||||
};
|
||||
let undo_before = s.doc()?.history.undo.len();
|
||||
let r = s.execute(&command, ¶ms)?;
|
||||
let id = r.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| EngineError::Other(format!("{command} didn't create an object")))?;
|
||||
let res = s.edit("Draw in Perspective", |d, _| {
|
||||
attach_in(d, &mut g, id, plane, snap, map)?;
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
});
|
||||
// One undo step for the whole gesture.
|
||||
let st = s.doc_mut()?;
|
||||
if st.interaction.is_none() && st.history.undo.len() > undo_before + 1 {
|
||||
st.history.undo.truncate(undo_before + 1);
|
||||
if let Some(e) = st.history.undo.last_mut() {
|
||||
e.label = "Draw in Perspective".into();
|
||||
}
|
||||
st.history.recost_last(&st.doc);
|
||||
}
|
||||
res?;
|
||||
Ok(json!({ "id": id.0, "plane": plane.id() }))
|
||||
}
|
||||
|
||||
/// Shape tool previews become `perspective.draw` while the grid is shown with an active plane.
|
||||
pub(crate) fn perspective_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<(String, Value)> {
|
||||
const SHAPES: &[&str] = &[
|
||||
"shape.rectangle",
|
||||
"shape.ellipse",
|
||||
"shape.polygon",
|
||||
"shape.star",
|
||||
"shape.line",
|
||||
"shape.rectangularGrid",
|
||||
"shape.arc",
|
||||
"shape.flare",
|
||||
"shape.spiral",
|
||||
"shape.polarGrid",
|
||||
];
|
||||
if !SHAPES.contains(&cmd) {
|
||||
return None;
|
||||
}
|
||||
let g = PerspectiveGrid::current(&s.active()?.doc);
|
||||
(g.visible && g.plane != Plane::None).then(|| ("perspective.draw".to_string(), json!({"command": cmd, "params": params})))
|
||||
}
|
||||
|
||||
/// A click-to-size shape dialog's command (`cmd` with `params`, clicked at `at`) as it runs: on the
|
||||
/// active plane while the grid shows (`perspective.draw` keeping the sizes in plane units from the
|
||||
/// click), else `None` (run it as it is).
|
||||
pub fn perspective_click(s: &Session, cmd: &str, params: &Value, at: Point) -> Option<(String, Value)> {
|
||||
let (c, mut p) = perspective_rewrite(s, cmd, params)?;
|
||||
p["at"] = json!([at.x, at.y]);
|
||||
Some((c, p))
|
||||
}
|
||||
|
||||
/// Object › Perspective › Edit Text: type in perspective shown flat where it is drawn, in isolation
|
||||
/// mode, to be edited; exiting isolation projects it again ([`finish_edit_text`]).
|
||||
fn edit_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id =
|
||||
id_param(p, "id").or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select type in perspective".into()))?;
|
||||
if !st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)) && n.projection().is_some()) {
|
||||
return Err(EngineError::Other("select type in perspective".into()));
|
||||
}
|
||||
s.edit("Edit Text", |d, _| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let h = n.projection().ok_or_else(|| EngineError::Other("select type in perspective".into()))?;
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("select type in perspective".into())) };
|
||||
// Shown flat where it is drawn: the type moves there and the projection moves the other
|
||||
// way, so the picture stays.
|
||||
let (Some(flat), Some(drawn)) = (t.bounds(), t.bounds().and_then(|b| h.map_rect_bbox(b))) else { return Ok(()) };
|
||||
let shift = vectorcraft_geom::Affine::translate(drawn.center() - flat.center());
|
||||
t.transform(shift);
|
||||
if let Some(rec) = n.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) {
|
||||
rec.projection = Some(h.then_after(&Homography::from_affine(shift.inverse())).to_array());
|
||||
rec.editing = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let st = s.doc_mut()?;
|
||||
st.isolation = Some(id);
|
||||
st.selection.set([id]);
|
||||
st.revision += 1;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// Edit Text ends (isolation mode on `id` exits): the type is projected again, in the document and
|
||||
/// in every undo state (the flat view is never an undo step of its own, and never saved: a saved
|
||||
/// state stays saved, [`crate::DocState::change_unsaved`]).
|
||||
pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) {
|
||||
let clear = |doc: &mut Arc<Document>| {
|
||||
// Undo steps keep no lookup cache: look without building one, and drop the one an edit
|
||||
// builds (the document now keeps its own).
|
||||
if doc.node_uncached(id).and_then(|n| n.extras().perspective.as_deref()).is_some_and(|p| p.editing)
|
||||
&& let Some(p) = Arc::make_mut(doc).node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.perspective.as_deref_mut()))
|
||||
{
|
||||
p.editing = false;
|
||||
}
|
||||
};
|
||||
st.change_unsaved(clear);
|
||||
for e in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) {
|
||||
let saved = Arc::ptr_eq(&e.doc, &st.saved_doc);
|
||||
clear(&mut e.doc);
|
||||
e.doc.drop_lookup_cache();
|
||||
if saved {
|
||||
st.saved_doc = e.doc.clone();
|
||||
}
|
||||
}
|
||||
if let Some(it) = &mut st.interaction {
|
||||
clear(&mut it.doc);
|
||||
}
|
||||
st.revision += 1;
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
use super::*;
|
||||
|
||||
// ---------- perspective grid ----------
|
||||
|
||||
/// The document's perspective grid (the default preset when none was defined).
|
||||
pub(crate) fn grid_of(d: &Document) -> PerspectiveGrid {
|
||||
PerspectiveGrid::effective(d)
|
||||
}
|
||||
|
||||
/// Write the grid into the document (`Document.unknown["perspectiveGrid"]`).
|
||||
pub(crate) fn store_grid(d: &mut Document, g: &PerspectiveGrid) {
|
||||
g.store(d);
|
||||
}
|
||||
|
||||
/// Whether `d` holds `g` as [`store_grid`] writes it (with `attached` cleared): then storing `g`
|
||||
/// leaves `d` as it is.
|
||||
fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
|
||||
let mut g = g.clone();
|
||||
g.attached.clear();
|
||||
serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v))
|
||||
}
|
||||
|
||||
/// Change view state of the grid without an undo step.
|
||||
pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result<PerspectiveGrid> {
|
||||
let st = s.doc_mut()?;
|
||||
let mut g = grid_of(&st.doc);
|
||||
f(&mut g);
|
||||
store_grid(Arc::make_mut(&mut st.doc), &g);
|
||||
if let Some(it) = &mut st.interaction {
|
||||
store_grid(Arc::make_mut(&mut it.doc), &g);
|
||||
}
|
||||
st.revision += 1;
|
||||
Ok(g)
|
||||
}
|
||||
|
||||
pub(super) fn grid_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.grid.set";
|
||||
let old = grid_of(&s.doc()?.doc);
|
||||
let g = old.merged(p).map_err(|e| bad(C, e))?;
|
||||
let reproject = switch_or(p, "reproject", false, C)?;
|
||||
// When the document holds this grid already, no object moves, and the document and its undo
|
||||
// history stay as they are.
|
||||
if grid_kept(&s.doc()?.doc, &g) {
|
||||
return Ok(g.definition_json());
|
||||
}
|
||||
s.edit("Define Perspective Grid", |d, _| {
|
||||
if reproject {
|
||||
old.adopt_stored_attachments(d);
|
||||
for (id, plane, depth) in persp::attached_roots(d) {
|
||||
let h = old.homography_at(plane, depth).and_then(|h| h.inverse()).zip(g.homography_at(plane, depth));
|
||||
let (hi, h) = h.ok_or_else(|| EngineError::Other("an object in perspective would leave the edited grid".into()))?;
|
||||
let m = h.then_after(&hi);
|
||||
warp_checked(d, id, &m)?;
|
||||
}
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(g.definition_json())
|
||||
}
|
||||
|
||||
pub(super) fn grid_show(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.grid.show";
|
||||
// A missing or null `visible` toggles the grid.
|
||||
let want = match p.get("visible") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(switch_or(p, "visible", false, C)?),
|
||||
};
|
||||
let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?;
|
||||
Ok(json!({ "visible": g.visible }))
|
||||
}
|
||||
|
||||
pub(super) fn plane_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?;
|
||||
silent(s, |g| g.plane = plane)?;
|
||||
Ok(json!({ "plane": plane.id() }))
|
||||
}
|
||||
|
||||
fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result<Plane> {
|
||||
let plane = match str_param(p, "plane") {
|
||||
Some(v) => Plane::parse(v).ok_or_else(|| bad(cmd, "plane must be left|right|ground"))?,
|
||||
None => g.plane,
|
||||
};
|
||||
if plane == Plane::None {
|
||||
return Err(EngineError::Other("no active perspective plane".into()));
|
||||
}
|
||||
Ok(plane)
|
||||
}
|
||||
|
||||
pub(super) fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) {
|
||||
Some(v) => Ok(outermost(&s.doc()?.doc, v)),
|
||||
None => selected_roots(s),
|
||||
}
|
||||
}
|
||||
|
||||
/// Map `n` with `f`, failing if any point would leave the plane's visible side.
|
||||
/// Map `n` with `h` (type and symbols in perspective keep their art and are drawn through it),
|
||||
/// failing if any point would leave the plane's visible side.
|
||||
fn warp_checked(d: &mut Document, id: NodeId, h: &Homography) -> Result<()> {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut pts = vec![];
|
||||
collect_points(n, &mut pts);
|
||||
if pts.iter().any(|q| h.apply(*q).is_none()) {
|
||||
return Err(EngineError::Other("the object would cross the horizon of the perspective plane".into()));
|
||||
}
|
||||
project_node(n, h);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Attach `id` to `plane`: projected by `map`, else by the map that keeps its bounds' corners
|
||||
/// (on the nearest gridlines with `snap`).
|
||||
fn attach_in(d: &mut Document, g: &mut PerspectiveGrid, id: NodeId, plane: Plane, snap: bool, map: Option<Homography>) -> Result<()> {
|
||||
let b = d.node(id).ok_or(EngineError::NoNode(id))?.geometric_bounds().ok_or_else(|| EngineError::Other("the object has no geometry".into()))?;
|
||||
let m =
|
||||
map.or_else(|| g.attach_homography(plane, b, snap)).ok_or_else(|| EngineError::Other("the object is beyond the plane's horizon".into()))?;
|
||||
warp_checked(d, id, &m)?;
|
||||
persp::set_attachment(d.node_mut(id).ok_or(EngineError::NoNode(id))?, plane, g.offset(plane));
|
||||
g.attached.insert(id.0.to_string(), plane);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn attach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = roots(s, p)?;
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
let plane = plane_param(&g, p, "perspective.attach")?;
|
||||
// With no object to attach, when the document holds the grid already, the document and its undo
|
||||
// history stay as they are.
|
||||
if ids.is_empty() && grid_kept(&s.doc()?.doc, &g) {
|
||||
return Ok(json!({ "ids": [], "plane": plane.id() }));
|
||||
}
|
||||
s.edit("Attach to Active Plane", |d, _| {
|
||||
for id in &ids {
|
||||
attach_in(d, &mut g, *id, plane, false, None)?;
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "plane": plane.id() }))
|
||||
}
|
||||
|
||||
pub(super) fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = roots(s, p)?;
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
// When releasing leaves every object as it is (none is in perspective) and the document holds
|
||||
// the grid already, the document and its undo history stay as they are.
|
||||
let d = &s.doc()?.doc;
|
||||
let unchanged = |id: &NodeId| {
|
||||
d.node(*id).is_none_or(|n| {
|
||||
let mut released = n.clone();
|
||||
persp::release(&mut released);
|
||||
released == *n
|
||||
})
|
||||
};
|
||||
if ids.iter().all(unchanged) && grid_kept(d, &g) {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Release with Perspective", |d, _| {
|
||||
for id in &ids {
|
||||
g.attached.remove(&id.0.to_string());
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
persp::release(n);
|
||||
}
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// One object's share of a perspective edit: the page map for an object on `plane` at `depth`, and
|
||||
/// the depth it ends at.
|
||||
type PerspStep<'a> = &'a dyn Fn(&PerspectiveGrid, Plane, f64) -> Result<(Homography, f64)>;
|
||||
|
||||
/// Where an object is in perspective: its plane and depth.
|
||||
type Attached = (Plane, f64);
|
||||
|
||||
fn beyond_horizon() -> EngineError {
|
||||
EngineError::Other("the pointer is beyond the plane's horizon".into())
|
||||
}
|
||||
|
||||
/// Whether the grid stored in `d` lists attachments of its own, as grids stored before attachments
|
||||
/// were kept on the objects do ([`PerspectiveGrid::adopt_stored_attachments`]).
|
||||
fn stores_attachments(d: &Document) -> bool {
|
||||
!PerspectiveGrid::current(d).attached.is_empty()
|
||||
}
|
||||
|
||||
/// Edit objects in perspective (one undo step `label`): with `copy` their duplicates (which stay
|
||||
/// attached), each mapped by `step` for its own plane and depth; objects not in perspective attach
|
||||
/// to `fallback` first. → the edited objects and where the first one was (plane, depth). In an
|
||||
/// interaction whose document is still its snapshot, the duplicates are the copies the interaction
|
||||
/// keeps ([`super::object::preview_copies`]), unless the snapshot's grid lists attachments of its
|
||||
/// own ([`stores_attachments`]).
|
||||
fn persp_edit(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
ids: &[NodeId],
|
||||
fallback: Option<Plane>,
|
||||
copy: bool,
|
||||
step: PerspStep,
|
||||
) -> Result<(Vec<NodeId>, Option<Attached>)> {
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("select the objects to transform in perspective".into()));
|
||||
}
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
g.adopt_stored_attachments(d);
|
||||
let targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, not yet mapped, and the loop
|
||||
// below maps only the copies.
|
||||
Some(k) => {
|
||||
*d = Document::clone(&k.doc);
|
||||
sel.clone_from(&k.selection);
|
||||
k.ids.clone()
|
||||
}
|
||||
None if copy => duplicate_in(d, sel, ids, Affine::IDENTITY)?,
|
||||
None => ids.to_vec(),
|
||||
};
|
||||
let mut first = None;
|
||||
for id in &targets {
|
||||
let (plane, depth) = match g.attachment_of(d, *id) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
let pl = fallback.ok_or_else(|| EngineError::Other("the object isn't on a perspective plane".into()))?;
|
||||
attach_in(d, &mut g, *id, pl, false, None)?;
|
||||
(pl, g.offset(pl))
|
||||
}
|
||||
};
|
||||
first.get_or_insert((plane, depth));
|
||||
let (h, depth) = step(&g, plane, depth)?;
|
||||
warp_checked(d, *id, &h)?;
|
||||
persp::set_attachment(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, plane, depth);
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok((targets, first))
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one
|
||||
/// of them is in perspective already, `still` holds for each one's plane and depth, and the document
|
||||
/// holds the grid already; None otherwise.
|
||||
fn unmoved(s: &Session, ids: &[NodeId], still: impl Fn(&PerspectiveGrid, Plane, f64) -> bool) -> Result<Option<Attached>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let g = grid_of(d);
|
||||
if ids.is_empty() || !grid_kept(d, &g) {
|
||||
return Ok(None);
|
||||
}
|
||||
let at: Option<Vec<Attached>> = ids.iter().map(|id| g.attachment_of(d, *id).filter(|(pl, depth)| still(&g, *pl, *depth))).collect();
|
||||
Ok(at.and_then(|at| at.first().copied()))
|
||||
}
|
||||
|
||||
/// Remember `again` (`perspective.transform` params) for Object › Transform › Transform Again, once
|
||||
/// the drag that made it is committed.
|
||||
fn record_again(s: &mut Session, again: Value) -> Result<()> {
|
||||
let st = s.doc_mut()?;
|
||||
match &mut st.interaction {
|
||||
Some(it) => it.perspective_again = Some(again),
|
||||
None => st.last_perspective = Some(again),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
|
||||
}
|
||||
|
||||
/// A plane-space affine map as `perspective.transform`'s `matrix` param.
|
||||
fn matrix_json(m: Affine) -> Value {
|
||||
json!(m.as_coeffs())
|
||||
}
|
||||
|
||||
pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.move";
|
||||
let ids = roots(s, p)?;
|
||||
let from = point_param(p, "from").ok_or_else(|| bad(C, "missing from"))?;
|
||||
let to = point_param(p, "to").ok_or_else(|| bad(C, "missing to"))?;
|
||||
if ![from.x, from.y, to.x, to.y].iter().all(|v| v.is_finite()) {
|
||||
return Err(bad(C, "from and to must be finite"));
|
||||
}
|
||||
let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok();
|
||||
let (perp, copy) = (switch_or(p, "perpendicular", false, C)?, switch_or(p, "copy", false, C)?);
|
||||
// `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false.
|
||||
check_switches(p, &["snap"], C)?;
|
||||
// Snap to Grid: a correction for the objects on the first one's plane and depth.
|
||||
let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, to)) };
|
||||
let snapped = move |pl: Plane, depth: f64, dv: vectorcraft_geom::Vec2| {
|
||||
dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| f.2)
|
||||
};
|
||||
// In-plane: the plane-space offset under the pointer; perpendicular: the depth it reaches.
|
||||
let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> {
|
||||
if perp {
|
||||
let to_depth = g.depth_at(pl, depth, from, to).ok_or_else(beyond_horizon)?;
|
||||
Ok((g.transform_map(pl, depth, Affine::IDENTITY, to_depth - depth).ok_or_else(beyond_horizon)?, to_depth))
|
||||
} else {
|
||||
let dv = snapped(pl, depth, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?);
|
||||
Ok((g.transform_map(pl, depth, Affine::translate(dv), 0.0).ok_or_else(beyond_horizon)?, depth))
|
||||
}
|
||||
};
|
||||
let label = if copy { "Copy in Perspective" } else { "Move in Perspective" };
|
||||
// When no object moves more than 1e-9 pt along its plane's axes or its normal (Snap to Grid
|
||||
// included) and there is no copy, the document and its undo history stay as they are.
|
||||
let still = |g: &PerspectiveGrid, pl: Plane, depth: f64| {
|
||||
if perp {
|
||||
g.depth_at(pl, depth, from, to).is_some_and(|d| (d - depth).abs() <= 1e-9)
|
||||
} else {
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, depth, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9)
|
||||
}
|
||||
};
|
||||
let first_still = if copy { None } else { unmoved(s, &ids, still)? };
|
||||
let (targets, first) = match first_still {
|
||||
Some(at) => (ids, Some(at)),
|
||||
None => persp_edit(s, label, &ids, fallback, copy, &step)?,
|
||||
};
|
||||
// Transform Again repeats the first object's move, and the identity when no object moved.
|
||||
if let Some((pl, depth)) = first {
|
||||
let g = grid_of(&s.doc()?.doc);
|
||||
let again = match perp {
|
||||
_ if first_still.is_some() => Some(json!({"matrix": matrix_json(Affine::IDENTITY), "copy": copy})),
|
||||
true => g.depth_at(pl, depth, from, to).map(|d| json!({"matrix": matrix_json(Affine::IDENTITY), "depth": d - depth, "copy": copy})),
|
||||
false => {
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, depth, dv))), "copy": copy}))
|
||||
}
|
||||
};
|
||||
if let Some(a) = again {
|
||||
record_again(s, a)?;
|
||||
}
|
||||
}
|
||||
Ok(ids_json(&targets))
|
||||
}
|
||||
|
||||
pub(super) fn persp_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.transform";
|
||||
let m = matrix_param(p, "matrix").ok_or_else(|| bad(C, "missing matrix [a,b,c,d,e,f]"))?;
|
||||
let dz = number_or(p, "depth", 0.0, C)?;
|
||||
if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 || !dz.is_finite() {
|
||||
return Err(bad(C, "matrix must be finite and invertible, depth finite"));
|
||||
}
|
||||
let ids = roots(s, p)?;
|
||||
let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok();
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> {
|
||||
let to = depth + dz;
|
||||
if to.abs() > persp::MAX_DEPTH {
|
||||
return Err(EngineError::Other("the objects would leave the grid".into()));
|
||||
}
|
||||
Ok((g.transform_map(pl, depth, m, dz).ok_or_else(beyond_horizon)?, to))
|
||||
};
|
||||
// An identity without a copy moves no object that is in perspective already: then the document
|
||||
// and its undo history stay as they are, and Transform Again repeats the identity.
|
||||
let identity = !copy && m == Affine::IDENTITY && dz == 0.0;
|
||||
let targets = if identity && unmoved(s, &ids, |g, pl, depth| g.transform_map(pl, depth, m, dz).is_some())?.is_some() {
|
||||
ids
|
||||
} else {
|
||||
persp_edit(s, if copy { "Copy in Perspective" } else { "Transform in Perspective" }, &ids, fallback, copy, &step)?.0
|
||||
};
|
||||
record_again(s, json!({"matrix": matrix_json(m), "depth": dz, "copy": copy}))?;
|
||||
Ok(ids_json(&targets))
|
||||
}
|
||||
|
||||
/// Object › Transform › Transform Again after a perspective move or scale: the same plane-space
|
||||
/// transform on the selection.
|
||||
pub(crate) fn transform_again(s: &mut Session, again: &Value) -> Result<Value> {
|
||||
let mut p = again.clone();
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.remove("ids");
|
||||
}
|
||||
persp_transform(s, &p)
|
||||
}
|
||||
|
||||
pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.plane.move";
|
||||
check_numbers(p, &["offset", "by"], C)?;
|
||||
let old = grid_of(&s.doc()?.doc);
|
||||
let plane = plane_param(&old, p, C)?;
|
||||
let from = old.offset(plane);
|
||||
let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) {
|
||||
(Some(o), _) => o,
|
||||
(None, Some(b)) => from + b,
|
||||
(None, None) => return Err(bad(C, "give offset or by")),
|
||||
};
|
||||
let objects = str_param(p, "objects").unwrap_or("none");
|
||||
if !matches!(objects, "none" | "move" | "copy") {
|
||||
return Err(bad(C, "objects must be none, move or copy"));
|
||||
}
|
||||
let mut g = old.clone();
|
||||
g.set_offset(plane, to);
|
||||
g.validate().map_err(|e| bad(C, e))?;
|
||||
let label = match objects {
|
||||
"copy" => "Move Plane and Copy Objects",
|
||||
"move" => "Move Plane and Objects",
|
||||
_ => "Move Plane",
|
||||
};
|
||||
// The objects on the plane where it was (not those moved off it along its normal).
|
||||
let on_plane = |d: &Document| -> Vec<NodeId> {
|
||||
let editable = d.editable();
|
||||
persp::attached_roots(d)
|
||||
.into_iter()
|
||||
.filter(|(id, pl, depth)| *pl == plane && (depth - from).abs() < 1e-6 && editable(*id))
|
||||
.map(|(id, ..)| id)
|
||||
.collect()
|
||||
};
|
||||
// A plane moved to where it is, with its objects or without them, moves nothing: when the
|
||||
// document holds the grid already, the document and its undo history stay as they are.
|
||||
if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) {
|
||||
let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] };
|
||||
return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
|
||||
}
|
||||
// In an interaction whose document is still its snapshot, the copies of the objects on the
|
||||
// plane are the copies the interaction keeps (`preview_copies`), unless the snapshot's grid
|
||||
// lists attachments of its own (`stores_attachments`).
|
||||
let kept = if objects == "copy" && s.in_interaction() && !stores_attachments(&s.doc()?.doc) {
|
||||
let on = on_plane(&s.doc()?.doc);
|
||||
crate::cmd::object::preview_copies(s, &on, false)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
old.adopt_stored_attachments(d);
|
||||
let mut ids = vec![];
|
||||
if objects != "none" {
|
||||
ids = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, not yet moved, and the
|
||||
// loop below moves only the copies.
|
||||
Some(k) => {
|
||||
*d = Document::clone(&k.doc);
|
||||
sel.clone_from(&k.selection);
|
||||
k.ids.clone()
|
||||
}
|
||||
None => {
|
||||
let on = on_plane(d);
|
||||
if objects == "copy" { duplicate_in(d, sel, &on, Affine::IDENTITY)? } else { on }
|
||||
}
|
||||
};
|
||||
let m = old.transform_map(plane, from, Affine::IDENTITY, to - from).ok_or_else(beyond_horizon)?;
|
||||
for id in &ids {
|
||||
warp_checked(d, *id, &m)?;
|
||||
persp::set_attachment(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, plane, to);
|
||||
}
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id = id_param(p, "id")
|
||||
.or_else(|| st.selection.objects.first().copied())
|
||||
.ok_or_else(|| EngineError::Other("select an object in perspective".into()))?;
|
||||
let mut g = grid_of(&st.doc);
|
||||
let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?;
|
||||
g.set_offset(plane, depth);
|
||||
g.plane = plane;
|
||||
g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?;
|
||||
// When the plane is at the object and active already, and the document holds that grid, the
|
||||
// document and its undo history stay as they are.
|
||||
if grid_kept(&st.doc, &g) {
|
||||
return Ok(json!({ "plane": plane.id(), "offset": depth }));
|
||||
}
|
||||
s.edit("Move Plane to Match Object", |d, _| {
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "plane": plane.id(), "offset": depth }))
|
||||
}
|
||||
|
||||
pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.nudge";
|
||||
let (dx, dy) = (number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?);
|
||||
if !(dx.is_finite() && dy.is_finite()) || (dx == 0.0 && dy == 0.0) {
|
||||
return Err(bad(C, "dx and dy give the arrow's direction"));
|
||||
}
|
||||
let k = s.prefs.keyboard_increment * if switch_or(p, "big", false, C)? { 10.0 } else { 1.0 };
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
let ids = selected_roots(s)?;
|
||||
// The step is measured on the page at the centre of the selection's perspective box.
|
||||
let st = s.doc()?;
|
||||
let g = grid_of(&st.doc);
|
||||
let (plane, depth, rect) = g.plane_bounds(&st.doc, &ids).ok_or_else(|| EngineError::Other("the selection isn't in perspective".into()))?;
|
||||
let from = g.homography_at(plane, depth).and_then(|h| h.apply(rect.center())).ok_or_else(beyond_horizon)?;
|
||||
let to = from + vectorcraft_geom::Vec2::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)) * k;
|
||||
persp_move(s, &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy}))
|
||||
}
|
||||
|
||||
pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "perspective.draw";
|
||||
let command = str_param(p, "command").filter(|c| c.starts_with("shape.")).ok_or_else(|| bad(C, "command must be a shape.* command"))?.to_string();
|
||||
let params = p.get("params").cloned().unwrap_or_else(|| json!({}));
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
let plane = plane_param(&g, p, C)?;
|
||||
let snap = switch_or(p, "snap", g.snap, C)?;
|
||||
// A click-to-size dialog's shape keeps its sizes in plane units from the click.
|
||||
let map = match p.get("at") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let at = finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?;
|
||||
Some(g.size_homography(plane, at, snap).ok_or_else(beyond_horizon)?)
|
||||
}
|
||||
};
|
||||
let undo_before = s.doc()?.history.undo.len();
|
||||
let r = s.execute(&command, ¶ms)?;
|
||||
let id = r.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| EngineError::Other(format!("{command} didn't create an object")))?;
|
||||
let res = s.edit("Draw in Perspective", |d, _| {
|
||||
attach_in(d, &mut g, id, plane, snap, map)?;
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
});
|
||||
// One undo step for the whole gesture.
|
||||
let st = s.doc_mut()?;
|
||||
if st.interaction.is_none() && st.history.undo.len() > undo_before + 1 {
|
||||
st.history.undo.truncate(undo_before + 1);
|
||||
if let Some(e) = st.history.undo.last_mut() {
|
||||
e.label = "Draw in Perspective".into();
|
||||
}
|
||||
st.history.recost_last(&st.doc);
|
||||
}
|
||||
res?;
|
||||
Ok(json!({ "id": id.0, "plane": plane.id() }))
|
||||
}
|
||||
|
||||
/// Shape tool previews become `perspective.draw` while the grid is shown with an active plane.
|
||||
pub(crate) fn perspective_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<(String, Value)> {
|
||||
const SHAPES: &[&str] = &[
|
||||
"shape.rectangle",
|
||||
"shape.ellipse",
|
||||
"shape.polygon",
|
||||
"shape.star",
|
||||
"shape.line",
|
||||
"shape.rectangularGrid",
|
||||
"shape.arc",
|
||||
"shape.flare",
|
||||
"shape.spiral",
|
||||
"shape.polarGrid",
|
||||
];
|
||||
if !SHAPES.contains(&cmd) {
|
||||
return None;
|
||||
}
|
||||
let g = PerspectiveGrid::current(&s.active()?.doc);
|
||||
(g.visible && g.plane != Plane::None).then(|| ("perspective.draw".to_string(), json!({"command": cmd, "params": params})))
|
||||
}
|
||||
|
||||
/// A click-to-size shape dialog's command (`cmd` with `params`, clicked at `at`) as it runs: on the
|
||||
/// active plane while the grid shows (`perspective.draw` keeping the sizes in plane units from the
|
||||
/// click), else `None` (run it as it is).
|
||||
pub fn perspective_click(s: &Session, cmd: &str, params: &Value, at: Point) -> Option<(String, Value)> {
|
||||
let (c, mut p) = perspective_rewrite(s, cmd, params)?;
|
||||
p["at"] = json!([at.x, at.y]);
|
||||
Some((c, p))
|
||||
}
|
||||
|
||||
/// Object › Perspective › Edit Text: type in perspective shown flat where it is drawn, in isolation
|
||||
/// mode, to be edited; exiting isolation projects it again ([`finish_edit_text`]).
|
||||
pub(super) fn edit_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id =
|
||||
id_param(p, "id").or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select type in perspective".into()))?;
|
||||
if !st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)) && n.projection().is_some()) {
|
||||
return Err(EngineError::Other("select type in perspective".into()));
|
||||
}
|
||||
s.edit("Edit Text", |d, _| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let h = n.projection().ok_or_else(|| EngineError::Other("select type in perspective".into()))?;
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("select type in perspective".into())) };
|
||||
// Shown flat where it is drawn: the type moves there and the projection moves the other
|
||||
// way, so the picture stays.
|
||||
let (Some(flat), Some(drawn)) = (t.bounds(), t.bounds().and_then(|b| h.map_rect_bbox(b))) else { return Ok(()) };
|
||||
let shift = vectorcraft_geom::Affine::translate(drawn.center() - flat.center());
|
||||
t.transform(shift);
|
||||
if let Some(rec) = n.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) {
|
||||
rec.projection = Some(h.then_after(&Homography::from_affine(shift.inverse())).to_array());
|
||||
rec.editing = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let st = s.doc_mut()?;
|
||||
st.isolation = Some(id);
|
||||
st.selection.set([id]);
|
||||
st.revision += 1;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// Edit Text ends (isolation mode on `id` exits): the type is projected again, in the document and
|
||||
/// in every undo state (the flat view is never an undo step of its own, and never saved: a saved
|
||||
/// state stays saved, [`crate::DocState::change_unsaved`]).
|
||||
pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) {
|
||||
let clear = |doc: &mut Arc<Document>| {
|
||||
// Undo steps keep no lookup cache: look without building one, and drop the one an edit
|
||||
// builds (the document now keeps its own).
|
||||
if doc.node_uncached(id).and_then(|n| n.extras().perspective.as_deref()).is_some_and(|p| p.editing)
|
||||
&& let Some(p) = Arc::make_mut(doc).node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.perspective.as_deref_mut()))
|
||||
{
|
||||
p.editing = false;
|
||||
}
|
||||
};
|
||||
st.change_unsaved(clear);
|
||||
for e in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) {
|
||||
let saved = Arc::ptr_eq(&e.doc, &st.saved_doc);
|
||||
clear(&mut e.doc);
|
||||
e.doc.drop_lookup_cache();
|
||||
if saved {
|
||||
st.saved_doc = e.doc.clone();
|
||||
}
|
||||
}
|
||||
if let Some(it) = &mut st.interaction {
|
||||
clear(&mut it.doc);
|
||||
}
|
||||
st.revision += 1;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind, RepeatKind, RepeatSpec};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_text::embed::Embedding;
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its licence lets it be embedded)}",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -35,10 +35,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Document Info's categories: (id, title), in the order the panel and the report show them.
|
||||
pub const CATEGORIES: [(&str, &str); 11] = [
|
||||
pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
("document", "Document"),
|
||||
("objects", "Objects"),
|
||||
("graphicStyles", "Graphic Styles"),
|
||||
("brushes", "Brushes"),
|
||||
("spotColors", "Spot Colors"),
|
||||
("patterns", "Pattern Objects"),
|
||||
("gradients", "Gradient Swatches"),
|
||||
@@ -47,6 +48,7 @@ pub const CATEGORIES: [(&str, &str); 11] = [
|
||||
("fontDetails", "Font Details"),
|
||||
("linkedImages", "Linked Images"),
|
||||
("embeddedImages", "Embedded Images"),
|
||||
("repeats", "Repeat Objects"),
|
||||
];
|
||||
|
||||
/// The object counts of `document.info` and their labels.
|
||||
@@ -96,9 +98,47 @@ pub fn embedding_label(fs_type: u16) -> &'static str {
|
||||
/// An image object as Document Info lists it: (name, width, height, linked file).
|
||||
type ImageRow = (String, u32, u32, Option<String>);
|
||||
|
||||
/// A Repeat object as Document Info lists it: its `repeatObjects` entry, and its row, which gives
|
||||
/// its name and then its kind with the number of instances it draws (for a grid, its rows and
|
||||
/// columns, followed by the number it draws when that is fewer).
|
||||
fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, String)) {
|
||||
let name = n.display_name();
|
||||
let count = |n: usize, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") };
|
||||
let instances = spec.instances(Some(d));
|
||||
let mut entry = json!({ "id": n.id.0, "name": name, "instances": instances });
|
||||
let kind = &spec.kind;
|
||||
let detail = match kind {
|
||||
RepeatKind::Radial { .. } => {
|
||||
entry["type"] = json!("radial");
|
||||
count(instances, "instance", "instances")
|
||||
}
|
||||
RepeatKind::Mirror { .. } => {
|
||||
entry["type"] = json!("mirror");
|
||||
count(instances, "instance", "instances")
|
||||
}
|
||||
RepeatKind::Grid { rows, cols, .. } => {
|
||||
// `repeat_transforms` clamps the rows and columns the same way.
|
||||
let (rows, cols) = ((*rows).clamp(1, 500), (*cols).clamp(1, 500));
|
||||
entry["type"] = json!("grid");
|
||||
entry["rows"] = json!(rows);
|
||||
entry["cols"] = json!(cols);
|
||||
let grid = format!("{} × {}", count(rows as usize, "row", "rows"), count(cols as usize, "column", "columns"));
|
||||
if instances < (rows * cols) as usize { format!("{grid}, {}", count(instances, "instance", "instances")) } else { grid }
|
||||
}
|
||||
};
|
||||
(entry, (name, format!("{}, {detail}", kind.label())))
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts `(family, style)`, image objects and used patterns.
|
||||
fn sections(d: &Document, info: &Value, fonts: &BTreeSet<super::fonts::UsedFont>, images: &[ImageRow], category: Option<&str>) -> Vec<Section> {
|
||||
/// `document.info` reports), its fonts, its image objects and the rows of its Repeat objects.
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
images: &[ImageRow],
|
||||
repeats: &[(String, String)],
|
||||
category: Option<&str>,
|
||||
) -> Vec<Section> {
|
||||
let names = |k: &str| -> Vec<(String, String)> {
|
||||
info[k].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), String::new())).collect()
|
||||
};
|
||||
@@ -138,6 +178,7 @@ fn sections(d: &Document, info: &Value, fonts: &BTreeSet<super::fonts::UsedFont>
|
||||
rows
|
||||
}
|
||||
"graphicStyles" => names("graphicStyleNames"),
|
||||
"brushes" => names("brushNames"),
|
||||
"spotColors" => names("spotColors"),
|
||||
"patterns" => names("patternNames"),
|
||||
"gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(),
|
||||
@@ -174,6 +215,7 @@ fn sections(d: &Document, info: &Value, fonts: &BTreeSet<super::fonts::UsedFont>
|
||||
"linkedImages" => {
|
||||
images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect()
|
||||
}
|
||||
"repeats" => repeats.to_vec(),
|
||||
_ => images.iter().filter(|i| i.3.is_none()).map(|(name, w, h, _)| (name.clone(), format!("{w} × {h} px"))).collect(),
|
||||
};
|
||||
Section { id, title, rows }
|
||||
@@ -246,6 +288,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut symbols = BTreeSet::new();
|
||||
let mut spot = BTreeSet::new();
|
||||
let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() };
|
||||
// `brushes` holds the Brushes panel's brushes, or with selectionOnly it holds the brushes that the selected objects' strokes use.
|
||||
let mut brushes: Vec<String> = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() };
|
||||
// `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order.
|
||||
let mut repeats: Vec<Value> = vec![];
|
||||
let mut repeat_rows: Vec<(String, String)> = vec![];
|
||||
for r in roots {
|
||||
r.walk(&mut |n| {
|
||||
let k = match &n.kind {
|
||||
@@ -319,6 +366,21 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
styles.push(&g.name);
|
||||
}
|
||||
if selection_only {
|
||||
for item in &n.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Stroke(st) = item
|
||||
&& let Some(b) = &st.brush
|
||||
&& !brushes.contains(b)
|
||||
{
|
||||
brushes.push(b.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Repeat(spec) = &n.kind {
|
||||
let (entry, row) = repeat_entry(d, n, spec);
|
||||
repeats.push(entry);
|
||||
repeat_rows.push(row);
|
||||
}
|
||||
});
|
||||
}
|
||||
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
|
||||
@@ -333,6 +395,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"swatches": d.swatches_iter().count(),
|
||||
"graphicStyles": d.graphic_styles.len(),
|
||||
"graphicStyleNames": styles,
|
||||
"brushNames": brushes,
|
||||
"repeatObjects": repeats,
|
||||
"characterStyles": d.char_styles.len(),
|
||||
"paragraphStyles": d.para_styles.len(),
|
||||
"patterns": d.patterns.len(),
|
||||
@@ -340,7 +404,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &image_rows, category);
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, category);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -372,8 +436,11 @@ fn snap_xf(b: Rect, half: bool) -> Affine {
|
||||
}
|
||||
|
||||
fn pixel_perfect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids: Vec<NodeId> =
|
||||
if p.get("ids").is_some() { super::edit::outermost(&s.doc()?.doc, targets(s, p)?) } else { super::edit::selected_roots(s)? };
|
||||
let ids: Vec<NodeId> = if p.get("ids").is_some() || p.get("id").is_some() {
|
||||
super::edit::outermost(&s.doc()?.doc, targets(s, p)?)
|
||||
} else {
|
||||
super::edit::selected_roots(s)?
|
||||
};
|
||||
let n = ids.len();
|
||||
s.edit("Make Pixel Perfect", |d, _| {
|
||||
for id in &ids {
|
||||
@@ -448,6 +515,109 @@ mod tests {
|
||||
assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
}
|
||||
|
||||
/// Document Info › Brushes lists the Brushes panel's brushes, and with Selection Only it lists
|
||||
/// the brushes the selected objects' strokes use, each once.
|
||||
#[test]
|
||||
fn info_lists_the_brushes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let panel: Vec<Value> =
|
||||
s.execute("brush.list", &json!({})).unwrap()["brushes"].as_array().unwrap().iter().map(|b| b["name"].clone()).collect();
|
||||
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
|
||||
assert_eq!(i["brushNames"], json!(panel));
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("brushes"), Some("Brushes")));
|
||||
let rows: Vec<Value> = panel.iter().map(|n| json!([n, ""])).collect();
|
||||
assert_eq!(i["sections"][0]["rows"], json!(rows));
|
||||
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
s.execute("brush.apply", &json!({"ids": [a], "name": "Charcoal"})).unwrap();
|
||||
s.execute("brush.apply", &json!({"ids": [b], "name": "Arrow"})).unwrap();
|
||||
s.execute("brush.apply", &json!({"ids": [c], "name": "Charcoal"})).unwrap();
|
||||
let names =
|
||||
|s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true, "category": "brushes"})).unwrap()["brushNames"].clone();
|
||||
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
|
||||
assert_eq!(names(&mut s), json!(["Charcoal", "Arrow"]));
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
assert_eq!(names(&mut s), json!(["Arrow"]));
|
||||
// A stroke without a brush lists none.
|
||||
let plain = s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [plain]})).unwrap();
|
||||
assert_eq!(names(&mut s), json!([]));
|
||||
let text = s.execute("document.info", &json!({"category": "brushes", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains(&format!("\nBRUSHES\n{}\n", panel[0].as_str().unwrap())), "{text}");
|
||||
assert!(text.contains("\nCharcoal\n") && text.contains("\nArrow\n") && !text.contains("OBJECTS"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number
|
||||
/// of instances it makes (for a grid, its rows and columns, followed by the number it draws when
|
||||
/// that is fewer), one in a group included. With Selection Only it lists the Repeat objects in
|
||||
/// the selection.
|
||||
#[test]
|
||||
fn info_lists_the_repeat_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let square =
|
||||
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let (a, b, c, d) = (square(&mut s, 0.0), square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0));
|
||||
let radial = s.execute("object.repeat.radial", &json!({"ids": [a], "instances": 6})).unwrap()["id"].clone();
|
||||
let grid = s.execute("object.repeat.grid", &json!({"ids": [b], "rows": 2, "cols": 1})).unwrap()["id"].clone();
|
||||
s.execute("layer.setProps", &json!({"id": grid, "name": "Tiles"})).unwrap();
|
||||
let mirror = s.execute("object.repeat.mirror", &json!({"ids": [c]})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [mirror, d]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
|
||||
let i = s.execute("document.info", &json!({"category": "repeats"})).unwrap();
|
||||
assert_eq!(
|
||||
i["repeatObjects"],
|
||||
json!([
|
||||
{"id": radial, "name": "<Radial Repeat>", "type": "radial", "instances": 6},
|
||||
{"id": grid, "name": "Tiles", "type": "grid", "rows": 2, "cols": 1, "instances": 2},
|
||||
{"id": mirror, "name": "<Mirror Repeat>", "type": "mirror", "instances": 2},
|
||||
])
|
||||
);
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("repeats"), Some("Repeat Objects")));
|
||||
assert_eq!(
|
||||
i["sections"][0]["rows"],
|
||||
json!([
|
||||
["<Radial Repeat>", "Radial Repeat, 6 instances"],
|
||||
["Tiles", "Grid Repeat, 2 rows × 1 column"],
|
||||
["<Mirror Repeat>", "Mirror Repeat, 2 instances"],
|
||||
])
|
||||
);
|
||||
let names = |s: &mut Session| -> Vec<Value> {
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "repeats"})).unwrap();
|
||||
i["repeatObjects"].as_array().unwrap().iter().map(|r| r["name"].clone()).collect()
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [grid, group]})).unwrap();
|
||||
assert_eq!(names(&mut s), ["Tiles", "<Mirror Repeat>"]);
|
||||
s.execute("select.set", &json!({"ids": [radial]})).unwrap();
|
||||
assert_eq!(names(&mut s), ["<Radial Repeat>"]);
|
||||
s.execute("select.set", &json!({"ids": [d]})).unwrap();
|
||||
assert!(names(&mut s).is_empty());
|
||||
let text = s.execute("document.info", &json!({"category": "repeats", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nREPEAT OBJECTS\n<Radial Repeat>: Radial Repeat, 6 instances\nTiles: Grid Repeat, 2 rows × 1 column\n"), "{text}");
|
||||
assert!(!text.contains("\nOBJECTS\n"), "{text}");
|
||||
// A radial of 1,000 copies of a 500 × 500 grid draws one copy within the instance budget,
|
||||
// and Document Info reports 1 instance.
|
||||
let e = square(&mut s, 350.0);
|
||||
let big = s.execute("object.repeat.grid", &json!({"ids": [e], "rows": 500, "cols": 500})).unwrap()["id"].clone();
|
||||
let outer = s.execute("object.repeat.radial", &json!({"ids": [big], "instances": 1000})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [outer]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "repeats"})).unwrap();
|
||||
assert_eq!((i["repeatObjects"][0]["id"].clone(), i["repeatObjects"][0]["instances"].clone()), (outer, json!(1)));
|
||||
assert_eq!((i["repeatObjects"][1]["id"].clone(), i["repeatObjects"][1]["instances"].clone()), (big, json!(250_000)));
|
||||
assert_eq!(i["sections"][0]["rows"][0], json!(["<Radial Repeat>", "Radial Repeat, 1 instance"]));
|
||||
// A 500 × 500 grid of a mirror draws 125,000 copies within the budget, and its row gives
|
||||
// that number after its rows and columns.
|
||||
let f = square(&mut s, 380.0);
|
||||
let pair = s.execute("object.repeat.mirror", &json!({"ids": [f]})).unwrap()["id"].clone();
|
||||
let tiles = s.execute("object.repeat.grid", &json!({"ids": [pair], "rows": 500, "cols": 500})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [tiles]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "repeats"})).unwrap();
|
||||
assert_eq!((i["repeatObjects"][0]["id"].clone(), i["repeatObjects"][0]["instances"].clone()), (tiles, json!(125_000)));
|
||||
assert_eq!(i["sections"][0]["rows"][0], json!(["<Grid Repeat>", "Grid Repeat, 500 rows × 500 columns, 125000 instances"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedding_permissions_read_from_fs_type() {
|
||||
assert_eq!(embedding_label(0), "embedding allowed");
|
||||
|
||||
@@ -83,13 +83,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Bristle Brush Strokes",
|
||||
["Select", "Object"],
|
||||
None,
|
||||
"{} objects whose brush name contains \"bristle\" → {count}",
|
||||
"{} objects whose topmost stroke has a bristle brush (type bristle in brush.list), whatever the brush is named → {count}",
|
||||
has_doc,
|
||||
|s, _| by_kind(s, |n| n
|
||||
.appearance
|
||||
.stroke()
|
||||
.and_then(|st| st.brush.as_deref())
|
||||
.is_some_and(|b| b.to_ascii_lowercase().contains("bristle")))
|
||||
|s, _| {
|
||||
let brushes = vectorcraft_brush::library(&s.doc()?.doc);
|
||||
by_kind(s, |n| {
|
||||
n.appearance
|
||||
.stroke()
|
||||
.and_then(|st| st.brush.as_deref())
|
||||
.and_then(|name| brushes.iter().find(|b| b.name == name))
|
||||
.is_some_and(|b| matches!(b.kind, vectorcraft_brush::BrushKind::Bristle(_)))
|
||||
})
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"select.save",
|
||||
@@ -264,11 +269,11 @@ fn candidates(s: &Session, f: impl Fn(&Node) -> bool) -> Result<Vec<NodeId>> {
|
||||
}
|
||||
|
||||
fn finish_same(s: &mut Session, cmd: &str, ids: Vec<NodeId>) -> Result<Value> {
|
||||
let n = ids.len();
|
||||
let from = s.doc()?.selection.objects.clone();
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
s.doc_mut()?.last_selection_cmd = Some((cmd.to_string(), json!({}), from));
|
||||
Ok(json!({ "count": n }))
|
||||
let st = s.doc_mut()?;
|
||||
st.last_selection_cmd = Some((cmd.to_string(), json!({}), from));
|
||||
Ok(json!({ "count": st.selection.objects.len() }))
|
||||
}
|
||||
|
||||
fn same(s: &mut Session, cmd: &str, eq: fn(&Node, &Node) -> bool) -> Result<Value> {
|
||||
@@ -305,11 +310,11 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool)
|
||||
finish_same(s, cmd, ids)
|
||||
}
|
||||
|
||||
fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> {
|
||||
fn by_kind(s: &mut Session, f: impl Fn(&Node) -> bool) -> Result<Value> {
|
||||
let ids = candidates(s, f)?;
|
||||
let n = ids.len();
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
Ok(json!({ "count": n }))
|
||||
// The objects selected, after Lock Guides has left out guide paths.
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
fn direction_handles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
@@ -538,10 +543,11 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = if ids.is_some() { checked_ids_param(s, p, "ids", C)? } else { vec![] };
|
||||
let d = &s.doc()?.doc;
|
||||
let mut paths = vec![];
|
||||
let editable = d.editable();
|
||||
for r in roots {
|
||||
if let Some(n) = d.node(r) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Path { guide: true, .. }) && d.is_editable(c.id) && !paths.contains(&c.id) {
|
||||
if matches!(c.kind, NodeKind::Path { guide: true, .. }) && editable(c.id) && !paths.contains(&c.id) {
|
||||
paths.push(c.id);
|
||||
}
|
||||
});
|
||||
@@ -557,7 +563,8 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
st.selection.guides.iter().copied().filter(|i| st.doc.guides.get(*i).is_some_and(|g| st.doc.guide_editable(g))).collect()
|
||||
};
|
||||
if sel.is_empty() && rulers.is_empty() { (vec![], all.into_iter().filter(|id| st.doc.is_editable(*id)).collect()) } else { (rulers, sel) }
|
||||
let editable = st.doc.editable();
|
||||
if sel.is_empty() && rulers.is_empty() { (vec![], all.into_iter().filter(|id| editable(*id)).collect()) } else { (rulers, sel) }
|
||||
};
|
||||
// Find each ruler guide's line and its parent: the guide's layer, else where new art goes.
|
||||
let st = s.doc()?;
|
||||
@@ -610,7 +617,7 @@ fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if v {
|
||||
let active = s.active;
|
||||
for (i, st) in s.docs.iter_mut().enumerate() {
|
||||
if Some(i) != active && crate::deselect_guides(&st.doc, &mut st.selection) {
|
||||
if Some(i) != active && crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection) {
|
||||
st.revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Setup",
|
||||
[],
|
||||
None,
|
||||
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedFonts?: bool, highlightSubstitutedGlyphs?: bool, gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
|
||||
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
|
||||
has_doc,
|
||||
setup
|
||||
)]
|
||||
@@ -31,7 +31,6 @@ pub(crate) fn setup_json(d: &Document) -> Value {
|
||||
"units": d.units.label(),
|
||||
"bleed": s.bleed,
|
||||
"outlineImages": s.outline_images,
|
||||
"highlightSubstitutedFonts": s.highlight_substituted_fonts,
|
||||
"highlightSubstitutedGlyphs": s.highlight_substituted_glyphs,
|
||||
"gridSize": s.grid_size.id(),
|
||||
"gridColors": s.grid_colors.map(|c| c.to_hex()),
|
||||
@@ -72,9 +71,19 @@ fn setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
apply(&mut new, &mut units, k, v, &s.prefs.flattener_presets)?;
|
||||
}
|
||||
// An older build's reply passed back still applies; the moved key only gets a warning.
|
||||
let reply = |d: &Document| {
|
||||
let mut r = setup_json(d);
|
||||
if o.contains_key("highlightSubstitutedFonts")
|
||||
&& let Some(m) = r.as_object_mut()
|
||||
{
|
||||
m.insert("warnings".into(), json!([MOVED_FONTS_HIGHLIGHT]));
|
||||
}
|
||||
r
|
||||
};
|
||||
let st = s.doc()?;
|
||||
if new == st.doc.setup && units == st.doc.units {
|
||||
return Ok(setup_json(&st.doc));
|
||||
return Ok(reply(&st.doc));
|
||||
}
|
||||
s.edit("Document Setup", |d, _| {
|
||||
let scripts_changed =
|
||||
@@ -86,9 +95,13 @@ fn setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(setup_json(&s.doc()?.doc))
|
||||
Ok(reply(&s.doc()?.doc))
|
||||
}
|
||||
|
||||
/// The warning for `highlightSubstitutedFonts`, which `document.setup` ignores.
|
||||
const MOVED_FONTS_HIGHLIGHT: &str =
|
||||
"highlightSubstitutedFonts is ignored: it is a preference (Preferences › Type), set with prefs.set {key: \"highlightSubstitutedFonts\", value}";
|
||||
|
||||
fn flag(k: &str, v: &Value) -> Result<bool> {
|
||||
v.as_bool().ok_or_else(|| bad(C, format!("{k} must be true or false")))
|
||||
}
|
||||
@@ -102,7 +115,10 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value
|
||||
"units" => *units = v.as_str().and_then(vectorcraft_doc::Unit::named).ok_or_else(|| bad(C, "unknown units"))?,
|
||||
"bleed" => s.bleed = bleed_param(v, s.bleed, C)?,
|
||||
"outlineImages" => s.outline_images = flag(k, v)?,
|
||||
"highlightSubstitutedFonts" => s.highlight_substituted_fonts = flag(k, v)?,
|
||||
// Preferences › Type holds it for every document: ignored, with a warning in the reply.
|
||||
"highlightSubstitutedFonts" => {
|
||||
flag(k, v)?;
|
||||
}
|
||||
"highlightSubstitutedGlyphs" => s.highlight_substituted_glyphs = flag(k, v)?,
|
||||
"gridSize" => s.grid_size = v.as_str().and_then(GridSize::parse).ok_or_else(|| bad(C, "gridSize must be small, medium or large"))?,
|
||||
"gridColors" => s.grid_colors = grid_colors(v)?,
|
||||
@@ -125,7 +141,7 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value
|
||||
"exportText" => s.export_text = v.as_str().and_then(ExportText::parse).ok_or_else(|| bad(C, "exportText must be editable or appearance"))?,
|
||||
"backgroundContents" => s.background = background_param(v, C)?,
|
||||
// Read-only values `document.setup` reports.
|
||||
"gridColorsName" => {}
|
||||
"gridColorsName" | "warnings" => {}
|
||||
_ => return Err(bad(C, format!("unknown setting `{k}`"))),
|
||||
}
|
||||
Ok(())
|
||||
|
||||
+10
-1387
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,269 @@
|
||||
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound};
|
||||
use super::*;
|
||||
|
||||
// ---------- Curvature ----------
|
||||
|
||||
pub(super) fn curvature(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.curvature";
|
||||
let arr = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(C, "missing points"))?;
|
||||
let pts: Vec<(Point, bool)> = arr.iter().map(|v| Ok((point_entry(v, C)?, switch_or(v, "corner", false, C)?))).collect::<Result<_>>()?;
|
||||
if pts.is_empty() {
|
||||
return Err(bad(C, "need at least one point"));
|
||||
}
|
||||
let sp = vectorcraft_tools::draw2::curvature_spline(&pts, switch_or(p, "closed", false, C)?);
|
||||
if let Some(id) = id_param(p, "id") {
|
||||
s.edit("Curvature", |d, sel| {
|
||||
*path_mut(d, id)? = PathData::single(sp);
|
||||
sel.set([id]);
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let ap = &mut look.appearance;
|
||||
if ap.stroke_paint().is_none() && ap.fill_paint().is_none() {
|
||||
ap.set_stroke(Paint::solid(Color::BLACK));
|
||||
}
|
||||
add_look(s, "Curvature", path_kind(PathData::single(sp)), look, None)
|
||||
}
|
||||
|
||||
/// An edit `path.curvatureEdit` makes.
|
||||
enum CurvatureOp {
|
||||
Move(usize, Point),
|
||||
Insert(usize, f64, Option<Point>),
|
||||
Extend(Point),
|
||||
Close,
|
||||
}
|
||||
|
||||
pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_tools::draw2::{EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move};
|
||||
const C: &str = "path.curvatureEdit";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
check_numbers(p, &["x", "y", "t"], C)?;
|
||||
let at = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) {
|
||||
(Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some(Point::new(x, y)),
|
||||
(None, None) => None,
|
||||
_ => return Err(bad(C, "x and y must be finite numbers")),
|
||||
};
|
||||
let to = || at.ok_or_else(|| bad(C, "missing x, y"));
|
||||
let start = match str_param(p, "end") {
|
||||
None | Some("end") => false,
|
||||
Some("start") => true,
|
||||
Some(e) => return Err(bad(C, format!("unknown end {e:?}"))),
|
||||
};
|
||||
let how = match str_param(p, "from") {
|
||||
None => EndCurve::Keep,
|
||||
Some(f) => EndCurve::parse(f).ok_or_else(|| bad(C, format!("unknown from {f:?}")))?,
|
||||
};
|
||||
let corner = switch_or(p, "corner", false, C)?;
|
||||
let op = match str_param(p, "op") {
|
||||
Some("move") => CurvatureOp::Move(usize_req(p, "anchor", C)?, to()?),
|
||||
Some("insert") => CurvatureOp::Insert(usize_req(p, "segment", C)?, f64_or(p, "t", 0.5), at),
|
||||
Some("extend") => CurvatureOp::Extend(to()?),
|
||||
Some("close") => CurvatureOp::Close,
|
||||
Some(o) => return Err(bad(C, format!("unknown op {o:?}"))),
|
||||
None => return Err(bad(C, "missing op")),
|
||||
};
|
||||
let anchor = s.edit("Curvature", |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 matches!(op, CurvatureOp::Extend(_) | CurvatureOp::Close) && sp.closed {
|
||||
return Err(EngineError::Other("path is already closed".into()));
|
||||
}
|
||||
let ai = match op {
|
||||
CurvatureOp::Move(ai, q) => curvature_move(sp, ai, q).then_some(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?,
|
||||
CurvatureOp::Insert(seg, t, q) => {
|
||||
let ai = curvature_insert(sp, seg, t).ok_or_else(|| EngineError::Other("no such segment".into()))?;
|
||||
if let Some(q) = q {
|
||||
curvature_move(sp, ai, q);
|
||||
}
|
||||
ai
|
||||
}
|
||||
CurvatureOp::Extend(q) => {
|
||||
curvature_extend(sp, start, q, how, corner);
|
||||
if start { 0 } else { sp.anchors.len() - 1 }
|
||||
}
|
||||
CurvatureOp::Close => {
|
||||
if sp.anchors.len() < 3 {
|
||||
return Err(EngineError::Other("closing needs three anchors".into()));
|
||||
}
|
||||
curvature_close(sp, start, how);
|
||||
if start { sp.anchors.len() - 1 } else { 0 }
|
||||
}
|
||||
};
|
||||
sel.set([id]);
|
||||
sel.anchors.insert(id, [(si, ai)].into());
|
||||
Ok(ai)
|
||||
})?;
|
||||
Ok(json!({ "anchor": anchor }))
|
||||
}
|
||||
|
||||
// ---------- anchor tools ----------
|
||||
|
||||
pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.removeAnchor";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let ai = usize_req(p, "anchor", C)?;
|
||||
let removed = s.edit("Delete Anchor Point", |d, sel| {
|
||||
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()));
|
||||
}
|
||||
let mut emptied = Beside::replacing(d, &[id]);
|
||||
let removed = remove_anchors_of(d, sel, &mut emptied, id, [(si, ai)])?;
|
||||
emptied.finish(d)?;
|
||||
Ok(removed)
|
||||
})?;
|
||||
Ok(json!({ "removedObject": removed }))
|
||||
}
|
||||
|
||||
pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let jobs: Vec<(NodeId, Vec<(usize, usize)>)> = st
|
||||
.selection
|
||||
.anchors
|
||||
.iter()
|
||||
.filter(|(id, set)| !set.is_empty() && st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))
|
||||
.map(|(id, set)| (*id, set.iter().copied().collect()))
|
||||
.collect();
|
||||
if jobs.is_empty() {
|
||||
return Err(bad("path.removeAnchors", "direct-select anchor points of a path"));
|
||||
}
|
||||
let removed = s.edit("Remove Anchor Points", |d, sel| {
|
||||
let mut removed = 0;
|
||||
let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, anchors) in jobs {
|
||||
let shape: Vec<(usize, bool)> =
|
||||
d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default();
|
||||
let next = following_anchors(&shape, &anchors);
|
||||
if remove_anchors_of(d, sel, &mut emptied, id, anchors)? {
|
||||
removed += 1;
|
||||
} else if !next.is_empty() {
|
||||
// The next anchor along is selected, so the next Remove Anchor Points goes on from
|
||||
// there without picking it first (#2241).
|
||||
sel.anchors.insert(id, next);
|
||||
}
|
||||
}
|
||||
emptied.finish(d)?;
|
||||
Ok(removed)
|
||||
})?;
|
||||
Ok(json!({ "removedObjects": removed }))
|
||||
}
|
||||
|
||||
/// Where the selection goes once Remove Anchor Points takes `removed` (subpath, anchor) out of a
|
||||
/// path whose subpaths have `shape` (anchor count, closed): in each subpath, the anchor after its
|
||||
/// last removed one, round the end of a closed subpath, or the one before it at an open subpath's
|
||||
/// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors.
|
||||
fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
let mut next = BTreeSet::new();
|
||||
let mut kept = 0;
|
||||
for (si, &(n, closed)) in shape.iter().enumerate() {
|
||||
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
|
||||
if n - gone.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
if let Some(&last) = gone.last() {
|
||||
let wrap = if closed { 0..last } else { 0..0 };
|
||||
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
|
||||
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
|
||||
next.insert((kept, a - gone.range(..a).count()));
|
||||
}
|
||||
}
|
||||
kept += 1;
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
/// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round
|
||||
/// each one. A subpath left with one anchor is removed, and a path left with no subpath is removed
|
||||
/// through `emptied`. True when the path went.
|
||||
fn remove_anchors_of(
|
||||
d: &mut Document,
|
||||
sel: &mut Selection,
|
||||
emptied: &mut Beside,
|
||||
id: NodeId,
|
||||
anchors: impl IntoIterator<Item = (usize, usize)>,
|
||||
) -> Result<bool> {
|
||||
let mut anchors: Vec<(usize, usize)> = anchors.into_iter().collect();
|
||||
// The last first, so the indexes still to come stay valid.
|
||||
anchors.sort_unstable_by(|a, b| b.cmp(a));
|
||||
anchors.dedup();
|
||||
let path = path_mut(d, id)?;
|
||||
for (si, ai) in anchors {
|
||||
if let Some(sp) = path.subpaths.get_mut(si) {
|
||||
po::remove_anchor(sp, ai);
|
||||
}
|
||||
}
|
||||
path.subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
let gone = path.is_empty();
|
||||
if gone {
|
||||
emptied.put(d, id, vec![])?;
|
||||
sel.remove(id);
|
||||
} else {
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
}
|
||||
Ok(gone)
|
||||
}
|
||||
|
||||
pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.convertAnchor";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let ai = usize_req(p, "anchor", C)?;
|
||||
let smooth = str_param(p, "to") == Some("smooth");
|
||||
check_numbers(p, &["x", "y"], C)?;
|
||||
let target = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) {
|
||||
(Some(x), Some(y)) => Some(Point::new(x, y)),
|
||||
(None, None) => None,
|
||||
_ => return Err(bad(C, "x and y must be given together")),
|
||||
};
|
||||
if target.is_some_and(|q| !within_input_bound(q)) {
|
||||
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()));
|
||||
}
|
||||
// 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(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.reshapeSegment";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let seg = usize_req(p, "segment", C)?;
|
||||
let t = number_or(p, "t", 0.5, C)?.clamp(0.05, 0.95);
|
||||
let dv = Vec2::new(number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?);
|
||||
if !(dv.x.is_finite() && dv.y.is_finite() && dv.hypot() < MAX_INPUT) {
|
||||
return Err(bad(C, "invalid delta"));
|
||||
}
|
||||
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(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment};
|
||||
use super::cut::{erase_region, erase_segments, knife, split};
|
||||
use super::freehand::{blob, freehand};
|
||||
use super::smooth::{join_scrub, smooth_region};
|
||||
use super::*;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"path.freehand",
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic brushes with Pressure variation; a point without one presses fully), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
cmd!(
|
||||
"path.curvature",
|
||||
"Curvature",
|
||||
[],
|
||||
None,
|
||||
"{points: [{x, y, corner?}], closed?, id?} create (or with id: replace) a path curving through the points → {id}",
|
||||
has_doc,
|
||||
curvature
|
||||
),
|
||||
cmd!(
|
||||
"path.curvatureEdit",
|
||||
"Curvature",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, op: \"move\"|\"insert\"|\"extend\"|\"close\", anchor?, segment?, t?, end?: \"start\"|\"end\", from?: \"keep\"|\"smooth\"|\"corner\", corner?, x?, y?} edit a path as the Curvature tool does, its shape kept elsewhere; the anchor edited becomes the direct-selected one → {anchor}. move: anchor to x, y, re-curving only its two segments (a smooth anchor takes the Curvature tool's handles, along the circle through it and its neighbours); insert: a smooth anchor at t on segment, the shape unchanged (with x, y: then moved there); extend: an open subpath goes on from its end (default) or start to a new end at x, y, curving into it unless corner is true; close: an open subpath closes from that end. The old end bends into the new segment as from says: keep its curve (default), smooth through its neighbours, or a corner",
|
||||
has_doc,
|
||||
curvature_edit
|
||||
),
|
||||
cmd!(
|
||||
"path.removeAnchor",
|
||||
"Delete Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor} remove one anchor, re-fitting the curve",
|
||||
has_doc,
|
||||
remove_anchor
|
||||
),
|
||||
cmd!(
|
||||
"path.removeAnchors",
|
||||
"Remove Anchor Points",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path → {removedObjects}",
|
||||
has_anchors,
|
||||
remove_anchors
|
||||
),
|
||||
cmd!(
|
||||
"path.convertAnchor",
|
||||
"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)",
|
||||
has_doc,
|
||||
convert_anchor
|
||||
),
|
||||
cmd!(
|
||||
"path.reshapeSegment",
|
||||
"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",
|
||||
has_doc,
|
||||
reshape_segment
|
||||
),
|
||||
cmd!(
|
||||
"path.split",
|
||||
"Split Path",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two → {ids}",
|
||||
has_doc,
|
||||
split
|
||||
),
|
||||
cmd!(
|
||||
"path.knife",
|
||||
"Knife",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…]} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}",
|
||||
has_doc,
|
||||
knife
|
||||
),
|
||||
cmd!(
|
||||
"path.eraseRegion",
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], size?: pt (10), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
cmd!(
|
||||
"path.eraseSegments",
|
||||
"Path Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
|
||||
has_selection,
|
||||
erase_segments
|
||||
),
|
||||
cmd!(
|
||||
"path.smoothRegion",
|
||||
"Smooth",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5)} smooth selected paths near the drag → {ids, before, after}",
|
||||
has_selection,
|
||||
smooth_region
|
||||
),
|
||||
cmd!(
|
||||
"path.joinScrub",
|
||||
"Join",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over → {id}",
|
||||
has_doc,
|
||||
join_scrub
|
||||
),
|
||||
cmd!(
|
||||
"path.blob",
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], size?: pt (10), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with touching same-colour blobs → {id}",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
use super::*;
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
/// `[[x,y]…]` or `[{x,y}…]`.
|
||||
pub(super) fn points_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Point>> {
|
||||
Ok(samples_param(p, key, cmd)?.into_iter().map(|(pt, _)| pt).collect())
|
||||
}
|
||||
|
||||
/// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite
|
||||
/// number.
|
||||
pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
let xy = match v {
|
||||
Value::Array(xy) => xy.first().and_then(Value::as_f64).zip(xy.get(1).and_then(Value::as_f64)),
|
||||
Value::Object(_) => v.get("x").and_then(Value::as_f64).zip(v.get("y").and_then(Value::as_f64)),
|
||||
_ => None,
|
||||
};
|
||||
xy.filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)).ok_or_else(|| bad(cmd, "x and y must both be numbers"))
|
||||
}
|
||||
|
||||
/// [`points_param`] with each point's pen pressure, if it has one: `[[x,y,pressure]…]` or
|
||||
/// `[{x,y,pressure}…]` (0..1). A point whose x or y is not a number, or whose pressure is neither a
|
||||
/// number nor null, is an error.
|
||||
pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<(Point, Option<f64>)>> {
|
||||
let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?;
|
||||
let pts: Vec<(Point, Option<f64>)> = a
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let pressure = match v {
|
||||
Value::Array(xy) => xy.get(2),
|
||||
_ => v.get("pressure"),
|
||||
};
|
||||
match pressure {
|
||||
None | Some(Value::Null) | Some(Value::Number(_)) => Ok((point_entry(v, cmd)?, pressure.and_then(Value::as_f64))),
|
||||
Some(f) => Err(bad(cmd, format!("`pressure` must be a number, not {f}"))),
|
||||
}
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if pts.is_empty() {
|
||||
return Err(bad(cmd, "need at least one point"));
|
||||
}
|
||||
Ok(pts)
|
||||
}
|
||||
|
||||
/// The pen pressure along a freehand stroke (positions measured along its polyline), when any of
|
||||
/// its samples has one; samples without one count as full pressure, as a pen event without one.
|
||||
pub(super) fn stroke_pressure(samples: &[(Point, Option<f64>)]) -> Option<PressureProfile> {
|
||||
if samples.iter().all(|(_, p)| p.is_none()) {
|
||||
return None;
|
||||
}
|
||||
let mut at = 0.0;
|
||||
let mut prev: Option<Point> = None;
|
||||
let along: Vec<(f64, f64)> = samples
|
||||
.iter()
|
||||
.map(|(pt, p)| {
|
||||
at += prev.map_or(0.0, |q| q.distance(*pt));
|
||||
prev = Some(*pt);
|
||||
(at, p.unwrap_or(1.0))
|
||||
})
|
||||
.collect();
|
||||
PressureProfile::from_samples(along.into_iter().map(|(s, p)| (if at > 1e-9 { s / at } else { 0.0 }, p)))
|
||||
}
|
||||
|
||||
/// The length of a subpath.
|
||||
pub(super) fn subpath_len(sp: &SubPath) -> f64 {
|
||||
use kurbo::ParamCurveArclen;
|
||||
PathData::single(sp.clone()).to_bezpath().segments().map(|s| s.arclen(0.01)).sum()
|
||||
}
|
||||
|
||||
/// The bound, in points, on the length of a `path.reshapeSegment` delta and on the x and y of a
|
||||
/// point given to `path.convertAnchor` or `path.freehand`. The blend spine commands set the same
|
||||
/// bound (`object.blend.spine.reshapeSegment`, `object.blend.spine.moveAnchor`).
|
||||
pub(super) const MAX_INPUT: f64 = 1e9;
|
||||
|
||||
/// Whether `q` is finite and its x and y are each smaller than [`MAX_INPUT`] in size.
|
||||
pub(super) fn within_input_bound(q: Point) -> bool {
|
||||
q.x.is_finite() && q.y.is_finite() && q.x.abs() < MAX_INPUT && q.y.abs() < MAX_INPUT
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, read with [`index`].
|
||||
pub(super) fn usize_req(p: &Value, key: &str, cmd: &str) -> Result<usize> {
|
||||
p.get(key).and_then(Value::as_u64).map(index).ok_or_else(|| bad(cmd, format!("missing integer `{key}`")))
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, or `None` when `key` is absent or null. Any other
|
||||
/// value is [`usize_req`]'s error.
|
||||
pub(in super::super) fn usize_opt(p: &Value, key: &str, cmd: &str) -> Result<Option<usize>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(_) => usize_req(p, key, cmd).map(Some),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
match &mut n.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*live = None;
|
||||
Ok(path)
|
||||
}
|
||||
_ => Err(EngineError::Other(format!("object {id} is not a path"))),
|
||||
}
|
||||
}
|
||||
|
||||
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)),
|
||||
Some(_) => Err(EngineError::Other(format!("object {id} is not a path"))),
|
||||
None => Err(EngineError::NoNode(id)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn dist_to_polyline(pts: &[Point], q: Point) -> f64 {
|
||||
if pts.len() == 1 {
|
||||
return pts[0].distance(q);
|
||||
}
|
||||
pts.windows(2)
|
||||
.map(|w| {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
let ab = b - a;
|
||||
let l2 = ab.hypot2();
|
||||
let t = if l2 < 1e-18 { 0.0 } else { ((q - a).dot(ab) / l2).clamp(0.0, 1.0) };
|
||||
(a + ab * t).distance(q)
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
pub(super) fn poly_bounds(pts: &[Point], pad: f64) -> Rect {
|
||||
let r = pts.iter().fold(Rect::from_points(pts[0], pts[0]), |r, p| r.union_pt(*p));
|
||||
r.inflate(pad, pad)
|
||||
}
|
||||
|
||||
/// The filled area painted by a round brush of diameter `size` along `pts`.
|
||||
pub(super) fn brush_region(pts: &[Point], size: f64) -> PathData {
|
||||
let mut pts = pts.to_vec();
|
||||
if pts.len() == 1 {
|
||||
pts.push(pts[0] + Vec2::new(0.01, 0.0));
|
||||
}
|
||||
po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), size, Cap::Round, Join::Round, 4.0)
|
||||
}
|
||||
|
||||
/// Path leaves the area tools act on: under the selected objects, or every path when nothing is
|
||||
/// selected. Only editable, non-guide paths whose bounds meet `area`.
|
||||
pub(super) fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut push = |n: &Node| {
|
||||
if let NodeKind::Path { guide: false, path, .. } = &n.kind
|
||||
&& path.control_bounds().is_some_and(|b| b.inflate(0.5, 0.5).intersect(area).area() > 0.0 || b.width() == 0.0 || b.height() == 0.0)
|
||||
&& !out.contains(&n.id)
|
||||
{
|
||||
out.push(n.id);
|
||||
}
|
||||
};
|
||||
if sel.is_empty() {
|
||||
doc.walk(&mut push);
|
||||
} else {
|
||||
for id in &sel.objects {
|
||||
if let Some(n) = doc.node(*id) {
|
||||
n.walk(&mut |c: &Node| push(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
let editable = doc.editable();
|
||||
out.retain(|id| editable(*id));
|
||||
out
|
||||
}
|
||||
|
||||
/// The members of a compound path with geometry `pd`: one path per subpath, with fresh ids.
|
||||
fn compound_members(d: &mut Document, pd: PathData) -> Vec<Arc<Node>> {
|
||||
pd.subpaths.into_iter().map(|sp| Arc::new(Node::path(d.alloc_id(), PathData::single(sp), Appearance::default()))).collect()
|
||||
}
|
||||
|
||||
/// Give path or compound path `id` the geometry `pd` (dropping a live shape; a compound's members
|
||||
/// are rebuilt, one per subpath).
|
||||
pub(in super::super) fn set_geometry(d: &mut Document, id: NodeId, pd: PathData) -> Result<()> {
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Compound { .. })) {
|
||||
let members = compound_members(d, pd);
|
||||
if let Some(NodeKind::Compound { children, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
*children = members;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
*path_mut(d, id)? = pd;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A copy of path or compound path node `id` (fresh ids, no live shape) with geometry `pd`.
|
||||
pub(super) fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result<Node> {
|
||||
let mut n = d.node(id).ok_or(EngineError::NoNode(id))?.clone();
|
||||
n.id = d.alloc_id();
|
||||
match &mut n.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*path = pd;
|
||||
*live = None;
|
||||
}
|
||||
NodeKind::Compound { children, .. } => *children = compound_members(d, pd),
|
||||
_ => {}
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above
|
||||
/// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids.
|
||||
pub(in super::super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec<PathData>) -> Result<Vec<NodeId>> {
|
||||
let mut it = pieces.into_iter();
|
||||
let Some(first) = it.next() else {
|
||||
cut.put(d, id, vec![])?;
|
||||
return Ok(vec![]);
|
||||
};
|
||||
let mut ids = vec![id];
|
||||
let mut above = vec![];
|
||||
for pd in it {
|
||||
let n = sibling_with(d, id, pd)?;
|
||||
ids.push(n.id);
|
||||
above.push(n);
|
||||
}
|
||||
set_geometry(d, id, first)?;
|
||||
if !above.is_empty() {
|
||||
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
cut.put(d, id, [n].into_iter().chain(above).collect())?;
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub(in super::super) fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
|
||||
}
|
||||
|
||||
pub(super) fn stroke_paint(s: &Session) -> Paint {
|
||||
if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }
|
||||
}
|
||||
|
||||
pub(super) fn path_kind(path: PathData) -> NodeKind {
|
||||
NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
use super::common::{
|
||||
dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, replace_with_pieces, sibling_with, target_paths, usize_opt,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
/// Split a filled path into connected pieces (each outer contour with its holes).
|
||||
pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
|
||||
let subs: Vec<&SubPath> = pd.subpaths.iter().filter(|s| s.closed && s.anchors.len() >= 2).collect();
|
||||
if subs.len() <= 1 {
|
||||
return if pd.is_empty() { vec![] } else { vec![pd.clone()] };
|
||||
}
|
||||
let bps: Vec<BezPath> = subs
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let mut b = BezPath::new();
|
||||
s.to_bezpath_into(&mut b);
|
||||
b
|
||||
})
|
||||
.collect();
|
||||
let samples: Vec<Point> = subs.iter().map(|s| s.segment(0).eval(0.5)).collect();
|
||||
let n = subs.len();
|
||||
let inside = |j: usize, i: usize| fill_contains(&bps[j], FillRule::NonZero, samples[i]);
|
||||
let depth: Vec<usize> = (0..n).map(|i| (0..n).filter(|&j| j != i && inside(j, i)).count()).collect();
|
||||
let areas: Vec<f64> = subs.iter().map(|s| s.area().abs()).collect();
|
||||
let outers: Vec<usize> = (0..n).filter(|&i| depth[i].is_multiple_of(2)).collect();
|
||||
let mut groups: Vec<Vec<SubPath>> = outers.iter().map(|&o| vec![subs[o].clone()]).collect();
|
||||
for h in (0..n).filter(|&i| !depth[i].is_multiple_of(2)) {
|
||||
let best = outers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, o)| depth[**o] + 1 == depth[h] && inside(**o, h))
|
||||
.min_by(|a, b| areas[*a.1].total_cmp(&areas[*b.1]));
|
||||
if let Some((k, _)) = best {
|
||||
groups[k].push(subs[h].clone());
|
||||
}
|
||||
}
|
||||
groups.into_iter().map(PathData::new).collect()
|
||||
}
|
||||
|
||||
/// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment
|
||||
/// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least
|
||||
/// `step` long is found.
|
||||
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<SubPath>> {
|
||||
let nseg = sp.segment_count();
|
||||
if nseg == 0 {
|
||||
return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]);
|
||||
}
|
||||
const K: usize = 24;
|
||||
const MAX_SAMPLES: usize = 4096;
|
||||
let mut runs: Vec<Vec<(usize, f64, f64)>> = vec![];
|
||||
let mut cur: Vec<(usize, f64, f64)> = vec![];
|
||||
let mut any = false;
|
||||
for i in 0..nseg {
|
||||
let c = sp.segment(i);
|
||||
// The curve moves at most 3 times its longest control-polygon edge per unit of t, so with
|
||||
// n samples, neighboring samples are at most 3 · edge / n apart.
|
||||
let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot());
|
||||
let wanted = (3.0 * edge / step).ceil();
|
||||
let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K };
|
||||
let mut prev_t = 0.0;
|
||||
let mut prev_rm = remove(c.eval(0.0));
|
||||
let mut start = if prev_rm { None } else { Some(0.0) };
|
||||
if prev_rm {
|
||||
any = true;
|
||||
if !cur.is_empty() {
|
||||
runs.push(std::mem::take(&mut cur));
|
||||
}
|
||||
}
|
||||
for k in 1..=samples {
|
||||
let t = k as f64 / samples as f64;
|
||||
let rm = remove(c.eval(t));
|
||||
if rm != prev_rm {
|
||||
let (mut lo, mut hi) = (prev_t, t);
|
||||
for _ in 0..30 {
|
||||
let m = 0.5 * (lo + hi);
|
||||
if remove(c.eval(m)) == prev_rm { lo = m } else { hi = m }
|
||||
}
|
||||
let b = 0.5 * (lo + hi);
|
||||
if prev_rm {
|
||||
start = Some(b);
|
||||
} else {
|
||||
any = true;
|
||||
if let Some(s) = start.take() {
|
||||
cur.push((i, s, b));
|
||||
}
|
||||
runs.push(std::mem::take(&mut cur));
|
||||
}
|
||||
}
|
||||
prev_t = t;
|
||||
prev_rm = rm;
|
||||
}
|
||||
if let Some(s) = start {
|
||||
cur.push((i, s, 1.0));
|
||||
}
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
runs.push(cur);
|
||||
}
|
||||
runs.retain(|r| !r.is_empty());
|
||||
if !any {
|
||||
return None;
|
||||
}
|
||||
// A closed path's last and first runs meet at anchor 0.
|
||||
if sp.closed && runs.len() >= 2 {
|
||||
let first_starts = runs.first().and_then(|r| r.first()).is_some_and(|s| s.0 == 0 && s.1 == 0.0);
|
||||
let last_ends = runs.last().and_then(|r| r.last()).is_some_and(|s| s.0 + 1 == nseg && s.2 == 1.0);
|
||||
if first_starts && last_ends {
|
||||
let first = runs.remove(0);
|
||||
if let Some(last) = runs.last_mut() {
|
||||
last.extend(first);
|
||||
}
|
||||
}
|
||||
}
|
||||
let out = runs
|
||||
.iter()
|
||||
.filter(|r| r.len() > 1 || r[0].2 - r[0].1 > 1e-4)
|
||||
.map(|r| {
|
||||
let mut anchors: Vec<Anchor> = vec![];
|
||||
for &(i, t0, t1) in r {
|
||||
let c = sp.segment(i).subsegment(t0..t1);
|
||||
let (h1, h2) = if sp.segment_is_line(i) { (c.p0, c.p3) } else { (c.p1, c.p2) };
|
||||
match anchors.last_mut() {
|
||||
Some(a) => a.h_out = h1,
|
||||
None => anchors.push(Anchor { h_out: h1, ..Anchor::corner(c.p0) }),
|
||||
}
|
||||
anchors.push(Anchor { p: c.p3, h_in: h2, h_out: c.p3, kind: AnchorKind::Corner });
|
||||
}
|
||||
for a in &mut anchors {
|
||||
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
|
||||
}
|
||||
SubPath::new(anchors, false)
|
||||
})
|
||||
.filter(|s| s.anchors.len() >= 2)
|
||||
.collect();
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Erase from an outline path (open or closed) where `remove` holds, sampling each segment at least
|
||||
/// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output
|
||||
/// object (one object per piece when the path had a single subpath), or None if unchanged.
|
||||
pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<PathData>> {
|
||||
let mut changed = false;
|
||||
let mut subs = vec![];
|
||||
for sp in &pd.subpaths {
|
||||
match cut_subpath(sp, step, remove) {
|
||||
Some(pieces) => {
|
||||
changed = true;
|
||||
subs.extend(pieces);
|
||||
}
|
||||
None => subs.push(sp.clone()),
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
Some(if pd.subpaths.len() == 1 {
|
||||
subs.into_iter().map(PathData::single).collect()
|
||||
} else if subs.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
vec![PathData::new(subs)]
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- Scissors ----------
|
||||
|
||||
pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.split";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let anchor = usize_opt(p, "anchor", C)?;
|
||||
let seg = usize_opt(p, "segment", C)?;
|
||||
if anchor.is_none() && seg.is_none() {
|
||||
return Err(bad(C, "need `anchor` or `segment` + `t`"));
|
||||
}
|
||||
let t = f64_or(p, "t", 0.5);
|
||||
if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) {
|
||||
return Err(bad(C, "invalid t"));
|
||||
}
|
||||
let ids = s.edit("Split Path", |d, sel| {
|
||||
let path = path_mut(d, id)?;
|
||||
let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
let n = sp.anchors.len();
|
||||
let k = match (anchor, seg) {
|
||||
(Some(a), _) if a < n => a,
|
||||
(Some(_), _) => return Err(EngineError::Other("no such anchor".into())),
|
||||
(None, Some(g)) if g < sp.segment_count() => {
|
||||
if t <= 1e-6 {
|
||||
g
|
||||
} else if t >= 1.0 - 1e-6 {
|
||||
(g + 1) % n
|
||||
} else {
|
||||
sp.insert_anchor(g, t)
|
||||
}
|
||||
}
|
||||
_ => return Err(EngineError::Other("no such segment".into())),
|
||||
};
|
||||
let mut pieces = sp.cut_at(&std::collections::BTreeSet::from([k]));
|
||||
if sp.closed {
|
||||
path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
sel.set([id]);
|
||||
return Ok(vec![id]);
|
||||
}
|
||||
let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?;
|
||||
if path.subpaths.len() == 1 {
|
||||
path.subpaths[0] = left;
|
||||
let node = sibling_with(d, id, PathData::single(right))?;
|
||||
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
let nid = d.insert(parent, idx + 1, node)?;
|
||||
sel.set([id, nid]);
|
||||
Ok(vec![id, nid])
|
||||
} else {
|
||||
path.subpaths[si] = left;
|
||||
path.subpaths.insert(si + 1, right);
|
||||
sel.set([id]);
|
||||
Ok(vec![id])
|
||||
}
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
// ---------- Knife / Eraser ----------
|
||||
|
||||
/// Width of the slit the knife leaves between pieces.
|
||||
const KNIFE_GAP: f64 = 0.05;
|
||||
|
||||
pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.knife";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
if pts.len() < 2 {
|
||||
return Err(bad(C, "need at least two points"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0);
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, 1.0)) {
|
||||
let (pd, rule) = path_of(&st.doc, id)?;
|
||||
if !pd.is_closed() {
|
||||
continue;
|
||||
}
|
||||
let pieces = components(&po::boolean(&pd, rule, &strip, FillRule::NonZero, BoolOp::Difference));
|
||||
if pieces.len() >= 2 {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let ids = s.edit("Knife", |d, sel| {
|
||||
let mut all = vec![];
|
||||
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, pieces) in plan {
|
||||
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
|
||||
}
|
||||
cut.finish(d)?;
|
||||
sel.set(all.iter().copied());
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.eraseRegion";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis: an open path is sampled at least every half of it.
|
||||
let short = size * roundness.clamp(1.0, 100.0) / 100.0;
|
||||
let st = s.doc()?;
|
||||
let region = eraser_area(&pts, size, angle, roundness);
|
||||
// A point is under the tip when, with the tip squashed back into a circle, it is within the
|
||||
// circle's radius of the squashed drag.
|
||||
let squash = eraser_tip(angle, roundness).inverse();
|
||||
let round: Vec<Point> = pts.iter().map(|q| squash * *q).collect();
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, r)) {
|
||||
let (pd, rule) = path_of(&st.doc, id)?;
|
||||
if pd.is_closed() {
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference))));
|
||||
} else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| dist_to_polyline(&round, squash * q) <= r) {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>) -> Result<Value> {
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
let mut all = vec![];
|
||||
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, pieces) in plan {
|
||||
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
|
||||
}
|
||||
cut.finish(d)?;
|
||||
sel.set(all.iter().copied());
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.eraseSegments";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let w = number_or(p, "width", 8.0, C)?;
|
||||
if !(w.is_finite() && w > 0.0) {
|
||||
return Err(bad(C, "width must be positive"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let mut plan = vec![];
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) {
|
||||
let (pd, _) = path_of(&st.doc, id)?;
|
||||
if let Some(pieces) = erase_outline(&pd, w / 2.0, &|q| dist_to_polyline(&pts, q) <= w / 2.0) {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
apply_plan(s, "Path Eraser", plan)
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
use super::common::{
|
||||
brush_region, path_kind, path_mut, path_of, points_param, poly_bounds, samples_param, stroke_paint, stroke_pressure, subpath_len, target_paths,
|
||||
within_input_bound,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
// ---------- Pencil / Paintbrush ----------
|
||||
|
||||
/// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay
|
||||
/// corners) and simplify it to `tol`.
|
||||
fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
|
||||
let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIDELITY * 0.3);
|
||||
let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) };
|
||||
let mut kept: Vec<Point> = vec![p0];
|
||||
for &p in pts.iter().skip(1) {
|
||||
if kept.last().is_none_or(|k| k.distance(p) >= min) {
|
||||
kept.push(p);
|
||||
}
|
||||
}
|
||||
// The last sample always ends the stroke.
|
||||
if kept.len() > 1 {
|
||||
if let Some(k) = kept.last_mut() {
|
||||
*k = pn;
|
||||
}
|
||||
} else if pts.len() > 1 {
|
||||
kept.push(pn);
|
||||
}
|
||||
let n = kept.len();
|
||||
let marked: Vec<(Point, bool)> = (0..n)
|
||||
.map(|i| {
|
||||
let corner = if i == 0 || i + 1 == n {
|
||||
false
|
||||
} else {
|
||||
let (a, b) = (kept[i] - kept[i - 1], kept[i + 1] - kept[i]);
|
||||
a.dot(b) / (a.hypot() * b.hypot()).max(1e-12) < -0.2 // turn > ~100°
|
||||
};
|
||||
(kept[i], corner)
|
||||
})
|
||||
.collect();
|
||||
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, closed);
|
||||
if sp.anchors.len() < 3 {
|
||||
return sp;
|
||||
}
|
||||
let fitted = po::simplify_with(&PathData::single(sp.clone()), &SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false });
|
||||
fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp)
|
||||
}
|
||||
|
||||
/// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points
|
||||
/// joined by straight segments (`path.freehand` with `fit: false`).
|
||||
fn stroke_subpath(pts: &[Point], tol: Option<f64>, closed: bool) -> SubPath {
|
||||
match tol {
|
||||
Some(tol) => fit_freehand(pts, tol, closed),
|
||||
None => SubPath::new(pts.iter().map(|&p| Anchor::corner(p)).collect(), closed),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pencil's Edit Selected Paths in the middle of a path: a stroke from one point of a subpath of
|
||||
/// `pd` to another, each within `within` of it, replaces the section between them (the shorter
|
||||
/// way round a closed subpath) with the stroke fitted at `tol` (with no `tol`, unfitted). The
|
||||
/// subpath's index and its new shape; None when the stroke doesn't start and end on the same
|
||||
/// subpath, or meets it once.
|
||||
fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -> Option<(usize, SubPath)> {
|
||||
use kurbo::ParamCurveArclen;
|
||||
let (first, last) = (*pts.first()?, *pts.last()?);
|
||||
let (si, _, _, _, d_a) = pd.nearest(first)?;
|
||||
let (sj, _, _, _, d_b) = pd.nearest(last)?;
|
||||
if si != sj || d_a > within || d_b > within || pts.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut sp = pd.subpaths.get(si)?.clone();
|
||||
if sp.anchors.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
// The anchor nearest to `q`: the one there, else a new one, and whether it was added. Each
|
||||
// point is looked up on the subpath as it is by then: splitting a straight segment makes two
|
||||
// new ones, which a `t` along the old one doesn't measure.
|
||||
let place = |sp: &mut SubPath, q: Point| {
|
||||
let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?;
|
||||
let n = sp.anchors.len();
|
||||
Some(if t <= 1e-6 {
|
||||
(seg % n, false)
|
||||
} else if t >= 1.0 - 1e-6 {
|
||||
((seg + 1) % n, false)
|
||||
} else {
|
||||
(sp.insert_anchor(seg, t), true)
|
||||
})
|
||||
};
|
||||
let (mut from, _) = place(&mut sp, first)?;
|
||||
let (to, added) = place(&mut sp, last)?;
|
||||
if added && to <= from {
|
||||
from += 1;
|
||||
}
|
||||
if from == to {
|
||||
return None;
|
||||
}
|
||||
let n = sp.anchors.len();
|
||||
// The length of the run of segments from anchor i forward to anchor j.
|
||||
let run = |i: usize, j: usize| (0..(j + n - i) % n).map(|k| sp.segment((i + k) % n).arclen(0.01)).sum::<f64>();
|
||||
// The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from
|
||||
// `end` round to `start`, then the stroke's inner anchors follow.
|
||||
let (start, end, reversed) = if sp.closed {
|
||||
if run(from, to) <= run(to, from) { (from, to, false) } else { (to, from, true) }
|
||||
} else if from < to {
|
||||
(from, to, false)
|
||||
} else {
|
||||
(to, from, true)
|
||||
};
|
||||
let mut stroke = pts.to_vec();
|
||||
if reversed {
|
||||
stroke.reverse();
|
||||
}
|
||||
let (Some(s0), Some(s1)) = (stroke.first_mut(), sp.anchors.get(start)) else { return None };
|
||||
*s0 = s1.p;
|
||||
let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None };
|
||||
*e0 = e1.p;
|
||||
let fit = stroke_subpath(&stroke, tol, false).anchors;
|
||||
let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None };
|
||||
let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default();
|
||||
let (before, after): (Vec<Anchor>, Vec<Anchor>) = if sp.closed {
|
||||
((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![])
|
||||
} else {
|
||||
(sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec())
|
||||
};
|
||||
let mut anchors = before;
|
||||
if let Some(a) = anchors.last_mut() {
|
||||
*a = Anchor::with_handles(a.p, a.h_in, f0.h_out);
|
||||
}
|
||||
anchors.extend_from_slice(inner);
|
||||
let at_end = anchors.len();
|
||||
anchors.extend(after);
|
||||
// The anchor the stroke ends on: the first after it, or round to the first of a closed one.
|
||||
let end_at = if sp.closed { 0 } else { at_end };
|
||||
if let Some(a) = anchors.get_mut(end_at) {
|
||||
*a = Anchor::with_handles(a.p, f1.h_in, a.h_out);
|
||||
}
|
||||
Some((si, SubPath::new(anchors, sp.closed)))
|
||||
}
|
||||
|
||||
pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.freehand";
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
if samples.iter().any(|(q, _)| !within_input_bound(*q)) {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
let pressure = stroke_pressure(&samples);
|
||||
let mut pts: Vec<Point> = samples.into_iter().map(|(pt, _)| pt).collect();
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0);
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let brush = str_param(p, "style") == Some("brush");
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let id = id_param(ext, "id").ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
let mut sp = pd.subpaths[si].clone();
|
||||
let old_len = subpath_len(&sp);
|
||||
if at_start {
|
||||
sp.reverse();
|
||||
}
|
||||
let (Some(first), Some(end)) = (sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)) else {
|
||||
return Err(bad(C, "path has no open end"));
|
||||
};
|
||||
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
|
||||
*p0 = end;
|
||||
if pts.len() < 2 {
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
// A stroke that ends on an open end of another path connects the two: (that path, its last
|
||||
// open subpath, that subpath starting at the end the stroke ends on, it ends at its end).
|
||||
let connect = match p.get("connect").filter(|v| !v.is_null()) {
|
||||
Some(cn) => {
|
||||
let other = id_param(cn, "id").ok_or_else(|| bad(C, "connect needs id"))?;
|
||||
if other == id {
|
||||
return Err(bad(C, "connect needs a path other than the one extended"));
|
||||
}
|
||||
let (opd, _) = path_of(&s.doc()?.doc, other)?;
|
||||
let osi =
|
||||
opd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "connect path has no open end"))?;
|
||||
let mut y = opd.subpaths[osi].clone();
|
||||
let at_end = match str_param(cn, "end") {
|
||||
Some("start") => false,
|
||||
Some("end") => true,
|
||||
_ => return Err(bad(C, "connect end must be \"start\" or \"end\"")),
|
||||
};
|
||||
if at_end {
|
||||
y.reverse();
|
||||
}
|
||||
Some((other, osi, y, at_end))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let close_tol = (tol * 4.0).max(6.0);
|
||||
let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol);
|
||||
if closing && let Some(l) = pts.last_mut() {
|
||||
*l = first;
|
||||
}
|
||||
if let Some((_, _, y, _)) = &connect
|
||||
&& let (Some(l), Some(y0)) = (pts.last_mut(), y.anchors.first())
|
||||
{
|
||||
*l = y0.p;
|
||||
}
|
||||
let fit = stroke_subpath(&pts, fit_tol, false);
|
||||
let mut add = fit.anchors;
|
||||
if let (Some(last), Some(a0)) = (sp.anchors.last_mut(), add.first()) {
|
||||
last.h_out = a0.h_out;
|
||||
}
|
||||
if !add.is_empty() {
|
||||
add.remove(0);
|
||||
}
|
||||
sp.anchors.extend(add);
|
||||
if closing
|
||||
&& sp.anchors.len() > 2
|
||||
&& let Some(l) = sp.anchors.pop()
|
||||
&& let Some(a0) = sp.anchors.first_mut()
|
||||
{
|
||||
a0.h_in = l.h_in;
|
||||
sp.closed = true;
|
||||
}
|
||||
for a in &mut sp.anchors {
|
||||
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
|
||||
}
|
||||
let drawn_len = subpath_len(&sp);
|
||||
// The other path's anchors follow on from the one the stroke ends on, which takes its
|
||||
// outgoing handle.
|
||||
let mut other_len = 0.0;
|
||||
if let Some((_, _, y, _)) = &connect
|
||||
&& let Some((y0, rest)) = y.anchors.split_first()
|
||||
{
|
||||
if let Some(last) = sp.anchors.last_mut() {
|
||||
*last = Anchor::with_handles(y0.p, last.h_in + (y0.p - last.p), y0.h_out);
|
||||
}
|
||||
sp.anchors.extend_from_slice(rest);
|
||||
other_len = subpath_len(y);
|
||||
}
|
||||
// The path's pressure (in the direction it is continued in) followed by the stroke's, and
|
||||
// by the pressure of the path it connects to.
|
||||
let pressure_of = |n: NodeId| s.doc().ok()?.doc.node(n).and_then(|n| n.appearance.stroke()).and_then(|st| st.pressure.clone());
|
||||
let old_pressure = pressure_of(id);
|
||||
let other_pressure = connect.as_ref().and_then(|(o, _, _, at_end)| pressure_of(*o).map(|p| if *at_end { p.reversed() } else { p }));
|
||||
let joined = (old_pressure.is_some() || pressure.is_some() || other_pressure.is_some()).then(|| {
|
||||
let old = old_pressure.map(|p| if at_start { p.reversed() } else { p });
|
||||
let drawn = PressureProfile::extended(old.as_ref(), old_len, pressure.as_ref(), drawn_len - old_len);
|
||||
if connect.is_some() { PressureProfile::extended(drawn.as_ref(), drawn_len, other_pressure.as_ref(), other_len) } else { drawn }
|
||||
});
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
let reverse = at_start && !sp.closed;
|
||||
if reverse {
|
||||
sp.reverse();
|
||||
}
|
||||
path_mut(d, id)?.subpaths[si] = sp;
|
||||
if let Some((other, osi, ..)) = &connect {
|
||||
let o = path_mut(d, *other)?;
|
||||
if *osi < o.subpaths.len() {
|
||||
o.subpaths.remove(*osi);
|
||||
}
|
||||
if o.is_empty() {
|
||||
d.remove(*other)?;
|
||||
sel.remove(*other);
|
||||
}
|
||||
// Direct-selected anchors and segments of the subpaths after the one removed move
|
||||
// down one; those of the one removed go, and a path left with no selected anchors
|
||||
// is no longer selected.
|
||||
let shift = |refs: &mut BTreeSet<(usize, usize)>| {
|
||||
*refs = refs.iter().filter(|r| r.0 != *osi).map(|&(sub, i)| if sub > *osi { (sub - 1, i) } else { (sub, i) }).collect();
|
||||
};
|
||||
if let Some(refs) = sel.anchors.get_mut(other) {
|
||||
shift(refs);
|
||||
}
|
||||
if let Some(refs) = sel.segments.get_mut(other) {
|
||||
shift(refs);
|
||||
}
|
||||
if sel.anchors.get(other).is_some_and(BTreeSet::is_empty) {
|
||||
sel.remove(*other);
|
||||
}
|
||||
}
|
||||
if let Some(joined) = joined
|
||||
&& let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut())
|
||||
{
|
||||
st.pressure = if reverse { joined.map(|p| p.reversed()) } else { joined };
|
||||
}
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
} else {
|
||||
sel.remove(id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
if let Some(rd) = p.get("redraw").filter(|v| !v.is_null()) {
|
||||
let id = id_param(rd, "id").ok_or_else(|| bad(C, "redraw needs id"))?;
|
||||
let within = number_or(rd, "within", 12.0, C)?;
|
||||
if !within.is_finite() || within < 0.0 {
|
||||
return Err(bad(C, "redraw within must be a finite distance of 0 or more"));
|
||||
}
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
// shortcut: a stroke pressure profile is left as it was, measured along the old path; fit
|
||||
// it to the new length if Calligraphic pressure strokes get redrawn.
|
||||
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
*path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp;
|
||||
// A member path of a compound path is redrawn in it: the compound path is what is
|
||||
// selected.
|
||||
let whole = d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id);
|
||||
if keep_selected {
|
||||
sel.set([whole]);
|
||||
} else {
|
||||
sel.remove(whole);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
}
|
||||
if pts.len() < 2 {
|
||||
return Err(bad(C, "need at least two points"));
|
||||
}
|
||||
let sp = stroke_subpath(&pts, fit_tol, closed);
|
||||
let fill = if filled { s.paint.fill.clone() } else { Paint::None };
|
||||
// A pencil path with a fill keeps a stroke of None (#1679); only one that would show nothing
|
||||
// gets black. A brush is its stroke.
|
||||
let stroke = if brush || fill.is_none() { stroke_paint(s) } else { s.paint.stroke.clone() };
|
||||
let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1));
|
||||
if let Some(st) = look.appearance.stroke_mut() {
|
||||
st.pressure = pressure;
|
||||
}
|
||||
insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)
|
||||
}
|
||||
|
||||
// ---------- Blob Brush ----------
|
||||
|
||||
pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.blob";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let region = brush_region(&pts, size);
|
||||
if region.is_empty() {
|
||||
return Err(EngineError::Other("empty brush stroke".into()));
|
||||
}
|
||||
let paint = if !s.paint.stroke.is_none() {
|
||||
s.paint.stroke.clone()
|
||||
} else if !s.paint.fill.is_none() {
|
||||
s.paint.fill.clone()
|
||||
} else {
|
||||
Paint::solid(Color::BLACK)
|
||||
};
|
||||
let keep_selected = switch_or(p, "keepSelected", false, C)?;
|
||||
let only_selection = switch_or(p, "mergeOnlySelection", false, C)?;
|
||||
let merge = switch_or(p, "merge", true, C)?;
|
||||
let st = s.doc()?;
|
||||
let mut merge_ids = vec![];
|
||||
if merge && !(only_selection && st.selection.is_empty()) {
|
||||
let all = Selection::default();
|
||||
let from = if only_selection { &st.selection } else { &all };
|
||||
for id in target_paths(&st.doc, from, poly_bounds(&pts, size)) {
|
||||
let Some(n) = st.doc.node(id) else { continue };
|
||||
if n.appearance.fill_paint() != paint || !n.appearance.stroke_paint().is_none() {
|
||||
continue;
|
||||
}
|
||||
let (pd, rule) = path_of(&st.doc, id)?;
|
||||
if pd.is_closed() && po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) > 1e-6 {
|
||||
merge_ids.push((id, pd, rule));
|
||||
}
|
||||
}
|
||||
}
|
||||
let ap = NewArt::plain(Appearance::basic(paint, Paint::None, 1.0));
|
||||
if merge_ids.is_empty() {
|
||||
return insert_look(s, "Blob Brush", path_kind(region), ap, None, keep_selected);
|
||||
}
|
||||
let mut inputs: Vec<(&PathData, FillRule)> = vec![(®ion, FillRule::NonZero)];
|
||||
inputs.extend(merge_ids.iter().map(|(_, pd, r)| (pd, *r)));
|
||||
let merged = po::try_unite_all(&inputs).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let Some(((keep, _, _), rest)) = merge_ids.split_last() else {
|
||||
return insert_look(s, "Blob Brush", path_kind(region), ap, None, keep_selected);
|
||||
};
|
||||
let keep = *keep;
|
||||
let others: Vec<NodeId> = rest.iter().map(|m| m.0).collect();
|
||||
s.edit("Blob Brush", |d, sel| {
|
||||
*path_mut(d, keep)? = merged;
|
||||
remove_each(d, &others)?;
|
||||
if keep_selected {
|
||||
sel.set([keep]);
|
||||
} else {
|
||||
sel.remove(keep);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "id": keep.0 }))
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, target_paths};
|
||||
use super::*;
|
||||
|
||||
// ---------- Smooth ----------
|
||||
|
||||
/// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
|
||||
fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
|
||||
let piece = PathData::single(SubPath::new(anchors.to_vec(), false));
|
||||
let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false });
|
||||
let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() };
|
||||
let (f, l) = (anchors[0], anchors[anchors.len() - 1]);
|
||||
let last = out.len() - 1;
|
||||
out[0].p = f.p;
|
||||
out[0].h_in = f.h_in;
|
||||
out[last].p = l.p;
|
||||
out[last].h_out = l.h_out;
|
||||
for a in &mut out {
|
||||
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option<SubPath> {
|
||||
let n = sp.anchors.len();
|
||||
let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect();
|
||||
if n < 3 || !marked.iter().any(|m| *m) {
|
||||
return None;
|
||||
}
|
||||
if sp.closed {
|
||||
let Some(k) = marked.iter().position(|m| !m) else {
|
||||
// Everything is in range: smooth the whole closed path.
|
||||
let f =
|
||||
po::simplify_with(&PathData::single(sp.clone()), &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false });
|
||||
return f.subpaths.into_iter().next();
|
||||
};
|
||||
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
|
||||
let mut open = sp.clone();
|
||||
open.anchors.rotate_left(k);
|
||||
let mut m = marked.clone();
|
||||
m.rotate_left(k);
|
||||
open.anchors.push(open.anchors[0]);
|
||||
m.push(false);
|
||||
open.closed = false;
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol);
|
||||
let l = res.pop()?;
|
||||
if let Some(r0) = res.first_mut() {
|
||||
r0.h_in = l.h_in;
|
||||
}
|
||||
return Some(SubPath::new(res, true));
|
||||
}
|
||||
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol), false))
|
||||
}
|
||||
|
||||
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
|
||||
/// enters the reach: the part outside, then the part in reach. `None` when no more than a sliver
|
||||
/// is outside.
|
||||
fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez, CubicBez)> {
|
||||
const STEPS: u32 = 32;
|
||||
let step = 1.0 / f64::from(STEPS);
|
||||
// Back from the end in reach to the first sample outside, then halving to the crossing.
|
||||
let outside = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t)))?;
|
||||
let (mut lo, mut hi) = (outside, outside + step);
|
||||
for _ in 0..20 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if near(c.eval(mid)) {
|
||||
hi = mid;
|
||||
} else {
|
||||
lo = mid;
|
||||
}
|
||||
}
|
||||
// A straight segment's parts stay straight, their handles on their ends.
|
||||
let straight = c.p1 == c.p0 && c.p2 == c.p3;
|
||||
let part = |range| {
|
||||
let s = c.subsegment(range);
|
||||
if straight { CubicBez::new(s.p0, s.p0, s.p3, s.p3) } else { s }
|
||||
};
|
||||
(hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0)))
|
||||
}
|
||||
|
||||
/// `anchors` with each run of `marked` ones refitted, together with the stretch of the segments
|
||||
/// leading into the run that is in the drag's reach (`near`): a short drag smooths what is under
|
||||
/// it, and the rest of a long segment next to it stays as it was (#1512).
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64) -> Vec<Anchor> {
|
||||
let n = anchors.len();
|
||||
let mut runs = vec![];
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
if marked[i] {
|
||||
let a = i;
|
||||
while i + 1 < n && marked[i + 1] {
|
||||
i += 1;
|
||||
}
|
||||
runs.push((a, i));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let mut out = anchors.to_vec();
|
||||
for (a, b) in runs.into_iter().rev() {
|
||||
let lo = a.saturating_sub(1);
|
||||
let hi = (b + 1).min(n - 1);
|
||||
if hi - lo < 2 {
|
||||
continue;
|
||||
}
|
||||
let mut piece = out[lo..=hi].to_vec();
|
||||
// The anchors outside the reach, kept with the part of their segment that is outside.
|
||||
let (mut head, mut tail) = (None, None);
|
||||
if hi > b
|
||||
&& let [.., inner, outer] = piece.as_mut_slice()
|
||||
&& let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_in, inner.h_out, inner.p), near)
|
||||
{
|
||||
inner.h_out = reach.p2;
|
||||
tail = Some(Anchor { h_in: far.p1, ..*outer });
|
||||
*outer = Anchor::with_handles(far.p3, reach.p1, far.p2);
|
||||
}
|
||||
if lo < a
|
||||
&& let [outer, inner, ..] = piece.as_mut_slice()
|
||||
&& let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_out, inner.h_in, inner.p), near)
|
||||
{
|
||||
inner.h_in = reach.p2;
|
||||
head = Some(Anchor { h_out: far.p1, ..*outer });
|
||||
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
|
||||
}
|
||||
let new = refit_run(&piece, tol);
|
||||
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.smoothRegion";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
|
||||
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_FIDELITY, 100.0);
|
||||
let st = s.doc()?;
|
||||
let near = |q: Point| dist_to_polyline(&pts, q) <= radius;
|
||||
let mut plan = vec![];
|
||||
let (mut before, mut after) = (0, 0);
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) {
|
||||
let (pd, _) = path_of(&st.doc, id)?;
|
||||
let mut changed = false;
|
||||
let subs: Vec<SubPath> = pd
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|sp| match smooth_subpath(sp, &near, tol) {
|
||||
Some(n) if n != *sp && n.anchors.len() >= 2 => {
|
||||
changed = true;
|
||||
n
|
||||
}
|
||||
_ => sp.clone(),
|
||||
})
|
||||
.collect();
|
||||
if changed {
|
||||
let np = PathData::new(subs);
|
||||
before += pd.anchor_count();
|
||||
after += np.anchor_count();
|
||||
plan.push((id, np));
|
||||
}
|
||||
}
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [], "before": 0, "after": 0 }));
|
||||
}
|
||||
let ids: Vec<NodeId> = plan.iter().map(|(id, _)| *id).collect();
|
||||
s.edit("Smooth", |d, _| {
|
||||
for (id, np) in plan {
|
||||
*path_mut(d, id)? = np;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let mut v = ids_json(&ids);
|
||||
v["before"] = json!(before);
|
||||
v["after"] = json!(after);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
// ---------- Join tool ----------
|
||||
|
||||
pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.joinScrub";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0);
|
||||
let st = s.doc()?;
|
||||
// Open endpoints near the scrub, ordered along it: (order, id, subpath, at_start).
|
||||
let poly = {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(pts[0]);
|
||||
for q in &pts[1..] {
|
||||
bp.line_to(*q);
|
||||
}
|
||||
bp
|
||||
};
|
||||
let order = |q: Point| -> f64 {
|
||||
poly.segments()
|
||||
.enumerate()
|
||||
.map(|(i, sg)| (i as f64 + sg.nearest(q, 1e-6).t, sg.nearest(q, 1e-6).distance_sq))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map_or(0.0, |x| x.0)
|
||||
};
|
||||
let (first_pt, last_pt) = (pts.first().copied(), pts.last().copied());
|
||||
let mut ends: Vec<(f64, NodeId, usize, bool, Point)> = vec![];
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)) {
|
||||
let (pd, _) = path_of(&st.doc, id)?;
|
||||
for (si, sp) in pd.subpaths.iter().enumerate() {
|
||||
if sp.closed || sp.anchors.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
for (start, a) in [(true, sp.anchors[0].p), (false, sp.anchors[sp.anchors.len() - 1].p)] {
|
||||
let on_scrub = dist_to_polyline(&pts, a) <= tol;
|
||||
let near_start = first_pt.is_some_and(|p| a.distance(p) <= tol);
|
||||
let near_end = last_pt.is_some_and(|p| a.distance(p) <= tol);
|
||||
if !on_scrub && !near_start && !near_end {
|
||||
continue;
|
||||
}
|
||||
let ord = if on_scrub {
|
||||
order(a)
|
||||
} else if near_start && (!near_end || first_pt.is_some_and(|p| a.distance(p) <= a.distance(last_pt.unwrap_or(p)))) {
|
||||
-1.0
|
||||
} else {
|
||||
1e30
|
||||
};
|
||||
ends.push((ord, id, si, start, a));
|
||||
}
|
||||
}
|
||||
}
|
||||
ends.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if ends.len() < 2 {
|
||||
return Ok(json!({ "id": null }));
|
||||
}
|
||||
let (_, ida, sa, starta, pa) = ends[0];
|
||||
let (_, idb, sb, startb, pb) = ends[1];
|
||||
let mid = pa.midpoint(pb);
|
||||
let merge = pa.distance(pb) <= tol;
|
||||
s.edit("Join", |d, sel| {
|
||||
if ida == idb && sa == sb {
|
||||
let path = path_mut(d, ida)?;
|
||||
let sp = &mut path.subpaths[sa];
|
||||
if merge
|
||||
&& sp.anchors.len() > 2
|
||||
&& let Some(l) = sp.anchors.pop()
|
||||
{
|
||||
let d0 = mid - sp.anchors[0].p;
|
||||
sp.anchors[0].translate(d0);
|
||||
sp.anchors[0].h_in = l.h_in + (mid - l.p);
|
||||
}
|
||||
sp.closed = true;
|
||||
sel.set([ida]);
|
||||
return Ok(());
|
||||
}
|
||||
let (pdb, _) = path_of(d, idb)?;
|
||||
let mut x = path_of(d, ida)?.0.subpaths[sa].clone();
|
||||
let mut y = pdb.subpaths[sb].clone();
|
||||
if starta {
|
||||
x.reverse();
|
||||
}
|
||||
if !startb {
|
||||
y.reverse();
|
||||
}
|
||||
if merge
|
||||
&& !y.anchors.is_empty()
|
||||
&& let Some(last) = x.anchors.last_mut()
|
||||
{
|
||||
let yf = y.anchors.remove(0);
|
||||
let lp = last.p;
|
||||
last.translate(mid - lp);
|
||||
last.h_out = yf.h_out + (mid - yf.p);
|
||||
*last = Anchor::with_handles(last.p, last.h_in, last.h_out);
|
||||
}
|
||||
x.anchors.extend(y.anchors);
|
||||
if ida == idb {
|
||||
let path = path_mut(d, ida)?;
|
||||
path.subpaths[sa] = x;
|
||||
path.subpaths.remove(sb);
|
||||
} else {
|
||||
path_mut(d, ida)?.subpaths[sa] = x;
|
||||
let pbm = path_mut(d, idb)?;
|
||||
pbm.subpaths.remove(sb);
|
||||
if pbm.is_empty() {
|
||||
d.remove(idb)?;
|
||||
}
|
||||
}
|
||||
sel.set([ida]);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "id": ida.0 }))
|
||||
}
|
||||
+219
-48
@@ -11,6 +11,7 @@ use super::clipboard::SwatchChoices;
|
||||
use super::*;
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
/// Register editing commands, including document-to-document artwork drops and their parameter contracts.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -24,9 +25,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, file_close),
|
||||
cmd!("document.activate", "Activate Document", [], None, "{index}", always, doc_activate),
|
||||
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
|
||||
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
|
||||
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
|
||||
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, limit?: max matches (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total}", has_doc, doc_find),
|
||||
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
|
||||
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model", has_doc, |s, _| Ok(serde_json::to_value(&*s.doc()?.doc).unwrap_or(Value::Null))),
|
||||
cmd!(
|
||||
"document.setUnits",
|
||||
@@ -73,15 +74,33 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
global_rulers
|
||||
),
|
||||
cmd!(
|
||||
"edit.dropSelection",
|
||||
"Drop Artwork",
|
||||
[],
|
||||
None,
|
||||
"{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y]} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step",
|
||||
has_doc,
|
||||
drop_selection
|
||||
),
|
||||
cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, undo),
|
||||
cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, redo),
|
||||
cmd!(
|
||||
"edit.clearHistory",
|
||||
"Clear History",
|
||||
[],
|
||||
None,
|
||||
"{} remove every undo and redo step of the active document (the History panel menu's Clear History): the document stays as it is, and clearing is not an undo step → {cleared: the number of steps removed}",
|
||||
can_clear_history,
|
||||
clear_history
|
||||
),
|
||||
cmd!(
|
||||
"edit.undoGroup.begin",
|
||||
"Begin Undo Group",
|
||||
[],
|
||||
None,
|
||||
"{label?: string} until edit.undoGroup.end, the edits made in the active document are one undo step, named `label` (else after its first edit): for automation, such as MCP command_batch with `atomic` (#1163)",
|
||||
has_doc,
|
||||
"{label?: string} until edit.undoGroup.end, the edits made in the document active at the begin, and in each document opened or created before then (also when no document is open; the edits of a command that opens a document and edits it stay that command's undo step), are one undo step in that document, named `label` (else after its first edit); in a document that was open before the begin and is switched to (document.activate), each edit stays its own undo step: for automation, such as MCP command_batch with `atomic` (#1163)",
|
||||
always,
|
||||
undo_group_begin
|
||||
),
|
||||
cmd!(
|
||||
@@ -90,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
[],
|
||||
None,
|
||||
"{cancel?: bool} close the undo group: its edits stay one undo step or, with `cancel`, are undone",
|
||||
has_doc,
|
||||
always,
|
||||
undo_group_end
|
||||
),
|
||||
cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{} (the Artboard tool chosen: artboard.cut)", has_selection_or_artboard_tool, cut),
|
||||
@@ -100,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{center?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers they came from (by name; made when missing). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
"{center?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers they came from (by name; made when missing). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Offset)
|
||||
),
|
||||
@@ -127,7 +146,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Place",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+V"),
|
||||
"{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste where the objects were copied (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::InPlace)
|
||||
),
|
||||
@@ -136,7 +155,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste on All Artboards",
|
||||
["Edit"],
|
||||
Some("Cmd+Alt+Shift+V"),
|
||||
"{swatchConflict?} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::AllArtboards)
|
||||
),
|
||||
@@ -162,7 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
fn file_close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?;
|
||||
let i = p.get("index").and_then(Value::as_u64).map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
|
||||
if !s.close_document(i) {
|
||||
return Err(bad("file.close", "no such document"));
|
||||
}
|
||||
@@ -170,7 +189,7 @@ fn file_close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.activate", "missing index"))? as usize;
|
||||
let i = p.get("index").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.activate", "missing index"))?;
|
||||
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
|
||||
}
|
||||
|
||||
@@ -224,19 +243,82 @@ fn opt_u64(p: &Value, cmd: &str, key: &str) -> Result<Option<u64>> {
|
||||
}
|
||||
|
||||
fn doc_find(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.find";
|
||||
// A filter of the wrong type is an error, not dropped: dropping it would widen the search.
|
||||
let needle = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(v)) => Ok(Some(v.to_lowercase()).filter(|v| !v.is_empty())),
|
||||
Some(_) => Err(bad("document.find", format!("`{key}` must be a string"))),
|
||||
Some(_) => Err(bad(C, format!("`{key}` must be a string"))),
|
||||
};
|
||||
let filter = inspect::FindFilter { name: needle("name")?, kind: needle("kind")?, text: needle("text")? };
|
||||
if filter.is_empty() {
|
||||
return Err(bad("document.find", "give at least one of `name`, `kind`, `text`"));
|
||||
let rect = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => match finite_numbers::<4>(v) {
|
||||
Some([x, y, w, h]) if w >= 0.0 && h >= 0.0 => Ok(Some(vectorcraft_geom::Rect::new(x, y, x + w, y + h))),
|
||||
_ => Err(bad(C, format!("`{key}` must be [x, y, width, height]: four finite numbers, width and height not negative"))),
|
||||
},
|
||||
};
|
||||
let bound = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_f64().filter(|n| n.is_finite() && *n >= 0.0).map(Some).ok_or_else(|| bad(C, format!("`{key}` must be a number not below 0"))),
|
||||
};
|
||||
let range = |name: &str| -> Result<inspect::FindRange> {
|
||||
let (min_key, max_key) = (format!("min{name}"), format!("max{name}"));
|
||||
let r = inspect::FindRange { min: bound(&min_key)?, max: bound(&max_key)? };
|
||||
if let (Some(min), Some(max)) = (r.min, r.max)
|
||||
&& min > max
|
||||
{
|
||||
return Err(bad(C, format!("`{min_key}` is greater than `{max_key}`")));
|
||||
}
|
||||
Ok(r)
|
||||
};
|
||||
let anchors = range("Anchors")?;
|
||||
if [anchors.min, anchors.max].iter().flatten().any(|n| n.fract() != 0.0) {
|
||||
return Err(bad(C, "`minAnchors` and `maxAnchors` must be whole numbers"));
|
||||
}
|
||||
let limit = opt_u64(p, "document.find", "limit")?.unwrap_or(100);
|
||||
let (matches, total) = inspect::find_nodes(&s.doc()?.doc, &filter, limit);
|
||||
Ok(json!({"matches": matches, "total": total}))
|
||||
let filter = inspect::FindFilter {
|
||||
name: needle("name")?,
|
||||
kind: needle("kind")?,
|
||||
text: needle("text")?,
|
||||
within: rect("within")?,
|
||||
intersects: rect("intersects")?,
|
||||
width: range("Width")?,
|
||||
height: range("Height")?,
|
||||
thickness: range("Thickness")?,
|
||||
area: range("Area")?,
|
||||
anchors,
|
||||
};
|
||||
if filter.is_empty() {
|
||||
return Err(bad(
|
||||
C,
|
||||
"give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors`",
|
||||
));
|
||||
}
|
||||
let select = match p.get("select") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(C, "`select` must be true or false"))?,
|
||||
};
|
||||
let limit = opt_u64(p, C, "limit")?.unwrap_or(100);
|
||||
let (matches, ids) = inspect::find_nodes(&s.doc()?.doc, &filter, limit);
|
||||
let mut reply = json!({"matches": matches, "total": ids.len()});
|
||||
if select {
|
||||
reply["selected"] = select_found(s, p, &ids)?["count"].clone();
|
||||
s.journal_query();
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
/// Select the objects among `ids` that Select All and the objects inside them take (none hidden or
|
||||
/// locked, nor inside a hidden or locked one), leaving out those inside another of them and the
|
||||
/// members of compound paths, unless a compound path is isolated. Select > Reselect repeats
|
||||
/// `document.find` with `p`.
|
||||
fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let compound = |n: &Node| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. });
|
||||
let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound)));
|
||||
let found: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
super::select::select_where(s, "document.find", p, |d, n| {
|
||||
found.contains(&n.id) && (members || !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
})
|
||||
}
|
||||
|
||||
/// Document Setup's units (also `document.setup {units}`).
|
||||
@@ -345,6 +427,7 @@ fn undo_group_begin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::String(l)) if !l.trim().is_empty() && l.chars().count() <= 200 => Some(l.trim().to_string()),
|
||||
Some(_) => return Err(bad(C, "`label` must be a non-empty name of at most 200 characters")),
|
||||
};
|
||||
s.explicit_undo_group = Some(label.clone());
|
||||
s.begin_named_undo_group(label);
|
||||
ok()
|
||||
}
|
||||
@@ -371,7 +454,7 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
|
||||
|
||||
fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
settle_interaction(s)?;
|
||||
let guides_locked = s.menu.guides_locked;
|
||||
let menu = s.menu.clone();
|
||||
let st = s.doc_mut()?;
|
||||
let e = st.history.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
|
||||
let label = e.label.clone();
|
||||
@@ -380,21 +463,24 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
st.history.redo.push(crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs));
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
st.history.redo.push(turned);
|
||||
st.history.trim();
|
||||
st.revision += 1;
|
||||
st.selection.prune(&st.doc);
|
||||
// Guides locked since the step was made stay deselected.
|
||||
if guides_locked {
|
||||
crate::deselect_guides(&st.doc, &mut st.selection);
|
||||
}
|
||||
// Guides locked and slices locked or hidden since the step was made stay deselected.
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
st.sync_new_art();
|
||||
super::maskedit::follow_history(st, editing);
|
||||
leave_isolation_if_gone(st);
|
||||
super::globaledit::follow_history(st);
|
||||
Ok(json!({ "undone": label }))
|
||||
}
|
||||
|
||||
fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
settle_interaction(s)?;
|
||||
let guides_locked = s.menu.guides_locked;
|
||||
let menu = s.menu.clone();
|
||||
let st = s.doc_mut()?;
|
||||
let e = st.history.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
|
||||
let label = e.label.clone();
|
||||
@@ -403,17 +489,42 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
st.history.undo.push(crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs));
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
st.history.undo.push(turned);
|
||||
st.history.trim();
|
||||
st.revision += 1;
|
||||
st.selection.prune(&st.doc);
|
||||
if guides_locked {
|
||||
crate::deselect_guides(&st.doc, &mut st.selection);
|
||||
}
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
st.sync_new_art();
|
||||
super::maskedit::follow_history(st, editing);
|
||||
leave_isolation_if_gone(st);
|
||||
super::globaledit::follow_history(st);
|
||||
Ok(json!({ "redone": label }))
|
||||
}
|
||||
|
||||
/// After undo or redo, isolation mode ends when the isolated object is no longer in the document,
|
||||
/// such as the clip group Draw Inside made around the isolated object (#3705), rather than naming
|
||||
/// an id a later object may take.
|
||||
fn leave_isolation_if_gone(st: &mut crate::DocState) {
|
||||
if st.isolation.is_some_and(|i| st.doc.node(i).is_none()) {
|
||||
st.isolation = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// History panel › Clear History: removes the steps after the current state and the steps before
|
||||
/// it, and leaves the document as it is. Typing or a drag still in progress is first kept as a
|
||||
/// step, as Undo keeps it, so it is removed with the others and its change stays in the document.
|
||||
fn clear_history(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
settle_interaction(s)?;
|
||||
let st = s.doc_mut()?;
|
||||
let cleared = st.history.undo.len() + st.history.redo.len();
|
||||
st.history.undo.clear();
|
||||
st.history.redo.clear();
|
||||
st.revision += 1;
|
||||
Ok(json!({ "cleared": cleared }))
|
||||
}
|
||||
|
||||
/// `selection` for an undo (redo) step, sharing that of `like`, the step beside it, when the same.
|
||||
fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate::HistoryEntry>) -> Arc<vectorcraft_doc::Selection> {
|
||||
match like {
|
||||
@@ -543,6 +654,40 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Document ids scope node ids: two tabs may contain objects with the same node id.
|
||||
fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "edit.dropSelection";
|
||||
let key = "sourceDocument";
|
||||
let uid = p[key].as_u64().ok_or_else(|| bad(CMD, format!("missing integer `{key}`")))?;
|
||||
let point = |key: &str| finite_numbers::<2>(&p[key]).ok_or_else(|| bad(CMD, format!("{key} must be [x, y] with finite coordinates")));
|
||||
let grab = point("grab")?;
|
||||
let at = point("at")?;
|
||||
let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(CMD, "that document is no longer open"))?;
|
||||
let key = "ids";
|
||||
let values = p[key].as_array().ok_or_else(|| bad(CMD, format!("{key} must be an array of non-negative integer object ids")))?;
|
||||
if values.is_empty() || values.len() > 10000 {
|
||||
return Err(bad(CMD, "ids must contain 1–10000 object ids"));
|
||||
}
|
||||
let ids = values
|
||||
.iter()
|
||||
.map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(CMD, format!("invalid object id {value}: expected a non-negative integer"))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
// Validate the entire batch in one walk; node ids are local to the source document.
|
||||
let paths = source.doc.index_paths(ids.iter().copied());
|
||||
if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
let clip = Clipboard::copy(source, &roots_of(&source.doc, ids));
|
||||
let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?;
|
||||
let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]);
|
||||
if !center.x.is_finite() || !center.y.is_finite() {
|
||||
return Err(bad(CMD, "result would exceed the canvas (coordinates out of range)"));
|
||||
}
|
||||
// A drop preserves the source colours even when the flyer has same-named swatches.
|
||||
let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?;
|
||||
paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, &clip, &choices)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PasteMode {
|
||||
Offset,
|
||||
@@ -552,9 +697,11 @@ enum PasteMode {
|
||||
AllArtboards,
|
||||
/// A graphic from the Libraries panel: centred where it is placed, as Paste centres.
|
||||
Library,
|
||||
Drag,
|
||||
}
|
||||
|
||||
impl PasteMode {
|
||||
/// Return the user-visible action label for this insertion mode.
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
PasteMode::Front => "Paste in Front",
|
||||
@@ -563,6 +710,7 @@ impl PasteMode {
|
||||
PasteMode::AllArtboards => "Paste on All Artboards",
|
||||
PasteMode::Offset => "Paste",
|
||||
PasteMode::Library => "Place from Library",
|
||||
PasteMode::Drag => "Drop Artwork",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -595,6 +743,7 @@ fn onto_artboard(doc: &Document, p: &Value, clip: &Clipboard) -> Affine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert clipboard resources atomically in the active editable context using the requested placement mode.
|
||||
fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, choices: &SwatchChoices) -> Result<Value> {
|
||||
let off = s.prefs.paste_offset;
|
||||
let st = s.doc()?;
|
||||
@@ -610,22 +759,34 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
.reduce(|a, b| a.union(b))
|
||||
.filter(|_| mode != PasteMode::AllArtboards)
|
||||
.map(|all| (&clip.artboards, if mode == PasteMode::Offset { super::panelcmds::beside_artboards(&st.doc, all) } else { Vec2::ZERO }));
|
||||
// Paste Remembers Layers (not while isolating a group: pastes stay in it); an artboard's art
|
||||
// always goes back into its layers.
|
||||
let remember = (st.doc.paste_remembers_layers || boards.is_some()) && parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
|
||||
// Drawing modes (#3705): Draw Inside puts what Paste, Paste in Place and Paste on All
|
||||
// Artboards bring inside the object it draws into; Draw Behind puts what Paste in Place and
|
||||
// Paste on All Artboards bring behind the selection, as Paste in Back does. Paste in Front and
|
||||
// Paste in Back keep their own places, and copied artboards' art goes back into its layers.
|
||||
let modal = boards.is_none() && matches!(mode, PasteMode::Offset | PasteMode::InPlace | PasteMode::AllArtboards);
|
||||
// (Only with objects to paste: an artboard copied without art makes no clip group.)
|
||||
let inside = s.draw_inside.filter(|t| modal && !clip.nodes.is_empty() && s.draw_mode == crate::DrawMode::Inside && st.doc.node(*t).is_some());
|
||||
let behind = modal && mode != PasteMode::Offset && s.draw_mode == crate::DrawMode::Behind;
|
||||
let (front, back) = (mode == PasteMode::Front, mode == PasteMode::Back || behind);
|
||||
// Paste Remembers Layers (not while isolating a group: pastes stay in it, nor in Draw
|
||||
// Inside); an artboard's art always goes back into its layers.
|
||||
// A drop goes into the current editable insertion context, not a same-named source layer.
|
||||
let remember = mode != PasteMode::Drag
|
||||
&& inside.is_none()
|
||||
&& (st.doc.paste_remembers_layers || boards.is_some())
|
||||
&& parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
|
||||
// Front/back: relative to the selection (top-most / bottom-most selected object); with
|
||||
// nothing selected, the top / bottom of the current layer.
|
||||
let anchor = match mode {
|
||||
PasteMode::Front | PasteMode::Back => {
|
||||
let order = st.selection.in_paint_order(&st.doc);
|
||||
let a = if mode == PasteMode::Front { order.last() } else { order.first() };
|
||||
a.and_then(|id| st.doc.position(*id))
|
||||
}
|
||||
_ => None,
|
||||
let anchor = if front || back {
|
||||
let order = st.selection.in_paint_order(&st.doc);
|
||||
let a = if front { order.last() } else { order.first() };
|
||||
a.and_then(|id| st.doc.position(*id))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let placements: Vec<Affine> = match (mode, boards) {
|
||||
(_, Some((_, dv))) => vec![Affine::translate(dv)],
|
||||
(PasteMode::Offset | PasteMode::Library, None) => vec![match point_param(p, "center") {
|
||||
(PasteMode::Offset | PasteMode::Library | PasteMode::Drag, None) => vec![match point_param(p, "center") {
|
||||
Some(c) => clip.bounds().map_or(Affine::IDENTITY, |b| Affine::translate(c - b.center())),
|
||||
None => Affine::translate((f64_or(p, "dx", off), f64_or(p, "dy", off))),
|
||||
}],
|
||||
@@ -636,8 +797,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
// In place, in front, in back: onto the active artboard when the UI names it.
|
||||
_ => vec![onto_artboard(&st.doc, p, clip)],
|
||||
};
|
||||
let (ids, imported, artboards) = s.edit(mode.label(), |d, sel| {
|
||||
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
|
||||
let imported = clip.import_into(d, choices, same_doc);
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
|
||||
let artboards: Vec<usize> = boards
|
||||
.into_iter()
|
||||
.flat_map(|(all, dv)| all.iter().map(move |a| (a, dv)))
|
||||
@@ -652,21 +815,25 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let mut c = d.reid(n);
|
||||
imported.apply(&mut c);
|
||||
if xf != Affine::IDENTITY {
|
||||
c.transform(xf, false);
|
||||
// A cross-document drag carries the graphic's appearance with it,
|
||||
// including the pattern phase, independently of transform-tool settings.
|
||||
c.transform(xf, vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() });
|
||||
}
|
||||
let layer = match clip.source_layers.get(k) {
|
||||
Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))),
|
||||
_ => None,
|
||||
};
|
||||
let (par, idx) = match (anchor, layer) {
|
||||
let (par, idx) = match (into, anchor, layer) {
|
||||
// Inside the object Draw Inside draws into, on top of what is in it already.
|
||||
(Some(group), ..) => (Some(group), usize::MAX),
|
||||
// Next to the anchor, unless the object goes back to another layer.
|
||||
(Some((par, i, _)), l) if l.is_none() || l == par => {
|
||||
(None, Some((par, i, _)), l) if l.is_none() || l == par => {
|
||||
let k = placed.get(&par).copied().unwrap_or(0);
|
||||
(par, if mode == PasteMode::Front { i + 1 + k } else { i + k })
|
||||
(par, if front { i + 1 + k } else { i + k })
|
||||
}
|
||||
(_, l) => {
|
||||
(None, _, l) => {
|
||||
let par = l.or(parent);
|
||||
(par, if mode == PasteMode::Back { placed.get(&par).copied().unwrap_or(0) } else { usize::MAX })
|
||||
(par, if back { placed.get(&par).copied().unwrap_or(0) } else { usize::MAX })
|
||||
}
|
||||
};
|
||||
*placed.entry(par).or_default() += 1;
|
||||
@@ -677,8 +844,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
// Pasted type arrives without the layout bounds cache: fill it so boxes and alignment are
|
||||
// right away (opening the file later would, but paste must not depend on a reopen).
|
||||
super::typecmd::refresh_bounds_of(d, &new_ids);
|
||||
Ok((new_ids, imported, artboards))
|
||||
Ok((new_ids, imported, artboards, into))
|
||||
})?;
|
||||
if let (Some(target), Some(group)) = (inside, into) {
|
||||
super::create::isolate_draw_inside_group(s, target, group)?;
|
||||
}
|
||||
// The Artboard tool selects the pasted artboards, the first one active.
|
||||
if !artboards.is_empty() && s.tool_id() == "artboard" {
|
||||
s.set_tool_option("selected", &json!(artboards));
|
||||
@@ -726,7 +896,7 @@ pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selectio
|
||||
/// document, each original and its copy before the copy goes in, and must leave the document's
|
||||
/// tree as it is. The copies take new ids in the order of `roots`. Roots listed twice, or inside
|
||||
/// another root, are copied one at a time: each copy is made from the document as the copies
|
||||
/// before it left it.
|
||||
/// before it left it. Copied type whose layout caches [`Document::reid`] dropped has them again.
|
||||
pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result<Vec<NodeId>> {
|
||||
let paths = d.index_paths(roots.iter().copied());
|
||||
let mut found: Vec<_> = roots.iter().filter_map(|id| paths.get(id)).collect();
|
||||
@@ -753,6 +923,7 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn
|
||||
}
|
||||
out
|
||||
};
|
||||
super::typecmd::refresh_bounds_of(d, &out);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
+257
-541
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_render::effects::{LIGHTING_PRESETS, matching_lighting_preset};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn setup(effect: &str, item: Value) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
|
||||
s.execute(
|
||||
"effect.apply",
|
||||
&json!({"effect":effect,"item":item,"params":{
|
||||
"rotationX":13,"rotationY":17,"rotationZ":9,"shade":false,"ambient":17,
|
||||
"lights":[{"color":"#ff8040"},{"color":"#4080ff","rotation":-35}]
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lighting_presets_preserve_source_and_view_and_round_trip_in_one_undo_step() {
|
||||
for effect in ["threeD.revolve", "threeD.extrude", "threeD.inflate", "threeD.rotate"] {
|
||||
for (i, preset) in LIGHTING_PRESETS.iter().enumerate() {
|
||||
let (mut s, id) = setup(effect, Value::Null);
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = s.doc().unwrap().history.undo.len();
|
||||
let p = json!({"index":0,"item":null,"preset":preset.id});
|
||||
s.check_params("effect.lightingPreset", &p).unwrap();
|
||||
s.execute("effect.lightingPreset", &p).unwrap();
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
let actual = &after.node(id).unwrap().appearance.effects[0].params;
|
||||
let mut expected = before.node(id).unwrap().appearance.effects[0].params.clone();
|
||||
expected.as_object_mut().unwrap().extend(preset.params().as_object().unwrap().clone());
|
||||
assert_eq!(*actual, expected);
|
||||
assert_eq!(matching_lighting_preset(actual), Some(i));
|
||||
assert_eq!(after.node(id).unwrap().path_data(), before.node(id).unwrap().path_data());
|
||||
assert_eq!(actual["rotationX"], 13);
|
||||
assert_eq!(actual["shade"], false);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
|
||||
let reopened = vectorcraft_format::load(&vectorcraft_format::save(&after, false)).unwrap();
|
||||
assert_eq!(reopened.node(id).unwrap().appearance.effects[0].params, *actual);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, after);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lighting_presets_target_fill_effects_and_reject_invalid_requests_atomically() {
|
||||
let (mut s, id) = setup("threeD.rotate", json!(0));
|
||||
for p in [
|
||||
json!({"index":0,"item":0,"preset":"unknown"}),
|
||||
json!({"index":0,"item":0,"preset":12}),
|
||||
json!({"index":1,"item":0,"preset":"right"}),
|
||||
json!({"index":0,"item":null,"preset":"right"}),
|
||||
json!({"index":0,"item":0,"preset":"right","params":{"ambient":200}}),
|
||||
] {
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = s.doc().unwrap().history.undo.len();
|
||||
assert!(s.execute("effect.lightingPreset", &p).is_err(), "{p}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), history);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
}
|
||||
s.execute("effect.lightingPreset", &json!({"ids":[id.0],"index":0,"item":0,"preset":"topLeft"})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(n.appearance.effects.is_empty());
|
||||
assert_eq!(n.appearance.effects_at(Some(0)).unwrap()[0].params["lightRotation"], 135.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lighting_presets_reject_a_mixed_selection_before_changing_any_effect() {
|
||||
let (mut s, first) = setup("threeD.rotate", Value::Null);
|
||||
let second = s.execute("shape.rectangle", &json!({"x":250,"y":100,"width":80,"height":80})).unwrap()["id"].clone();
|
||||
s.execute("effect.apply", &json!({"effect":"path.offsetPath","item":null})).unwrap();
|
||||
s.execute("select.set", &json!({"ids":[first.0,second]})).unwrap();
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = s.doc().unwrap().history.undo.len();
|
||||
assert!(s.execute("effect.lightingPreset", &json!({"index":0,"item":null,"preset":"right"})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), history);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use crate::{NodeId, Session};
|
||||
|
||||
fn session_with_rect() -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
|
||||
(s, NodeId(r["id"].as_u64().unwrap()))
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_commands_keep_profile_live_edit_options_expand_and_undo() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":300,"height":300})).unwrap();
|
||||
let r = s.execute("path.create", &json!({"d":"M 150 40 L 180 60 L 180 140 L 150 160"})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let source = node(&s, id).path_data().unwrap().clone();
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).unwrap();
|
||||
let before = effects_for_test(&s, id);
|
||||
assert_eq!(node(&s, id).path_data(), Some(&source));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(restored.node(id).unwrap().path_data(), Some(&source));
|
||||
assert_eq!(effects::revolve_art(restored.node(id).unwrap()).unwrap(), before);
|
||||
let pdf = s.execute("document.serialize", &json!({"format":"pdf"})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap();
|
||||
assert!(bytes.starts_with(b"%PDF"));
|
||||
assert!(s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).is_err());
|
||||
assert!(s.execute("effect.duplicate", &json!({"index":0,"ids":[id.0],"item":null})).is_err());
|
||||
s.execute("effect.setParams", &json!({"index":0,"params":{"angle":180,"offset":10},"ids":[id.0],"item":null})).unwrap();
|
||||
assert_ne!(effects_for_test(&s, id), before);
|
||||
assert!(s.execute("effect.setParams", &json!({"index":0,"params":{"edge":"invalid"},"ids":[id.0],"item":null})).is_err());
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Group { .. }));
|
||||
assert!(!effects::has_revolve(&node(&s, id)));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id).path_data(), Some(&source));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(effects_for_test(&s, id), before);
|
||||
}
|
||||
|
||||
/// Extrude & Bevel, Inflate and Rotate: applied by command, saved and reopened, edited,
|
||||
/// exported, expanded and undone; one 3D effect per object.
|
||||
#[test]
|
||||
fn solid_effects_apply_save_edit_export_expand_and_undo() {
|
||||
for effect in effects::SOLIDS {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let source = node(&s, id).path_data().unwrap().clone();
|
||||
s.execute("effect.apply", &json!({"effect": effect, "ids": [id.0], "item": null})).unwrap();
|
||||
let art = effects::solid_art(&node(&s, id)).unwrap();
|
||||
assert_eq!(node(&s, id).path_data(), Some(&source), "{effect}: the source stays editable");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(effects::solid_art(restored.node(id).unwrap()).unwrap(), art, "{effect}: reopens the same");
|
||||
// One 3D effect per object, whichever kind.
|
||||
for other in ["threeD.revolve", "threeD.extrude", "threeD.rotate"] {
|
||||
assert!(s.execute("effect.apply", &json!({"effect": other, "ids": [id.0], "item": null})).is_err(), "{effect} + {other}");
|
||||
}
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"rotationY": 50, "rotationX": 10}, "ids": [id.0], "item": null})).unwrap();
|
||||
assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "{effect}: options change the art");
|
||||
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"bevel": "nope"}, "ids": [id.0], "item": null})).is_err());
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
|
||||
assert!(svg.matches("<path").count() >= 2, "{effect}: exported as vector faces");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Group { .. }), "{effect}");
|
||||
assert!(!effects::has_solid(&node(&s, id)));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id).appearance.effects.len(), 0, "{effect}: back to the plain rectangle");
|
||||
}
|
||||
// Type has no outline to extrude.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 50, "y": 50, "text": "3D"})).unwrap();
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [t["id"]], "item": null})).unwrap_err();
|
||||
assert!(err.to_string().contains("requires a path"), "{err}");
|
||||
}
|
||||
|
||||
/// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is
|
||||
/// stored as the angle that shows the same view, and a later angle replaces an earlier strength.
|
||||
#[test]
|
||||
fn an_earlier_perspective_strength_is_set_as_its_angle() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"perspective": 60}})).unwrap();
|
||||
let params = |s: &Session| node(s, id).appearance.effects[0].params.clone();
|
||||
let angle_of = |pct: f64| effects::merged_params(effects::EXTRUDE, &json!({"perspective": pct}))["perspectiveAngle"].as_f64().unwrap();
|
||||
let angle = angle_of(60.0);
|
||||
assert!((angle - 30.12).abs() < 0.01, "{angle}");
|
||||
assert!(params(&s).get("perspective").is_none() && (params(&s)["perspectiveAngle"].as_f64().unwrap() - angle).abs() < 1e-12, "{}", params(&s));
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"perspective": 100}, "ids": [id.0], "item": null})).unwrap();
|
||||
assert!((params(&s)["perspectiveAngle"].as_f64().unwrap() - angle_of(100.0)).abs() < 1e-12);
|
||||
// A file of then: the strength stored; setting an angle replaces it.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params =
|
||||
json!({"depth": 50, "perspective": 60});
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"perspectiveAngle": 120}, "ids": [id.0], "item": null})).unwrap();
|
||||
assert_eq!(params(&s), json!({"depth": 50, "perspectiveAngle": 120}));
|
||||
}
|
||||
|
||||
/// Scripts from before Rotation and Height give the light by `lightAzimuth` and
|
||||
/// `lightElevation`: stored as the same light; a later Height keeps that light's Rotation.
|
||||
#[test]
|
||||
fn an_earlier_light_direction_is_set_as_rotation_and_height() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": effects::ROTATE, "ids": [id.0], "item": null, "params": {"lightAzimuth": 180, "lightElevation": 0}}))
|
||||
.unwrap();
|
||||
let params = |s: &Session| node(s, id).appearance.effects[0].params.clone();
|
||||
// Straight from behind the object, level with it.
|
||||
assert!(params(&s).get("lightAzimuth").is_none() && params(&s).get("lightElevation").is_none(), "{}", params(&s));
|
||||
assert_eq!((params(&s)["lightHeight"].as_f64().unwrap().round(), ¶ms(&s)["lightBehind"]), (90.0, &json!(true)));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params =
|
||||
json!({"lightAzimuth": 90, "lightElevation": 0});
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"lightHeight": 60}, "ids": [id.0], "item": null})).unwrap();
|
||||
assert_eq!(params(&s), json!({"lightRotation": 0.0, "lightHeight": 60, "lightBehind": false}));
|
||||
}
|
||||
|
||||
/// Scripts from before Scribble's separate variations give one `variation`, which is stored as the
|
||||
/// Path Overlap and Spacing variations. An angle is stored above -180° and up to 180°.
|
||||
#[test]
|
||||
fn scribble_stores_an_earlier_variation_as_two_and_its_angle_within_180() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let p = json!({"effect": "stylize.scribble", "ids": [id.0], "item": null, "params": {"angle": 270, "variation": 2}});
|
||||
s.execute("effect.apply", &p).unwrap();
|
||||
let params = |s: &Session| node(s, id).appearance.effects[0].params.clone();
|
||||
assert_eq!((params(&s)["angle"].as_f64(), params(&s).get("variation")), (Some(-90.0), None), "{}", params(&s));
|
||||
assert_eq!((¶ms(&s)["overlapVariation"], ¶ms(&s)["spacingVariation"]), (&json!(2), &json!(2)));
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"angle": -200}, "ids": [id.0], "item": null})).unwrap();
|
||||
assert_eq!(params(&s)["angle"].as_f64(), Some(160.0));
|
||||
// A file of then stores its variation; setting one of the two keeps it for the other.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params = json!({"variation": 3});
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"spacingVariation": 1}, "ids": [id.0], "item": null})).unwrap();
|
||||
assert_eq!(params(&s), json!({"overlapVariation": 3, "spacingVariation": 1}));
|
||||
}
|
||||
|
||||
fn effects_for_test(s: &Session, id: NodeId) -> vectorcraft_doc::Node {
|
||||
effects::revolve_art(&node(s, id)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_revolve_commands_validate_save_expand_and_undo() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":300,"height":300})).unwrap();
|
||||
let r = s.execute("path.create", &json!({"d":"M150 40 C190 60 190 140 150 160"})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null,"params":{"offset":20,"segments":16}})).unwrap();
|
||||
let initial = node(&s, id);
|
||||
let source = initial.path_data().unwrap().clone();
|
||||
assert!(!initial.appearance.effects[0].params.as_object().unwrap().contains_key("smoothShading"));
|
||||
assert!(initial.appearance.effects[0].params["cap"].as_bool().unwrap());
|
||||
let mut gradients = 0;
|
||||
effects_for_test(&s, id).walk(&mut |face| {
|
||||
gradients += face.appearance.items.iter().filter(|item| {
|
||||
matches!(item, vectorcraft_doc::AppearanceItem::Fill(fill) if matches!(fill.paint, vectorcraft_doc::color::Paint::Gradient(_)))
|
||||
}).count();
|
||||
});
|
||||
assert!(gradients > 0, "commands use smooth vector shading by default");
|
||||
s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"lightAzimuth":30}})).unwrap();
|
||||
let smooth = node(&s, id);
|
||||
assert_eq!(smooth.path_data(), Some(&source));
|
||||
assert_ne!(effects_for_test(&s, id), effects::revolve_art(&initial).unwrap());
|
||||
let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!(effects::revolve_art(restored.node(id).unwrap()), Some(effects_for_test(&s, id)));
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
assert!(!effects::has_revolve(&node(&s, id)));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id), smooth);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id), initial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_caps_save_export_expand_and_undo_without_changing_the_source() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":300,"height":300})).unwrap();
|
||||
let r = s.execute("path.create", &json!({"d":"M150 40 L150 160"})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let source = node(&s, id).path_data().unwrap().clone();
|
||||
s.execute(
|
||||
"effect.apply",
|
||||
&json!({"effect":"threeD.revolve","ids":[id.0],"item":null,
|
||||
"params":{"offset":30,"rotationX":-35,"segments":16,"expandVisibleOnly":false,"cap":false}}),
|
||||
)
|
||||
.unwrap();
|
||||
let uncapped = node(&s, id);
|
||||
assert_eq!(uncapped.appearance.effects[0].params["cap"], json!(false));
|
||||
let count = |n: &vectorcraft_doc::Node| n.children().unwrap()[0].children().unwrap().len();
|
||||
let open_count = count(&effects_for_test(&s, id));
|
||||
s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"cap":true}})).unwrap();
|
||||
let capped = node(&s, id);
|
||||
let art = effects_for_test(&s, id);
|
||||
assert_eq!(count(&art), open_count + 2, "each endpoint adds one continuous vector cap");
|
||||
assert_eq!(capped.path_data(), Some(&source));
|
||||
assert!(s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"cap":"yes"}})).is_err());
|
||||
assert_eq!(node(&s, id), capped, "a bad boolean does not mutate the document");
|
||||
let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!(restored.node(id).unwrap().appearance.effects[0].params["cap"], json!(true));
|
||||
assert_eq!(effects::revolve_art(restored.node(id).unwrap()), Some(art.clone()));
|
||||
let pdf = s.execute("document.serialize", &json!({"format":"pdf"})).unwrap();
|
||||
assert!(vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap().starts_with(b"%PDF"));
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
assert_eq!(count(&node(&s, id)), count(&art));
|
||||
assert!(!effects::has_revolve(&node(&s, id)));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id), capped);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id), uncapped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_visibility_parameter_saves_expands_and_undoes_without_other_appearance_changes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":300,"height":300})).unwrap();
|
||||
let r = s.execute("path.create", &json!({"d":"M 150 40 L 180 60 L 180 140 L 150 160"})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).unwrap();
|
||||
let live = node(&s, id);
|
||||
let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!(restored.node(id).unwrap().appearance.effects[0].params["expandVisibleOnly"], json!(true));
|
||||
let count = |n: &vectorcraft_doc::Node| n.children().unwrap()[0].children().unwrap().len();
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
let visible = count(&node(&s, id));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id), live);
|
||||
s.execute("effect.setParams", &json!({"index":0,"item":null,"ids":[id.0],"params":{"expandVisibleOnly":false}})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
assert!(count(&node(&s, id)) > visible);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id).appearance.effects[0].params["expandVisibleOnly"], json!(false));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id), live);
|
||||
// The shared command still expands ordinary multiple-fill artwork as before.
|
||||
let r = s.execute("shape.rectangle", &json!({"x":10,"y":10,"width":20,"height":20})).unwrap();
|
||||
let ordinary = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"effect":"distort.twist","ids":[ordinary.0],"params":{"angle":15}})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[ordinary.0]})).unwrap();
|
||||
assert!(node(&s, ordinary).appearance.effects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_uses_catalog_defaults_and_undoes() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let r = s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 3}})).unwrap();
|
||||
assert_eq!(r["index"], json!(0));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(n.appearance.effects.len(), 1);
|
||||
assert_eq!(n.appearance.effects[0].params["x"], json!(3));
|
||||
assert_eq!(n.appearance.effects[0].params["opacity"], json!(75.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, id).appearance.effects.is_empty());
|
||||
assert!(s.execute("effect.apply", &json!({"effect": "nope"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warp_options_style_change_preserves_slot_and_visibility() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
for effect in ["path.offsetPath", "warp.arc", "stylize.roundCorners"] {
|
||||
s.execute("effect.apply", &json!({"effect": effect, "item": 1})).unwrap();
|
||||
}
|
||||
s.execute("effect.setParams", &json!({"index": 1, "item": 1, "visible": false})).unwrap();
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let result = s.execute("effect.setParams", &json!({"index": 1, "item": 1, "warpStyle": "flag", "params": {"bend": 25.0}}));
|
||||
assert!(result.is_ok(), "an applied warp can change style in place: {result:?}");
|
||||
let old = before.node(id).unwrap().appearance.effects_at(Some(1)).unwrap();
|
||||
let n = node(&s, id);
|
||||
let new = n.appearance.effects_at(Some(1)).unwrap();
|
||||
assert_eq!(new.len(), 3);
|
||||
assert_eq!(new[0], old[0]);
|
||||
assert_eq!(new[2], old[2]);
|
||||
assert_eq!(new[1].id, "warp.flag");
|
||||
assert_eq!(new[1].params["bend"], 25.0);
|
||||
assert!(!new[1].visible);
|
||||
assert!(n.appearance.effects.is_empty());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warp_options_non_warp_target_rejection_is_atomic() {
|
||||
let (mut s, first) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": "warp.arc", "item": null})).unwrap();
|
||||
let second = s.execute("shape.rectangle", &json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].clone();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.twist", "item": null})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [first.0, second]})).unwrap();
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
assert!(s.execute("effect.setParams", &json!({"index": 0, "item": null, "warpStyle": "flag"})).is_err());
|
||||
let state = s.doc().unwrap();
|
||||
assert_eq!(state.doc, before);
|
||||
assert_eq!(state.selection, selection);
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
assert!(!state.is_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_remove_and_set_params() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.twist"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap();
|
||||
let l = s.execute("effect.list", &json!({})).unwrap();
|
||||
assert!(l["catalog"].as_array().unwrap().len() >= 34);
|
||||
assert_eq!(l["applied"][0]["effects"].as_array().unwrap().len(), 2);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"angle": 45}, "visible": false})).unwrap();
|
||||
let e = &node(&s, id).appearance.effects[0];
|
||||
assert_eq!(e.params["angle"], json!(45));
|
||||
assert!(!e.visible);
|
||||
s.execute("effect.remove", &json!({"index": 0})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert_eq!(n.appearance.effects.len(), 1);
|
||||
assert_eq!(n.appearance.effects[0].id, "stylize.outerGlow");
|
||||
assert!(s.execute("effect.remove", &json!({"index": 5})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_appearance_bakes_geometry() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": 10}})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
// One fill: the path itself, reshaped.
|
||||
let n = node(&s, id);
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 120.0).abs() < 0.1, "{b:?}");
|
||||
assert!(n.appearance.effects.is_empty());
|
||||
assert!(matches!(n.kind, NodeKind::Path { live: None, .. }));
|
||||
// Nothing left to expand.
|
||||
assert!(s.execute("effect.expandAppearance", &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_transform_copies_makes_compound() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 120, "copies": 1}})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert!(matches!(n.kind, NodeKind::Compound { .. }));
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!((b.x1 - 320.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathfinder_effect_on_loose_objects_groups_them_first() {
|
||||
let (mut s, a) = session_with_rect();
|
||||
let b = NodeId(s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let r = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
|
||||
assert_eq!(r["grouped"], true);
|
||||
let g = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let gn = node(&s, g);
|
||||
assert_eq!(gn.children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>(), [a, b], "stacking order kept");
|
||||
assert!(vectorcraft_render::effects::has_pathfinder(&gn));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [g]);
|
||||
// Live: one united shape, so expanding leaves a single path.
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, g).children().unwrap().len(), 1);
|
||||
// Grouping and applying are one undo step.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(g).is_none());
|
||||
assert!(d.node(a).is_some_and(|n| n.appearance.effects.is_empty()) && d.parent_of(a) == d.parent_of(b));
|
||||
// A selection holding a group applies to each object as before; so does a single object.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let r = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
|
||||
assert!(r.get("grouped").is_none());
|
||||
assert_eq!(node(&s, a).appearance.effects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathfinder_effect_on_a_group_with_type_cuts_the_glyphs_out() {
|
||||
let (mut s, a) = session_with_rect();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 110, "y": 180, "text": "H", "size": 100})).unwrap()["id"].as_u64().unwrap());
|
||||
let glyphs = effects::outline_text(&node(&s, t)).unwrap();
|
||||
let b = glyphs.geometric_bounds().unwrap();
|
||||
assert!(b.x0 > 105.0 && b.y0 > 105.0 && b.x1 < 195.0 && b.y1 < 195.0, "the type lies inside the square: {b:?}");
|
||||
let area = |n: &vectorcraft_doc::Node| effects::member_shapes(None, n).iter().map(|(p, r)| vectorcraft_pathops::area(p, *r)).sum::<f64>();
|
||||
let glyph_area = area(&glyphs);
|
||||
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "pathfinder.subtract"})).unwrap();
|
||||
// Live: the renderer leaves the glyph's place in the square empty.
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let img = vectorcraft_render::Renderer::new().render(&doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default());
|
||||
let empty = (105..195).flat_map(|y| (105..195).map(move |x| (x, y))).filter(|&(x, y)| img.pixel(x, y)[3] == 0).count();
|
||||
assert!(empty as f64 > glyph_area / 2.0, "{empty} empty pixels for a glyph area of {glyph_area}");
|
||||
// Expanded: the group holds the square minus the glyph.
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let left = area(&node(&s, g));
|
||||
assert!((left - (10_000.0 - glyph_area)).abs() < 0.5, "{left} left of the square for a glyph area of {glyph_area}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathfinder_effect_on_a_group_renders_live_and_expands() {
|
||||
let (mut s, a) = session_with_rect();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b["id"]]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "pathfinder.subtract"})).unwrap();
|
||||
// Live: the renderer shows only the back square minus the front one.
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let img = vectorcraft_render::Renderer::new().render(&doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default());
|
||||
assert!(img.pixel(125, 150)[3] > 0);
|
||||
assert_eq!(img.pixel(200, 150)[3], 0);
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert!(n.appearance.effects.is_empty());
|
||||
let ch = n.children().unwrap();
|
||||
assert_eq!(ch.len(), 1);
|
||||
assert!((ch[0].geometric_bounds().unwrap().width() - 50.0).abs() < 1e-6);
|
||||
}
|
||||
#[test]
|
||||
fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() {
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let (mut s, id) = session_with_rect();
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
s.edit("gradient", |d, _| {
|
||||
let n = d.node_mut(id).unwrap();
|
||||
n.appearance.set_fill(ramp);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"index":0,"params":{"moveH":150,"copies":2},"ids":[id.0],"item":null})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
let mut boxes = vec![];
|
||||
node(&s, id).walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) && matches!(n.appearance.fill_paint(), Paint::Gradient(_)) {
|
||||
boxes.push(n.geometric_bounds().unwrap().width());
|
||||
}
|
||||
});
|
||||
assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient");
|
||||
}
|
||||
@@ -5,14 +5,15 @@
|
||||
//! gradient becomes a mesh shaped like the object. A pattern fill becomes the tiles it paints inside a clip
|
||||
//! group shaped like the object. Create Gradient Mesh shares the sampling.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::cms::Model;
|
||||
use vectorcraft_color::freeform::spread_scale;
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer};
|
||||
use vectorcraft_doc::live::{GradientMesh, lerp_color};
|
||||
use vectorcraft_doc::live::GradientMesh;
|
||||
use vectorcraft_doc::pattern::{PatternDef, place_art};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling};
|
||||
use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, Vec2, shapes};
|
||||
@@ -290,7 +291,7 @@ fn expand_fills(d: &mut Document, l: &Node, to: GradientTo) -> Option<Node> {
|
||||
for item in &l.appearance.items {
|
||||
// Items that paint nothing go; a gradient that can't be expanded stays.
|
||||
let art = gradient_fill(item).and_then(|(f, g)| {
|
||||
let (fl, path, bounds) = fill_shape(l, f, &path, bounds)?;
|
||||
let (fl, path, bounds) = fill_shape(l, item, &path, bounds)?;
|
||||
gradient_art(d, &fl, &path, bounds, f, g, to)
|
||||
});
|
||||
let Some(art) = art else {
|
||||
@@ -318,7 +319,7 @@ fn expand_fills(d: &mut Document, l: &Node, to: GradientTo) -> Option<Node> {
|
||||
/// fill's opacity, blend mode and effects other than geometry effects ([`fill_effects`]).
|
||||
fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &FillLayer, g: &GradientPaint, to: GradientTo) -> Option<Node> {
|
||||
let content = if g.gradient.kind == GradientKind::Freeform {
|
||||
let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds))?;
|
||||
let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds, d.color_mode.model()))?;
|
||||
vec![Node::new(d.alloc_id(), NodeKind::Mesh(m))]
|
||||
} else {
|
||||
let frame = Frame::new(g, bounds);
|
||||
@@ -363,15 +364,16 @@ fn reshaped(l: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// Path `l` (outline `path`, box `bounds`) as fill `f` paints it on the canvas, with its outline
|
||||
/// and box: when the fill has visible geometry effects, `l` with the outline they make of `path`
|
||||
/// as a plain path, and that outline's box.
|
||||
fn fill_shape(l: &Node, f: &FillLayer, path: &PathData, bounds: Rect) -> Option<(Node, PathData, Rect)> {
|
||||
/// Path `l` (outline `path`, box `bounds`) as its fill `item` paints it on the canvas, with its
|
||||
/// outline and box: when the fill has visible geometry effects, `l` with the outline they make of
|
||||
/// `path` as a plain path, and that outline's box.
|
||||
fn fill_shape(l: &Node, item: &AppearanceItem, path: &PathData, bounds: Rect) -> Option<(Node, PathData, Rect)> {
|
||||
use vectorcraft_render::effects::{GeomContext, apply_geometry_with, has_geometry};
|
||||
if !has_geometry(&f.effects) {
|
||||
if !has_geometry(item.effects()) {
|
||||
return Some((l.clone(), path.clone(), bounds));
|
||||
}
|
||||
let outline = apply_geometry_with(&f.effects, path, bounds, &GeomContext::of(l));
|
||||
// In the fill's context, as drawing runs them: a plug-in effect is told which fill it is on.
|
||||
let outline = apply_geometry_with(item.effects(), path, bounds, &GeomContext::of(l).item(item));
|
||||
let b = outline.bounds()?;
|
||||
Some((with_path(l, outline.clone()), outline, b))
|
||||
}
|
||||
@@ -411,6 +413,45 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Expand the pattern fills under `root` that paint a transparent image into the tiles they paint
|
||||
/// ([`expand_patterns_where`]), so each tile image becomes an object of its own; the other
|
||||
/// pattern fills stay. A tile image counts as
|
||||
/// transparent when its key is in `see_through` (it has see-through pixels), or when it, a group
|
||||
/// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending
|
||||
/// mode. Returns how many shapes changed.
|
||||
pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, see_through: &BTreeSet<String>) -> Result<usize> {
|
||||
let (_, n) = replace_leaves(d, root, |d, l| {
|
||||
// Most leaves have no pattern fill: skip the ancestry walk for them.
|
||||
if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) {
|
||||
return None;
|
||||
}
|
||||
let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended);
|
||||
let transparent = |d: &Document, i: &AppearanceItem| {
|
||||
pattern_fill(d, i).is_some_and(|(f, def, _)| {
|
||||
let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal;
|
||||
def.art.iter().any(|a| transparent_image(a, see_through, on))
|
||||
})
|
||||
};
|
||||
expand_patterns_where(d, l, transparent)
|
||||
})?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Whether `n` has opacity or a blending mode of its own.
|
||||
fn blended(n: &Node) -> bool {
|
||||
n.opacity < 1.0 || n.blend != BlendMode::Normal
|
||||
}
|
||||
|
||||
/// Whether `n` is or holds a transparent image: one with see-through pixels (key in `keys`), or
|
||||
/// with opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`.
|
||||
fn transparent_image(n: &Node, keys: &BTreeSet<String>, on: bool) -> bool {
|
||||
let on = on || blended(n);
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) => on || keys.contains(&im.key),
|
||||
_ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Path `l` with each pattern fill turned into the tiles it paints over the box of the outline it
|
||||
/// fills, in a clip group shaped like that outline with the fill's opacity, blend mode and effects
|
||||
/// other than geometry effects, in appearance order: the other items stay on plain copies of the
|
||||
@@ -419,7 +460,15 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> {
|
||||
/// ([`pattern_tiles`]). A pattern fill that lays no tile there stays. `None` when no pattern fill
|
||||
/// lays a tile.
|
||||
fn expand_patterns(d: &mut Document, l: &Node) -> Option<Node> {
|
||||
if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) {
|
||||
expand_patterns_where(d, l, |_, _| true)
|
||||
}
|
||||
|
||||
/// [`expand_patterns`] for only the pattern fills `which` picks: the others stay like the other
|
||||
/// items.
|
||||
fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool) -> Option<Node> {
|
||||
if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
|| !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some() && which(d, i))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let reshaped = reshaped(l);
|
||||
@@ -430,9 +479,9 @@ fn expand_patterns(d: &mut Document, l: &Node) -> Option<Node> {
|
||||
let mut rest = vec![];
|
||||
let mut expanded = false;
|
||||
for item in &l.appearance.items {
|
||||
let fill = pattern_fill(d, item).map(|(f, def, xf)| (f, def.clone(), xf));
|
||||
let fill = pattern_fill(d, item).filter(|_| which(d, item)).map(|(f, def, xf)| (f, def.clone(), xf));
|
||||
let tiles = fill.and_then(|(f, def, xf)| {
|
||||
let (fl, _, bounds) = fill_shape(l, f, &path, bounds)?;
|
||||
let (fl, _, bounds) = fill_shape(l, item, &path, bounds)?;
|
||||
let t = pattern_tiles(d, &def, xf, bounds);
|
||||
(!t.is_empty()).then_some((f, fl, t))
|
||||
});
|
||||
@@ -603,7 +652,7 @@ fn seeded_here(n: &Node) -> bool {
|
||||
|
||||
/// Does `n`, something in it or one of their opacity masks have a random Transform effect
|
||||
/// ([`seeded_here`])?
|
||||
fn has_seeded(n: &Node) -> bool {
|
||||
pub(crate) fn has_seeded(n: &Node) -> bool {
|
||||
seeded_here(n)
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| has_seeded(&m.art))
|
||||
|| (!matches!(n.kind, NodeKind::Compound { .. }) && n.children().is_some_and(|c| c.iter().any(|c| has_seeded(c))))
|
||||
@@ -720,27 +769,22 @@ fn tile_art(d: &mut Document, l: &Node, f: &FillLayer, tiles: &[Node]) -> Option
|
||||
|
||||
/// The colour and opacity gradient fill `g` paints at a document point of an object whose box is
|
||||
/// `bounds`, as the canvas draws it (the end colours continue past the ends). Colours stay in the
|
||||
/// colour model their stops (or freeform points) share; display RGB where models differ.
|
||||
pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect) -> Box<dyn Fn(Point) -> (Color, f32) + '_> {
|
||||
/// color model their stops share; display RGB where models differ. Freeform points mix in the
|
||||
/// model they share ([`vectorcraft_color::Freeform::model_field`]); where their models differ, the
|
||||
/// RGB color they mix to is stored in `doc_model` (the document's model) the way `paint.setFill`
|
||||
/// stores an RGB color ([`super::paint::stored_color`]).
|
||||
pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model) -> Box<dyn Fn(Point) -> (Color, f32) + '_> {
|
||||
if g.gradient.kind == GradientKind::Freeform {
|
||||
let b = bounds.abs();
|
||||
let f = g.freeform_on(b);
|
||||
let model = shared_model(f.points.iter().map(|p| p.color));
|
||||
let field = f.field(spread_scale(b));
|
||||
let field = g.freeform_on(b).model_field(spread_scale(b));
|
||||
let store_in = (field.model().is_none() && doc_model != Model::Rgb).then_some(doc_model);
|
||||
return Box::new(move |p| {
|
||||
let ([r, g, b], a) = field.sample(p);
|
||||
let c = Color::rgb(r, g, b);
|
||||
(model.map_or(c, |m| c.in_model(m)), a)
|
||||
let (c, a) = field.sample(p);
|
||||
(super::paint::stored_color(store_in, c), a)
|
||||
});
|
||||
}
|
||||
let geom = g.resolve(bounds);
|
||||
Box::new(move |p| g.gradient.sample_with(geom.param_at(g.gradient.kind, p) as f32, lerp_color))
|
||||
}
|
||||
|
||||
/// The colour model all of `colors` share.
|
||||
fn shared_model(mut colors: impl Iterator<Item = Color>) -> Option<Model> {
|
||||
let m = colors.next()?.model();
|
||||
colors.all(|c| c.model() == m).then_some(m)
|
||||
Box::new(move |p| g.gradient.sample_keep_model(geom.param_at(g.gradient.kind, p) as f32))
|
||||
}
|
||||
|
||||
/// Where the colour changes along a gradient between parameters `t0` and `t1`: both ends, every
|
||||
@@ -749,8 +793,13 @@ fn shared_model(mut colors: impl Iterator<Item = Color>) -> Option<Model> {
|
||||
/// are over `max_gap` apart. The colour is linear in display RGB between neighbours, as the
|
||||
/// canvas draws it.
|
||||
fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32))> {
|
||||
let at = |t: f64| (t, g.sample_with(t as f32, lerp_color));
|
||||
let at = |t: f64| (t, g.sample_keep_model(t as f32));
|
||||
let mut v = vec![at(t0)];
|
||||
// A Perceptual gradient curves between its stops: the mesh takes a column at each of the stops
|
||||
// its expansion adds, so the linear mix between columns follows that curve.
|
||||
if !g.method.is_classic() {
|
||||
v.extend(g.expanded().map(|(o, ..)| f64::from(o)).filter(|o| *o > t0 && *o < t1).map(at));
|
||||
}
|
||||
for (i, s) in g.stops.iter().enumerate() {
|
||||
let o = s.offset as f64;
|
||||
if o > t0 && o < t1 {
|
||||
@@ -848,7 +897,7 @@ impl Frame {
|
||||
/// is just its band, so nothing doubles up.
|
||||
fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> {
|
||||
let step = (self.t1 - self.t0) / n as f64;
|
||||
let color = |k: usize| g.sample_with((self.t0 + (k as f64 + 0.5) * step) as f32, lerp_color);
|
||||
let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32);
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
if self.radial {
|
||||
let ellipse = |t: f64| {
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Document file I/O for every frontend (desktop, web, CLI, control channel, headless MCP): open,
|
||||
//! save, export and serialize by path or bytes (base64), the format table, `command.batch` and
|
||||
//! `action.batch` (the Actions panel menu's Batch…).
|
||||
//!
|
||||
//! - `load`: `document.open` (native, legacy, SVG/SVGZ, PDF/.ai/.ait, DXF, raster images).
|
||||
//! - `action_batch`: play an action on every file in a folder or every data set.
|
||||
//! - `encode`: one encoder per writable format, with typed options parsed from the params.
|
||||
//! - `svg`: the SVG Options (styling, fonts, images, object ids, artboards…).
|
||||
//! - `export`: `document.export` / `serialize` / `exportSelection` / `exportForOffice`.
|
||||
//! - `screens`: Export for Screens (`document.exportForScreens`, `document.exportSettings`); `zip`
|
||||
//! packs its files as one download, and reads the files of Word documents placed as type.
|
||||
//! - `save`: `document.save`, Save As / a Copy / as Template, New from Template, Revert and the
|
||||
//! per-format options (`file.formatOptions`); [`save_with`] is the one save path of every frontend.
|
||||
//! - `pdf`: PDF settings and presets for every PDF export, `document.exportPdf`.
|
||||
//! - `pdfimport`: the PDF pages, box and password `document.open` and Place read, `document.pdfInfo`.
|
||||
//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PICT).
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place.
|
||||
//!
|
||||
//! [`FORMATS`] is the single list of formats (append-only); open dialogs use [`open_filters`],
|
||||
//! agents query `document.formats`.
|
||||
|
||||
mod action_batch;
|
||||
mod affinity;
|
||||
mod batch;
|
||||
pub mod dxf;
|
||||
pub mod dxfimport;
|
||||
mod encode;
|
||||
pub mod eps;
|
||||
mod export;
|
||||
pub(crate) mod imagemap;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
mod metafile;
|
||||
mod naming;
|
||||
mod native;
|
||||
pub mod pdf;
|
||||
mod pdfimport;
|
||||
pub mod pngtext;
|
||||
pub mod ppi;
|
||||
pub mod progress;
|
||||
pub mod psdread;
|
||||
mod save;
|
||||
mod screens;
|
||||
mod svg;
|
||||
mod text;
|
||||
mod tgaread;
|
||||
pub mod zip;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
|
||||
pub(crate) use encode::{anti_alias, background, with_single_artboard};
|
||||
pub use export::export_source;
|
||||
pub(crate) use export::{export_crop, isolated};
|
||||
pub(crate) use load::check_not_lossy_overwrite;
|
||||
use load::err;
|
||||
pub(crate) use load::import_svg;
|
||||
pub(crate) use load::is_placeholder;
|
||||
pub(crate) use load::native_file;
|
||||
pub(crate) use load::page_or_editing_data;
|
||||
pub(crate) use load::source;
|
||||
pub use load::{
|
||||
Loaded, RasterImage, ReadFile, detect, file_name, load, load_with, open_bytes, open_bytes_with, open_read, open_template, raster_image,
|
||||
read_for_open, texture_image,
|
||||
};
|
||||
pub use load::{losses_summary, overwrite_losses};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use save::job_for;
|
||||
pub use save::{
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option,
|
||||
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
|
||||
templates_folder,
|
||||
};
|
||||
pub use screens::{
|
||||
PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS, PRESETS as SCREEN_PRESETS, ScreenExport, ScreenExportPreset, ScreenSize,
|
||||
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_rows as screen_preset_rows,
|
||||
};
|
||||
pub(crate) use screens::{
|
||||
SHARED_KEYS as SCREEN_SETTINGS_KEYS, check_settings as check_screen_settings, export as export_screens, safe_file_name,
|
||||
store_settings as store_screen_settings,
|
||||
};
|
||||
pub use svg::options_map as svg_options;
|
||||
/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the
|
||||
/// file it replaces), for the apps' own writers too.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use vectorcraft_format::write_atomic;
|
||||
|
||||
use super::*;
|
||||
use crate::EngineError;
|
||||
|
||||
mod access;
|
||||
mod commands;
|
||||
mod export_names;
|
||||
mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use access::list_dir;
|
||||
pub use access::write_file_with;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::{Placed, copy_new, file_metadata};
|
||||
pub(crate) use access::{absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, write_file, write_new_file};
|
||||
#[cfg(all(test, windows))]
|
||||
pub(crate) use access::{document_path_on, document_path_with};
|
||||
#[cfg(test)]
|
||||
pub(crate) use access::{drive_share_of, share_of};
|
||||
#[cfg(test)]
|
||||
pub(crate) use access::{drive_share_path, share_path, touched};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use access::{may_read, may_write};
|
||||
pub use commands::specs;
|
||||
pub use export_names::artboard_file_names;
|
||||
pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return};
|
||||
use export_names::{distinct_names, write_encoded};
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable};
|
||||
pub use formats::{
|
||||
DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, file_stem,
|
||||
format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export, writable_format,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_affinity;
|
||||
#[cfg(test)]
|
||||
mod tests_pdf;
|
||||
#[cfg(test)]
|
||||
mod tests_pdfcolor;
|
||||
#[cfg(test)]
|
||||
mod tests_pdfedit;
|
||||
#[cfg(test)]
|
||||
mod tests_pdffidelity;
|
||||
#[cfg(test)]
|
||||
mod tests_pdfimport;
|
||||
#[cfg(test)]
|
||||
mod tests_svg;
|
||||
#[cfg(test)]
|
||||
mod tests_svgedit;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_raster;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_exportas;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_jpeg;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_palette;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_batch;
|
||||
#[cfg(test)]
|
||||
mod tests_screens;
|
||||
#[cfg(test)]
|
||||
mod tests_text;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_dxf;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_pdfsecurity;
|
||||
#[cfg(test)]
|
||||
mod tests_svgenc;
|
||||
#[cfg(test)]
|
||||
mod tests_svgimport;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_eps;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_dxfimport;
|
||||
#[cfg(test)]
|
||||
mod tests_metafile;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_pdfoutput;
|
||||
#[cfg(test)]
|
||||
mod tests_tiffbmp;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_pdfx;
|
||||
#[cfg(test)]
|
||||
mod tests_psd;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_epsimport;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_aiimport;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_pdflayers;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_pdfwebview;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_pdf13;
|
||||
@@ -0,0 +1,418 @@
|
||||
use super::*;
|
||||
|
||||
// ---------- the file system (none on the web, where commands take and return bytes) ----------
|
||||
//
|
||||
// Every path a command reads or writes goes through these, which check it against the automation
|
||||
// roots in force ([`crate::file_access`]): a path outside them is an error (`file_stamp` and
|
||||
// `file_created`: no file), as is any path once roots are in force without its kind of access.
|
||||
|
||||
/// `path` checked for reading against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn may_read(path: &str) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
touch(path);
|
||||
crate::file_access::check_read(path).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
/// Paths read while [`touched`] runs, on any thread (the SVG importer reads on one of its own).
|
||||
#[cfg(test)]
|
||||
static TOUCHED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
#[cfg(test)]
|
||||
static RECORDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
#[cfg(test)]
|
||||
fn touch(path: &str) {
|
||||
if RECORDING.load(std::sync::atomic::Ordering::SeqCst) > 0 {
|
||||
TOUCHED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(path.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` and list the paths read through this module meanwhile (by any test running then).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
use std::sync::atomic::Ordering::SeqCst;
|
||||
let start = TOUCHED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).len();
|
||||
RECORDING.fetch_add(1, SeqCst);
|
||||
let out = f();
|
||||
RECORDING.fetch_sub(1, SeqCst);
|
||||
let seen = TOUCHED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(start..).unwrap_or_default().to_vec();
|
||||
(out, seen)
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn may_write(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
may_read(path)?;
|
||||
// A device or pipe may never end: only a regular file is read to its end.
|
||||
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a
|
||||
/// regular file (a folder, a pipe, a device) is refused, also through a link.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file_head(path: &str, max: usize) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
may_read(path)?;
|
||||
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
let mut out = vec![];
|
||||
std::fs::File::open(path).and_then(|f| f.take(max as u64).read_to_end(&mut out)).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
// Work that stops early for a cancel can leave a truncated result: none of it is written.
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
// Never a half-written file: see [`write_atomic`].
|
||||
write_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// [`write_file`] with what `fill` writes into the file (a save streamed into it).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn create_dir(path: &str) -> Result<()> {
|
||||
may_write(path)?;
|
||||
std::fs::create_dir_all(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// Write `bytes` to a new file at `path`. A file already at `path` is an error and is never
|
||||
/// replaced. When the write fails part way, the file it started is removed.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn write_new_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
use std::io::Write as _;
|
||||
may_write(path)?;
|
||||
let err = |e: std::io::Error| EngineError::Other(format!("{path}: {e}"));
|
||||
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(err)?;
|
||||
let written = f.write_all(bytes).and_then(|()| vectorcraft_format::sync_file(&f));
|
||||
drop(f);
|
||||
written.map_err(|e| {
|
||||
// Best effort: the partly written file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(path);
|
||||
err(e)
|
||||
})
|
||||
}
|
||||
|
||||
/// The highest number [`copy_new`] gives a copy's name (`Name 99.png`).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_COPY_NUMBER: u32 = 99;
|
||||
|
||||
/// Where [`copy_new`] put a file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) enum Placed {
|
||||
/// Copied to this new file.
|
||||
Copied(std::path::PathBuf),
|
||||
/// Kept as this file, which holds the same contents.
|
||||
Kept(std::path::PathBuf),
|
||||
}
|
||||
|
||||
/// Put a copy of the file `from` into the folder `dir`, never replacing a file there. It tries
|
||||
/// `Name.ext`, then `Name 2.ext` up to `Name 99.ext`, and stops at the first name that is free,
|
||||
/// where `create` makes the copy, or that is a file holding the same contents (`same`, given that
|
||||
/// file and its metadata), which is kept. When `create` fails with `AlreadyExists` (the name was
|
||||
/// taken meanwhile), it tries the next name. `None` when no name is free or holds the same
|
||||
/// contents; a name whose metadata can't be read counts as taken.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn copy_new(
|
||||
from: &std::path::Path,
|
||||
dir: &std::path::Path,
|
||||
create: impl Fn(&std::path::Path) -> std::io::Result<()>,
|
||||
same: impl Fn(&std::path::Path, &std::fs::Metadata) -> bool,
|
||||
) -> std::io::Result<Option<Placed>> {
|
||||
use std::io::ErrorKind;
|
||||
let (Some(name), Some(stem)) = (from.file_name(), from.file_stem()) else { return Err(ErrorKind::InvalidInput.into()) };
|
||||
let ext = from.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
|
||||
for n in 1..=MAX_COPY_NUMBER {
|
||||
let to = if n == 1 { dir.join(name) } else { dir.join(format!("{} {n}{ext}", stem.to_string_lossy())) };
|
||||
match std::fs::symlink_metadata(&to) {
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => match create(&to) {
|
||||
Ok(()) => return Ok(Some(Placed::Copied(to))),
|
||||
// Taken meanwhile: the next name.
|
||||
Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
Ok(m) if m.is_file() && same(&to, &m) => return Ok(Some(Placed::Kept(to))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The most entries `file.list` returns.
|
||||
const LIST_MAX: usize = 5000;
|
||||
|
||||
pub(super) fn file_list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = p.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad("file.list", "missing `path`"))?;
|
||||
let (entries, truncated) = list_dir(path, LIST_MAX)?;
|
||||
Ok(json!({ "path": absolute_path(path), "entries": entries, "truncated": truncated }))
|
||||
}
|
||||
|
||||
/// The entries of folder `path`, sorted by name: at most `max`, and whether there were more. A
|
||||
/// link isn't followed: its target may lie outside the automation roots.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
|
||||
may_read(path)?;
|
||||
let dir = std::fs::read_dir(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let mut entries: Vec<(String, Value)> = vec![];
|
||||
let mut truncated = false;
|
||||
for e in dir.flatten() {
|
||||
if entries.len() == max {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
let Ok(t) = e.file_type() else { continue };
|
||||
let entry = if t.is_symlink() {
|
||||
json!({ "name": name, "kind": "link" })
|
||||
} else if t.is_dir() {
|
||||
json!({ "name": name, "kind": "folder" })
|
||||
} else {
|
||||
json!({ "name": name, "kind": "file", "size": e.metadata().map(|m| m.len()).ok() })
|
||||
};
|
||||
entries.push((name, entry));
|
||||
}
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok((entries.into_iter().map(|(_, v)| v).collect(), truncated))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) fn list_dir(_: &str, _: usize) -> Result<(Vec<Value>, bool)> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
/// A file's size (bytes) and modification time (ms since the Unix epoch, when the file system
|
||||
/// keeps one); `None` when there is no file at `path` (or automation may not read it).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn file_stamp(path: &str) -> Option<(u64, Option<u64>)> {
|
||||
let m = file_metadata(path).filter(std::fs::Metadata::is_file)?;
|
||||
let modified = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as u64);
|
||||
Some((m.len(), modified))
|
||||
}
|
||||
|
||||
/// When the file at `path` was created (ms since the Unix epoch), when the file system keeps it
|
||||
/// (and automation may read it).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn file_created(path: &str) -> Option<u64> {
|
||||
let t = file_metadata(path)?.created().ok()?;
|
||||
t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_millis() as u64)
|
||||
}
|
||||
|
||||
/// The file system's metadata of `path`, following links (when automation may read it).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn file_metadata(path: &str) -> Option<std::fs::Metadata> {
|
||||
may_read(path).ok()?;
|
||||
std::fs::metadata(path).ok()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn file_created(_: &str) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
|
||||
/// `path` made absolute against the working directory (as given when absolute already, or when
|
||||
/// that fails).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn absolute_path(path: &str) -> String {
|
||||
if std::path::Path::new(path).is_absolute() {
|
||||
return path.to_string();
|
||||
}
|
||||
std::path::absolute(path).map_or_else(|_| path.to_string(), |p| p.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// The file to open for `stored`, a path or `file:` URL stored in a document (a linked file, an
|
||||
/// SVG image's href), or why it is not followed. `document` is the path of the document it is
|
||||
/// stored in, when it has one: a relative path is taken from its folder. Only files on this
|
||||
/// computer, or on the network share the document is on, are followed (see `craft_docpath`); a
|
||||
/// path that is still relative (no document) is refused, as the working directory isn't the
|
||||
/// document's choice. On Windows, a document on a mapped drive is on the share behind the drive
|
||||
/// ([`share_path`]): a path refused as on another computer is checked again against the
|
||||
/// document's path on that share. A path on a drive mapped to a network share other than the
|
||||
/// document's ([`drive_share_path`]) is refused as on another computer. Every stored path
|
||||
/// reaches the file system through this.
|
||||
pub(crate) fn document_path(stored: &str, document: Option<&str>) -> std::result::Result<String, craft_docpath::Refused> {
|
||||
document_path_on(stored, document, share_path, drive_share_path)
|
||||
}
|
||||
|
||||
/// [`document_path`], with `share` giving a document's path on the network share behind its drive.
|
||||
pub(crate) fn document_path_with(
|
||||
stored: &str,
|
||||
document: Option<&str>,
|
||||
share: impl FnOnce(&str) -> Option<String>,
|
||||
) -> std::result::Result<String, craft_docpath::Refused> {
|
||||
use craft_docpath::Refused;
|
||||
let document = document.map(absolute_path);
|
||||
let resolve = |document: Option<&str>| craft_docpath::resolve_absolute(stored, document.map(std::path::Path::new));
|
||||
let path = match resolve(document.as_deref()) {
|
||||
Err(Refused::Network) => {
|
||||
let share = document.as_deref().and_then(share).ok_or(Refused::Network)?;
|
||||
resolve(Some(share.as_str()))?
|
||||
}
|
||||
path => path?,
|
||||
};
|
||||
path.into_os_string().into_string().map_err(|_| Refused::Invalid)
|
||||
}
|
||||
|
||||
/// [`document_path_with`], also refusing a path on a drive that is mapped to a network share other
|
||||
/// than the document's (or, for a document on this computer or without a path, to any share) as
|
||||
/// [`craft_docpath::Refused::Network`]. `drive_share` gives a path's path on the share behind its
|
||||
/// drive (`Y:\art\x.png` on `\\server\other\art\x.png`), or `None` for a path on this computer. A
|
||||
/// path on the document's own drive is not looked up. A document written `\\?\Z:\…` is looked up
|
||||
/// on its share as `Z:\…` is.
|
||||
pub(crate) fn document_path_on(
|
||||
stored: &str,
|
||||
document: Option<&str>,
|
||||
share: impl Fn(&str) -> Option<String>,
|
||||
drive_share: impl FnOnce(&str) -> Option<String>,
|
||||
) -> std::result::Result<String, craft_docpath::Refused> {
|
||||
let share = |d: &str| share(d.strip_prefix(r"\\?\").filter(|d| drive_letter(d).is_some()).unwrap_or(d));
|
||||
let path = document_path_with(stored, document, share)?;
|
||||
let document = document.map(absolute_path);
|
||||
let Some(drive) = drive_letter(&path) else { return Ok(path) };
|
||||
if document.as_deref().and_then(drive_letter).is_some_and(|d| d.eq_ignore_ascii_case(&drive)) {
|
||||
return Ok(path);
|
||||
}
|
||||
let Some(on_share) = drive_share(&path) else { return Ok(path) };
|
||||
let home = document.map(|d| share(&d).unwrap_or(d));
|
||||
craft_docpath::resolve(&on_share, home.as_deref().map(std::path::Path::new))?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// The drive letter of an absolute path on a drive (`C:\…`, `C:/…` or `\\?\C:\…`).
|
||||
fn drive_letter(path: &str) -> Option<char> {
|
||||
let mut chars = path.strip_prefix(r"\\?\").unwrap_or(path).chars();
|
||||
match (chars.next(), chars.next(), chars.next()) {
|
||||
(Some(l), Some(':'), Some('\\' | '/')) if l.is_ascii_alphabetic() => Some(l),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of `path` (on a drive, `Y:\art\x.png`) on the network share the drive is mapped to
|
||||
/// (`\\server\other\art\x.png`), when the drive's root folder is on one and automation may read
|
||||
/// `path`. The root folder's final path ([`std::fs::canonicalize`]) names the share.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn drive_share_path(path: &str) -> Option<String> {
|
||||
may_read(path).ok()?;
|
||||
drive_share_of(path, |root| std::fs::canonicalize(root).ok())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub(crate) fn drive_share_path(_: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The path of `path` on the network share its drive is mapped to, given `final_path`, which
|
||||
/// returns the final path of the drive's root folder (`Y:\`): as [`share_of`] gives it for a
|
||||
/// document, also for a path written `\\?\Y:\…`.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) fn drive_share_of(path: &str, final_path: impl FnOnce(&str) -> Option<std::path::PathBuf>) -> Option<String> {
|
||||
let path = path.strip_prefix(r"\\?\").unwrap_or(path);
|
||||
share_of(path, |folder| {
|
||||
let (root, rest) = (folder.get(..3)?, folder.get(3..)?);
|
||||
let root = final_path(root)?;
|
||||
let root = root.to_str()?.trim_end_matches('\\');
|
||||
Some(if rest.is_empty() { root.into() } else { format!(r"{root}\{rest}").into() })
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of `document` (on a drive, `Z:\jobs\doc.vectorcraft`) on the network share the drive is
|
||||
/// mapped to (`\\server\share\jobs\doc.vectorcraft`), when its folder is on one and automation may
|
||||
/// read the folder. The folder's final path ([`std::fs::canonicalize`]) names the share as
|
||||
/// `\\?\UNC\server\share\…`.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn share_path(document: &str) -> Option<String> {
|
||||
share_of(document, |folder| {
|
||||
may_read(folder).ok()?;
|
||||
std::fs::canonicalize(folder).ok()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub(crate) fn share_path(_: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The path of `document` on the network share its drive is mapped to, given `final_path`, which
|
||||
/// returns the final path of a folder: `None` when `document` is not on a drive (`C:\` or `C:/`)
|
||||
/// or `final_path` gives no share (`\\?\UNC\server\share\…`), such as a folder on a local volume.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) fn share_of(document: &str, final_path: impl FnOnce(&str) -> Option<std::path::PathBuf>) -> Option<String> {
|
||||
let mut chars = document.chars();
|
||||
if !matches!((chars.next(), chars.next(), chars.next()), (Some(l), Some(':'), Some('\\' | '/')) if l.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
// The drive's root folder keeps its separator (`Z:\`).
|
||||
let split = document.rfind(['\\', '/'])?;
|
||||
let (folder, name) = (document.get(..split.max(3))?, document.get(split + 1..)?);
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let target = final_path(folder)?;
|
||||
let target = target.to_str()?;
|
||||
let unc = target.get(..8).filter(|p| p.eq_ignore_ascii_case(r"\\?\UNC\")).and(target.get(8..))?.trim_end_matches('\\');
|
||||
if unc.split('\\').filter(|c| !c.is_empty()).count() < 2 {
|
||||
return None;
|
||||
}
|
||||
Some(format!(r"\\{unc}\{name}"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn file_stamp(_: &str) -> Option<(u64, Option<u64>)> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn absolute_path(path: &str) -> String {
|
||||
path.to_string()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn no_fs(path: &str) -> EngineError {
|
||||
EngineError::Other(format!("{path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64)"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
Err(no_fs(path))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn read_file_head(path: &str, _: usize) -> Result<Vec<u8>> {
|
||||
Err(no_fs(path))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn write_file(path: &str, _: &[u8]) -> Result<()> {
|
||||
Err(no_fs(path))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn write_file_with(path: &str, _: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
Err(no_fs(path))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn create_dir(path: &str) -> Result<()> {
|
||||
Err(no_fs(path))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn write_new_file(path: &str, _: &[u8]) -> Result<()> {
|
||||
Err(no_fs(path))
|
||||
}
|
||||
@@ -56,7 +56,13 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "batches cannot nest"));
|
||||
}
|
||||
if find_command(id).is_none() {
|
||||
return Err(bad(C, format!("commands[{i}]: unknown command `{id}`")));
|
||||
return Err(bad(
|
||||
C,
|
||||
match super::super::params::nearest_command(id) {
|
||||
Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"),
|
||||
None => format!("commands[{i}]: unknown command `{id}`"),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
let source = str_param(p, "source").unwrap_or("folder");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): the native layers, curves,
|
||||
//! shapes, artboards, text and images that `vectorcraft-affinity` reads, mapped to editable
|
||||
//! VectorCraft art. Whatever the reader could not map is listed in the warnings. A file whose
|
||||
//! shapes, artboards, text, tables, master pages, layer effects and images that
|
||||
//! `vectorcraft-affinity` reads, mapped to editable VectorCraft art. Whatever the reader could not map is listed in the warnings. A file whose
|
||||
//! native document can't be read opens as its embedded preview instead, with a warning that says
|
||||
//! why, and can't be placed.
|
||||
|
||||
@@ -8,63 +8,28 @@ use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
|
||||
use serde_json::json;
|
||||
use vectorcraft_affinity::model::{self as af, Align as AfAlign, Blend, Kind, Pixels};
|
||||
use vectorcraft_affinity::paint::{self as ap, Cap, GradientKind as AfKind, Join};
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer};
|
||||
use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, Effect, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer};
|
||||
use vectorcraft_doc::geom::{FillRule, PathData, shapes};
|
||||
use vectorcraft_doc::text::{CharStyle, Justify, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_doc::text::{CharStyle, FirstBaseline, Justify, TextKind, TextObject, TextRun, VerticalAlign};
|
||||
use vectorcraft_doc::{Artboard, Document, ImageObject, LayerColor, Node, NodeKind, OpacityMask};
|
||||
|
||||
use super::load::{err, raster_doc};
|
||||
use crate::Result;
|
||||
|
||||
/// What an Affinity file opened as.
|
||||
pub(super) struct Imported {
|
||||
pub doc: Document,
|
||||
pub warnings: Vec<String>,
|
||||
/// Only the embedded preview: never placed, used as a template or mined for styles.
|
||||
pub preview_only: bool,
|
||||
}
|
||||
mod document;
|
||||
mod import;
|
||||
mod layout;
|
||||
mod master_copies;
|
||||
mod nodes;
|
||||
mod paint;
|
||||
mod text;
|
||||
|
||||
pub(super) fn import(name: &str, bytes: &[u8]) -> Result<Imported> {
|
||||
match vectorcraft_affinity::read(bytes, vectorcraft_affinity::Limits::default()) {
|
||||
Ok(d) => {
|
||||
let mut b = Builder { doc: Document::new(0.0, 0.0), warnings: Vec::new(), k: 72.0 / d.dpi, layer: 0 };
|
||||
b.document(&d)?;
|
||||
b.doc.limit_depth_noting(&mut b.warnings);
|
||||
let mut warnings = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect::<Vec<_>>();
|
||||
warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}.")));
|
||||
Ok(Imported { doc: b.doc, warnings, preview_only: false })
|
||||
}
|
||||
Err(native) => {
|
||||
let (doc, w) = preview(name, bytes, &native)?;
|
||||
Ok(Imported { doc, warnings: vec![w], preview_only: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The embedded preview, for files whose native document can't be read.
|
||||
fn preview(name: &str, bytes: &[u8], native: &vectorcraft_affinity::Error) -> Result<(Document, String)> {
|
||||
let p = vectorcraft_affinity::preview(bytes).map_err(|e| err(format!("{native}; its embedded preview can't be read either ({e})")))?;
|
||||
// `raster_doc` normally probes PNG dimensions and keeps its encoded bytes. Verify this
|
||||
// untrusted preview's complete pixels first, so corrupt data cannot create a blank image.
|
||||
let mut reader = image::ImageReader::with_format(Cursor::new(p.png), image::ImageFormat::Png);
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(4096);
|
||||
limits.max_image_height = Some(4096);
|
||||
limits.max_alloc = Some(128 << 20);
|
||||
reader.limits(limits);
|
||||
let _pixels = reader.decode().map_err(err)?;
|
||||
let d = raster_doc(name, p.png)?;
|
||||
Ok((
|
||||
d,
|
||||
format!(
|
||||
"The native Affinity document could not be read ({native}). Opened only its embedded {}×{} PNG preview, which may be smaller than the document: no layers, vectors, text or pages. Save a new copy; the Affinity source cannot be saved back. Export SVG or PDF from Affinity for editable vectors.",
|
||||
p.width, p.height
|
||||
),
|
||||
))
|
||||
}
|
||||
pub(super) use import::import;
|
||||
use master_copies::{CopyCost, MasterPart};
|
||||
|
||||
struct Builder {
|
||||
doc: Document,
|
||||
@@ -73,471 +38,21 @@ struct Builder {
|
||||
k: f64,
|
||||
/// Layers made so far (their colours cycle).
|
||||
layer: u8,
|
||||
}
|
||||
|
||||
fn rect_of(r: af::Rect) -> Rect {
|
||||
Rect::new(r.x0, r.y0, r.x1, r.y1)
|
||||
}
|
||||
|
||||
fn affine(a: af::Affine) -> Affine {
|
||||
Affine::new(a.0)
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) {
|
||||
self.warnings.push(w.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn document(&mut self, d: &af::Document) -> Result<()> {
|
||||
// Spreads (Publisher pages) sit side by side, 36 pt apart; a single spread keeps its origin.
|
||||
let mut layers = Vec::new();
|
||||
let mut artboards = Vec::new();
|
||||
let mut x = 0.0;
|
||||
for (i, spread) in d.spreads.iter().enumerate() {
|
||||
let shift = if i == 0 { 0.0 } else { x - spread.bounds.x0 * self.k };
|
||||
let to_doc = Affine::translate((shift, 0.0)) * Affine::scale(self.k);
|
||||
let before = artboards.len();
|
||||
let mut loose: Vec<Arc<Node>> = Vec::new();
|
||||
for n in &spread.nodes {
|
||||
let top = match &n.kind {
|
||||
Kind::Layer => self.node(n, to_doc, &mut artboards, true),
|
||||
Kind::Artboard { .. } => self.node(n, to_doc, &mut artboards, true).map(|art| self.layer_of(&n.name, art, n.visible, n.locked)),
|
||||
_ => {
|
||||
if let Some(art) = self.node(n, to_doc, &mut artboards, false) {
|
||||
loose.push(art);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !loose.is_empty() {
|
||||
layers.push(self.layer_with(None, std::mem::take(&mut loose)));
|
||||
}
|
||||
layers.extend(top);
|
||||
}
|
||||
if !loose.is_empty() {
|
||||
layers.push(self.layer_with(None, loose));
|
||||
}
|
||||
// Without artboards, each page (or the spread) becomes one.
|
||||
if artboards.len() == before {
|
||||
let rects = if spread.pages.is_empty() { vec![spread.bounds] } else { spread.pages.clone() };
|
||||
for r in rects {
|
||||
let name = format!("{} {}", if d.spreads.len() > 1 || spread.pages.len() > 1 { "Page" } else { "Artboard" }, artboards.len() + 1);
|
||||
artboards.push((name, to_doc.transform_rect_bbox(rect_of(r))));
|
||||
}
|
||||
}
|
||||
x = artboards.iter().map(|(_, r)| r.x1).fold(x, f64::max) + 36.0;
|
||||
if spread.transparent && i == 0 {
|
||||
self.warn("transparent page backgrounds show as white artboards");
|
||||
}
|
||||
}
|
||||
self.doc.artboards = artboards
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, r))| r.width() > 0.0 && r.height() > 0.0)
|
||||
.map(|(i, (name, rect))| Artboard { id: i as u32 + 1, name, rect, show_center_mark: false, show_cross_hairs: false })
|
||||
.collect();
|
||||
if self.doc.artboards.is_empty() {
|
||||
return Err(err("the Affinity document has no page with a size"));
|
||||
}
|
||||
// Bottom to top, as Affinity lists them.
|
||||
self.doc.layers = layers;
|
||||
if self.doc.layers.is_empty() {
|
||||
let empty = self.layer_with(None, Vec::new());
|
||||
self.doc.layers.push(empty);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn layer_with(&mut self, name: Option<&str>, children: Vec<Arc<Node>>) -> Arc<Node> {
|
||||
let id = self.doc.alloc_id();
|
||||
self.layer = self.layer.wrapping_add(1);
|
||||
let label = name.map(str::to_string).unwrap_or_else(|| format!("Layer {}", self.layer));
|
||||
let mut n = Node::layer(id, &label, LayerColor::Preset(self.layer % 9));
|
||||
if let Some(c) = n.children_mut() {
|
||||
*c = children;
|
||||
}
|
||||
Arc::new(n)
|
||||
}
|
||||
|
||||
/// An artboard at the top level becomes a layer of its name holding its clip group.
|
||||
fn layer_of(&mut self, name: &str, art: Arc<Node>, visible: bool, locked: bool) -> Arc<Node> {
|
||||
let mut l = (*self.layer_with(Some(if name.is_empty() { "Artboard" } else { name }), vec![art])).clone();
|
||||
l.visible = visible;
|
||||
l.locked = locked;
|
||||
Arc::new(l)
|
||||
}
|
||||
|
||||
fn base(&mut self, n: &af::Node, kind: NodeKind) -> Node {
|
||||
let mut out = Node::new(self.doc.alloc_id(), kind);
|
||||
out.name = (!n.name.is_empty()).then(|| n.name.clone());
|
||||
out.visible = n.visible;
|
||||
out.locked = n.locked;
|
||||
out.opacity = n.opacity as f32;
|
||||
out.blend = self.blend(n.blend);
|
||||
out
|
||||
}
|
||||
|
||||
fn blend(&mut self, b: Blend) -> BlendMode {
|
||||
match b {
|
||||
Blend::Normal | Blend::PassThrough => BlendMode::Normal,
|
||||
Blend::Darken => BlendMode::Darken,
|
||||
Blend::Multiply => BlendMode::Multiply,
|
||||
Blend::ColorBurn => BlendMode::ColorBurn,
|
||||
Blend::Lighten => BlendMode::Lighten,
|
||||
Blend::Screen => BlendMode::Screen,
|
||||
Blend::ColorDodge => BlendMode::ColorDodge,
|
||||
Blend::Overlay => BlendMode::Overlay,
|
||||
Blend::SoftLight => BlendMode::SoftLight,
|
||||
Blend::HardLight => BlendMode::HardLight,
|
||||
Blend::Difference => BlendMode::Difference,
|
||||
Blend::Exclusion => BlendMode::Exclusion,
|
||||
Blend::Hue => BlendMode::Hue,
|
||||
Blend::Saturation => BlendMode::Saturation,
|
||||
Blend::Color => BlendMode::Color,
|
||||
Blend::Luminosity => BlendMode::Luminosity,
|
||||
_ => {
|
||||
self.warn("blend modes VectorCraft doesn't have (Add, Linear Light, Vivid Light, Pin Light, Hard Mix, Subtract, Darker/Lighter Colour, Average, Negation, Reflect, Glow, Erase) import as Normal");
|
||||
BlendMode::Normal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One Affinity node (and its subtree) as VectorCraft art; `to_doc` maps document pixels to
|
||||
/// points. `layer_level`: the node is directly in a spread or a layer, so a layer stays a layer.
|
||||
fn node(&mut self, n: &af::Node, to_doc: Affine, boards: &mut Vec<(String, Rect)>, layer_level: bool) -> Option<Arc<Node>> {
|
||||
// Register before descending so nested artboards keep their document order.
|
||||
if let Kind::Artboard { rect, .. } = &n.kind {
|
||||
boards.push((
|
||||
if n.name.is_empty() { format!("Artboard {}", boards.len() + 1) } else { n.name.clone() },
|
||||
to_doc.transform_rect_bbox(rect_of(*rect)),
|
||||
));
|
||||
}
|
||||
let child_level = matches!(n.kind, Kind::Layer) && layer_level;
|
||||
let children: Vec<Arc<Node>> = n.children.iter().filter_map(|c| self.node(c, to_doc, boards, child_level)).collect();
|
||||
let mut out = match &n.kind {
|
||||
Kind::Layer if layer_level => {
|
||||
let mut l = (*self.layer_with(Some(if n.name.is_empty() { "Layer" } else { &n.name }), children)).clone();
|
||||
l.visible = n.visible;
|
||||
l.locked = n.locked;
|
||||
l.opacity = n.opacity as f32;
|
||||
l.blend = self.blend(n.blend);
|
||||
l
|
||||
}
|
||||
Kind::Layer | Kind::Group => {
|
||||
let mut g = self.base(n, NodeKind::Group { children, clip: false });
|
||||
// Affinity groups isolate their blending unless they pass through.
|
||||
g.isolate = n.blend != Blend::PassThrough;
|
||||
g
|
||||
}
|
||||
Kind::Shape { path, fills, strokes, even_odd } => {
|
||||
let data = self.path(path, to_doc);
|
||||
let rule = if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero };
|
||||
let appearance = self.appearance(fills, strokes, to_doc);
|
||||
if children.is_empty() {
|
||||
let mut p = self.base(n, NodeKind::Path { path: data, rule, live: None, clipping: false, guide: false });
|
||||
p.appearance = appearance.into();
|
||||
p
|
||||
} else {
|
||||
// A shape clips its children: VectorCraft's clipping path keeps its paint, its
|
||||
// fill behind the clipped art and its stroke over it, as Affinity draws it.
|
||||
let mut clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path: data, rule, live: None, clipping: true, guide: false });
|
||||
clip.appearance = appearance.into();
|
||||
let mut kids = vec![Arc::new(clip)];
|
||||
kids.extend(children);
|
||||
self.base(n, NodeKind::Group { children: kids, clip: true })
|
||||
}
|
||||
}
|
||||
Kind::Artboard { path, even_odd, background, strokes, .. } => {
|
||||
let mut clip = Node::new(
|
||||
self.doc.alloc_id(),
|
||||
NodeKind::Path {
|
||||
path: self.path(path, to_doc),
|
||||
rule: if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero },
|
||||
live: None,
|
||||
clipping: true,
|
||||
guide: false,
|
||||
},
|
||||
);
|
||||
clip.appearance = self.appearance(background, strokes, to_doc).into();
|
||||
let mut kids = vec![Arc::new(clip)];
|
||||
kids.extend(children);
|
||||
let mut g = self.base(n, NodeKind::Group { children: kids, clip: true });
|
||||
g.name = Some(if n.name.is_empty() { "Artboard".into() } else { n.name.clone() });
|
||||
g
|
||||
}
|
||||
Kind::Text(t) => {
|
||||
let text = self.text(t, to_doc);
|
||||
let mut node = self.base(n, NodeKind::Text(Box::new(text)));
|
||||
if !children.is_empty() {
|
||||
let mut kids = vec![Arc::new(node)];
|
||||
kids.extend(children);
|
||||
node = Node::group(self.doc.alloc_id(), kids);
|
||||
}
|
||||
node
|
||||
}
|
||||
Kind::Image(img) => match self.image(img, to_doc) {
|
||||
Some(kind) => self.base(n, kind),
|
||||
None if children.is_empty() => return None,
|
||||
None => self.base(n, NodeKind::Group { children, clip: false }),
|
||||
},
|
||||
Kind::Unsupported if children.is_empty() => return None,
|
||||
Kind::Unsupported => self.base(n, NodeKind::Group { children, clip: false }),
|
||||
};
|
||||
if let Some(img) = &n.pixel_mask {
|
||||
// A pixel mask: its grey levels show (white) or hide (black) the node, and nothing
|
||||
// shows outside it, as an opacity mask that clips.
|
||||
if let Some(kind) = self.image(img, to_doc) {
|
||||
let art = Node::new(self.doc.alloc_id(), kind);
|
||||
out.extras_mut().mask = Some(Box::new(OpacityMask::new(art, true)));
|
||||
}
|
||||
}
|
||||
if let Some(mask) = &n.mask {
|
||||
// A vector mask: the node shows only inside it.
|
||||
let clip = Node::new(
|
||||
self.doc.alloc_id(),
|
||||
NodeKind::Path { path: self.path(mask, to_doc), rule: FillRule::NonZero, live: None, clipping: true, guide: false },
|
||||
);
|
||||
let (opacity, blend, visible, name) = (out.opacity, out.blend, out.visible, out.name.clone());
|
||||
out.opacity = 1.0;
|
||||
out.blend = BlendMode::Normal;
|
||||
let mut g = Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(out)], clip: true });
|
||||
(g.opacity, g.blend, g.visible, g.name) = (opacity, blend, visible, name);
|
||||
out = g;
|
||||
}
|
||||
Some(Arc::new(out))
|
||||
}
|
||||
|
||||
fn path(&self, p: &af::Path, to_doc: Affine) -> PathData {
|
||||
let mut bp = BezPath::new();
|
||||
for s in &p.subpaths {
|
||||
let pt = |q: af::Point| Point::new(q.x, q.y);
|
||||
bp.move_to(pt(s.start));
|
||||
for [c1, c2, e] in &s.segments {
|
||||
if c1 == c2 && c2 == e {
|
||||
bp.line_to(pt(*e));
|
||||
} else {
|
||||
bp.curve_to(pt(*c1), pt(*c2), pt(*e));
|
||||
}
|
||||
}
|
||||
if s.closed {
|
||||
bp.close_path();
|
||||
}
|
||||
}
|
||||
PathData::from_bezpath(&(to_doc * bp))
|
||||
}
|
||||
|
||||
fn color(c: ap::Color) -> (Color, f32) {
|
||||
let f = |v: f64| v.clamp(0.0, 1.0) as f32;
|
||||
match c {
|
||||
ap::Color::Rgb { r, g, b, a } => (Color::Rgb { r: f(r), g: f(g), b: f(b) }, f(a)),
|
||||
ap::Color::Cmyk { c, m, y, k, a } => (Color::Cmyk { c: f(c), m: f(m), y: f(y), k: f(k) }, f(a)),
|
||||
ap::Color::Gray { v, a } => (Color::Gray { k: 1.0 - f(v) }, f(a)),
|
||||
ap::Color::Lab { l, a, b, alpha } => (Color::Lab { l: l as f32, a: a as f32, b: b as f32 }, f(alpha)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A paint and the opacity its colour's alpha becomes.
|
||||
fn paint(&mut self, p: &ap::Paint, to_doc: Affine) -> Option<(Paint, f32)> {
|
||||
match p {
|
||||
ap::Paint::None => None,
|
||||
ap::Paint::Solid(c) => {
|
||||
let (color, a) = Self::color(*c);
|
||||
Some((Paint::solid(color), a))
|
||||
}
|
||||
ap::Paint::Gradient(g) => {
|
||||
let stops = g
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let (color, opacity) = Self::color(s.color);
|
||||
let mut stop = GradientStop::new(s.offset as f32, color);
|
||||
stop.opacity = opacity;
|
||||
stop.midpoint = s.half_point().clamp(0.13, 0.87) as f32;
|
||||
stop
|
||||
})
|
||||
.collect();
|
||||
let m = to_doc * affine(g.transform);
|
||||
let (o, x, y) = (m * Point::ZERO, m * Point::new(1.0, 0.0), m * Point::new(0.0, 1.0));
|
||||
let kind = match g.kind {
|
||||
AfKind::Linear => GradientKind::Linear,
|
||||
AfKind::Radial => GradientKind::Radial,
|
||||
AfKind::Conical => {
|
||||
self.warn("conical gradients import as radial gradients");
|
||||
GradientKind::Radial
|
||||
}
|
||||
};
|
||||
let (u, v): (Vec2, Vec2) = (x - o, y - o);
|
||||
if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {
|
||||
self.warn("skewed elliptical gradients import as upright ellipses");
|
||||
}
|
||||
let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 };
|
||||
let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None };
|
||||
let mut gp = GradientPaint::new(Gradient { kind, stops });
|
||||
gp.angle = (-(u.y)).atan2(u.x).to_degrees();
|
||||
gp.geom = Some(geom);
|
||||
Some((Paint::Gradient(Box::new(gp)), 1.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn appearance(&mut self, fills: &[ap::Paint], strokes: &[ap::Stroke], to_doc: Affine) -> Appearance {
|
||||
let mut items = Vec::new();
|
||||
let mut above = Vec::new();
|
||||
for f in fills {
|
||||
if let Some((paint, opacity)) = self.paint(f, to_doc) {
|
||||
let mut l = FillLayer::new(paint);
|
||||
l.opacity = opacity;
|
||||
items.push(AppearanceItem::Fill(l));
|
||||
}
|
||||
}
|
||||
for s in strokes {
|
||||
let Some((paint, opacity)) = self.paint(&s.paint, to_doc) else { continue };
|
||||
let mut l = StrokeLayer::new(paint, s.width * self.k);
|
||||
l.opacity = opacity;
|
||||
l.cap = match s.cap {
|
||||
Cap::Butt => LineCap::Butt,
|
||||
Cap::Round => LineCap::Round,
|
||||
Cap::Square => LineCap::Square,
|
||||
};
|
||||
l.join = match s.join {
|
||||
Join::Miter => LineJoin::Miter,
|
||||
Join::Round => LineJoin::Round,
|
||||
Join::Bevel => LineJoin::Bevel,
|
||||
};
|
||||
l.miter_limit = s.miter_limit;
|
||||
l.align = match s.align {
|
||||
ap::Align::Center => StrokeAlign::Center,
|
||||
ap::Align::Inside => StrokeAlign::Inside,
|
||||
ap::Align::Outside => StrokeAlign::Outside,
|
||||
};
|
||||
l.dash = s.dash.as_ref().map(|(pattern, phase)| Dash {
|
||||
pattern: pattern.iter().map(|v| v * self.k).collect(),
|
||||
offset: phase * self.k,
|
||||
align_corners: false,
|
||||
});
|
||||
if s.behind {
|
||||
items.insert(0, AppearanceItem::Stroke(l));
|
||||
} else {
|
||||
above.push(AppearanceItem::Stroke(l));
|
||||
}
|
||||
}
|
||||
items.extend(above);
|
||||
Appearance { items, ..Appearance::default() }
|
||||
}
|
||||
|
||||
fn text(&mut self, t: &af::Text, to_doc: Affine) -> TextObject {
|
||||
let origin = match t.frame {
|
||||
Some(f) => Point::new(f.x0, f.y0),
|
||||
None => Point::new(t.anchor.x, t.anchor.y),
|
||||
};
|
||||
// Text space: origin at the anchor (or frame corner), the transform's uniform scale moved
|
||||
// into the type size so sizes read in points.
|
||||
let m = to_doc * affine(t.transform) * Affine::translate(origin.to_vec2());
|
||||
let c = m.as_coeffs();
|
||||
let k = (c[0] * c[3] - c[1] * c[2]).abs().sqrt().max(1e-9);
|
||||
let xf = m * Affine::scale(1.0 / k);
|
||||
let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default());
|
||||
obj.xf = xf;
|
||||
obj.runs = t
|
||||
.runs
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut style = CharStyle::default();
|
||||
if !r.family.is_empty() {
|
||||
style.font_family = r.family.clone();
|
||||
} else if !r.postscript.is_empty() {
|
||||
style.font_family = r.postscript.clone();
|
||||
} else {
|
||||
self.warn("text without a font name uses the default font");
|
||||
}
|
||||
// A family/weight pair cannot identify width variants such as Arial Narrow.
|
||||
// Resolve a known PostScript identity to the exact installed family and style.
|
||||
if let Some((family, face_style)) = vectorcraft_text::FontDb::global().by_postscript_name(&r.postscript) {
|
||||
style.font_family = family;
|
||||
style.font_style = face_style;
|
||||
} else {
|
||||
style.font_style = font_style(r.weight, r.italic);
|
||||
}
|
||||
style.features = r.features.clone();
|
||||
if r.features.iter().any(|feature| !vectorcraft_text::OtFeatures::known_tag(feature)) {
|
||||
self.warn("unsupported text OpenType features (retained but not rendered)");
|
||||
}
|
||||
style.all_caps = r.all_caps;
|
||||
style.size = r.size * k;
|
||||
style.leading = r.leading.map(|l| l * k);
|
||||
style.tracking = r.tracking * 1000.0;
|
||||
style.fill = match self.paint(&r.fill, to_doc) {
|
||||
Some((p, a)) => {
|
||||
if a < 0.999 {
|
||||
self.warn("translucent text colours import opaque");
|
||||
}
|
||||
p
|
||||
}
|
||||
None => Paint::None,
|
||||
};
|
||||
// Affinity separates paragraphs with U+2029 and lines with U+2028.
|
||||
TextRun::new(r.text.replace(['\u{2029}', '\u{2028}'], "\n"), style)
|
||||
})
|
||||
.collect();
|
||||
obj.para.justify = match t.align {
|
||||
AfAlign::Left => Justify::Left,
|
||||
AfAlign::Center => Justify::Center,
|
||||
AfAlign::Right => Justify::Right,
|
||||
AfAlign::Justify => Justify::JustifyLeft,
|
||||
};
|
||||
if let Some(f) = t.frame {
|
||||
obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, (f.x1 - f.x0) * k, (f.y1 - f.y0) * k)) };
|
||||
// Affinity shows a line in a frame shorter than it (#1423); here none of it would draw.
|
||||
if vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), &mut obj) {
|
||||
self.warn("text frames too short for their first line (made taller so the line shows)");
|
||||
}
|
||||
}
|
||||
obj
|
||||
}
|
||||
|
||||
fn image(&mut self, img: &af::Image, to_doc: Affine) -> Option<NodeKind> {
|
||||
let bytes = match &img.pixels {
|
||||
Pixels::Encoded(b) => b.clone(),
|
||||
Pixels::Rgba8(rgba) => {
|
||||
let buf = image::RgbaImage::from_raw(img.width, img.height, rgba.clone())?;
|
||||
let mut png = Vec::new();
|
||||
buf.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
png
|
||||
}
|
||||
};
|
||||
let r = match super::load::raster_image(&bytes) {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
self.warn("an embedded image that could not be decoded was left out");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// The pixel grid maps onto the Affinity image's own size, whatever the stored file's.
|
||||
let sx = img.width as f64 / f64::from(r.width.max(1));
|
||||
let sy = img.height as f64 / f64::from(r.height.max(1));
|
||||
let xf = to_doc * affine(img.transform) * Affine::scale_non_uniform(sx, sy);
|
||||
self.doc.images.entry(r.key.clone()).or_insert(r.blob);
|
||||
Some(NodeKind::Image(Box::new(ImageObject { key: r.key, width: r.width, height: r.height, xf, link: None, placement: Default::default() })))
|
||||
}
|
||||
}
|
||||
|
||||
fn font_style(weight: i64, italic: bool) -> String {
|
||||
let w = match weight {
|
||||
..=150 => "Thin",
|
||||
151..=250 => "ExtraLight",
|
||||
251..=325 => "Light",
|
||||
326..=450 => "Regular",
|
||||
451..=550 => "Medium",
|
||||
551..=650 => "SemiBold",
|
||||
651..=750 => "Bold",
|
||||
751..=850 => "ExtraBold",
|
||||
_ => "Black",
|
||||
};
|
||||
match (w, italic) {
|
||||
("Regular", true) => "Italic".into(),
|
||||
(w, true) => format!("{w} Italic"),
|
||||
(w, false) => w.into(),
|
||||
}
|
||||
/// How deep inside embedded Affinity documents the node being mapped is: their artboards
|
||||
/// are only clip groups, never artboards of this document.
|
||||
embedded: usize,
|
||||
/// Each master spread's art as shown on pages, in the order the masters are first used.
|
||||
masters: Vec<(usize, Vec<Arc<Node>>)>,
|
||||
/// The document's CMYK profile, until [`Builder::document_cmyk`] makes its table.
|
||||
cmyk_profile: Option<Vec<u8>>,
|
||||
/// That table, once made (`Some(None)`: there is none).
|
||||
cmyk_lut: Option<Option<Arc<vectorcraft_color::cms::CmykLut>>>,
|
||||
/// The working CMYK profile's table, once a CMYK pixel layer needs it.
|
||||
working_cmyk: Option<Arc<vectorcraft_color::cms::CmykLut>>,
|
||||
/// What baking colour and gradient overlays may still take ([`overlay::MAX_WORK`]).
|
||||
overlay_work: u64,
|
||||
/// What copying master pages onto the pages that show them may still take.
|
||||
copy_left: CopyCost,
|
||||
/// Each master spread's objects as its pages show them, made the first time one does.
|
||||
master_parts: std::collections::HashMap<usize, Arc<[MasterPart]>>,
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
use super::layout::{master_instances, master_prefix, page_masters};
|
||||
use super::master_copies::{CopyCost, MAX_MASTER_COPIES, MasterPart, copy_cost};
|
||||
use super::nodes::rect_of;
|
||||
use super::*;
|
||||
|
||||
impl Builder {
|
||||
pub(super) fn new(k: f64) -> Self {
|
||||
Self {
|
||||
doc: Document::new(0.0, 0.0),
|
||||
warnings: Vec::new(),
|
||||
k,
|
||||
layer: 0,
|
||||
embedded: 0,
|
||||
masters: Vec::new(),
|
||||
cmyk_profile: None,
|
||||
cmyk_lut: None,
|
||||
working_cmyk: None,
|
||||
overlay_work: vectorcraft_affinity::overlay::MAX_WORK,
|
||||
copy_left: MAX_MASTER_COPIES,
|
||||
master_parts: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) {
|
||||
self.warnings.push(w.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn document(&mut self, d: &af::Document) -> Result<()> {
|
||||
self.cmyk_profile = d.cmyk_profile.clone();
|
||||
// Spreads (Publisher pages) sit side by side, 36 pt apart; a single spread keeps its origin.
|
||||
let mut layers = Vec::new();
|
||||
let mut artboards = Vec::new();
|
||||
let mut x = 0.0;
|
||||
for (i, spread) in d.spreads.iter().enumerate() {
|
||||
let shift = if i == 0 { 0.0 } else { x - spread.bounds.x0 * self.k };
|
||||
let to_doc = Affine::translate((shift, 0.0)) * Affine::scale(self.k);
|
||||
let before = artboards.len();
|
||||
let mut loose: Vec<Arc<Node>> = Vec::new();
|
||||
for n in &spread.nodes {
|
||||
let top = match &n.kind {
|
||||
Kind::Layer => self.node(n, to_doc, &mut artboards, true, 0),
|
||||
Kind::Artboard { .. } => {
|
||||
self.node(n, to_doc, &mut artboards, true, 0).map(|art| self.layer_of(&n.name, art, n.visible, n.locked))
|
||||
}
|
||||
_ => {
|
||||
if let Some(art) = self.node(n, to_doc, &mut artboards, false, 0) {
|
||||
loose.push(art);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !loose.is_empty() {
|
||||
layers.push(self.layer_with(None, std::mem::take(&mut loose)));
|
||||
}
|
||||
layers.extend(top);
|
||||
}
|
||||
if !loose.is_empty() {
|
||||
layers.push(self.layer_with(None, loose));
|
||||
}
|
||||
self.master_pages(d, spread, to_doc);
|
||||
// Without artboards, each page (or the spread) becomes one.
|
||||
if artboards.len() == before {
|
||||
let rects = if spread.pages.is_empty() { vec![spread.bounds] } else { spread.pages.clone() };
|
||||
for r in rects {
|
||||
let name = format!("{} {}", if d.spreads.len() > 1 || spread.pages.len() > 1 { "Page" } else { "Artboard" }, artboards.len() + 1);
|
||||
artboards.push((name, to_doc.transform_rect_bbox(rect_of(r))));
|
||||
}
|
||||
}
|
||||
// (Earlier spreads' artboards are all left of `x` already.)
|
||||
x = artboards.get(before..).unwrap_or_default().iter().map(|(_, r)| r.x1).fold(x, f64::max) + 36.0;
|
||||
if spread.transparent && i == 0 {
|
||||
self.warn("transparent page backgrounds show as white artboards");
|
||||
}
|
||||
}
|
||||
self.doc.artboards = artboards
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, r))| r.width() > 0.0 && r.height() > 0.0)
|
||||
.map(|(i, (name, rect))| Artboard {
|
||||
id: i as u32 + 1,
|
||||
name,
|
||||
rect,
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
})
|
||||
.collect();
|
||||
if self.doc.artboards.is_empty() {
|
||||
return Err(err("the Affinity document has no page with a size"));
|
||||
}
|
||||
// Master pages are behind everything on the pages that show them.
|
||||
let mut masters = std::mem::take(&mut self.masters);
|
||||
masters.sort_by_key(|(m, _)| *m);
|
||||
let mut bottom = Vec::new();
|
||||
for (m, art) in masters {
|
||||
let mut l = (*self.layer_with(Some(&format!("Master {}", master_prefix(m))), art)).clone();
|
||||
l.locked = true;
|
||||
bottom.push(Arc::new(l));
|
||||
}
|
||||
// Bottom to top, as Affinity lists them.
|
||||
bottom.extend(layers);
|
||||
self.doc.layers = bottom;
|
||||
if self.doc.layers.is_empty() {
|
||||
let empty = self.layer_with(None, Vec::new());
|
||||
self.doc.layers.push(empty);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The master pages `spread`'s pages show, placed on those pages (`to_doc` places the spread).
|
||||
/// Each master page shows only the objects on it, moved from its page to the one showing it.
|
||||
fn master_pages(&mut self, d: &af::Document, spread: &af::Spread, to_doc: Affine) {
|
||||
let instances = master_instances(&spread.nodes);
|
||||
if instances.is_empty() {
|
||||
return;
|
||||
}
|
||||
let owners = page_masters(&instances, spread.pages.len());
|
||||
for (pi, page) in spread.pages.iter().enumerate() {
|
||||
let Some(&Some((master, first, master_page))) = owners.get(pi) else { continue };
|
||||
let Some(m) = d.masters.get(master) else { continue };
|
||||
let index = master_page.saturating_add(pi.saturating_sub(first));
|
||||
let r = m.pages.get(index).or_else(|| m.pages.last()).copied().unwrap_or(m.bounds);
|
||||
let parts = self.master_parts(master, m);
|
||||
let on_page = |b: &Option<af::Rect>| b.is_some_and(|b| b.x1 > r.x0 && b.x0 < r.x1 && b.y1 > r.y0 && b.y0 < r.y1);
|
||||
// Looking through the master's objects takes one each, copying them what they hold.
|
||||
let looked = CopyCost { work: parts.len() as u64, pixels: 0 };
|
||||
let cost = parts.iter().filter(|p| on_page(&p.bounds)).fold(looked, |c, p| c.plus(p.cost));
|
||||
let Some(left) = self.copy_left.minus(cost) else {
|
||||
self.warn("master pages shown on more pages than one import copies them to (left out on the rest)");
|
||||
return;
|
||||
};
|
||||
self.copy_left = left;
|
||||
let place = to_doc * Affine::translate((page.x0 - r.x0, page.y0 - r.y0));
|
||||
let mut art = Vec::new();
|
||||
let mut boards = Vec::new();
|
||||
self.embedded += 1;
|
||||
let mut i = 0;
|
||||
while let Some(p) = parts.get(i).copied() {
|
||||
let Some(n) = m.nodes.get(p.node) else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
if p.child.is_none() {
|
||||
if on_page(&p.bounds) {
|
||||
art.extend(self.node(n, place, &mut boards, false, 0));
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// A layer of the master spread: just its objects on this page.
|
||||
let mut kids: Vec<Arc<Node>> = Vec::new();
|
||||
while let Some(q) = parts.get(i).copied().filter(|q| q.node == p.node) {
|
||||
if on_page(&q.bounds)
|
||||
&& let Some(c) = q.child.and_then(|c| n.children.get(c))
|
||||
{
|
||||
kids.extend(self.node(c, place, &mut boards, false, 1));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if !kids.is_empty() {
|
||||
let mut g = self.base(n, NodeKind::Group { children: kids, clip: false });
|
||||
g.isolate = n.blend != Blend::PassThrough;
|
||||
art.push(Arc::new(g));
|
||||
}
|
||||
}
|
||||
self.embedded -= 1;
|
||||
if art.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut g = Node::group(self.doc.alloc_id(), art);
|
||||
g.name = Some(format!("Master {} (page {})", master_prefix(master), pi + 1));
|
||||
match self.masters.iter_mut().find(|(i, _)| *i == master) {
|
||||
Some((_, v)) => v.push(Arc::new(g)),
|
||||
None => self.masters.push((master, vec![Arc::new(g)])),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects of master spread `m` (number `index`) as its pages show them: its layers'
|
||||
/// objects one by one and its other top-level objects, with their bounds and costs.
|
||||
fn master_parts(&mut self, index: usize, m: &af::Spread) -> Arc<[MasterPart]> {
|
||||
if let Some(parts) = self.master_parts.get(&index) {
|
||||
return parts.clone();
|
||||
}
|
||||
if !master_instances(&m.nodes).is_empty() {
|
||||
self.warn("master pages based on other master pages (only their own objects are used)");
|
||||
}
|
||||
let part = |node: usize, child: Option<usize>, n: &af::Node| MasterPart {
|
||||
node,
|
||||
child,
|
||||
bounds: af::nodes_bounds(std::slice::from_ref(n)),
|
||||
cost: copy_cost(n, 0),
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
for (i, n) in m.nodes.iter().enumerate() {
|
||||
if matches!(n.kind, Kind::Layer) {
|
||||
parts.extend(n.children.iter().enumerate().map(|(c, child)| part(i, Some(c), child)));
|
||||
} else {
|
||||
parts.push(part(i, None, n));
|
||||
}
|
||||
}
|
||||
let parts: Arc<[MasterPart]> = parts.into();
|
||||
self.master_parts.insert(index, parts.clone());
|
||||
parts
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
use super::*;
|
||||
|
||||
/// What an Affinity file opened as.
|
||||
pub(in super::super) struct Imported {
|
||||
pub doc: Document,
|
||||
pub warnings: Vec<String>,
|
||||
/// Only the embedded preview: never placed, used as a template or mined for styles.
|
||||
pub preview_only: bool,
|
||||
}
|
||||
|
||||
pub(in super::super) fn import(name: &str, bytes: &[u8]) -> Result<Imported> {
|
||||
match vectorcraft_affinity::read(bytes, vectorcraft_affinity::Limits::default()) {
|
||||
Ok(d) => {
|
||||
let mut b = Builder::new(72.0 / d.dpi);
|
||||
b.document(&d)?;
|
||||
b.doc.limit_depth_noting(&mut b.warnings);
|
||||
let mut warnings = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect::<Vec<_>>();
|
||||
warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}.")));
|
||||
Ok(Imported { doc: b.doc, warnings, preview_only: false })
|
||||
}
|
||||
Err(native) => {
|
||||
let (doc, w) = preview(name, bytes, &native)?;
|
||||
Ok(Imported { doc, warnings: vec![w], preview_only: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The embedded preview, for files whose native document can't be read.
|
||||
fn preview(name: &str, bytes: &[u8], native: &vectorcraft_affinity::Error) -> Result<(Document, String)> {
|
||||
let p = vectorcraft_affinity::preview(bytes).map_err(|e| err(format!("{native}; its embedded preview can't be read either ({e})")))?;
|
||||
// `raster_doc` normally probes PNG dimensions and keeps its encoded bytes. Verify this
|
||||
// untrusted preview's complete pixels first, so corrupt data cannot create a blank image.
|
||||
let mut reader = image::ImageReader::with_format(Cursor::new(p.png), image::ImageFormat::Png);
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(4096);
|
||||
limits.max_image_height = Some(4096);
|
||||
limits.max_alloc = Some(128 << 20);
|
||||
reader.limits(limits);
|
||||
let _pixels = reader.decode().map_err(err)?;
|
||||
let d = raster_doc(name, p.png)?;
|
||||
Ok((
|
||||
d,
|
||||
format!(
|
||||
"The native Affinity document could not be read ({native}). Opened only its embedded {}×{} PNG preview, which may be smaller than the document: no layers, vectors, text or pages. Save a new copy; the Affinity source cannot be saved back. Export SVG or PDF from Affinity for editable vectors.",
|
||||
p.width, p.height
|
||||
),
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use super::nodes::MAX_DEPTH;
|
||||
use super::*;
|
||||
|
||||
/// The master page instances among `nodes` (also inside layers and groups): (master, first page,
|
||||
/// first master page, page count).
|
||||
pub(super) fn master_instances(nodes: &[af::Node]) -> Vec<(usize, usize, usize, usize)> {
|
||||
fn visit(n: &af::Node, depth: usize, out: &mut Vec<(usize, usize, usize, usize)>) {
|
||||
if depth > MAX_DEPTH || !n.visible {
|
||||
return;
|
||||
}
|
||||
match n.kind {
|
||||
Kind::MasterInstance { master, page, master_page, count } => out.push((master, page, master_page, count)),
|
||||
Kind::Layer | Kind::Group => n.children.iter().for_each(|c| visit(c, depth + 1, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
nodes.iter().for_each(|n| visit(n, 0, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
/// Which master page instance each of `pages` pages shows: (master, first page, first master
|
||||
/// page) of the first instance in `instances` that covers it. Each page is settled once (the
|
||||
/// next page still open is found by a path-halving jump), so this is about linear in pages and
|
||||
/// instances however much their ranges overlap.
|
||||
pub(super) fn page_masters(instances: &[(usize, usize, usize, usize)], pages: usize) -> Vec<Option<(usize, usize, usize)>> {
|
||||
fn open_from(next: &mut [usize], mut i: usize) -> usize {
|
||||
while let Some(&n) = next.get(i) {
|
||||
if n == i {
|
||||
break;
|
||||
}
|
||||
let skip = next.get(n).copied().unwrap_or(n);
|
||||
if let Some(slot) = next.get_mut(i) {
|
||||
*slot = skip;
|
||||
}
|
||||
i = n;
|
||||
}
|
||||
i
|
||||
}
|
||||
let mut owner = vec![None; pages];
|
||||
// `next[p]` leads towards the first page from `p` on with no master yet (`pages`: none).
|
||||
let mut next: Vec<usize> = (0..=pages).collect();
|
||||
for &(master, first, master_page, count) in instances {
|
||||
let end = first.saturating_add(count).min(pages);
|
||||
let mut p = open_from(&mut next, first.min(pages));
|
||||
while p < end {
|
||||
if let Some(o) = owner.get_mut(p) {
|
||||
*o = Some((master, first, master_page));
|
||||
}
|
||||
if let Some(n) = next.get_mut(p) {
|
||||
*n = p + 1;
|
||||
}
|
||||
p = open_from(&mut next, p + 1);
|
||||
}
|
||||
}
|
||||
owner
|
||||
}
|
||||
|
||||
/// Master names: A, B … Z, then A1, B1 ….
|
||||
pub(super) fn master_prefix(index: usize) -> String {
|
||||
let letter = char::from(b'A' + (index % 26) as u8);
|
||||
match index / 26 {
|
||||
0 => letter.to_string(),
|
||||
n => format!("{letter}{n}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A table cell's text `w` × `h` at the origin, placed as Affinity places it. Affinity aligns the
|
||||
/// block from the first line's capitals' tops to the last baseline in the cell, and draws it even
|
||||
/// where it doesn't fit (centred cells measured on a document's thumbnail: two lines in a cell
|
||||
/// shorter than them reach out of it at both ends). VectorCraft aligns the block down to the last
|
||||
/// line's descenders and keeps lines inside the frame: the frame moves by what this returns (down
|
||||
/// the cell) and grows where the lines need more room.
|
||||
pub(super) fn place_cell(obj: &mut TextObject, w: f64, h: f64) -> f64 {
|
||||
let share = match obj.area.vertical_align {
|
||||
VerticalAlign::Center => 0.5,
|
||||
VerticalAlign::Bottom => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
let mut tall = obj.clone();
|
||||
tall.area.vertical_align = VerticalAlign::Top;
|
||||
tall.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h * 4.0 + 10_000.0)) };
|
||||
let lines = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tall).lines;
|
||||
let Some(last) = lines.iter().rfind(|l| l.region == 0) else { return 0.0 };
|
||||
let (baseline, descent) = (last.baseline, last.descent);
|
||||
if !(baseline.is_finite() && descent.is_finite() && h.is_finite()) {
|
||||
return 0.0;
|
||||
}
|
||||
// (A little more than the lines need, for the rounding of the layout.)
|
||||
let frame = h.max(baseline + descent + 0.05);
|
||||
obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, frame)) };
|
||||
// Where Affinity has the block's top, less where VectorCraft puts it in the frame.
|
||||
(h - baseline) * share - (frame - baseline - descent) * share
|
||||
}
|
||||
|
||||
/// Area type `w` × `h` at the origin whose lines don't all fit. Affinity shows each line whose
|
||||
/// baseline is inside the frame, its descenders hanging out of it; VectorCraft's area type leaves
|
||||
/// such a line out. The frame is made taller, from its top, by what those lines need. Whether it was.
|
||||
pub(super) fn fit_lines(obj: &mut TextObject, w: f64, h: f64) -> bool {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
if !(w > 0.0 && h > 0.0 && h.is_finite()) {
|
||||
return false;
|
||||
}
|
||||
let first = vectorcraft_text::layout(db, obj);
|
||||
if !first.overflow {
|
||||
return false;
|
||||
}
|
||||
// Where the lines go in a frame with room for all of them.
|
||||
let mut tall = obj.clone();
|
||||
tall.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h * 4.0 + 10_000.0)) };
|
||||
let need = vectorcraft_text::layout(db, &tall)
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|l| l.region == 0 && l.baseline <= h + 1e-6)
|
||||
.map(|l| l.baseline + l.descent)
|
||||
.filter(|b| b.is_finite())
|
||||
.fold(0.0, f64::max);
|
||||
if need <= h {
|
||||
return false;
|
||||
}
|
||||
let before = first.lines.len();
|
||||
// (A little more than they need, for the rounding of the layout.)
|
||||
let short = std::mem::replace(&mut obj.kind, TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, need + 0.05)) });
|
||||
// Something else keeps the lines out: as the source has it.
|
||||
if vectorcraft_text::layout(db, obj).lines.len() <= before {
|
||||
obj.kind = short;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// RGBA pixels as a PNG file.
|
||||
pub(super) fn png(width: u32, height: u32, rgba: Vec<u8>) -> Option<Vec<u8>> {
|
||||
let buf = image::RgbaImage::from_raw(width, height, rgba)?;
|
||||
let mut png = Vec::new();
|
||||
buf.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some(png)
|
||||
}
|
||||
|
||||
/// Where a line of `w` starts in a span from 0 to `room` (as a share of `room - w`).
|
||||
fn share(j: Justify) -> f64 {
|
||||
match j {
|
||||
Justify::Center | Justify::JustifyCenter => 0.5,
|
||||
Justify::Right | Justify::JustifyRight => 1.0,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Artistic text whose paragraphs are aligned differently. Affinity aligns each line within the
|
||||
/// width of the longest, and places that block at the anchor by the text's own alignment (its
|
||||
/// first paragraph's); VectorCraft's point type aligns each line on the anchor. Indents move the
|
||||
/// lines to where Affinity has them and keep their alignment: a centred line centres between its
|
||||
/// indents and a right-aligned one ends at its right indent, whatever its width.
|
||||
pub(super) fn align_lines(obj: &mut TextObject) {
|
||||
let block = share(obj.para.justify);
|
||||
if obj.paras.iter().all(|p| share(p.justify) == block) {
|
||||
return;
|
||||
}
|
||||
let lines = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), obj).lines;
|
||||
let w = lines.iter().map(|l| l.x1 - l.x0).filter(|w| w.is_finite()).fold(0.0, f64::max);
|
||||
if !(w > 0.0 && w < 1e6) {
|
||||
return;
|
||||
}
|
||||
// The block's left edge, from the anchor.
|
||||
let left = -w * block;
|
||||
for p in &mut obj.paras {
|
||||
let at = share(p.justify);
|
||||
let shift = left + w * at;
|
||||
// A left-aligned line starts at its left indent, a right-aligned one ends at minus its right
|
||||
// indent, and a centred one centres on half their difference.
|
||||
if at < 0.25 {
|
||||
p.left_indent += shift;
|
||||
} else if at > 0.75 {
|
||||
p.right_indent -= shift;
|
||||
} else {
|
||||
p.left_indent += shift;
|
||||
p.right_indent -= shift;
|
||||
}
|
||||
}
|
||||
if let Some(first) = obj.paras.first() {
|
||||
obj.para = first.clone();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn justify(a: AfAlign) -> Justify {
|
||||
match a {
|
||||
AfAlign::Left => Justify::Left,
|
||||
AfAlign::Center => Justify::Center,
|
||||
AfAlign::Right => Justify::Right,
|
||||
AfAlign::Justify => Justify::JustifyLeft,
|
||||
}
|
||||
}
|
||||
|
||||
/// A font's line gap in em, as VectorCraft will set it (the installed face, or the fallback for
|
||||
/// a missing one); 0 when no font is loaded.
|
||||
pub(super) fn line_gap(family: &str, style: &str) -> f64 {
|
||||
let defaults = CharStyle::default();
|
||||
let family = if family.is_empty() { defaults.font_family.as_str() } else { family };
|
||||
let style = if style.is_empty() { defaults.font_style.as_str() } else { style };
|
||||
let Some(face) = vectorcraft_text::FontDb::global().face(family, style) else { return 0.0 };
|
||||
let upem = face.units_per_em();
|
||||
let gap = if upem > 0.0 { face.line_gap() / upem } else { 0.0 };
|
||||
if gap.is_finite() { gap.clamp(0.0, 2.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
pub(super) fn font_style(weight: i64, italic: bool) -> String {
|
||||
let w = match weight {
|
||||
..=150 => "Thin",
|
||||
151..=250 => "ExtraLight",
|
||||
251..=325 => "Light",
|
||||
326..=450 => "Regular",
|
||||
451..=550 => "Medium",
|
||||
551..=650 => "SemiBold",
|
||||
651..=750 => "Bold",
|
||||
751..=850 => "ExtraBold",
|
||||
_ => "Black",
|
||||
};
|
||||
match (w, italic) {
|
||||
("Regular", true) => "Italic".into(),
|
||||
(w, true) => format!("{w} Italic"),
|
||||
(w, false) => w.into(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use super::nodes::MAX_DEPTH;
|
||||
use super::*;
|
||||
|
||||
/// What copying a subtree takes: its nodes, characters and table cells (`work`), and its pixels.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(super) struct CopyCost {
|
||||
pub(super) work: u64,
|
||||
pub(super) pixels: u64,
|
||||
}
|
||||
|
||||
impl CopyCost {
|
||||
pub(super) fn plus(self, o: CopyCost) -> CopyCost {
|
||||
CopyCost { work: self.work.saturating_add(o.work), pixels: self.pixels.saturating_add(o.pixels) }
|
||||
}
|
||||
pub(super) fn minus(self, o: CopyCost) -> Option<CopyCost> {
|
||||
Some(CopyCost { work: self.work.checked_sub(o.work)?, pixels: self.pixels.checked_sub(o.pixels)? })
|
||||
}
|
||||
}
|
||||
|
||||
/// Master page copies of one import together: as many objects, characters and pixels as a
|
||||
/// document may hold, a few times over. A master shown on thousands of pages, or a huge one
|
||||
/// on many, would otherwise multiply them.
|
||||
pub(super) const MAX_MASTER_COPIES: CopyCost = CopyCost { work: 1 << 23, pixels: 512 << 20 };
|
||||
|
||||
/// One object a master spread shows on the pages that show it: a top-level node of the spread
|
||||
/// (`child` `None`) or one object in one of its layers, with its bounds and what copying it takes.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct MasterPart {
|
||||
pub(super) node: usize,
|
||||
pub(super) child: Option<usize>,
|
||||
pub(super) bounds: Option<af::Rect>,
|
||||
pub(super) cost: CopyCost,
|
||||
}
|
||||
|
||||
pub(super) fn copy_cost(n: &af::Node, depth: usize) -> CopyCost {
|
||||
if depth > MAX_DEPTH {
|
||||
return CopyCost::default();
|
||||
}
|
||||
let len = |runs: &[af::TextRun]| runs.iter().map(|r| r.text.len() as u64).sum::<u64>();
|
||||
let own = match &n.kind {
|
||||
Kind::Text(t) => CopyCost { work: 1 + len(&t.runs), pixels: 0 },
|
||||
Kind::Table(t) => CopyCost { work: 1 + t.cells.iter().map(|c| 1 + len(&c.runs)).sum::<u64>(), pixels: 0 },
|
||||
Kind::Image(img) => CopyCost { work: 1, pixels: u64::from(img.width) * u64::from(img.height) },
|
||||
_ => CopyCost { work: 1, pixels: 0 },
|
||||
};
|
||||
n.children.iter().fold(own, |c, ch| c.plus(copy_cost(ch, depth + 1)))
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
use super::*;
|
||||
|
||||
/// Deepest node tree mapped (the reader bounds trees well below this).
|
||||
pub(super) const MAX_DEPTH: usize = 160;
|
||||
|
||||
pub(super) fn rect_of(r: af::Rect) -> Rect {
|
||||
Rect::new(r.x0, r.y0, r.x1, r.y1)
|
||||
}
|
||||
|
||||
pub(super) fn affine(a: af::Affine) -> Affine {
|
||||
Affine::new(a.0)
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
pub(super) fn layer_with(&mut self, name: Option<&str>, children: Vec<Arc<Node>>) -> Arc<Node> {
|
||||
let id = self.doc.alloc_id();
|
||||
self.layer = self.layer.wrapping_add(1);
|
||||
let label = name.map(str::to_string).unwrap_or_else(|| format!("Layer {}", self.layer));
|
||||
let mut n = Node::layer(id, &label, LayerColor::Preset(self.layer % 9));
|
||||
if let Some(c) = n.children_mut() {
|
||||
*c = children;
|
||||
}
|
||||
Arc::new(n)
|
||||
}
|
||||
|
||||
/// An artboard at the top level becomes a layer of its name holding its clip group.
|
||||
pub(super) fn layer_of(&mut self, name: &str, art: Arc<Node>, visible: bool, locked: bool) -> Arc<Node> {
|
||||
let mut l = (*self.layer_with(Some(if name.is_empty() { "Artboard" } else { name }), vec![art])).clone();
|
||||
l.visible = visible;
|
||||
l.locked = locked;
|
||||
Arc::new(l)
|
||||
}
|
||||
|
||||
pub(super) fn base(&mut self, n: &af::Node, kind: NodeKind) -> Node {
|
||||
let mut out = Node::new(self.doc.alloc_id(), kind);
|
||||
out.name = (!n.name.is_empty()).then(|| n.name.clone());
|
||||
out.visible = n.visible;
|
||||
out.locked = n.locked;
|
||||
out.opacity = n.opacity as f32;
|
||||
out.blend = self.blend(n.blend);
|
||||
out
|
||||
}
|
||||
|
||||
fn blend(&mut self, b: Blend) -> BlendMode {
|
||||
match b {
|
||||
Blend::Normal | Blend::PassThrough => BlendMode::Normal,
|
||||
Blend::Darken => BlendMode::Darken,
|
||||
Blend::Multiply => BlendMode::Multiply,
|
||||
Blend::ColorBurn => BlendMode::ColorBurn,
|
||||
Blend::Lighten => BlendMode::Lighten,
|
||||
Blend::Screen => BlendMode::Screen,
|
||||
Blend::ColorDodge => BlendMode::ColorDodge,
|
||||
Blend::Overlay => BlendMode::Overlay,
|
||||
Blend::SoftLight => BlendMode::SoftLight,
|
||||
Blend::HardLight => BlendMode::HardLight,
|
||||
Blend::Difference => BlendMode::Difference,
|
||||
Blend::Exclusion => BlendMode::Exclusion,
|
||||
Blend::Hue => BlendMode::Hue,
|
||||
Blend::Saturation => BlendMode::Saturation,
|
||||
Blend::Color => BlendMode::Color,
|
||||
Blend::Luminosity => BlendMode::Luminosity,
|
||||
_ => {
|
||||
self.warn("blend modes VectorCraft doesn't have (Add, Linear Light, Vivid Light, Pin Light, Hard Mix, Subtract, Darker/Lighter Colour, Average, Negation, Reflect, Glow, Erase) import as Normal");
|
||||
BlendMode::Normal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` with its colour and gradient overlays baked into its paint and pixels (VectorCraft has
|
||||
/// no overlay effect).
|
||||
fn overlaid<'n>(&mut self, n: &'n af::Node) -> std::borrow::Cow<'n, af::Node> {
|
||||
// Each kind of message once, however often it is heard.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let mut work = self.overlay_work;
|
||||
let out = vectorcraft_affinity::overlay::apply(n, &mut work, &mut |w| {
|
||||
if !warnings.iter().any(|x| x == w) {
|
||||
warnings.push(w.to_string());
|
||||
}
|
||||
});
|
||||
self.overlay_work = work;
|
||||
for w in warnings {
|
||||
self.warn(&w);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One Affinity node (and its subtree) as VectorCraft art; `to_doc` maps document pixels to
|
||||
/// points. `layer_level`: the node is directly in a spread or a layer, so a layer stays a layer.
|
||||
pub(super) fn node(
|
||||
&mut self,
|
||||
n: &af::Node,
|
||||
to_doc: Affine,
|
||||
boards: &mut Vec<(String, Rect)>,
|
||||
layer_level: bool,
|
||||
depth: usize,
|
||||
) -> Option<Arc<Node>> {
|
||||
if depth > MAX_DEPTH {
|
||||
self.warn("objects nested too deeply (left out)");
|
||||
return None;
|
||||
}
|
||||
// VectorCraft documents stay within `MAX_COORD` of the origin (renderers and exports rely
|
||||
// on it): objects reaching beyond it are left out.
|
||||
if let Some(b) = af::kind_bounds(&n.kind) {
|
||||
let r = to_doc.transform_rect_bbox(rect_of(b));
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD) {
|
||||
self.warn("objects beyond the document range VectorCraft supports (left out)");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let n = &*self.overlaid(n);
|
||||
// Register before descending so nested artboards keep their document order. Inside an
|
||||
// embedded document an artboard is just its content's frame.
|
||||
if let Kind::Artboard { rect, .. } = &n.kind
|
||||
&& self.embedded == 0
|
||||
{
|
||||
boards.push((
|
||||
if n.name.is_empty() { format!("Artboard {}", boards.len() + 1) } else { n.name.clone() },
|
||||
to_doc.transform_rect_bbox(rect_of(*rect)),
|
||||
));
|
||||
}
|
||||
let child_level = matches!(n.kind, Kind::Layer) && layer_level;
|
||||
let embeds = n.class == vectorcraft_affinity::stream::Tag::of(b"EmbN");
|
||||
self.embedded += usize::from(embeds);
|
||||
let children: Vec<Arc<Node>> = n.children.iter().filter_map(|c| self.node(c, to_doc, boards, child_level, depth + 1)).collect();
|
||||
self.embedded -= usize::from(embeds);
|
||||
let mut out = match &n.kind {
|
||||
Kind::Layer if layer_level => {
|
||||
let mut l = (*self.layer_with(Some(if n.name.is_empty() { "Layer" } else { &n.name }), children)).clone();
|
||||
l.visible = n.visible;
|
||||
l.locked = n.locked;
|
||||
l.opacity = n.opacity as f32;
|
||||
l.blend = self.blend(n.blend);
|
||||
l
|
||||
}
|
||||
Kind::Layer | Kind::Group => {
|
||||
let mut g = self.base(n, NodeKind::Group { children, clip: false });
|
||||
// Affinity groups isolate their blending unless they pass through.
|
||||
g.isolate = n.blend != Blend::PassThrough;
|
||||
g
|
||||
}
|
||||
Kind::Shape { path, fills, strokes, even_odd } => {
|
||||
let data = self.path(path, to_doc);
|
||||
let rule = if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero };
|
||||
let mut appearance = self.appearance(fills, strokes, to_doc);
|
||||
// An outline effect on a shape is one more stroke.
|
||||
self.outline_stroke(&n.effects, &mut appearance);
|
||||
if children.is_empty() {
|
||||
let mut p = self.base(n, NodeKind::Path { path: data, rule, live: None, clipping: false, guide: false });
|
||||
p.appearance = appearance.into();
|
||||
p
|
||||
} else {
|
||||
// A shape clips its children: VectorCraft's clipping path keeps its paint, its
|
||||
// fill behind the clipped art and its stroke over it, as Affinity draws it.
|
||||
let mut clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path: data, rule, live: None, clipping: true, guide: false });
|
||||
clip.appearance = appearance.into();
|
||||
let mut kids = vec![Arc::new(clip)];
|
||||
kids.extend(children);
|
||||
self.base(n, NodeKind::Group { children: kids, clip: true })
|
||||
}
|
||||
}
|
||||
Kind::Artboard { path, even_odd, background, strokes, .. } => {
|
||||
let mut clip = Node::new(
|
||||
self.doc.alloc_id(),
|
||||
NodeKind::Path {
|
||||
path: self.path(path, to_doc),
|
||||
rule: if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero },
|
||||
live: None,
|
||||
clipping: true,
|
||||
guide: false,
|
||||
},
|
||||
);
|
||||
clip.appearance = self.appearance(background, strokes, to_doc).into();
|
||||
let mut kids = vec![Arc::new(clip)];
|
||||
kids.extend(children);
|
||||
let mut g = self.base(n, NodeKind::Group { children: kids, clip: true });
|
||||
g.name = Some(if n.name.is_empty() { "Artboard".into() } else { n.name.clone() });
|
||||
g
|
||||
}
|
||||
Kind::Text(t) => {
|
||||
let Some((mut text, alpha)) = self.text(t, to_doc) else {
|
||||
// The text is left out (warned); what it holds still comes in.
|
||||
if children.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let g = self.base(n, NodeKind::Group { children, clip: false });
|
||||
return Some(Arc::new(g));
|
||||
};
|
||||
self.outline_text(&n.effects, &mut text);
|
||||
let mut node = self.base(n, NodeKind::Text(Box::new(text)));
|
||||
node.opacity *= alpha;
|
||||
if !children.is_empty() {
|
||||
let mut kids = vec![Arc::new(node)];
|
||||
kids.extend(children);
|
||||
node = Node::group(self.doc.alloc_id(), kids);
|
||||
}
|
||||
node
|
||||
}
|
||||
Kind::Table(t) => {
|
||||
let mut kids = self.table(t, to_doc);
|
||||
if kids.is_empty() && children.is_empty() {
|
||||
return None;
|
||||
}
|
||||
kids.extend(children);
|
||||
let mut g = self.base(n, NodeKind::Group { children: kids, clip: false });
|
||||
g.name.get_or_insert_with(|| "Table".into());
|
||||
g
|
||||
}
|
||||
Kind::Image(img) => match self.image(img, to_doc) {
|
||||
Some(kind) => self.base(n, kind),
|
||||
None if children.is_empty() => return None,
|
||||
None => self.base(n, NodeKind::Group { children, clip: false }),
|
||||
},
|
||||
// Shown on the pages through the master's layer (see `master_pages`).
|
||||
Kind::MasterInstance { .. } => return None,
|
||||
Kind::Unsupported if children.is_empty() => return None,
|
||||
Kind::Unsupported => self.base(n, NodeKind::Group { children, clip: false }),
|
||||
};
|
||||
if !matches!(n.kind, Kind::Shape { .. } | Kind::Text(_)) && n.effects.iter().any(|e| matches!(e, af::Effect::Outline { .. })) {
|
||||
self.warn("outline effects on groups, images and tables (left out)");
|
||||
}
|
||||
if let Some(img) = &n.pixel_mask {
|
||||
// A pixel mask: its grey levels show (white) or hide (black) the node, and nothing
|
||||
// shows outside it, as an opacity mask that clips.
|
||||
if let Some(kind) = self.image(img, to_doc) {
|
||||
let art = Node::new(self.doc.alloc_id(), kind);
|
||||
out.extras_mut().mask = Some(Box::new(OpacityMask::new(art, true)));
|
||||
}
|
||||
}
|
||||
if let Some(mask) = &n.mask {
|
||||
// A vector mask: the node shows only inside it.
|
||||
let clip = Node::new(
|
||||
self.doc.alloc_id(),
|
||||
NodeKind::Path { path: self.path(mask, to_doc), rule: FillRule::NonZero, live: None, clipping: true, guide: false },
|
||||
);
|
||||
let (opacity, blend, visible, name) = (out.opacity, out.blend, out.visible, out.name.clone());
|
||||
out.opacity = 1.0;
|
||||
out.blend = BlendMode::Normal;
|
||||
let mut g = Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(out)], clip: true });
|
||||
(g.opacity, g.blend, g.visible, g.name) = (opacity, blend, visible, name);
|
||||
out = g;
|
||||
}
|
||||
// Shadows and glows apply to what the node shows, mask and all.
|
||||
let fx = self.effects(&n.effects);
|
||||
if !fx.is_empty() {
|
||||
out.appearance.effects.extend(fx);
|
||||
}
|
||||
Some(Arc::new(out))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
use super::layout::png;
|
||||
use super::nodes::affine;
|
||||
use super::text::Placement;
|
||||
use super::*;
|
||||
|
||||
impl Builder {
|
||||
/// Drop shadows, inner shadows and outer glows as VectorCraft's Stylize effects. Affinity's
|
||||
/// blur radius sets the same Gaussian as VectorCraft's blur (σ = half of it), and its angle
|
||||
/// is the direction the shadow goes in.
|
||||
pub(super) fn effects(&mut self, effects: &[af::Effect]) -> Vec<Effect> {
|
||||
let k = self.k;
|
||||
let len = move |v: f64| if v.is_finite() { (v * k).clamp(0.0, 1000.0) } else { 0.0 };
|
||||
let num = |v: f64| (v * 1000.0).round() / 1000.0;
|
||||
let mut out = Vec::new();
|
||||
for e in effects {
|
||||
let (id, params) = match e {
|
||||
af::Effect::DropShadow { color, opacity, radius, distance, angle } => {
|
||||
let (color, alpha) = Self::color(*color);
|
||||
let d = len(*distance);
|
||||
let a = if angle.is_finite() { *angle } else { 0.0 };
|
||||
let p = json!({
|
||||
"mode": "normal",
|
||||
"opacity": num(opacity * f64::from(alpha) * 100.0),
|
||||
"x": num(d * a.cos()),
|
||||
"y": num(d * a.sin()),
|
||||
"blur": num(len(*radius)),
|
||||
"color": color,
|
||||
});
|
||||
("stylize.dropShadow", p)
|
||||
}
|
||||
af::Effect::InnerShadow { color, opacity, radius, distance, .. } => {
|
||||
self.warn("inner shadows (imported as inner glows at the edge, without their offset)");
|
||||
let (color, alpha) = Self::color(*color);
|
||||
let p = json!({
|
||||
"mode": "normal",
|
||||
"opacity": num(opacity * f64::from(alpha) * 100.0),
|
||||
"blur": num(len(*radius) + len(*distance)),
|
||||
"color": color,
|
||||
"source": "edge",
|
||||
});
|
||||
("stylize.innerGlow", p)
|
||||
}
|
||||
af::Effect::OuterGlow { color, opacity, radius } => {
|
||||
let (color, alpha) = Self::color(*color);
|
||||
let p =
|
||||
json!({ "mode": "normal", "opacity": num(opacity * f64::from(alpha) * 100.0), "blur": num(len(*radius)), "color": color });
|
||||
("stylize.outerGlow", p)
|
||||
}
|
||||
af::Effect::Bevel { .. } => {
|
||||
self.warn("bevel and emboss effects (left out)");
|
||||
continue;
|
||||
}
|
||||
// Outlines become strokes (`outline_stroke`, `outline_text`), overlays are baked
|
||||
// into the paint (`overlaid`).
|
||||
af::Effect::Outline { .. } | af::Effect::ColorOverlay { .. } | af::Effect::GradientOverlay { .. } => continue,
|
||||
};
|
||||
out.push(Effect { id: id.into(), params, visible: true });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An outline effect on a shape: a stroke layer. Affinity outlines what the shape shows, its own
|
||||
/// strokes included: an outline outside goes under them (from the path out to as far past them as
|
||||
/// it is wide), one centred on or inside that edge over them. A centred one reaches as far into
|
||||
/// the shape as out of it here, which only differs by the width of the shape's own stroke.
|
||||
pub(super) fn outline_stroke(&mut self, effects: &[af::Effect], appearance: &mut Appearance) {
|
||||
// How far the shape's own strokes reach outside its path.
|
||||
let reach = appearance
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
AppearanceItem::Stroke(s) => Some(match s.align {
|
||||
StrokeAlign::Center => s.width / 2.0,
|
||||
StrokeAlign::Outside => s.width,
|
||||
StrokeAlign::Inside => 0.0,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|w| w.is_finite())
|
||||
.fold(0.0, f64::max);
|
||||
for e in effects {
|
||||
let af::Effect::Outline { color, opacity, width, align } = e else { continue };
|
||||
let w = width * self.k;
|
||||
if !(w.is_finite() && w > 0.0) {
|
||||
continue;
|
||||
}
|
||||
let (c, alpha) = Self::color(*color);
|
||||
let (align, w) = match align {
|
||||
1 => (StrokeAlign::Inside, w),
|
||||
2 => (StrokeAlign::Center, w + 2.0 * reach),
|
||||
_ => (StrokeAlign::Outside, w + reach),
|
||||
};
|
||||
let mut l = StrokeLayer::new(Paint::solid(c), w.min(1000.0));
|
||||
l.opacity = (opacity.clamp(0.0, 1.0) as f32) * alpha;
|
||||
l.join = LineJoin::Round;
|
||||
l.align = align;
|
||||
let item = AppearanceItem::Stroke(l);
|
||||
if align == StrokeAlign::Outside {
|
||||
// Under the shape's strokes, over its fills.
|
||||
let at = appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap_or(appearance.items.len());
|
||||
appearance.items.insert(at, item);
|
||||
} else {
|
||||
appearance.items.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An outline effect on text: the characters' stroke, where they have none of their own.
|
||||
pub(super) fn outline_text(&mut self, effects: &[af::Effect], text: &mut TextObject) {
|
||||
for e in effects {
|
||||
let af::Effect::Outline { color, opacity, width, align } = e else { continue };
|
||||
let w = width * self.k;
|
||||
if !(w.is_finite() && w > 0.0) {
|
||||
continue;
|
||||
}
|
||||
let (c, alpha) = Self::color(*color);
|
||||
if opacity * f64::from(alpha) < 0.999 {
|
||||
self.warn("semi-transparent outline effects on text (imported opaque)");
|
||||
}
|
||||
if *align != 2 {
|
||||
self.warn("outline effects on text inside or outside the characters (centred on them)");
|
||||
}
|
||||
for r in &mut text.runs {
|
||||
if r.style.stroke == Paint::None {
|
||||
r.style.stroke = Paint::solid(c);
|
||||
// Centred on the outline, so twice as wide to show as far outside.
|
||||
r.style.stroke_width = if *align == 2 { w } else { 2.0 * w }.min(1000.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn path(&self, p: &af::Path, to_doc: Affine) -> PathData {
|
||||
let mut bp = BezPath::new();
|
||||
for s in &p.subpaths {
|
||||
let pt = |q: af::Point| Point::new(q.x, q.y);
|
||||
bp.move_to(pt(s.start));
|
||||
for [c1, c2, e] in &s.segments {
|
||||
if c1 == c2 && c2 == e {
|
||||
bp.line_to(pt(*e));
|
||||
} else {
|
||||
bp.curve_to(pt(*c1), pt(*c2), pt(*e));
|
||||
}
|
||||
}
|
||||
if s.closed {
|
||||
bp.close_path();
|
||||
}
|
||||
}
|
||||
PathData::from_bezpath(&(to_doc * bp))
|
||||
}
|
||||
|
||||
fn color(c: ap::Color) -> (Color, f32) {
|
||||
let f = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 };
|
||||
match c {
|
||||
ap::Color::Rgb { r, g, b, a } => (Color::Rgb { r: f(r), g: f(g), b: f(b) }, f(a)),
|
||||
ap::Color::Cmyk { c, m, y, k, a } => (Color::Cmyk { c: f(c), m: f(m), y: f(y), k: f(k) }, f(a)),
|
||||
ap::Color::Gray { v, a } => (Color::Gray { k: 1.0 - f(v) }, f(a)),
|
||||
ap::Color::Lab { l, a, b, alpha } => (Color::Lab { l: l as f32, a: a as f32, b: b as f32 }, f(alpha)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A paint and the opacity its colour's alpha becomes.
|
||||
pub(super) fn paint(&mut self, p: &ap::Paint, to_doc: Affine) -> Option<(Paint, f32)> {
|
||||
match p {
|
||||
ap::Paint::None => None,
|
||||
ap::Paint::Solid(c) => {
|
||||
let (color, a) = Self::color(*c);
|
||||
Some((Paint::solid(color), a))
|
||||
}
|
||||
ap::Paint::Gradient(g) => {
|
||||
let stops = g
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let (color, opacity) = Self::color(s.color);
|
||||
let mut stop = GradientStop::new(s.offset as f32, color);
|
||||
stop.opacity = opacity;
|
||||
stop.midpoint = s.half_point().clamp(0.13, 0.87) as f32;
|
||||
stop
|
||||
})
|
||||
.collect();
|
||||
let m = to_doc * affine(g.transform);
|
||||
let (o, x, y) = (m * Point::ZERO, m * Point::new(1.0, 0.0), m * Point::new(0.0, 1.0));
|
||||
let kind = match g.kind {
|
||||
AfKind::Linear => GradientKind::Linear,
|
||||
AfKind::Radial => GradientKind::Radial,
|
||||
AfKind::Conical => {
|
||||
self.warn("conical gradients import as radial gradients");
|
||||
GradientKind::Radial
|
||||
}
|
||||
};
|
||||
let (u, v): (Vec2, Vec2) = (x - o, y - o);
|
||||
if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {
|
||||
self.warn("skewed elliptical gradients import as upright ellipses");
|
||||
}
|
||||
let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 };
|
||||
let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None };
|
||||
let mut gp = GradientPaint::new(Gradient::new(kind, stops));
|
||||
gp.angle = (-(u.y)).atan2(u.x).to_degrees();
|
||||
gp.geom = Some(geom);
|
||||
Some((Paint::Gradient(Box::new(gp)), 1.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stroke_layer(&mut self, s: &ap::Stroke, to_doc: Affine) -> Option<StrokeLayer> {
|
||||
let (paint, opacity) = self.paint(&s.paint, to_doc)?;
|
||||
let mut l = StrokeLayer::new(paint, s.width * self.k);
|
||||
l.opacity = opacity;
|
||||
l.cap = match s.cap {
|
||||
Cap::Butt => LineCap::Butt,
|
||||
Cap::Round => LineCap::Round,
|
||||
Cap::Square => LineCap::Square,
|
||||
};
|
||||
l.join = match s.join {
|
||||
Join::Miter => LineJoin::Miter,
|
||||
Join::Round => LineJoin::Round,
|
||||
Join::Bevel => LineJoin::Bevel,
|
||||
};
|
||||
l.miter_limit = s.miter_limit;
|
||||
l.align = match s.align {
|
||||
ap::Align::Center => StrokeAlign::Center,
|
||||
ap::Align::Inside => StrokeAlign::Inside,
|
||||
ap::Align::Outside => StrokeAlign::Outside,
|
||||
};
|
||||
l.dash = s.dash.as_ref().map(|(pattern, phase)| Dash {
|
||||
pattern: pattern.iter().map(|v| v * self.k).collect(),
|
||||
offset: phase * self.k,
|
||||
align_corners: false,
|
||||
});
|
||||
Some(l)
|
||||
}
|
||||
|
||||
pub(super) fn appearance(&mut self, fills: &[ap::Paint], strokes: &[ap::Stroke], to_doc: Affine) -> Appearance {
|
||||
let mut items = Vec::new();
|
||||
let mut above = Vec::new();
|
||||
for f in fills {
|
||||
if let Some((paint, opacity)) = self.paint(f, to_doc) {
|
||||
let mut l = FillLayer::new(paint);
|
||||
l.opacity = opacity;
|
||||
items.push(AppearanceItem::Fill(l));
|
||||
}
|
||||
}
|
||||
for s in strokes {
|
||||
let Some(l) = self.stroke_layer(s, to_doc) else { continue };
|
||||
if s.behind {
|
||||
items.insert(0, AppearanceItem::Stroke(l));
|
||||
} else {
|
||||
above.push(AppearanceItem::Stroke(l));
|
||||
}
|
||||
}
|
||||
items.extend(above);
|
||||
Appearance { items, ..Appearance::default() }
|
||||
}
|
||||
|
||||
/// Where text placed by `m` (node space to points) goes, its type scaled by `type_m`.
|
||||
pub(super) fn placement(&mut self, m: Affine, type_m: Affine) -> Option<Placement> {
|
||||
let [a, b, c, d, e, f] = m.as_coeffs();
|
||||
let sx = a.hypot(b);
|
||||
let det = a * d - b * c;
|
||||
if !(sx > 1e-9 && det.is_finite() && det.abs() > 1e-12 && e.is_finite() && f.is_finite()) {
|
||||
self.warn("text with an invalid transform (left out)");
|
||||
return None;
|
||||
}
|
||||
let sy = det / sx;
|
||||
let shear = (a * c + b * d) / (sx * sx);
|
||||
if shear.abs() > 1e-3 || sy < 0.0 {
|
||||
self.warn("skewed or flipped text (imported without the skew or flip)");
|
||||
}
|
||||
// The type's vertical scale gives the font size, its horizontal scale relative to that the
|
||||
// characters' width.
|
||||
let [ta, tb, tc, td, ..] = type_m.as_coeffs();
|
||||
let (tsx, tdet) = (ta.hypot(tb), ta * td - tb * tc);
|
||||
let (size_scale, h_scale) = if tsx > 1e-9 && tdet.is_finite() && tdet.abs() > 1e-12 {
|
||||
let tsy = (tdet / tsx).abs();
|
||||
(tsy, tsx / tsy)
|
||||
} else {
|
||||
self.warn("text with an invalid text scale (imported unscaled)");
|
||||
(det.abs().sqrt(), 1.0)
|
||||
};
|
||||
Some(Placement {
|
||||
to_frame: Affine::scale_non_uniform(sx, sy.abs()),
|
||||
place: Affine::translate((e, f)) * Affine::rotate(b.atan2(a)),
|
||||
size_scale,
|
||||
h_scale,
|
||||
})
|
||||
}
|
||||
|
||||
/// A CMYK pixel layer as an image file. Through the document's own CMYK profile when it
|
||||
/// embeds one (as Affinity shows it): RGBA. Otherwise, opaque, a CMYK image that keeps its
|
||||
/// inks (shown and separated through the working CMYK profile, as placed CMYK images are);
|
||||
/// with transparency, RGBA through the working CMYK profile.
|
||||
fn cmyk_image(&mut self, width: u32, height: u32, cmyka: &[u8]) -> Option<Vec<u8>> {
|
||||
let n = (width as usize).checked_mul(height as usize)?;
|
||||
let px = cmyka.get(..n.checked_mul(5)?)?.as_chunks::<5>().0;
|
||||
if let Some(lut) = self.document_cmyk() {
|
||||
let rgba = px
|
||||
.iter()
|
||||
.flat_map(|p| {
|
||||
let [r, g, b, _] = lut.apply8([p[0], p[1], p[2], p[3]]);
|
||||
[r, g, b, p[4]]
|
||||
})
|
||||
.collect();
|
||||
return png(width, height, rgba);
|
||||
}
|
||||
if px.iter().all(|p| p[4] == 255) {
|
||||
let inks = px.iter().flat_map(|p| [p[0], p[1], p[2], p[3]]).collect();
|
||||
if let Some(blob) = vectorcraft_doc::cmyk::Inks::new(width, height, inks).and_then(|i| vectorcraft_doc::ImageBlob::cmyk_tiff(&i)) {
|
||||
return Some(Arc::unwrap_or_clone(blob.bytes));
|
||||
}
|
||||
}
|
||||
self.warn("CMYK pixel layers with transparency (converted to RGB through the working CMYK profile)");
|
||||
let lut = self
|
||||
.working_cmyk
|
||||
.get_or_insert_with(|| {
|
||||
Arc::new(vectorcraft_color::cms::CmykLut::build(|[c, m, y, k]| {
|
||||
let [r, g, b] = Color::cmyk(c, m, y, k).to_rgb();
|
||||
[r, g, b, 0.0]
|
||||
}))
|
||||
})
|
||||
.clone();
|
||||
let rgba = px
|
||||
.iter()
|
||||
.flat_map(|p| {
|
||||
let [r, g, b, _] = lut.apply8([p[0], p[1], p[2], p[3]]);
|
||||
[r, g, b, p[4]]
|
||||
})
|
||||
.collect();
|
||||
png(width, height, rgba)
|
||||
}
|
||||
|
||||
/// The document's CMYK profile as a table from ink amounts to sRGB (relative colorimetric,
|
||||
/// with black-point compensation, as Affinity's pixel layers convert), made once; `None` when
|
||||
/// the document embeds none, or not one that converts.
|
||||
fn document_cmyk(&mut self) -> Option<Arc<vectorcraft_color::cms::CmykLut>> {
|
||||
use vectorcraft_color::cms::{self, CmykLut, IccProfile, Intent};
|
||||
if let Some(lut) = &self.cmyk_lut {
|
||||
return lut.clone();
|
||||
}
|
||||
let embedded = self.cmyk_profile.is_some();
|
||||
let lut = self.cmyk_profile.take().and_then(|bytes| {
|
||||
let profile = IccProfile::from_bytes(None, &bytes).ok()?;
|
||||
let srgb = cms::icc::builtin_rgb(cms::SRGB)?;
|
||||
profile.to_rgb_of(&srgb, &[0.0; 4], Intent::RelativeColorimetric, true)?;
|
||||
Some(Arc::new(CmykLut::build(|inks| {
|
||||
let [r, g, b] = profile
|
||||
.to_rgb_of(&srgb, &inks, Intent::RelativeColorimetric, true)
|
||||
.unwrap_or_else(|| Color::cmyk(inks[0], inks[1], inks[2], inks[3]).to_rgb());
|
||||
[r, g, b, 0.0]
|
||||
})))
|
||||
});
|
||||
if embedded && lut.is_none() {
|
||||
self.warn("CMYK pixel layers whose document's colour profile could not be read (shown through the working CMYK profile)");
|
||||
}
|
||||
self.cmyk_lut = Some(lut.clone());
|
||||
lut
|
||||
}
|
||||
|
||||
pub(super) fn image(&mut self, img: &af::Image, to_doc: Affine) -> Option<NodeKind> {
|
||||
let bytes = match &img.pixels {
|
||||
Pixels::Encoded(b) => b.clone(),
|
||||
Pixels::Rgba8(rgba) => png(img.width, img.height, rgba.clone())?,
|
||||
Pixels::Cmyka8(cmyka) => self.cmyk_image(img.width, img.height, cmyka)?,
|
||||
};
|
||||
let r = match crate::cmd::fileio::load::raster_image(&bytes) {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
self.warn("an embedded image that could not be decoded was left out");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// The pixel grid maps onto the Affinity image's own size, whatever the stored file's.
|
||||
let sx = img.width as f64 / f64::from(r.width.max(1));
|
||||
let sy = img.height as f64 / f64::from(r.height.max(1));
|
||||
let xf = to_doc * affine(img.transform) * Affine::scale_non_uniform(sx, sy);
|
||||
self.doc.images.entry(r.key.clone()).or_insert(r.blob);
|
||||
Some(NodeKind::Image(Box::new(ImageObject {
|
||||
key: r.key,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
xf,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
})))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
use super::layout::{align_lines, fit_lines, font_style, justify, line_gap, place_cell};
|
||||
use super::nodes::affine;
|
||||
use super::*;
|
||||
|
||||
/// Where text goes: a rigid placement (translation and rotation) and the scale that maps node
|
||||
/// space into it (applied to the frame's geometry, not the type), plus the type's own scale.
|
||||
pub(super) struct Placement {
|
||||
/// Node space to the frame's space, before `place`.
|
||||
pub(super) to_frame: Affine,
|
||||
pub(super) place: Affine,
|
||||
/// Points per node unit of type size.
|
||||
pub(super) size_scale: f64,
|
||||
/// Horizontal scale of the type relative to `size_scale`.
|
||||
pub(super) h_scale: f64,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
/// Text → its object and the opacity its characters' shared transparency gives the node.
|
||||
pub(super) fn text(&mut self, t: &af::Text, to_doc: Affine) -> Option<(TextObject, f32)> {
|
||||
let p = self.placement(to_doc * affine(t.transform), to_doc * affine(t.text_transform))?;
|
||||
let alpha = self.text_alpha(&t.runs);
|
||||
let mut obj = self.type_object(&t.runs, &p)?;
|
||||
obj.para.justify = justify(t.align);
|
||||
if let Some(first) = obj.paras.first_mut() {
|
||||
first.justify = obj.para.justify;
|
||||
}
|
||||
match t.frame {
|
||||
Some(f) => {
|
||||
let (a, b) = (p.to_frame * Point::new(f.x0, f.y0), p.to_frame * Point::new(f.x1, f.y1));
|
||||
let r = Rect::from_points(a, b);
|
||||
obj.xf = p.place * Affine::translate(r.origin().to_vec2());
|
||||
obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, r.width(), r.height())) };
|
||||
// Affinity hangs a frame's first line from its capitals' tops, not the font's ascent.
|
||||
obj.area.first_baseline = FirstBaseline::CapHeight;
|
||||
if fit_lines(&mut obj, r.width(), r.height()) {
|
||||
self.warn("text frames whose last lines hang out of them (made taller so the lines show)");
|
||||
}
|
||||
// Affinity shows a line in a frame shorter than it (#1423); here none of it would draw.
|
||||
if vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), &mut obj) {
|
||||
self.warn("text frames too short for their first line (made taller so the line shows)");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
align_lines(&mut obj);
|
||||
obj.xf = p.place * Affine::translate((p.to_frame * Point::new(t.anchor.x, t.anchor.y)).to_vec2());
|
||||
}
|
||||
}
|
||||
Some((obj, alpha))
|
||||
}
|
||||
|
||||
/// The opacity text takes from its characters' colour: VectorCraft's characters have none of
|
||||
/// their own, so text whose characters share one becomes an object with that opacity.
|
||||
fn text_alpha(&mut self, runs: &[af::TextRun]) -> f32 {
|
||||
let alphas: Vec<f64> =
|
||||
runs.iter().filter_map(|r| if let ap::Paint::Solid(c) = &r.fill { Some(c.alpha()) } else { None }).filter(|a| a.is_finite()).collect();
|
||||
let (lo, hi) = alphas.iter().fold((1.0f64, 0.0f64), |(lo, hi), a| (lo.min(*a), hi.max(*a)));
|
||||
if alphas.is_empty() || lo >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
if hi - lo > 0.01 {
|
||||
self.warn("text with characters of different transparency (imported opaque)");
|
||||
return 1.0;
|
||||
}
|
||||
lo.clamp(0.0, 1.0) as f32
|
||||
}
|
||||
|
||||
/// The characters and paragraphs of `runs` as a text object at the origin of text space.
|
||||
fn type_object(&mut self, runs: &[af::TextRun], p: &Placement) -> Option<TextObject> {
|
||||
let (v, h) = (p.size_scale, p.size_scale * p.h_scale);
|
||||
let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default());
|
||||
let mut formats: Vec<af::Paragraph> = Vec::new();
|
||||
let mut out: Vec<TextRun> = Vec::new();
|
||||
let mut paragraph = 0usize;
|
||||
// Whether each paragraph here continues the one before after a line break (U+2028):
|
||||
// VectorCraft has no line break inside a paragraph, so the lines become paragraphs.
|
||||
let mut continues = vec![false];
|
||||
for r in runs {
|
||||
for c in r.text.chars() {
|
||||
match c {
|
||||
'\u{2028}' => continues.push(true),
|
||||
'\u{2029}' | '\r' | '\n' => continues.push(false),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Affinity separates paragraphs with U+2029 and lines with U+2028; other control
|
||||
// characters don't show.
|
||||
let text: String = r
|
||||
.text
|
||||
.chars()
|
||||
.filter_map(|c| match c {
|
||||
'\u{2029}' | '\u{2028}' | '\r' | '\n' => Some('\n'),
|
||||
'\t' => Some('\t'),
|
||||
c if c.is_control() => None,
|
||||
c => Some(c),
|
||||
})
|
||||
.collect();
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for c in text.chars() {
|
||||
if formats.len() <= paragraph {
|
||||
formats.push(r.paragraph);
|
||||
}
|
||||
if c == '\n' {
|
||||
paragraph += 1;
|
||||
}
|
||||
}
|
||||
let mut style = self.char_style(r, (v, p.h_scale));
|
||||
if style.leading.is_none() {
|
||||
style.leading = r.paragraph.leading.map(|l| l * v).filter(|l| l.is_finite() && *l > 0.0).map(|l| l.min(5000.0));
|
||||
}
|
||||
out.push(TextRun::new(text, style));
|
||||
}
|
||||
// Affinity ends a story with a paragraph mark; VectorCraft's last paragraph has none.
|
||||
if let Some(last) = out.last_mut()
|
||||
&& last.text.ends_with('\n')
|
||||
{
|
||||
last.text.pop();
|
||||
if last.text.is_empty() {
|
||||
out.pop();
|
||||
}
|
||||
}
|
||||
obj.runs = out;
|
||||
let count = obj.runs.iter().map(|r| r.text.matches('\n').count()).sum::<usize>() + 1;
|
||||
let mut paras = Vec::with_capacity(count);
|
||||
let mut previous_after = 0.0;
|
||||
// The run of each paragraph's first character.
|
||||
let mut first_runs = Vec::with_capacity(count);
|
||||
{
|
||||
let mut at_start = true;
|
||||
for (i, r) in obj.runs.iter().enumerate() {
|
||||
for c in r.text.chars() {
|
||||
if at_start {
|
||||
first_runs.push(i);
|
||||
at_start = false;
|
||||
}
|
||||
if c == '\n' {
|
||||
at_start = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Line gaps by font, each looked up once.
|
||||
let mut gaps: std::collections::HashMap<(&str, &str), f64> = std::collections::HashMap::new();
|
||||
for i in 0..count {
|
||||
let f = formats.get(i).or(formats.last()).copied().unwrap_or_default();
|
||||
let pt = |x: f64, k: f64| if (x * k).is_finite() { (x * k).clamp(-5000.0, 5000.0) } else { 0.0 };
|
||||
let mut ps = vectorcraft_doc::text::ParaStyle { justify: justify(f.align), ..Default::default() };
|
||||
// Affinity places the first line and the others from the left edge; VectorCraft's
|
||||
// first-line indent is relative to its left indent.
|
||||
ps.left_indent = pt(f.left, h);
|
||||
ps.first_line_indent = pt(f.first - f.left, h);
|
||||
ps.right_indent = pt(f.right, h);
|
||||
// Between two paragraphs Affinity keeps the larger of the space after the first and
|
||||
// before the second; VectorCraft adds them.
|
||||
let (mut before, mut after) = (pt(f.space_before, v).max(0.0), pt(f.space_after, v).max(0.0));
|
||||
// The lines of one Affinity paragraph: no space between them, and the first-line
|
||||
// indent only on its first.
|
||||
if continues.get(i).copied().unwrap_or(false) {
|
||||
before = 0.0;
|
||||
ps.first_line_indent = 0.0;
|
||||
}
|
||||
if continues.get(i + 1).copied().unwrap_or(false) {
|
||||
after = 0.0;
|
||||
}
|
||||
ps.space_before = if i == 0 { before } else { (before - previous_after).max(0.0) };
|
||||
ps.space_after = after;
|
||||
previous_after = after;
|
||||
// Automatic leading: the font size plus the font's line gap, times the paragraph's
|
||||
// factor, for artistic and frame text alike. Fitted on Affinity's thumbnails: Bebas
|
||||
// Neue Pro and Impact lines about 1 em apart, DIN Condensed (a gap of 0.2 em) 1.2 em,
|
||||
// and the public Arial frame fixture fits this better than the font's line height.
|
||||
let (family, style) =
|
||||
first_runs.get(i).and_then(|r| obj.runs.get(*r)).map_or(("", ""), |r| (r.style.font_family.as_str(), r.style.font_style.as_str()));
|
||||
let gap = *gaps.entry((family, style)).or_insert_with(|| line_gap(family, style));
|
||||
let ratio = (1.0 + gap) * f.auto_leading;
|
||||
// Affinity documents use tiny factors for spacer paragraphs (0.15 of a line); VectorCraft
|
||||
// takes 0–500 %.
|
||||
if ratio.is_finite() && (0.01..=5.0).contains(&ratio) {
|
||||
ps.justification.auto_leading = ratio * 100.0;
|
||||
}
|
||||
paras.push(ps);
|
||||
}
|
||||
if let Some(first) = paras.first() {
|
||||
obj.para = first.clone();
|
||||
}
|
||||
obj.paras = paras;
|
||||
obj.normalize_paras();
|
||||
Some(obj)
|
||||
}
|
||||
|
||||
/// A run's character style; `(size_scale, h_scale)` the type's vertical scale to points and
|
||||
/// its horizontal scale relative to that.
|
||||
fn char_style(&mut self, r: &af::TextRun, (size_scale, h_scale): (f64, f64)) -> CharStyle {
|
||||
let finite = |v: f64, d: f64| if v.is_finite() { v } else { d };
|
||||
let mut style = CharStyle::default();
|
||||
if !r.family.is_empty() {
|
||||
style.font_family = r.family.clone();
|
||||
} else if !r.postscript.is_empty() {
|
||||
style.font_family = r.postscript.clone();
|
||||
} else {
|
||||
self.warn("text without a font name uses the default font");
|
||||
}
|
||||
// A family/weight pair cannot identify width variants such as Arial Narrow.
|
||||
// Resolve a known PostScript identity to the exact installed family and style.
|
||||
if let Some((family, face_style)) = vectorcraft_text::FontDb::global().by_postscript_name(&r.postscript) {
|
||||
style.font_family = family;
|
||||
style.font_style = face_style;
|
||||
} else {
|
||||
style.font_style = font_style(r.weight, r.italic);
|
||||
}
|
||||
style.features = r.features.clone();
|
||||
if r.features.iter().any(|feature| !vectorcraft_text::OtFeatures::known_tag(feature)) {
|
||||
self.warn("unsupported text OpenType features (retained but not rendered)");
|
||||
}
|
||||
style.all_caps = r.all_caps;
|
||||
style.underline = r.underline;
|
||||
style.strikethrough = r.strikethrough;
|
||||
style.size = finite(r.size * size_scale, 12.0).clamp(0.1, 1296.0);
|
||||
style.leading = r.leading.map(|l| finite(l * size_scale, 0.0)).filter(|l| *l > 0.0).map(|l| l.min(5000.0));
|
||||
style.tracking = finite(r.tracking * 1000.0, 0.0).clamp(-1000.0, 10000.0);
|
||||
// Text squeezed or stretched by its transform keeps that as horizontal scale, on top of
|
||||
// its own.
|
||||
let hs = h_scale * r.h_scale;
|
||||
if hs.is_finite() && (hs - 1.0).abs() > 1e-3 {
|
||||
style.h_scale = (hs * 100.0).clamp(1.0, 1000.0);
|
||||
}
|
||||
// Transparency is the object's (see `text_alpha`); the paint's transform doesn't matter
|
||||
// for a solid colour, and gradients on type are laid out in text space.
|
||||
style.fill = match self.paint(&r.fill, Affine::scale(size_scale)) {
|
||||
Some((p, _)) => p,
|
||||
None => Paint::None,
|
||||
};
|
||||
if let Some(st) = &r.stroke {
|
||||
let w = st.width * size_scale;
|
||||
if let Some((paint, _)) = self.paint(&st.paint, Affine::scale(size_scale))
|
||||
&& w.is_finite()
|
||||
&& w > 0.0
|
||||
{
|
||||
style.stroke = paint;
|
||||
style.stroke_width = w.min(1000.0);
|
||||
}
|
||||
}
|
||||
style
|
||||
}
|
||||
|
||||
/// A table: its cells as area type and the lines on their edges, as VectorCraft has no
|
||||
/// tables.
|
||||
pub(super) fn table(&mut self, t: &af::Table, to_doc: Affine) -> Vec<Arc<Node>> {
|
||||
let mut out = Vec::new();
|
||||
let (ncols, nrows) = (t.ncols(), t.nrows());
|
||||
if ncols == 0 || nrows == 0 {
|
||||
return out;
|
||||
}
|
||||
self.warn("tables (imported as text frames and lines)");
|
||||
let m = to_doc * affine(t.transform);
|
||||
let Some(p) = self.placement(m, to_doc * affine(t.text_transform)) else { return out };
|
||||
let col = |i: usize| t.columns.get(i).copied().unwrap_or(0.0);
|
||||
let row = |i: usize| t.rows.get(i).copied().unwrap_or(0.0);
|
||||
for (i, cell) in t.cells.iter().enumerate() {
|
||||
if cell.merged_left || cell.runs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (r, c) = (i / ncols, i % ncols);
|
||||
// Cells to the right merged into this one widen it.
|
||||
let span = 1 + t.cells.iter().skip(i + 1).take(ncols - c - 1).take_while(|n| n.merged_left).count();
|
||||
let [l, tp, rt, bt] = cell.inset;
|
||||
let node = af::Rect { x0: col(c) + l, y0: row(r) + tp, x1: col(c + span) - rt, y1: row(r + 1) - bt };
|
||||
let (a, b) = (p.to_frame * Point::new(node.x0, node.y0), p.to_frame * Point::new(node.x1, node.y1));
|
||||
let rect = Rect::from_points(a, b);
|
||||
if !(rect.width() > 0.0 && rect.height() > 0.0) {
|
||||
continue;
|
||||
}
|
||||
let Some(mut obj) = self.type_object(&cell.runs, &p) else { continue };
|
||||
obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, rect.width(), rect.height())) };
|
||||
obj.area.vertical_align = match cell.valign {
|
||||
af::VAlign::Top => VerticalAlign::Top,
|
||||
af::VAlign::Center => VerticalAlign::Center,
|
||||
af::VAlign::Bottom => VerticalAlign::Bottom,
|
||||
};
|
||||
obj.area.first_baseline = FirstBaseline::CapHeight;
|
||||
let dy = place_cell(&mut obj, rect.width(), rect.height());
|
||||
obj.xf = p.place * Affine::translate(rect.origin().to_vec2() + Vec2::new(0.0, dy));
|
||||
// A cell's text never vanishes for want of a line's height.
|
||||
vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), &mut obj);
|
||||
let alpha = self.text_alpha(&cell.runs);
|
||||
let mut n = Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(obj)));
|
||||
n.opacity = alpha;
|
||||
out.push(Arc::new(n));
|
||||
}
|
||||
// Lines over the cells: the vertical edges row by row (none inside merged cells), then
|
||||
// the horizontal ones.
|
||||
let mut line = |b: &mut Self, s: &Option<ap::Stroke>, from: (f64, f64), to: (f64, f64)| {
|
||||
let Some(s) = s else { return };
|
||||
let Some(layer) = b.stroke_layer(s, to_doc) else { return };
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(m * Point::new(from.0, from.1));
|
||||
bp.line_to(m * Point::new(to.0, to.1));
|
||||
let mut n = Node::new(
|
||||
b.doc.alloc_id(),
|
||||
NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false },
|
||||
);
|
||||
n.appearance = Appearance { items: vec![AppearanceItem::Stroke(layer)], ..Appearance::default() }.into();
|
||||
out.push(Arc::new(n));
|
||||
};
|
||||
for r in 0..nrows {
|
||||
for k in 0..=ncols {
|
||||
let merged = k > 0 && k < ncols && t.cells.get(r * ncols + k).is_some_and(|c| c.merged_left);
|
||||
if merged {
|
||||
continue;
|
||||
}
|
||||
if let Some(s) = t.vertical.get(r * (ncols + 1) + k) {
|
||||
line(self, s, (col(k), row(r)), (col(k), row(r + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
for j in 0..=nrows {
|
||||
for k in 0..ncols {
|
||||
if let Some(s) = t.horizontal.get(j * ncols + k) {
|
||||
line(self, s, (col(k), row(j)), (col(k + 1), row(j)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! `command.batch`: several commands as one undo step (in each document they edit).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Document;
|
||||
|
||||
use super::super::*;
|
||||
use crate::{DocState, EngineError};
|
||||
@@ -11,8 +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).
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter);
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group).
|
||||
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());
|
||||
// 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() {
|
||||
@@ -23,14 +26,18 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let start = s.docs.clone();
|
||||
let active = s.active;
|
||||
s.batch_stash = Some(vec![]);
|
||||
let r = run_steps(s, &label, artboard, &mut cmds);
|
||||
let mut grouped = Vec::with_capacity(cmds.len());
|
||||
let r = run_steps(s, &label, artboard, &mut cmds, &mut grouped);
|
||||
let stash = s.batch_stash.take().unwrap_or_default();
|
||||
let results = match r {
|
||||
Ok(results) => results,
|
||||
Ok(results) => {
|
||||
s.batch_steps = Some(grouped);
|
||||
results
|
||||
}
|
||||
Err(e) => {
|
||||
roll_back(s, start, &stash);
|
||||
s.active = active;
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter) = saved;
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
|
||||
s.pending_paint = None;
|
||||
return Err(e);
|
||||
}
|
||||
@@ -57,7 +64,14 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
|
||||
/// document's last artboard, the last one. A step that resizes the active artboard
|
||||
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
|
||||
fn run_steps(s: &mut Session, label: &str, artboard: Option<u64>, cmds: &mut [Value]) -> Result<Vec<Value>> {
|
||||
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
|
||||
fn run_steps(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
artboard: Option<u64>,
|
||||
cmds: &mut [Value],
|
||||
grouped: &mut Vec<(Vec<u64>, Option<usize>)>,
|
||||
) -> Result<Vec<Value>> {
|
||||
let mut results = Vec::with_capacity(cmds.len());
|
||||
for c in cmds {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
@@ -81,8 +95,12 @@ fn run_steps(s: &mut Session, label: &str, artboard: Option<u64>, cmds: &mut [Va
|
||||
{
|
||||
o.insert(key.into(), json!(usize::try_from(a).map_or(last, |a| a.min(last))));
|
||||
}
|
||||
// The documents with an undo group open, held so that the step's first edit in one copies it.
|
||||
let start = s.active().map(|d| d.uid);
|
||||
let held: Vec<(u64, Arc<Document>)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect();
|
||||
let (v, noted) =
|
||||
s.execute_step(&id, ¶ms).map_err(|e| EngineError::Other(format!("batch step {} (`{id}`) failed: {e}", results.len())))?;
|
||||
grouped.push(step_groups(s, start, &held));
|
||||
// The step's journal entry records what it took from the preferences or the clock (a
|
||||
// save's date, a new document's), as a command of its own would.
|
||||
if noted != params
|
||||
@@ -95,11 +113,36 @@ fn run_steps(s: &mut Session, label: &str, artboard: Option<u64>, cmds: &mut [Va
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// The undo groups a step belongs to, as [`Session::execute`] notes a command's journal entry in
|
||||
/// them: the group of each document in `held` (the grouped documents before the step) that the step
|
||||
/// changed, each group it opened and edited, and the group of the document with [`DocState::uid`]
|
||||
/// `start` when it started there and ended there. With the index of the document it left active
|
||||
/// when it changed the active document.
|
||||
fn step_groups(s: &Session, start: Option<u64>, held: &[(u64, Arc<Document>)]) -> (Vec<u64>, Option<usize>) {
|
||||
let end = s.active().map(|d| d.uid);
|
||||
let uids = s
|
||||
.docs
|
||||
.iter()
|
||||
.filter(|st| {
|
||||
st.undo_group.as_ref().is_some_and(|g| {
|
||||
let edited = match held.iter().find(|(uid, _)| *uid == st.uid) {
|
||||
Some((_, d)) => !Arc::ptr_eq(d, &st.doc),
|
||||
None => g.first.is_some(),
|
||||
};
|
||||
edited || (start == Some(st.uid) && end == start)
|
||||
})
|
||||
})
|
||||
.map(|st| st.uid)
|
||||
.collect();
|
||||
(uids, if end == start { None } else { s.active })
|
||||
}
|
||||
|
||||
/// The documents as they were before the batch (`start`), whatever the steps did to them: opened
|
||||
/// ones close, closed or replaced ones (`stash`) come back, and each has its art, selection,
|
||||
/// history, file, format and saved state again (#1697: undoing the batch's interaction alone left
|
||||
/// a Save As step's new file and an Undo step's history in place). Files the steps wrote stay
|
||||
/// written. Lock Guides stays as the steps left it, and while it is on the guides are deselected.
|
||||
/// written. Lock Guides, Lock Slices and Hide Slices stay as the steps left them, and the guides
|
||||
/// and slices they keep from being selected are deselected.
|
||||
fn roll_back(s: &mut Session, start: Vec<DocState>, stash: &[DocState]) {
|
||||
let open = std::mem::take(&mut s.docs);
|
||||
s.docs = start;
|
||||
@@ -107,8 +150,6 @@ fn roll_back(s: &mut Session, start: Vec<DocState>, stash: &[DocState]) {
|
||||
// Past the newest revision the document reached, so the restored one redraws.
|
||||
let newest = open.iter().chain(stash).filter(|d| d.uid == st.uid).map(|d| d.revision).max().unwrap_or(st.revision);
|
||||
st.revision = newest.saturating_add(1);
|
||||
if s.menu.guides_locked {
|
||||
crate::deselect_guides(&st.doc, &mut st.selection);
|
||||
}
|
||||
crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
use super::access::file_list;
|
||||
use super::formats::formats;
|
||||
use super::*;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"document.open",
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
cmd!(
|
||||
query "file.list",
|
||||
"List Folder",
|
||||
[],
|
||||
None,
|
||||
"{path} the files and folders in folder `path`, by name: what an agent may open there (held to the automation read root when one is in force) → {path, entries: [{name, kind: file|folder|link, size? (files, bytes)}], truncated (more than 5000 entries)} (#1163)",
|
||||
always,
|
||||
file_list
|
||||
),
|
||||
cmd!(
|
||||
query "document.serialize",
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in their layers)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
cmd!(
|
||||
"document.export",
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
cmd!(
|
||||
"document.exportSelection",
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), scale?: 1, …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
cmd!(
|
||||
"document.exportForScreens",
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one store-only .zip of every file: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
cmd!(
|
||||
query "document.exportPresets.list",
|
||||
"Export Presets",
|
||||
[],
|
||||
None,
|
||||
"{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones; any name works as document.exportForScreens' exportPreset",
|
||||
always,
|
||||
screens::presets_list
|
||||
),
|
||||
cmd!(
|
||||
query "document.exportPresets.save",
|
||||
"Save Export Preset",
|
||||
[],
|
||||
None,
|
||||
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}",
|
||||
always,
|
||||
screens::presets_save
|
||||
),
|
||||
cmd!(
|
||||
query "document.exportPresets.delete",
|
||||
"Delete Export Preset",
|
||||
[],
|
||||
None,
|
||||
"{name} delete a saved batch export preset (built-in ones stay) → {deleted}",
|
||||
always,
|
||||
screens::presets_delete
|
||||
),
|
||||
cmd!(
|
||||
query "command.batch",
|
||||
"Batch",
|
||||
[],
|
||||
None,
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing or select.allOnArtboard step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
has_doc,
|
||||
batch::batch
|
||||
),
|
||||
cmd!(
|
||||
"action.batch",
|
||||
"Batch…",
|
||||
[],
|
||||
None,
|
||||
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension, with `-2`, `-3`… added to a name an earlier file used), or on every data set of the open document (source: datasets; File + Data Set Name for the folder destination and Override Save/Export, with `/`, `\\`, `:`, `<`, `>`, `\"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and `-2`, `-3`… added to a name already used). Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}",
|
||||
always,
|
||||
action_batch::action_batch
|
||||
),
|
||||
cmd!(
|
||||
query "document.formats",
|
||||
"File Formats",
|
||||
[],
|
||||
None,
|
||||
"{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in that adds the format (its id is plugin.<plug-in id>; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…], unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PICT, with what to use instead)}",
|
||||
always,
|
||||
formats
|
||||
),
|
||||
cmd!(
|
||||
query "document.pdfInfo",
|
||||
"PDF Info",
|
||||
[],
|
||||
None,
|
||||
"{path | name? | dataBase64 (a file's path, or its bytes), password?, thumbnail?: page (1-based), thumbnailSize?: 160 (px, longest side), cropTo?: crop (the thumbnail's box)} → {pages, needsPassword, wrongPassword?, pageInfo: [{width, height (pt, as shown), rotation, boxes: {media, crop, bleed, trim, art: [x0, y0, x1, y1] (PDF space, pt)}}], thumbnail?: PNG dataBase64}; a page whose UserUnit (PDF 1.6) is above 1 gives its size and boxes in pt, its numbers times the UserUnit (one above 75,000 counts as 75,000); an encrypted PDF without its password → {pages: 0, needsPassword: true}; a PostScript file (an EPS, a .ps file, a .ai in PostScript form) → {pages: 1, needsPassword: false, pageInfo: [{width, height (its bounding box, a US Letter page without one), rotation: 0, boxes: {}}]} (password and cropTo don't apply; thumbnail: 1 shows what the page prints)",
|
||||
always,
|
||||
pdfimport::pdf_info
|
||||
),
|
||||
cmd!(
|
||||
"document.exportForOffice",
|
||||
"Save for Office Documents…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, ppi?: 150 (72, 150, 300… pixels per inch), transparent?: false (else on white), artboard?: 0, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out)} the artboard as a PNG for office documents and slides → {path, bytes, width, height, warnings} (pixels); no path → {dataBase64, bytes, width, height, warnings}; warnings as for document.export (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame)",
|
||||
has_doc,
|
||||
export::export_for_office
|
||||
),
|
||||
cmd!(
|
||||
query "document.exportSettings",
|
||||
"Export for Screens Settings",
|
||||
[],
|
||||
None,
|
||||
"{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them)",
|
||||
has_doc,
|
||||
screens::export_settings
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(save::specs())
|
||||
.collect()
|
||||
}
|
||||
@@ -94,6 +94,12 @@ pub const UNSUPPORTED: &[Unsupported] = &[
|
||||
extensions: &["pict", "pct", "pic"],
|
||||
hint: "PICT is a retired format and is not supported: convert the file to PDF or PNG first",
|
||||
},
|
||||
Unsupported {
|
||||
id: "pmd",
|
||||
label: "PageMaker",
|
||||
extensions: &["pmd"],
|
||||
hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here",
|
||||
},
|
||||
];
|
||||
|
||||
/// The unsupported format an id or extension (any case, leading dot allowed) names.
|
||||
|
||||
@@ -340,7 +340,17 @@ pub(super) fn single_artboard(doc: &Document, rect: Rect, name: &str) -> Documen
|
||||
|
||||
/// `d` with one artboard, `rect`.
|
||||
pub(crate) fn with_single_artboard(mut d: Document, rect: Rect, name: &str) -> Document {
|
||||
d.artboards = vec![Artboard { id: 1, name: name.into(), rect, show_center_mark: false, show_cross_hairs: false }];
|
||||
d.artboards = vec![Artboard {
|
||||
id: 1,
|
||||
name: name.into(),
|
||||
rect,
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
}];
|
||||
d
|
||||
}
|
||||
|
||||
@@ -411,6 +421,9 @@ pub fn encode_all(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
/// [`encode_all`] of `doc` as it is.
|
||||
fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
let f = super::writable(C, Some(format), None)?;
|
||||
if let Some(plugin) = vectorcraft_plugins::export::by_format(f.id) {
|
||||
return plugin_file(doc, &plugin, f, p);
|
||||
}
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let mut enc = encode_files(doc, f, p)?;
|
||||
// Baking, flattening and drawing stop early when cancelled and leave a truncated result.
|
||||
@@ -432,6 +445,32 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// The file exporter plug-in `plugin` writes of `doc` in its format `f`
|
||||
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
|
||||
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
|
||||
/// one named after the document) with that path's extension when the plug-in lists it, else its
|
||||
/// first. Its warnings come back with the file.
|
||||
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
use vectorcraft_plugins::{Error, export};
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let path = p.get("path").and_then(Value::as_str);
|
||||
let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e));
|
||||
let extension = listed.or(f.extensions.first().copied()).unwrap_or_default();
|
||||
let name = super::file_stem(path.unwrap_or(&super::default_name(doc, extension)));
|
||||
let params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
let target = export::Target { extension, name: &name };
|
||||
let out = export::run(plugin, vectorcraft_format::json_part(&file), ¶ms, target).map_err(|e| match e {
|
||||
Error::Cancelled => EngineError::Cancelled,
|
||||
Error::Params(why) => bad(C, why),
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
// The plug-in's output, so reported as its other output errors are.
|
||||
let invalid = || EngineError::Other(Error::Output("`dataBase64` is not valid base64".into()).to_string());
|
||||
let bytes = vectorcraft_format::base64_decode(&out.data_base64).ok_or_else(invalid)?;
|
||||
Ok(Encoded { warnings: out.warnings, ..Encoded::one(bytes) })
|
||||
}
|
||||
|
||||
/// [`encode_all`] without the font substitution warning.
|
||||
fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let doc = &*doc.without_edit_modes();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! EPS export for every EPS path (`document.export {format: eps}`, `document.exportEps`, Export As
|
||||
//! → EPS Options): the options parsed from the params, transparency flattened with a flattener
|
||||
//! preset, one file of the art's bounds or one per artboard, the preview and thumbnail rendered,
|
||||
//! preset, one file of the art's bounds or one per artboard (with a central file of the whole
|
||||
//! document when there are several and art shows), the preview and thumbnail rendered,
|
||||
//! and the native document embedded for reopening.
|
||||
|
||||
use std::borrow::Cow;
|
||||
@@ -28,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export EPS",
|
||||
[],
|
||||
None,
|
||||
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard) | false (default: one file, the bounding box the visible art, y up from the first artboard's bottom-left corner), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (with useArtboards: the artboards written)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}",
|
||||
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}",
|
||||
has_doc,
|
||||
export_eps
|
||||
)]
|
||||
@@ -43,7 +44,7 @@ pub(super) const OPTIONS: &[FormatOption] = &[
|
||||
name: "useArtboards",
|
||||
ty: "boolean",
|
||||
default: "null",
|
||||
description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps; false or absent: one file of the visible art (naming artboards also uses them)",
|
||||
description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (none when no art shows); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named",
|
||||
},
|
||||
FormatOption { name: "level", ty: "integer", default: "3", description: "PostScript language level, 2 or 3" },
|
||||
FormatOption {
|
||||
@@ -197,7 +198,8 @@ fn expanded(cmd: &str, p: &Value, saved: &[super::super::FlattenerPreset]) -> Re
|
||||
}
|
||||
|
||||
/// The files to write: `(artboard, region, origin)` each — every chosen artboard with its corner
|
||||
/// as the origin, or the visible art's bounds with the first artboard's corner.
|
||||
/// as the origin, or the visible art's bounds with the first artboard's corner. With two or more
|
||||
/// chosen artboards, a central file of the visible art comes first (none when no art shows).
|
||||
fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Point)>> {
|
||||
let n = doc.artboards.len();
|
||||
let named = set.boards.resolve(n).map_err(|e| bad(C, e))?;
|
||||
@@ -208,14 +210,18 @@ fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Poi
|
||||
(None, None) => None,
|
||||
};
|
||||
let corner = |r: Rect| Point::new(r.x0, r.y1);
|
||||
let art = |art: Rect| (None, art, doc.artboards.first().map_or(corner(art), |a| corner(a.rect)));
|
||||
match boards {
|
||||
Some(boards) => boards
|
||||
.into_iter()
|
||||
.map(|b| doc.artboards.get(b).map(|a| (Some(b), a.rect, corner(a.rect))).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect(),
|
||||
Some(boards) => {
|
||||
let central = (boards.len() > 1).then(|| vectorcraft_render::encode::art_bounds(doc).map(art)).flatten();
|
||||
let each = boards
|
||||
.into_iter()
|
||||
.map(|b| doc.artboards.get(b).map(|a| (Some(b), a.rect, corner(a.rect))).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))));
|
||||
central.map(Ok).into_iter().chain(each).collect()
|
||||
}
|
||||
None => {
|
||||
let art = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?;
|
||||
Ok(vec![(None, art, doc.artboards.first().map_or(corner(art), |a| corner(a.rect)))])
|
||||
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?;
|
||||
Ok(vec![art(bounds)])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -251,8 +257,8 @@ fn native(doc: &Document, board: Option<usize>, include_linked: bool) -> Vec<u8>
|
||||
}
|
||||
|
||||
/// Encode `doc` as EPS: one file of the visible art, or with Use Artboards one per chosen
|
||||
/// artboard. Transparency is flattened first (once for all of them); the previews show `doc`
|
||||
/// itself.
|
||||
/// artboard (after a central file of the whole document when there are several and art shows).
|
||||
/// Transparency is flattened first (once for all of them); the previews show `doc` itself.
|
||||
pub(super) fn encode(doc: &Document, p: &Value) -> Result<Encoded> {
|
||||
let set = parse(p)?;
|
||||
let original = doc;
|
||||
@@ -278,7 +284,7 @@ pub(super) fn encode(doc: &Document, p: &Value) -> Result<Encoded> {
|
||||
if transparent && flat.is_some() {
|
||||
enc.warnings.push("transparency is flattened into opaque art and images (EPS has none): see the flattener preset".into());
|
||||
}
|
||||
let created = vectorcraft_doc::metadata::now_unix();
|
||||
let created = vectorcraft_doc::metadata::output_time();
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
for (board, region, origin) in pages {
|
||||
let rect = vectorcraft_eps::preview_rect(region, origin);
|
||||
|
||||
@@ -19,8 +19,15 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(str_param(p, "format").unwrap_or("vectorcraft")), None)?;
|
||||
let expanded = expand_presets(s, "document.serialize", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let doc = &*source(s, f, &p, "document.serialize")?;
|
||||
let enc = encode_all(doc, f.id, &p)?;
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
|
||||
let doc = &*doc;
|
||||
let mut q = p.clone();
|
||||
if f.id == "pdf"
|
||||
&& let Some(o) = q.as_object_mut()
|
||||
{
|
||||
o.insert("_displayDocTitle".into(), json!(display_doc_title));
|
||||
}
|
||||
let enc = encode_all(doc, f.id, &q)?;
|
||||
let files = enc.named(doc, &default_name(doc, f.extensions[0]));
|
||||
let (main, linked) = files.split_at(enc.files.len());
|
||||
// Text formats come back as text; an SVG in UTF-16 or ISO 8859-1 also as its bytes.
|
||||
@@ -53,8 +60,15 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.export", str_param(p, "format"), path)?;
|
||||
let expanded = expand_presets(s, "document.export", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let doc = &*source(s, f, &p, "document.export")?;
|
||||
let enc = encode_all(doc, f.id, &p)?;
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
|
||||
let doc = &*doc;
|
||||
let mut q = p.clone();
|
||||
if f.id == "pdf"
|
||||
&& let Some(o) = q.as_object_mut()
|
||||
{
|
||||
o.insert("_displayDocTitle".into(), json!(display_doc_title));
|
||||
}
|
||||
let enc = encode_all(doc, f.id, &q)?;
|
||||
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.warnings }))
|
||||
}
|
||||
|
||||
@@ -154,13 +168,16 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Va
|
||||
|
||||
/// The document an export of `f` writes: the active one (see [`export_source`]), or for text
|
||||
/// with `selectionOnly` the selected objects alone.
|
||||
fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<Cow<'a, Document>> {
|
||||
fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(Cow<'a, Document>, bool)> {
|
||||
if f.id == "txt" && bool_or(p, "selectionOnly", false) {
|
||||
return Ok(Cow::Owned(selection(s, cmd)?.0));
|
||||
let doc = selection(s, cmd)?.0;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
return Ok((Cow::Owned(doc), display_doc_title));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = export_source(st, p)?;
|
||||
Ok(super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned))
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
|
||||
}
|
||||
|
||||
/// The selected objects (not on template layers) alone on one layer, with one artboard: their
|
||||
@@ -172,7 +189,7 @@ fn selection(s: &mut Session, cmd: &str) -> Result<(Document, vectorcraft_geom::
|
||||
|
||||
/// The selected objects (their top-most selected ancestors) that are artwork: those on template
|
||||
/// layers are guides and are left out.
|
||||
pub(crate) fn selected_artwork(s: &mut Session) -> Result<Vec<NodeId>> {
|
||||
pub(crate) fn selected_artwork(s: &Session) -> Result<Vec<NodeId>> {
|
||||
let ids = edit::selected_roots(s)?;
|
||||
let st = s.doc()?;
|
||||
let is_template = |id| st.doc.node(id).is_some_and(|l| matches!(l.kind, NodeKind::Layer { template: true, .. }));
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
use super::access::write_file;
|
||||
use super::*;
|
||||
|
||||
/// File-name parts for artboards `boards` of `doc`: the artboard's name with unsafe characters as
|
||||
/// `-`, `Artboard-N` when unnamed, and `-2`, `-3`… after a name already used (compared without
|
||||
/// case: `Icon` and `icon` are one file on most desktop file systems).
|
||||
pub fn artboard_file_names(doc: &vectorcraft_doc::Document, boards: &[usize]) -> Vec<String> {
|
||||
unique_file_names(boards.iter().map(|&b| (doc.artboards.get(b).map_or("", |a| a.name.as_str()), format!("Artboard-{}", b + 1))))
|
||||
}
|
||||
|
||||
/// File-name parts for `(name, fallback)` pairs (artboards, assets): the name with unsafe
|
||||
/// characters as `-`, the fallback when it is empty, and `-2`, `-3`… after a name already used
|
||||
/// (compared without case).
|
||||
pub(crate) fn unique_file_names<'a>(names: impl IntoIterator<Item = (&'a str, String)>) -> Vec<String> {
|
||||
distinct_names(names.into_iter().map(|(name, fallback)| {
|
||||
let base: String = name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '-' }).collect();
|
||||
if base.is_empty() { fallback } else { base }
|
||||
}))
|
||||
}
|
||||
|
||||
/// `names` with `-2`, `-3`… after a name already used (compared without case).
|
||||
pub(super) fn distinct_names(names: impl IntoIterator<Item = String>) -> Vec<String> {
|
||||
let mut taken = std::collections::HashSet::new();
|
||||
// The next number to try for each base: a name repeated many times doesn't search the numbers
|
||||
// taken before it.
|
||||
let mut next: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
||||
names
|
||||
.into_iter()
|
||||
.map(|base| {
|
||||
let mut name = base.clone();
|
||||
while !taken.insert(name.to_lowercase()) {
|
||||
let n = next.entry(base.to_lowercase()).or_insert(1);
|
||||
*n += 1;
|
||||
name = format!("{base}-{n}");
|
||||
}
|
||||
name
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}`
|
||||
/// (`files`: every file when there are several; `linked`: the images it links to); with no path
|
||||
/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`.
|
||||
pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result<Value> {
|
||||
let files = enc.named(doc, path.unwrap_or(name));
|
||||
let (main, linked) = files.split_at(enc.files.len());
|
||||
let row = |(name, bytes): &(String, std::borrow::Cow<[u8]>)| match path {
|
||||
Some(_) => json!(name),
|
||||
None => json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }),
|
||||
};
|
||||
if path.is_some() {
|
||||
for (p, bytes) in &files {
|
||||
write_file(p, bytes)?;
|
||||
}
|
||||
}
|
||||
let Some((first, bytes)) = main.first() else { return Err(EngineError::Other("the export wrote no file".into())) };
|
||||
let mut out = match path {
|
||||
Some(_) => json!({ "path": first, "bytes": bytes.len() }),
|
||||
None => json!({ "dataBase64": vectorcraft_format::base64_encode(bytes), "bytes": bytes.len() }),
|
||||
};
|
||||
if main.len() > 1 {
|
||||
out["files"] = main.iter().map(row).collect();
|
||||
}
|
||||
if !linked.is_empty() {
|
||||
out["linked"] = linked.iter().map(row).collect();
|
||||
}
|
||||
Ok(merge(out, extra))
|
||||
}
|
||||
|
||||
/// `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) {
|
||||
a.extend(b);
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// Appearance of Black › Printing / Exporting (#394): Output All Blacks as Rich Black makes RGB
|
||||
/// raster exports draw pure CMYK black as RGB black (`richBlack` on the encoder params).
|
||||
pub(crate) fn with_black_output(s: &Session, p: &Value) -> Value {
|
||||
if s.prefs.black_output == "rich" { merge(p.clone(), json!({ "richBlack": true })) } else { p.clone() }
|
||||
}
|
||||
|
||||
/// A file name for bytes handed back without a path: the document's title with `ext`.
|
||||
pub(crate) fn default_name(doc: &vectorcraft_doc::Document, ext: &str) -> String {
|
||||
let stem = std::path::Path::new(&doc.title).file_stem().map(|s| s.to_string_lossy().into_owned()).filter(|s| !s.is_empty());
|
||||
format!("{}.{ext}", stem.as_deref().unwrap_or("Untitled"))
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` → `{path, bytes, …extra}`; with no path → `{dataBase64, bytes, …extra}`.
|
||||
pub(crate) fn write_or_return(path: Option<&str>, bytes: &[u8], extra: Value) -> Result<Value> {
|
||||
let out = match path {
|
||||
Some(path) => {
|
||||
write_file(path, bytes)?;
|
||||
json!({ "path": path, "bytes": bytes.len() })
|
||||
}
|
||||
None => json!({ "dataBase64": vectorcraft_format::base64_encode(bytes), "bytes": bytes.len() }),
|
||||
};
|
||||
Ok(merge(out, extra))
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
use super::*;
|
||||
|
||||
/// One option a format's encoder reads from the export params.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct FormatOption {
|
||||
pub name: &'static str,
|
||||
/// JSON type: `number`, `integer`, `boolean`, `string`, `array` or `object`.
|
||||
pub ty: &'static str,
|
||||
/// The default as a JSON literal (`"1"`, `"false"`, `"null"`).
|
||||
pub default: &'static str,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
/// One file format: how `document.open` recognises it and what `document.export` writes.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Format {
|
||||
/// The `format` param value (`svg`, `png`, …).
|
||||
pub id: &'static str,
|
||||
/// Open/save dialog filter name.
|
||||
pub label: &'static str,
|
||||
/// Lower-case extensions without the dot; the first is the one exports use.
|
||||
pub extensions: &'static [&'static str],
|
||||
pub mime: &'static str,
|
||||
pub read: bool,
|
||||
pub write: bool,
|
||||
/// Pixels (export `scale` applies) rather than vectors.
|
||||
pub raster: bool,
|
||||
/// Options the encoder reads (writable formats).
|
||||
pub options: &'static [FormatOption],
|
||||
}
|
||||
|
||||
impl Format {
|
||||
pub fn to_json(&self) -> Value {
|
||||
let options: serde_json::Map<String, Value> = self
|
||||
.options
|
||||
.iter()
|
||||
.map(|o| {
|
||||
let default: Value = serde_json::from_str(o.default).unwrap_or(Value::Null);
|
||||
(o.name.to_string(), json!({"type": o.ty, "default": default, "description": o.description}))
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"extensions": self.extensions,
|
||||
"mime": self.mime,
|
||||
"read": self.read,
|
||||
"write": self.write,
|
||||
"raster": self.raster,
|
||||
"options": options,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const ARTBOARD: FormatOption = FormatOption {
|
||||
name: "artboard",
|
||||
ty: "integer",
|
||||
default: "0",
|
||||
description: "0-based artboard to export (`artboards: [i]` or `range: \"n\"` naming one artboard work too)",
|
||||
};
|
||||
|
||||
pub(super) const ARTBOARDS: FormatOption = FormatOption {
|
||||
name: "artboards",
|
||||
ty: "array",
|
||||
default: "null",
|
||||
description: "0-based artboards (PDF and AI: one page each, default all; SVG, and raster formats with useArtboards: one file each)",
|
||||
};
|
||||
|
||||
pub(super) const RANGE: FormatOption = FormatOption {
|
||||
name: "range",
|
||||
ty: "string",
|
||||
default: "null",
|
||||
description: "1-based artboards such as \"1-3, 5\", or \"all\" (wins over artboards and artboard)",
|
||||
};
|
||||
|
||||
const SCALE: FormatOption = FormatOption { name: "scale", ty: "number", default: "1", description: "pixels per point (0.01–64)" };
|
||||
|
||||
const QUALITY: FormatOption =
|
||||
FormatOption { name: "quality", ty: "integer", default: "90", description: "JPEG quality 0–100 (the JPEG Options dialog shows 0–10)" };
|
||||
|
||||
pub(super) const USE_ARTBOARDS: FormatOption = FormatOption {
|
||||
name: "useArtboards",
|
||||
ty: "boolean",
|
||||
default: "null",
|
||||
description: "true: every chosen artboard (default all), one file each named <file>-<artboard>.<ext> (PDF and AI: one page each); false: the bounds of the visible art",
|
||||
};
|
||||
|
||||
const RECT: FormatOption = FormatOption {
|
||||
name: "rect",
|
||||
ty: "array",
|
||||
default: "null",
|
||||
description: "[x, y, width, height] in document points, y down: exports that area of the page (no artboard needed, the document is not changed); not with artboard, artboards, range or useArtboards",
|
||||
};
|
||||
|
||||
const PPI: FormatOption = FormatOption {
|
||||
name: "ppi",
|
||||
ty: "number",
|
||||
default: "72",
|
||||
description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file; wins over scale",
|
||||
};
|
||||
|
||||
const BACKGROUND: FormatOption = FormatOption {
|
||||
name: "background",
|
||||
ty: "string",
|
||||
default: "\"transparent\"",
|
||||
description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent)",
|
||||
};
|
||||
|
||||
const ANTI_ALIAS: FormatOption = FormatOption {
|
||||
name: "antiAlias",
|
||||
ty: "string",
|
||||
default: "\"art\"",
|
||||
description: "none (hard pixel edges), art (smooth edges) or type (smooth, text snapped to whole pixels)",
|
||||
};
|
||||
|
||||
const INTERLACED: FormatOption =
|
||||
FormatOption { name: "interlaced", ty: "boolean", default: "false", description: "Adam7 interlacing (the image builds up while it loads)" };
|
||||
|
||||
const COLOR_MODEL: FormatOption = FormatOption {
|
||||
name: "colorModel",
|
||||
ty: "string",
|
||||
default: "\"rgb\"",
|
||||
description: "rgb, cmyk (ink amounts in the working CMYK space: CMYK colours keep their inks) or gray",
|
||||
};
|
||||
|
||||
const METHOD: FormatOption = FormatOption {
|
||||
name: "method",
|
||||
ty: "string",
|
||||
default: "\"baseline\"",
|
||||
description: "baseline (standard), optimized (smaller Huffman tables) or progressive (builds up in scans)",
|
||||
};
|
||||
|
||||
const SCANS: FormatOption = FormatOption { name: "scans", ty: "integer", default: "3", description: "progressive scans, 3–5" };
|
||||
|
||||
const EMBED_ICC: FormatOption = FormatOption {
|
||||
name: "embedIcc",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk)",
|
||||
};
|
||||
|
||||
const IMAGE_MAP: FormatOption = FormatOption {
|
||||
name: "imageMap",
|
||||
ty: "string",
|
||||
default: "\"none\"",
|
||||
description: "none, client (an HTML page with <map>, <stem>.html) or server (an NCSA <stem>.map): the areas of objects with a URL and an Image Map shape (attributes.set)",
|
||||
};
|
||||
|
||||
const COLORS: FormatOption =
|
||||
FormatOption { name: "colors", ty: "integer", default: "256", description: "most palette entries, 2–256 (the transparent one included)" };
|
||||
|
||||
const REDUCTION: FormatOption = FormatOption {
|
||||
name: "reduction",
|
||||
ty: "string",
|
||||
default: "\"selective\"",
|
||||
description: "the palette: perceptual, selective (also keeps rarer colours, snaps near web colours), adaptive (most used), web (web-safe), blackWhite or gray; art with that many colours or fewer keeps them exactly",
|
||||
};
|
||||
|
||||
const DITHER: FormatOption = FormatOption {
|
||||
name: "dither",
|
||||
ty: "string",
|
||||
default: "\"diffusion\"",
|
||||
description: "none, diffusion (Floyd–Steinberg), pattern (8×8 ordered) or noise",
|
||||
};
|
||||
|
||||
const DITHER_AMOUNT: FormatOption = FormatOption { name: "ditherAmount", ty: "integer", default: "100", description: "dither strength 0–100" };
|
||||
|
||||
const TRANSPARENCY: FormatOption = FormatOption {
|
||||
name: "transparency",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "pixels under half opacity become one transparent entry (false: everything is blended over the matte)",
|
||||
};
|
||||
|
||||
const MATTE: FormatOption = FormatOption {
|
||||
name: "matte",
|
||||
ty: "string",
|
||||
default: "\"white\"",
|
||||
description: "the colour partly transparent edges are blended over (\"#rrggbb\", white, black), or none (they keep their colour)",
|
||||
};
|
||||
|
||||
const LOSSLESS: FormatOption = FormatOption {
|
||||
name: "lossless",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "lossless WebP; false asks for lossy, which isn't available yet (written lossless, with a warning)",
|
||||
};
|
||||
|
||||
const WEBP_QUALITY: FormatOption =
|
||||
FormatOption { name: "quality", ty: "integer", default: "90", description: "lossy quality 0–100 (for when lossy WebP is available)" };
|
||||
|
||||
/// The options of the palette formats (PNG-8, GIF).
|
||||
const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
ARTBOARD,
|
||||
ARTBOARDS,
|
||||
RANGE,
|
||||
USE_ARTBOARDS,
|
||||
RECT,
|
||||
PPI,
|
||||
SCALE,
|
||||
BACKGROUND,
|
||||
ANTI_ALIAS,
|
||||
INTERLACED,
|
||||
COLORS,
|
||||
REDUCTION,
|
||||
DITHER,
|
||||
DITHER_AMOUNT,
|
||||
TRANSPARENCY,
|
||||
MATTE,
|
||||
];
|
||||
|
||||
const LZW: FormatOption = FormatOption { name: "lzw", ty: "boolean", default: "true", description: "LZW compression (lossless, smaller files)" };
|
||||
|
||||
const BYTE_ORDER: FormatOption = FormatOption {
|
||||
name: "byteOrder",
|
||||
ty: "string",
|
||||
default: "\"little\"",
|
||||
description: "the order of the bytes in the file's numbers: little (II, as on PCs) or big (MM)",
|
||||
};
|
||||
|
||||
const TIFF_OPTIONS: &[FormatOption] =
|
||||
&[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, BACKGROUND, ANTI_ALIAS, COLOR_MODEL, LZW, BYTE_ORDER, EMBED_ICC];
|
||||
|
||||
const BMP_COLOR_MODEL: FormatOption =
|
||||
FormatOption { name: "colorModel", ty: "string", default: "\"rgb\"", description: "rgb or gray (greys at every depth)" };
|
||||
|
||||
const BMP_DEPTH: FormatOption = FormatOption {
|
||||
name: "depth",
|
||||
ty: "integer",
|
||||
default: "24",
|
||||
description: "bits per pixel: 1 (black and white), 4 or 8 (a palette by reduction and dither), 16, 24, or 32 (keeps transparency); the others are flattened on white",
|
||||
};
|
||||
|
||||
const FILE_FORMAT: FormatOption = FormatOption {
|
||||
name: "fileFormat",
|
||||
ty: "string",
|
||||
default: "\"windows\"",
|
||||
description: "windows, or os2 (1, 4, 8 or 24 bits, uncompressed, rows bottom-up)",
|
||||
};
|
||||
|
||||
const RLE: FormatOption =
|
||||
FormatOption { name: "rle", ty: "boolean", default: "false", description: "run-length encode a 4- or 8-bit windows bitmap (RLE4, RLE8)" };
|
||||
|
||||
const FLIP_ROWS: FormatOption = FormatOption {
|
||||
name: "flipRows",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "rows top-down (a negative height) instead of bottom-up; not with rle or os2",
|
||||
};
|
||||
|
||||
const BMP_OPTIONS: &[FormatOption] = &[
|
||||
ARTBOARD,
|
||||
ARTBOARDS,
|
||||
RANGE,
|
||||
USE_ARTBOARDS,
|
||||
RECT,
|
||||
PPI,
|
||||
SCALE,
|
||||
BACKGROUND,
|
||||
ANTI_ALIAS,
|
||||
BMP_COLOR_MODEL,
|
||||
BMP_DEPTH,
|
||||
FILE_FORMAT,
|
||||
RLE,
|
||||
FLIP_ROWS,
|
||||
REDUCTION,
|
||||
DITHER,
|
||||
DITHER_AMOUNT,
|
||||
];
|
||||
|
||||
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)",
|
||||
};
|
||||
|
||||
const TGA_OPTIONS: &[FormatOption] = &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, BACKGROUND, ANTI_ALIAS, TGA_DEPTH];
|
||||
|
||||
const PSD_LAYERS: FormatOption = FormatOption {
|
||||
name: "layers",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent",
|
||||
};
|
||||
|
||||
const MAX_EDITABILITY: FormatOption = FormatOption {
|
||||
name: "maxEditability",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "with layers: layers and sublayers become groups and every object a layer of its own, named as the Layers panel names it (text by its text); clipping, masked or knockout layers stay one layer",
|
||||
};
|
||||
|
||||
const PSD_HIDDEN_LAYERS: FormatOption = FormatOption {
|
||||
name: "hiddenLayers",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "with layers: hidden layers (and hidden objects) are written as hidden layers instead of left out",
|
||||
};
|
||||
|
||||
const PSD_OPTIONS: &[FormatOption] = &[
|
||||
ARTBOARD,
|
||||
ARTBOARDS,
|
||||
RANGE,
|
||||
USE_ARTBOARDS,
|
||||
RECT,
|
||||
PPI,
|
||||
SCALE,
|
||||
BACKGROUND,
|
||||
ANTI_ALIAS,
|
||||
COLOR_MODEL,
|
||||
PSD_LAYERS,
|
||||
MAX_EDITABILITY,
|
||||
PSD_HIDDEN_LAYERS,
|
||||
EMBED_ICC,
|
||||
];
|
||||
|
||||
/// A format `document.open` reads but nothing writes yet.
|
||||
const fn reader(id: &'static str, label: &'static str, extensions: &'static [&'static str], mime: &'static str, raster: bool) -> Format {
|
||||
Format { id, label, extensions, mime, read: true, write: false, raster, options: &[] }
|
||||
}
|
||||
|
||||
/// Every format VectorCraft reads or writes. Append-only: new formats go at the end.
|
||||
pub const FORMATS: &[Format] = &[
|
||||
Format {
|
||||
id: "vectorcraft",
|
||||
label: "VectorCraft",
|
||||
extensions: &[vectorcraft_format::EXTENSION, vectorcraft_format::LEGACY_EXTENSION],
|
||||
mime: "application/json",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: native::OPTIONS,
|
||||
},
|
||||
Format { id: "svg", label: "SVG", extensions: &["svg"], mime: "image/svg+xml", read: true, write: true, raster: false, options: svg::OPTIONS },
|
||||
Format {
|
||||
id: "svgz",
|
||||
label: "SVG Compressed",
|
||||
extensions: &["svgz"],
|
||||
mime: "image/svg+xml",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: svg::OPTIONS,
|
||||
},
|
||||
Format { id: "pdf", label: "PDF", extensions: &["pdf"], mime: "application/pdf", read: true, write: true, raster: false, options: pdf::OPTIONS },
|
||||
Format {
|
||||
id: "ai",
|
||||
label: "PDF-compatible .ai",
|
||||
extensions: &["ai"],
|
||||
mime: "application/pdf",
|
||||
read: true,
|
||||
// Save As writes it; exports write the same file.
|
||||
write: true,
|
||||
raster: false,
|
||||
options: native::AI_OPTIONS,
|
||||
},
|
||||
Format {
|
||||
id: "ait",
|
||||
label: "PDF-compatible .ait template",
|
||||
extensions: &["ait"],
|
||||
mime: "application/pdf",
|
||||
read: true,
|
||||
// Save as Template writes it, with the .ai file's options; exports don't.
|
||||
write: false,
|
||||
raster: false,
|
||||
options: native::AI_OPTIONS,
|
||||
},
|
||||
Format {
|
||||
id: "png",
|
||||
label: "PNG",
|
||||
extensions: &["png"],
|
||||
mime: "image/png",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: true,
|
||||
options: &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, BACKGROUND, ANTI_ALIAS, INTERLACED, EMBED_ICC],
|
||||
},
|
||||
Format {
|
||||
id: "jpg",
|
||||
label: "JPEG",
|
||||
extensions: &["jpg", "jpeg"],
|
||||
mime: "image/jpeg",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: true,
|
||||
options: &[
|
||||
ARTBOARD,
|
||||
ARTBOARDS,
|
||||
RANGE,
|
||||
USE_ARTBOARDS,
|
||||
RECT,
|
||||
PPI,
|
||||
SCALE,
|
||||
BACKGROUND,
|
||||
ANTI_ALIAS,
|
||||
QUALITY,
|
||||
COLOR_MODEL,
|
||||
METHOD,
|
||||
SCANS,
|
||||
EMBED_ICC,
|
||||
IMAGE_MAP,
|
||||
],
|
||||
},
|
||||
Format { id: "gif", label: "GIF", extensions: &["gif"], mime: "image/gif", read: true, write: true, raster: true, options: PALETTE_OPTIONS },
|
||||
Format {
|
||||
id: "webp",
|
||||
label: "WebP",
|
||||
extensions: &["webp"],
|
||||
mime: "image/webp",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: true,
|
||||
options: &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, BACKGROUND, ANTI_ALIAS, LOSSLESS, WEBP_QUALITY],
|
||||
},
|
||||
Format {
|
||||
id: "tiff",
|
||||
label: "TIFF",
|
||||
extensions: &["tif", "tiff"],
|
||||
mime: "image/tiff",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: true,
|
||||
options: TIFF_OPTIONS,
|
||||
},
|
||||
Format { id: "bmp", label: "BMP", extensions: &["bmp"], mime: "image/bmp", read: true, write: true, raster: true, options: BMP_OPTIONS },
|
||||
Format {
|
||||
id: "template",
|
||||
label: "VectorCraft Template",
|
||||
extensions: &["vctemplate"],
|
||||
mime: "application/json",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: native::OPTIONS,
|
||||
},
|
||||
Format { id: "png8", label: "PNG-8", extensions: &["png"], mime: "image/png", read: false, write: true, raster: true, options: PALETTE_OPTIONS },
|
||||
Format { id: "txt", label: "Text", extensions: TEXT_EXTS, mime: "text/plain", read: false, write: true, raster: false, options: text::OPTIONS },
|
||||
Format { id: "dxf", label: "DXF", extensions: &["dxf"], mime: "image/vnd.dxf", read: true, write: true, raster: false, options: dxf::OPTIONS },
|
||||
Format {
|
||||
id: "eps",
|
||||
label: "EPS",
|
||||
extensions: &["eps", "epsf"],
|
||||
mime: "application/postscript",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: eps::OPTIONS,
|
||||
},
|
||||
Format { id: "emf", label: "EMF", extensions: &["emf"], mime: "image/emf", read: true, write: true, raster: false, options: metafile::OPTIONS },
|
||||
Format { id: "wmf", label: "WMF", extensions: &["wmf"], mime: "image/wmf", read: true, write: true, raster: false, options: metafile::OPTIONS },
|
||||
Format {
|
||||
id: "tga",
|
||||
label: "Targa",
|
||||
extensions: &["tga", "vda", "icb", "vst"],
|
||||
mime: "image/x-tga",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: true,
|
||||
options: TGA_OPTIONS,
|
||||
},
|
||||
Format { id: "psd", label: "PSD", extensions: &["psd"], mime: "image/x-psd", read: true, write: true, raster: true, options: PSD_OPTIONS },
|
||||
// Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a
|
||||
// vector app for a raster editor's documents.
|
||||
reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/x-affinity", false),
|
||||
// Photoshop's large document format: read like a PSD (its merged image), never written.
|
||||
reader("psb", "PSB", &["psb"], "image/x-psb", true),
|
||||
// PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't.
|
||||
reader("ps", "PostScript", &["ps"], "application/postscript", false),
|
||||
];
|
||||
|
||||
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
|
||||
pub const OPEN_EXTS: &[&str] = &[
|
||||
"vectorcraft",
|
||||
"drawcraft",
|
||||
"svg",
|
||||
"svgz",
|
||||
"pdf",
|
||||
"ai",
|
||||
"ait",
|
||||
"png",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"gif",
|
||||
"webp",
|
||||
"tif",
|
||||
"tiff",
|
||||
"bmp",
|
||||
"tga",
|
||||
"vda",
|
||||
"icb",
|
||||
"vst",
|
||||
"psd",
|
||||
"psb",
|
||||
"vctemplate",
|
||||
"dxf",
|
||||
"emf",
|
||||
"wmf",
|
||||
"eps",
|
||||
"epsf",
|
||||
"ps",
|
||||
"af",
|
||||
"afdesign",
|
||||
"afpub",
|
||||
];
|
||||
|
||||
/// 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` or Targa type (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.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst"];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
/// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order.
|
||||
pub fn export_extensions() -> Vec<&'static str> {
|
||||
let mut v: Vec<&'static str> = Vec::new();
|
||||
let added = plugin_formats();
|
||||
for e in FORMATS.iter().chain(added.iter().copied()).filter(|f| f.write).filter_map(|f| f.extensions.first()) {
|
||||
if !v.contains(e) {
|
||||
v.push(e);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Text files: File → Place sets them as area type (Text Import Options).
|
||||
pub const TEXT_EXTS: &[&str] = &["txt"];
|
||||
|
||||
/// RTF files: File → Place sets them as area type with their formatting.
|
||||
pub const RTF_EXTS: &[&str] = &["rtf"];
|
||||
|
||||
/// Word documents: File → Place sets them as area type with their formatting.
|
||||
pub const DOCX_EXTS: &[&str] = &["docx"];
|
||||
|
||||
/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`] and
|
||||
/// [`DOCX_EXTS`].
|
||||
pub const PLACE_EXTS: &[&str] = &[
|
||||
"vectorcraft",
|
||||
"drawcraft",
|
||||
"svg",
|
||||
"svgz",
|
||||
"pdf",
|
||||
"ai",
|
||||
"ait",
|
||||
"png",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"gif",
|
||||
"webp",
|
||||
"tif",
|
||||
"tiff",
|
||||
"bmp",
|
||||
"tga",
|
||||
"vda",
|
||||
"icb",
|
||||
"vst",
|
||||
"psd",
|
||||
"psb",
|
||||
"vctemplate",
|
||||
"dxf",
|
||||
"emf",
|
||||
"wmf",
|
||||
"eps",
|
||||
"epsf",
|
||||
"ps",
|
||||
"af",
|
||||
"afdesign",
|
||||
"afpub",
|
||||
"txt",
|
||||
"rtf",
|
||||
"docx",
|
||||
];
|
||||
|
||||
/// 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, f.extensions))
|
||||
}
|
||||
|
||||
/// Open-dialog filters: "All readable files" first, then one per readable format, then swatch
|
||||
/// libraries (which open in the library panel), Libraries panel libraries, flattener, PDF and print
|
||||
/// presets (imported), scripts (checked without running them) and plug-ins (installed).
|
||||
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All readable files", OPEN_EXTS))
|
||||
.chain(format_filters())
|
||||
.chain(std::iter::once(("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS)))
|
||||
.chain(std::iter::once(("Libraries", crate::cmd::library::LIBRARY_EXTS)))
|
||||
.chain(std::iter::once(("Flattener presets", crate::cmd::flatten::PRESET_EXTS)))
|
||||
.chain(std::iter::once(("PDF presets", crate::cmd::pdfcmds::PRESET_EXTS)))
|
||||
.chain(std::iter::once(("Print presets", crate::cmd::printpresets::PRESET_EXTS)))
|
||||
.chain(std::iter::once(("Shortcut sets", crate::cmd::shortcutset::EXTS)))
|
||||
.chain(std::iter::once(("Scripts", crate::cmd::scripts::EXTS)))
|
||||
.chain(std::iter::once(("Plug-ins", crate::cmd::plugin::EXTS)))
|
||||
}
|
||||
|
||||
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
|
||||
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
|
||||
/// match the default filter) still list `.ase` and the other library extensions; then the same
|
||||
/// filters as [`open_filters`] so a document can be picked for its swatches or graphic styles.
|
||||
pub fn library_open_filters(
|
||||
library_label: &'static str,
|
||||
library_exts: &'static [&'static str],
|
||||
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once((library_label, library_exts)).chain(open_filters())
|
||||
}
|
||||
|
||||
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
|
||||
/// RTF and Word.
|
||||
pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
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)))
|
||||
.chain(std::iter::once(("Word", DOCX_EXTS)))
|
||||
}
|
||||
|
||||
/// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in
|
||||
/// one, else one an exporter plug-in adds ([`plugin_formats`]). A built-in format keeps its
|
||||
/// extension, so an exporter that lists it too is found by its format id.
|
||||
pub fn format(id_or_ext: &str) -> Option<&'static Format> {
|
||||
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
FORMATS.iter().find(|f| f.id == k).or_else(|| FORMATS.iter().find(|f| f.extensions.contains(&k.as_str()))).or_else(|| {
|
||||
let added = plugin_formats();
|
||||
added.iter().find(|f| f.id.eq_ignore_ascii_case(&k)).or_else(|| added.iter().find(|f| f.extensions.contains(&k.as_str()))).copied()
|
||||
})
|
||||
}
|
||||
|
||||
/// The formats the installed exporter plug-ins add ([`vectorcraft_plugins::export`]), by plug-in
|
||||
/// id: write only, with the plug-in's name as the label and its extensions. Each is made once for
|
||||
/// each installation of its plug-in, its strings interned, so formats live as long as the catalogues
|
||||
/// that hold them.
|
||||
pub fn plugin_formats() -> Vec<&'static Format> {
|
||||
use vectorcraft_plugins::{export, registry};
|
||||
static MADE: std::sync::Mutex<Vec<(u64, &'static Format)>> = std::sync::Mutex::new(Vec::new());
|
||||
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
export::installed()
|
||||
.iter()
|
||||
.map(|p| {
|
||||
if let Some((_, f)) = made.iter().find(|(serial, _)| *serial == p.serial()) {
|
||||
return *f;
|
||||
}
|
||||
let m = p.manifest();
|
||||
let extensions: Vec<&'static str> = m.extensions.iter().map(|e| registry::intern(e)).collect();
|
||||
let f: &'static Format = Box::leak(Box::new(Format {
|
||||
id: registry::intern(&export::format_id(&m.id)),
|
||||
label: registry::intern(&m.name),
|
||||
extensions: Box::leak(extensions.into_boxed_slice()),
|
||||
mime: "application/octet-stream",
|
||||
read: false,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: &[],
|
||||
}));
|
||||
made.push((p.serial(), f));
|
||||
f
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The lower-case extension of a file name or path (empty when it has none).
|
||||
pub fn extension(name: &str) -> String {
|
||||
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A file name or path without its folder and extension (`/a/Poster.svg` → `Poster`).
|
||||
pub fn file_stem(name: &str) -> String {
|
||||
std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string())
|
||||
}
|
||||
|
||||
/// What a `format` export of `doc`, whose file is `path`, writes when it isn't `doc` itself: a
|
||||
/// document that only has the Untitled-N name New gave it is titled after its file, as its tab is
|
||||
/// (the title PDF, PNG and SVG metadata carry). A title of its own stays, and native files keep
|
||||
/// the stored title.
|
||||
pub fn has_own_title(doc: &vectorcraft_doc::Document) -> bool {
|
||||
!doc.title.trim().is_empty() && !doc.title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
pub fn titled_for_export(doc: &vectorcraft_doc::Document, path: Option<&str>, format: &str) -> Option<vectorcraft_doc::Document> {
|
||||
let path = path.filter(|_| !has_own_title(doc) && !matches!(format, "vectorcraft" | "template" | "ai"))?;
|
||||
let mut d = doc.clone();
|
||||
d.title = file_stem(path);
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// The format a file name's extension names.
|
||||
pub fn format_for_name(name: &str) -> Option<&'static Format> {
|
||||
Some(extension(name)).filter(|e| !e.is_empty()).and_then(|e| format(&e))
|
||||
}
|
||||
|
||||
/// The format to write: `format` (an id or extension), else the path's extension, else PNG. For a
|
||||
/// `.ait` template it returns an error that names `file.saveAsTemplate`, which writes it.
|
||||
pub fn writable_format(format_param: Option<&str>, path: Option<&str>) -> std::result::Result<&'static Format, String> {
|
||||
// Formats that can't be written say what to use instead.
|
||||
let unknown = |what: String, key: &str| unsupported(key).map_or(what, |u| u.hint.to_string());
|
||||
let f = match (format_param, path.map(extension).filter(|e| !e.is_empty())) {
|
||||
(Some(f), _) => format(f).ok_or_else(|| unknown(format!("unknown format `{f}` (see document.formats)"), f))?,
|
||||
(None, Some(e)) => format(&e).ok_or_else(|| unknown(format!("unknown extension `.{e}`: pass `format` (see document.formats)"), &e))?,
|
||||
(None, None) => format("png").ok_or("no PNG encoder")?,
|
||||
};
|
||||
if f.write {
|
||||
Ok(f)
|
||||
} else if TEMPLATE_FORMATS.contains(&f.id) {
|
||||
Err(format!("{} files are written by file.saveAsTemplate", f.label))
|
||||
} else {
|
||||
Err(format!("{} files can be opened but not written (see document.formats)", f.label))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`writable_format`] for command `cmd`.
|
||||
pub(super) fn writable(cmd: &str, format_param: Option<&str>, path: Option<&str>) -> Result<&'static Format> {
|
||||
writable_format(format_param, path).map_err(|e| bad(cmd, e))
|
||||
}
|
||||
|
||||
pub(super) fn formats(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let added = plugin_formats();
|
||||
let all = || FORMATS.iter().chain(added.iter().copied());
|
||||
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 let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) {
|
||||
v["plugin"] = json!(id);
|
||||
}
|
||||
v
|
||||
};
|
||||
Ok(json!({
|
||||
"formats": all().map(listed).collect::<Vec<_>>(),
|
||||
"readable": ids(|f| f.read),
|
||||
"writable": ids(|f| f.write),
|
||||
"openExtensions": OPEN_EXTS,
|
||||
"unsupported": UNSUPPORTED.iter().map(Unsupported::to_json).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
@@ -15,7 +15,14 @@
|
||||
//! blending mode written opaque is a box hiding the art under it (version 7 images have no alpha
|
||||
//! channel, §8.1). With `flatten` (the default) each becomes an opaque image of itself and the art
|
||||
//! under it, rendered from the document as it is, clipped to the area where it changes what shows;
|
||||
//! the art under it stays as it was. With `omit` they are left out.
|
||||
//! the art under it stays as it was. An image in a group with opacity or a blending mode is
|
||||
//! flattened the same way, and a pattern fill that paints a transparent image (see-through
|
||||
//! pixels, or opacity or a blending mode on the image, the fill, the shape or a group it is in) is
|
||||
//! expanded into its tiles first so its images flatten too. With `omit` the images with
|
||||
//! see-through pixels, opacity or a blending mode of their own are left out, and pattern fills stay
|
||||
//! as the writer draws them (their tiles opaque over white). An image that can't be decoded is
|
||||
//! missing from the images that flattening and expanding raster effects draw, and the warnings
|
||||
//! then carry the raster exports' note once.
|
||||
//!
|
||||
//! The format can't hide objects, only layers (`hiddenObjects`): with `layer` (the default) each
|
||||
//! layer's hidden objects go to a hidden layer of their own just above it, with `omit` they are
|
||||
@@ -33,15 +40,20 @@ use vectorcraft_geom::{Anchor, FillRule, PathData, Point, Rect, SubPath};
|
||||
use super::super::*;
|
||||
use super::{ArtboardPick, Encoded, Format};
|
||||
|
||||
/// Does `p` ask for a legacy `.ai` file of version 7 (`aiVersion: "7"`)? An unknown version is an error.
|
||||
pub(super) fn wanted(cmd: &str, p: &Value) -> Result<bool> {
|
||||
match p.get("aiVersion") {
|
||||
None | Some(Value::Null) => Ok(false),
|
||||
Some(Value::String(v)) if v.trim().is_empty() || v.eq_ignore_ascii_case("pdf") => Ok(false),
|
||||
Some(Value::String(v)) if v.trim() == "7" => Ok(true),
|
||||
Some(Value::Number(n)) if n.as_f64() == Some(7.0) => Ok(true),
|
||||
Some(v) => Err(bad(cmd, format!("aiVersion {v}: \"pdf\" (PDF-compatible, the default) or \"7\" (legacy .ai, version 7)"))),
|
||||
/// Does `p` ask a save in `f` for a legacy `.ai` file of version 7 (`aiVersion: "7"`)? An unknown
|
||||
/// version is an error, and so is version 7 for a `.ait` template, which is PDF-compatible only.
|
||||
pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result<bool> {
|
||||
let legacy = match p.get("aiVersion") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::String(v)) if v.trim().is_empty() || v.eq_ignore_ascii_case("pdf") => false,
|
||||
Some(Value::String(v)) if v.trim() == "7" => true,
|
||||
Some(Value::Number(n)) if n.as_f64() == Some(7.0) => true,
|
||||
Some(v) => return Err(bad(cmd, format!("aiVersion {v}: \"pdf\" (PDF-compatible, the default) or \"7\" (legacy .ai, version 7)"))),
|
||||
};
|
||||
if legacy && f.id == "ait" {
|
||||
return Err(bad(cmd, "aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible"));
|
||||
}
|
||||
Ok(legacy)
|
||||
}
|
||||
|
||||
/// What a legacy `.ai` does with the images it can't hold (`transparentImages`).
|
||||
@@ -103,12 +115,16 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
if boards.len() > 1 {
|
||||
enc.warnings.push(SEPARATE.to_string());
|
||||
}
|
||||
let created = vectorcraft_doc::metadata::now_unix();
|
||||
let created = vectorcraft_doc::metadata::output_time();
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
for b in boards {
|
||||
let one = super::save::artboard_doc(doc, b);
|
||||
let (full, placed) = crate::cmd::place::document::full_documents(&one);
|
||||
let mut d = full.into_owned();
|
||||
expand_appearances(&mut d);
|
||||
if mode == SeeThrough::Flatten {
|
||||
expand_image_patterns(&mut d)?;
|
||||
}
|
||||
let images = see_through_images(&d, mode);
|
||||
if !images.is_empty() {
|
||||
note(&mut enc.warnings, if mode == SeeThrough::Flatten { FLATTENED } else { OMITTED });
|
||||
@@ -127,6 +143,11 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
}
|
||||
enc.files.push((Some(b), out.bytes));
|
||||
}
|
||||
// Expanding raster effects and flattening images draw the art, and an image the renderer
|
||||
// couldn't decode drew nothing there.
|
||||
if let Some(w) = super::super::rasterfx::undecoded_warning(failed) {
|
||||
note(&mut enc.warnings, w);
|
||||
}
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
@@ -140,17 +161,30 @@ fn expand_appearances(d: &mut Document) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand every layer's pattern fills that paint a transparent image into their tiles, so those
|
||||
/// images flatten like any other transparent image. The writer would otherwise draw them opaque
|
||||
/// over white.
|
||||
fn expand_image_patterns(d: &mut Document) -> Result<()> {
|
||||
let keys = super::super::flatten::see_through_images(d);
|
||||
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
|
||||
for id in layers {
|
||||
super::super::expand::expand_transparent_image_patterns(d, id, &keys)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as
|
||||
/// [`Document::walk`] counts): those with see-through pixels, opacity or a blending mode. Only
|
||||
/// visible ones flatten (a hidden one, which the hidden objects option may write, is written over
|
||||
/// white); all are left out with `omit`.
|
||||
/// [`Document::walk`] counts). These are the images with see-through pixels, and the images
|
||||
/// that have opacity or a blending mode of their own or, with `flatten`, of a group they are in.
|
||||
/// With `flatten` only visible images are returned, because a hidden one (which the hidden objects
|
||||
/// option may write) is written over white. With `omit` all of them are returned.
|
||||
fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
|
||||
let keys = super::super::flatten::see_through_images(d);
|
||||
let mut out = vec![];
|
||||
let mut at = 0;
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& (keys.contains(&im.key) || n.opacity < 1.0 || n.blend != BlendMode::Normal)
|
||||
&& (keys.contains(&im.key) || n.opacity < 1.0 || n.blend != BlendMode::Normal || (mode == SeeThrough::Flatten && transparent(d, n.id)))
|
||||
{
|
||||
out.push((at, n.id));
|
||||
}
|
||||
@@ -162,6 +196,12 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether node `id` or a group it is in has opacity or a blending mode. [`Document::ancestry`]
|
||||
/// lists `id` itself last, so its own opacity and blending mode count too.
|
||||
fn transparent(d: &Document, id: NodeId) -> bool {
|
||||
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| n.opacity < 1.0 || n.blend != BlendMode::Normal)
|
||||
}
|
||||
|
||||
/// Replace each of `images` (from [`see_through_images`]) with an opaque image of what shows
|
||||
/// where it is, clipped to where it changes that; one that changes nothing is left out. Each is
|
||||
/// rendered from `d` as it was, so images over one another flatten as they look.
|
||||
@@ -175,7 +215,8 @@ fn flatten_images(d: &mut Document, images: &[(usize, NodeId)]) -> Result<()> {
|
||||
let png = flat.png;
|
||||
let key = super::super::menucmds::unique_key(d, "flattened");
|
||||
d.images.insert(key.clone(), ImageBlob::new("image/png", png));
|
||||
let image = ImageObject { key, width: flat.width, height: flat.height, xf: flat.xf, link: None, placement: Default::default() };
|
||||
let image =
|
||||
ImageObject { key, width: flat.width, height: flat.height, xf: flat.xf, link: None, placement: Default::default(), pixels: None };
|
||||
let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
|
||||
let mut group = super::super::rasterfx::clip_group(d, flat.clip, FillRule::NonZero, image);
|
||||
group.name = src.node(id).and_then(|n| n.name.clone());
|
||||
|
||||
@@ -26,6 +26,9 @@ pub struct Loaded {
|
||||
/// Only a stand-in picture of the file (an Affinity document whose native data couldn't be
|
||||
/// read): Open shows it with its warning; Place, templates and libraries refuse it.
|
||||
pub preview_only: bool,
|
||||
/// A PDF, or a `.ai` or `.ait` that holds a PDF, read through the editor's own copy of its art
|
||||
/// that it carries (its layers), not from its PDF part alone.
|
||||
pub editing_data: bool,
|
||||
}
|
||||
|
||||
impl Loaded {
|
||||
@@ -156,17 +159,17 @@ pub fn load(name: &str, bytes: &[u8]) -> Result<Loaded> {
|
||||
/// of its art, which it carries: its layers and hidden objects as they were, and the art outside
|
||||
/// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read.
|
||||
/// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its
|
||||
/// first page's `UserUnit`).
|
||||
fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec<String>, unit: f64) -> (Document, Vec<String>) {
|
||||
/// first page's `UserUnit`) → (document, warnings, whether its layers were read).
|
||||
fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec<String>, unit: f64) -> (Document, Vec<String>, bool) {
|
||||
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
|
||||
return (doc, warnings);
|
||||
return (doc, warnings, false);
|
||||
}
|
||||
let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings) };
|
||||
let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings, false) };
|
||||
let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines;
|
||||
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(&private, doc, warnings, outlined, opts.trust_editing_data, unit);
|
||||
// The layers weren't read (or couldn't be): the notes of reading the PDF part still hold.
|
||||
if !read {
|
||||
return (doc, warnings);
|
||||
return (doc, warnings, false);
|
||||
}
|
||||
// The layers' text objects hold type and the stroked paths around it, which can include stroked
|
||||
// glyphs the PDF part kept as outlines: without any such glyph in the document, the warnings on
|
||||
@@ -177,7 +180,7 @@ fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warning
|
||||
// The layers hold the art that the PDF part leaves out or, in a PDF, that the import clipped
|
||||
// to the page.
|
||||
warnings.retain(|w| w != vectorcraft_pdf::OFF_ARTBOARD_NOTE && w != vectorcraft_pdf::PAST_PAGE_NOTE);
|
||||
(doc, warnings)
|
||||
(doc, warnings, true)
|
||||
}
|
||||
|
||||
/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page) from the editor's
|
||||
@@ -194,6 +197,38 @@ fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option<Result<(D
|
||||
)
|
||||
}
|
||||
|
||||
/// Is `e` the error of a file whose pages are only a placeholder
|
||||
/// ([`vectorcraft_pdf::PdfError::PlaceholderOnly`])?
|
||||
pub(crate) fn is_placeholder(e: &EngineError) -> bool {
|
||||
e.to_string() == vectorcraft_pdf::PdfError::PlaceholderOnly.to_string()
|
||||
}
|
||||
|
||||
/// Do `opts` read every page of the PDF `bytes`: no `pages`, or a range that names each one?
|
||||
fn every_page(bytes: &[u8], opts: &LoadOptions) -> bool {
|
||||
let Some(range) = &opts.pages else { return true };
|
||||
vectorcraft_pdf::info(bytes, opts.password.as_deref()).is_ok_and(|i| parse_range(range, i.pages.len()).is_ok_and(|p| p.len() == i.pages.len()))
|
||||
}
|
||||
|
||||
/// A page read from a PDF or `.ai` (`read`, as [`super::page_document`] reads it) → (document,
|
||||
/// notes, false); for a `.ai` saved without PDF compatibility (its page only a placeholder), the
|
||||
/// file `name` read as `document.open` reads it with `password`, from its editing copy alone →
|
||||
/// (document, notes, true).
|
||||
pub(crate) fn page_or_editing_data(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
password: Option<&str>,
|
||||
read: Result<(Document, Vec<String>)>,
|
||||
) -> Result<(Document, Vec<String>, bool)> {
|
||||
match read {
|
||||
Ok((doc, notes)) => Ok((doc, notes, false)),
|
||||
Err(e) if is_placeholder(&e) => {
|
||||
let l = load_with(name, bytes, &LoadOptions { password: password.map(str::to_string), ..Default::default() })?;
|
||||
Ok((l.doc, l.warnings, true))
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`load`] with `document.open` options (the PDF pages, box and password; the DXF options).
|
||||
pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> {
|
||||
let format = detect(name, bytes).ok_or_else(|| match super::unsupported(&super::extension(name)) {
|
||||
@@ -203,12 +238,14 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let title = file_name(name);
|
||||
let mut converted = false;
|
||||
let mut preview_only = false;
|
||||
let mut editing_data = false;
|
||||
let (mut doc, mut warnings, restored) = match format.id {
|
||||
// EPS, .ps and PostScript .ai: the document our EPS files carry, else the PostScript read.
|
||||
_ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => {
|
||||
let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes)));
|
||||
restore_or_import(editing, || {
|
||||
let r = vectorcraft_eps::import_with(bytes, opts.editing_data).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
|
||||
let r = vectorcraft_eps::import_trusting(bytes, opts.editing_data, opts.trust_editing_data)
|
||||
.map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
|
||||
Ok((r.document, r.warnings))
|
||||
})?
|
||||
}
|
||||
@@ -237,11 +274,20 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// Pages of text alone: the editing copy alone where it reads, as for a file
|
||||
// saved without its PDF part (#1387: else the page, which is the art).
|
||||
let alone = r.only_text.then(|| from_editing_data_alone(bytes, opts)).flatten().and_then(|read| read.ok());
|
||||
Ok(alone.unwrap_or_else(|| through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit)))
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit),
|
||||
};
|
||||
editing_data = read;
|
||||
Ok((doc, warnings))
|
||||
}
|
||||
// Saved without its PDF part: the editing copy is all the file has.
|
||||
Err(e) if e.to_string() == vectorcraft_pdf::PdfError::PlaceholderOnly.to_string() => {
|
||||
from_editing_data_alone(bytes, opts).unwrap_or(Err(e))
|
||||
// Saved without its PDF part: the editing copy is all the file has (`pages` that
|
||||
// name every page read it as the whole file).
|
||||
Err(e) if is_placeholder(&e) => {
|
||||
let whole = LoadOptions { pages: None, ..opts.clone() };
|
||||
from_editing_data_alone(bytes, if every_page(bytes, opts) { &whole } else { opts })
|
||||
.unwrap_or(Err(e))
|
||||
.inspect(|_| editing_data = true)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
})?
|
||||
@@ -277,6 +323,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc);
|
||||
} else if !doc.text_threads.is_empty() {
|
||||
crate::cmd::threads::share_optical_margin(&mut doc);
|
||||
// A frame whose first paragraph continues from the frame before draws it without the
|
||||
// paragraph's first-line indent and list marker.
|
||||
crate::cmd::threads::mark_continued(&mut doc);
|
||||
}
|
||||
if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) {
|
||||
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays);
|
||||
@@ -286,8 +335,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
if !matches!(format.id, "vectorcraft" | "template") || doc.title.is_empty() {
|
||||
doc.title = title;
|
||||
}
|
||||
warnings.extend(doc.images.values().filter_map(|b| too_large_note(&b.bytes)));
|
||||
Ok(Loaded { doc, format, warnings, restored, converted, preview_only })
|
||||
warnings.extend(doc.images.values().filter_map(|b| size_note(&b.bytes)));
|
||||
Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data })
|
||||
}
|
||||
|
||||
/// Import SVG text, reading the files its images link to (relative links from `folder`, the SVG's
|
||||
@@ -297,8 +346,11 @@ pub(crate) fn import_svg(text: &str, folder: Option<&str>) -> Result<(Document,
|
||||
// The importer reads on a thread of its own (for its stack): what may be read is what may be
|
||||
// read here.
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
// Paths are checked as stored in a document inside `folder` (only the folder is used).
|
||||
let document = folder.map(|f| std::path::Path::new(f).join("-").to_string_lossy().into_owned());
|
||||
let read = |path: &str| {
|
||||
scope.clone().run(|| {
|
||||
let path = &super::document_path(path, document.as_deref()).ok()?;
|
||||
// Only files (not folders or devices) are read.
|
||||
file_stamp(path)?;
|
||||
let bytes = read_file(path).ok()?;
|
||||
@@ -321,7 +373,7 @@ pub fn open_bytes(s: &mut Session, name: &str, bytes: &[u8], path: Option<String
|
||||
/// [`open_bytes`] with the `document.open` options in `p` ([`LoadOptions::from_params`]).
|
||||
pub fn open_bytes_with(s: &mut Session, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> Result<Value> {
|
||||
let update_links = s.prefs.update_links == "automatically";
|
||||
open_read(s, read_for_open(name, bytes, path, p, update_links)?)
|
||||
open_read(s, read_for_open(name, bytes, path, p, update_links, s.prefs.low_res_proxy_eps)?)
|
||||
}
|
||||
|
||||
/// A file read for `document.open` but not opened yet ([`read_for_open`], [`open_read`]).
|
||||
@@ -347,10 +399,10 @@ impl ReadFile {
|
||||
/// [`open_read`] opens. The linked files are looked for from `path`, where the file was read from,
|
||||
/// and modified ones are read again when `update_links` (Preferences › File Handling › Update
|
||||
/// Links set to Automatically; see [`crate::cmd::links::resolve`]).
|
||||
pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value, update_links: bool) -> Result<ReadFile> {
|
||||
pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result<ReadFile> {
|
||||
let opts = LoadOptions::from_params("document.open", p)?;
|
||||
let mut loaded = load_with(name, bytes, &opts)?;
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, path.as_deref(), update_links);
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, path.as_deref(), update_links, low_res_proxy_eps);
|
||||
Session::refresh_text_bounds(&mut loaded.doc);
|
||||
Ok(ReadFile { loaded, opts, path, links })
|
||||
}
|
||||
@@ -370,7 +422,7 @@ pub fn open_template(s: &mut Session, name: &str, bytes: &[u8], path: Option<&st
|
||||
"only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first",
|
||||
));
|
||||
}
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, path, s.prefs.update_links == "automatically");
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, path, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
|
||||
open_loaded(s, loaded, links, path.map(str::to_string), &LoadOptions::default(), true)
|
||||
}
|
||||
|
||||
@@ -405,12 +457,21 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
|
||||
let st = s.doc_mut()?;
|
||||
if saves_back {
|
||||
st.format = format.id;
|
||||
// An SVG that reopened as the full document saves as one again: Save keeps Preserve
|
||||
// Editing, as it would after a save of this session (#3867).
|
||||
if restored && matches!(format.id, "svg" | "svgz") {
|
||||
st.save_options.insert("preserveEditing".into(), json!(true));
|
||||
}
|
||||
}
|
||||
st.converted = converted;
|
||||
st.imported_from = source_path;
|
||||
st.import_losses = losses;
|
||||
let title = s.documents()[index].title();
|
||||
Ok(super::merge(json!({ "index": index, "title": title, "format": format.id, "warnings": warnings, "restored": restored }), links.to_json()))
|
||||
let opened = &s.documents()[index];
|
||||
let (title, file_info_title) = (opened.title(), opened.doc.title.clone());
|
||||
Ok(super::merge(
|
||||
json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }),
|
||||
links.to_json(),
|
||||
))
|
||||
}
|
||||
|
||||
/// A file named by a command's params: `{path}` (read from disk) or `{name, dataBase64}`.
|
||||
@@ -454,8 +515,8 @@ pub(crate) use vectorcraft_doc::MAX_RASTER_ALLOC;
|
||||
|
||||
/// What to say of encoded image `bytes` that need more than [`MAX_RASTER_ALLOC`] to decode,
|
||||
/// counted as RGBA (4 bytes a pixel) or as the decoder gives them when that is more (its header
|
||||
/// says so; the pixels aren't read): Open, Place and the Links panel say it (#1479). `None` for
|
||||
/// images within the allowance, and for bytes that aren't an image.
|
||||
/// says so; the pixels aren't read): Open, Place and the Links panel say it ([`size_note`], #1479).
|
||||
/// `None` for images within the allowance, and for bytes that aren't an image.
|
||||
pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
|
||||
use image::ImageDecoder as _;
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
@@ -469,6 +530,17 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
|
||||
(rgba_over || d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
|
||||
}
|
||||
|
||||
/// What Open, Place and the Links panel say of encoded image `bytes` that [`too_large_note`] is
|
||||
/// said of: that the image is shown at reduced size when the renderer decodes it smaller
|
||||
/// ([`vectorcraft_render::reduced_size`]), nothing when the renderer reads it at its own size a
|
||||
/// row at a time, otherwise that note. Returns `None` when [`too_large_note`] returns `None`.
|
||||
pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
let note = too_large_note(bytes)?;
|
||||
let Some(drawn) = vectorcraft_render::reduced_size(bytes) else { return Some(note) };
|
||||
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
|
||||
(drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size"))
|
||||
}
|
||||
|
||||
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
|
||||
/// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per
|
||||
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
|
||||
@@ -478,6 +550,10 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
|
||||
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
|
||||
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
|
||||
/// either, become RGBA too, whether they store their channels together or one plane per channel.
|
||||
/// A Targa file, which starts with no signature, is recognized by its header
|
||||
/// ([`super::tgaread::is_targa`]) and becomes RGBA with the transparency it stores
|
||||
/// ([`super::tgaread::fix_alpha`]). An image stored as PNG whose decoded samples, or whose pixels
|
||||
/// as RGBA, need more than [`MAX_RASTER_ALLOC`] is refused as too large to draw.
|
||||
/// A TIFF with more strips or tiles than the decoder can count
|
||||
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw.
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
@@ -490,6 +566,9 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, ppi);
|
||||
}
|
||||
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
|
||||
if reader.format().is_none() && super::tgaread::is_targa(bytes) {
|
||||
reader.set_format(image::ImageFormat::Tga);
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
@@ -508,13 +587,25 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
|
||||
};
|
||||
let img = match (f.id == "tiff").then(extra_samples).flatten() {
|
||||
let mut img = match (f.id == "tiff").then(extra_samples).flatten() {
|
||||
Some(img) => img,
|
||||
None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() {
|
||||
Some(read) => read.map_err(err)?,
|
||||
None => reader.decode().map_err(err)?.to_rgba8(),
|
||||
None => {
|
||||
use image::ImageDecoder as _;
|
||||
let decoder = reader.into_decoder().map_err(err)?;
|
||||
// The allowance counts the decoded samples and the RGBA pixels they become (#1717).
|
||||
let (w, h) = decoder.dimensions();
|
||||
if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC {
|
||||
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
image::DynamicImage::from_decoder(decoder).map_err(err)?.to_rgba8()
|
||||
}
|
||||
},
|
||||
};
|
||||
if f.id == "tga" {
|
||||
super::tgaread::fix_alpha(bytes, &mut img);
|
||||
}
|
||||
as_png(img, ppi)
|
||||
}
|
||||
|
||||
@@ -585,8 +676,10 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let xf = Affine::scale_non_uniform(sx, sy);
|
||||
let mut n =
|
||||
Node::new(id, NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default() })));
|
||||
let mut n = Node::new(
|
||||
id,
|
||||
NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })),
|
||||
);
|
||||
n.name = Some(name.to_string());
|
||||
d.images.insert(key, blob);
|
||||
d.insert(Some(layer), 0, n).map_err(err)?;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -103,7 +103,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
|
||||
name: "aiVersion",
|
||||
ty: "string",
|
||||
default: "\"pdf\"",
|
||||
description: "pdf (a PDF-compatible .ai carrying the VectorCraft document) or 7 (the legacy, PostScript-form .ai of version 7, which keeps layers, groups, compound paths and clipping groups in apps that read it; one file per artboard, transparent objects opaque; the other .ai options don't apply)",
|
||||
description: "pdf (a PDF-compatible .ai carrying the VectorCraft document) or 7 (the legacy, PostScript-form .ai of version 7, which keeps layers, groups, compound paths and clipping groups in apps that read it; one file per artboard, transparent objects opaque; the other .ai options don't apply; an error for a .ait template)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "transparentImages",
|
||||
@@ -121,7 +121,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
|
||||
name: "outlineText",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "with aiVersion 7, type as its outlines instead of text (which apps reading the file set in the fonts it names: they need them installed); type 8-bit text can't hold (characters outside Windows Latin-1, vertical type, inline graphics, gradient or pattern fills) is always outlines",
|
||||
description: "with aiVersion 7, type as its outlines instead of text (which apps reading the file set in the fonts it names: they need them installed); type 8-bit text can't hold (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is always outlines",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -146,10 +146,13 @@ pub(super) struct Extras {
|
||||
/// are left to [`encode`]).
|
||||
pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<(SaveOptions, Extras)> {
|
||||
let o: NativeOptions = super::encode::options(f, p)?;
|
||||
let mut so = SaveOptions::for_doc(doc);
|
||||
so.compress = o.compress.unwrap_or(false);
|
||||
so.version = o.version.unwrap_or(vectorcraft_format::VERSION);
|
||||
so.include_linked = o.include_linked;
|
||||
// Pretty or compact is decided by [`encode_to`] on the document it writes.
|
||||
let mut so = SaveOptions {
|
||||
compress: o.compress.unwrap_or(false),
|
||||
version: o.version.unwrap_or(vectorcraft_format::VERSION),
|
||||
include_linked: o.include_linked,
|
||||
..SaveOptions::default()
|
||||
};
|
||||
if o.embed_profiles.unwrap_or(true) {
|
||||
so.profiles = embedded_profiles(doc);
|
||||
}
|
||||
@@ -190,6 +193,7 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
so.pretty = so.pretty_fits(&native);
|
||||
vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
|
||||
@@ -235,11 +235,22 @@ pub fn expand_preset<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a,
|
||||
super::eps::with_flattener(s, cmd, expanded)
|
||||
}
|
||||
|
||||
/// The full export options for `doc`: settings plus the artboards `p` picks (default all).
|
||||
/// The full export options for `doc`: settings plus the artboards `p` picks (default all), created
|
||||
/// at `doc`'s File Info creation date (the time of writing when it has none) and modified at the
|
||||
/// time of writing. On the web, which has no clock, the creation date is the modification date too,
|
||||
/// and a document without one gets neither.
|
||||
pub fn options(cmd: &str, doc: &Document, p: &Value) -> Result<PdfOptions> {
|
||||
let pick = if p.is_object() { ArtboardPick::deserialize(p).map_err(|e| bad(cmd, format!("PDF options: {e}")))? } else { ArtboardPick::default() };
|
||||
let artboards = pick.resolve(doc.artboards.len()).map_err(|e| bad(cmd, e))?;
|
||||
Ok(PdfOptions { settings: settings(cmd, p)?, artboards, ..Default::default() })
|
||||
let now = vectorcraft_doc::metadata::output_time();
|
||||
Ok(PdfOptions {
|
||||
settings: settings(cmd, p)?,
|
||||
artboards,
|
||||
display_doc_title: bool_or(p, "_displayDocTitle", super::has_own_title(doc)),
|
||||
created: doc.metadata.created.or(now),
|
||||
modified: now,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Why a PDF of some artboards carries no editing data.
|
||||
@@ -383,8 +394,15 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let expanded = expand_preset(s, C, p)?;
|
||||
let p = &*expanded;
|
||||
let st = s.doc()?;
|
||||
let display_doc_title = super::has_own_title(&st.doc);
|
||||
let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf");
|
||||
let (bytes, warnings) = encode(C, titled.as_ref().unwrap_or(&st.doc), p)?;
|
||||
let mut q = p.clone();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.insert("_displayDocTitle".into(), json!(display_doc_title));
|
||||
} else {
|
||||
q = json!({ "_displayDocTitle": display_doc_title });
|
||||
}
|
||||
let (bytes, warnings) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?;
|
||||
write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": warnings }))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Opening and placing PDF (and PDF-compatible `.ai`/`.ait`) files: the options `document.open`
|
||||
//! and `file.place` read ([`LoadOptions`]), the pages they import and `document.pdfInfo` (pages,
|
||||
//! boxes, a thumbnail) for the Import PDF dialog.
|
||||
//! boxes, a thumbnail; one page for a PostScript file) for the Import PDF dialog.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{ColorMode, Document};
|
||||
@@ -143,13 +143,13 @@ pub(super) fn import(bytes: &[u8], o: &LoadOptions, editor_document: bool) -> Re
|
||||
}
|
||||
|
||||
/// Page `page` (0-based) of a PDF as a document of one artboard (its `o.crop` box) and one
|
||||
/// layer of what it shows (text as outlines: it looks as printed), and the import notes.
|
||||
/// layer of what it shows, with the same text choice as Open, and the import notes.
|
||||
pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
let opts = ImportOptions {
|
||||
pages: Some(vec![page]),
|
||||
crop: o.crop,
|
||||
password: o.password.clone(),
|
||||
text_as: TextAs::Outlines,
|
||||
text_as: o.text_as,
|
||||
layers: false,
|
||||
..Default::default()
|
||||
};
|
||||
@@ -162,6 +162,10 @@ const INFO: &str = "document.pdfInfo";
|
||||
pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bytes = source(p, INFO)?.bytes;
|
||||
let o = LoadOptions::from_params(INFO, p)?;
|
||||
// Programs whose header is only `%!` are PostScript too, as `clipboard.importEps` reads them.
|
||||
if bytes.starts_with(b"%!") || vectorcraft_pdf::is_postscript(&bytes) {
|
||||
return postscript_info(&bytes, p);
|
||||
}
|
||||
let info = match vectorcraft_pdf::info(&bytes, o.password.as_deref()) {
|
||||
Ok(i) => i,
|
||||
Err(e @ (PdfError::NeedsPassword | PdfError::WrongPassword)) => {
|
||||
@@ -179,14 +183,42 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({"pages": pages.len(), "needsPassword": false, "pageInfo": pages});
|
||||
if let Some(n) = p.get("thumbnail").and_then(Value::as_u64) {
|
||||
let page = usize::try_from(n).ok().and_then(|n| n.checked_sub(1)).filter(|i| *i < info.pages.len());
|
||||
let page = page.ok_or_else(|| bad(INFO, format!("thumbnail: no page {n} (the PDF has {})", info.pages.len())))?;
|
||||
if let Some(page) = thumbnail_page(p, info.pages.len(), "PDF")? {
|
||||
let (doc, _) = page_document(&bytes, page, &o)?;
|
||||
let size = f64_or(p, "thumbnailSize", 160.0).clamp(16.0, 1024.0);
|
||||
let r = doc.artboards.first().map(|a| a.rect).ok_or_else(|| err("the page has no area"))?;
|
||||
let png = super::encode(&doc, "png", &json!({"scale": size / r.width().max(r.height()).max(1.0)}))?;
|
||||
out["thumbnail"] = json!(vectorcraft_format::base64_encode(&png));
|
||||
out["thumbnail"] = json!(thumbnail(&doc, p)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The page (0-based) `document.pdfInfo`'s `thumbnail` names, from 1 to `count`; `None` when it is
|
||||
/// absent or null. Any other value (0, a negative or fractional number, a string) is an error that
|
||||
/// names the pages the `what` has.
|
||||
fn thumbnail_page(p: &Value, count: usize, what: &str) -> Result<Option<usize>> {
|
||||
let Some(v) = p.get("thumbnail").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let page = v.as_u64().and_then(|n| usize::try_from(n).ok()).and_then(|n| n.checked_sub(1)).filter(|i| *i < count);
|
||||
page.map(Some).ok_or_else(|| bad(INFO, format!("thumbnail: no page {v} (the {what} has {count})")))
|
||||
}
|
||||
|
||||
/// `document.pdfInfo` of a PostScript file (an EPS, a `.ps` file, a `.ai` in PostScript form): one
|
||||
/// page, the page [`vectorcraft_eps::page`] reads, with no PDF boxes. Its thumbnail is the file as
|
||||
/// the EPS reader reads it without any editing data it carries: what the page prints, or the
|
||||
/// file's preview when its PostScript can't be read.
|
||||
fn postscript_info(bytes: &[u8], p: &Value) -> Result<Value> {
|
||||
let page = vectorcraft_eps::page(bytes).map_err(err)?;
|
||||
let info = json!({"width": page.width(), "height": page.height(), "rotation": 0, "boxes": {}});
|
||||
let mut out = json!({"pages": 1, "needsPassword": false, "pageInfo": [info]});
|
||||
if thumbnail_page(p, 1, "file")?.is_some() {
|
||||
let doc = vectorcraft_eps::import_with(bytes, false).map_err(err)?.document;
|
||||
out["thumbnail"] = json!(thumbnail(&doc, p)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A PNG of `doc`'s first artboard, `thumbnailSize` px (default 160, from 16 to 1024) on its longer
|
||||
/// side, base64.
|
||||
fn thumbnail(doc: &Document, p: &Value) -> Result<String> {
|
||||
let size = f64_or(p, "thumbnailSize", 160.0).clamp(16.0, 1024.0);
|
||||
let r = doc.artboards.first().map(|a| a.rect).ok_or_else(|| err("the page has no area"))?;
|
||||
let png = super::encode(doc, "png", &json!({"scale": size / r.width().max(r.height()).max(1.0)}))?;
|
||||
Ok(vectorcraft_format::base64_encode(&png))
|
||||
}
|
||||
@@ -220,6 +220,21 @@ mod tests {
|
||||
assert!(close(resolution(&jpg).unwrap(), (254.0, 240.0 * 2.54)));
|
||||
}
|
||||
|
||||
/// A CMYK JPEG carries no JFIF (it describes one- and three-component images), so its
|
||||
/// resolution is written as EXIF instead and this reader still finds it (#3084).
|
||||
#[test]
|
||||
fn a_cmyk_jpeg_keeps_its_resolution_without_jfif() {
|
||||
use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions};
|
||||
let o = JpegOptions { color_model: ColorModel::Cmyk, ..Default::default() };
|
||||
let jpg = jpeg::encode(&[0; 4 * 4], 2, 2, 90, Some(240.0), &o).unwrap();
|
||||
assert!(!jpg.windows(5).any(|w| w == b"JFIF\0"), "no JFIF on a CMYK file");
|
||||
assert_eq!(resolution(&jpg), Some((240.0, 240.0)));
|
||||
// An RGB file still says it in JFIF, as it always did.
|
||||
let rgb = jpeg::encode(&[0; 3 * 4], 2, 2, 90, Some(240.0), &JpegOptions::default()).unwrap();
|
||||
assert!(rgb.windows(5).any(|w| w == b"JFIF\0"));
|
||||
assert_eq!(resolution(&rgb), Some((240.0, 240.0)));
|
||||
}
|
||||
|
||||
/// A little-endian TIFF/EXIF block declaring `x`/`y` resolution in `unit`.
|
||||
fn exif_block(x: u32, y: u32, unit: u16) -> Vec<u8> {
|
||||
let mut b = b"II*\0".to_vec();
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Progress and Cancel of an export running off the UI thread (Background Export), on the shared
|
||||
//! [`vectorcraft_doc::cancel`] mechanism.
|
||||
//!
|
||||
//! The frontend makes a [`Progress`], runs the export inside [`scope`] on its worker and reads the
|
||||
//! counts from the UI thread to draw them; its Cancel button calls [`Progress::cancel`]. Inside the
|
||||
//! scope the encoders that work in steps (raster formats: one artboard at a time) report each step
|
||||
//! through [`vectorcraft_doc::cancel::progress`] and stop at the next check once cancelled; the
|
||||
//! renderer stops drawing and keeps no half-drawn pattern tile or effect raster. Encoders that
|
||||
//! make one file in one go report nothing: the frontend shows them as busy and checks
|
||||
//! [`Progress::cancelled`] itself before writing, so a cancelled export never writes a file.
|
||||
//! Export for Screens ([`super::ScreenExport::write`]) reports one step per file instead, keeps
|
||||
//! its encoders' reports out, and stops before the next file, so the files it wrote before the
|
||||
//! cancel stay.
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use vectorcraft_doc::cancel::{self, CancelToken, ProgressSink};
|
||||
|
||||
/// How far an export has got, shared between the worker and the UI thread.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Progress {
|
||||
token: CancelToken,
|
||||
done: AtomicU64,
|
||||
total: AtomicU64,
|
||||
/// The steps are files (Export for Screens), not artboards.
|
||||
files: bool,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
pub fn new() -> Arc<Self> {
|
||||
Arc::new(Self::default())
|
||||
}
|
||||
|
||||
/// A [`Progress`] whose steps are files: the export of [`super::ScreenExport::write`].
|
||||
pub fn of_files() -> Arc<Self> {
|
||||
Arc::new(Self { files: true, ..Self::default() })
|
||||
}
|
||||
|
||||
/// Are the steps files rather than artboards?
|
||||
pub fn counts_files(&self) -> bool {
|
||||
self.files
|
||||
}
|
||||
|
||||
/// `(steps done, steps in all)`; `total` is 0 while the export can't say (one file made in one go).
|
||||
pub fn counts(&self) -> (u64, u64) {
|
||||
let total = self.total.load(Ordering::Relaxed);
|
||||
(self.done.load(Ordering::Relaxed).min(total), total)
|
||||
}
|
||||
|
||||
/// The share of the export done, 0 to 1; `None` while the export can't say.
|
||||
pub fn fraction(&self) -> Option<f64> {
|
||||
let (done, total) = self.counts();
|
||||
(total > 0).then(|| done as f64 / total as f64)
|
||||
}
|
||||
|
||||
/// Ask the export to stop: it writes nothing more, and a render under way stops drawing.
|
||||
pub fn cancel(&self) {
|
||||
self.token.cancel();
|
||||
}
|
||||
|
||||
pub fn cancelled(&self) -> bool {
|
||||
self.token.is_cancelled()
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` with `progress`'s token in effect on this thread and the steps reported to it.
|
||||
pub fn scope<R>(progress: &Arc<Progress>, f: impl FnOnce() -> R) -> R {
|
||||
let to = Arc::clone(progress);
|
||||
let sink: ProgressSink = Rc::new(move |done, total, _| {
|
||||
to.total.store(total, Ordering::Relaxed);
|
||||
to.done.store(done, Ordering::Relaxed);
|
||||
});
|
||||
cancel::scope(&progress.token, Some(sink), f)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_raster_export_counts_its_artboards_and_stops_once_cancelled() {
|
||||
let mut doc = vectorcraft_doc::Document::new(100.0, 100.0);
|
||||
let second = doc.artboards[0].clone();
|
||||
doc.artboards.push(second);
|
||||
let p = Progress::new();
|
||||
assert_eq!(p.fraction(), None, "nothing reported yet");
|
||||
let png = scope(&p, || super::super::encode_all(&doc, "png", &serde_json::json!({"useArtboards": true})));
|
||||
assert!(png.is_ok(), "{:?}", png.err());
|
||||
assert_eq!(p.counts(), (1, 2), "the step under way when the last artboard started");
|
||||
p.cancel();
|
||||
let r = scope(&p, || super::super::encode_all(&doc, "png", &serde_json::json!({"useArtboards": true})));
|
||||
assert!(matches!(r, Err(crate::EngineError::Cancelled)), "{:?}", r.err());
|
||||
assert!(!cancel::is_cancelled(), "the scope ended");
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,8 @@ use vectorcraft_doc::Document;
|
||||
|
||||
use super::super::*;
|
||||
use super::{
|
||||
ArtboardPick, Encoded, Format, Loaded, encode_all, file_stem, format, format_for_name, load, read_file, with_compression_pref, write_encoded,
|
||||
ARTBOARD_PARAMS, ArtboardPick, Encoded, Format, Loaded, encode_all, file_stem, format, format_for_name, load, read_file, with_compression_pref,
|
||||
write_encoded,
|
||||
};
|
||||
use crate::{DocState, Prefs};
|
||||
|
||||
@@ -94,6 +95,9 @@ pub struct SavePlan {
|
||||
/// The `modified` param (as `date_param` reads it): the File Info date a Save or Save As to a file
|
||||
/// stamps; `None`: the time it is written.
|
||||
pub modified: Option<Option<i64>>,
|
||||
/// Warnings about the params themselves: each native option (`compress`, `version`,
|
||||
/// `preview`) given beside the path that the format doesn't read.
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
impl SavePlan {
|
||||
@@ -181,6 +185,14 @@ fn parent_folder(path: &str) -> Option<String> {
|
||||
std::path::Path::new(path).parent().map(|p| p.to_string_lossy().to_string()).filter(|p| !p.is_empty())
|
||||
}
|
||||
|
||||
/// A file dialog's starting folder for a path on disk (#4122): the path's parent when it is a
|
||||
/// folder, else the nearest ancestor directory that exists.
|
||||
pub fn dialog_folder(path: &str) -> Option<String> {
|
||||
let folder = parent_folder(path)?;
|
||||
let path = std::path::PathBuf::from(folder);
|
||||
path.ancestors().find(|a| a.is_dir()).map(|a| a.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// A save format by id or extension, or why it isn't one.
|
||||
fn save_format_of(f: &str) -> std::result::Result<&'static Format, String> {
|
||||
match format(f) {
|
||||
@@ -233,6 +245,14 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
(_, None, None) => checked(cmd, st.format)?,
|
||||
};
|
||||
let path = if mode == SaveMode::Template { path.map(|p| template_path(&p, format)) } else { path };
|
||||
if let Some((key, top, inner)) = disagreeing_option(p, is_svg(format)).map_err(|e| bad(cmd, e))? {
|
||||
return Err(bad(cmd, format!("`{key}: {top}` and `options.{key}: {inner}` disagree: give the option once")));
|
||||
}
|
||||
let notes = NATIVE_OPTIONS
|
||||
.iter()
|
||||
.filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k))
|
||||
.map(|k| format!("`{k}` was not used: {} files don't read it", format.label))
|
||||
.collect();
|
||||
let mut given: Map<String, Value> = match p.get("options") {
|
||||
Some(Value::Object(o)) => o.iter().filter(|(k, _)| reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())).collect(),
|
||||
None | Some(Value::Null) => Map::new(),
|
||||
@@ -253,7 +273,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
}
|
||||
}
|
||||
// None given: the ones the document was last saved with in this format.
|
||||
let options = if given.is_empty() && format.id == st.format { st.save_options.clone() } else { given };
|
||||
let options = if given.is_empty() && format.id == st.format { remembered_save_options(st) } else { given };
|
||||
// Save writes the document's own file; the other modes only where they are told to.
|
||||
let path =
|
||||
path.or_else(|| (mode == SaveMode::Save && !st.converted && !st.recovered && format.id == st.format).then(|| st.path.clone()).flatten());
|
||||
@@ -272,12 +292,141 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
if let Some(path) = &path {
|
||||
super::check_not_lossy_overwrite(st, path, p, cmd)?;
|
||||
}
|
||||
Ok(SavePlan { mode, path, format, options, name, folder, modified })
|
||||
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes })
|
||||
}
|
||||
|
||||
/// The native save options, which a save also takes beside the path.
|
||||
const NATIVE_OPTIONS: [&str; 3] = ["compress", "version", "preview"];
|
||||
|
||||
/// The first option `p` gives both beside the path and in `options` with different values, as
|
||||
/// `(key, top-level value, options value)`. For an SVG save (`svg`), an SVG option's value on
|
||||
/// either side is the one its `svg: {…}` object gives, else the flat one.
|
||||
fn disagreeing_option(p: &Value, svg: bool) -> std::result::Result<Option<(String, Value, Value)>, String> {
|
||||
let Some(inner) = p.get("options").filter(|o| o.is_object()) else { return Ok(None) };
|
||||
let given = |m: &Value| -> std::result::Result<Map<String, Value>, String> {
|
||||
let mut out: Map<String, Value> = m
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(k, v)| !(v.is_null() || matches!(k.as_str(), "path" | "format" | "options") || svg && k.as_str() == "svg"))
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
if svg {
|
||||
out.extend(super::svg_options(m)?);
|
||||
}
|
||||
Ok(out)
|
||||
};
|
||||
let top = given(p)?;
|
||||
Ok(given(inner)?.into_iter().find_map(|(k, v)| {
|
||||
let t = top.get(&k).filter(|t| !same_value(t, &v))?.clone();
|
||||
Some((k, t, v))
|
||||
}))
|
||||
}
|
||||
|
||||
/// `a == b`, with a whole number and a float of the same value (`3` and `3.0`) the same.
|
||||
fn same_value(a: &Value, b: &Value) -> bool {
|
||||
match (a, b) {
|
||||
(Value::Number(x), Value::Number(y)) => x == y || ((x.is_f64() || y.is_f64()) && x.as_f64() == y.as_f64()),
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// The options `st` was last saved with, their artboards (`artboard`, `artboards` and `range`)
|
||||
/// following the artboards they named ([`DocState::save_artboards`]): an artboard deleted since is
|
||||
/// left out, and one that moved is named by its new number. When none of the artboards the save
|
||||
/// used is left, the pick is left out, and a save without options writes the artboards it writes
|
||||
/// when none is named. `range` `"all"` stays as it is. Artboards given to a save are still checked.
|
||||
pub fn remembered_save_options(st: &DocState) -> Map<String, Value> {
|
||||
let mut options = st.save_options.clone();
|
||||
let ids: Vec<u32> = st.doc.artboards.iter().map(|a| a.id).collect();
|
||||
// The encoders refuse a document without artboards themselves.
|
||||
if ids.is_empty() {
|
||||
return options;
|
||||
}
|
||||
// Artboard `i` of the save, where it is now (by number when the save's artboards are unknown).
|
||||
let then = &st.save_artboards;
|
||||
let count = if then.is_empty() { ids.len() } else { then.len() };
|
||||
let now = |i: usize| match then.get(i) {
|
||||
Some(id) => ids.iter().position(|x| x == id),
|
||||
None => (then.is_empty() && i < ids.len()).then_some(i),
|
||||
};
|
||||
// Each pick that names artboards: `Some` of where they are now (empty: all gone).
|
||||
let mut moved: Vec<(&str, Option<Vec<usize>>)> = vec![];
|
||||
for k in ARTBOARD_PARAMS {
|
||||
let named = match (k, options.get(k)) {
|
||||
("range", Some(Value::String(r))) if r.trim().is_empty() || r.trim().eq_ignore_ascii_case("all") => continue,
|
||||
("range", Some(Value::String(r))) => match vectorcraft_doc::range::parse_range(r, count) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
moved.push((k, Some(vec![])));
|
||||
continue;
|
||||
}
|
||||
},
|
||||
("artboards", Some(v @ Value::Array(_))) => match serde_json::from_value::<Vec<usize>>(v.clone()) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
},
|
||||
("artboard", Some(v)) => match v.as_u64().and_then(|i| usize::try_from(i).ok()) {
|
||||
Some(i) => vec![i],
|
||||
None => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
let there: Vec<usize> = named.iter().filter_map(|i| now(*i)).collect();
|
||||
// A range that reads differently against the artboards there are now (`"2-"` once one
|
||||
// was added) is written out as the artboards it named.
|
||||
let reads = match (k, options.get(k)) {
|
||||
("range", Some(Value::String(r))) => vectorcraft_doc::range::parse_range(r, ids.len()).ok(),
|
||||
_ => Some(named),
|
||||
};
|
||||
moved.push((k, (reads.as_ref() != Some(&there)).then_some(there)));
|
||||
}
|
||||
// The pick a save uses (as `ArtboardPick::resolve` reads it: `range`, then `artboards`, then
|
||||
// `artboard`) is gone: so is the rest.
|
||||
let used = ["range", "artboards", "artboard"].into_iter().find(|k| match options.get(*k) {
|
||||
Some(Value::String(r)) => !r.trim().is_empty(),
|
||||
Some(v) => !v.is_null(),
|
||||
None => false,
|
||||
});
|
||||
let gone = |k: &str| moved.iter().any(|(m, there)| *m == k && there.as_ref().is_some_and(Vec::is_empty));
|
||||
if used.is_some_and(gone) {
|
||||
for k in ARTBOARD_PARAMS {
|
||||
options.remove(k);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
for (k, there) in moved {
|
||||
let Some(there) = there else { continue };
|
||||
let value = match (k, there.first()) {
|
||||
(_, None) => None,
|
||||
("range", Some(_)) => Some(json!(range_text(&there))),
|
||||
("artboards", Some(_)) => Some(json!(there)),
|
||||
(_, Some(i)) => Some(json!(i)),
|
||||
};
|
||||
match value {
|
||||
Some(v) => _ = options.insert(k.into(), v),
|
||||
None => _ = options.remove(k),
|
||||
}
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
/// 0-based artboard indices as a 1-based range in the same order, runs joined (`"1-2, 5"`).
|
||||
fn range_text(picked: &[usize]) -> String {
|
||||
let mut runs: Vec<(usize, usize)> = vec![];
|
||||
for &i in picked {
|
||||
match runs.last_mut() {
|
||||
Some((_, end)) if *end + 1 == i => *end = i,
|
||||
_ => runs.push((i, i)),
|
||||
}
|
||||
}
|
||||
let run = |&(a, b): &(usize, usize)| if a == b { format!("{}", a + 1) } else { format!("{}-{}", a + 1, b + 1) };
|
||||
runs.iter().map(run).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// Does a save in `f` read option `key`? PDF (and a .ai file, a PDF) also reads its General
|
||||
/// settings (`createLayers`…) and presets.
|
||||
fn reads_option(f: &Format, key: &str) -> bool {
|
||||
/// settings (`createLayers`…) and presets. A save drops each option its format doesn't read.
|
||||
pub fn reads_option(f: &Format, key: &str) -> bool {
|
||||
f.options.iter().any(|o| o.name == key) || (is_pdf(f) && (super::pdf::OPTIONS.iter().any(|o| o.name == key) || super::pdf::is_setting(key)))
|
||||
}
|
||||
|
||||
@@ -371,7 +520,7 @@ impl<W: std::io::Write> std::io::Write for Counted<W> {
|
||||
/// `separateArtboards`, those `range` names (default all).
|
||||
fn separate_boards(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Vec<usize>> {
|
||||
// A legacy .ai file is a file per artboard already.
|
||||
if !is_native(f) || !bool_or(p, "separateArtboards", false) || super::legacy_ai::wanted(cmd, p)? {
|
||||
if !is_native(f) || !bool_or(p, "separateArtboards", false) || super::legacy_ai::wanted(cmd, f, p)? {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let range = str_param(p, "range").filter(|r| !r.trim().is_empty()).map(str::to_string);
|
||||
@@ -385,22 +534,27 @@ fn separate_boards(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<V
|
||||
pub(super) fn artboard_doc(doc: &Document, i: usize) -> Document {
|
||||
let mut d = doc.clone();
|
||||
let Some(a) = doc.artboards.get(i) else { return d };
|
||||
let r = a.rect;
|
||||
d.artboards = vec![a.clone()];
|
||||
// It opens fitted to its artboard, not at the master file's view.
|
||||
keep_art_on(&mut d, a.rect);
|
||||
d
|
||||
}
|
||||
|
||||
/// Reduce `d` to the objects touching `r`, in their layers (resources are kept), opening
|
||||
/// fitted to its artboard rather than at the master file's view.
|
||||
pub(super) fn keep_art_on(d: &mut Document, r: vectorcraft_geom::Rect) {
|
||||
d.last_view = None;
|
||||
d.layers_open = None;
|
||||
for layer in &mut d.layers {
|
||||
keep_on(layer, r);
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Keep in layer `n` (and its sublayers) only the objects touching `r`.
|
||||
/// Keep in layer `n` (and its sublayers) only the objects touching `r`, and those without bounds.
|
||||
fn keep_on(n: &mut Arc<vectorcraft_doc::Node>, r: vectorcraft_geom::Rect) {
|
||||
let touches = |b: vectorcraft_geom::Rect| b.x0 <= r.x1 && b.x1 >= r.x0 && b.y0 <= r.y1 && b.y1 >= r.y0;
|
||||
if let Some(children) = Arc::make_mut(n).children_mut() {
|
||||
children.retain(|c| c.is_layer() || c.visual_bounds().is_some_and(touches));
|
||||
// An object whose bounds can't be measured (type in a missing font) stays: dropping it loses art.
|
||||
children.retain(|c| c.is_layer() || c.visual_bounds().is_none_or(touches));
|
||||
for c in children.iter_mut().filter(|c| c.is_layer()) {
|
||||
keep_on(c, r);
|
||||
}
|
||||
@@ -421,10 +575,19 @@ fn blank_pages(doc: &Document) -> Document {
|
||||
/// Why a `.ai` file saved without PDF content looks empty elsewhere.
|
||||
const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens it as before, other apps show empty pages";
|
||||
|
||||
/// `e`, an error of the export encoders, under the save command `cmd` instead of
|
||||
/// `document.export`.
|
||||
fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError {
|
||||
match e {
|
||||
crate::EngineError::BadParams { cmd: c, msg } if c == "document.export" => bad(cmd, msg),
|
||||
e => e,
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared Save and Export encoder for PDF-compatible `.ai` files (and `.ait` templates, the
|
||||
/// same file).
|
||||
pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Encoded> {
|
||||
if super::legacy_ai::wanted(cmd, p)? {
|
||||
if super::legacy_ai::wanted(cmd, f, p)? {
|
||||
return super::legacy_ai::encode(cmd, f, doc, p);
|
||||
}
|
||||
let mut params = if p.is_object() { p.clone() } else { json!({}) };
|
||||
@@ -504,11 +667,11 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
if matches!(plan.format.id, "vectorcraft" | "template") {
|
||||
// Not remembered with the options: the preference decides each time it isn't given.
|
||||
params = with_compression_pref(&s.prefs, ¶ms);
|
||||
super::native::save_options(cmd, plan.format, &doc, ¶ms)?;
|
||||
super::native::save_options(cmd, plan.format, &doc, ¶ms).map_err(|e| named_for_save(cmd, e))?;
|
||||
}
|
||||
let boards = separate_boards(cmd, plan.format, &doc, ¶ms)?;
|
||||
let mut params = super::pdf::expand_preset(s, cmd, ¶ms)?.into_owned();
|
||||
let legacy = super::legacy_ai::wanted(cmd, ¶ms)?;
|
||||
let legacy = super::legacy_ai::wanted(cmd, plan.format, ¶ms)?;
|
||||
if let (Some(o), "ai" | "ait") = (params.as_object_mut(), plan.format.id) {
|
||||
// Save keeps every artboard; exports may choose a subset instead. A legacy .ai file per
|
||||
// artboard keeps a range given: the artboards to save.
|
||||
@@ -542,23 +705,40 @@ impl SaveJob {
|
||||
|
||||
/// Encode the file → it (and, with `separateArtboards`, a file per artboard after it), with
|
||||
/// the warnings (what the format loses first, then the encoder's own notes: PDF options not
|
||||
/// applied yet…).
|
||||
/// applied yet…, then the plan's notes on its params).
|
||||
pub fn encode(&self) -> Result<Encoded> {
|
||||
let mut enc = self.encode_one(&self.doc)?;
|
||||
for &b in &self.boards {
|
||||
let one = self.encode_one(&artboard_doc(&self.doc, b))?;
|
||||
enc.files.extend(one.files.into_iter().map(|(_, bytes)| (Some(b), bytes)));
|
||||
}
|
||||
enc.warnings.splice(0..0, fidelity_warning(self.plan.format));
|
||||
enc.warnings.splice(0..0, self.format_losses());
|
||||
enc.warnings.extend(self.plan.notes.iter().cloned());
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// What the file loses against the document: the artboards an SVG file leaves out first (the
|
||||
/// status bar shows only the first warning), then what the format loses.
|
||||
fn format_losses(&self) -> impl Iterator<Item = String> {
|
||||
let f = self.plan.format;
|
||||
let lost = if is_svg(f) { super::svg::lost_artboards_warning(&self.doc, &self.params, f.label) } else { None };
|
||||
lost.into_iter().chain(fidelity_warning(f))
|
||||
}
|
||||
|
||||
/// The warnings known before the file is encoded, in the order a written file's reply gives
|
||||
/// them: what the format loses, then the plan's notes on its params (a reply sent before the
|
||||
/// file is written, as Background Save's, gives these).
|
||||
pub fn known_warnings(&self) -> Vec<String> {
|
||||
self.format_losses().chain(self.plan.notes.iter().cloned()).collect()
|
||||
}
|
||||
|
||||
/// Encode one file of `doc` in the job's format.
|
||||
fn encode_one(&self, doc: &Document) -> Result<Encoded> {
|
||||
let (cmd, f) = (self.plan.mode.command(), self.plan.format);
|
||||
let enc = if matches!(f.id, "ai" | "ait") { encode_ai(cmd, f, doc, &self.params)? } else { encode_all(doc, f.id, &self.params)? };
|
||||
let enc = if matches!(f.id, "ai" | "ait") { encode_ai(cmd, f, doc, &self.params) } else { encode_all(doc, f.id, &self.params) }
|
||||
.map_err(|e| named_for_save(cmd, e))?;
|
||||
// A legacy .ai file per artboard.
|
||||
let per_artboard = f.id == "ai" && super::legacy_ai::wanted(cmd, &self.params)?;
|
||||
let per_artboard = f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?;
|
||||
if enc.files.len() != 1 && !per_artboard {
|
||||
return Err(bad(cmd, "Save writes one artboard: name one, or export several with document.export"));
|
||||
}
|
||||
@@ -642,8 +822,7 @@ impl SaveJob {
|
||||
};
|
||||
let r = stream(path, &mut fill);
|
||||
r.map_err(|e| failed.take().unwrap_or(e))?;
|
||||
let warnings: Vec<String> = fidelity_warning(f).into_iter().collect();
|
||||
Ok(json!({ "path": path, "bytes": written, "format": f.id, "warnings": warnings }))
|
||||
Ok(json!({ "path": path, "bytes": written, "format": f.id, "warnings": self.known_warnings() }))
|
||||
}
|
||||
|
||||
/// Once written: Save and Save As (except to a template) make the file `st`'s own: path,
|
||||
@@ -656,6 +835,7 @@ impl SaveJob {
|
||||
st.path = Some(path);
|
||||
st.format = self.plan.format.id;
|
||||
st.save_options = self.plan.options;
|
||||
st.save_artboards = self.snapshot.artboards.iter().map(|a| a.id).collect();
|
||||
st.converted = false;
|
||||
st.recovered = false;
|
||||
if let Some(at) = self.stamped {
|
||||
@@ -748,14 +928,14 @@ fn format_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = format(id)
|
||||
.filter(|f| f.write || SAVE_FORMATS.contains(&f.id) || TEMPLATE_FORMATS.contains(&f.id))
|
||||
.ok_or_else(|| bad(C, format!("`{id}` is no writable format (see document.formats)")))?;
|
||||
let saved = st.filter(|d| d.format == f.id).map(|d| &d.save_options);
|
||||
let saved = st.filter(|d| d.format == f.id).map(remembered_save_options);
|
||||
// A native save compresses as Use Compression says, unless told otherwise.
|
||||
let prefs = with_compression_pref(&s.prefs, &json!({}));
|
||||
let mut v = f.to_json();
|
||||
if let Some(options) = v["options"].as_object_mut() {
|
||||
for (name, o) in options.iter_mut() {
|
||||
let default = prefs.get(name).filter(|_| matches!(f.id, "vectorcraft" | "template")).unwrap_or(&o["default"]);
|
||||
o["value"] = saved.and_then(|m| m.get(name)).unwrap_or(default).clone();
|
||||
o["value"] = saved.as_ref().and_then(|m| m.get(name)).unwrap_or(default).clone();
|
||||
}
|
||||
}
|
||||
v["saveFormats"] =
|
||||
@@ -770,7 +950,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai (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, compress?: bool (native, also in options: gzip; default: the useCompression preference), 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), 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?: false for native (also carry a PDF of every artboard) | 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: 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; separateArtboards writes more files, one per artboard. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF 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",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai (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 say when the format doesn't read compress, version or preview given flat), 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), 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?: false for native (also carry a PDF of every artboard) | 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: 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; separateArtboards writes more files, one per artboard. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF 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",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
@@ -797,7 +977,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save as Template…",
|
||||
["File"],
|
||||
None,
|
||||
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}",
|
||||
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Template, p)
|
||||
),
|
||||
@@ -848,6 +1028,20 @@ mod tests_folders {
|
||||
assert_eq!(super::xdg_documents("XDG_MUSIC_DIR=\"$HOME/Musica\"", home), None);
|
||||
}
|
||||
|
||||
/// #4122: File → Open starts in the folder of the last opened file.
|
||||
#[test]
|
||||
fn dialog_folder_is_the_nearest_existing_parent() {
|
||||
let base = std::env::temp_dir().join(format!("vc-open-folder-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let file = base.join("poster.svg");
|
||||
assert_eq!(super::dialog_folder(&file.to_string_lossy()).map(PathBuf::from), Some(base.clone()));
|
||||
let missing = base.join("gone").join("card.ai");
|
||||
assert_eq!(super::dialog_folder(&missing.to_string_lossy()).map(PathBuf::from), Some(base.clone()));
|
||||
assert!(super::dialog_folder("poster.svg").is_none());
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// #703: the Templates folder a dialog starts in exists: made when missing, else the nearest
|
||||
/// folder above it.
|
||||
#[test]
|
||||
|
||||
@@ -18,7 +18,7 @@ use vectorcraft_geom::Rect;
|
||||
|
||||
use super::super::*;
|
||||
use super::encode::single_artboard;
|
||||
use super::export::{isolated, selected_artwork, without_artboards};
|
||||
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
|
||||
use super::naming::{self, NameParts};
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names, encode_with_warnings, unique_file_names,
|
||||
@@ -26,6 +26,8 @@ use super::{
|
||||
};
|
||||
|
||||
const C: &str = "document.exportForScreens";
|
||||
/// The Asset Export panel's export, which exports through [`export`].
|
||||
const ASSETS: &str = "assets.export";
|
||||
|
||||
/// How big a raster row's files are.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -44,7 +46,14 @@ impl ScreenSize {
|
||||
/// `2x` (or `2`), `100w`, `100h` or `72ppi`, in any case; positive numbers only.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
let s = s.trim().to_ascii_lowercase();
|
||||
let num = |t: &str| t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0);
|
||||
// Digits and `.` only: `str::parse` would also take `+2`, `1e2`, `inf` and `nan`.
|
||||
let num = |t: &str| {
|
||||
let t = t.trim();
|
||||
if !t.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
|
||||
return None;
|
||||
}
|
||||
t.parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0)
|
||||
};
|
||||
if let Some(n) = s.strip_suffix("ppi") {
|
||||
return num(n).map(Self::Ppi);
|
||||
}
|
||||
@@ -162,11 +171,14 @@ pub(super) fn file_part(s: &str) -> String {
|
||||
/// trailing periods and spaces, and with `-` after a Windows device name that is the whole name or
|
||||
/// comes before its first period: `CON`, `PRN`, `AUX`, `NUL`, `COM1` to `COM9` and `LPT1` to `LPT9`,
|
||||
/// also with `¹`, `²` or `³` for the digit, in any case (`CON.png` becomes `CON-.png`). The same on
|
||||
/// every platform.
|
||||
/// every platform. Spaces between the device name and the period are dropped (`CON .png` becomes
|
||||
/// `CON-.png`).
|
||||
pub(crate) fn safe_file_name(s: &str) -> String {
|
||||
let name = file_part(s);
|
||||
let name = name.trim_end_matches(['.', ' ']);
|
||||
let (base, rest) = name.split_at(name.find('.').unwrap_or(name.len()));
|
||||
// Windows ignores spaces before the extension, so `CON .png` is the CON device too.
|
||||
let base = base.trim_end_matches(' ');
|
||||
let upper = base.to_ascii_uppercase();
|
||||
let numbered = |n: &str| n.chars().count() == 1 && n.chars().all(|c| matches!(c, '1'..='9' | '¹' | '²' | '³'));
|
||||
let device = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|
||||
@@ -342,6 +354,97 @@ impl ScreenParams {
|
||||
fn of(p: &Value) -> Result<Self> {
|
||||
if p.is_object() { Self::deserialize(p).map_err(|e| bad(C, e.to_string())) } else { Ok(Self::default()) }
|
||||
}
|
||||
|
||||
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given.
|
||||
fn one_source(&self) -> Result<()> {
|
||||
let sources = [self.full_document, self.assets.is_some(), self.layers.is_some(), self.selection.is_some()].iter().filter(|b| **b).count();
|
||||
if sources > 1 {
|
||||
return Err(bad(C, "give one of assets, layers, selection or fullDocument"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `selection`: `None` without it, `Some(false)` for `one` file, `Some(true)` for `each` object.
|
||||
fn selection_mode(&self) -> Result<Option<bool>> {
|
||||
match self.selection.as_deref() {
|
||||
None => Ok(None),
|
||||
Some("one") => Ok(Some(false)),
|
||||
Some("each") => Ok(Some(true)),
|
||||
Some(m) => Err(bad(C, format!("selection `{m}`: one or each"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a batch export names its files and sorts them into folders.
|
||||
struct Naming {
|
||||
/// The `name` pattern, when it holds more than spaces.
|
||||
pattern: Option<String>,
|
||||
/// The `prefix`, through [`file_part`].
|
||||
prefix: String,
|
||||
/// The document's name, safe as a file name (`<filename>`, the Full Document's item).
|
||||
filename: String,
|
||||
/// The date and time the pattern's tokens use.
|
||||
when: [i64; 6],
|
||||
counter_start: u64,
|
||||
/// The counter counts files rather than items.
|
||||
per_file: bool,
|
||||
folders: Folders,
|
||||
}
|
||||
|
||||
impl Naming {
|
||||
/// The naming of params `o` for a document named `title`: its file's path, or its title before it is saved.
|
||||
fn of(o: &ScreenParams, title: &str) -> Result<Self> {
|
||||
let folders = Folders::of(o)?;
|
||||
// A prefix names files, not folders.
|
||||
let prefix = file_part(o.prefix.as_deref().unwrap_or(""));
|
||||
let when = match o.date.as_deref() {
|
||||
Some(d) => naming::parse_date(d).ok_or_else(|| bad(C, format!("date `{d}`: YYYY-MM-DD")))?,
|
||||
None => vectorcraft_doc::metadata::output_time().map_or([1970, 1, 1, 0, 0, 0], vectorcraft_doc::metadata::civil),
|
||||
};
|
||||
let per_file = match o.counter_per.as_deref() {
|
||||
None | Some("item") => false,
|
||||
Some("file") => true,
|
||||
Some(c) => return Err(bad(C, format!("counterPer `{c}`: item or file"))),
|
||||
};
|
||||
let filename = safe_name(&super::file_stem(title)).unwrap_or_else(|| "Untitled".into());
|
||||
let pattern = o.name.clone().filter(|n| !n.trim().is_empty());
|
||||
Ok(Self { pattern, prefix, filename, when, counter_start: o.counter_start.unwrap_or(1), per_file, folders })
|
||||
}
|
||||
|
||||
/// The sub-folder (`None` for the export folder itself) and the file name of the file row `r`
|
||||
/// writes of `item`, the `index`th item (from 0), when `files` files came before it.
|
||||
fn file(&self, item: &Item, index: usize, files: u64, r: &Row) -> (Option<String>, String) {
|
||||
let counter = self.counter_start.saturating_add(if self.per_file { files } else { index as u64 });
|
||||
let ext = r.format.extensions.first().copied().unwrap_or(r.format.id);
|
||||
let prefix = &self.prefix;
|
||||
let stem = match self.pattern.as_deref() {
|
||||
Some(pattern) => {
|
||||
let parts = NameParts {
|
||||
filename: &self.filename,
|
||||
name: &item.name,
|
||||
index: index + 1,
|
||||
counter,
|
||||
format: ext,
|
||||
scale: &if r.format.raster { r.size.label() } else { String::new() },
|
||||
suffix: &r.suffix,
|
||||
when: self.when,
|
||||
};
|
||||
let named = naming::render(pattern, &parts);
|
||||
let named = if named.is_empty() { item.stem.clone() } else { named };
|
||||
if naming::has_suffix_token(pattern) { format!("{prefix}{named}") } else { format!("{prefix}{named}{}", r.suffix) }
|
||||
}
|
||||
None => format!("{prefix}{}{}", item.stem, r.suffix),
|
||||
};
|
||||
let file = safe_file_name(&format!("{stem}.{ext}"));
|
||||
let sub = match self.folders {
|
||||
Folders::None => None,
|
||||
Folders::Rows => Some(safe_file_name(&r.folder)),
|
||||
Folders::Format => Some(ext.to_string()),
|
||||
Folders::Item => Some(item.stem.clone()),
|
||||
Folders::ItemFormat => Some(format!("{}/{ext}", item.stem)),
|
||||
};
|
||||
(sub, file)
|
||||
}
|
||||
}
|
||||
|
||||
/// The format rows `p` asks for (`formats`, else `preset`'s, else one PNG at 1x), each with the
|
||||
@@ -416,8 +519,15 @@ impl Output {
|
||||
None
|
||||
}
|
||||
|
||||
/// Write `bytes` as `name` (relative) under `folder`, or keep them.
|
||||
fn put(&mut self, folder: Option<&str>, keep: bool, name: String, bytes: Vec<u8>) -> Result<()> {
|
||||
/// Write `bytes` as `name` (relative) under `folder` with `writer`, or keep them.
|
||||
fn put(
|
||||
&mut self,
|
||||
folder: Option<&str>,
|
||||
keep: bool,
|
||||
name: String,
|
||||
bytes: Vec<u8>,
|
||||
writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
match folder {
|
||||
Some(dir) if !keep => {
|
||||
if let Some((sub, _)) = name.rsplit_once('/')
|
||||
@@ -426,7 +536,9 @@ impl Output {
|
||||
create_dir(&format!("{dir}/{sub}"))?;
|
||||
}
|
||||
let path = format!("{dir}/{name}");
|
||||
write_file(&path, &bytes)?;
|
||||
// A cancel that came while the file was encoded writes nothing more.
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
writer(&path, &bytes)?;
|
||||
self.written.push(path);
|
||||
}
|
||||
_ => self.kept.push((name, bytes)),
|
||||
@@ -566,36 +678,13 @@ pub(super) fn presets_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let o = ScreenParams::of(p)?;
|
||||
let rows = rows_of(s, p, o.preset.as_deref())?;
|
||||
let sources = [o.full_document, o.assets.is_some(), o.layers.is_some(), o.selection.is_some()].iter().filter(|b| **b).count();
|
||||
if sources > 1 {
|
||||
return Err(bad(C, "give one of assets, layers, selection or fullDocument"));
|
||||
}
|
||||
let folders = Folders::of(&o)?;
|
||||
// A prefix names files, not folders.
|
||||
let prefix = file_part(o.prefix.as_deref().unwrap_or(""));
|
||||
let folder = o.folder.as_deref().filter(|f| !f.is_empty());
|
||||
let when = match o.date.as_deref() {
|
||||
Some(d) => naming::parse_date(d).ok_or_else(|| bad(C, format!("date `{d}`: YYYY-MM-DD")))?,
|
||||
None => vectorcraft_doc::metadata::now_unix().map_or([1970, 1, 1, 0, 0, 0], vectorcraft_doc::metadata::civil),
|
||||
};
|
||||
let per_file = match o.counter_per.as_deref() {
|
||||
None | Some("item") => false,
|
||||
Some("file") => true,
|
||||
Some(c) => return Err(bad(C, format!("counterPer `{c}`: item or file"))),
|
||||
};
|
||||
let counter_start = o.counter_start.unwrap_or(1);
|
||||
let selection = match o.selection.as_deref() {
|
||||
None => None,
|
||||
Some("one") => Some(false),
|
||||
Some("each") => Some(true),
|
||||
Some(m) => return Err(bad(C, format!("selection `{m}`: one or each"))),
|
||||
};
|
||||
o.one_source()?;
|
||||
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
|
||||
let st = s.doc()?;
|
||||
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
|
||||
let selection = o.selection_mode()?;
|
||||
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
|
||||
if let Some(dir) = folder {
|
||||
create_dir(dir)?;
|
||||
}
|
||||
let doc = s.doc()?.doc.clone();
|
||||
let filename = safe_name(&super::file_stem(&doc.title)).unwrap_or_else(|| "Untitled".into());
|
||||
// Include Bleed: each artboard grown by the document's bleed.
|
||||
let doc = if o.include_bleed && doc.setup.has_bleed() {
|
||||
let mut d = (*doc).clone();
|
||||
@@ -607,13 +696,78 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
doc
|
||||
};
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &filename, crop)?;
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
let rows = rows.into_iter().map(|r| Row { options: with_black_output(s, &r.options), ..r }).collect();
|
||||
let export = ScreenExport { cmd: C, o, rows, naming, items };
|
||||
match &mut s.screens_hand_off {
|
||||
Some(slot) => {
|
||||
*slot = Some(export);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
None => export.write(&mut |path, bytes| write_file(path, bytes)),
|
||||
}
|
||||
}
|
||||
|
||||
/// An export as `document.exportForScreens` and `assets.export` take it from the session: the
|
||||
/// params, the format rows, the naming, and each item with the document it writes
|
||||
/// ([`Session::prepare_screen_export`]). [`ScreenExport::write`] encodes and writes its files
|
||||
/// without the session, on any thread.
|
||||
pub struct ScreenExport {
|
||||
/// The command whose errors it gives: `document.exportForScreens` or `assets.export`.
|
||||
cmd: &'static str,
|
||||
o: ScreenParams,
|
||||
rows: Vec<Row>,
|
||||
naming: Naming,
|
||||
items: Vec<Item>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run `assets.export` when `id` names it, else `document.exportForScreens`, with `params` as
|
||||
/// a command (checked and journaled as any other; Export for Screens remembers its settings)
|
||||
/// that encodes and writes nothing → the export it prepared, which [`ScreenExport::write`]
|
||||
/// encodes and writes (on the desktop with Background Export on, Export for Screens and the
|
||||
/// Asset Export panel do this on the background thread).
|
||||
pub fn prepare_screen_export(&mut self, id: &str, params: &Value) -> Result<ScreenExport> {
|
||||
let cmd = if id == ASSETS { ASSETS } else { C };
|
||||
self.screens_hand_off = Some(None);
|
||||
let r = self.execute(cmd, params);
|
||||
let handed = self.screens_hand_off.take().flatten();
|
||||
match (r, handed) {
|
||||
(Err(e), _) => Err(e),
|
||||
(Ok(_), Some(export)) => Ok(ScreenExport { cmd, ..export }),
|
||||
// Every run that succeeds hands one over.
|
||||
(Ok(_), None) => Err(bad(cmd, "nothing to export")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenExport {
|
||||
/// Make the export folder, encode the files and write each with `writer` into the folder and
|
||||
/// its sub-folders, or keep them to zip (the zip written with `writer` into the folder) or to
|
||||
/// return → the reply of `document.exportForScreens`. It reports one progress step per file
|
||||
/// ([`vectorcraft_doc::cancel::progress`]), and a cancel stops it before it encodes or writes
|
||||
/// another file.
|
||||
pub fn write(self, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let cmd = self.cmd;
|
||||
// A refusal names `assets.export` when that command prepared the export, as its reply does.
|
||||
encode_and_write(self, writer).map_err(|e| if cmd == C { e } else { crate::cmd::assets::of_cmd(cmd, e) })
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ScreenExport::write`].
|
||||
fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let ScreenExport { o, rows, naming, items, .. } = export;
|
||||
let folder = o.folder.as_deref().filter(|f| !f.is_empty());
|
||||
if let Some(dir) = folder {
|
||||
create_dir(dir)?;
|
||||
}
|
||||
let mut out = Output::default();
|
||||
// The encoders' warnings for every file, each once.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
|
||||
let (bytes, notes) = encode_with_warnings(doc, format, &with_black_output(s, options))?;
|
||||
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
|
||||
let (bytes, notes) = vectorcraft_doc::cancel::quiet(|| encode_with_warnings(doc, format, options))?;
|
||||
for w in notes {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
@@ -624,36 +778,15 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A whole-document copy of an artboard, for the formats that write documents to edit.
|
||||
let mut board_docs: std::collections::HashMap<usize, Arc<Document>> = std::collections::HashMap::new();
|
||||
let mut files = 0u64;
|
||||
// One step per item and row, the files a name collision skips included.
|
||||
let steps = (items.len() * rows.len()) as u64;
|
||||
let mut step = 0u64;
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
for r in &rows {
|
||||
let counter = counter_start.saturating_add(if per_file { files } else { index as u64 });
|
||||
let ext = r.format.extensions.first().copied().unwrap_or(r.format.id);
|
||||
let stem = match o.name.as_deref().filter(|n| !n.trim().is_empty()) {
|
||||
Some(pattern) => {
|
||||
let parts = NameParts {
|
||||
filename: &filename,
|
||||
name: &item.name,
|
||||
index: index + 1,
|
||||
counter,
|
||||
format: ext,
|
||||
scale: &if r.format.raster { r.size.label() } else { String::new() },
|
||||
suffix: &r.suffix,
|
||||
when,
|
||||
};
|
||||
let named = naming::render(pattern, &parts);
|
||||
let named = if named.is_empty() { item.stem.clone() } else { named };
|
||||
if naming::has_suffix_token(pattern) { format!("{prefix}{named}") } else { format!("{prefix}{named}{}", r.suffix) }
|
||||
}
|
||||
None => format!("{prefix}{}{}", item.stem, r.suffix),
|
||||
};
|
||||
let file = safe_file_name(&format!("{stem}.{ext}"));
|
||||
let sub = match folders {
|
||||
Folders::None => None,
|
||||
Folders::Rows => Some(safe_file_name(&r.folder)),
|
||||
Folders::Format => Some(ext.to_string()),
|
||||
Folders::Item => Some(item.stem.clone()),
|
||||
Folders::ItemFormat => Some(format!("{}/{ext}", item.stem)),
|
||||
};
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
vectorcraft_doc::cancel::progress(step, steps, &format!("Exporting file {} of {steps}", step + 1));
|
||||
step += 1;
|
||||
let (sub, file) = naming.file(item, index, files, r);
|
||||
let name = sub.map_or_else(|| file.clone(), |d| format!("{d}/{file}"));
|
||||
let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key), o.name.is_some()) else { continue };
|
||||
let bytes = if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) {
|
||||
@@ -663,23 +796,37 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
write(all, "pdf", &options)?
|
||||
} else if r.whole_document() && item.artboard.is_some() {
|
||||
let b = item.artboard.unwrap_or(0);
|
||||
let d = board_docs.entry(b).or_insert_with(|| Arc::new(single_artboard(&item.doc, item.region, &item.name))).clone();
|
||||
write(&d, r.format.id, &r.options_for(item.region, None)?)?
|
||||
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
|
||||
let d = board_docs
|
||||
.entry(b)
|
||||
.or_insert_with(|| {
|
||||
let mut d = single_artboard(&item.doc, item.region, &item.name);
|
||||
super::save::keep_art_on(&mut d, item.region);
|
||||
Arc::new(d)
|
||||
})
|
||||
.clone();
|
||||
let mut options = r.options_for(item.region, None)?;
|
||||
// An EPS page is the artboard, not its art's bounds: an artboard without art still writes.
|
||||
if r.format.id == "eps" {
|
||||
options["useArtboards"] = json!(true);
|
||||
}
|
||||
write(&d, r.format.id, &options)?
|
||||
} else {
|
||||
write(&item.doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
|
||||
};
|
||||
out.put(folder, o.zip, name, bytes)?;
|
||||
out.put(folder, o.zip, name, bytes, writer)?;
|
||||
files += 1;
|
||||
}
|
||||
}
|
||||
let names: Vec<&str> = out.kept.iter().map(|(n, _)| n.as_str()).collect();
|
||||
if o.zip {
|
||||
let zip = super::zip::store(&out.kept).map_err(|e| bad(C, e))?;
|
||||
let zip_name = safe_file_name(&format!("{prefix}{filename}.zip"));
|
||||
let zip_name = safe_file_name(&format!("{}{}.zip", naming.prefix, naming.filename));
|
||||
return match folder {
|
||||
Some(dir) => {
|
||||
let path = format!("{dir}/{zip_name}");
|
||||
write_file(&path, &zip)?;
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
writer(&path, &zip)?;
|
||||
Ok(json!({ "path": path, "bytes": zip.len(), "files": names, "warnings": warnings }))
|
||||
}
|
||||
None => Ok(
|
||||
@@ -697,12 +844,53 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The path, relative to the export folder, of the first file `document.exportForScreens` with
|
||||
/// params `p` writes (sub-folders included: `2x/Logo@2x.png`): the first format row's file of the
|
||||
/// first artboard, asset, layer or selected object, or of the whole document, named as [`export`]
|
||||
/// names it. It encodes and writes nothing and cuts no art out of the document: of the objects
|
||||
/// selected for a file each, it measures only the first ones, up to the first that draws something.
|
||||
/// It does not refuse what the export refuses for drawing nothing: a checked asset or layer, the
|
||||
/// selection as one file, or the Full Document with no visible art.
|
||||
/// The Export for Screens dialog shows it on its Example line.
|
||||
pub fn first_file(s: &Session, p: &Value) -> Result<String> {
|
||||
let p = with_preset(s, p)?;
|
||||
let o = ScreenParams::of(&p)?;
|
||||
let rows = rows_of(s, &p, o.preset.as_deref())?;
|
||||
o.one_source()?;
|
||||
let selection = o.selection_mode()?;
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let mut selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
|
||||
// A file per object: objects that draw nothing write no file.
|
||||
if selection == Some(true) {
|
||||
selected = selected.into_iter().find(|id| export_crop(doc, &[*id]).is_some()).into_iter().collect();
|
||||
}
|
||||
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&doc.title))?;
|
||||
let items = items(doc, &o, selection, &selected, &naming.filename, false, false)?;
|
||||
let (Some(item), Some(r)) = (items.first(), rows.first()) else { return Err(bad(C, "nothing to export")) };
|
||||
let (sub, file) = naming.file(item, 0, 0, r);
|
||||
Ok(sub.map_or_else(|| file.clone(), |d| format!("{d}/{file}")))
|
||||
}
|
||||
|
||||
/// What `o` exports a file of per row ([`Item`]): the whole document, the assets, the layers, the
|
||||
/// selection (one item, or one per object), else the chosen artboards.
|
||||
/// `crop`: some row needs the Full Document's art bounds (a format other than PDF).
|
||||
fn items(doc: &Arc<Document>, o: &ScreenParams, selection: Option<bool>, selected: &[NodeId], filename: &str, crop: bool) -> Result<Vec<Item>> {
|
||||
/// `crop`: some row needs the Full Document's art bounds (a format other than PDF). `art`: each
|
||||
/// asset, layer and selected object is cut out of the document; without it, only the items' names
|
||||
/// are made, every item holds the whole document, and none is left out for drawing nothing.
|
||||
fn items(
|
||||
doc: &Arc<Document>,
|
||||
o: &ScreenParams,
|
||||
selection: Option<bool>,
|
||||
selected: &[NodeId],
|
||||
filename: &str,
|
||||
crop: bool,
|
||||
art: bool,
|
||||
) -> Result<Vec<Item>> {
|
||||
// The art of `ids` alone, as an item named `name`.
|
||||
let alone = |ids: &[NodeId], name: &str| -> Option<(Arc<Document>, Rect)> {
|
||||
if !art {
|
||||
return Some((doc.clone(), Rect::ZERO));
|
||||
}
|
||||
isolated(doc, &doc.paint_order(ids.iter().copied()), name).map(|(d, r)| (Arc::new(d), r))
|
||||
};
|
||||
// Each item's stem follows Windows' file-naming rules, and no two items share one.
|
||||
@@ -717,10 +905,12 @@ fn items(doc: &Arc<Document>, o: &ScreenParams, selection: Option<bool>, selecte
|
||||
};
|
||||
if o.full_document {
|
||||
// The bounds of all visible art, as the one artboard of the files that aren't PDFs (a PDF
|
||||
// row writes every artboard of the document itself).
|
||||
// row writes every artboard of the document itself). It is named after the document: an
|
||||
// SVG of one artboard takes the artboard's name as its title (#3544), and this one stands
|
||||
// for the whole document.
|
||||
let (whole, region) = if crop {
|
||||
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?;
|
||||
(Arc::new(single_artboard(doc, bounds, "Document")), bounds)
|
||||
(Arc::new(single_artboard(doc, bounds, &doc.title)), bounds)
|
||||
} else {
|
||||
(doc.clone(), Rect::ZERO)
|
||||
};
|
||||
@@ -818,3 +1008,29 @@ pub(crate) fn store_settings(s: &mut Session, settings: Map<String, Value>) -> R
|
||||
pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "settings": s.doc()?.doc.export_settings }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ScreenSize, safe_file_name};
|
||||
|
||||
#[test]
|
||||
fn size_parse_refuses_signs_and_exponents() {
|
||||
for s in ["+2x", "+2", "+100w", "+100h", "+72ppi", "-2x", "1e2", "2e0w"] {
|
||||
assert_eq!(ScreenSize::parse(s), None, "{s}");
|
||||
}
|
||||
assert_eq!(ScreenSize::parse("2x"), Some(ScreenSize::Scale(2.0)));
|
||||
assert_eq!(ScreenSize::parse("1.5"), Some(ScreenSize::Scale(1.5)));
|
||||
assert_eq!(ScreenSize::parse("100W"), Some(ScreenSize::Width(100.0)));
|
||||
assert_eq!(ScreenSize::parse("72ppi"), Some(ScreenSize::Ppi(72.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_name_with_space_before_extension_is_protected() {
|
||||
assert_eq!(safe_file_name("CON.png"), "CON-.png");
|
||||
assert_eq!(safe_file_name("CON .png"), "CON-.png");
|
||||
assert_eq!(safe_file_name("NUL .png"), "NUL-.png");
|
||||
assert_eq!(safe_file_name("COM1 .png"), "COM1-.png");
|
||||
assert_eq!(safe_file_name("lpt9 .png"), "lpt9-.png");
|
||||
assert_eq!(safe_file_name("My CON .png"), "My CON .png");
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,9 @@ pub fn options_map(p: &Value) -> Result<Map<String, Value>, String> {
|
||||
match o.get("svg") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Object(svg)) => m.extend(svg.clone()),
|
||||
Some(_) => return Err("`svg` must be an object of SVG options (see document.formats)".into()),
|
||||
Some(_) => {
|
||||
return Err("`svg` must be an object of SVG options (see document.formats)".into());
|
||||
}
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
@@ -147,6 +149,17 @@ fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec<Option<usize>>,
|
||||
Ok((opts, named.unwrap_or_else(|| vec![0]).into_iter().map(Some).collect(), chosen))
|
||||
}
|
||||
|
||||
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
|
||||
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
|
||||
/// Editing Capabilities).
|
||||
pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
|
||||
let n = doc.artboards.len();
|
||||
let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing);
|
||||
(n > 1 && !preserved).then(|| {
|
||||
format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.")
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
|
||||
/// link to and the writer's warnings.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Encoded, String> {
|
||||
@@ -166,9 +179,10 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
|
||||
let doc = flat.as_ref().unwrap_or(doc);
|
||||
let mut enc = Encoded { warnings, ..Encoded::default() };
|
||||
for artboard in boards {
|
||||
// A chosen artboard's file holds the art over it (#550).
|
||||
// A chosen artboard's file holds the art over it (#550) and is named after it (#3544).
|
||||
let over = artboard.filter(|_| chosen).and_then(|b| doc.artboards.get(b)).map(|a| super::export::art_over(doc, a.rect));
|
||||
let mut out = vectorcraft_svg::export_full(over.as_ref().unwrap_or(doc), &ExportOptions { artboard, ..opts.clone() }, native.as_deref());
|
||||
let file = ExportOptions { artboard, artboard_title: chosen, ..opts.clone() };
|
||||
let mut out = vectorcraft_svg::export_full(over.as_ref().unwrap_or(doc), &file, native.as_deref());
|
||||
let bytes = out.take_bytes();
|
||||
for l in out.linked {
|
||||
if !enc.linked.iter().any(|e| e.name == l.name) {
|
||||
|
||||
@@ -185,10 +185,26 @@ fn planar_tiffs_with_more_strips_than_can_be_counted_are_too_large() {
|
||||
file[102..106].copy_from_slice(&1u32.to_le_bytes());
|
||||
let e = raster_image(&file).err().expect("refused");
|
||||
assert!(e.to_string().contains("an image of 3 × 2147483649 pixels is too large to draw"), "{e}");
|
||||
assert!(too_large_note(&file).is_some());
|
||||
assert!(load::too_large_note(&file).is_some());
|
||||
assert_eq!(vectorcraft_doc::cmyk::oversized_tiff(&file), Some((3, 1 << 31 | 1)));
|
||||
}
|
||||
|
||||
/// A 16-bit RGB TIFF whose samples need more than the allowance (6 bytes a pixel), though its RGBA
|
||||
/// pixels would fit, is refused as too large to draw before it is decoded.
|
||||
#[test]
|
||||
fn tiffs_whose_samples_pass_the_allowance_are_too_large() {
|
||||
let plane = |v: u16| vec![v; 6];
|
||||
let mut file = hand_tiff(2, 16, &[], false, &[plane(9000), plane(30_000), plane(60_000)]);
|
||||
// The loop sets ImageWidth, ImageLength and RowsPerStrip (the first, second and eighth entries) to `side`.
|
||||
let side = 20_000u32;
|
||||
assert!(u64::from(side * side) * 6 > MAX_RASTER_ALLOC && u64::from(side * side) * 4 <= MAX_RASTER_ALLOC);
|
||||
for at in [18, 30, 102] {
|
||||
file[at..at + 4].copy_from_slice(&side.to_le_bytes());
|
||||
}
|
||||
let e = raster_image(&file).err().expect("refused");
|
||||
assert_eq!(e.to_string(), "an image of 20000 × 20000 pixels is too large to draw");
|
||||
}
|
||||
|
||||
/// A planar CMYK TIFF opens and places with its ink amounts, stored as a TIFF the image decoder
|
||||
/// reads (#1466).
|
||||
#[test]
|
||||
@@ -368,6 +384,14 @@ fn open_exts_cover_every_readable_format() {
|
||||
assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_open_filters_list_library_formats_first() {
|
||||
let filters: Vec<_> = library_open_filters("Swatch libraries", super::swatchlib::LIBRARY_EXTS).collect();
|
||||
assert_eq!(filters[0], ("Swatch libraries", super::swatchlib::LIBRARY_EXTS));
|
||||
assert!(filters[0].1.contains(&"ase"));
|
||||
assert_eq!(filters[1], ("All readable files", OPEN_EXTS));
|
||||
}
|
||||
|
||||
/// The extensions usage texts list for export: one per writable format, each picking that format
|
||||
/// (`.png` picks PNG; PNG-8 is asked for by `format`).
|
||||
#[test]
|
||||
@@ -678,6 +702,58 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// An option given beside the path (an SVG option flat or in `svg`) and in `options` with different
|
||||
/// values is refused before anything is written; `compress`, `version` or `preview` beside the path of a format that doesn't
|
||||
/// read it is named in the warnings.
|
||||
#[test]
|
||||
fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() {
|
||||
let d = tmp_dir("save-options");
|
||||
let mut s = session(200.0, 100.0, 1);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let path = d.join("both.vectorcraft").to_string_lossy().to_string();
|
||||
for cmd in ["document.save", "file.saveAs", "file.saveCopy", "file.saveAsTemplate"] {
|
||||
let e = s.execute(cmd, &json!({"path": path, "compress": true, "options": {"compress": false}})).unwrap_err().to_string();
|
||||
assert!(e.contains("`compress: true` and `options.compress: false` disagree") && e.contains(&format!("`{cmd}`")), "{cmd}: {e}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&path).exists(), "nothing is written");
|
||||
assert!(!d.join("both.vctemplate").exists(), "nor a template");
|
||||
// An SVG option given in `svg: {…}` or in `options.svg` counts as given there.
|
||||
let svg = d.join("a.svg").to_string_lossy().to_string();
|
||||
for p in [
|
||||
json!({"svg": {"hiddenLayers": false}, "options": {"hiddenLayers": true}}),
|
||||
json!({"hiddenLayers": false, "options": {"svg": {"hiddenLayers": true}}}),
|
||||
json!({"hiddenLayers": true, "svg": {"hiddenLayers": false}, "options": {"hiddenLayers": true}}),
|
||||
] {
|
||||
let mut p = p;
|
||||
p["path"] = json!(svg);
|
||||
let e = s.execute("file.saveCopy", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("`hiddenLayers: false` and `options.hiddenLayers: true` disagree") && e.contains("`file.saveCopy`"), "{p}: {e}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&svg).exists(), "nothing is written");
|
||||
// Agreeing values, or one of them null, save as asked; `3` and `3.0` agree.
|
||||
for p in [
|
||||
json!({"compress": true, "options": {"compress": true}}),
|
||||
json!({"compress": null, "options": {"compress": true}}),
|
||||
json!({"compress": true, "version": 3, "options": {"compress": true, "version": 3.0}}),
|
||||
] {
|
||||
let mut p = p;
|
||||
p["path"] = json!(path);
|
||||
let r = s.execute("file.saveCopy", &p).unwrap();
|
||||
assert_eq!(r["warnings"], json!([]), "{p}: {r}");
|
||||
assert_eq!(std::fs::read(&path).unwrap()[..2], [0x1f, 0x8b], "{p}");
|
||||
}
|
||||
// An SVG file reads none of the native options; a .ai file reads `compress` only.
|
||||
let r = s.execute("file.saveCopy", &json!({"path": svg, "compress": true, "version": 3, "preview": null})).unwrap();
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(w.contains(&"`compress` was not used: SVG files don't read it"), "{w:?}");
|
||||
assert!(w.contains(&"`version` was not used: SVG files don't read it") && !w.iter().any(|w| w.starts_with("`preview`")), "{w:?}");
|
||||
assert!(std::fs::read(&svg).unwrap().starts_with(b"<"), "plain SVG");
|
||||
let r = s.execute("file.saveCopy", &json!({"path": d.join("a.ai").to_string_lossy(), "compress": false, "version": 3})).unwrap();
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(w.iter().any(|w| w.starts_with("`version` was not used")) && !w.iter().any(|w| w.starts_with("`compress`")), "{w:?}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A native save whose file write fails partway (a full disk) leaves the file as it was, and no
|
||||
/// temporary file behind.
|
||||
#[test]
|
||||
|
||||
@@ -82,6 +82,37 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() {
|
||||
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
/// A `.ai` file opens with the swatches its palette holds, spot colours the art doesn't use and colour
|
||||
/// groups included, in place of the default swatches; art painted with Registration (`XZ`) still
|
||||
/// opens from the editing data.
|
||||
#[test]
|
||||
fn an_ai_file_opens_with_the_swatches_of_its_palette() {
|
||||
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\
|
||||
0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n";
|
||||
// The square the page draws, in the red ink, after a stroke colour of Registration.
|
||||
let art = format!("0 0 0 0 0 0 0 ([Registration]) 0 1 XZ\n0.06 0.98 1 0 (Red ink) 0 x\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0));
|
||||
let data = ai::editing_data(200.0, 100.0, &format!("{palette}{}", ai::layer("Art", &art)));
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "inks.ai", &ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
|
||||
assert_eq!(r["format"], json!("ai"), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(names(&doc.layers), ["Art"], "opened from the editing data: {r}");
|
||||
let swatches: Vec<&str> = doc.swatches.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(swatches, ["[None]", "White", "Pink ink", "Red ink"]);
|
||||
let pink = doc.swatch("Pink ink").unwrap();
|
||||
assert!(pink.spot && pink.global);
|
||||
assert_eq!(pink.paint.color(), Some(vectorcraft_color::Color::lab(81.96, 21.0, -8.0)), "a Lab ink keeps its Lab values");
|
||||
let groups: Vec<&str> = doc.swatch_groups.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(groups, ["Inks"]);
|
||||
assert!(doc.swatch("Yellow ink").is_some_and(|s| s.spot), "an ink the art doesn't use");
|
||||
let red = &doc.layers[0].children().unwrap()[0];
|
||||
assert!(
|
||||
matches!(red.appearance.fill().map(|f| &f.paint), Some(vectorcraft_color::Paint::Solid { swatch: Some(n), .. }) if n == "Red ink"),
|
||||
"{:?}",
|
||||
red.appearance.fill()
|
||||
);
|
||||
}
|
||||
|
||||
/// A 1-bit RGB image opens from the editing data in the colors its PDF part shows.
|
||||
#[test]
|
||||
fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
|
||||
@@ -103,6 +134,87 @@ fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
|
||||
assert_eq!(found, [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], "{r}");
|
||||
}
|
||||
|
||||
/// A page of a square and a line of type, as a `.ai`'s PDF part draws them.
|
||||
const SQUARE_AND_TYPE: &str = "0 g 10 10 40 40 re f BT /F1 12 Tf 100 50 Td (Hi) Tj ET";
|
||||
|
||||
/// `file` loaded with `clipboard.importPdf` (`editingData` as given) and pasted → the command's
|
||||
/// reply and the objects the paste selected, in stacking order.
|
||||
fn paste(s: &mut Session, file: &[u8], editing_data: bool) -> (Value, Vec<Node>) {
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "editingData": editing_data});
|
||||
let r = s.execute("clipboard.importPdf", &p).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
(r, st.selection.in_paint_order(&st.doc).into_iter().filter_map(|id| st.doc.node(id).cloned()).collect())
|
||||
}
|
||||
|
||||
/// Is any of `nodes` (or an object inside one) type?
|
||||
fn has_type(nodes: &[Node]) -> bool {
|
||||
let mut found = false;
|
||||
nodes.iter().for_each(|n| n.walk(&mut |c| found |= matches!(c.kind, NodeKind::Text(_))));
|
||||
found
|
||||
}
|
||||
|
||||
/// A `.ai` copied in a file manager pastes the objects of its editing data, as `document.open`
|
||||
/// reads it: both layers' objects in their stacking order, into the active layer, with their names
|
||||
/// and hidden members, and its type as type. Without `editingData`, as for a PDF, its page pastes:
|
||||
/// the shown layer's art without names.
|
||||
#[test]
|
||||
fn a_copied_ai_file_pastes_from_its_editing_data() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let file = ai::ai(&compressed(&ai::sample_data()), ai::page_pdf());
|
||||
let (r, pasted) = paste(&mut s, &file, true);
|
||||
assert_eq!(r["count"], 7, "{r}");
|
||||
let pasted_names: Vec<String> = pasted.iter().map(|n| n.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(pasted_names, ["Pair", "Ring", "Window", "Shaded", "", "Sub", ""]);
|
||||
let pair = pasted[0].children().unwrap();
|
||||
assert!(pair[0].visible && !pair[1].visible, "the hidden member stays hidden");
|
||||
assert!(matches!(pasted[5].kind, NodeKind::Layer { .. }) && pasted[5].locked, "the sublayer comes as it is");
|
||||
assert_eq!(pasted.iter().map(|n| n.visible).collect::<Vec<_>>(), [true, true, true, false, false, false, false], "the hidden layer's objects");
|
||||
let layers = &s.doc().unwrap().doc.layers;
|
||||
assert_eq!(layers.len(), 1, "no layer is added");
|
||||
assert!(pasted.iter().all(|n| layers[0].children().unwrap().iter().any(|c| c.id == n.id)), "into the active layer");
|
||||
// The same editing data in an EPS: the same objects, the hidden layer's objects hidden.
|
||||
let eps = ai::eps(&ai::sample_data(), ai::page_ps());
|
||||
s.execute("clipboard.importEps", &json!({"dataBase64": vectorcraft_format::base64_encode(&eps)})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let shown = |nodes: Vec<&Node>| nodes.iter().map(|n| (n.name.clone().unwrap_or_default(), n.visible)).collect::<Vec<_>>();
|
||||
assert_eq!(shown(st.selection.in_paint_order(&st.doc).into_iter().filter_map(|id| st.doc.node(id)).collect()), shown(pasted.iter().collect()));
|
||||
let (r, page) = paste(&mut s, &file, false);
|
||||
assert!(page.iter().all(|n| n.name.is_none()), "{r}");
|
||||
// A page of text only, or only a placeholder (saved without PDF compatibility): the editing
|
||||
// data's objects all the same.
|
||||
for (page, boxed) in [(TEXT_ART, "/ArtBox [0 0 200 100]"), (PLACEHOLDER, "")] {
|
||||
let (r, pasted) = paste(&mut s, &ai::ai_with(&compressed(&ai::sample_data()), page, boxed), true);
|
||||
assert_eq!(pasted.first().and_then(|n| n.name.as_deref()), Some("Pair"), "{page}: {r}");
|
||||
assert_eq!(r["count"], 7, "{page}: {r}");
|
||||
}
|
||||
// Type: a text object from the editing data, outlines from the page.
|
||||
let data = ai::editing_data(
|
||||
200.0,
|
||||
100.0,
|
||||
&ai::layer("Art", &format!("0 g\n{}f\n/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n", ai::rect(10.0, 10.0, 50.0, 50.0))),
|
||||
);
|
||||
let typed = ai::ai(&compressed(data.as_bytes()), SQUARE_AND_TYPE);
|
||||
// (The page's type comes in as type too now that PDF import keeps it, so only this side is told apart.)
|
||||
let (r, pasted) = paste(&mut s, &typed, true);
|
||||
assert!(has_type(&pasted), "{r}: {pasted:?}");
|
||||
// A `.ai` VectorCraft wrote: the document it carries, its hidden square too.
|
||||
let mut other = Session::new();
|
||||
other.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
for x in [10, 100] {
|
||||
other.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
}
|
||||
other.execute("object.hide", &json!({})).unwrap();
|
||||
let saved = other.execute("document.export", &json!({"format": "ai"})).unwrap();
|
||||
let saved = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let (r, pasted) = paste(&mut s, &saved, true);
|
||||
assert_eq!(pasted.iter().map(|n| n.visible).collect::<Vec<_>>(), [true, false], "{r}");
|
||||
let (r, page) = paste(&mut s, &saved, false);
|
||||
assert!(page.iter().all(|n| n.visible), "{r}");
|
||||
}
|
||||
|
||||
/// A PDF saved with the editing data opens from it, as a `.ai` does (#868).
|
||||
#[test]
|
||||
fn a_pdf_saved_with_the_editing_data_opens_from_it() {
|
||||
@@ -135,16 +247,65 @@ fn a_pdfs_art_past_the_page_opens_whole_from_its_editing_data() {
|
||||
assert!(s.doc().unwrap().doc.art_bounds().is_some_and(|b| b.x1 < 200.5));
|
||||
}
|
||||
|
||||
/// Editing data that can't be read leaves the file as its PDF part reads, with that part's notes:
|
||||
/// a `.ai`'s art outside its artboards is missing, and a PDF's art past the page is clipped.
|
||||
/// A `.ai` or a PDF whose editing data can't be decompressed opens from its PDF part with a note
|
||||
/// that its layers weren't read, and an export to its own path is refused unless it is given
|
||||
/// `acknowledgeLoss`.
|
||||
#[test]
|
||||
fn a_file_whose_editing_data_cant_be_decompressed_is_not_written_over_unasked() {
|
||||
let d = std::env::temp_dir().join(format!("vc-aiundecoded-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let damaged = b"%AI12_CompressedDataxx";
|
||||
for (name, file) in [("art.ai", ai::ai(damaged, ai::page_pdf())), ("art.pdf", ai::pdf(damaged, ai::page_pdf()))] {
|
||||
let path = d.join(name);
|
||||
std::fs::write(&path, &file).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("layers weren't read from its editing data (its zlib compression is damaged)"), "{name}: {r}");
|
||||
let e = s.execute("document.export", &json!({"path": path})).unwrap_err().to_string();
|
||||
assert!(e.contains("left things out") && e.contains("layers weren't read"), "{name}: {e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), file, "{name}");
|
||||
s.execute("document.export", &json!({"path": path, "acknowledgeLoss": true})).unwrap();
|
||||
assert_ne!(std::fs::read(&path).unwrap(), file, "{name}");
|
||||
}
|
||||
std::fs::remove_dir_all(d).ok();
|
||||
}
|
||||
|
||||
/// Editing data that can't be read leaves the file as its PDF part reads, with that part's notes
|
||||
/// and then a note saying why its layers weren't read: a `.ai`'s art outside its artboards is
|
||||
/// missing, and a PDF's art past the page is clipped.
|
||||
#[test]
|
||||
fn editing_data_that_cant_be_read_keeps_the_pdf_parts_notes() {
|
||||
let damaged = b"%AI12_CompressedData not zlib";
|
||||
let unread = "the file's layers weren't read from its editing data (its zlib compression is damaged): they come from its PDF part";
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "damaged.ai", &ai::ai(damaged, ai::page_pdf()), json!({})).unwrap();
|
||||
assert_eq!(r["warnings"], json!([vectorcraft_pdf::OFF_ARTBOARD_NOTE]), "{r}");
|
||||
assert_eq!(r["warnings"], json!([vectorcraft_pdf::OFF_ARTBOARD_NOTE, unread]), "{r}");
|
||||
let r = open(&mut s, "damaged.pdf", &ai::pdf(damaged, "0 g 150 20 100 60 re f"), json!({})).unwrap();
|
||||
assert_eq!(r["warnings"], json!([vectorcraft_pdf::PAST_PAGE_NOTE]), "{r}");
|
||||
assert_eq!(r["warnings"], json!([vectorcraft_pdf::PAST_PAGE_NOTE, unread]), "{r}");
|
||||
}
|
||||
|
||||
/// A copied `.ai` whose editing data can't be read, or isn't there, pastes its page as a PDF
|
||||
/// does: the same objects as without `editingData`.
|
||||
#[test]
|
||||
fn a_copied_ai_file_whose_editing_data_cant_be_read_pastes_its_page() {
|
||||
let symbols = ai::editing_data(200.0, 100.0, &ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n"));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
for (what, private) in
|
||||
[("damaged", b"%AI12_CompressedData not zlib".to_vec()), ("unread layers", compressed(symbols.as_bytes())), ("none", vec![])]
|
||||
{
|
||||
let file = ai::ai(&private, SQUARE_AND_TYPE);
|
||||
let (r, pasted) = paste(&mut s, &file, true);
|
||||
let (want, page) = paste(&mut s, &file, false);
|
||||
assert_eq!((&r["count"], &r["warnings"]), (&want["count"], &want["warnings"]), "{what}");
|
||||
let kinds = |nodes: &[Node]| nodes.iter().map(|n| std::mem::discriminant(&n.kind)).collect::<Vec<_>>();
|
||||
assert_eq!(kinds(&pasted), kinds(&page), "{what}");
|
||||
assert!(!pasted.is_empty(), "{what}: {r}");
|
||||
}
|
||||
// Editing data that reads and draws as the page does: its objects, not the page's.
|
||||
let (r, _) = paste(&mut s, &ai::ai(&compressed(&ai::sample_data()), ai::page_pdf()), true);
|
||||
assert_eq!(r["count"], 7, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -158,6 +319,34 @@ fn what_the_reader_doesnt_read_opens_as_before_with_a_warning() {
|
||||
assert!(r["warnings"].to_string().contains("symbols") && r["warnings"].to_string().contains("PDF part"), "{r}");
|
||||
}
|
||||
|
||||
/// A `.ai` whose document data has a variable library opens with a note that its variables and
|
||||
/// data sets weren't read, whether its layers are read or it comes in as its PDF part.
|
||||
#[test]
|
||||
fn an_ai_file_with_a_variable_library_says_its_variables_werent_read() {
|
||||
const NOTE: &str = "the file's variables and data sets weren't read (variables: 2, data sets: 3): the Variables panel doesn't list them";
|
||||
let library = ai::variable_library(&["Name", "Number"], &["One", "Two", "Three"]);
|
||||
let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0));
|
||||
let notes =
|
||||
|r: &Value| r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().contains("variables")).cloned().collect::<Vec<_>>();
|
||||
let mut s = Session::new();
|
||||
let layered = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", &square)));
|
||||
let file = ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
|
||||
let r = open(&mut s, "variables.ai", &file, json!({})).unwrap();
|
||||
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
|
||||
assert_eq!(notes(&r), [json!(NOTE)], "{r}");
|
||||
let r = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(r["variables"], json!([]), "{r}");
|
||||
// Its layers can't be read (a symbol): it comes in as its PDF part, with the note.
|
||||
let symbols = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n")));
|
||||
let r = open(&mut s, "symbols.ai", &ai::ai(&compressed(symbols.as_bytes()), ai::page_pdf()), json!({})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("PDF part"), "{r}");
|
||||
assert_eq!(notes(&r), [json!(NOTE)], "{r}");
|
||||
// Without a library, no note.
|
||||
let plain = ai::editing_data(200.0, 100.0, &ai::layer("Art", &square));
|
||||
let r = open(&mut s, "plain.ai", &ai::ai(&compressed(plain.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
}
|
||||
|
||||
/// A page showing only a placeholder line, as a `.ai` saved without PDF compatibility has.
|
||||
const PLACEHOLDER: &str = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET";
|
||||
|
||||
@@ -175,6 +364,90 @@ fn an_ai_file_saved_without_its_pdf_part_opens_from_its_editing_data() {
|
||||
assert!(e.contains("placeholder"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_file_saved_without_its_pdf_part_opens_with_pages_naming_every_page() {
|
||||
let file = ai::ai(&compressed(&ai::sample_data()), PLACEHOLDER);
|
||||
for pages in [json!("1"), json!(1), json!("1-")] {
|
||||
let mut s = Session::new();
|
||||
open(&mut s, "art.ai", &file, json!({"pages": pages})).unwrap();
|
||||
check_sample(&s);
|
||||
}
|
||||
// Without editing data, the placeholder still isn't opened as the art.
|
||||
let e = open(&mut Session::new(), "plain.ai", &ai::ai(b"", PLACEHOLDER), json!({"pages": "1"})).unwrap_err().to_string();
|
||||
assert!(e.contains("placeholder"), "{e}");
|
||||
}
|
||||
|
||||
/// [`PLACEHOLDER`]'s `.ai` files as `dataBase64`: the sample's editing data, damaged editing data
|
||||
/// and none.
|
||||
fn placeholder_files() -> [String; 3] {
|
||||
[compressed(&ai::sample_data()), b"%AI12_CompressedData not zlib".to_vec(), vec![]]
|
||||
.map(|private| vectorcraft_format::base64_encode(&ai::ai(&private, PLACEHOLDER)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_file_saved_without_its_pdf_part_pastes_from_its_editing_data() {
|
||||
let [sample, damaged, plain] = placeholder_files();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
// clipboard.importPdf (the PDF flavor's command) takes every object of both layers, as
|
||||
// document.open reads them.
|
||||
let r = s.execute("clipboard.importPdf", &json!({"dataBase64": sample})).unwrap();
|
||||
assert_eq!(r["count"], json!(7), "{r}");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let art = s.doc().unwrap().doc.layers[0].children().unwrap().clone();
|
||||
assert_eq!(names(&art), ["Pair", "Ring", "Window", "Shaded", "", "Sub", ""]);
|
||||
assert_eq!(art.iter().map(|n| n.visible).collect::<Vec<_>>(), [true, true, true, false, false, false, false], "the hidden layer's objects");
|
||||
let e = s.execute("clipboard.importPdf", &json!({"dataBase64": damaged})).unwrap_err().to_string();
|
||||
assert!(e.contains("without PDF compatibility") && e.contains("zlib"), "{e}");
|
||||
let e = s.execute("clipboard.importPdf", &json!({"dataBase64": plain})).unwrap_err().to_string();
|
||||
assert!(e.contains("placeholder"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() {
|
||||
let [sample, damaged, plain] = placeholder_files();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
// The place takes the art of the layers that show on the artboard and clips it to the artboard.
|
||||
let r = s.execute("file.place", &json!({"name": "art.ai", "dataBase64": sample, "link": false})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{r}");
|
||||
let placed = s.doc().unwrap().doc.layers[0].children().unwrap()[0].clone();
|
||||
let kids = placed.children().unwrap();
|
||||
assert_eq!(names(&kids[1..]), ["Pair", "Ring", "Window"], "after the clipping path");
|
||||
// With `crop: "bounding"` the size is the bounds of the art that shows. They run from the red
|
||||
// square's left edge to the window's right one; the pair's hidden square, stroked 2 pt wide,
|
||||
// is left out.
|
||||
let r = s.execute("file.place.info", &json!({"name": "art.ai", "dataBase64": sample, "crop": "bounding"})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(170.0), Some(40.0)), "{r}");
|
||||
// The place takes the art of both layers that show.
|
||||
let square = |x: f64| format!("0 g\n{}f\n", ai::rect(x, 10.0, x + 40.0, 50.0));
|
||||
let two = ai::editing_data(200.0, 100.0, &[ai::layer("Back", &square(10.0)), ai::layer("Front", &square(110.0))].concat());
|
||||
let two = vectorcraft_format::base64_encode(&ai::ai(&compressed(two.as_bytes()), PLACEHOLDER));
|
||||
let r = s.execute("file.place.info", &json!({"name": "two.ai", "dataBase64": two, "crop": "bounding"})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(140.0), Some(40.0)), "{r}");
|
||||
// The file has two 100-point artboards and one placeholder page. The second artboard lies 50
|
||||
// below the first. A square of 40 lies on the first and an oblong of 60 × 40 on the second.
|
||||
let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\
|
||||
%_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\
|
||||
%_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\
|
||||
%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n";
|
||||
let art = format!("0 g\n{}f\n{}f\n", ai::rect(10.0, 10.0, 50.0, 50.0), ai::rect(10.0, -140.0, 70.0, -100.0));
|
||||
let paged = ai::editing_data(100.0, 100.0, &(boards.to_string() + &ai::layer("Art", &art)));
|
||||
let paged = vectorcraft_format::base64_encode(&ai::ai(&compressed(paged.as_bytes()), PLACEHOLDER));
|
||||
let mut size = |page: u64| {
|
||||
let r = s.execute("file.place.info", &json!({"name": "boards.ai", "dataBase64": paged, "page": page, "crop": "bounding"}));
|
||||
r.map(|r| (r["width"].as_f64(), r["height"].as_f64())).map_err(|e| e.to_string())
|
||||
};
|
||||
assert_eq!(size(1), Ok((Some(40.0), Some(40.0))));
|
||||
assert_eq!(size(2), Ok((Some(60.0), Some(40.0))));
|
||||
let third = size(3);
|
||||
assert!(third.as_ref().is_err_and(|e| e.contains("has 2 page(s)")), "{third:?}");
|
||||
let e = s.execute("file.place", &json!({"name": "damaged.ai", "dataBase64": damaged})).unwrap_err().to_string();
|
||||
assert!(e.contains("without PDF compatibility") && e.contains("zlib"), "{e}");
|
||||
let e = s.execute("file.place", &json!({"name": "plain.ai", "dataBase64": plain})).unwrap_err().to_string();
|
||||
assert!(e.contains("placeholder"), "{e}");
|
||||
}
|
||||
|
||||
/// A page of text alone, as text-only art has in its PDF part: no path is painted.
|
||||
const TEXT_ART: &str = "BT /F1 36 Tf 10 40 Td (Text only) Tj ET";
|
||||
|
||||
|
||||
@@ -134,17 +134,25 @@ fn layers_and_the_selection_are_exported_by_name() {
|
||||
assert!(s.execute("document.exportForScreens", &json!({"selection": "one"})).is_err(), "nothing selected");
|
||||
}
|
||||
|
||||
/// Document formats write each artboard as a document of its own: one artboard, its art.
|
||||
/// Document formats write each artboard as a document of its own: one artboard, its art and
|
||||
/// not the other artboards' (#3868).
|
||||
#[test]
|
||||
fn document_formats_write_one_artboard_each() {
|
||||
let mut s = session(2);
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect;
|
||||
s.execute("shape.ellipse", &json!({"x": second.x0 + 5.0, "y": 5, "width": 10, "height": 10})).unwrap();
|
||||
let r = export(&mut s, json!({"formats": [{"format": "vectorcraft"}, {"format": "ai"}, {"format": "eps"}]}));
|
||||
let n = names(&r);
|
||||
assert_eq!(n, ["Artboard-1.vectorcraft", "Artboard-1.ai", "Artboard-1.eps", "Artboard-2.vectorcraft", "Artboard-2.ai", "Artboard-2.eps"]);
|
||||
let native = &files(&r)[0].1;
|
||||
let mut t = Session::new();
|
||||
t.execute("document.open", &json!({"name": "a.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(native)})).unwrap();
|
||||
assert_eq!(t.doc().unwrap().doc.artboards.len(), 1, "that artboard alone");
|
||||
let all = files(&r);
|
||||
for (name, bytes) in &all {
|
||||
let mut t = Session::new();
|
||||
t.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap();
|
||||
let d = &t.doc().unwrap().doc;
|
||||
assert_eq!(d.artboards.len(), 1, "{name}: that artboard alone");
|
||||
let objects: usize = d.layers.iter().filter_map(|l| l.children()).map(|c| c.len()).sum();
|
||||
assert_eq!(objects, 1, "{name}: only its own artboard's art");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -125,6 +125,24 @@ fn placed_images_come_back_as_linked_files() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Two placed images whose pixel data can't be decoded are left out of the drawing and get no
|
||||
/// linked file, and `warnings` holds the note raster exports give, once, without naming either
|
||||
/// image's key.
|
||||
#[test]
|
||||
fn images_that_cant_be_decoded_give_the_raster_note_once() {
|
||||
const NOTE: &str = "an image couldn't be decoded and is missing from the picture";
|
||||
let mut s = session(200.0, 100.0, 1);
|
||||
crate::tests_menucmds::place_undecodable_png(&mut s);
|
||||
crate::tests_menucmds::place_undecodable_png_sized(&mut s, 32, 16);
|
||||
let keys: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
let r = s.execute("document.export", &json!({"format": "dxf"})).unwrap();
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(w.iter().filter(|w| **w == NOTE).count(), 1, "{w:?}");
|
||||
assert!(!w.iter().any(|w| keys.iter().any(|k| w.contains(k.as_str()))), "{w:?}");
|
||||
assert!(entities(&text(&r)).is_empty() && r.get("linked").is_none(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_dxf_options_are_refused() {
|
||||
let mut s = two_boards();
|
||||
@@ -169,7 +187,7 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
}
|
||||
assert!(r["writable"].as_array().unwrap().contains(&json!("dxf")));
|
||||
let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(unsupported, ["dwg", "pict"]);
|
||||
assert_eq!(unsupported, ["dwg", "pict", "pmd"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -191,4 +209,9 @@ fn dwg_and_pict_say_what_to_use_instead() {
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(e.contains("DWG is not available"), "{e}");
|
||||
let e = s
|
||||
.execute("document.open", &json!({"name": "brochure.PMD", "dataBase64": vectorcraft_format::base64_encode(b"PageMaker")}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(e.contains("brochure.PMD") && e.contains("PageMaker"), "{e}");
|
||||
}
|
||||
@@ -80,8 +80,13 @@ fn use_artboards_writes_a_file_per_artboard_named_with_an_underscore() {
|
||||
let r = s.execute("document.export", &json!({"format": "eps", "useArtboards": true, "previewFormat": "none"})).unwrap();
|
||||
let files = r["files"].as_array().unwrap();
|
||||
let names: Vec<&str> = files.iter().map(|f| f["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Untitled-1_Artboard-1.eps", "Untitled-1_Artboard-2.eps"]);
|
||||
for f in files {
|
||||
assert_eq!(names, ["Untitled-1.eps", "Untitled-1_Artboard-1.eps", "Untitled-1_Artboard-2.eps"]);
|
||||
// The central file comes first: the whole document, bounded by the visible art of both artboards.
|
||||
let central = b64(&files[0]);
|
||||
assert_eq!(dsc(&postscript(¢ral), "BoundingBox").as_deref(), Some(format!("10 60 {} 90", second + 40.0).as_str()));
|
||||
let native = vectorcraft_format::load(&vectorcraft_eps::native(¢ral).unwrap()).unwrap();
|
||||
assert_eq!((native.artboards.len(), native.layers[0].children().unwrap().len()), (2, 2));
|
||||
for f in &files[1..] {
|
||||
let bytes = b64(f);
|
||||
let ps = postscript(&bytes);
|
||||
assert_eq!(dsc(&ps, "BoundingBox").as_deref(), Some("0 0 100 100"));
|
||||
@@ -89,14 +94,49 @@ fn use_artboards_writes_a_file_per_artboard_named_with_an_underscore() {
|
||||
let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap();
|
||||
assert_eq!(native.artboards.len(), 1);
|
||||
}
|
||||
// Named artboards, two or more, get the central file too.
|
||||
let r = s.execute("document.exportEps", &json!({"artboards": [1, 0], "previewFormat": "none"})).unwrap();
|
||||
let names: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Untitled-1.eps", "Untitled-1_Artboard-2.eps", "Untitled-1_Artboard-1.eps"]);
|
||||
// A range names the artboards (useArtboards implied); one file keeps the path's name.
|
||||
let r = s.execute("document.exportEps", &json!({"range": "2", "previewFormat": "none"})).unwrap();
|
||||
assert!(r.get("files").is_none());
|
||||
assert!(postscript(&b64(&r)).contains(&format!("[1 0 0 -1 {} 100] cm", -second)));
|
||||
// useArtboards: false writes one file of the visible art, even with artboards named.
|
||||
let r = s.execute("document.exportEps", &json!({"useArtboards": false, "artboards": [0, 1], "previewFormat": "none"})).unwrap();
|
||||
assert!(r.get("files").is_none());
|
||||
assert_eq!(dsc(&postscript(&b64(&r)), "BoundingBox").as_deref(), Some(format!("10 60 {} 90", second + 40.0).as_str()));
|
||||
assert!(s.execute("document.exportEps", &json!({"artboard": 5})).is_err());
|
||||
// Without art there is nothing to bound.
|
||||
let mut empty = session(100.0, 100.0, 1);
|
||||
assert!(empty.execute("document.exportEps", &json!({})).unwrap_err().to_string().contains("nothing to export"));
|
||||
// Artboards without art still get their files, but no central file.
|
||||
let mut empty = session(100.0, 100.0, 2);
|
||||
let r = empty.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": "none"})).unwrap();
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
// Named artboards without useArtboards get the same files.
|
||||
let r = empty.execute("document.exportEps", &json!({"range": "1-2", "previewFormat": "none"})).unwrap();
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn use_artboards_writes_the_central_file_beside_the_artboard_files() {
|
||||
let mut s = session(100.0, 100.0, 2);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("vc-epsboards-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("logo.eps").to_string_lossy().to_string();
|
||||
s.execute("document.exportEps", &json!({"path": path, "useArtboards": true, "previewFormat": "none"})).unwrap();
|
||||
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
written.sort();
|
||||
assert_eq!(written, ["logo.eps", "logo_Artboard-1.eps", "logo_Artboard-2.eps"]);
|
||||
let central = std::fs::read(&path).unwrap();
|
||||
assert_eq!(dsc(&postscript(¢ral), "BoundingBox").as_deref(), Some("10 60 40 90"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
// Export for Screens still writes one EPS per artboard, with no central file.
|
||||
let rows = json!({"formats": [{"format": "eps", "useArtboards": true}], "settings": {"eps": {"useArtboards": true}}});
|
||||
let r = s.execute("document.exportForScreens", &rows).unwrap();
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -156,6 +196,23 @@ fn placed_images_are_written_and_previews_are_black_and_white_on_request() {
|
||||
assert!(l3.contains("/FlateDecode filter >> image"));
|
||||
}
|
||||
|
||||
/// Two placed images whose pixel data can't be decoded are left out of the EPS, and `warnings`
|
||||
/// holds the note raster exports give, once, without naming either image's key.
|
||||
#[test]
|
||||
fn images_that_cant_be_decoded_give_the_raster_note_once() {
|
||||
const NOTE: &str = "an image couldn't be decoded and is missing from the picture";
|
||||
let mut s = session(200.0, 100.0, 1);
|
||||
crate::tests_menucmds::place_undecodable_png(&mut s);
|
||||
crate::tests_menucmds::place_undecodable_png_sized(&mut s, 32, 16);
|
||||
let keys: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
let r = s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap();
|
||||
let w = warnings(&r);
|
||||
assert_eq!(w.iter().filter(|w| *w == NOTE).count(), 1, "{w:?}");
|
||||
assert!(!w.iter().any(|w| keys.iter().any(|k| w.contains(k.as_str()))), "{w:?}");
|
||||
assert!(!postscript(&b64(&r)).contains("filter >> image"), "no image is written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_eps_options_are_refused_and_formats_list_eps() {
|
||||
let mut s = session(100.0, 100.0, 1);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! EPS and PostScript files opened and placed: our own EPS files restore the document they carry,
|
||||
//! others are read by the PostScript interpreter or come in as their preview.
|
||||
|
||||
use std::io::Write as _;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::tests_svgedit::{comparable, rich};
|
||||
@@ -93,6 +95,33 @@ fn cmyk_images_keep_their_inks_when_an_eps_opens_or_is_placed() {
|
||||
assert_eq!(images(&s), [want.clone(), want]);
|
||||
}
|
||||
|
||||
/// A 4-bit gray image compressed with Flate and TIFF predictor 2 draws the samples it had before
|
||||
/// differencing, in an EPS and in a PostScript `.ai`.
|
||||
#[test]
|
||||
fn tiff_predicted_4_bit_images_open_from_eps_and_postscript_ai_files() {
|
||||
// Two rows of four samples, 0 5 15 3 and 9 9 2 0, differenced to 0 5 10 4 and 9 0 9 14.
|
||||
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
z.write_all(&[0x05, 0xa4, 0x90, 0x9e]).unwrap();
|
||||
let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02x}")).collect();
|
||||
let ps = format!(
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 20\n%%EndComments\n40 20 scale 4 2 4 [4 0 0 -2 0 2] currentfile /ASCIIHexDecode filter \
|
||||
<< /Predictor 2 /Colors 1 /BitsPerComponent 4 /Columns 4 >> /FlateDecode filter image\n{hex}>\nshowpage\n%%EOF\n"
|
||||
);
|
||||
for name in ["predicted.eps", "predicted.ai"] {
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, name, ps.as_bytes()).unwrap();
|
||||
assert_eq!(r["warnings"], json!([]), "{name}: {r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut grays = vec![];
|
||||
d.walk(|n| {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
grays = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_luma8().into_raw();
|
||||
}
|
||||
});
|
||||
assert_eq!(grays, [0, 5, 15, 3, 9, 9, 2, 0].map(|v| v * 17), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_eps_file_comes_in_as_its_preview() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -95,6 +95,24 @@ fn raster_effects_are_written_as_images() {
|
||||
assert!(kinds.contains(&114), "the shadow is an image with transparency");
|
||||
}
|
||||
|
||||
/// Two placed images whose pixel data can't be decoded are left out of an EMF or WMF, and
|
||||
/// `warnings` holds the note raster exports give, once, without naming either image's key.
|
||||
#[test]
|
||||
fn images_that_cant_be_decoded_give_the_raster_note_once() {
|
||||
const NOTE: &str = "an image couldn't be decoded and is missing from the picture";
|
||||
let mut s = session(200.0, 100.0, 1);
|
||||
crate::tests_menucmds::place_undecodable_png(&mut s);
|
||||
crate::tests_menucmds::place_undecodable_png_sized(&mut s, 32, 16);
|
||||
let keys: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
for format in ["emf", "wmf"] {
|
||||
let r = s.execute("document.export", &json!({"format": format})).unwrap();
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(w.iter().filter(|w| **w == NOTE).count(), 1, "{format}: {w:?}");
|
||||
assert!(!w.iter().any(|w| keys.iter().any(|k| w.contains(k.as_str()))), "{format}: {w:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafiles_open_and_place() {
|
||||
let mut s = two_boards();
|
||||
|
||||
@@ -131,6 +131,82 @@ fn options_not_applied_yet_and_document_features_warn() {
|
||||
assert!(warnings(&s.execute("document.export", &json!({"format": "png"})).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
/// A placed 16-bit PNG is written at 8 bits a sample in PDF 1.3 and 1.4 files (PDF/X-3 and the
|
||||
/// pages of a .ai file too), and keeps 16 bits from PDF 1.5.
|
||||
#[test]
|
||||
fn a_16_bit_png_is_written_at_8_bits_before_pdf_1_5() {
|
||||
let mut s = session(1);
|
||||
let deep = image::ImageBuffer::from_fn(8, 8, |x, y| image::Rgb([x as u16 * 8000, y as u16 * 8000, 40000]));
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::ImageRgb16(deep).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
s.execute("file.place", &json!({"name": "deep.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [50, 40]})).unwrap();
|
||||
let readable = json!({"compressText": false});
|
||||
for (cmd, p, depth) in [
|
||||
("document.exportPdf", json!({"compatibility": "1.3", "compression": readable}), 8),
|
||||
("document.exportPdf", json!({"compatibility": "1.4", "compression": readable}), 8),
|
||||
("document.exportPdf", json!({"standard": "pdfX3", "compression": readable}), 8),
|
||||
("file.saveCopy", json!({"format": "ai", "compatibility": "1.4", "compress": false}), 8),
|
||||
("document.exportPdf", json!({"compatibility": "1.5", "compression": readable}), 16),
|
||||
("document.exportPdf", json!({"compression": readable}), 16),
|
||||
] {
|
||||
let v = s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
|
||||
let text = String::from_utf8_lossy(&b64(&v)).into_owned();
|
||||
let (eight, sixteen) = (text.contains("/BitsPerComponent 8"), text.contains("/BitsPerComponent 16"));
|
||||
assert_eq!((eight, sixteen), (depth == 8, depth == 16), "{cmd} {p}");
|
||||
assert!(warnings(&v).iter().all(|w| !w.contains("decoded")), "{cmd} {p}: {}", v["warnings"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A placed image whose pixel data can't be decoded is left out of every PDF the engine writes,
|
||||
/// and the rest of the page is written. Each reply that carries the PDF's warnings has the note
|
||||
/// raster exports give, once.
|
||||
#[test]
|
||||
fn every_pdf_leaves_out_an_image_that_cant_be_decoded() {
|
||||
const NOTE: &str = "an image couldn't be decoded and is missing from the picture";
|
||||
let mut s = session(1);
|
||||
let cut = crate::tests_menucmds::place_undecodable_png(&mut s);
|
||||
// Whether each object on the PDF's pages is an image. The pages should hold the rectangle and
|
||||
// no image.
|
||||
let drawn = |bytes: &[u8]| {
|
||||
let mut images = vec![];
|
||||
vectorcraft_pdf::import(bytes).unwrap().walk(|n| {
|
||||
if !n.is_container() && !matches!(n.kind, vectorcraft_doc::NodeKind::Path { clipping: true, .. }) {
|
||||
images.push(matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)));
|
||||
}
|
||||
});
|
||||
images
|
||||
};
|
||||
for (cmd, p) in [
|
||||
("document.exportPdf", json!({})),
|
||||
("document.exportPdf", json!({"preset": "High Quality Print"})),
|
||||
("document.exportPdf", json!({"standard": "pdfX1a"})),
|
||||
("document.export", json!({"format": "pdf"})),
|
||||
("file.saveCopy", json!({"format": "pdf"})),
|
||||
("file.saveCopy", json!({"format": "ai"})),
|
||||
("file.print", json!({})),
|
||||
] {
|
||||
let v = s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
|
||||
assert_eq!(warnings(&v).iter().filter(|w| *w == NOTE).count(), 1, "{cmd} {p}: {}", v["warnings"]);
|
||||
assert_eq!(drawn(&b64(&v)), [false], "{cmd} {p}");
|
||||
}
|
||||
// The .ai file reopens with the image as it was placed, from the image bytes in its editing data.
|
||||
let ai = b64(&s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap());
|
||||
let placed = s.doc().unwrap().doc.images.clone();
|
||||
s.execute("document.open", &json!({"name": "cut.ai", "dataBase64": vectorcraft_format::base64_encode(&ai)})).unwrap();
|
||||
let reopened = &s.doc().unwrap().doc;
|
||||
assert!(reopened.node(cut).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_))));
|
||||
assert_eq!(reopened.images, placed);
|
||||
// Export for Screens, a native file carrying a PDF, and the PDF that Copy offers are written.
|
||||
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "pdf"}]})).unwrap();
|
||||
assert_eq!(drawn(&b64(&r["files"][0])), [false]);
|
||||
assert!(s.execute("file.saveCopy", &json!({"format": "vectorcraft", "pdfCompatible": true})).is_ok());
|
||||
s.execute("select.set", &json!({"ids": [cut.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
assert!(b64(&s.execute("clipboard.exportPdf", &json!({})).unwrap()).starts_with(b"%PDF"));
|
||||
s.execute("prefs.set", &json!({"key": "copyAsPdf", "value": true})).unwrap();
|
||||
assert!(s.clipboard_flavours().iter().any(|f| f.mime == crate::cmd::clipboard::PDF));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_pdf_writes_a_path() {
|
||||
let mut s = session(2);
|
||||
|
||||
@@ -69,6 +69,33 @@ fn pages_changed_elsewhere_open_as_artwork_with_a_warning() {
|
||||
assert_eq!(r["warnings"][0], load::EDITING_DAMAGED, "{r}");
|
||||
}
|
||||
|
||||
/// `pdf` with its editing file's description rewritten by another app in UTF-16BE with a byte
|
||||
/// order mark: "hash " and the hash it held, padded with spaces to its length.
|
||||
fn utf16_described(pdf: &[u8]) -> Vec<u8> {
|
||||
let from = b"(VectorCraft editing data; page hash ";
|
||||
let at = pdf.windows(from.len()).position(|w| w == from).unwrap_or_else(|| panic!("no description"));
|
||||
let (hash, len) = (&pdf[at + from.len()..at + from.len() + 16], from.len() + 17);
|
||||
let mut desc = b"(\xFE\xFF".to_vec();
|
||||
desc.extend(b"hash ".iter().chain(hash).flat_map(|&c| [0, c]));
|
||||
desc.push(b')');
|
||||
desc.resize(len, b' ');
|
||||
patched(pdf, &pdf[at..at + len], &desc)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_changed_elsewhere_are_noticed_with_a_utf16_description() {
|
||||
let mut s = rich();
|
||||
let pdf = b64(&s.execute("document.exportPdf", &json!({"compression": {"compressText": false}})).unwrap());
|
||||
let ai = b64(&s.execute("document.export", &json!({"format": "ai", "compress": false})).unwrap());
|
||||
for (name, file) in [("edited.pdf", pdf), ("edited.ai", ai)] {
|
||||
let r = open(&mut s, name, &utf16_described(&file));
|
||||
assert_eq!((&r["warnings"], &r["restored"]), (&json!([]), &json!(true)), "{name}: the same pages: {r}");
|
||||
let edited = patched(&file, b"/MediaBox[0 0 300 200]", b"/MediaBox[0 0 300 201]");
|
||||
let r = open(&mut s, name, &utf16_described(&edited));
|
||||
assert_eq!((&r["warnings"][0], &r["restored"]), (&json!(load::EDITING_STALE), &json!(false)), "{name}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_legacy_payload_name_is_accepted() {
|
||||
let mut s = rich();
|
||||
@@ -232,6 +259,52 @@ fn save_as_template_names_its_file_after_the_template_format() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports don't write a `.ait`: each export asked for one, by its path or `format`, answers an
|
||||
/// error that names `file.saveAsTemplate`, which writes it, and writes nothing. A format that
|
||||
/// nothing writes keeps its own error.
|
||||
#[test]
|
||||
fn exports_of_an_ait_name_save_as_template() {
|
||||
let mut s = rich();
|
||||
let path = tmp("exported.ait");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
for (cmd, p) in [
|
||||
("document.export", json!({"path": path})),
|
||||
("document.export", json!({"format": "ait"})),
|
||||
("document.serialize", json!({"format": "ait"})),
|
||||
("document.exportSelection", json!({"path": path})),
|
||||
("document.exportForScreens", json!({"formats": [{"format": "ait"}]})),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("PDF-compatible .ait template files are written by file.saveAsTemplate"), "{cmd} {p}: {e}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&path).exists(), "nothing written");
|
||||
assert_eq!(writable_format(Some("ps"), None).unwrap_err(), "PostScript files can be opened but not written (see document.formats)");
|
||||
}
|
||||
|
||||
/// Save as Template refuses `aiVersion` 7 for a `.ait`, given in `options` or flat, and writes no
|
||||
/// file; `aiVersion` "pdf" writes the PDF-compatible template.
|
||||
#[test]
|
||||
fn save_as_template_refuses_a_legacy_ait() {
|
||||
let mut s = rich();
|
||||
let path = tmp("legacy-ait/card.ait");
|
||||
let dir = std::path::Path::new(&path).parent().unwrap().to_path_buf();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for p in [
|
||||
json!({"path": path, "options": {"aiVersion": "7"}}),
|
||||
json!({"path": path, "format": "ait", "aiVersion": 7}),
|
||||
json!({"format": "ait", "options": {"aiVersion": "7"}}),
|
||||
] {
|
||||
let e = s.execute("file.saveAsTemplate", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("aiVersion 7 writes legacy .ai files"), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing written");
|
||||
let r = s.execute("file.saveAsTemplate", &json!({"path": path, "options": {"aiVersion": "pdf"}})).unwrap();
|
||||
assert_eq!(r["format"], "ait", "{r}");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert!(bytes.starts_with(b"%PDF") && vectorcraft_pdf::editing(&bytes).is_some_and(|e| e.intact), "PDF-compatible, carrying the document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standards_and_screens_leave_the_editing_data_out() {
|
||||
let mut s = rich();
|
||||
|
||||
@@ -38,6 +38,64 @@ fn text_opens_as_type_or_outlines() {
|
||||
assert!(e.contains("textAs must be one of text, outlines"), "{e}");
|
||||
}
|
||||
|
||||
fn live_text_pdf() -> Vec<u8> {
|
||||
let page = |text: &str| PdfPage {
|
||||
resources: "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>".into(),
|
||||
..PdfPage::new(200.0, 100.0, &format!("BT /F1 12 Tf 10 50 Td ({text}) Tj ET"))
|
||||
};
|
||||
pdf(&[page("First page"), page("Second page")], None)
|
||||
}
|
||||
|
||||
fn live_texts(s: &Session) -> Vec<String> {
|
||||
let mut texts = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
texts.push(t.plain_text());
|
||||
}
|
||||
});
|
||||
texts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() {
|
||||
let bytes = live_text_pdf();
|
||||
let dir = vectorcraft_testkit::temp_dir("pdf-place-live-text");
|
||||
let path = dir.join("text.pdf");
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
for source in [json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)}), json!({"path": path, "link": false})] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let mut p = source;
|
||||
p["page"] = json!(2);
|
||||
let r = s.execute("file.place", &p).unwrap();
|
||||
assert_eq!(live_texts(&s), ["Second page"], "{r}");
|
||||
assert!(!r["warnings"].to_string().contains("outlines"), "{r}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_clipboard_paste_keeps_live_text_on_the_selected_page() {
|
||||
let bytes = live_text_pdf();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let r = s.execute("clipboard.importPdf", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "page": 2})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(live_texts(&s), ["Second page"], "{r}");
|
||||
assert!(!r["warnings"].to_string().contains("outlines"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_place_honors_explicit_text_outlines() {
|
||||
let bytes = live_text_pdf();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let r =
|
||||
s.execute("file.place", &json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes), "textAs": "outlines"})).unwrap();
|
||||
assert!(live_texts(&s).is_empty());
|
||||
assert!(r["warnings"].to_string().contains("outlines"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_option_keeps_or_flattens_optional_content() {
|
||||
let (a, b) = (first_extra(1), first_extra(1) + 1);
|
||||
@@ -59,6 +117,23 @@ fn layers_option_keeps_or_flattens_optional_content() {
|
||||
assert!(open(&mut s, &bytes, json!({"layers": "no"})).unwrap_err().to_string().contains("layers must be true or false"));
|
||||
}
|
||||
|
||||
/// A PDF-compatible `.ai` without the editor's private data opens its layers from its optional
|
||||
/// content groups, whose names without a byte order mark are PDFDocEncoding.
|
||||
#[test]
|
||||
fn ai_layer_names_are_read_as_pdf_doc_encoding() {
|
||||
let (a, b) = (first_extra(1), first_extra(1) + 1);
|
||||
let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << >> >> ");
|
||||
let page = PdfPage {
|
||||
resources: format!("/Properties << /A {a} 0 R /B {b} 0 R >>"),
|
||||
..PdfPage::new(100.0, 100.0, "/OC /A BDC 0 g 0 0 10 10 re f EMC /OC /B BDC 0 g 20 20 10 10 re f EMC")
|
||||
};
|
||||
let bytes = pdf_with_catalog(&[page], &[r"<< /Type /OCG /Name (Art\205final) >>", "<< /Type /OCG /Name (Notes) >>"], &catalog, None);
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "art.ai", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
let names: Vec<String> = s.active().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Art\u{2013}final", "Notes"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_options_read_text_and_layers() {
|
||||
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false})).unwrap();
|
||||
|
||||
@@ -157,27 +157,31 @@ fn a_postscript_ai_file_says_it_cannot_be_opened_yet() {
|
||||
let e = s.execute("document.open", &json!({"name": name, "dataBase64": b64(ps)})).unwrap_err().to_string();
|
||||
assert!(e.contains(name) && e.contains("PostScript") && e.contains("save it as PDF"), "{name}: {e}");
|
||||
}
|
||||
// An EPS with a binary header too, and the PDF info of either.
|
||||
// An EPS with a binary header too, and the PDF info of each. The plain program's PDF info gives
|
||||
// its page, and its thumbnail gives the reader's error; the binary file's header points at no
|
||||
// PostScript, so its PDF info is an error.
|
||||
let mut binary = vec![0xC5, 0xD0, 0xD3, 0xC6];
|
||||
binary.extend_from_slice(&[0; 28]);
|
||||
binary.extend_from_slice(ps);
|
||||
assert!(s.execute("document.open", &json!({"name": "x.eps", "dataBase64": b64(&binary)})).unwrap_err().to_string().contains("PostScript"));
|
||||
assert!(s.execute("document.pdfInfo", &json!({"dataBase64": b64(ps)})).unwrap_err().to_string().contains("PostScript"));
|
||||
assert!(s.execute("document.pdfInfo", &json!({"dataBase64": b64(&binary)})).unwrap_err().to_string().contains("PostScript"));
|
||||
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(ps)})).unwrap();
|
||||
assert_eq!((v["pages"].as_u64(), v["pageInfo"][0]["width"].as_f64()), (Some(1), Some(100.0)), "{v}");
|
||||
let e = s.execute("document.pdfInfo", &json!({"dataBase64": b64(ps), "thumbnail": 1})).unwrap_err().to_string();
|
||||
assert!(e.contains("PostScript") && e.contains("frobnicate"), "{e}");
|
||||
assert!(s.active().is_none());
|
||||
}
|
||||
|
||||
/// PostScript given where a PDF is read (`document.pdfInfo`, `clipboard.importPdf`) is refused
|
||||
/// with an error that names File › Open and File › Place, and both of those read the file.
|
||||
/// PostScript given where a PDF is read (`clipboard.importPdf`) is refused with an error that
|
||||
/// names File › Open and File › Place, and both of those read the file.
|
||||
#[test]
|
||||
fn postscript_read_as_a_pdf_names_open_and_place() {
|
||||
let ps = b"%!PS-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n1 0 0 setrgbcolor 10 10 50 50 rectfill\nshowpage\n%%EOF\n";
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
for cmd in ["document.pdfInfo", "clipboard.importPdf"] {
|
||||
let e = s.execute(cmd, &json!({"dataBase64": b64(ps)})).unwrap_err().to_string();
|
||||
assert!(e.contains("PostScript") && e.contains("not a PDF: File › Open and File › Place read it as EPS"), "{cmd}: {e}");
|
||||
assert!(!e.contains("can't be opened"), "{cmd}: {e}");
|
||||
}
|
||||
let e = s.execute("clipboard.importPdf", &json!({"dataBase64": b64(ps)})).unwrap_err().to_string();
|
||||
assert!(e.contains("PostScript") && e.contains("not a PDF: File › Open and File › Place read it as EPS"), "{e}");
|
||||
assert!(!e.contains("can't be opened"), "{e}");
|
||||
for name in ["legacy.ai", "art.eps"] {
|
||||
let r = s.execute("document.open", &json!({"name": name, "dataBase64": b64(ps)})).unwrap();
|
||||
assert_eq!(r["warnings"], json!([]), "{name}: {r}");
|
||||
@@ -186,6 +190,65 @@ fn postscript_read_as_a_pdf_names_open_and_place() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `document.pdfInfo` reads PostScript (an EPS, a `.ai` in PostScript form, a `.ps` file) as one
|
||||
/// page, its bounding box or a letter page without one, and its thumbnail shows that page. Each
|
||||
/// file here opens on that page with `editingData: false`.
|
||||
#[test]
|
||||
fn pdf_info_reads_postscript_as_one_page() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
let data = |r: Value| vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let eps = data(s.execute("document.exportEps", &json!({"useArtboards": true})).unwrap());
|
||||
let ai = data(s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7"})).unwrap());
|
||||
assert!(eps.starts_with(&[0xC5, 0xD0, 0xD3, 0xC6]) && ai.starts_with(b"%!PS"));
|
||||
let hires = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 101 41\n%%HiResBoundingBox: 0 0 100.5 40.25\n%%EndComments\n0 0 1 setrgbcolor 0 0 50 20 rectfill\n";
|
||||
let letter = b"%!PS\n1 0 0 setrgbcolor 72 72 144 72 rectfill\nshowpage\n";
|
||||
let bare = b"%!\n0 0 1 setrgbcolor 100 100 50 50 rectfill\nshowpage\n";
|
||||
for (name, bytes, size) in [
|
||||
("art.eps", &eps[..], (300.0, 200.0)),
|
||||
("legacy.ai", &ai, (101.0, 51.0)),
|
||||
("hires.eps", hires, (100.5, 40.25)),
|
||||
("page.ps", letter, (612.0, 792.0)),
|
||||
("bare.ps", bare, (612.0, 792.0)),
|
||||
] {
|
||||
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 100})).unwrap();
|
||||
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
|
||||
let img = image::load_from_memory(&png).unwrap();
|
||||
assert_eq!(img.width().max(img.height()), 100, "{name}");
|
||||
let mut v = v;
|
||||
v["thumbnail"] = json!("png");
|
||||
let page = json!({"width": size.0, "height": size.1, "rotation": 0, "boxes": {}});
|
||||
assert_eq!(v, json!({"pages": 1, "needsPassword": false, "pageInfo": [page], "thumbnail": "png"}), "{name}");
|
||||
s.execute("document.open", &json!({"name": name, "dataBase64": b64(bytes), "editingData": false})).unwrap();
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert_eq!((board.width(), board.height()), size, "{name}: the page document.open reads");
|
||||
}
|
||||
let e = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&eps), "thumbnail": 2})).unwrap_err().to_string();
|
||||
assert!(e.contains("no page 2"), "{e}");
|
||||
}
|
||||
|
||||
/// `document.pdfInfo`'s `thumbnail` is a page number from 1, for a PDF and for PostScript alike:
|
||||
/// any other value is an error that names the pages, and an absent or null one gives no thumbnail.
|
||||
#[test]
|
||||
fn pdf_info_refuses_a_thumbnail_that_is_not_a_page_number() {
|
||||
let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor 0 0 50 20 rectfill\n";
|
||||
let mut s = Session::new();
|
||||
for (bytes, pages) in [(&three_pages()[..], "(the PDF has 3)"), (ps, "(the file has 1)")] {
|
||||
for n in [json!(-1), json!(0), json!(1.5), json!("1"), json!(true)] {
|
||||
let e = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": n})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("thumbnail: no page {n} {pages}")), "{n}: {e}");
|
||||
}
|
||||
for none in [json!({"dataBase64": b64(bytes)}), json!({"dataBase64": b64(bytes), "thumbnail": null})] {
|
||||
assert!(s.execute("document.pdfInfo", &none).unwrap().get("thumbnail").is_none(), "{pages}");
|
||||
}
|
||||
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 64})).unwrap();
|
||||
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
|
||||
let img = image::load_from_memory(&png).unwrap();
|
||||
assert_eq!(img.width().max(img.height()), 64, "{pages}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A page showing only text, with an editor's private data when `private`.
|
||||
fn text_page(private: bool, also: &str) -> PdfPage {
|
||||
PdfPage {
|
||||
|
||||
@@ -89,3 +89,51 @@ fn choosing_a_pdfx_standard_sets_its_version_and_turns_off_what_it_forbids() {
|
||||
assert!(s.execute("document.exportPdf", &json!({"preset": preset})).is_ok(), "{preset}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there).
|
||||
fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> {
|
||||
fn visit(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::ImageObject>) {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
out.push((**im).clone());
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, out);
|
||||
}
|
||||
}
|
||||
let mut images = vec![];
|
||||
for l in &doc.layers {
|
||||
visit(l, &mut images);
|
||||
}
|
||||
images.iter().rev().find_map(|im| {
|
||||
let q = im.xf.inverse() * p;
|
||||
if q.x < 0.0 || q.y < 0.0 || q.x >= im.width as f64 || q.y >= im.height as f64 {
|
||||
return None;
|
||||
}
|
||||
let ink = doc.images.get(&im.key)?.sample_cmyk_object(q.x, q.y, (im.width, im.height), 1)?;
|
||||
Some(ink.map(|v| v as f32 / 255.0))
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdfx_1a_flattening_keeps_the_inks_behind_an_image_in_a_cmyk_document() {
|
||||
// #2160: a CMYK panel under a PNG with see-through pixels. The flattener rasterizes where the
|
||||
// image reaches; the panel there keeps its ink numbers instead of going through RGB.
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 80})).unwrap();
|
||||
let teal = [1.0, 0.06, 0.41, 0.03];
|
||||
s.execute("paint.setFill", &json!({"color": {"c": teal[0], "m": teal[1], "y": teal[2], "k": teal[3]}})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([0, 120, 255, if x < 20 { 0 } else { 255 }]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
s.execute("file.place", &json!({"name": "logos.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 50]})).unwrap();
|
||||
let v = s.execute("document.exportPdf", &json!({"standard": "pdfX1a"})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let back = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
// Behind the image's see-through half: the panel's own inks, K included.
|
||||
let ink = image_inks_at(&back, vectorcraft_geom::Point::new(88.0, 50.0)).expect("a CMYK image behind the see-through pixels");
|
||||
assert!(ink.iter().zip(teal).all(|(a, b)| (a - b).abs() <= 1.5 / 255.0), "{ink:?} is not {teal:?}");
|
||||
}
|
||||
@@ -248,6 +248,7 @@ fn a_raster_export_says_nothing_of_images_another_thread_could_not_decode() {
|
||||
xf: vectorcraft_geom::Affine::scale(20.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let (id, layer) = (broken.alloc_id(), broken.layers[0].id);
|
||||
broken.insert(Some(layer), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Export for Screens: sizes (factor, width, height, resolution), presets and sub-folders, Full
|
||||
//! Document, Include Bleed, per-format settings, ZIP downloads and the settings the document keeps.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::screens::ScreenSize;
|
||||
@@ -146,6 +148,96 @@ fn device_names_and_trailing_periods_follow_windows_naming_rules() {
|
||||
assert_eq!(r["name"], "nul-.zip");
|
||||
}
|
||||
|
||||
/// `first_file` names the file the export writes first, for the same params: the item's file name,
|
||||
/// a prefix and a suffix with characters Windows does not allow, a range, a Windows device name,
|
||||
/// every kind of folder, presets, size suffixes, a name pattern with its counter and date, an
|
||||
/// export preset, a ZIP, Full Document, Include Bleed, assets, layers and the selection; and it
|
||||
/// refuses what the export refuses.
|
||||
#[test]
|
||||
fn the_first_file_is_the_file_the_export_writes_first() {
|
||||
let mut s = session(3);
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "name": "CON"})).unwrap();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id.0;
|
||||
let square = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0;
|
||||
let asset = s.execute("assets.add", &json!({"ids": [square], "name": "Logo?"})).unwrap()["assets"][0].as_u64().unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let written = |r: &Value| r["files"][0].as_str().or_else(|| r["files"][0]["name"].as_str()).unwrap_or_default().to_string();
|
||||
let cases = [
|
||||
json!({}),
|
||||
json!({"prefix": "a?b/", "formats": [{"format": "png", "suffix": "<x>"}]}),
|
||||
json!({"range": "2-3", "folders": "item"}),
|
||||
json!({"range": "2", "folders": "itemFormat", "formats": [{"format": "svg", "scale": "2x", "suffix": "@2x"}]}),
|
||||
json!({"preset": "mobile"}),
|
||||
json!({"preset": "density"}),
|
||||
json!({"subfolders": true, "formats": [{"format": "png", "scale": "144ppi", "folder": "a b"}]}),
|
||||
json!({"folders": "format", "formats": [{"format": "jpg", "quality": 50}]}),
|
||||
json!({
|
||||
"name": "<filename>-<name>-<scale>-<index>-###-YYYYMMDD",
|
||||
"counterStart": 7,
|
||||
"counterPer": "file",
|
||||
"date": "2026-10-17",
|
||||
"formats": [{"format": "png", "scale": "2x"}]
|
||||
}),
|
||||
json!({"name": "<suffix>", "formats": [{"format": "png", "suffix": ""}]}),
|
||||
json!({"exportPreset": "Logo Package"}),
|
||||
json!({"zip": true, "formats": [{"format": "svg"}, {"format": "png"}]}),
|
||||
json!({"fullDocument": true, "folders": "item", "formats": [{"format": "pdf"}]}),
|
||||
json!({"fullDocument": true, "formats": [{"format": "png"}]}),
|
||||
json!({"includeBleed": true}),
|
||||
json!({"assets": [asset], "formats": [{"format": "svg"}]}),
|
||||
json!({"layers": [layer], "folders": "item"}),
|
||||
json!({"selection": "one"}),
|
||||
json!({"selection": "each", "name": "<name>"}),
|
||||
];
|
||||
for p in cases {
|
||||
let first = super::screens::first_file(&s, &p).unwrap();
|
||||
assert_eq!(first, written(&export(&mut s, p.clone())), "{p}");
|
||||
}
|
||||
for p in [json!({"layers": [layer], "assets": [asset]}), json!({"selection": "all"}), json!({"counterPer": "row"})] {
|
||||
assert!(super::screens::first_file(&s, &p).is_err() && s.execute("document.exportForScreens", &p).is_err(), "{p}");
|
||||
}
|
||||
// A document named after a Windows device.
|
||||
s.execute("file.new", &json!({"width": 40, "height": 30, "name": "nul"})).unwrap();
|
||||
for p in [json!({"fullDocument": true, "folders": "item", "formats": [{"format": "pdf"}]}), json!({"name": "<filename>"})] {
|
||||
let first = super::screens::first_file(&s, &p).unwrap();
|
||||
assert_eq!(first, written(&export(&mut s, p.clone())), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved document's `<filename>`, Full Document file and ZIP are named after its file without the
|
||||
/// extension, as Save names it, whatever its File Info title says.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_saved_document_exports_under_its_file_name() {
|
||||
let mut s = session(1);
|
||||
s.execute("file.info", &json!({"title": "Logo: final version"})).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("vc-screens-filename-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
s.execute("document.save", &json!({"path": dir.join("my-logo.vectorcraft").to_string_lossy()})).unwrap();
|
||||
for (p, name) in [
|
||||
(json!({"name": "<filename>__<name>", "formats": [{"format": "png"}]}), "my-logo__Artboard 1.png"),
|
||||
(json!({"fullDocument": true, "formats": [{"format": "png"}]}), "my-logo.png"),
|
||||
] {
|
||||
assert_eq!(names(&export(&mut s, p.clone())), [name], "{p}");
|
||||
assert_eq!(super::screens::first_file(&s, &p).unwrap(), name, "{p}");
|
||||
}
|
||||
assert_eq!(export(&mut s, json!({"zip": true, "formats": [{"format": "svg"}]}))["name"], "my-logo.zip");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A document that has not been saved has no file: `<filename>` is its title.
|
||||
#[test]
|
||||
fn an_unsaved_document_exports_under_its_title() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 40, "height": 30, "name": "Poster"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("file.info", &json!({"title": "Spring poster"})).unwrap();
|
||||
let p = json!({"name": "<filename>", "formats": [{"format": "png"}]});
|
||||
assert_eq!(names(&export(&mut s, p.clone())), ["Spring-poster.png"]);
|
||||
assert_eq!(super::screens::first_file(&s, &p).unwrap(), "Spring-poster.png");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn sub_folders_are_made_in_the_export_folder() {
|
||||
@@ -200,6 +292,169 @@ fn a_zip_is_written_into_the_folder() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The reply of a prepared export's [`super::ScreenExport::write`] and the files it gave the
|
||||
/// writer, by path.
|
||||
fn write_prepared(export: super::ScreenExport) -> (Value, BTreeMap<String, Vec<u8>>) {
|
||||
let mut files = BTreeMap::new();
|
||||
let mut write = |path: &str, bytes: &[u8]| {
|
||||
files.insert(path.to_string(), bytes.to_vec());
|
||||
Ok(())
|
||||
};
|
||||
let r = export.write(&mut write).unwrap_or_else(|e| panic!("{e}"));
|
||||
(r, files)
|
||||
}
|
||||
|
||||
/// The files reply `r` names (its `files`, else the zip at its `path`) as they are on disk, by path.
|
||||
fn on_disk(r: &Value) -> BTreeMap<String, Vec<u8>> {
|
||||
let paths: Vec<&str> = match r["path"].as_str() {
|
||||
Some(zip) => vec![zip],
|
||||
None => r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(),
|
||||
};
|
||||
paths.into_iter().map(|p| (p.to_string(), std::fs::read(p).unwrap())).collect()
|
||||
}
|
||||
|
||||
/// [`Session::prepare_screen_export`] runs `document.exportForScreens` and `assets.export` as
|
||||
/// commands, journaled, and writes nothing; the export it gives writes the files the command
|
||||
/// writes, with the same names (`-2` included), sub-folders, bytes and reply, into a folder, as a
|
||||
/// zip in it and without a folder, through the writer it is given. Export for Screens remembers
|
||||
/// its settings when it is prepared.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_prepared_export_writes_what_the_command_writes() {
|
||||
let mut s = session(2);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "name": "Icon"})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "name": "icon"})).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("vc-screens-prepared-{}", std::process::id()));
|
||||
let folder = dir.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
|
||||
let rows = json!([{"format": "png", "suffix": ""}, {"format": "png", "scale": "2x"}, {"format": "svg"}]);
|
||||
for zip in [false, true] {
|
||||
let p = json!({"folder": folder, "zip": zip, "folders": "rows", "name": "<name>", "formats": rows});
|
||||
let want = export(&mut s, p.clone());
|
||||
if !zip {
|
||||
let names = ["1x/Icon.png", "2x/Icon@2x.png", "SVG/Icon.svg", "1x/icon-2.png", "2x/icon@2x-2.png", "SVG/icon-2.svg"];
|
||||
assert_eq!(want["files"], json!(names.map(|n| format!("{folder}/{n}"))));
|
||||
}
|
||||
let disk = on_disk(&want);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let journaled = s.journal.len();
|
||||
let prepared = s.prepare_screen_export("document.exportForScreens", &p).unwrap();
|
||||
assert_eq!((s.journal.len(), s.journal.last().map(|(id, _)| id.as_str())), (journaled + 1, Some("document.exportForScreens")));
|
||||
assert!(!dir.exists(), "nothing is written until the export writes");
|
||||
let (got, files) = write_prepared(prepared);
|
||||
assert_eq!(got, want, "zip: {zip}");
|
||||
assert_eq!(files, disk, "zip: {zip}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
// Without a folder, the files come back in the reply and nothing is written.
|
||||
let p = json!({"name": "<name>", "formats": rows});
|
||||
let want = export(&mut s, p.clone());
|
||||
let (got, files) = write_prepared(s.prepare_screen_export("document.exportForScreens", &p).unwrap());
|
||||
assert_eq!((got, files.len()), (want, 0));
|
||||
// The settings are remembered when the export is prepared.
|
||||
s.prepare_screen_export("document.exportForScreens", &json!({"prefix": "pre-", "formats": rows})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.export_settings.get("prefix"), Some(&json!("pre-")));
|
||||
// The Asset Export panel's export.
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("assets.add", &json!({"multiple": false})).unwrap();
|
||||
let p = json!({"folder": folder, "formats": rows});
|
||||
let want = s.execute("assets.export", &p).unwrap();
|
||||
let disk = on_disk(&want);
|
||||
assert_eq!(disk.len(), 3, "{want}");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let prepared = s.prepare_screen_export("assets.export", &p).unwrap();
|
||||
assert_eq!(s.journal.last().map(|(id, _)| id.as_str()), Some("assets.export"));
|
||||
assert_eq!(write_prepared(prepared), (want, disk));
|
||||
// An encoder's refusal names the command, as the command's own reply does.
|
||||
let p = json!({"folder": folder, "formats": [{"format": "bmp", "colorModel": "cmyk"}]});
|
||||
let want = s.execute("assets.export", &p).unwrap_err();
|
||||
let got = s.prepare_screen_export("assets.export", &p).unwrap().write(&mut |_: &str, _: &[u8]| Ok(())).unwrap_err();
|
||||
assert!(matches!(&got, crate::EngineError::BadParams { cmd, .. } if cmd == "assets.export"), "{got:?}");
|
||||
assert_eq!(got.to_string(), want.to_string());
|
||||
// The checks come first, as the command's do.
|
||||
let journaled = s.journal.len();
|
||||
assert!(s.prepare_screen_export("document.exportForScreens", &json!({"range": "9"})).is_err());
|
||||
assert_eq!(s.journal.len(), journaled);
|
||||
assert!(s.screens_hand_off.is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepared_export_holds_the_document_as_it_was() {
|
||||
let mut s = session(1);
|
||||
let p = json!({"formats": [{"format": "svg"}]});
|
||||
let want = export(&mut s, p.clone());
|
||||
let prepared = s.prepare_screen_export("document.exportForScreens", &p).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert_ne!(export(&mut s, p), want, "the edit changes the file");
|
||||
assert_eq!(write_prepared(prepared).0, want);
|
||||
}
|
||||
|
||||
/// Output All Blacks as Rich Black (Appearance of Black › Printing / Exporting) makes the RGB files
|
||||
/// draw a CMYK black as RGB black, prepared or not.
|
||||
#[test]
|
||||
fn rich_black_reaches_the_files() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 40, "height": 30, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 1}})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap();
|
||||
let p = json!({"formats": [{"format": "png"}]});
|
||||
let px = |r: &Value| image::load_from_memory(&files(r)[0].1).unwrap().to_rgba8().get_pixel(10, 10).0;
|
||||
let accurate = px(&export(&mut s, p.clone()));
|
||||
assert!(accurate[0] > 10, "accurate: dark grey, {accurate:?}");
|
||||
s.execute("prefs.set", &json!({"key": "blackOutput", "value": "rich"})).unwrap();
|
||||
assert_eq!(px(&export(&mut s, p.clone())), [0, 0, 0, 255]);
|
||||
let (prepared, _) = write_prepared(s.prepare_screen_export("document.exportForScreens", &p).unwrap());
|
||||
assert_eq!(px(&prepared), [0, 0, 0, 255]);
|
||||
}
|
||||
|
||||
/// A cancel stops a prepared export before its next file; the file written before it stays.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_canceled_export_stops_before_its_next_file() {
|
||||
let mut s = session(3);
|
||||
let dir = std::env::temp_dir().join(format!("vc-screens-cancel-{}", std::process::id()));
|
||||
let folder = dir.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
|
||||
let prepared = s.prepare_screen_export("document.exportForScreens", &json!({"folder": folder, "formats": [{"format": "svg"}]})).unwrap();
|
||||
let progress = super::progress::Progress::new();
|
||||
let mut written = vec![];
|
||||
let r = super::progress::scope(&progress, || {
|
||||
prepared.write(&mut |path: &str, _: &[u8]| {
|
||||
written.push(path.to_string());
|
||||
progress.cancel();
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(matches!(r, Err(crate::EngineError::Cancelled)), "{r:?}");
|
||||
assert_eq!(written, [format!("{folder}/Artboard-1.svg")]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A prepared export reports one progress step per file, and the raster encoders' artboard steps
|
||||
/// are not reported.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_prepared_export_counts_its_files() {
|
||||
let mut s = session(3);
|
||||
let dir = std::env::temp_dir().join(format!("vc-screens-steps-{}", std::process::id()));
|
||||
let folder = dir.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
|
||||
let rows = json!([{"format": "png"}, {"format": "png", "scale": "2x"}]);
|
||||
let prepared = s.prepare_screen_export("document.exportForScreens", &json!({"folder": folder, "formats": rows})).unwrap();
|
||||
let progress = super::progress::Progress::of_files();
|
||||
let mut seen = vec![];
|
||||
let r = super::progress::scope(&progress, || {
|
||||
prepared.write(&mut |_: &str, _: &[u8]| {
|
||||
seen.push(progress.counts());
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(r.is_ok(), "{r:?}");
|
||||
assert_eq!(seen, (0..6).map(|n| (n, 6)).collect::<Vec<_>>());
|
||||
assert!(progress.counts_files());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The warnings in `r` that contain `text`.
|
||||
fn warned<'a>(r: &'a Value, text: &str) -> Vec<&'a str> {
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains(text)).collect()
|
||||
|
||||
@@ -145,6 +145,65 @@ fn preserve_editing_reopens_the_native_document() {
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_several_artboards_as_plain_svg_warns_they_are_lost() {
|
||||
let artboards = |r: &Value| r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().contains("artboards")).count();
|
||||
let mut s = session(3);
|
||||
let r = s.execute("document.save", &json!({"format": "svg"})).unwrap();
|
||||
assert_eq!(artboards(&r), 1, "{r}");
|
||||
// First: the status bar shows only the first warning.
|
||||
assert!(r["warnings"][0].as_str().unwrap().contains("1 of the document's 3 artboards"), "{r}");
|
||||
assert_eq!(artboards(&s.execute("file.saveAs", &json!({"format": "svgz"})).unwrap()), 1);
|
||||
// Preserve Editing keeps them all (they reopen); a single artboard loses none.
|
||||
for p in [json!({"format": "svg", "preserveEditing": true}), json!({"format": "svg", "svg": {"preserveEditing": true}})] {
|
||||
let r = s.execute("document.save", &p).unwrap();
|
||||
assert_eq!(artboards(&r), 0, "{p}: {r}");
|
||||
}
|
||||
assert_eq!(artboards(&session(1).execute("document.save", &json!({"format": "svg"})).unwrap()), 0);
|
||||
}
|
||||
|
||||
/// #3867: a Preserve Editing SVG opened from disk and saved with plain Save keeps the full
|
||||
/// document (every artboard), not just the artwork of the first.
|
||||
#[test]
|
||||
fn reopened_preserve_editing_svg_saves_as_the_full_document() {
|
||||
let dir = tmp_dir("reopen");
|
||||
let path = dir.join("keep.svg").to_string_lossy().to_string();
|
||||
session(3).execute("document.save", &json!({"path": path, "svg": {"preserveEditing": true}})).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 3);
|
||||
s.execute("document.save", &json!({})).unwrap();
|
||||
let mut t = Session::new();
|
||||
let r = t.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(r["restored"], json!(true), "{r}");
|
||||
assert_eq!(t.doc().unwrap().doc.artboards.len(), 3, "every artboard survives open and Save");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// #3869: small capitals, superscript and subscript, and tab leaders, which SVG text can't draw,
|
||||
/// are written as outlines (as vertical type and ruby are) rather than as plain text at full size;
|
||||
/// type without them stays text.
|
||||
#[test]
|
||||
fn type_svg_text_cant_draw_is_written_as_outlines() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 500, "height": 200})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 50, "y": 100, "text": "Small caps x2 H2O", "size": 30})).unwrap();
|
||||
let plain = svg(&mut s, json!({}));
|
||||
assert!(plain.contains("<text"), "plain type stays text: {plain}");
|
||||
for style in [json!({"smallCaps": true}), json!({"position": "superscript"}), json!({"position": "subscript"})] {
|
||||
let mut t = Session::new();
|
||||
t.execute("file.new", &json!({"width": 500, "height": 200})).unwrap();
|
||||
let id = t.execute("text.create", &json!({"x": 50, "y": 100, "text": "Small caps x2 H2O", "size": 30})).unwrap()["id"].clone();
|
||||
let mut p = style.clone();
|
||||
p["id"] = id;
|
||||
p["start"] = json!(0);
|
||||
p["end"] = json!(5);
|
||||
t.execute("text.setRangeStyle", &p).unwrap();
|
||||
let out = svg(&mut t, json!({}));
|
||||
assert!(!out.contains("<text") && out.contains("<path"), "{style}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_writes_svg_and_remembers_its_options() {
|
||||
let mut s = session(1);
|
||||
|
||||
@@ -108,3 +108,39 @@ fn a_chosen_artboard_s_svg_keeps_an_object_whose_shadow_reaches_it() {
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id], "params": {"x": 20, "y": 0, "blur": 0}})).unwrap();
|
||||
assert_eq!(paths(&mut s), 1, "its shadow reaches 10 pt onto the artboard");
|
||||
}
|
||||
|
||||
/// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset)
|
||||
/// has the artboard's (or asset's) name as `<title>`; Save's SVG and Export for Screens' Full
|
||||
/// Document keep the document's.
|
||||
#[test]
|
||||
fn an_svg_of_one_artboard_is_titled_after_it() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"name": "Icons", "width": 24, "height": 24, "artboards": 2})).unwrap();
|
||||
for (index, name) in [(0, "arrow-left"), (1, "arrow-right")] {
|
||||
s.execute("artboard.setProps", &json!({"index": index, "name": name})).unwrap();
|
||||
}
|
||||
let square = s.execute("shape.rectangle", &json!({"x": 4, "y": 4, "width": 16, "height": 16})).unwrap()["id"].clone();
|
||||
let title = |svg: &str| svg.lines().find_map(|l| l.trim().strip_prefix("<title>")?.strip_suffix("</title>")).map(str::to_string);
|
||||
let serialize = |s: &mut Session, p: serde_json::Value| s.execute("document.serialize", &p).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert_eq!(title(&serialize(&mut s, json!({"format": "svg", "artboard": 1}))).as_deref(), Some("arrow-right"));
|
||||
assert_eq!(title(&serialize(&mut s, json!({"format": "svg", "artboard": 0}))).as_deref(), Some("arrow-left"));
|
||||
assert_eq!(title(&serialize(&mut s, json!({"format": "svg"}))).as_deref(), Some("Icons"), "Save's SVG");
|
||||
let all = s.execute("document.serialize", &json!({"format": "svg", "useArtboards": true, "range": "all"})).unwrap();
|
||||
let titles: Vec<_> = all["files"].as_array().unwrap().iter().map(|f| title(f["text"].as_str().unwrap())).collect();
|
||||
assert_eq!(titles, [Some("arrow-left".into()), Some("arrow-right".into())]);
|
||||
// Export for Screens: each artboard, an asset, and the Full Document.
|
||||
let screens = |s: &mut Session, p: serde_json::Value| -> Vec<Option<String>> {
|
||||
let r = s.execute("document.exportForScreens", &p).unwrap();
|
||||
r["files"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|f| title(&String::from_utf8(vectorcraft_format::base64_decode(f["dataBase64"].as_str().unwrap()).unwrap()).unwrap()))
|
||||
.collect()
|
||||
};
|
||||
let svg = json!([{"format": "svg"}]);
|
||||
assert_eq!(screens(&mut s, json!({"formats": svg})), [Some("arrow-left".into()), Some("arrow-right".into())]);
|
||||
let asset = s.execute("assets.add", &json!({"ids": [square], "name": "Square"})).unwrap()["assets"][0].clone();
|
||||
assert_eq!(screens(&mut s, json!({"assets": [asset], "formats": svg})), [Some("Square".into())]);
|
||||
assert_eq!(screens(&mut s, json!({"fullDocument": true, "formats": svg})), [Some("Icons".into())]);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! TIFF, BMP and Targa export through `document.export`: the options reach the files, impossible
|
||||
//! ones are refused, and the files open again.
|
||||
//! ones are refused, and the files open again; Targa files open and place.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -135,6 +135,152 @@ fn targa_depth_reaches_the_file() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGBA pixels of the image `document.open` or `file.place` stored for the first object of the
|
||||
/// active document's first layer.
|
||||
fn stored_pixels(s: &Session) -> image::RgbaImage {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let im = match &doc.layers[0].children().unwrap()[0].kind {
|
||||
vectorcraft_doc::NodeKind::Image(im) => im.clone(),
|
||||
other => panic!("expected an image, got {other:?}"),
|
||||
};
|
||||
image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8()
|
||||
}
|
||||
|
||||
/// A Targa header: no image id or color map, image type `kind`, `w` × `h` pixels of `depth` bits,
|
||||
/// image descriptor `descriptor`.
|
||||
fn targa_header(kind: u8, w: u16, h: u16, depth: u8, descriptor: u8) -> Vec<u8> {
|
||||
let mut f = vec![0, 0, kind, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
f.extend(w.to_le_bytes());
|
||||
f.extend(h.to_le_bytes());
|
||||
f.extend([depth, descriptor]);
|
||||
f
|
||||
}
|
||||
|
||||
/// Targa files open and place at their pixel size with the transparency they store, by any of the
|
||||
/// four Targa extensions; copied in a file manager they paste as a bitmap; the dialogs list them.
|
||||
#[test]
|
||||
fn targa_files_open_and_place() {
|
||||
use crate::cmd::clipboard::{PASTE_ORDER, file_flavour};
|
||||
let mut s = session();
|
||||
let b64 = vectorcraft_format::base64_encode;
|
||||
// VectorCraft's own exports: the transparent corner stays transparent at 16 and 32 bits (24
|
||||
// bits are flattened on white) and the black rectangle stays black.
|
||||
for depth in [16, 24, 32] {
|
||||
let tga = export(&mut s, json!({"format": "tga", "depth": depth}));
|
||||
let r = s.execute("document.open", &json!({"name": "art.tga", "dataBase64": b64(&tga)})).unwrap();
|
||||
assert_eq!((&r["format"], &r["warnings"]), (&json!("tga"), &json!([])), "{depth} bits: {r}");
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(60.0, 40.0));
|
||||
let px = stored_pixels(&s);
|
||||
assert_eq!(px.dimensions(), (60, 40));
|
||||
let corner = if depth == 24 { [255; 4] } else { [0, 0, 0, 0] };
|
||||
assert_eq!(px.get_pixel(5, 5).0[3], corner[3], "{depth} bits: the corner's alpha");
|
||||
if depth == 24 {
|
||||
assert_eq!(px.get_pixel(5, 5).0, corner, "flattened on white");
|
||||
}
|
||||
let black = px.get_pixel(40, 20).0;
|
||||
assert!(black[3] == 255 && black[..3].iter().all(|c| *c < 80), "{depth} bits: {black:?}");
|
||||
// The next export starts from the session's document again.
|
||||
s = session();
|
||||
}
|
||||
let tga = export(&mut s, json!({"format": "tga", "depth": 32}));
|
||||
for name in ["art.vda", "ART.ICB", "art.vst"] {
|
||||
let r = s.execute("document.open", &json!({"name": name, "dataBase64": b64(&tga)})).unwrap();
|
||||
assert_eq!(r["format"], "tga", "{name}: {r}");
|
||||
}
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "art.tga", "dataBase64": b64(&tga)})).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("tga"), Some(1)), "{r}");
|
||||
assert_eq!(stored_pixels(&s).get_pixel(5, 5).0[3], 0, "placed with its transparency");
|
||||
// Copied in a file manager, a Targa file pastes as a bitmap.
|
||||
assert_eq!(file_flavour("art.tga", &tga, &PASTE_ORDER), Some("image/x-tga"));
|
||||
let r = s.execute("clipboard.importImage", &json!({"mime": "image/x-tga", "dataBase64": b64(&tga)})).unwrap();
|
||||
assert_eq!((&r["count"], &r["pixelWidth"], &r["pixelHeight"]), (&json!(1), &json!(60), &json!(40)), "{r}");
|
||||
// The dialogs list the four extensions; the desktop packaging doesn't associate them.
|
||||
for e in ["tga", "vda", "icb", "vst"] {
|
||||
assert!(OPEN_EXTS.contains(&e) && PLACE_EXTS.contains(&e) && UNASSOCIATED_EXTS.contains(&e), "{e}");
|
||||
}
|
||||
let targa = ("Targa", &["tga", "vda", "icb", "vst"][..]);
|
||||
assert!(open_filters().any(|f| f == targa) && place_filters().any(|f| f == targa));
|
||||
}
|
||||
|
||||
/// Targa pixels in every layout: run-length encoded rows stored top down (as the `image` crate
|
||||
/// writes them), a 16-bit file whose one attribute bit per pixel is its alpha, with runs, stored
|
||||
/// right to left and top down, 32-bit files with no attribute bits (opaque), with eight, and with
|
||||
/// each Attributes Type in an extension area, and color-mapped files whose 16-bit entries carry the
|
||||
/// attribute bit.
|
||||
#[test]
|
||||
fn targa_layouts_and_alpha_read() {
|
||||
let src = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([x as u8 * 100, y as u8 * 200, 50, if x == 1 { 128 } else { 255 }]));
|
||||
let mut rle = Vec::new();
|
||||
src.write_to(&mut std::io::Cursor::new(&mut rle), image::ImageFormat::Tga).unwrap();
|
||||
assert_eq!((rle[2], rle[17] & 0x20), (10, 0x20), "run-length encoded true color, stored top down");
|
||||
assert_eq!(raster_image(&rle).map(|r| image::load_from_memory(&r.blob.bytes).unwrap().to_rgba8()).unwrap(), src);
|
||||
|
||||
// 3 × 2, 5-5-5 color and an attribute bit, right to left (bit 4), top down (bit 5): a raw
|
||||
// packet of red, blue and a clear pixel for the first row, then a run of green.
|
||||
let mut f = targa_header(10, 3, 2, 16, 0x31);
|
||||
f.push(0x02);
|
||||
f.extend([0xfc00u16, 0x801f, 0x0000].iter().flat_map(|v| v.to_le_bytes()));
|
||||
f.push(0x82);
|
||||
f.extend(0x83e0u16.to_le_bytes());
|
||||
let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8();
|
||||
let px = |x, y| img.get_pixel(x, y).0;
|
||||
assert_eq!((px(2, 0), px(1, 0), px(0, 0)[3]), ([255, 0, 0, 255], [0, 0, 255, 255], 0), "the first row, right to left");
|
||||
assert!((0..3).all(|x| px(x, 1) == [0, 255, 0, 255]), "the run");
|
||||
|
||||
// 2 × 1 at 32 bits with no attribute bits: the fourth byte isn't alpha, whatever it holds.
|
||||
for fourth in [[0, 0], [0, 255]] {
|
||||
let mut f = targa_header(2, 2, 1, 32, 0x20);
|
||||
f.extend([10, 20, 30, fourth[0], 40, 50, 60, fourth[1]]);
|
||||
let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8();
|
||||
assert_eq!((img.get_pixel(0, 0).0, img.get_pixel(1, 0).0), ([30, 20, 10, 255], [60, 50, 40, 255]), "{fourth:?}");
|
||||
}
|
||||
// The same with eight attribute bits: the fourth byte is alpha, also when it is 0 everywhere.
|
||||
let mut f = targa_header(2, 2, 1, 32, 0x28);
|
||||
f.extend([10, 20, 30, 0, 40, 50, 60, 0]);
|
||||
let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8();
|
||||
assert!(img.pixels().all(|p| p.0[3] == 0));
|
||||
// The extension area's Attributes Type: undefined data (1, 2) isn't alpha, premultiplied colors
|
||||
// (4) are divided by their alpha, and alpha (3) or 0, the field left unset, keeps it.
|
||||
for (kind, want) in [(0, [50, 50, 50, 128]), (1, [50, 50, 50, 255]), (2, [50, 50, 50, 255]), (3, [50, 50, 50, 128]), (4, [100, 100, 100, 128])] {
|
||||
let mut f = targa_header(2, 1, 1, 32, 0x28);
|
||||
f.extend([50, 50, 50, 128]);
|
||||
let mut area = vec![0; 495];
|
||||
area[..2].copy_from_slice(&495u16.to_le_bytes());
|
||||
area[494] = kind;
|
||||
let at = f.len() as u32;
|
||||
f.extend(area);
|
||||
f.extend(at.to_le_bytes());
|
||||
f.extend([0; 4]);
|
||||
f.extend(b"TRUEVISION-XFILE.\0");
|
||||
let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8();
|
||||
assert_eq!(img.get_pixel(0, 0).0, want, "Attributes Type {kind}");
|
||||
}
|
||||
|
||||
// Color-mapped, one attribute bit, top down: 16-bit entries 5 (clear black) and 6 (red), as a
|
||||
// raw row of 8-bit indices and as runs.
|
||||
for (kind, data) in [(1, vec![6, 5, 6]), (9, vec![0x80, 6, 0x00, 5, 0x80, 6])] {
|
||||
let mut f = vec![0, 1, kind, 5, 0, 2, 0, 16, 0, 0, 0, 0, 3, 0, 1, 0, 8, 0x21];
|
||||
f.extend([0x0000u16, 0xfc00].iter().flat_map(|v| v.to_le_bytes()));
|
||||
f.extend(data);
|
||||
let img = image::load_from_memory(&raster_image(&f).unwrap().blob.bytes).unwrap().to_rgba8();
|
||||
let row: Vec<[u8; 4]> = (0..3).map(|x| img.get_pixel(x, 0).0).collect();
|
||||
assert_eq!(row, [[255, 0, 0, 255], [0, 0, 0, 0], [255, 0, 0, 255]], "image type {kind}");
|
||||
}
|
||||
|
||||
// A grayscale image the decoder could hold whose RGBA pixels pass the allowance is refused from
|
||||
// its header.
|
||||
let huge = targa_header(11, 32768, 32768, 8, 0);
|
||||
let e = raster_image(&huge).err().expect("refused");
|
||||
assert_eq!(e.to_string(), "an image of 32768 × 32768 pixels is too large to draw");
|
||||
|
||||
// Headers with values the specification doesn't define aren't Targa files.
|
||||
for bad in [targa_header(2, 0, 1, 24, 0), targa_header(1, 1, 1, 8, 0), targa_header(2, 1, 1, 12, 0), targa_header(2, 1, 1, 24, 0xc0)] {
|
||||
assert!(!super::tgaread::is_targa(&bad), "{bad:?}");
|
||||
}
|
||||
assert!(raster_image(b"nothing an image reader knows").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_formats_are_listed_and_write_one_file_per_artboard() {
|
||||
let mut s = Session::new();
|
||||
@@ -143,7 +289,7 @@ fn the_formats_are_listed_and_write_one_file_per_artboard() {
|
||||
let find = |id: &str| r["formats"].as_array().unwrap().iter().find(|f| f["id"] == id).unwrap().clone();
|
||||
let (tiff, bmp, tga) = (find("tiff"), find("bmp"), find("tga"));
|
||||
assert_eq!((tiff["write"].as_bool(), tiff["read"].as_bool()), (Some(true), Some(true)));
|
||||
assert_eq!((bmp["write"].as_bool(), tga["write"].as_bool(), tga["read"].as_bool()), (Some(true), Some(true), Some(false)));
|
||||
assert_eq!((bmp["write"].as_bool(), tga["write"].as_bool(), tga["read"].as_bool()), (Some(true), Some(true), Some(true)));
|
||||
for (f, keys) in [
|
||||
(&tiff, &["colorModel", "lzw", "byteOrder", "embedIcc", "ppi", "antiAlias"][..]),
|
||||
(&bmp, &["colorModel", "depth", "fileFormat", "rle", "flipRows", "reduction", "dither"]),
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Reading Targa files (`.tga`, `.vda`, `.icb`, `.vst`) for File › Open and File › Place, from the
|
||||
//! Truevision TGA File Format Specification, version 2.0. The `image` crate decodes the pixels.
|
||||
//! A Targa file starts with no signature, so [`is_targa`] checks its header's fields instead, and
|
||||
//! [`fix_alpha`] gives the decoded image the transparency the file stores. The file is untrusted:
|
||||
//! every read is checked.
|
||||
|
||||
/// Does `bytes` start with a Targa header? The fields must hold values the specification defines:
|
||||
/// a color map type of 0 or 1; an image type of 1, 2, 3, 9, 10 or 11 (color-mapped, true-color or
|
||||
/// black-and-white, raw or run-length encoded), with a color map for the color-mapped types; a
|
||||
/// color map entry size of 15, 16, 24 or 32 bits when there is a map; a width and a height; a pixel
|
||||
/// depth of 8, 15, 16, 24 or 32 bits; and bits 6 and 7 of the image descriptor clear.
|
||||
pub(super) fn is_targa(bytes: &[u8]) -> bool {
|
||||
let [_, map_type, image_type, _, _, _, _, entry_bits, _, _, _, _, w0, w1, h0, h1, depth, descriptor, ..] = *bytes else {
|
||||
return false;
|
||||
};
|
||||
matches!(map_type, 0 | 1)
|
||||
&& matches!(image_type, 1 | 2 | 3 | 9 | 10 | 11)
|
||||
&& (map_type == 1 || !matches!(image_type, 1 | 9))
|
||||
&& (map_type == 0 || matches!(entry_bits, 15 | 16 | 24 | 32))
|
||||
&& u16::from_le_bytes([w0, w1]) > 0
|
||||
&& u16::from_le_bytes([h0, h1]) > 0
|
||||
&& matches!(depth, 8 | 15 | 16 | 24 | 32)
|
||||
&& descriptor & 0xc0 == 0
|
||||
}
|
||||
|
||||
/// Give `img`, decoded from Targa file `bytes`, the transparency the file stores. Bits 0 to 3 of
|
||||
/// the image descriptor give the number of attribute bits per pixel, and the extension area's
|
||||
/// Attributes Type, when the file has one, says what they hold:
|
||||
/// - with no attribute bits, or attribute data the Attributes Type calls undefined (1 or 2), the
|
||||
/// image is opaque, whatever a 32-bit pixel's fourth byte holds (the decoder reads it as alpha);
|
||||
/// - with one bit, a 16-bit true-color pixel takes that bit as its alpha (clear: transparent), and
|
||||
/// a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; the decoder drops
|
||||
/// the bit;
|
||||
/// - with more, the decoder's alpha stays, and colors the Attributes Type calls premultiplied (4)
|
||||
/// are divided by it.
|
||||
///
|
||||
/// An Attributes Type of 0 ("no alpha") with attribute bits in the descriptor counts as alpha.
|
||||
pub(super) fn fix_alpha(bytes: &[u8], img: &mut image::RgbaImage) {
|
||||
let Some(bits) = bytes.get(17).map(|d| d & 0x0f) else { return };
|
||||
let kind = attributes_type(bytes);
|
||||
if bits == 0 || matches!(kind, Some(1 | 2)) {
|
||||
img.pixels_mut().for_each(|p| p.0[3] = 255);
|
||||
return;
|
||||
}
|
||||
if bits == 1 {
|
||||
one_bit_alpha(bytes, img);
|
||||
}
|
||||
if kind == Some(4) {
|
||||
for p in img.pixels_mut() {
|
||||
let a = u16::from(p.0[3]);
|
||||
for c in &mut p.0[..3] {
|
||||
// A fully transparent pixel keeps its colors.
|
||||
if let Some(v) = (u16::from(*c) * 255 + a / 2).checked_div(a) {
|
||||
*c = v.min(255) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Attributes Type of a Targa 2.0 file's extension area: `None` without the footer's
|
||||
/// `TRUEVISION-XFILE.` signature, an extension area, or one of the 495 bytes the specification
|
||||
/// gives it.
|
||||
fn attributes_type(bytes: &[u8]) -> Option<u8> {
|
||||
let footer = bytes.len().checked_sub(26)?;
|
||||
if bytes.get(footer + 8..)? != b"TRUEVISION-XFILE.\0" {
|
||||
return None;
|
||||
}
|
||||
let at = usize::try_from(u32::from_le_bytes(bytes.get(footer..footer + 4)?.try_into().ok()?)).ok()?;
|
||||
// The area follows the header and ends before the footer; its first field is its size.
|
||||
if at < 18 || at.checked_add(495)? > footer || u16::from_le_bytes([*bytes.get(at)?, *bytes.get(at + 1)?]) != 495 {
|
||||
return None;
|
||||
}
|
||||
bytes.get(at + 494).copied()
|
||||
}
|
||||
|
||||
/// The attribute bit of each pixel of a Targa image with one attribute bit per pixel, as `img`'s
|
||||
/// alpha: the top bit of a 16-bit true-color pixel, or of the 16-bit color map entry an 8- or
|
||||
/// 16-bit index names, raw or run-length encoded. Rows and columns are stored in the order the
|
||||
/// image descriptor's bits 5 (top to bottom) and 4 (right to left) give. Other images, and pixels
|
||||
/// the data doesn't reach, keep the alpha they have.
|
||||
fn one_bit_alpha(bytes: &[u8], img: &mut image::RgbaImage) {
|
||||
let [id_len, map_type, image_type, o0, o1, m0, m1, entry_bits, _, _, _, _, w0, w1, h0, h1, depth, descriptor, ..] = *bytes else {
|
||||
return;
|
||||
};
|
||||
let (w, h) = (u32::from(u16::from_le_bytes([w0, w1])), u32::from(u16::from_le_bytes([h0, h1])));
|
||||
let mapped = matches!(image_type, 1 | 9);
|
||||
// The number of bytes each pixel takes.
|
||||
let size = match image_type {
|
||||
2 | 10 if depth == 16 => 2,
|
||||
1 | 9 if map_type == 1 && entry_bits == 16 && matches!(depth, 8 | 16) => usize::from(depth / 8),
|
||||
_ => return,
|
||||
};
|
||||
if img.dimensions() != (w, h) {
|
||||
return;
|
||||
}
|
||||
let (first, entries) = (u16::from_le_bytes([o0, o1]), u16::from_le_bytes([m0, m1]));
|
||||
let map_at = 18 + usize::from(id_len);
|
||||
let map_len = if map_type == 1 { usize::from(entries) * usize::from(entry_bits).div_ceil(8) } else { 0 };
|
||||
// The attribute bit is the top bit of the little-endian pixel or color map entry.
|
||||
let attribute = |at: usize| -> Option<bool> {
|
||||
let px = bytes.get(at..at.checked_add(size)?)?;
|
||||
let high = if mapped {
|
||||
let index = match *px {
|
||||
[i] => u16::from(i),
|
||||
[lo, hi] => u16::from_le_bytes([lo, hi]),
|
||||
_ => return None,
|
||||
};
|
||||
let entry = index.checked_sub(first).filter(|e| *e < entries)?;
|
||||
*bytes.get(map_at + usize::from(entry) * 2 + 1)?
|
||||
} else {
|
||||
*px.get(1)?
|
||||
};
|
||||
Some(high & 0x80 != 0)
|
||||
};
|
||||
let (top_down, right_to_left) = (descriptor & 0x20 != 0, descriptor & 0x10 != 0);
|
||||
let total = u64::from(w) * u64::from(h);
|
||||
let mut set = |i: u64, opaque: bool| {
|
||||
let (row, col) = ((i / u64::from(w)) as u32, (i % u64::from(w)) as u32);
|
||||
let y = if top_down { row } else { h - 1 - row };
|
||||
let x = if right_to_left { w - 1 - col } else { col };
|
||||
img.get_pixel_mut(x, y).0[3] = if opaque { 255 } else { 0 };
|
||||
};
|
||||
let mut at = map_at + map_len;
|
||||
let mut i = 0;
|
||||
while i < total {
|
||||
if image_type < 9 {
|
||||
let Some(opaque) = attribute(at) else { return };
|
||||
set(i, opaque);
|
||||
(i, at) = (i + 1, at + size);
|
||||
continue;
|
||||
}
|
||||
let Some(&packet) = bytes.get(at) else { return };
|
||||
let count = u64::from(packet & 0x7f) + 1;
|
||||
at += 1;
|
||||
if packet & 0x80 != 0 {
|
||||
// A run packet repeats one pixel.
|
||||
let Some(opaque) = attribute(at) else { return };
|
||||
at += size;
|
||||
for _ in 0..count.min(total - i) {
|
||||
set(i, opaque);
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
for _ in 0..count.min(total - i) {
|
||||
let Some(opaque) = attribute(at) else { return };
|
||||
set(i, opaque);
|
||||
(i, at) = (i + 1, at + size);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -259,6 +259,10 @@ pub(crate) fn start_in(
|
||||
}
|
||||
// The walkers follow no links, so a folder automation may read holds all they read.
|
||||
crate::file_access::check_read(&folder.to_string_lossy())?;
|
||||
// The check above reads a lossy string: under roots, a path it would alter names another folder.
|
||||
if folder.to_str().is_none() && crate::file_access::current().is_some() {
|
||||
return Err("automation path rejected: the folder's name isn't valid text".into());
|
||||
}
|
||||
let seconds = if limits.seconds.is_finite() { limits.seconds.clamp(0.0, 3600.0) } else { 60.0 };
|
||||
let n = pool.reserve(threads.clamp(1, MAX_THREADS));
|
||||
if n == 0 {
|
||||
@@ -279,6 +283,7 @@ pub(crate) fn start_in(
|
||||
walk: Mutex::new(Walk { root: Some(folder), alive: n, found: vec![0; items], ..Walk::default() }),
|
||||
wake: Condvar::new(),
|
||||
pool,
|
||||
scope: crate::file_access::ScopeHandle::capture(),
|
||||
});
|
||||
let mut spawned = 0;
|
||||
for _ in 0..n {
|
||||
@@ -325,6 +330,8 @@ struct Shared {
|
||||
/// Woken when folders are queued, a walker finishes a folder, or the search ends.
|
||||
wake: Condvar,
|
||||
pool: &'static Pool,
|
||||
/// The automation roots in force when the search started, for the folders the walkers add.
|
||||
scope: crate::file_access::ScopeHandle,
|
||||
}
|
||||
|
||||
/// The state walkers change under the lock.
|
||||
@@ -490,7 +497,10 @@ impl Shared {
|
||||
}
|
||||
queue.push((path, depth + 1));
|
||||
}
|
||||
let home = rules.home_below(&listed);
|
||||
// The home folder is added by a rule, not picked: it needs the picked folder's authority.
|
||||
let home = rules
|
||||
.home_below(&listed)
|
||||
.filter(|h| !rules.is_refused(h) && self.scope.clone().run(|| crate::file_access::check_read(&h.to_string_lossy())).is_ok());
|
||||
{
|
||||
let mut w = self.lock();
|
||||
w.files += files;
|
||||
|
||||
+17
-1550
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
use super::*;
|
||||
|
||||
// ---------- plain art ----------
|
||||
|
||||
/// Converts art into what the compositor works on.
|
||||
pub(super) struct Scratch {
|
||||
/// A copy of the document the art comes from (outlining allocates ids in it).
|
||||
pub(super) doc: Document,
|
||||
pub(super) brushes: Vec<vectorcraft_brush::Brush>,
|
||||
}
|
||||
|
||||
impl Scratch {
|
||||
/// `n` as plain filled shapes: type outlined, symbol instances replaced by their art, live
|
||||
/// objects evaluated and strokes outlined (brush strokes as their art), each keeping the
|
||||
/// object's transparency.
|
||||
pub(super) fn plain(&mut self, n: &Node) -> Node {
|
||||
if !n.visible {
|
||||
return n.clone();
|
||||
}
|
||||
let made = match &n.kind {
|
||||
NodeKind::Text(_) => outlined_text(n),
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
let art = self.doc.symbols.iter().find(|s| &s.name == symbol).map(|s| vectorcraft_render::instance_art(&s.art, n));
|
||||
art.and_then(|a| effects::outline_art(Some(&self.doc), n, Some(&a))).map(|g| carry(n, g))
|
||||
}
|
||||
// A placed document stays one: its art's resources aren't the document's.
|
||||
NodeKind::PlacedDocument(_) => None,
|
||||
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) => {
|
||||
let hook: &dyn Fn(&Node) -> Option<Node> = &effects::outline_text;
|
||||
let hooks = vectorcraft_doc::live::Hooks { outline: Some(hook), symbols: Some(&self.doc), ..Default::default() };
|
||||
Some(carry(n, vectorcraft_doc::live::expanded_group_hooks(n, hooks)))
|
||||
}
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => outline_strokes(&mut self.doc, &self.brushes, n),
|
||||
_ => None,
|
||||
};
|
||||
let mut m = match made {
|
||||
// The pieces of one object never knock each other out.
|
||||
Some(m) if m.is_container() => Node { knockout: Knockout::Off, ..m },
|
||||
Some(m) => m,
|
||||
None => n.clone(),
|
||||
};
|
||||
if !matches!(m.kind, NodeKind::Compound { .. })
|
||||
&& let Some(ch) = m.children_mut()
|
||||
{
|
||||
for c in ch.iter_mut() {
|
||||
*c = Arc::new(self.plain(c));
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
/// Type as outlines painted like it ([`effects::outline_text`]), keeping its transparency.
|
||||
pub(super) fn outlined_text(n: &Node) -> Option<Node> {
|
||||
effects::outline_text(n).map(|g| Node { knockout: Knockout::Off, ..carry(n, g) })
|
||||
}
|
||||
|
||||
/// `to` (art made from `from`) with `from`'s name, transparency, opacity mask and effects.
|
||||
fn carry(from: &Node, mut to: Node) -> Node {
|
||||
to.name = from.name.clone();
|
||||
to.opacity = from.opacity;
|
||||
to.blend = from.blend;
|
||||
to.isolate = from.isolate;
|
||||
to.knockout_shape = from.knockout_shape;
|
||||
to.extras_mut().mask = from.extras().mask.clone();
|
||||
to.appearance.effects = from.appearance.effects.clone();
|
||||
to
|
||||
}
|
||||
|
||||
/// The keys of `doc`'s images that have see-through pixels (an alpha channel that isn't opaque
|
||||
/// everywhere).
|
||||
pub(crate) fn see_through_images(doc: &Document) -> BTreeSet<String> {
|
||||
let see_through = |b: &ImageBlob| {
|
||||
b.mime != "image/jpeg" && image::load_from_memory(&b.bytes).is_ok_and(|i| i.color().has_alpha() && i.to_rgba8().pixels().any(|p| p[3] < 255))
|
||||
};
|
||||
doc.images.iter().filter(|(_, b)| see_through(b)).map(|(k, _)| k.clone()).collect()
|
||||
}
|
||||
|
||||
/// `n` shows an image of `keys` (itself or inside).
|
||||
pub(super) fn draws_image(n: &Node, keys: &BTreeSet<String>) -> bool {
|
||||
!keys.is_empty()
|
||||
&& n.visible
|
||||
&& match &n.kind {
|
||||
NodeKind::Image(im) => keys.contains(&im.key),
|
||||
_ => n.children().is_some_and(|ch| ch.iter().any(|c| draws_image(c, keys))),
|
||||
}
|
||||
}
|
||||
|
||||
fn visible_fx(fx: &[Effect]) -> bool {
|
||||
fx.iter().any(|e| e.visible)
|
||||
}
|
||||
|
||||
/// Effects on the object or on one of its fills or strokes (raster effects, once baked).
|
||||
pub(super) fn has_effects(n: &Node) -> bool {
|
||||
visible_fx(&n.appearance.effects) || n.appearance.items.iter().any(|i| visible_fx(i.effects()))
|
||||
}
|
||||
|
||||
pub(super) fn masked(n: &Node) -> bool {
|
||||
n.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|
||||
}
|
||||
|
||||
/// Where `n` can paint: its visual bounds grown by its effects (and a margin for antialiasing).
|
||||
pub(super) fn reach(n: &Node) -> Option<Rect> {
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
let b = match n.children() {
|
||||
Some(ch) if !n.clips() && !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().filter_map(|c| reach(c)).reduce(|a, b| a.union(b))?,
|
||||
_ => n.visual_bounds()?,
|
||||
};
|
||||
let fx = n.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(effects::outset(&n.appearance.effects, b), f64::max);
|
||||
Some(b.inflate(fx + 1.0, fx + 1.0))
|
||||
}
|
||||
|
||||
/// Indices of `bounds` grouped by overlap (transitively), each group in index order.
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
|
||||
fn find(p: &mut [usize], mut i: usize) -> usize {
|
||||
while p[i] != i {
|
||||
p[i] = p[p[i]];
|
||||
i = p[i];
|
||||
}
|
||||
i
|
||||
}
|
||||
let mut parent: Vec<usize> = (0..bounds.len()).collect();
|
||||
let mut order: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.map(|b| (i, b))).collect();
|
||||
order.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0));
|
||||
// Sweep left to right, comparing each box with those still open at its left edge.
|
||||
let mut open: Vec<(usize, Rect)> = vec![];
|
||||
for (i, b) in order {
|
||||
open.retain(|(_, o)| o.x1 >= b.x0);
|
||||
for (j, o) in &open {
|
||||
if o.y0 <= b.y1 && b.y0 <= o.y1 {
|
||||
let (a, c) = (find(&mut parent, i), find(&mut parent, *j));
|
||||
parent[a.max(c)] = a.min(c);
|
||||
}
|
||||
}
|
||||
open.push((i, b));
|
||||
}
|
||||
let mut groups: Vec<Vec<usize>> = vec![];
|
||||
let mut slot: Vec<Option<usize>> = vec![None; bounds.len()];
|
||||
for i in 0..bounds.len() {
|
||||
let r = find(&mut parent, i);
|
||||
match slot[r] {
|
||||
Some(g) => groups[g].push(i),
|
||||
None => {
|
||||
slot[r] = Some(groups.len());
|
||||
groups.push(vec![i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
use super::analysis::{Scratch, outlined_text, overlapping, reach};
|
||||
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, WHITE};
|
||||
use super::options::FlattenOptions;
|
||||
use super::*;
|
||||
|
||||
// ---------- plan ----------
|
||||
|
||||
/// What the flattening does, worked out before the document changes.
|
||||
pub(super) struct Plan {
|
||||
pub(super) flat: Vec<Flat>,
|
||||
/// Objects without transparency (they stay, but for the outline options).
|
||||
pub(super) kept: Vec<NodeId>,
|
||||
/// The objects with transparency of their own.
|
||||
pub(super) transparent: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// One group of overlapping objects with transparency and what replaces it.
|
||||
pub(super) struct Flat {
|
||||
/// Its objects in paint order; the result takes the place of the last.
|
||||
pub(super) roots: Vec<NodeId>,
|
||||
pub(super) regions: Regions,
|
||||
/// Where its image goes, and the image (once rendered).
|
||||
pub(super) area: Option<Area>,
|
||||
raster: Option<Raster>,
|
||||
}
|
||||
|
||||
/// Where a group's image goes.
|
||||
pub(super) struct Area {
|
||||
rect: Rect,
|
||||
ppi: f64,
|
||||
/// The complex regions it is clipped to (Clip Complex Regions).
|
||||
clip: Option<PathData>,
|
||||
/// The raster/vector balance rasterizes the whole group (it splits into too many regions).
|
||||
pub(super) whole: bool,
|
||||
}
|
||||
|
||||
impl Area {
|
||||
/// The area's outline.
|
||||
pub(super) fn outline(&self) -> PathData {
|
||||
self.clip.clone().unwrap_or_else(|| shapes::rectangle(self.rect))
|
||||
}
|
||||
}
|
||||
|
||||
/// Flat-colour regions: their outlines and paints.
|
||||
pub(super) type Regions = Vec<(PathData, RegionFill)>;
|
||||
|
||||
/// A flat-colour region's paint.
|
||||
pub(super) struct RegionFill {
|
||||
paint: Paint,
|
||||
alpha: f32,
|
||||
overprint: bool,
|
||||
}
|
||||
|
||||
/// A rendered image of complex regions, clipped to them or not.
|
||||
struct Raster {
|
||||
blob: ImageBlob,
|
||||
width: u32,
|
||||
height: u32,
|
||||
xf: Affine,
|
||||
clip: Option<PathData>,
|
||||
}
|
||||
|
||||
/// The flattening of `roots` with `o`; `render` renders the images (the preview only needs where
|
||||
/// they go). Fails only when an image can't be encoded.
|
||||
pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: bool) -> Result<Plan> {
|
||||
let tmp = isolated_doc(src, roots.iter().filter_map(|id| src.node(*id).cloned()).collect());
|
||||
// Geometry effects first: what is left on the art are raster effects.
|
||||
let baked = effects::bake_document(&tmp).unwrap_or(tmp);
|
||||
let art: Vec<Node> = baked.layers[0].children().into_iter().flatten().map(|a| (**a).clone()).collect();
|
||||
let mut sc = Scratch { brushes: vectorcraft_brush::library(&baked), doc: baked.clone() };
|
||||
let plain: Vec<Node> = art.iter().map(|n| sc.plain(n)).collect();
|
||||
let reaches: Vec<Option<Rect>> = plain.iter().map(reach).collect();
|
||||
let see_through: Vec<bool> = plain.iter().map(|n| n.shows_transparency() || o.draws_see_through_image(n)).collect();
|
||||
let cmyk = src.color_mode == ColorMode::Cmyk;
|
||||
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
|
||||
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
for g in overlapping(&reaches) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let ids: Vec<NodeId> = g.iter().map(|&i| roots[i]).collect();
|
||||
let group = g.iter().any(|&i| see_through[i]).then(|| {
|
||||
let plain: Vec<&Node> = g.iter().map(|&i| &plain[i]).collect();
|
||||
flatten_group(&plain, o, cmyk)
|
||||
});
|
||||
let Some((regions, area)) = group.flatten() else {
|
||||
out.kept.extend(ids);
|
||||
continue;
|
||||
};
|
||||
let raster = match area.as_ref().filter(|_| render) {
|
||||
Some(a) => {
|
||||
let art: Vec<Node> = g.iter().map(|&i| art[i].clone()).collect();
|
||||
Some(render_raster(&baked, &art, a.rect, a.ppi, a.clip.clone(), o)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
out.flat.push(Flat { roots: ids, regions, area, raster });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The regions and the image area replacing one group of overlapping objects (`plain`: the art as
|
||||
/// composited; `cmyk`: in a CMYK document); `None` when it paints nothing.
|
||||
fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Regions, Option<Area>)> {
|
||||
let mut b = Builder { cmyk, ..Default::default() };
|
||||
let elems: Vec<Elem> = plain.iter().filter_map(|n| b.elem(n)).collect();
|
||||
if b.shapes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// An unclipped full raster needs no regions.
|
||||
let whole = o.balance <= 0.0 && !o.clip_complex_regions;
|
||||
let regions = if whole { vec![] } else { po::regions(&b.shapes) };
|
||||
// An arrangement that failed (degenerate geometry) leaves only rasterizing.
|
||||
let all = regions.is_empty() || o.rasterize_all(regions.len());
|
||||
let mut vector: Vec<(usize, RegionFill)> = vec![];
|
||||
let mut complex: Vec<usize> = vec![];
|
||||
let mut gradients_only = !all;
|
||||
for (k, r) in regions.iter().enumerate() {
|
||||
if all || r.sources.iter().any(|&i| b.kinds[i] != Kind::Vector) {
|
||||
gradients_only &= r.sources.iter().all(|&i| b.kinds[i] == Kind::Gradient);
|
||||
complex.push(k);
|
||||
} else if let Some(fill) = region_fill(&elems, &r.sources, o, cmyk) {
|
||||
vector.push((k, fill));
|
||||
}
|
||||
}
|
||||
let bounds = |ks: &[usize]| ks.iter().filter_map(|&k| regions[k].path.bounds()).reduce(|a, b| a.union(b));
|
||||
if !o.clip_complex_regions && !all {
|
||||
// A rectangle of raster takes in every region it overlaps.
|
||||
while let Some(r) = bounds(&complex) {
|
||||
let before = complex.len();
|
||||
let rect = shapes::rectangle(r);
|
||||
vector.retain(|(k, _)| {
|
||||
let path = ®ions[*k].path;
|
||||
let hit = path.bounds().is_some_and(|b| b.intersect(r).area() > 0.0)
|
||||
&& po::area(&po::boolean(path, FillRule::NonZero, &rect, FillRule::NonZero, po::BoolOp::Intersect), FillRule::NonZero) > 1e-6;
|
||||
if hit {
|
||||
complex.push(*k);
|
||||
}
|
||||
!hit
|
||||
});
|
||||
if complex.len() == before {
|
||||
break;
|
||||
}
|
||||
gradients_only = false;
|
||||
}
|
||||
}
|
||||
let raster_rect = if all { plain.iter().filter_map(|n| reach(n)).reduce(|a, b| a.union(b)) } else { bounds(&complex) };
|
||||
let area = raster_rect.map(|rect| {
|
||||
let clip = o.clip_complex_regions.then(|| PathData::new(complex.iter().flat_map(|&k| regions[k].path.subpaths.iter().cloned()).collect()));
|
||||
let ppi = if gradients_only { o.gradient_ppi } else { o.line_art_ppi };
|
||||
Area { rect, ppi, clip: clip.filter(|c| !c.is_empty()), whole: all }
|
||||
});
|
||||
let vector = vector.into_iter().map(|(k, f)| (regions[k].path.clone(), f)).collect();
|
||||
Some((vector, area))
|
||||
}
|
||||
|
||||
/// The flat colour of a region covered by `sources` (CMYK in a `cmyk` document); `None` where
|
||||
/// nothing paints it.
|
||||
fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool) -> Option<RegionFill> {
|
||||
let mut c = Composer { sources, top: None, plane: 0 };
|
||||
let alone = c.eval(elems, CLEAR);
|
||||
if alone[3] < 0.5 / 255.0 {
|
||||
return None;
|
||||
}
|
||||
let start = if o.preserve_alpha { CLEAR } else { WHITE };
|
||||
let px = if o.preserve_alpha {
|
||||
alone
|
||||
} else {
|
||||
c.top = None;
|
||||
c.eval(elems, start)
|
||||
};
|
||||
let rgb = [px[0], px[1], px[2]];
|
||||
// The K plane composites the same way.
|
||||
let k = cmyk.then(|| {
|
||||
c.plane = 1;
|
||||
c.eval(elems, start)[0]
|
||||
});
|
||||
// A paint showing as it is keeps its colour (spot, process, swatch) and overprint.
|
||||
let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3);
|
||||
let same = |f: &Fill| px[3] >= 1.0 - 1e-4 && near(&f.planes[0], &rgb) && k.is_none_or(|k| near(&f.planes[1][..1], &[k]));
|
||||
let color = match k {
|
||||
Some(k) => {
|
||||
let [c, m, y, k] = planes_cmyk(rgb, k);
|
||||
Color::cmyk(c, m, y, k)
|
||||
}
|
||||
None => Color::rgb(rgb[0], rgb[1], rgb[2]),
|
||||
};
|
||||
let (paint, overprint) = match c.top {
|
||||
Some(f) if o.preserve_overprints && same(f) => (f.paint.clone(), f.overprint),
|
||||
_ => (Paint::solid(color), false),
|
||||
};
|
||||
Some(RegionFill { paint, alpha: px[3], overprint })
|
||||
}
|
||||
|
||||
/// `art` rendered over `rect` at `ppi`: over white with the white the art doesn't cover taken out
|
||||
/// again (so blend modes see the white page), or over nothing with Preserve Alpha. The image and
|
||||
/// its `clip` reach a pixel further. An opaque image in a CMYK document holds the art's ink
|
||||
/// amounts (a CMYK TIFF), so its CMYK colours keep their numbers (#2160); other images are PNGs.
|
||||
/// Fails when the image can't be encoded.
|
||||
fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Option<PathData>, o: &FlattenOptions) -> Result<Raster> {
|
||||
let mut scale = ppi / 72.0;
|
||||
scale = scale.min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt());
|
||||
let px = 1.0 / scale;
|
||||
let rect = rect.inflate(px, px);
|
||||
let clip = clip.map(|c| Some(po::offset_path(&c, px, po::Join::Miter, 4.0)).filter(|g| !g.is_empty()).unwrap_or(c));
|
||||
let region = Rect::new(
|
||||
rect.x0,
|
||||
rect.y0,
|
||||
rect.x0 + (rect.width() * scale).ceil().max(1.0) / scale,
|
||||
rect.y0 + (rect.height() * scale).ceil().max(1.0) / scale,
|
||||
);
|
||||
let xf = Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale);
|
||||
let tmp = isolated_doc(doc, art.to_vec());
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
let no_alpha = o.no_transparency.is_some() && clip.is_some() && !o.preserve_alpha;
|
||||
if no_alpha && doc.color_mode == ColorMode::Cmyk {
|
||||
// Drawn as inks over the paper: as screen colours, the file would separate them again,
|
||||
// and a CMYK colour comes back with other inks (K moves into C, M and Y).
|
||||
let opts = vectorcraft_render::RenderOptions { background: Some([255; 4]), skip_templates: true, ..Default::default() };
|
||||
let inks = r.render_region_inks(&tmp, region, scale, &opts);
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let (width, height) = vectorcraft_render::region_pixels(region, scale);
|
||||
// Past the size of a CMYK image: drawn in screen colours, below.
|
||||
if let Some(blob) = Inks::new(width, height, inks).and_then(|i| ImageBlob::cmyk_tiff(&i)) {
|
||||
return Ok(Raster { blob, width, height, xf, clip });
|
||||
}
|
||||
}
|
||||
let mut img = r.render_region(&tmp, region, scale, !o.preserve_alpha);
|
||||
// The drawing stops early when cancelled: this image is not whole.
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
if no_alpha {
|
||||
// Without transparency the clip alone shapes the image: it is opaque, over white (its
|
||||
// edge pixels too).
|
||||
for p in img.pixels.as_chunks_mut::<4>().0 {
|
||||
p[3] = 255;
|
||||
}
|
||||
} else if !o.preserve_alpha || !o.anti_alias {
|
||||
// The art's coverage: drawn opaque, so only its own edges (and soft effects) are partial.
|
||||
let cover: Vec<Node> = art
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let mut c = n.clone();
|
||||
opaque(&mut c);
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
let cover = r.render_region(&isolated_doc(doc, cover), region, scale, false);
|
||||
for (px, c) in img.pixels.as_chunks_mut::<4>().0.iter_mut().zip(cover.pixels.as_chunks::<4>().0) {
|
||||
let k = c[3];
|
||||
let k2 = if o.anti_alias || k == 0 || k == 255 {
|
||||
k
|
||||
} else if k >= 128 {
|
||||
255
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if o.preserve_alpha {
|
||||
let f = k2 as f32 / k.max(1) as f32;
|
||||
for v in px.iter_mut() {
|
||||
*v = (*v as f32 * f).round().min(255.0) as u8;
|
||||
}
|
||||
} else {
|
||||
let white = 255 - k2;
|
||||
for v in &mut px[..3] {
|
||||
*v = v.saturating_sub(white).min(k2);
|
||||
}
|
||||
px[3] = k2;
|
||||
}
|
||||
}
|
||||
}
|
||||
let png = img.to_png().map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip })
|
||||
}
|
||||
|
||||
/// `n` at full opacity with Normal blending throughout (objects, fills and strokes).
|
||||
pub(super) fn opaque(n: &mut Node) {
|
||||
n.opacity = 1.0;
|
||||
n.blend = BlendMode::Normal;
|
||||
for i in &mut n.appearance.items {
|
||||
match i {
|
||||
AppearanceItem::Fill(f) => (f.opacity, f.blend) = (1.0, BlendMode::Normal),
|
||||
AppearanceItem::Stroke(s) => (s.opacity, s.blend) = (1.0, BlendMode::Normal),
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch {
|
||||
opaque(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `doc` with everything it draws flattened with `o`, as formats without transparency (EPS)
|
||||
/// write it: every visible object of the visible layers, locked ones too (a clipping layer's
|
||||
/// clipping path stays). `None` when that changes nothing.
|
||||
pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> {
|
||||
let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints;
|
||||
if !outlining && !doc.layers.iter().any(|l| l.shows_transparency() || o.draws_see_through_image(l)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut roots = vec![];
|
||||
for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
|
||||
let children = l.children().map_or(&[][..], Vec::as_slice);
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(doc, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.kept.iter().any(|id| doc.node(*id).is_some_and(|n| kept_work(n, o))) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
apply(&mut d, &mut vectorcraft_doc::Selection::default(), plan, o)?;
|
||||
Ok(Some(d))
|
||||
}
|
||||
|
||||
// ---------- apply ----------
|
||||
|
||||
pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan: Plan, o: &FlattenOptions) -> Result<(Vec<NodeId>, usize, usize)> {
|
||||
let (mut vector, mut rasterized) = (0, 0);
|
||||
let (mut ids, mut flat) = (vec![], vec![]);
|
||||
// The groups replace their objects in one pass at the end. When an object is listed twice or
|
||||
// lies inside another listed one, each group replaces its objects as it is made instead.
|
||||
let one_pass = separate(d, &plan.flat.iter().flat_map(|f| f.roots.iter().copied()).collect::<Vec<_>>());
|
||||
for f in plan.flat {
|
||||
// A group always has objects.
|
||||
let Some(&top) = f.roots.last() else { continue };
|
||||
let mut children = vec![];
|
||||
// The image goes under the regions, reaching a pixel past its own: their edges then fall on
|
||||
// matching pixels instead of on what is behind the group.
|
||||
if let Some(r) = f.raster {
|
||||
children.push(Arc::new(raster_node(d, r)));
|
||||
rasterized += 1;
|
||||
}
|
||||
for (path, fill) in f.regions {
|
||||
let mut n = shape_node(d, path, None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer { overprint: fill.overprint, ..FillLayer::new(fill.paint) })],
|
||||
..Appearance::default()
|
||||
}
|
||||
.into();
|
||||
n.opacity = fill.alpha.min(1.0);
|
||||
children.push(Arc::new(n));
|
||||
vector += 1;
|
||||
}
|
||||
let g = Node::group(d.alloc_id(), children);
|
||||
ids.push(g.id);
|
||||
if one_pass {
|
||||
// The group replaces the topmost object, and the other objects are removed.
|
||||
flat.extend(f.roots.iter().filter(|r| **r != top).map(|r| (*r, vec![])));
|
||||
flat.push((top, vec![g]));
|
||||
} else {
|
||||
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
|
||||
d.insert(par, idx + 1, g)?;
|
||||
for r in &f.roots {
|
||||
d.remove(*r)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !flat.is_empty() {
|
||||
d.insert_beside(flat, true)?;
|
||||
}
|
||||
let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] };
|
||||
for mut id in plan.kept {
|
||||
if o.text_to_outlines {
|
||||
id = outline_texts_under(d, id)?;
|
||||
}
|
||||
if o.strokes_to_outlines {
|
||||
id = outline_strokes_under(d, &brushes, id)?.0;
|
||||
}
|
||||
if !o.preserve_overprints
|
||||
&& let Some(n) = d.node_mut(id)
|
||||
{
|
||||
drop_overprints(n);
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
ids.sort_by_key(|id| d.index_path(*id));
|
||||
sel.set(ids.iter().copied());
|
||||
Ok((ids, vector, rasterized))
|
||||
}
|
||||
|
||||
/// An image of `r` (in a clip group when it is clipped).
|
||||
fn raster_node(d: &mut Document, r: Raster) -> Node {
|
||||
let key = unique_key(d, "flattened");
|
||||
d.images.insert(key.clone(), r.blob);
|
||||
let image = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Image(Box::new(ImageObject {
|
||||
key,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
xf: r.xf,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
})),
|
||||
);
|
||||
let Some(path) = r.clip else { return image };
|
||||
crate::cmd::rasterfx::clip_group(d, path, FillRule::NonZero, image)
|
||||
}
|
||||
|
||||
/// Replace the type under `root` by its outlines: → the id now standing for `root`.
|
||||
fn outline_texts_under(d: &mut Document, root: NodeId) -> Result<NodeId> {
|
||||
let mut texts = vec![];
|
||||
if let Some(n) = d.node(root) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Text(_)) {
|
||||
texts.push(c.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut out = root;
|
||||
for t in texts {
|
||||
let Some(o) = outlined_text(&t) else { continue };
|
||||
let o = d.reid(&o);
|
||||
let nid = o.id;
|
||||
*d.node_mut(t.id).ok_or(EngineError::NoNode(t.id))? = o;
|
||||
if t.id == root {
|
||||
out = nid;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether the outline and overprint options change `n`, an object without transparency.
|
||||
pub(super) fn kept_work(n: &Node, o: &FlattenOptions) -> bool {
|
||||
let mut any = false;
|
||||
n.walk(&mut |c| {
|
||||
any |= (o.text_to_outlines && matches!(c.kind, NodeKind::Text(_)))
|
||||
|| (o.strokes_to_outlines && stroked(c))
|
||||
|| (!o.preserve_overprints && overprints(c));
|
||||
});
|
||||
any
|
||||
}
|
||||
|
||||
/// Whether `n` is a path with a visible stroke (outlining turns it into a fill).
|
||||
pub(super) fn stroked(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. })
|
||||
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0))
|
||||
}
|
||||
|
||||
fn overprints(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(AppearanceItem::overprint)
|
||||
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|
||||
}
|
||||
|
||||
fn drop_overprints(n: &mut Node) {
|
||||
if overprints(n) {
|
||||
for i in &mut n.appearance.items {
|
||||
*i.overprint_mut() = false;
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
(r.style.overprint_fill, r.style.overprint_stroke) = (false, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch {
|
||||
drop_overprints(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use super::options::flatten;
|
||||
use super::presets::{presets_delete, presets_export, presets_import, presets_list, presets_save};
|
||||
use super::report::preview;
|
||||
use super::*;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"object.flattenTransparency",
|
||||
"Flatten Transparency…",
|
||||
["Object"],
|
||||
None,
|
||||
"{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach; objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
has_doc,
|
||||
flatten
|
||||
),
|
||||
cmd!(
|
||||
query "flattener.presets.list",
|
||||
"Transparency Flattener Presets",
|
||||
[],
|
||||
None,
|
||||
"{} → {presets: [{name, builtIn, options}]} the built-in presets (High, Medium and Low Resolution), then the saved ones; any of these names works as `preset` wherever flattener options are taken",
|
||||
always,
|
||||
presets_list
|
||||
),
|
||||
cmd!(
|
||||
query "flattener.presets.save",
|
||||
"Save Transparency Flattener Preset",
|
||||
[],
|
||||
None,
|
||||
"{name?: (default: a new \"Flattener Preset N\"), newName?: rename it, preset?: the preset to start from (default: the saved preset `name`, else medium), …options (the keys of object.flattenTransparency, at the top level or in `options`)} create or change a saved preset (built-in ones can't change) → {name, options, created}",
|
||||
always,
|
||||
presets_save
|
||||
),
|
||||
cmd!(
|
||||
query "flattener.presets.delete",
|
||||
"Delete Transparency Flattener Preset",
|
||||
[],
|
||||
None,
|
||||
"{name} delete a saved preset (built-in ones stay) → {deleted: name}",
|
||||
always,
|
||||
presets_delete
|
||||
),
|
||||
cmd!(
|
||||
query "flattener.presets.import",
|
||||
"Import Transparency Flattener Presets",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, replace?: false (replace saved presets of the same names; else the imported ones get a number)} add the presets of a .vcflattener file (as flattener.presets.export writes) to the saved ones → {imported: [names]}",
|
||||
always,
|
||||
presets_import
|
||||
),
|
||||
cmd!(
|
||||
query "flattener.presets.export",
|
||||
"Export Transparency Flattener Presets",
|
||||
[],
|
||||
None,
|
||||
"{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcflattener file (JSON) → {path, count}; without path → {data: the file's text, count}",
|
||||
always,
|
||||
presets_export
|
||||
),
|
||||
cmd!(
|
||||
query "flattener.preview",
|
||||
"Flattener Preview",
|
||||
[],
|
||||
None,
|
||||
"{highlight?: \"none\"|\"rasterizedRegions\" (areas the raster/vector balance rasterizes whole)|\"transparentObjects\"|\"allAffected\"|\"expandedPatterns\" (pattern art taking part)|\"outlinedStrokes\"|\"outlinedText\"|\"allRasterized\" (default none), overprints?: \"preserve\"|\"simulate\"|\"discard\" (simulate and discard flatten without preserveOverprints), preset?, …options as object.flattenTransparency, ids?|id?: (default: the whole document)} what flattening would do, without changing anything → {highlight, regions: [{bounds: {x, y, width, height}, id?}] (the highlighted objects, or areas), counts: {transparentObjects, allAffected, expandedPatterns, outlinedStrokes, outlinedText, rasterizedRegions, allRasterized, vectorRegions}, options}",
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
use super::analysis::{has_effects, masked, reach};
|
||||
use super::*;
|
||||
|
||||
// ---------- the compositor ----------
|
||||
|
||||
/// What an arrangement shape stands for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum Kind {
|
||||
/// Solid fills and clipping paths: regions inside get a flat colour.
|
||||
Vector,
|
||||
/// A gradient or mesh: regions inside are rasterized at the gradient resolution.
|
||||
Gradient,
|
||||
/// Anything else that has no single colour (patterns, images, masks, raster effects).
|
||||
Other,
|
||||
}
|
||||
|
||||
/// A solid fill as the compositor uses it.
|
||||
pub(super) struct Fill {
|
||||
/// What it composites: its screen colour (twice), or in a CMYK document its two ink planes
|
||||
/// ([`cmyk_planes`]).
|
||||
pub(super) planes: [[f32; 3]; 2],
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
pub(super) paint: Paint,
|
||||
pub(super) overprint: bool,
|
||||
}
|
||||
|
||||
/// One object of the art being flattened, with the transparency the renderer gives it.
|
||||
pub(super) struct Elem {
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
isolate: bool,
|
||||
knockout: Knockout,
|
||||
knockout_shape: bool,
|
||||
/// Blending inside reaches the backdrop ([`Node::blends_through`]).
|
||||
blends: bool,
|
||||
/// Inside a knockout group its children are elements of their own ([`Node::passes_knockout_through`]).
|
||||
pass_through: bool,
|
||||
body: Body,
|
||||
}
|
||||
|
||||
enum Body {
|
||||
/// Solid fills (bottom first) of arrangement shape `shape`.
|
||||
Fills { shape: usize, fills: Vec<Fill> },
|
||||
/// A group's children, clipped to arrangement shape `clip` in a clip group.
|
||||
Group { clip: Option<usize>, children: Vec<Elem> },
|
||||
/// Art without a flat colour: its regions are rasterized, so it never composites here.
|
||||
Complex,
|
||||
}
|
||||
|
||||
/// Builds the compositor's objects and the arrangement shapes they cover.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Builder {
|
||||
pub(super) shapes: Vec<po::Shape>,
|
||||
pub(super) kinds: Vec<Kind>,
|
||||
/// Building a CMYK document's art.
|
||||
pub(super) cmyk: bool,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
/// What colour `c` composites as ([`Fill::planes`]).
|
||||
fn planes(&self, c: &Color) -> [[f32; 3]; 2] {
|
||||
if self.cmyk {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
cmyk_planes(cms.to_cmyk(c, cms.settings().intent))
|
||||
} else {
|
||||
[c.to_rgb(); 2]
|
||||
}
|
||||
}
|
||||
|
||||
fn shape(&mut self, path: PathData, rule: FillRule, kind: Kind) -> Option<usize> {
|
||||
path.bounds()?;
|
||||
self.shapes.push(po::Shape::new(path, rule, self.shapes.len() as u64));
|
||||
self.kinds.push(kind);
|
||||
Some(self.shapes.len() - 1)
|
||||
}
|
||||
|
||||
pub(super) fn elem(&mut self, n: &Node) -> Option<Elem> {
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
let body = if masked(n) || has_effects(n) {
|
||||
self.shape(shapes::rectangle(reach(n)?), FillRule::NonZero, Kind::Other)?;
|
||||
Body::Complex
|
||||
} else {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
let (clip, rest) = if n.clips() {
|
||||
let (first, rest) = children.split_first()?;
|
||||
// Nothing to clip by hides the clipped art.
|
||||
let (bp, rule) = effects::clip_outline(first)?;
|
||||
(Some(self.shape(PathData::from_bezpath(&bp), rule, Kind::Vector)?), rest)
|
||||
} else {
|
||||
(None, &children[..])
|
||||
};
|
||||
Body::Group { clip, children: rest.iter().filter_map(|c| self.elem(c)).collect() }
|
||||
}
|
||||
NodeKind::Path { guide: true, .. } => return None,
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
let (path, rule) = node_path(n)?;
|
||||
let mut fills = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| i.is_fill() && i.visible() && !i.paint().is_none()) {
|
||||
match item.paint() {
|
||||
Paint::Solid { color, .. } => fills.push(Fill {
|
||||
planes: self.planes(color),
|
||||
opacity: item.opacity(),
|
||||
blend: item.blend(),
|
||||
paint: item.paint().clone(),
|
||||
overprint: item.overprint(),
|
||||
}),
|
||||
p => {
|
||||
let kind = if matches!(p, Paint::Gradient(_)) { Kind::Gradient } else { Kind::Other };
|
||||
self.shape(path.clone(), rule, kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
if fills.is_empty() { Body::Complex } else { Body::Fills { shape: self.shape(path, rule, Kind::Vector)?, fills } }
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
|
||||
self.shape(frame, FillRule::NonZero, Kind::Other)?;
|
||||
Body::Complex
|
||||
}
|
||||
NodeKind::Mesh(_) => {
|
||||
self.shape(shapes::rectangle(reach(n)?), FillRule::NonZero, Kind::Gradient)?;
|
||||
Body::Complex
|
||||
}
|
||||
_ => {
|
||||
self.shape(shapes::rectangle(reach(n)?), FillRule::NonZero, Kind::Other)?;
|
||||
Body::Complex
|
||||
}
|
||||
}
|
||||
};
|
||||
Some(Elem {
|
||||
opacity: n.opacity,
|
||||
blend: n.blend,
|
||||
isolate: n.isolate,
|
||||
knockout: n.knockout,
|
||||
knockout_shape: n.knockout_shape,
|
||||
blends: n.blends_through(),
|
||||
pass_through: n.passes_knockout_through(),
|
||||
body,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A straight (not premultiplied) RGBA colour in 0..=1.
|
||||
pub(super) type Px = [f32; 4];
|
||||
|
||||
pub(super) const CLEAR: Px = [0.0; 4];
|
||||
|
||||
pub(super) const WHITE: Px = [1.0; 4];
|
||||
|
||||
fn premul(p: Px) -> Px {
|
||||
[p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]
|
||||
}
|
||||
|
||||
fn unpremul(q: Px) -> Px {
|
||||
if q[3] <= 0.0 { CLEAR } else { [q[0] / q[3], q[1] / q[3], q[2] / q[3], q[3].min(1.0)] }
|
||||
}
|
||||
|
||||
/// Composites the objects covering one atomic region exactly as the renderer composites pixels
|
||||
/// (its transparency groups, non-isolated groups, knockout groups and clip groups): the same
|
||||
/// paints cover the whole region, so one colour stands for all of it.
|
||||
pub(super) struct Composer<'a> {
|
||||
/// Arrangement shapes covering the region, ascending.
|
||||
pub(super) sources: &'a [usize],
|
||||
/// The last solid fill composited.
|
||||
pub(super) top: Option<&'a Fill>,
|
||||
/// Which of the fills' [`Fill::planes`] composites.
|
||||
pub(super) plane: usize,
|
||||
}
|
||||
|
||||
impl<'a> Composer<'a> {
|
||||
fn inside(&self, shape: usize) -> bool {
|
||||
self.sources.binary_search(&shape).is_ok()
|
||||
}
|
||||
|
||||
/// `elems` (paint order) composited over `start`.
|
||||
pub(super) fn eval(&mut self, elems: &'a [Elem], start: Px) -> Px {
|
||||
elems.iter().fold(start, |acc, e| self.draw(e, acc, false, false, false))
|
||||
}
|
||||
|
||||
/// `e` drawn over backdrop `b` inside a group that knocks out when `enclosing`. `as_shape`
|
||||
/// draws it as its knockout shape (full object opacity); `nested` is drawing inside a layer,
|
||||
/// where a non-isolated group can't copy its backdrop and is drawn isolated.
|
||||
fn draw(&mut self, e: &'a Elem, b: Px, enclosing: bool, as_shape: bool, nested: bool) -> Px {
|
||||
let opacity = if as_shape { 1.0 } else { e.opacity };
|
||||
let ko = matches!(e.body, Body::Group { .. }) && e.knockout.resolve(enclosing);
|
||||
if opacity >= 1.0 && e.blend == BlendMode::Normal && !e.isolate && !ko {
|
||||
return self.content(e, b, ko, None, nested);
|
||||
}
|
||||
if e.blends && !e.isolate && !nested {
|
||||
// Drawn over a copy of the backdrop, so blending inside reaches it.
|
||||
let c = self.content(e, b, ko, Some(b), false);
|
||||
if e.blend == BlendMode::Normal {
|
||||
let (pb, pc) = (premul(b), premul(c));
|
||||
return unpremul([0, 1, 2, 3].map(|i| pb[i] + (pc[i] - pb[i]) * opacity));
|
||||
}
|
||||
// The group's own colour: the backdrop's share taken out by the group's coverage.
|
||||
let (pc, pa, pb) = (premul(c), premul(self.content(e, CLEAR, ko, None, false)), premul(b));
|
||||
let keep = 1.0 - pa[3];
|
||||
let g = [0, 1, 2].map(|i| (pc[i] - keep * pb[i]).clamp(0.0, pa[3]));
|
||||
let g = unpremul([g[0], g[1], g[2], pa[3]]);
|
||||
return composite(e.blend, b, [g[0], g[1], g[2], g[3] * opacity]);
|
||||
}
|
||||
let inner_nested = !(e.blends && (e.isolate || !nested));
|
||||
let g = self.content(e, CLEAR, ko, None, inner_nested);
|
||||
composite(e.blend, b, [g[0], g[1], g[2], g[3] * opacity])
|
||||
}
|
||||
|
||||
/// What `e` draws over `b` inside its group (`ko`: its children knock each other out, against
|
||||
/// `backdrop` when the group was drawn over a copy of it).
|
||||
fn content(&mut self, e: &'a Elem, b: Px, ko: bool, backdrop: Option<Px>, nested: bool) -> Px {
|
||||
match &e.body {
|
||||
Body::Fills { shape, fills } if self.inside(*shape) => fills.iter().fold(b, |acc, f| {
|
||||
self.top = Some(f);
|
||||
let [r, g, b] = f.planes[self.plane];
|
||||
composite(f.blend, acc, [r, g, b, f.opacity])
|
||||
}),
|
||||
Body::Group { clip, children } if clip.is_none_or(|c| self.inside(c)) => {
|
||||
if ko {
|
||||
self.knockout(children, b, backdrop)
|
||||
} else {
|
||||
children.iter().fold(b, |acc, c| self.draw(c, acc, false, false, nested))
|
||||
}
|
||||
}
|
||||
_ => b,
|
||||
}
|
||||
}
|
||||
|
||||
/// The children of a knockout group over `b`: each first erases what the ones below it drew
|
||||
/// by its knockout shape, then adds itself composited against the group's backdrop.
|
||||
fn knockout(&mut self, children: &'a [Elem], b: Px, backdrop: Option<Px>) -> Px {
|
||||
fn elements<'e>(children: &'e [Elem], out: &mut Vec<&'e Elem>) {
|
||||
for c in children {
|
||||
match &c.body {
|
||||
Body::Group { children, .. } if c.pass_through => elements(children, out),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut els = vec![];
|
||||
elements(children, &mut els);
|
||||
let mut acc = premul(b);
|
||||
for c in els {
|
||||
let s = self.draw(c, CLEAR, true, !c.knockout_shape, true)[3];
|
||||
let own = match backdrop {
|
||||
Some(b0) => premul(self.draw(c, b0, true, false, true)).map(|v| v * s),
|
||||
None => premul(self.draw(c, CLEAR, true, false, true)),
|
||||
};
|
||||
acc = [0, 1, 2, 3].map(|i| acc[i] * (1.0 - s) + own[i]);
|
||||
}
|
||||
unpremul(acc)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
use super::analysis::draws_image;
|
||||
use super::apply::{apply, kept_work, plan};
|
||||
use super::presets::{FlattenerPreset, saved_preset};
|
||||
use super::report::target_roots;
|
||||
use super::*;
|
||||
|
||||
/// Object → Flatten Transparency settings: a preset's, adjusted by the command's params.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct FlattenOptions {
|
||||
/// Raster/vector balance, 0–100: 0 rasterizes all flattened art; 100 keeps everything vector
|
||||
/// that can be; in between, groups that split into more regions than it allows are rasterized.
|
||||
pub balance: f64,
|
||||
/// Resolution (ppi) of rasterized art.
|
||||
pub line_art_ppi: f64,
|
||||
/// Resolution (ppi) of rasterized areas that only gradients and meshes reach.
|
||||
pub gradient_ppi: f64,
|
||||
/// Outline all type, also where it isn't transparent.
|
||||
pub text_to_outlines: bool,
|
||||
/// Outline all strokes, also where they aren't transparent.
|
||||
pub strokes_to_outlines: bool,
|
||||
/// Clip rasterized areas to their region outlines (else they are rectangles).
|
||||
pub clip_complex_regions: bool,
|
||||
/// Smooth the edges of rasterized areas.
|
||||
pub anti_alias: bool,
|
||||
/// Keep the art's own alpha: composite over nothing instead of over white.
|
||||
pub preserve_alpha: bool,
|
||||
/// Areas showing a single paint keep it (spot and process colours, swatches) with its
|
||||
/// overprint; off, the flattened objects lose their overprints.
|
||||
pub preserve_overprints: bool,
|
||||
/// Flattening for files without any transparency (PDF/X-1a, PDF/X-3): images with
|
||||
/// see-through pixels (these keys, [`see_through_images`]) count as transparency, and
|
||||
/// rasterized areas clipped to their regions are opaque (in a CMYK document, images of ink
|
||||
/// amounts). `None` for ordinary flattening. Not a preset option.
|
||||
#[serde(skip)]
|
||||
pub no_transparency: Option<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
impl Default for FlattenOptions {
|
||||
fn default() -> Self {
|
||||
Self::builtin("medium")
|
||||
}
|
||||
}
|
||||
|
||||
impl FlattenOptions {
|
||||
/// Preset ids, finest first.
|
||||
pub const PRESETS: [&'static str; 3] = ["high", "medium", "low"];
|
||||
|
||||
/// Display name of a preset id.
|
||||
pub fn preset_label(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"high" => "High Resolution",
|
||||
"medium" => "Medium Resolution",
|
||||
"low" => "Low Resolution",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A preset by id or display name, any case.
|
||||
pub fn preset(name: &str) -> Option<Self> {
|
||||
let key = name.trim().to_ascii_lowercase();
|
||||
let id = Self::PRESETS.into_iter().find(|id| key == *id || Self::preset_label(id).is_some_and(|l| l.eq_ignore_ascii_case(&key)))?;
|
||||
Some(Self::builtin(id))
|
||||
}
|
||||
|
||||
/// The built-in preset `id` (one of [`Self::PRESETS`]; anything else is low).
|
||||
fn builtin(id: &str) -> Self {
|
||||
let (balance, line_art_ppi, gradient_ppi, clip_complex_regions, anti_alias) = match id {
|
||||
"high" => (100.0, 1200.0, 300.0, true, false),
|
||||
"medium" => (75.0, 300.0, 300.0, false, true),
|
||||
_ => (75.0, 300.0, 150.0, false, true),
|
||||
};
|
||||
Self {
|
||||
balance,
|
||||
line_art_ppi,
|
||||
gradient_ppi,
|
||||
text_to_outlines: false,
|
||||
strokes_to_outlines: false,
|
||||
clip_complex_regions,
|
||||
anti_alias,
|
||||
preserve_alpha: false,
|
||||
preserve_overprints: true,
|
||||
no_transparency: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in presets, finest first.
|
||||
pub fn builtin_presets() -> Vec<FlattenerPreset> {
|
||||
Self::PRESETS
|
||||
.into_iter()
|
||||
.filter_map(|id| Some(FlattenerPreset { name: Self::preset_label(id)?.into(), options: Self::preset(id)? }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A built-in preset (by id or display name) or one of `saved` (by name), any case.
|
||||
pub fn find_preset(name: &str, saved: &[FlattenerPreset]) -> Option<Self> {
|
||||
Self::preset(name).or_else(|| saved_preset(saved, name).map(|p| p.options.clone()))
|
||||
}
|
||||
|
||||
/// The options `p` asks for, with the built-in presets only ([`Self::from_params_with`]).
|
||||
pub fn from_params(p: &Value) -> std::result::Result<Self, String> {
|
||||
Self::from_params_with(p, &[])
|
||||
}
|
||||
|
||||
/// The options an export flattens with: preset `name` (built-in or one of `saved`; default
|
||||
/// medium) with the export's `flattener` `options` over it.
|
||||
pub fn for_export(name: Option<&str>, options: Option<&Value>, saved: &[FlattenerPreset]) -> std::result::Result<Self, String> {
|
||||
let mut q = json!({ "options": options.cloned().unwrap_or(Value::Null) });
|
||||
if let Some(name) = name {
|
||||
q["preset"] = json!(name);
|
||||
}
|
||||
Self::from_params_with(&q, saved)
|
||||
}
|
||||
|
||||
/// The options `p` asks for: `preset` (built-in or one of `saved`; default medium) adjusted by
|
||||
/// the option keys given at the top level or in `options`.
|
||||
pub fn from_params_with(p: &Value, saved: &[FlattenerPreset]) -> std::result::Result<Self, String> {
|
||||
let base = match str_param(p, "preset") {
|
||||
Some(name) => Self::find_preset(name, saved)
|
||||
.ok_or_else(|| format!("unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list)"))?,
|
||||
None => Self::default(),
|
||||
};
|
||||
let mut v = serde_json::to_value(&base).map_err(|e| e.to_string())?;
|
||||
for src in [Some(p), p.get("options")].into_iter().flatten().filter_map(Value::as_object) {
|
||||
for (k, val) in src {
|
||||
if let Some(slot) = v.get_mut(k) {
|
||||
*slot = val.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
let o: Self = serde_json::from_value(v).map_err(|e| e.to_string())?;
|
||||
if !(0.0..=100.0).contains(&o.balance) {
|
||||
return Err("balance must be between 0 and 100".into());
|
||||
}
|
||||
if ![o.line_art_ppi, o.gradient_ppi].iter().all(|r| (1.0..=2400.0).contains(r)) {
|
||||
return Err("resolutions must be between 1 and 2400 ppi".into());
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// `n` shows an image whose see-through pixels count as transparency.
|
||||
pub(super) fn draws_see_through_image(&self, n: &Node) -> bool {
|
||||
self.no_transparency.as_ref().is_some_and(|keys| draws_image(n, keys))
|
||||
}
|
||||
|
||||
/// Whether a group that splits into `regions` atomic regions is rasterized whole.
|
||||
pub(super) fn rasterize_all(&self, regions: usize) -> bool {
|
||||
self.balance <= 0.0 || (self.balance < 100.0 && regions as f64 > 10f64.powf(self.balance / 20.0))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.flattenTransparency";
|
||||
let o = s.flatten_options(p).map_err(|m| bad(C, m))?;
|
||||
let roots = target_roots(s, p)?;
|
||||
if roots.is_empty() {
|
||||
return Err(EngineError::Other("Flatten Transparency: select objects to flatten".into()));
|
||||
}
|
||||
let src = s.doc()?.doc.clone();
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let plan = plan(&src, &roots, &o, true)?;
|
||||
let warning = crate::cmd::rasterfx::undecoded_warning(failed);
|
||||
let options = serde_json::to_value(&o).unwrap_or_default();
|
||||
if plan.flat.is_empty() && !plan.kept.iter().any(|id| src.node(*id).is_some_and(|n| kept_work(n, &o))) {
|
||||
return Ok(json!({ "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>(), "rasterized": 0, "vector": 0, "options": options }));
|
||||
}
|
||||
let (ids, vector, rasterized) = s.edit("Flatten Transparency", |d, sel| {
|
||||
let threaded = crate::cmd::threads::frames(d);
|
||||
let out = apply(d, sel, plan, &o)?;
|
||||
// Frames of threaded text that were outlined or flattened leave their threads with the
|
||||
// text they show.
|
||||
crate::cmd::threads::leave_threads(d, &threaded);
|
||||
Ok(out)
|
||||
})?;
|
||||
let mut out = json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "rasterized": rasterized, "vector": vector, "options": options });
|
||||
if let Some(w) = warning {
|
||||
out["warning"] = json!(w);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use super::options::FlattenOptions;
|
||||
use super::*;
|
||||
|
||||
// ---------- presets ----------
|
||||
|
||||
/// A named set of flattener options: a built-in preset or a saved one
|
||||
/// ([`crate::Prefs::flattener_presets`]).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FlattenerPreset {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub options: FlattenOptions,
|
||||
}
|
||||
|
||||
/// What `flattener.presets.export` writes and `flattener.presets.import` reads.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PresetFile {
|
||||
format: String,
|
||||
#[serde(default)]
|
||||
presets: Vec<FlattenerPreset>,
|
||||
}
|
||||
|
||||
/// The `format` of a presets file, also its extension.
|
||||
pub const PRESET_FORMAT: &str = "vcflattener";
|
||||
|
||||
/// The extensions of presets files (opening one imports it).
|
||||
pub const PRESET_EXTS: &[&str] = &[PRESET_FORMAT];
|
||||
|
||||
pub(super) fn saved_preset<'a>(saved: &'a [FlattenerPreset], name: &str) -> Option<&'a FlattenerPreset> {
|
||||
saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim()))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Every flattener preset: the built-in ones, then the saved ones.
|
||||
pub fn flattener_presets(&self) -> Vec<FlattenerPreset> {
|
||||
let mut v = FlattenOptions::builtin_presets();
|
||||
v.extend(self.prefs.flattener_presets.iter().cloned());
|
||||
v
|
||||
}
|
||||
|
||||
/// The preset `name` names: a built-in one (by id or display name) or a saved one, any case.
|
||||
pub fn flattener_preset(&self, name: &str) -> Option<FlattenerPreset> {
|
||||
let key = name.trim();
|
||||
let key = FlattenOptions::preset_label(&key.to_ascii_lowercase()).unwrap_or(key);
|
||||
self.flattener_presets().into_iter().find(|p| p.name.eq_ignore_ascii_case(key))
|
||||
}
|
||||
|
||||
/// The flattener options `p` asks for: a `preset` by name, built-in or saved, adjusted by the
|
||||
/// option keys ([`FlattenOptions::from_params_with`]).
|
||||
pub fn flatten_options(&self, p: &Value) -> std::result::Result<FlattenOptions, String> {
|
||||
FlattenOptions::from_params_with(p, &self.prefs.flattener_presets)
|
||||
}
|
||||
|
||||
/// The first free "Flattener Preset N": the name a new preset gets.
|
||||
pub fn new_preset_name(&self) -> String {
|
||||
(1..).map(|i| format!("Flattener Preset {i}")).find(|n| !self.preset_taken(n, None)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The index of the saved preset `name`.
|
||||
fn saved_index(&self, name: &str) -> Option<usize> {
|
||||
self.prefs.flattener_presets.iter().position(|q| q.name.eq_ignore_ascii_case(name.trim()))
|
||||
}
|
||||
|
||||
/// Whether `name` is taken by a built-in preset or a saved one other than the one at `except`.
|
||||
fn preset_taken(&self, name: &str, except: Option<usize>) -> bool {
|
||||
FlattenOptions::preset(name).is_some() || self.saved_index(name).is_some_and(|i| Some(i) != except)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let rows = FlattenOptions::builtin_presets()
|
||||
.into_iter()
|
||||
.map(|p| (p, true))
|
||||
.chain(s.prefs.flattener_presets.iter().cloned().map(|p| (p, false)))
|
||||
.map(|(p, builtin)| json!({"name": p.name, "builtIn": builtin, "options": p.options}));
|
||||
Ok(json!({ "presets": rows.collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
pub(super) fn presets_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "flattener.presets.save";
|
||||
let name = match str_param(p, "name").map(str::trim) {
|
||||
Some("") => return Err(bad(C, "`name` is empty")),
|
||||
Some(n) => n.to_string(),
|
||||
None => s.new_preset_name(),
|
||||
};
|
||||
if FlattenOptions::preset(&name).is_some() {
|
||||
return Err(bad(C, format!("`{name}` is a built-in preset and can't change: save it under another name")));
|
||||
}
|
||||
let at = s.saved_index(&name);
|
||||
// A saved preset changes from its own options unless `preset` says where to start.
|
||||
let mut q = p.clone();
|
||||
if let (Some(i), Some(o), None) = (at, q.as_object_mut(), str_param(p, "preset")) {
|
||||
o.insert("preset".into(), json!(s.prefs.flattener_presets[i].name));
|
||||
}
|
||||
let options = s.flatten_options(&q).map_err(|m| bad(C, m))?;
|
||||
let name = match str_param(p, "newName").map(str::trim) {
|
||||
Some("") => return Err(bad(C, "`newName` is empty")),
|
||||
Some(n) if s.preset_taken(n, at) => return Err(bad(C, format!("a preset named `{n}` exists"))),
|
||||
Some(n) => n.to_string(),
|
||||
None => at.map_or(name, |i| s.prefs.flattener_presets[i].name.clone()),
|
||||
};
|
||||
let preset = FlattenerPreset { name: name.clone(), options: options.clone() };
|
||||
match at {
|
||||
Some(i) => s.prefs.flattener_presets[i] = preset,
|
||||
None => s.prefs.flattener_presets.push(preset),
|
||||
}
|
||||
Ok(json!({"name": name, "options": options, "created": at.is_none()}))
|
||||
}
|
||||
|
||||
pub(super) fn presets_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "flattener.presets.delete";
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
|
||||
if FlattenOptions::preset(name).is_some() {
|
||||
return Err(bad(C, format!("`{name}` is a built-in preset and stays")));
|
||||
}
|
||||
let i = s.saved_index(name).ok_or_else(|| bad(C, format!("no saved preset named `{name}`")))?;
|
||||
Ok(json!({ "deleted": s.prefs.flattener_presets.remove(i).name }))
|
||||
}
|
||||
|
||||
pub(super) fn presets_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "flattener.presets.export";
|
||||
let presets = match p.get("names").and_then(Value::as_array) {
|
||||
Some(names) => {
|
||||
let find = |n: &Value| {
|
||||
let n = n.as_str().unwrap_or_default();
|
||||
s.flattener_preset(n).ok_or_else(|| bad(C, format!("no preset named `{n}`")))
|
||||
};
|
||||
names.iter().map(find).collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
None => s.prefs.flattener_presets.clone(),
|
||||
};
|
||||
if presets.is_empty() {
|
||||
return Err(bad(C, "no saved presets to export (name built-in ones in `names`)"));
|
||||
}
|
||||
let count = presets.len();
|
||||
let text = serde_json::to_string_pretty(&PresetFile { format: PRESET_FORMAT.into(), presets }).map_err(|e| bad(C, e.to_string()))?;
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
crate::cmd::fileio::write_file(path, text.as_bytes())?;
|
||||
Ok(json!({"path": path, "count": count}))
|
||||
}
|
||||
None => Ok(json!({"data": text, "count": count})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn presets_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "flattener.presets.import";
|
||||
let bytes = match (str_param(p, "path"), str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
(Some(path), ..) => crate::cmd::fileio::read_file(path)?,
|
||||
(None, Some(text), _) => text.as_bytes().to_vec(),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(C, "bad dataBase64"))?,
|
||||
_ => return Err(bad(C, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
let file: PresetFile = serde_json::from_slice(&bytes).map_err(|e| bad(C, format!("not a flattener presets file: {e}")))?;
|
||||
if file.format != PRESET_FORMAT {
|
||||
return Err(bad(C, format!("not a flattener presets file (format `{}`)", file.format)));
|
||||
}
|
||||
// Values a hand-edited file may carry are rejected as the commands reject them.
|
||||
for q in &file.presets {
|
||||
FlattenOptions::from_params(&json!({ "options": q.options })).map_err(|m| bad(C, format!("`{}`: {m}", q.name)))?;
|
||||
}
|
||||
let replace = bool_or(p, "replace", false);
|
||||
let mut imported = vec![];
|
||||
for mut preset in file.presets {
|
||||
let base = Some(preset.name.trim()).filter(|n| !n.is_empty()).unwrap_or("Flattener Preset").to_string();
|
||||
match s.saved_index(&base) {
|
||||
Some(i) if replace => {
|
||||
preset.name = s.prefs.flattener_presets[i].name.clone();
|
||||
imported.push(preset.name.clone());
|
||||
s.prefs.flattener_presets[i] = preset;
|
||||
}
|
||||
_ => {
|
||||
preset.name = unique_name(&base, |n| s.preset_taken(n, None));
|
||||
imported.push(preset.name.clone());
|
||||
s.prefs.flattener_presets.push(preset);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({ "imported": imported }))
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
use super::apply::{kept_work, opaque, plan, stroked};
|
||||
use super::options::FlattenOptions;
|
||||
use super::*;
|
||||
|
||||
/// The top-level objects among `ids` (or the selection), in paint order: layers stand for their
|
||||
/// contents; hidden and locked objects and clipping paths are left alone.
|
||||
pub(super) fn target_roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut ids = vec![];
|
||||
for id in targets(s, p)? {
|
||||
match d.node(id) {
|
||||
Some(n) if n.is_layer() => ids.extend(n.children().into_iter().flatten().map(|c| c.id)),
|
||||
Some(_) => ids.push(id),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
let mut keyed: Vec<(Vec<usize>, NodeId)> = ids.into_iter().filter_map(|id| d.index_path(id).map(|p| (p, id))).collect();
|
||||
keyed.sort();
|
||||
keyed.dedup();
|
||||
let roots = roots_of(d, keyed.into_iter().map(|(_, id)| id).collect());
|
||||
// A clipping path stays where it clips.
|
||||
let clipping = |id: NodeId| {
|
||||
d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == id))
|
||||
};
|
||||
let editable = d.editable();
|
||||
Ok(roots.into_iter().filter(|id| d.is_visible(*id) && editable(*id) && !clipping(*id)).collect())
|
||||
}
|
||||
|
||||
// ---------- preview ----------
|
||||
|
||||
/// What the Flattener Preview highlights.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Highlight {
|
||||
/// Nothing: the art in colour.
|
||||
#[default]
|
||||
None,
|
||||
/// Areas the raster/vector balance rasterizes whole.
|
||||
RasterizedRegions,
|
||||
/// Objects with transparency of their own.
|
||||
TransparentObjects,
|
||||
/// Every object flattening changes.
|
||||
AllAffected,
|
||||
/// Objects with pattern paint in the flattened art.
|
||||
ExpandedPatterns,
|
||||
/// Strokes that become filled outlines.
|
||||
OutlinedStrokes,
|
||||
/// Type that becomes outlines.
|
||||
OutlinedText,
|
||||
/// Every area that becomes an image.
|
||||
AllRasterized,
|
||||
}
|
||||
|
||||
impl Highlight {
|
||||
pub const ALL: [Self; 8] = [
|
||||
Self::None,
|
||||
Self::RasterizedRegions,
|
||||
Self::TransparentObjects,
|
||||
Self::AllAffected,
|
||||
Self::ExpandedPatterns,
|
||||
Self::OutlinedStrokes,
|
||||
Self::OutlinedText,
|
||||
Self::AllRasterized,
|
||||
];
|
||||
|
||||
/// The id `flattener.preview` takes.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::None => "none",
|
||||
Self::RasterizedRegions => "rasterizedRegions",
|
||||
Self::TransparentObjects => "transparentObjects",
|
||||
Self::AllAffected => "allAffected",
|
||||
Self::ExpandedPatterns => "expandedPatterns",
|
||||
Self::OutlinedStrokes => "outlinedStrokes",
|
||||
Self::OutlinedText => "outlinedText",
|
||||
Self::AllRasterized => "allRasterized",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::None => "None (Color Preview)",
|
||||
Self::RasterizedRegions => "Rasterized Complex Regions",
|
||||
Self::TransparentObjects => "Transparent Objects",
|
||||
Self::AllAffected => "All Affected Objects",
|
||||
Self::ExpandedPatterns => "Expanded Patterns",
|
||||
Self::OutlinedStrokes => "Outlined Strokes",
|
||||
Self::OutlinedText => "Outlined Text",
|
||||
Self::AllRasterized => "All Rasterized Regions",
|
||||
}
|
||||
}
|
||||
|
||||
/// A highlight by id or label, any case.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
let s = s.trim();
|
||||
Self::ALL.into_iter().find(|h| h.id().eq_ignore_ascii_case(s) || h.label().eq_ignore_ascii_case(s))
|
||||
}
|
||||
}
|
||||
|
||||
/// How the Flattener Preview treats overprints: kept as they are, simulated in the preview, or
|
||||
/// dropped; only Preserve flattens with Preserve Overprints and Spot Colors.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Overprints {
|
||||
#[default]
|
||||
Preserve,
|
||||
Simulate,
|
||||
Discard,
|
||||
}
|
||||
|
||||
impl Overprints {
|
||||
pub const ALL: [Self; 3] = [Self::Preserve, Self::Simulate, Self::Discard];
|
||||
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Preserve => "preserve",
|
||||
Self::Simulate => "simulate",
|
||||
Self::Discard => "discard",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Preserve => "Preserve",
|
||||
Self::Simulate => "Simulate",
|
||||
Self::Discard => "Discard",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|o| o.id().eq_ignore_ascii_case(s.trim()) || o.label().eq_ignore_ascii_case(s.trim()))
|
||||
}
|
||||
}
|
||||
|
||||
/// What flattening would do (Window → Flattener Preview, `flattener.preview`).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FlattenReport {
|
||||
/// Top-level objects with transparency of their own.
|
||||
pub transparent: Vec<NodeId>,
|
||||
/// Top-level objects flattening changes: the overlapping groups with transparency, and those
|
||||
/// the outline and overprint options change.
|
||||
pub affected: Vec<NodeId>,
|
||||
/// Objects with pattern paint in the flattened art.
|
||||
pub patterns: Vec<NodeId>,
|
||||
/// Paths whose strokes become filled outlines.
|
||||
pub strokes: Vec<NodeId>,
|
||||
/// Type that becomes outlines.
|
||||
pub text: Vec<NodeId>,
|
||||
/// Areas the raster/vector balance rasterizes whole.
|
||||
pub complex: Vec<PathData>,
|
||||
/// Every area that becomes an image.
|
||||
pub rasterized: Vec<PathData>,
|
||||
/// Flat-colour regions made.
|
||||
pub vector: usize,
|
||||
}
|
||||
|
||||
impl FlattenReport {
|
||||
/// The objects `h` highlights.
|
||||
pub fn objects(&self, h: Highlight) -> &[NodeId] {
|
||||
match h {
|
||||
Highlight::TransparentObjects => &self.transparent,
|
||||
Highlight::AllAffected => &self.affected,
|
||||
Highlight::ExpandedPatterns => &self.patterns,
|
||||
Highlight::OutlinedStrokes => &self.strokes,
|
||||
Highlight::OutlinedText => &self.text,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// The areas `h` highlights.
|
||||
pub fn areas(&self, h: Highlight) -> &[PathData] {
|
||||
match h {
|
||||
Highlight::RasterizedRegions => &self.complex,
|
||||
Highlight::AllRasterized => &self.rasterized,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// How many objects or areas each highlight shows.
|
||||
pub fn counts(&self) -> Value {
|
||||
json!({
|
||||
"transparentObjects": self.transparent.len(),
|
||||
"allAffected": self.affected.len(),
|
||||
"expandedPatterns": self.patterns.len(),
|
||||
"outlinedStrokes": self.strokes.len(),
|
||||
"outlinedText": self.text.len(),
|
||||
"rasterizedRegions": self.complex.len(),
|
||||
"allRasterized": self.rasterized.len(),
|
||||
"vectorRegions": self.vector,
|
||||
})
|
||||
}
|
||||
|
||||
/// The report as `flattener.preview` answers: the highlighted objects (or areas) of `doc` and
|
||||
/// the counts.
|
||||
pub fn to_json(&self, doc: &Document, h: Highlight) -> Value {
|
||||
let rect = |r: Rect| json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height()});
|
||||
let objects = self.objects(h).iter().filter_map(|id| Some(json!({"id": id.0, "bounds": rect(doc.node(*id)?.visual_bounds()?)})));
|
||||
let areas = self.areas(h).iter().filter_map(|p| Some(json!({ "bounds": rect(p.bounds()?) })));
|
||||
json!({"highlight": h.id(), "regions": objects.chain(areas).collect::<Vec<_>>(), "counts": self.counts()})
|
||||
}
|
||||
|
||||
/// The art `h` highlights, opaque, alone in a copy of `doc`: the objects and the areas (filled
|
||||
/// black). Its coverage is the highlight. `None` when nothing is highlighted.
|
||||
pub fn highlight_art(&self, doc: &Document, h: Highlight) -> Option<Document> {
|
||||
let (ids, areas) = (self.objects(h), self.areas(h));
|
||||
if ids.is_empty() && areas.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut tmp = doc.clone();
|
||||
let mut art: Vec<Node> = ids.iter().filter_map(|id| doc.node(*id).cloned()).collect();
|
||||
art.iter_mut().for_each(opaque);
|
||||
for path in areas {
|
||||
let mut n = shape_node(&mut tmp, path.clone(), None);
|
||||
n.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into();
|
||||
art.push(n);
|
||||
}
|
||||
Some(isolated_doc(&tmp, art))
|
||||
}
|
||||
}
|
||||
|
||||
/// What flattening `roots` of `doc` with `o` would do.
|
||||
pub fn report(doc: &Document, roots: &[NodeId], o: &FlattenOptions) -> Result<FlattenReport> {
|
||||
let plan = plan(doc, roots, o, false)?;
|
||||
let mut r = FlattenReport { transparent: plan.transparent, ..Default::default() };
|
||||
// Every object under `id` (but a compound path's own pieces), visible ones only.
|
||||
fn visit(n: &Node, f: &mut dyn FnMut(&Node)) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
f(n);
|
||||
if !matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
let pattern = |n: &Node| n.appearance.items.iter().any(|i| i.visible() && matches!(i.paint(), Paint::Pattern { .. }));
|
||||
for f in &plan.flat {
|
||||
r.affected.extend(&f.roots);
|
||||
r.vector += f.regions.len();
|
||||
for root in f.roots.iter().filter_map(|id| doc.node(*id)) {
|
||||
visit(root, &mut |n| {
|
||||
// Flattened art is outlined throughout and its patterns become part of the image.
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
r.text.push(n.id);
|
||||
} else if stroked(n) {
|
||||
r.strokes.push(n.id);
|
||||
}
|
||||
if pattern(n) {
|
||||
r.patterns.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(a) = &f.area {
|
||||
if a.whole {
|
||||
r.complex.push(a.outline());
|
||||
}
|
||||
r.rasterized.push(a.outline());
|
||||
}
|
||||
}
|
||||
for root in plan.kept.iter().filter_map(|id| doc.node(*id)).filter(|n| kept_work(n, o)) {
|
||||
r.affected.push(root.id);
|
||||
visit(root, &mut |n| {
|
||||
if o.text_to_outlines && matches!(n.kind, NodeKind::Text(_)) {
|
||||
r.text.push(n.id);
|
||||
} else if o.strokes_to_outlines && stroked(n) {
|
||||
r.strokes.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
r.affected.sort_by_key(|id| doc.index_path(*id));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// What flattening would do with the options `p` asks for (as `flattener.preview`): the
|
||||
/// options and the report.
|
||||
pub fn flattener_report(&self, p: &Value) -> Result<(FlattenOptions, FlattenReport)> {
|
||||
const C: &str = "flattener.preview";
|
||||
let mut o = self.flatten_options(p).map_err(|m| bad(C, m))?;
|
||||
if let Some(v) = str_param(p, "overprints") {
|
||||
let ov = Overprints::parse(v).ok_or_else(|| bad(C, format!("unknown overprints `{v}` (preserve, simulate or discard)")))?;
|
||||
o.preserve_overprints = ov == Overprints::Preserve;
|
||||
}
|
||||
let roots = if p.get("ids").is_some() {
|
||||
target_roots(self, p)?
|
||||
} else {
|
||||
let layers: Vec<u64> = self.doc()?.doc.layers.iter().map(|l| l.id.0).collect();
|
||||
target_roots(self, &json!({ "ids": layers }))?
|
||||
};
|
||||
let r = report(&self.doc()?.doc, &roots, &o)?;
|
||||
Ok((o, r))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let h = match str_param(p, "highlight") {
|
||||
Some(v) => Highlight::parse(v).ok_or_else(|| bad("flattener.preview", format!("unknown highlight `{v}`")))?,
|
||||
None => Highlight::None,
|
||||
};
|
||||
let (o, r) = s.flattener_report(p)?;
|
||||
let mut out = r.to_json(&s.doc()?.doc, h);
|
||||
out["options"] = serde_json::to_value(&o).unwrap_or_default();
|
||||
Ok(out)
|
||||
}
|
||||
@@ -101,6 +101,12 @@ pub(super) fn font_label((family, style, version): &UsedFont) -> String {
|
||||
|
||||
/// The fonts (family, style, version) of the type in the layers and symbols of `d`.
|
||||
pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
|
||||
art_fonts(d, &[])
|
||||
}
|
||||
|
||||
/// The fonts (family, style, version) of the type in the layers and symbols of `d` and in `art`
|
||||
/// (art read from a file, its resources in `d`).
|
||||
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
|
||||
let mut fonts = BTreeSet::new();
|
||||
let mut add = |n: &Node| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
@@ -111,6 +117,9 @@ pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
|
||||
for s in &d.symbols {
|
||||
s.art.walk(&mut add);
|
||||
}
|
||||
for n in art {
|
||||
n.walk(&mut add);
|
||||
}
|
||||
fonts
|
||||
}
|
||||
|
||||
@@ -301,7 +310,8 @@ fn drawn_runs(t: &vectorcraft_doc::TextObject) -> (Vec<&TextRun>, bool) {
|
||||
}
|
||||
|
||||
/// What an export that draws type (as outlines, embedded fonts or pixels) says when `d` uses font
|
||||
/// families that aren't available: their type is drawn in the fallback font, not the font it names.
|
||||
/// families that aren't available (their type is drawn in the fallback font, not the font it
|
||||
/// names) or styles that its family doesn't have (the closest style is drawn).
|
||||
pub(super) fn substitution_warning(d: &Document) -> Option<String> {
|
||||
substitution_warning_of(used_fonts(d))
|
||||
}
|
||||
@@ -309,20 +319,34 @@ pub(super) fn substitution_warning(d: &Document) -> Option<String> {
|
||||
/// [`substitution_warning`] for type set in `fonts`.
|
||||
pub(super) fn substitution_warning_of(fonts: BTreeSet<UsedFont>) -> Option<String> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let mut missing: Vec<String> = fonts
|
||||
.into_iter()
|
||||
.filter(|(family, style, _)| db.resolve(family, style).is_none_or(|(_, m)| m == vectorcraft_text::FontMatch::Missing))
|
||||
.map(|(family, _, _)| family)
|
||||
.collect();
|
||||
let mut missing: Vec<String> = Vec::new();
|
||||
let mut styles: BTreeSet<String> = BTreeSet::new();
|
||||
for (family, style, _) in fonts {
|
||||
match db.resolve(&family, &style) {
|
||||
None | Some((_, vectorcraft_text::FontMatch::Missing)) => missing.push(family),
|
||||
Some((face, vectorcraft_text::FontMatch::Style)) => {
|
||||
styles.insert(format!("{family} {style} was drawn in {} {}", face.family, face.style));
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
// Sorted by family: its styles and versions are neighbours.
|
||||
missing.dedup();
|
||||
(!missing.is_empty()).then(|| {
|
||||
format!(
|
||||
let mut parts = Vec::new();
|
||||
if !missing.is_empty() {
|
||||
parts.push(format!(
|
||||
"fonts that aren't available were written in the fallback font, {}: {} (install them, or replace them with Find Font)",
|
||||
vectorcraft_text::FALLBACK_FAMILY,
|
||||
missing.join(", ")
|
||||
)
|
||||
})
|
||||
));
|
||||
}
|
||||
if !styles.is_empty() {
|
||||
parts.push(format!(
|
||||
"font styles that aren't available were written in the closest style: {} (pick a style the family has)",
|
||||
styles.into_iter().collect::<Vec<_>>().join(", ")
|
||||
));
|
||||
}
|
||||
(!parts.is_empty()).then(|| parts.join("; "))
|
||||
}
|
||||
|
||||
fn text(d: &Document, id: NodeId) -> Option<&vectorcraft_doc::TextObject> {
|
||||
@@ -585,6 +609,16 @@ mod open_tests {
|
||||
assert_eq!(inter["missingGlyphs"], 2, "雅 and 楽 come from a fallback font: {inter}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_warns_when_a_style_is_drawn_in_another_style() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi", "font": "Source Sans 3", "style": "Black Wide"})).unwrap();
|
||||
let out = s.execute("document.export", &json!({"format": "pdf"})).unwrap();
|
||||
let warnings = out["warnings"].to_string();
|
||||
assert!(warnings.contains("Source Sans 3 Black Wide was drawn in Source Sans 3"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opened_documents_have_exact_text_bounds() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color?, opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color?, keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
@@ -134,6 +134,12 @@ fn point_fields(v: &Value, pt: &mut FreeformPoint, to_paint: Affine) -> std::res
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `color` of `p` as the document stores it: an RGB color in a CMYK document becomes CMYK
|
||||
/// through the color settings ([`super::paint::new_color`]). `None` without a valid one.
|
||||
fn given_color(s: &Session, p: &Value) -> Option<vectorcraft_color::Color> {
|
||||
p.get("color").and_then(color_value).map(|c| super::paint::new_color(s, p, c))
|
||||
}
|
||||
|
||||
/// Parse the `freeform` param of a gradient paint (`{points: [{at, color, opacity?, spread?}],
|
||||
/// lines?: [[index, …]], mode?}`; points in the paint's space). Lossless for
|
||||
/// `vectorcraft_tools::params::freeform_json`.
|
||||
@@ -170,7 +176,7 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result<FreeformMode, String> {
|
||||
/// automatic points it shows first, and the stops follow the points' colours.
|
||||
fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result<R, String>) -> Result<R> {
|
||||
let item = item_target(s, p, cmd)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?;
|
||||
let item = item.of_kind(s, !stroke);
|
||||
let ids = item.targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
@@ -221,7 +227,7 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
/// The `index` param, else the selected point.
|
||||
fn point_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
|
||||
match p.get("index") {
|
||||
Some(v) => v.as_u64().map(|i| i as usize).ok_or_else(|| bad(cmd, "`index` must be a point index")),
|
||||
Some(v) => v.as_u64().map(index).ok_or_else(|| bad(cmd, "`index` must be a point index")),
|
||||
None => s.selected_freeform_point().ok_or_else(|| bad(cmd, "no point selected (give `index`)")),
|
||||
}
|
||||
}
|
||||
@@ -238,11 +244,16 @@ fn add_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Bool(true)) => s.selected_freeform_point(),
|
||||
Some(_) => return Err(bad(C, "`line` must be true or false")),
|
||||
};
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
let given = given_color(s, p);
|
||||
let index = edit(s, p, C, |f, sp| {
|
||||
let q = sp.to_paint * at;
|
||||
let (color, opacity) = f.sample(q, sp.scale);
|
||||
let mut pt = FreeformPoint { opacity, ..FreeformPoint::new(q, color) };
|
||||
point_fields(p, &mut pt, sp.to_paint)?;
|
||||
if let Some(c) = given {
|
||||
pt.color = c;
|
||||
}
|
||||
let i = f.add_point(pt);
|
||||
if let Some(from) = join {
|
||||
f.connect(from, i);
|
||||
@@ -256,9 +267,15 @@ fn add_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn set_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paint.freeform.setPoint";
|
||||
let i = point_index(s, p, C)?;
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
let given = given_color(s, p);
|
||||
edit(s, p, C, |f, sp| {
|
||||
check_index(f, i)?;
|
||||
point_fields(p, &mut f.points[i], sp.to_paint)
|
||||
point_fields(p, &mut f.points[i], sp.to_paint)?;
|
||||
if let Some(c) = given {
|
||||
f.points[i].color = c;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "index": i }))
|
||||
}
|
||||
@@ -291,7 +308,7 @@ fn split_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paint.freeform.splitLine";
|
||||
let line = index_param(p, "line", C)?;
|
||||
let segment = index_param(p, "segment", C)?;
|
||||
let t = f64_or(p, "t", 0.5);
|
||||
let t = number_or(p, "t", 0.5, C)?;
|
||||
let index = edit(s, p, C, |f, _| f.split_line(line, segment, t).ok_or_else(|| format!("no segment {segment} on line {line}")))?;
|
||||
s.select_freeform_point(Some(index));
|
||||
Ok(json!({ "index": index }))
|
||||
@@ -303,7 +320,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => return Err(bad(C, "missing `index` (a point index, or null to clear)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let i = v.as_u64().ok_or_else(|| bad(C, "`index` must be a whole number or null"))? as usize;
|
||||
let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?;
|
||||
let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, NOT_FREEFORM))?;
|
||||
check_index(&f, i).map_err(|e| bad(C, e))?;
|
||||
Some(i)
|
||||
@@ -315,7 +332,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paint.freeform.get";
|
||||
let stroke = bool_or(p, "stroke", !s.fill_active);
|
||||
let stroke = switch_or(p, "stroke", !s.fill_active, C)?;
|
||||
let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, NOT_FREEFORM))?;
|
||||
let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None };
|
||||
let mut v = vectorcraft_tools::params::freeform_json(&f);
|
||||
|
||||
@@ -0,0 +1,600 @@
|
||||
//! Select › Start Global Edit / Stop Global Edit, and the Global Edit Options.
|
||||
//!
|
||||
//! Behaviour from the public help pages "Edit similar objects"
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html>)
|
||||
//! and "Update assets quickly with Global Edit"
|
||||
//! (<https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html>), in our words:
|
||||
//!
|
||||
//! - With one object selected, Start Global Edit finds the objects that repeat its shape: the
|
||||
//! same outline, wherever it lies and at whatever size. Two options narrow the match: Appearance
|
||||
//! (the same fill and stroke too) and Size (the same width and height too). The search covers
|
||||
//! every artboard and the canvas around them by default; it can be limited to a range of
|
||||
//! artboards (`1, 3-5`) and can leave out the objects that lie on no artboard. Images, type,
|
||||
//! masks, linked files and selections of more than one object are not supported.
|
||||
//! - While Global Edit is on, an edit made to one of the found objects is made to all of them,
|
||||
//! each in proportion to its own size: halving the height of a 100 pt object halves a 20 pt
|
||||
//! match to 10 pt. Stop Global Edit (or Escape) ends it.
|
||||
//!
|
||||
//! Here the found objects ([`GlobalEdit::members`]) stay highlighted while the selection keeps the
|
||||
//! object that was selected, so that the Transform panel and the bounding box measure that object
|
||||
//! and not the whole set. Each member keeps the transform (a move and a uniform scale) that maps
|
||||
//! the first object's outline onto its own. After every edit ([`propagate`], run inside
|
||||
//! [`Session::edit`], so the whole change is one undo step), the first selected member the edit
|
||||
//! changed is the model: what changed about it is given to every other member, and nothing else,
|
||||
//! so members found by shape alone keep their own fills and strokes where the edit didn't touch
|
||||
//! them:
|
||||
//!
|
||||
//! - its outline (and anchors), placed through that transform, so in proportion to each member's
|
||||
//! size. Only geometry is placed so: no stroke weight is scaled to a member's size;
|
||||
//! - its opacity, blending, knockout and the object's effects, each when it changed;
|
||||
//! - of its fills and strokes, each setting that changed (paint, weight, opacity, blending,
|
||||
//! effects, caps, dashes, arrowheads …), as it is: it goes to the member's fill or stroke of the
|
||||
//! same rank (the second fill from the bottom to the second fill), and a member without one is
|
||||
//! left without it. A weight set to 4 pt is 4 pt on a smaller member too. The pen pressure a
|
||||
//! stroke was drawn with stays each member's own;
|
||||
//! - a fill or stroke added or removed: a member whose fills and strokes lie in the model's
|
||||
//! former order gains the same item at the same place (or loses the one at that place). A
|
||||
//! member with another order, and any other change to the list (items moved, or several added
|
||||
//! or removed at once), takes the model's whole list of fills and strokes.
|
||||
//!
|
||||
//! Members that are hidden or locked at the time are left as they are. An edit that would take any
|
||||
//! member past the canvas (beyond [`vectorcraft_doc::MAX_COORD`]) is refused whole, as one that
|
||||
//! takes the selection there is. Whenever the document is put back (Undo, Redo, a cancelled drag
|
||||
//! or scrub, an edit that failed), the members it lacks (or no longer supports) leave the Global
|
||||
//! Edit, and it ends when fewer than two are left ([`follow_history`]), so that an object made
|
||||
//! later under a freed id is never edited. Rotated copies, groups (the help page "Edit groups with
|
||||
//! similar objects") and excluding a member with a Shift-click are not covered.
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape};
|
||||
|
||||
use super::wand::{fill_of, stroke_of};
|
||||
use super::*;
|
||||
|
||||
const C: &str = "select.globalEdit";
|
||||
const OPTIONS: &str = "select.globalEditOptions";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"select.globalEdit",
|
||||
"Start Global Edit",
|
||||
["Select"],
|
||||
None,
|
||||
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object, with the objects of the same shape (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard) → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
|
||||
can_toggle,
|
||||
toggle
|
||||
),
|
||||
cmd!(
|
||||
"select.globalEditOptions",
|
||||
"Global Edit Options",
|
||||
[],
|
||||
None,
|
||||
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} set the options Start Global Edit matches with (defaults: shape only, all artboards, objects on the canvas included) → {appearance, size, artboards, includeCanvas, count: the objects Start Global Edit would take now (0 unless one supported object is selected)}",
|
||||
has_doc,
|
||||
set_options
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The Global Edit Options: what a similar object must share with the selected one besides its
|
||||
/// shape, and where it may lie. Kept for the session.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Options {
|
||||
/// Match the fill and stroke too.
|
||||
pub appearance: bool,
|
||||
/// Match the width and height too.
|
||||
pub size: bool,
|
||||
/// The artboards to search (1-based range as typed); `None`: all of them.
|
||||
pub artboards: Option<String>,
|
||||
/// Include the objects that lie on no artboard.
|
||||
pub include_canvas: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self { appearance: false, size: false, artboards: None, include_canvas: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Options {
|
||||
/// These options with the ones `p` gives, checked against `d`'s artboards.
|
||||
fn with(&self, p: &Value, d: &Document, cmd: &str) -> Result<Self> {
|
||||
let mut o = self.clone();
|
||||
o.appearance = bool_or(p, "appearance", o.appearance);
|
||||
o.size = bool_or(p, "size", o.size);
|
||||
o.include_canvas = bool_or(p, "includeCanvas", o.include_canvas);
|
||||
match p.get("artboards") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::String(s)) if s.trim().is_empty() || s.trim().eq_ignore_ascii_case("all") => o.artboards = None,
|
||||
Some(Value::String(s)) => {
|
||||
vectorcraft_doc::range::parse_range(s, d.artboards.len()).map_err(|e| bad(cmd, e))?;
|
||||
o.artboards = Some(s.trim().to_string());
|
||||
}
|
||||
Some(v) => return Err(bad(cmd, format!("`artboards`: all or a range such as 1, 3-5, not {v}"))),
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
fn json(&self, count: usize) -> Value {
|
||||
json!({
|
||||
"appearance": self.appearance,
|
||||
"size": self.size,
|
||||
"artboards": self.artboards.as_deref().unwrap_or("all"),
|
||||
"includeCanvas": self.include_canvas,
|
||||
"count": count,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Outlines with their layer colours ([`highlights`]).
|
||||
pub type Outlines = Vec<(BezPath, [u8; 3])>;
|
||||
|
||||
/// A Global Edit in progress (per document; not saved, not an undo step).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GlobalEdit {
|
||||
/// The objects edited together, the one selected at the start first, each with the transform
|
||||
/// (a move and a uniform scale) that maps that first object's outline onto its own.
|
||||
pub members: Vec<(NodeId, Affine)>,
|
||||
/// [`highlights`] as of a document revision: the canvas asks every frame.
|
||||
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
|
||||
}
|
||||
|
||||
/// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells
|
||||
/// such outlines apart (kind, fill rule, subpaths and their anchor counts, open or closed).
|
||||
struct Form {
|
||||
tag: Vec<u64>,
|
||||
symbol: Option<String>,
|
||||
points: Vec<Point>,
|
||||
/// The unit box → the object.
|
||||
frame: Affine,
|
||||
}
|
||||
|
||||
impl Form {
|
||||
fn of(n: &Node) -> Option<Self> {
|
||||
let mut tag = vec![];
|
||||
let mut points = vec![];
|
||||
let mut symbol = None;
|
||||
let mut push = |path: &PathData, tag: &mut Vec<u64>| {
|
||||
tag.push(path.subpaths.len() as u64);
|
||||
for sp in &path.subpaths {
|
||||
tag.extend([u64::from(sp.closed), sp.anchors.len() as u64]);
|
||||
points.extend(sp.anchors.iter().flat_map(|a| [a.p, a.h_in, a.h_out]));
|
||||
}
|
||||
};
|
||||
let rule = |r: vectorcraft_geom::FillRule| u64::from(r == vectorcraft_geom::FillRule::EvenOdd);
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule: r, clipping: false, guide: false, .. } => {
|
||||
tag.extend([0, rule(*r)]);
|
||||
push(path, &mut tag);
|
||||
}
|
||||
NodeKind::Compound { children, rule: r } => {
|
||||
tag.extend([1, rule(*r), children.len() as u64]);
|
||||
for c in children {
|
||||
push(c.path_data()?, &mut tag);
|
||||
}
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol: s, xf } => {
|
||||
tag.push(2);
|
||||
symbol = Some(s.clone());
|
||||
points.extend([*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)]);
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
let first = *points.first()?;
|
||||
let b = points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p));
|
||||
let side = b.width().max(b.height());
|
||||
if !(side.is_finite() && side > 1e-9) {
|
||||
return None;
|
||||
}
|
||||
let frame = Affine::translate(b.origin().to_vec2()) * Affine::scale(side);
|
||||
let back = frame.inverse();
|
||||
points.iter_mut().for_each(|p| *p = back * *p);
|
||||
Some(Self { tag, symbol, points, frame })
|
||||
}
|
||||
|
||||
fn same(&self, o: &Form) -> bool {
|
||||
self.tag == o.tag
|
||||
&& self.symbol == o.symbol
|
||||
&& self.points.len() == o.points.len()
|
||||
&& self.points.iter().zip(&o.points).all(|(a, b)| a.distance(*b) < 1e-6)
|
||||
}
|
||||
}
|
||||
|
||||
/// Global Edit supports paths, compound paths and symbol instances; not images, type, linked
|
||||
/// files, objects with an opacity mask, clipping paths or guides (the help page lists images,
|
||||
/// text, masks and links as unsupported).
|
||||
fn supported(n: &Node) -> bool {
|
||||
n.extras().mask.is_none() && Form::of(n).is_some()
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0)
|
||||
}
|
||||
|
||||
/// The members a Global Edit started on the one selected object would take, with `o`: that
|
||||
/// object first, then the others in paint order.
|
||||
fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let [id] = st.selection.objects.as_slice() else { return Err(bad(C, "select one object")) };
|
||||
let key = d.node(*id).ok_or_else(|| bad(C, "nothing selected"))?;
|
||||
let form = match Form::of(key) {
|
||||
Some(f) if supported(key) => f,
|
||||
_ => return Err(bad(C, "Global Edit works on paths, compound paths and symbol instances")),
|
||||
};
|
||||
let symbols = d.symbol_boxes();
|
||||
let size = |n: &Node| n.geometric_bounds_with(&symbols).map(|b| (b.width(), b.height()));
|
||||
let key_size = size(key);
|
||||
let (fill, stroke) = (fill_of(key), stroke_of(key));
|
||||
let boards: Option<Vec<Rect>> = match &o.artboards {
|
||||
None => None,
|
||||
Some(r) => Some(
|
||||
vectorcraft_doc::range::parse_range(r, d.artboards.len())
|
||||
.map_err(|e| bad(C, e))?
|
||||
.into_iter()
|
||||
.filter_map(|i| d.artboards.get(i).map(|a| a.rect))
|
||||
.collect(),
|
||||
),
|
||||
};
|
||||
let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center());
|
||||
let in_scope = |n: &Node| {
|
||||
let Some(b) = n.geometric_bounds_with(&symbols) else { return false };
|
||||
if !d.artboards.iter().any(|a| on(a.rect, b)) {
|
||||
return o.include_canvas;
|
||||
}
|
||||
boards.as_ref().is_none_or(|rs| rs.iter().any(|r| on(*r, b)))
|
||||
};
|
||||
let mut out = vec![(*id, Affine::IDENTITY)];
|
||||
let back = form.frame.inverse();
|
||||
super::select::walk_selectable(d, st.isolation, |n| {
|
||||
if n.id == *id {
|
||||
return false;
|
||||
}
|
||||
match &n.kind {
|
||||
// Look into layers and plain groups (clip groups too: their art, not their clipping path).
|
||||
NodeKind::Layer { .. } => return true,
|
||||
NodeKind::Group { .. } => {
|
||||
let x = n.extras();
|
||||
return x.graph.is_none() && x.shaper.is_none() && x.dimension.is_none() && x.objects_on_path.is_none() && x.trace.is_none();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n))
|
||||
&& (!o.size || matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)))
|
||||
&& (!o.appearance || {
|
||||
let (f2, s2) = (fill_of(n), stroke_of(n));
|
||||
super::select::same_paint(&fill, &f2, true) && super::select::same_paint(&stroke.0, &s2.0, true) && close(stroke.1, s2.1)
|
||||
})
|
||||
&& in_scope(n)
|
||||
{
|
||||
out.push((n.id, f.frame * back));
|
||||
}
|
||||
// Compound paths, symbol instances and the other objects are taken whole.
|
||||
false
|
||||
});
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn can_toggle(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.global_edit.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let [id] = st.selection.objects.as_slice() else {
|
||||
return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into());
|
||||
};
|
||||
match st.doc.node(*id) {
|
||||
Some(n) if supported(n) => Ok(()),
|
||||
_ => Err("Global Edit works on paths, compound paths and symbol instances".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.doc()?.global_edit.is_some() {
|
||||
let st = s.doc_mut()?;
|
||||
st.global_edit = None;
|
||||
st.revision += 1;
|
||||
return Ok(json!({ "active": false }));
|
||||
}
|
||||
let o = s.global_edit_options.with(p, &s.doc()?.doc, C)?;
|
||||
let members = matches(s, &o)?;
|
||||
if members.len() < 2 {
|
||||
return Err(bad(C, "no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again"));
|
||||
}
|
||||
let ids: Vec<u64> = members.iter().map(|(id, _)| id.0).collect();
|
||||
let st = s.doc_mut()?;
|
||||
st.global_edit = Some(GlobalEdit { members, outlines: Default::default() });
|
||||
st.revision += 1;
|
||||
Ok(json!({ "active": true, "count": ids.len(), "ids": ids }))
|
||||
}
|
||||
|
||||
fn set_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let o = s.global_edit_options.with(p, &s.doc()?.doc, OPTIONS)?;
|
||||
s.global_edit_options = o.clone();
|
||||
Ok(o.json(match_count(s)))
|
||||
}
|
||||
|
||||
/// How many objects Start Global Edit would take now with the session's options (the Result(s)
|
||||
/// line of the options): 0 unless one supported object is selected.
|
||||
pub fn match_count(s: &Session) -> usize {
|
||||
match s.active() {
|
||||
Some(st) if st.global_edit.is_none() => matches(s, &s.global_edit_options).map_or(0, |m| m.len()),
|
||||
Some(st) => st.global_edit.as_ref().map_or(0, |g| g.members.len()),
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `id` there, shown and unlocked, with every layer and group it is in?
|
||||
fn editable(d: &Document, id: NodeId) -> bool {
|
||||
d.ancestry(id).is_some_and(|a| a.iter().all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template())))
|
||||
}
|
||||
|
||||
/// After the document of `st` was put back to an earlier one (Undo, Redo, a cancelled interaction
|
||||
/// or undo group, a failed or panicked command, a preview starting again, Discard Empty Type): the
|
||||
/// members it lacks (or no longer supports) leave the Global Edit, so that an object made later
|
||||
/// under a freed id is never edited; with fewer than two left, Global Edit ends.
|
||||
pub(crate) fn follow_history(st: &mut crate::DocState) {
|
||||
let Some(ge) = &mut st.global_edit else { return };
|
||||
let d = &st.doc;
|
||||
ge.members.retain(|(id, _)| d.node(*id).is_some_and(supported));
|
||||
if ge.members.len() < 2 {
|
||||
st.global_edit = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// What an edit changed about a member: what [`propagate`] gives the others.
|
||||
#[derive(Default)]
|
||||
struct Changed {
|
||||
outline: bool,
|
||||
/// The member's appearance before and after the edit, when it changed.
|
||||
appearance: Option<[Shared<Appearance>; 2]>,
|
||||
opacity: bool,
|
||||
blend: bool,
|
||||
isolate: bool,
|
||||
knockout: bool,
|
||||
knockout_shape: bool,
|
||||
}
|
||||
|
||||
impl Changed {
|
||||
fn between(a: &Node, b: &Node) -> Self {
|
||||
Self {
|
||||
outline: a.kind != b.kind || a.bbox_angle != b.bbox_angle,
|
||||
appearance: (a.appearance != b.appearance).then(|| [a.appearance.clone(), b.appearance.clone()]),
|
||||
opacity: a.opacity != b.opacity,
|
||||
blend: a.blend != b.blend,
|
||||
isolate: a.isolate != b.isolate,
|
||||
knockout: a.knockout != b.knockout,
|
||||
knockout_shape: a.knockout_shape != b.knockout_shape,
|
||||
}
|
||||
}
|
||||
|
||||
fn any(&self) -> bool {
|
||||
self.outline || self.appearance.is_some() || self.opacity || self.blend || self.isolate || self.knockout || self.knockout_shape
|
||||
}
|
||||
|
||||
/// Give `n` what changed, from `model` (the changed member placed on `n`).
|
||||
fn apply(&self, model: Node, n: &mut Node) {
|
||||
if self.outline {
|
||||
n.kind = model.kind;
|
||||
n.bbox_angle = model.bbox_angle;
|
||||
}
|
||||
if let Some([a, b]) = &self.appearance {
|
||||
give_appearance(a, b, &model.appearance, &mut n.appearance);
|
||||
}
|
||||
if self.opacity {
|
||||
n.opacity = model.opacity;
|
||||
}
|
||||
if self.blend {
|
||||
n.blend = model.blend;
|
||||
}
|
||||
if self.isolate {
|
||||
n.isolate = model.isolate;
|
||||
}
|
||||
if self.knockout {
|
||||
n.knockout = model.knockout;
|
||||
}
|
||||
if self.knockout_shape {
|
||||
n.knockout_shape = model.knockout_shape;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set each field of `$n` that differs between `$a` and `$b` to the binding of the same name.
|
||||
macro_rules! give_fields {
|
||||
($a:ident, $b:ident, $n:ident: $($f:ident),+) => {
|
||||
$(
|
||||
if $a.$f != $b.$f {
|
||||
$n.$f = Clone::clone($f);
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
/// Give `n` what changed about the model's appearance from `a` (before the edit) to `b` (after),
|
||||
/// with the values of `m` (`b` placed on `n`'s object); the module doc gives the rules.
|
||||
fn give_appearance(a: &Appearance, b: &Appearance, m: &Appearance, n: &mut Shared<Appearance>) {
|
||||
let Appearance { items, effects, contents_index } = m;
|
||||
if a.effects != b.effects || a.contents_index != b.contents_index {
|
||||
let n = &mut **n;
|
||||
give_fields!(a, b, n: effects, contents_index);
|
||||
}
|
||||
if a.items == b.items {
|
||||
return;
|
||||
}
|
||||
let kinds = |v: &[AppearanceItem]| v.iter().map(AppearanceItem::is_fill).collect::<Vec<_>>();
|
||||
if kinds(&a.items) == kinds(&b.items) {
|
||||
// Fills and strokes kept in order: each changed one goes to the member's of its kind and
|
||||
// rank.
|
||||
for (k, ((p, q), mq)) in a.items.iter().zip(&b.items).zip(items).enumerate() {
|
||||
if p == q {
|
||||
continue;
|
||||
}
|
||||
let rank = a.items.iter().take(k).filter(|x| x.is_fill() == p.is_fill()).count();
|
||||
if let Some(t) = n.items.iter_mut().filter(|x| x.is_fill() == p.is_fill()).nth(rank) {
|
||||
give_item(p, q, mq, t);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// One item added (`grew`) or removed at `at`, the others kept in order; the member must hold
|
||||
// the model's former kinds in order.
|
||||
let one = |long: &[AppearanceItem], short: &[AppearanceItem]| {
|
||||
if long.len() != short.len() + 1 {
|
||||
return None;
|
||||
}
|
||||
let at = long.iter().zip(short).position(|(x, y)| x != y).unwrap_or(short.len());
|
||||
let mut rest = kinds(long);
|
||||
rest.remove(at);
|
||||
(rest == kinds(short)).then_some(at)
|
||||
};
|
||||
let step = match (one(&b.items, &a.items), one(&a.items, &b.items)) {
|
||||
(Some(at), _) => Some((at, true)),
|
||||
(None, Some(at)) => Some((at, false)),
|
||||
_ => None,
|
||||
};
|
||||
match step {
|
||||
Some((at, grew)) if kinds(&n.items) == kinds(&a.items) => {
|
||||
let n = &mut n.items;
|
||||
for (i, (p, t)) in a.items.iter().zip(n.iter_mut()).enumerate() {
|
||||
// The model's item after the edit that was `p` before it.
|
||||
let j = match (grew, i < at) {
|
||||
(_, true) => i,
|
||||
(true, false) => i + 1,
|
||||
(false, false) if i == at => continue,
|
||||
(false, false) => i - 1,
|
||||
};
|
||||
if let (Some(q), Some(mq)) = (b.items.get(j), items.get(j))
|
||||
&& p != q
|
||||
{
|
||||
give_item(p, q, mq, t);
|
||||
}
|
||||
}
|
||||
match (grew, items.get(at)) {
|
||||
(true, Some(new)) => n.insert(at.min(n.len()), new.clone()),
|
||||
(false, _) if at < n.len() => {
|
||||
n.remove(at);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => n.items = items.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the member's fill or stroke `n` the settings of the model's that changed from `a` to `b`,
|
||||
/// with the values of `m` (`b` placed on the member). A stroke's pen pressure stays its own.
|
||||
fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut AppearanceItem) {
|
||||
use AppearanceItem::{Fill, Stroke};
|
||||
match (a, b, m, n) {
|
||||
(Fill(a), Fill(b), Fill(m), Fill(n)) => {
|
||||
let FillLayer { paint, opacity, blend, visible, effects, overprint } = m;
|
||||
give_fields!(a, b, n: paint, opacity, blend, visible, effects, overprint);
|
||||
}
|
||||
(Stroke(a), Stroke(b), Stroke(m), Stroke(n)) => {
|
||||
let StrokeLayer {
|
||||
paint,
|
||||
width,
|
||||
cap,
|
||||
join,
|
||||
miter_limit,
|
||||
align,
|
||||
dash,
|
||||
start_arrow,
|
||||
end_arrow,
|
||||
arrow_scale,
|
||||
profile,
|
||||
brush,
|
||||
opacity,
|
||||
blend,
|
||||
visible,
|
||||
effects,
|
||||
arrow_align,
|
||||
overprint,
|
||||
gradient_mode,
|
||||
pressure: _,
|
||||
} = m;
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the children of a copy placed on another object ids of that object's: its own children's
|
||||
/// in order, new ids for any more and for everything deeper.
|
||||
fn renumber(children: &mut [std::sync::Arc<Node>], own: &[NodeId], d: &mut Document) {
|
||||
for (i, c) in children.iter_mut().enumerate() {
|
||||
let c = std::sync::Arc::make_mut(c);
|
||||
c.id = own.get(i).copied().unwrap_or_else(|| d.alloc_id());
|
||||
if let Some(ch) = c.children_mut() {
|
||||
renumber(ch, &[], d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After an edit made while Global Edit is on (`before` → `d`): the first member selected before
|
||||
/// or after the edit that it changed is the model, and every other member that is shown and
|
||||
/// unlocked gets what changed about it, placed by the members' transforms. → the members it
|
||||
/// changed so (which [`Session::edit`] checks stay within the canvas, as it checks the selection).
|
||||
pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, selected: [&[NodeId]; 2]) -> Vec<NodeId> {
|
||||
let model = ge.members.iter().filter(|(id, _)| selected.iter().any(|s| s.contains(id))).find_map(|(id, xf)| {
|
||||
let (a, b) = (before.node(*id)?, d.node(*id)?);
|
||||
if std::ptr::eq(a, b) {
|
||||
return None;
|
||||
}
|
||||
let changed = Changed::between(a, b);
|
||||
changed.any().then(|| (*id, *xf, changed, b.clone()))
|
||||
});
|
||||
let Some((model_id, model_xf, changed, model)) = model else { return vec![] };
|
||||
let back = model_xf.inverse();
|
||||
let mut edited = vec![];
|
||||
for (id, xf) in &ge.members {
|
||||
if *id == model_id || !editable(d, *id) {
|
||||
continue;
|
||||
}
|
||||
let mut placed = model.clone();
|
||||
placed.transform(*xf * back, Scaling::default());
|
||||
if changed.outline {
|
||||
let own: Vec<NodeId> = d.node(*id).and_then(Node::children).map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default();
|
||||
if let Some(ch) = placed.children_mut() {
|
||||
renumber(ch, &own, d);
|
||||
}
|
||||
}
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
changed.apply(placed, n);
|
||||
edited.push(*id);
|
||||
}
|
||||
}
|
||||
edited
|
||||
}
|
||||
|
||||
/// The outlines of the members of the active document's Global Edit that are not selected, in
|
||||
/// their layer's colour: the canvas highlights them while Global Edit is on.
|
||||
pub fn highlights(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let Some(ge) = &st.global_edit else { return vec![] };
|
||||
if let Some((rev, out)) = &*ge.outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
{
|
||||
return out.clone();
|
||||
}
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let out: Vec<_> = ge
|
||||
.members
|
||||
.iter()
|
||||
.filter(|(id, _)| !st.selection.contains(*id))
|
||||
.filter_map(|(id, _)| {
|
||||
let n = st.doc.node(*id)?;
|
||||
let path = match n.stroke_path() {
|
||||
Some(p) => p,
|
||||
None => n.geometric_bounds_with(&symbols)?.to_path(0.1),
|
||||
};
|
||||
Some((path, st.doc.layer_color(*id)))
|
||||
})
|
||||
.collect();
|
||||
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
|
||||
out
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The Gradient panel and the Gradient tool: in-place gradient edits and the gradient vector.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::appearance::stroke_paint_bounds;
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, StrokeGradientMode};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), angle?: deg, aspect?: %, reverse?: bool, item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -60,7 +60,7 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => return Err(bad(C, "missing `index` (a stop index, or null to clear)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let i = v.as_u64().ok_or_else(|| bad(C, "`index` must be a whole number or null"))? as usize;
|
||||
let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?;
|
||||
let n = active_gradient(s).ok_or_else(|| bad(C, "the active paint is not a gradient"))?.gradient.stops.len();
|
||||
if i >= n {
|
||||
return Err(bad(C, format!("no stop {i} (the gradient has {n})")));
|
||||
@@ -105,6 +105,14 @@ fn parse_kind(k: &str) -> Parsed<GradientKind> {
|
||||
GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, freeform)"))
|
||||
}
|
||||
|
||||
/// The `method` param of `p`, if given: how the colours between the stops mix.
|
||||
fn method_param(p: &Value) -> Parsed<Option<GradientMethod>> {
|
||||
match p.get("method") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_str().and_then(GradientMethod::parse).map(Some).ok_or_else(|| "`method` must be classic or perceptual".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` (params holding `stops`) with each stop that names a `swatch` resolved through `d`
|
||||
/// ([`swatch_solid`]): a global or spot colour or a tint swatch gives the stop its colour, link and
|
||||
/// tint, a process colour just its colour. A stop linked to a swatch that no longer exists keeps
|
||||
@@ -117,7 +125,12 @@ pub(crate) fn link_stops(d: &Document, v: &Value) -> Parsed<Value> {
|
||||
if d.swatch(&name).is_none() && st.get("color").is_some() {
|
||||
continue;
|
||||
}
|
||||
let tint = st.get("tint").and_then(Value::as_f64).map(|t| (t / 100.0).clamp(0.0, 1.0) as f32);
|
||||
let tint = st
|
||||
.get("tint")
|
||||
.filter(|v| !v.is_null())
|
||||
.map(|v| v.as_f64().ok_or_else(|| format!("stop {i}: `{k}` must be a number", k = "tint")))
|
||||
.transpose()?;
|
||||
let tint = tint.map(|t| (t / 100.0).clamp(0.0, 1.0) as f32);
|
||||
let Paint::Solid { color, swatch, tint } = swatch_solid(d, &name, tint).map_err(|e| format!("stop {i}: {e}"))? else {
|
||||
continue;
|
||||
};
|
||||
@@ -137,6 +150,47 @@ pub(crate) fn link_stops(d: &Document, v: &Value) -> Parsed<Value> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Stop colors to store, one per stop of `g` (params holding `stops`, before [`link_stops`]): the
|
||||
/// color a stop gives and the color the document stores it as when it is new to the gradient, an
|
||||
/// RGB color in a CMYK document becoming CMYK through the color settings
|
||||
/// ([`super::paint::new_color`], with `p`'s `keepModel`). `None` for a stop that names a swatch,
|
||||
/// which gives its color in the swatch's model, and for a color stored as given.
|
||||
pub(crate) type StopColors = Vec<Option<(vectorcraft_color::Color, vectorcraft_color::Color)>>;
|
||||
|
||||
/// The [`StopColors`] of `g`'s stops.
|
||||
pub(crate) fn stop_colors(s: &Session, p: &Value, g: &Value) -> StopColors {
|
||||
let stops = g.get("stops").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
let stored = |st: &Value| {
|
||||
let c = st.get("color").and_then(color_value).filter(|_| str_param(st, "swatch").is_none())?;
|
||||
let to = super::paint::new_color(s, p, c);
|
||||
(to != c).then_some((c, to))
|
||||
};
|
||||
stops.iter().map(stored).collect()
|
||||
}
|
||||
|
||||
/// `g` (params holding `stops`, resolved by [`link_stops`] in their order) for an edit of paint
|
||||
/// `old`, with each stop's color replaced by the one `stored` ([`stop_colors`]) gives for it,
|
||||
/// unless `old`'s stops already have that color. A freeform gradient's points are colored from the
|
||||
/// stored colors, and a stop list sent back with only its positions changed keeps its colors.
|
||||
pub(crate) fn with_stored_stops<'a>(g: &'a Value, old: &Paint, stored: &StopColors) -> std::borrow::Cow<'a, Value> {
|
||||
use std::borrow::Cow;
|
||||
if stored.iter().all(Option::is_none) {
|
||||
return Cow::Borrowed(g);
|
||||
}
|
||||
let had = |c: &vectorcraft_color::Color| matches!(old, Paint::Gradient(o) if o.gradient.stops.iter().any(|st| st.color == *c));
|
||||
let mut v = g.clone();
|
||||
let Some(stops) = v.get_mut("stops").and_then(Value::as_array_mut) else { return Cow::Borrowed(g) };
|
||||
for (st, sc) in stops.iter_mut().zip(stored) {
|
||||
let Some((from, to)) = sc.filter(|(from, _)| !had(from)) else { continue };
|
||||
if st.get("color").and_then(color_value) == Some(from)
|
||||
&& let Some(o) = st.as_object_mut()
|
||||
{
|
||||
o.insert("color".into(), color_json(&to));
|
||||
}
|
||||
}
|
||||
Cow::Owned(v)
|
||||
}
|
||||
|
||||
/// Parse `stops` params: at least two, each with a numeric `offset` (clamped to 0..1) and a valid
|
||||
/// `color`; `opacity` is 0..1 (values above 1 are percentages) and `midpoint` is clamped to the
|
||||
/// diamond's range; `swatch` and `tint` (%) keep a stop's link as given (resolve them first with
|
||||
@@ -178,7 +232,12 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
}
|
||||
let kind = str_param(g, "kind").map(parse_kind).transpose()?.unwrap_or_default();
|
||||
let stops = g.get("stops").map(parse_stops).transpose()?.unwrap_or_else(|| Gradient::default().stops);
|
||||
let mut gp = GradientPaint::new(Gradient { kind, stops });
|
||||
let mut gp = GradientPaint::new(Gradient::new(kind, stops));
|
||||
gp.gradient.dither = match g.get("dither") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => v.as_bool().ok_or("`dither` must be true or false")?,
|
||||
};
|
||||
gp.gradient.method = method_param(g)?.unwrap_or_default();
|
||||
gp.angle = f64_or(g, "angle", 0.0);
|
||||
gp.swatch = str_param(g, "swatch").map(str::to_string);
|
||||
let geom = GeomEdit::parse(g)?;
|
||||
@@ -273,6 +332,12 @@ pub(crate) fn apply_gradient_edit_in(
|
||||
// Midpoints mirrored with their segments.
|
||||
gp.gradient.reverse();
|
||||
}
|
||||
if let Some(d) = p.get("dither").and_then(Value::as_bool) {
|
||||
gp.gradient.dither = d;
|
||||
}
|
||||
if let Some(m) = method_param(p)? {
|
||||
gp.gradient.method = m;
|
||||
}
|
||||
// Angle and aspect edits keep the focal point in its place in the extent ellipse.
|
||||
let before = gp.geom;
|
||||
if let Some(a) = p.get("angle").and_then(Value::as_f64) {
|
||||
@@ -331,7 +396,9 @@ pub(crate) fn apply_gradient_edit_in(
|
||||
fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paint.editGradient";
|
||||
let item = item_target(s, p, C)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, C)?;
|
||||
check_switches(p, &["reverse", "dither"], C)?;
|
||||
check_numbers(p, &["angle"], C)?;
|
||||
let item = item.of_kind(s, !stroke);
|
||||
let ids = item.targets(s, p)?;
|
||||
// How the gradient lies on a stroke (the panel's Stroke buttons).
|
||||
@@ -340,11 +407,17 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) if !stroke => return Err(bad(C, "`strokeMode` applies to strokes (stroke: true)")),
|
||||
Some(m) => Some(StrokeGradientMode::parse(m).ok_or_else(|| bad(C, format!("strokeMode must be within|along|across, got {m}")))?),
|
||||
};
|
||||
if p.get("dither").and_then(Value::as_bool).is_some() && stroke {
|
||||
return Err(bad(C, "`dither` applies to gradient fills (stroke: false)"));
|
||||
}
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
// New RGB stop colors take the document's model; those of the swatches the stops name don't.
|
||||
let stored = stop_colors(s, p, p);
|
||||
// Stops naming swatches take their colours from them.
|
||||
let p = &link_stops(&s.doc()?.doc, p).map_err(|e| bad(C, e))?;
|
||||
// Validate against the defaults first so bad params fail without touching the document.
|
||||
let default_paint = if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() };
|
||||
let new_default = apply_gradient_edit(&default_paint, p, None).map_err(|e| bad(C, e))?;
|
||||
let new_default = apply_gradient_edit(&default_paint, &with_stored_stops(p, &default_paint, &stored), None).map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
@@ -353,7 +426,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let lb = t.local_bounds();
|
||||
for r in &mut t.runs {
|
||||
let (cur, b) = run_paint_mut(r, stroke, lb);
|
||||
*cur = apply_gradient_edit(cur, p, Some(b)).map_err(|e| bad(C, e))?;
|
||||
*cur = apply_gradient_edit(cur, &with_stored_stops(p, cur, &stored), Some(b)).map_err(|e| bad(C, e))?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -364,7 +437,8 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(f) => f,
|
||||
None => &|_| true,
|
||||
};
|
||||
let np = apply_gradient_edit_in(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), p, b, inside).map_err(|e| bad(C, e))?;
|
||||
let old = n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None);
|
||||
let np = apply_gradient_edit_in(old, &with_stored_stops(p, old, &stored), b, inside).map_err(|e| bad(C, e))?;
|
||||
n.appearance.set_paint_at(index, !stroke, np);
|
||||
if let Some(m) = mode
|
||||
&& let Some(st) = n.appearance.stroke_at_mut(index)
|
||||
@@ -509,10 +583,12 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let p = &p;
|
||||
let item = item_target(s, p, C)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, C)?;
|
||||
let item = item.of_kind(s, !stroke);
|
||||
let targets = match item {
|
||||
ItemTarget::Top => leaf_targets(s, &ids_param(p, "ids").map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?)?,
|
||||
ItemTarget::Top => {
|
||||
leaf_targets(s, &super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?)?
|
||||
}
|
||||
_ => item.targets(s, p)?,
|
||||
};
|
||||
if targets.is_empty() {
|
||||
|
||||
+25
-4728
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) const LABEL_SIZE: f64 = 9.0;
|
||||
|
||||
/// Most tick marks per division (Graph Type › Tick Marks), and most category tick marks a graph draws.
|
||||
pub(super) const MAX_TICK_MARKS: usize = 20;
|
||||
|
||||
pub(super) const MAX_CATEGORY_TICKS: usize = 10_000;
|
||||
|
||||
/// Longest axis label prefix or suffix (Graph Type › Add Labels).
|
||||
const MAX_AFFIX: usize = 64;
|
||||
|
||||
/// An axis label prefix or suffix: one line (no control characters or line separators), at most [`MAX_AFFIX`] long.
|
||||
pub(super) fn one_line(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_control() && !matches!(c, '\u{2028}' | '\u{2029}')).take(MAX_AFFIX).collect()
|
||||
}
|
||||
|
||||
/// A count parameter: a whole number, also as the float a dialog sends back (3.0), at most `max`.
|
||||
pub(super) fn count_param(p: &Value, key: &str, max: u64) -> Option<usize> {
|
||||
let v = p.get(key)?;
|
||||
let n = v.as_u64().or_else(|| v.as_f64().filter(|x| x.is_finite() && *x >= 0.0).map(|x| x.round().min(max as f64) as u64))?;
|
||||
usize::try_from(n.min(max)).ok()
|
||||
}
|
||||
|
||||
/// A "nice" axis: (min, max, step).
|
||||
pub(super) fn nice_axis(lo: f64, hi: f64, ticks: usize) -> (f64, f64, f64) {
|
||||
let (lo, hi) = if (hi - lo).abs() < 1e-12 { (lo.min(0.0), lo.max(0.0) + 1.0) } else { (lo, hi) };
|
||||
let n = if ticks == 0 { 5 } else { ticks.clamp(1, 100) } as f64;
|
||||
let raw = (hi - lo) / n;
|
||||
let mag = 10f64.powf(raw.log10().floor());
|
||||
let step = [1.0, 2.0, 2.5, 5.0, 10.0].iter().map(|m| m * mag).find(|s| *s >= raw - 1e-12).unwrap_or(10.0 * mag);
|
||||
((lo / step).floor() * step, (hi / step).ceil() * step, step)
|
||||
}
|
||||
|
||||
/// A value axis: with both `min` and `max` set (Graph Type › Tick Values › Override Calculated Values), exactly that
|
||||
/// range split into `ticks` divisions (5 when automatic); otherwise a nice axis around the data, using whichever bound
|
||||
/// was given.
|
||||
pub(super) fn value_axis(ticks: usize, axis_min: Option<f64>, axis_max: Option<f64>, lo: f64, hi: f64) -> (f64, f64, f64) {
|
||||
match (axis_min, axis_max) {
|
||||
(Some(min), Some(max)) if max > min && (max - min).is_finite() => {
|
||||
let n = if ticks == 0 { 5 } else { ticks.clamp(1, 100) } as f64;
|
||||
(min, max, (max - min) / n)
|
||||
}
|
||||
_ => {
|
||||
// An override too wide for f64 (or NaN) gives a non-finite axis, which would reach `clamp` with NaN bounds
|
||||
// and panic: fall back to the data, then to 0..1.
|
||||
let finite = |(a, b, s): (f64, f64, f64)| a.is_finite() && b.is_finite() && s.is_finite() && b > a && s > 0.0;
|
||||
[nice_axis(axis_min.unwrap_or(lo), axis_max.unwrap_or(hi), ticks), nice_axis(lo, hi, ticks)]
|
||||
.into_iter()
|
||||
.find(|&a| finite(a))
|
||||
.unwrap_or((0.0, 1.0, 0.2))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tick values from `lo` to `hi` every `step`, both ends included: counted, not accumulated, so the last tick
|
||||
/// lands on `hi` and a step too small for the range (or not finite) can't loop forever. At most 1000 ticks.
|
||||
pub(super) fn tick_values(lo: f64, hi: f64, step: f64) -> Vec<f64> {
|
||||
let n = ((hi - lo) / step).round();
|
||||
if !(lo.is_finite() && step.is_finite() && step > 0.0 && n.is_finite() && n >= 0.0) {
|
||||
return vec![];
|
||||
}
|
||||
(0..=(n as usize).min(1000)).map(|i| lo + i as f64 * step).collect()
|
||||
}
|
||||
Loaded 100 of 1615 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user