VectorCraft: An open-source, vector art tool written by scratch in pure Rust
Merge main into feat/native-save-precision
dotCooCoo5d5b775e27ad
diff --cc crates/doc/src/document_ext.rsindex 000000000,9d17f689a..37fd869c3mode 000000,100644..100644--- a/crates/doc/src/document_ext.rs+++ b/crates/doc/src/document_ext.rs@@@ -1,0 -1,285 +1,389 @@@+ use super::graphic_style::GraphicStyle;+ use super::limits::MAX_NEXT_ID;+ use super::records::{ImageBlob, SavedSelection, SavedView};+ use super::*;++ impl Document {+ /// The pixels image `im` shows: its own ([`ImageObject::pixels`]) or this document's.+ pub fn image_blob<'a>(&'a self, im: &'a ImageObject) -> Option<&'a ImageBlob> {+ im.pixels.as_deref().or_else(|| self.images.get(&im.key))+ }++ /// Take the pixels the images in `n` (its opacity masks' art included) hold themselves (art+ /// made outside a document) into [`Self::images`]: under the image's key, or a free one when+ /// the key shows other pixels.+ pub fn adopt_pixels(&mut self, n: &mut Node) {+ // Only what holds such pixels is copied out of the art it shares.+ fn holds(n: &Node) -> bool {+ matches!(&n.kind, NodeKind::Image(im) if im.pixels.is_some())+ || n.extras().mask.as_ref().is_some_and(|m| holds(&m.art))+ || n.children().into_iter().flatten().any(|c| holds(c))+ }+ if let NodeKind::Image(im) = &mut n.kind {+ self.adopt_image_pixels(im);+ }+ if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut())+ && holds(&m.art)+ {+ self.adopt_pixels(Arc::make_mut(&mut m.art));+ }+ for c in n.children_mut().into_iter().flatten() {+ if holds(c) {+ self.adopt_pixels(Arc::make_mut(c));+ }+ }+ }++ pub(crate) fn adopt_image_pixels(&mut self, im: &mut ImageObject) {+ let Some(blob) = im.pixels.take() else { return };+ let mut key = im.key.clone();+ let mut i = 1;+ while self.images.get(&key).is_some_and(|b| b.bytes != blob.bytes) {+ i += 1;+ key = format!("{}-{i}", im.key);+ }+ self.images.entry(key.clone()).or_insert_with(|| (*blob).clone());+ im.key = key;+ }++ /// Saved selections as a file gives them, made safe to list and recall: at most+ /// [`SavedSelection::MAX`], each with a clean, unique name and naming objects this document+ /// has, each once. (An id it doesn't have would select whatever object takes that id later.)+ pub fn tidy_saved_selections(&mut self) {+ if self.saved_selections.is_empty() {+ return;+ }+ let mut ids = std::collections::HashSet::new();+ self.walk(|n| {+ ids.insert(n.id);+ });+ let mut kept: Vec<SavedSelection> = vec![];+ for s in std::mem::take(&mut self.saved_selections) {+ if kept.len() >= SavedSelection::MAX {+ break;+ }+ let Some(name) = SavedSelection::clean_name(&s.name) else { continue };+ if kept.iter().any(|k| k.name == name) {+ continue;+ }+ let mut seen = std::collections::HashSet::new();+ let objects = s.objects.into_iter().filter(|id| ids.contains(id) && seen.insert(*id)).collect();+ kept.push(SavedSelection { name, objects });+ }+ self.saved_selections = kept.into();+ }++ /// Saved views as a file gives them, made safe to list and go to: at most [`SavedView::MAX`],+ /// each with a clean, unique name, a finite centre and a finite, positive zoom (a rotation+ /// that isn't finite becomes 0°).+ pub fn tidy_views(&mut self) {+ if self.views.is_empty() {+ return;+ }+ let mut kept: Vec<SavedView> = vec![];+ for v in std::mem::take(&mut self.views) {+ if kept.len() >= SavedView::MAX {+ break;+ }+ let Some(name) = SavedView::clean_name(&v.name) else { continue };+ if !v.is_usable() || kept.iter().any(|k| k.name == name) {+ continue;+ }+ let rotation = if v.rotation.is_finite() { v.rotation } else { 0.0 };+ kept.push(SavedView { name, rotation, ..v });+ }+ self.views = kept;+ }++ /// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the+ /// mask already holds (the engine syncs it after every edit).+ pub fn drop_edit_modes(&mut self) {+ if let Some(me) = self.mask_edit.take() {+ self.layers.retain(|l| l.id != me.layer);+ }+ }++ /// The document as saved and exported: without the opacity-mask editing layer. Borrowed when+ /// no mask is being edited. (Pattern editing is saved: its tile layer holds unapplied edits.)+ pub fn without_edit_modes(&self) -> std::borrow::Cow<'_, Document> {+ if self.mask_edit.is_none() {+ return std::borrow::Cow::Borrowed(self);+ }+ let mut d = self.clone();+ d.drop_edit_modes();+ std::borrow::Cow::Owned(d)+ }++++ /// Round every path's anchors and handles to `decimals` decimal places: path objects (with++ /// Live Corners' uncut outlines), blend spines, envelopes' top-object outlines and Intertwine++ /// areas, in the layers, symbol definitions, graph designs, pattern swatches (the one being++ /// edited included), opacity masks and the brushes kept as foreign data. Colors, transforms,++ /// opacity, live shapes' own sizes, meshes and type (its frames and paths included) are left++ /// as they are.++ pub fn round_geometry(&mut self, decimals: u8) {++ let scale = 10f64.powi(i32::from(decimals));++ let round = |v: f64| {++ let r = (v * scale).round() / scale;++ if !r.is_finite() {++ v++ } else if r == 0.0 {++ // `-0.0` is written as `0.0`.++ 0.0++ } else {++ r++ }++ };++ let round_path = |path: &mut vectorcraft_geom::PathData| {++ for a in path.subpaths.iter_mut().flat_map(|s| s.anchors.iter_mut()) {++ for p in [&mut a.p, &mut a.h_in, &mut a.h_out] {++ *p = Point::new(round(p.x), round(p.y));++ }++ }++ };++ let mut fix = |n: &mut Node| {++ match &mut n.kind {++ NodeKind::Path { path, live, .. } => {++ round_path(path);++ // Live Corners' uncut outline.++ if let Some(LiveShape::Path { base, .. }) = live.as_deref_mut() {++ round_path(base);++ }++ }++ NodeKind::Blend { spec, .. } => {++ if let Some(spine) = &mut spec.spine {++ round_path(spine);++ }++ }++ NodeKind::Envelope { kind, .. } => {++ if let EnvelopeKind::TopObject { path } = kind.as_mut() {++ round_path(path);++ }++ }++ _ => {}++ }++ if let Some(area) = n.extras_if_any().and_then(|e| e.intertwine.as_deref_mut()) {++ round_path(area);++ }++ };++ let roots = self++ .layers++ .iter_mut()++ .chain(self.symbols.iter_mut().map(|s| &mut s.art))++ .chain(self.graph_designs.iter_mut().map(|g| &mut g.art))++ .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))++ .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));++ for root in roots {++ placed_document::each_mut(Arc::make_mut(root), &mut fix);++ }++ if self.unknown.contains_key("brushes")++ && let Some(brushes) = self.unknown.get_mut("brushes")++ {++ round_json_paths(brushes, &round);++ }++ }++}++++/// Round with `round` the anchors of the paths in `v`, nodes in their file form kept as JSON: every++/// `{"subpaths": [{"anchors": [{"p", "in", "out"}]}]}` outside type (`{"type": "text"}`), as++/// [`Document::round_geometry`] rounds the nodes it holds.++fn round_json_paths(v: &mut serde_json::Value, round: &impl Fn(f64) -> f64) {++ use serde_json::Value;++ match v {++ Value::Object(o) => {++ if o.get("type").and_then(Value::as_str) == Some("text") {++ return;++ }++ if let Some(subpaths) = o.get_mut("subpaths").and_then(Value::as_array_mut) {++ let anchors = subpaths.iter_mut().filter_map(|s| s.get_mut("anchors").and_then(Value::as_array_mut)).flatten();++ for a in anchors.filter_map(Value::as_object_mut) {++ let points = a.iter_mut().filter(|(k, _)| matches!(k.as_str(), "p" | "in" | "out")).filter_map(|(_, v)| v.as_array_mut());++ for xy in points {++ for n in xy.iter_mut().filter(|n| n.is_f64()) {++ if let Some(r) = n.as_f64().and_then(|x| serde_json::Number::from_f64(round(x))) {++ *n = Value::Number(r);++ }++ }++ }++ }++ }++ for c in o.values_mut() {++ round_json_paths(c, round);++ }++ }++ Value::Array(a) => {++ for c in a {++ round_json_paths(c, round);++ }++ }++ _ => {}++ }+ }++ /// Graphic styles.+ impl Document {+ /// Index of the graphic style named `name`.+ pub fn graphic_style_index(&self, name: &str) -> Option<usize> {+ self.graphic_styles.iter().position(|g| g.name == name)+ }++ /// The graphic style named `name`.+ pub fn graphic_style(&self, name: &str) -> Option<&GraphicStyle> {+ self.graphic_styles.iter().find(|g| g.name == name)+ }++ /// The graphic style with id `id` (0 never matches).+ pub fn graphic_style_by_id(&self, id: u32) -> Option<&GraphicStyle> {+ self.graphic_styles.iter().find(|g| g.id != 0 && g.id == id)+ }++ /// An id no graphic style has.+ pub fn next_graphic_style_id(&self) -> u32 {+ free_id(self.graphic_styles.iter().map(|g| g.id))+ }++ /// The id of graphic style `index`, assigning one if it has none yet.+ pub fn graphic_style_id(&mut self, index: usize) -> u32 {+ if self.graphic_styles[index].id == 0 {+ self.graphic_styles[index].id = self.next_graphic_style_id();+ }+ self.graphic_styles[index].id+ }++ /// The default name of a new graphic style: the first free "Graphic Style N", N counting on+ /// from the number of styles.+ pub fn new_graphic_style_name(&self) -> String {+ (self.graphic_styles.len() + 1..).map(|i| format!("Graphic Style {i}")).find(|n| self.graphic_style(n).is_none()).unwrap_or_default()+ }++ /// `base`, or the first free "`base` N" (N from 2) when a symbol already has that name.+ pub fn unique_symbol_name(&self, base: &str) -> String {+ let taken = |n: &str| self.symbols.iter().any(|s| s.name == n);+ if !taken(base) {+ return base.to_string();+ }+ (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string())+ }++ /// Symbol Options › Registration for `name` (default: centre).+ pub fn symbol_registration(&self, name: &str) -> SymbolRegistration {+ self.unknown+ .get(SYMBOL_REGISTRATION)+ .and_then(|m| m.get(name))+ .and_then(|v| v.as_u64())+ .and_then(SymbolRegistration::from_u64)+ .unwrap_or_default()+ }++ /// Set or clear (when centre) the registration point stored for `name`.+ pub fn set_symbol_registration(&mut self, name: &str, reg: SymbolRegistration) {+ let m = self.unknown.entry(SYMBOL_REGISTRATION.to_string()).or_insert_with(|| serde_json::json!({}));+ let Some(o) = m.as_object_mut() else { return };+ if reg.is_center() {+ o.remove(name);+ if o.is_empty() {+ self.unknown.remove(SYMBOL_REGISTRATION);+ }+ } else {+ o.insert(name.into(), serde_json::json!(reg.0));+ }+ }++ /// Move the stored registration when a symbol is renamed.+ pub fn rename_symbol_registration(&mut self, from: &str, to: &str) {+ if from == to {+ return;+ }+ let reg = self.symbol_registration(from);+ self.set_symbol_registration(from, SymbolRegistration::CENTER);+ self.set_symbol_registration(to, reg);+ }++ /// Symbol Options › Export Type for `name` (default: Movie Clip).+ pub fn symbol_export_type(&self, name: &str) -> SymbolExportType {+ self.unknown.get(SYMBOL_EXPORT_TYPE).and_then(|m| m.get(name)).and_then(SymbolExportType::from_value).unwrap_or_default()+ }++ /// Set or clear (when Movie Clip, the default) the export type stored for `name`.+ pub fn set_symbol_export_type(&mut self, name: &str, kind: SymbolExportType) {+ if kind.is_default() {+ self.clear_symbol_export_type(name);+ return;+ }+ let m = self.unknown.entry(SYMBOL_EXPORT_TYPE.to_string()).or_insert_with(|| serde_json::json!({}));+ let Some(o) = m.as_object_mut() else { return };+ o.insert(name.into(), serde_json::json!(kind.id()));+ }++ /// Drop any stored export type for `name` (Movie Clip default).+ pub fn clear_symbol_export_type(&mut self, name: &str) {+ let Some(m) = self.unknown.get_mut(SYMBOL_EXPORT_TYPE) else { return };+ let Some(o) = m.as_object_mut() else { return };+ o.remove(name);+ if o.is_empty() {+ self.unknown.remove(SYMBOL_EXPORT_TYPE);+ }+ }++ /// Move the stored export type when a symbol is renamed.+ pub fn rename_symbol_export_type(&mut self, from: &str, to: &str) {+ if from == to {+ return;+ }+ let kind = self.symbol_export_type(from);+ self.clear_symbol_export_type(from);+ self.set_symbol_export_type(to, kind);+ }++ /// Symbol Options › 9-slice guides for `name`: `None` when 9-slice scaling is off (default).+ pub fn symbol_nine_slice(&self, name: &str) -> Option<SymbolNineSlice> {+ self.unknown.get(SYMBOL_NINE_SLICE).and_then(|m| m.get(name)).and_then(SymbolNineSlice::from_value)+ }++ /// Turn 9-slice scaling on with `guides`, or off with `None`, for `name`.+ pub fn set_symbol_nine_slice(&mut self, name: &str, guides: Option<SymbolNineSlice>) {+ let Some(g) = guides else {+ let Some(o) = self.unknown.get_mut(SYMBOL_NINE_SLICE).and_then(|m| m.as_object_mut()) else { return };+ o.remove(name);+ if o.is_empty() {+ self.unknown.remove(SYMBOL_NINE_SLICE);+ }+ return;+ };+ let m = self.unknown.entry(SYMBOL_NINE_SLICE.to_string()).or_insert_with(|| serde_json::json!({}));+ if let Some(o) = m.as_object_mut() {+ o.insert(name.into(), g.to_value());+ }+ }++ /// Move the stored 9-slice guides when a symbol is renamed.+ pub fn rename_symbol_nine_slice(&mut self, from: &str, to: &str) {+ if from == to {+ return;+ }+ let g = self.symbol_nine_slice(from);+ self.set_symbol_nine_slice(from, None);+ self.set_symbol_nine_slice(to, g);+ }+ }++ /// An id (never 0) none of `used` has: one past the largest, or, when that is the largest there+ /// is (a damaged file), the smallest one free.+ pub(crate) fn free_id(used: impl Iterator<Item = u32>) -> u32 {+ let mut used: Vec<u32> = used.collect();+ if let Some(next) = used.iter().max().copied().unwrap_or(0).checked_add(1) {+ return next;+ }+ used.sort_unstable();+ used.dedup();+ // Ids 1, 2, 3… as far as they are all taken: the first that isn't follows them.+ let taken = used.iter().filter(|&&id| id != 0).zip(1u32..).take_while(|&(&id, n)| id == n).count();+ u32::try_from(taken).map_or(u32::MAX, |n| n.saturating_add(1))+ }++ impl Document {+ /// Make the next id allocated at least `next`: ids handed out outside the layer tree (such+ /// as an importer's opacity mask and pattern art), which [`Document::fix_next_id`] doesn't see.+ pub fn reserve_ids(&mut self, next: u64) {+ self.next_id = self.next_id.max(next.min(MAX_NEXT_ID));+ }+ }diff --cc crates/mcp/src/tools/definitions.rsindex 000000000,89432e9fc..3f77b1d87mode 000000,100644..100644--- a/crates/mcp/src/tools/definitions.rs+++ b/crates/mcp/src/tools/definitions.rs@@@ -1,0 -1,512 +1,513 @@@+ use super::dispatch::{BRIEF, MAX_SIDE_WINDOW, MENU_FILTER, TRACE_VIEWS};+ use super::handlers::MAX_DIALOG_FIELDS;+ use super::*;++ // ---------- schemas ----------++ fn num(desc: &str) -> Value {+ json!({"type": "number", "description": desc})+ }++ fn string(desc: &str) -> Value {+ json!({"type": "string", "description": desc})+ }++ /// The arguments `save_file` passes on to `document.save` beside `path`.-pub(super) const SAVE_FILE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "options"];++pub(super) const SAVE_FILE_OPTIONS: [&str; 5] = ["compress", "version", "preview", "precision", "options"];++ /// The arguments `doc_inspect` / `inspect_document` pass on to `document.inspect`.+ pub(super) const INSPECT_KEYS: [&str; 6] = ["depth", "childLimit", "ids", "kind", "limit", "offset"];++ /// Their schema.+ fn inspect_props() -> Value {+ json!({+ "depth": {"type": "integer", "minimum": 0, "description": "Child levels of the layer tree to include (default all; 0 = top layers with counts)"},+ "childLimit": {"type": "integer", "minimum": 0, "description": "Children shown per node (default all; a level that shows fewer reports childCount)"},+ "ids": {"type": "array", "maxItems": 10000, "items": {"type": "integer", "minimum": 0}, "description": "List just these nodes (any level) as `nodes` instead of the whole layer tree; an unknown id is an error"},+ "kind": {"type": "string", "description": "List every node of this panel label (Layer, Group, Path, Type, Image, ...; ignores case) as `nodes`, each with its ancestor `path`; searches the subtrees of `ids` when given"},+ "limit": {"type": "integer", "minimum": 0, "description": "At most this many layers or nodes (the reply adds `total`)"},+ "offset": {"type": "integer", "minimum": 0, "description": "Layers or nodes skipped first (default 0)"}+ })+ }++ fn paint_schema(what: &str) -> Value {+ json!({+ "description": format!("{what}: \"#rrggbb\", \"none\", [r,g,b] (0..1), {{\"c\",\"m\",\"y\",\"k\"}}, {{\"gray\"}}, or a full paint.setFill params object ({{\"gradient\":…}} / {{\"swatch\":name}})"),+ "anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "number"}}, {"type": "object"}]+ })+ }++ /// The options `draw_path` and `draw_shape` apply to the object they draw (#2112).+ fn with_draw_options(mut props: Value) -> Value {+ let more = json!({+ "dash": {"description": "Dash and gap lengths in pt ([d, g, …]), or null for a solid stroke (stroke.set `dash`)", "anyOf": [{"type": "array", "items": {"type": "number"}}, {"type": "null"}]},+ "cap": {"type": "string", "enum": ["butt", "round", "square", "projecting"], "description": "Stroke cap"},+ "join": {"type": "string", "enum": ["miter", "round", "bevel"], "description": "Stroke corner join"},+ "opacity": {"type": "number", "minimum": 0, "maximum": 100, "description": "Opacity in % (object.setProps `opacity`); doc_inspect reads it back as `opacityPct` (its `opacity` is a 0–1 fraction)"},+ "name": string("Name in the Layers panel"),+ "effects": {+ "type": "array",+ "description": "Live effects applied in order, as apply_effect: [{effect: id (effect.list), params?: {…}}]",+ "items": obj(json!({"effect": string("Effect id, e.g. \"blur.gaussian\""), "params": {"type": "object"}}), &["effect"]),+ },+ });+ if let (Some(p), Value::Object(more)) = (props.as_object_mut(), more) {+ p.extend(more);+ }+ props+ }++ fn mods_schema() -> Value {+ json!({+ "type": "object",+ "description": "Modifier keys held (cmd = Command on macOS / Ctrl elsewhere; alt = Option)",+ "properties": {"shift": {"type": "boolean"}, "alt": {"type": "boolean"}, "cmd": {"type": "boolean"}, "ctrl": {"type": "boolean"}},+ "additionalProperties": false+ })+ }++ fn obj(props: Value, required: &[&str]) -> Value {+ let mut o = json!({"type": "object", "properties": props, "additionalProperties": false});+ if !required.is_empty() {+ o["required"] = json!(required);+ }+ o+ }++ /// The extension of each format Save writes, in [`SAVE_FORMATS`] order.+ fn save_extensions() -> Vec<&'static str> {+ SAVE_FORMATS.iter().filter_map(|id| format(id)?.extensions.first().copied()).collect()+ }++ fn tool(name: &str, title: &str, desc: &str, schema: Value, read_only: bool) -> Value {+ let writes_file = matches!(name, "screenshot" | "save_file" | "export");+ let read_only = read_only && !writes_file;+ json!({+ "name": name,+ "title": title,+ "description": desc,+ "inputSchema": schema,+ "annotations": {"title": title, "readOnlyHint": read_only, "destructiveHint": !read_only, "idempotentHint": read_only, "openWorldHint": false},+ })+ }++ /// All tools, in `tools/list` order.+ pub fn tool_definitions() -> Vec<Value> {+ let empty = || obj(json!({}), &[]);+ vec![+ tool(+ "command_list",+ "List commands",+ "Discover command ids, labels, parameter descriptions and enabled state. Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}.",+ obj(+ json!({"filter": string("Case-insensitive id, label or menu substring"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabled_only": {"type":"boolean"}, "brief": {"type":"boolean", "description": BRIEF}}),+ &[],+ ),+ true,+ ),+ tool(+ "command_run",+ "Run a command",+ "Run an engine command by id with its JSON params. Command parameters follow the registry's descriptions. run_command runs it the same way; it takes the id as command instead of id.",+ obj(json!({"id": string("Command id"), "params": {"type":"object"}}), &["id"]),+ false,+ ),+ tool(+ "command_batch",+ "Run several commands",+ "Run steps in order; each edit is its own undo step, or with atomic:true the whole batch is one (named `label`, else after its first edit; `atomic` says which documents). A step's id is a command id, or draw_path / draw_shape with that tool's arguments as params (its result is the tool's: the new object's `id`). A param string that is exactly \"$N.path\" (N: 0-based step index) or \"$last.path\" takes that value from an earlier step's result, e.g. {\"id\":\"$1.id\"}; \"$$\" starts a literal \"$\". Returns completed, failed, results and created (the ids draw_path / draw_shape steps made, in order). Stops on the first error by default. At most 256 steps; kept step results total at most 8 MiB, past which the batch stops with the reason.",+ obj(+ json!({"steps": {"type":"array", "maxItems": 256, "items":obj(json!({"id":string("Command id, or draw_path / draw_shape"),"params":{"type":"object"}}), &["id"])}, "stop_on_error":{"type":"boolean", "default":true}, "atomic":{"type":"boolean", "default":false, "description":"Make the batch's edits one undo step in the active document and in each document a step opens or creates; in a document open before the batch that a step switches to, each edit stays its own undo step"}, "label":string("The undo step's name with atomic")}),+ &["steps"],+ ),+ false,+ ),+ tool(+ "doc_inspect",+ "Inspect document",+ "Summary of the active document, including artboards, layer tree, selection and history. A node below full opacity reports `opacity` as a 0–1 fraction and `opacityPct` in the 0–100 % scale the drawing tools and object.setProps take: pass `opacityPct` back, never `opacity`. On a large document scope it: depth 0 for the layer skeleton, ids for just those nodes, kind for every node of one kind, limit/offset to page. inspect_document returns the same summary.",+ obj(inspect_props(), &[]),+ true,+ ),+ tool(+ "render_preview",+ "Render a preview",+ "Render an artboard (default the first) as inline PNG without changing the document. max_side defaults to 1024, limited to 1..4096.",+ obj(+ json!({"max_side":{"type":"integer","minimum":1,"maximum":4096},"artboard":{"type":"integer","minimum":0,"description":"0-based artboard (default 0)"},"traceViews":{"type":"boolean","description":TRACE_VIEWS}}),+ &[],+ ),+ true,+ ),+ tool(+ "ui_inspect",+ "Inspect the interface",+ "Inspect the connected desktop interface; returns a tool error in headless mode. The same call as inspect_ui.",+ empty(),+ true,+ ),+ tool(+ "ui_screenshot",+ "Capture the interface",+ "Capture the connected desktop window as inline PNG; requires a running desktop app. The same call as screenshot with window:true. max_side scales the returned image down to at most that many pixels on its longer side (1..4096; default: the full capture).",+ obj(json!({"max_side": {"type":"integer","minimum":1,"maximum":4096,"description":MAX_SIDE_WINDOW}}), &[]),+ true,+ ),+ tool(+ "list_commands",+ "List commands",+ "List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state). Every editing action is a command; run any of them with run_command. Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only.",+ obj(+ json!({"filter": string("Case-insensitive substring matched against id, label and menu path (e.g. \"align\", \"Object\")"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabledOnly": {"type": "boolean", "description": "Only commands that can run right now"}, "brief": {"type": "boolean", "description": BRIEF}}),+ &[],+ ),+ true,+ ),+ tool(+ "run_command",+ "Run command",+ "Execute any VectorCraft command by id with JSON params (see list_commands for ids and params). Examples: {\"command\":\"object.group\"}, {\"command\":\"object.align\",\"params\":{\"horizontal\":\"left\"}}, {\"command\":\"file.new\",\"params\":{\"width\":800,\"height\":600}}. Returns the command's result (e.g. {id} for creation commands). command_run runs it the same way and takes the id as id.",+ obj(+ json!({"command": string("Command id, e.g. shape.rectangle, object.group, paint.setFill"), "params": {"type": "object", "description": "Command parameters"}}),+ &["command"],+ ),+ false,+ ),+ tool(+ "inspect_document",+ "Inspect document",+ "Summary of the active document: artboards, layer tree (ids, names, kinds, bounds, fill/stroke; `opacity` as a 0–1 fraction and `opacityPct` in the 0–100 % scale the drawing tools take), selection, undo history, current tool and default paint. On a large document pass depth: 0 for the layer skeleton (truncated levels report childCount), then locate objects with run_command document.find and read them with document.node. doc_inspect returns the same summary.",+ obj(inspect_props(), &[]),+ true,+ ),+ tool(+ "inspect_ui",+ "Inspect UI",+ "UI state of the running desktop app: tool and options, panels, dialogs, view (zoom/center), window, documents, perf. Desktop app only. The same call as ui_inspect.",+ empty(),+ true,+ ),+ tool(+ "select_tool",+ "Select tool",+ "Switch the active tool (as clicking it in the Tools panel). Ids: selection, directSelection, groupSelection, pen, rectangle, roundedRectangle, ellipse, polygon, star, lineSegment, …",+ obj(json!({"tool": string("Tool id")}), &["tool"]),+ false,+ ),+ tool(+ "pointer_gesture",+ "Pointer gesture",+ "Drive the active tool with mouse events in document coordinates, exactly like the mouse would (e.g. a rectangle drag: down at (100,100), drag to (200,150), up at (200,150)). Optionally selects `tool` first.",+ obj(+ json!({+ "tool": string("Optional tool to select before the gesture"),+ "events": {+ "type": "array",+ "minItems": 1,+ "items": obj(json!({+ "kind": {"type": "string", "enum": ["down", "drag", "up", "move", "doubleclick"]},+ "x": num("Document x (pt)"),+ "y": num("Document y (pt)"),+ "mods": mods_schema(),+ "pressure": num("Pen pressure 0..1 (default 1): the Liquify tools' intensity with Use Pressure Pen on"),+ "holdMs": num("Milliseconds the pointer then holds still, button down (0..60000): Twirl, Pucker and Bloat keep applying"),+ }), &["kind", "x", "y"]),+ },+ "mods": mods_schema(),+ }),+ &["events"],+ ),+ false,+ ),+ tool(+ "draw_path",+ "Draw path",+ "Create a path from points ([[x,y],…] or [{x,y,in?:[x,y],out?:[x,y]},…] with Bézier handles) or SVG path data `d`, then apply optional paint, stroke dash/cap/join, opacity, name and live effects. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke). For a filled path without an outline, pass an explicit fill and stroke:\"none\". Returns the new object id.",+ obj(+ with_draw_options(json!({+ "points": {"type": "array", "description": "Anchors: [x,y] pairs or {x, y, in?, out?, smooth?} objects", "items": {"anyOf": [{"type": "array", "items": {"type": "number"}, "minItems": 2}, {"type": "object"}]}},+ "d": string("SVG path data (alternative to points), e.g. \"M0 0 L100 0 L50 80 Z\""),+ "closed": {"type": "boolean", "description": "Close the path (points only)"},+ "fill": paint_schema("Fill"),+ "stroke": paint_schema("Stroke"),+ "strokeWidth": num("Stroke weight in pt"),+ })),+ &[],+ ),+ false,+ ),+ tool(+ "draw_shape",+ "Draw shape",+ "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.",+ obj(+ with_draw_options(json!({+ "shape": {"type": "string", "enum": ["rectangle", "ellipse", "polygon", "star", "line"]},+ "x": num("Left (rectangle/ellipse)"),+ "y": num("Top (rectangle/ellipse)"),+ "width": num("Width (rectangle/ellipse)"),+ "height": num("Height (rectangle/ellipse)"),+ "radius": num("Corner radius (rectangle) or radius (polygon)"),+ "cx": num("Centre x (polygon/star)"),+ "cy": num("Centre y (polygon/star)"),+ "sides": {"type": "integer", "minimum": 3, "description": "Polygon sides (default 6)"},+ "radius1": num("Star outer radius"),+ "radius2": num("Star inner radius"),+ "points": {"type": "integer", "minimum": 3, "description": "Star points (default 5)"},+ "rotation": num("Rotation in degrees (polygon/star)"),+ "x1": num("Line start x"),+ "y1": num("Line start y"),+ "x2": num("Line end x"),+ "y2": num("Line end y"),+ "fill": paint_schema("Fill"),+ "stroke": paint_schema("Stroke"),+ "strokeWidth": num("Stroke weight in pt"),+ })),+ &["shape"],+ ),+ false,+ ),+ tool(+ "set_paint",+ "Set paint",+ "Set fill, stroke and/or stroke weight on the selection (or `ids`) and as the default for new art. Returns {applied, objects}: `objects` counts the objects painted, as paint.setFill, paint.setStroke and stroke.set report them (the largest of their counts); when it is 0, a `note` says that only the default for new art changed.",+ obj(+ json!({+ "fill": paint_schema("Fill"),+ "stroke": paint_schema("Stroke"),+ "strokeWidth": num("Stroke weight in pt"),+ "ids": {"type": "array", "items": {"type": "integer"}, "description": "Object ids (default: the selection)"},+ }),+ &[],+ ),+ false,+ ),+ tool(+ "press_key",+ "Press key",+ "Send a key press with modifiers, e.g. {key:\"Z\", mods:{cmd:true}} (undo), {key:\"Escape\"}, {key:\"Enter\"}. In the desktop app it goes through the real keyboard path; headless, it runs the command or tool bound to that shortcut.",+ obj(+ json!({"key": string("Key name: A–Z, 0–9, Enter, Escape, Delete, Backspace, Tab, Space, Left/Right/Up/Down, [ ]…"), "mods": mods_schema()}),+ &["key"],+ ),+ false,+ ),+ tool(+ "type_text",+ "Type text",+ "Type text into the focused widget (text tool, dialog field). Desktop app only.",+ obj(json!({"text": string("Text to type")}), &["text"]),+ false,+ ),+ tool(+ "answer_dialog",+ "Answer dialog",+ "Set fields of the desktop app's open dialog in order, then confirm (OK) or cancel it, as the control protocol's ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do. The app stores all the fields or none. When the app refuses the ui.dialog.set, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. inspect_ui shows the open dialog and its fields (ui.dialog). After invoke_menu app.quit or file.close replies {\"pending\":\"saveChanges\"}: {action:\"confirm\"} saves, {set:[{field:\"discard\",value:true}],action:\"confirm\"} closes without saving, {action:\"cancel\"} cancels. Returns {dialog, result}: the dialog after the fields were set, and the reply to confirm or cancel. Desktop app only.",+ obj(+ json!({+ "set": {+ "type": "array",+ "maxItems": MAX_DIALOG_FIELDS,+ "items": obj(json!({"field": string("Dialog field"), "value": {"description": "The field's new value (any JSON; default null)"}}), &["field"]),+ "description": "Fields to set, in order (one ui.dialog.set that sets all of them or none)",+ },+ "action": {"type": "string", "enum": ["confirm", "cancel"], "description": "Then confirm (OK) or cancel the dialog"},+ }),+ &[],+ ),+ false,+ ),+ tool(+ "invoke_menu",+ "Invoke menu",+ "Invoke a menu item by its command id (same ids as list_commands, including UI-only commands like view.zoomIn or window.* in the desktop app).",+ obj(json!({"command": string("Menu command id"), "params": {"type": "object"}}), &["command"]),+ false,+ ),+ tool(+ "open_panel",+ "Open panel",+ "Open a panel in the desktop app's dock by id (layers, swatches, stroke, align, pathfinder, transform, …; case-insensitive, display labels like \"Layers\" work too). Desktop app only.",+ obj(json!({"panel": string("Panel id or display label")}), &["panel"]),+ false,+ ),+ tool(+ "screenshot",+ "Screenshot",+ "Render the active artboard to PNG and return it as an image (optionally also saving it to `path`). With window:true (desktop app only) captures the whole app window instead, as ui_screenshot does; max_side then scales the returned image down (a file written to `path` keeps the full capture).",+ obj(+ json!({+ "path": string("Also write the PNG here"),+ "scale": num("Pixels per point (default 1)"),+ "artboard": {"type": "integer", "minimum": 0, "description": "Artboard index (default 0)"},+ "window": {"type": "boolean", "description": "Capture the app window (desktop app only)"},+ "max_side": {"type": "integer", "minimum": 1, "maximum": 4096, "description": MAX_SIDE_WINDOW},+ "traceViews": {"type": "boolean", "description": TRACE_VIEWS},+ }),+ &[],+ ),+ true,+ ),+ tool(+ "open_file",+ "Open file",+ &format!(+ "Open a file as a new, active document: .{} (see run_command document.formats). Templates (.ait, native templates) open as a new untitled document. The reply's `warnings` say what didn't come in as it was (an EPS shown as its preview image says why its PostScript couldn't be read).",+ OPEN_EXTS.join(", .")+ ),+ obj(json!({"path": string("File path")}), &["path"]),+ false,+ ),+ tool(+ "save_file",+ "Save file",+ &format!(- "Save the active document with the engine's document.save: by default to its own file in its own format (native .vectorcraft unless it was opened from or saved as SVG, PDF or a restorable .ai). With `path`, the extension picks the format: .{}. Other formats are exports (see export). A native file is gzipped when `compress` is true (default: the useCompression preference, Preferences > File Handling > Use Compression); `version` writes it for an older VectorCraft and `preview` embeds a PNG of the first artboard. `options` carries the format's save options (see run_command document.formats); giving `compress`, `version` or `preview` both at the top level and in `options` with different values is an error. The reply's `format` says what was written and `warnings` what that format loses and each option given that the format doesn't read (such as `compress` for .svg). In the running app the call returns once the file is written, or with the error, even with Background Save on. When the save asks first (before replacing a file that opened with losses, or with a file dialog for an untitled document without `path`), the reply is `pending` or \"cancelled\" as before.",++ "Save the active document with the engine's document.save: by default to its own file in its own format (native .vectorcraft unless it was opened from or saved as SVG, PDF or a restorable .ai). With `path`, the extension picks the format: .{}. Other formats are exports (see export). A native file is gzipped when `compress` is true (default: the useCompression preference, Preferences > File Handling > Use Compression); `version` writes it for an older VectorCraft, `preview` embeds a PNG of the first artboard, and `precision` rounds path anchors and handles to that many decimal places for that save only. `options` carries the format's save options (see run_command document.formats); giving `compress`, `version`, `preview` or `precision` both at the top level and in `options` with different values is an error. The reply's `format` says what was written and `warnings` what that format loses and each option given that the format doesn't read (such as `compress` for .svg). In the running app the call returns once the file is written, or with the error, even with Background Save on. When the save asks first (before replacing a file that opened with losses, or with a file dialog for an untitled document without `path`), the reply is `pending` or \"cancelled\" as before.",+ save_extensions().join(", .")+ ),+ obj(+ json!({+ "path": string("Destination; its extension picks the format (default: the document's own file)"),+ "compress": {"type": "boolean", "description": "Native files: gzip the file (default: the useCompression preference)"},+ "version": {"type": "integer", "minimum": 1, "maximum": vectorcraft_format::VERSION, "description": "Native files: the format version to write (default: the current one; 1 and 2 are never compressed)"},+ "preview": {"type": "boolean", "description": "Native files: embed a PNG of the first artboard, at most 256 px (default false)"},++ "precision": {"type": "integer", "minimum": 0, "maximum": vectorcraft_format::MAX_PRECISION, "description": "Native files: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact (default: exact)"},+ "options": {"type": "object", "description": "The format's save options, passed through (see run_command document.formats); default: as last saved"},+ }),+ &[],+ ),+ false,+ ),+ tool(+ "export",+ "Export",+ "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",+ obj(+ json!({+ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::<Vec<_>>(), "description": "Default: from the path's extension"},+ "path": string("Destination file (omit to get dataBase64)"),+ "scale": num("Raster pixels per point (default 1)"),+ "artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"},+ "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF and WMF: one, or one file each with options.useArtboards: true)"),+ "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"},+ "outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"},+ "options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"},+ }),+ &[],+ ),+ false,+ ),+ tool(+ "add_text",+ "Add text",+ "Create point type at (x, y) (the first baseline), area type when width/height are given (`fit` autoHeight grows the frame to the text, shrinkText scales the text down to fit), or type in/on an existing path (`path` id + `mode` area|onPath; `pathEffect` rainbow|skew|3dRibbon|stairStep|gravity). Returns the text object id, with `overflow: true` when the text doesn't fit its frame or path (the lines past it aren't drawn: enlarge the frame, shrink the text or give `fit`).",+ obj(+ json!({+ "text": {"type": "string"},+ "x": num("Baseline origin x (area type: left; point type: where the line starts, or its centre or end with justify center/right)"),+ "y": num("First baseline y (area type: top)"),+ "width": num("Area type frame width"),+ "height": num("Area type frame height"),+ "vertical": {"type": "boolean", "description": "Vertical writing for point, area or path type (default false, horizontal), as text.create / text.createInPath"},+ "fit": {"type": "string", "enum": ["none", "autoHeight", "shrinkText"], "description": "Area type: keep the frame (none), fit its height to the text (autoHeight) or scale overflowing text down (shrinkText)"},+ "fitMinPercent": num("shrinkText: the smallest scale in percent, 10 to 100 (default 50)"),+ "path": {"type": "integer", "description": "Existing path id to flow the text in (area) or along (onPath)"},+ "mode": {"type": "string", "enum": ["area", "onPath"]},+ "pathEffect": {"type": "string", "enum": ["rainbow", "skew", "3dRibbon", "stairStep", "gravity"]},+ "size": num("Font size in pt"),+ "font": {"type": "string", "description": "Font family"},+ "color": paint_schema("Text colour (#rrggbb)"),+ "justify": {"type": "string", "enum": ["auto", "left", "center", "right", "justifyAll"], "description": "Paragraph alignment (default auto: the start of the text's direction). Point type lines up on x: center centres each line on it, right ends it there"},+ }),+ &["text"],+ ),+ false,+ ),+ tool(+ "apply_effect",+ "Apply live effect",+ "Append a live effect (Effect menu) to the selection or `ids`. Omit `effect` to get the catalogue (ids, parameters, defaults). Examples: stylize.dropShadow {x, y, blur, opacity}, distort.roughen, warp.arc {bend}, path.offsetPath {offset}, pathfinder.add (on groups), blur.gaussian {radius}.",+ obj(+ json!({+ "effect": {"type": "string", "description": "Effect id (see the catalogue)"},+ "params": {"type": "object", "description": "Effect parameters; missing keys take the dialog defaults"},+ "ids": {"type": "array", "items": {"type": "integer"}},+ }),+ &[],+ ),+ false,+ ),+ tool(+ "pathfinder",+ "Pathfinder",+ "Combine the selected (or `ids`) objects destructively, back to front: unite, minusFront, intersect, exclude, divide, trim, merge, crop, outline, minusBack. For a non-destructive version apply the pathfinder.* effect to a group.",+ obj(+ json!({+ "operation": {"type": "string", "enum": ["unite", "minusFront", "intersect", "exclude", "divide", "trim", "merge", "crop", "outline", "minusBack"]},+ "ids": {"type": "array", "items": {"type": "integer"}},+ }),+ &["operation"],+ ),+ false,+ ),+ tool(+ "transform",+ "Transform",+ "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.",+ obj(+ json!({+ "ids": {"type": "array", "items": {"type": "integer"}},+ "dx": num("Move right"),+ "dy": num("Move down"),+ "rotate": num("Rotation in degrees"),+ "scale": num("Uniform scale in %"),+ "scaleX": num("Horizontal scale in %"),+ "scaleY": num("Vertical scale in %"),+ "reflect": {"type": "string", "enum": ["vertical", "horizontal"]},+ "shear": num("Shear angle in degrees (horizontal axis)"),+ "origin": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2},+ "copy": {"type": "boolean"},+ }),+ &[],+ ),+ false,+ ),+ tool(+ "create_graph",+ "Create graph",+ "Create a graph (graph tools) in the plot rectangle. Data as `csv` (first row: empty cell then series names; then one row per category: label, values…) or `series`/`categories`/`rows`. An empty CSV cell or a null in `rows` is a blank value (no column; lines break around it); a number in straight quotes is a label. Edit later with run_command graph.setData / graph.setType.",+ obj(+ json!({+ "type": {"type": "string", "enum": ["column", "stackedColumn", "bar", "stackedBar", "line", "area", "scatter", "pie", "radar"]},+ "x": num("Plot left"),+ "y": num("Plot top"),+ "width": num("Plot width"),+ "height": num("Plot height"),+ "csv": {"type": "string"},+ "series": {"type": "array", "items": {"type": "string"}},+ "categories": {"type": "array", "items": {"type": "string"}},+ "rows": {"type": "array", "items": {"type": "array", "items": {"type": ["number", "null"]}}},+ }),+ &["x", "y", "width", "height"],+ ),+ false,+ ),+ tool(+ "text_wrap",+ "Text wrap",+ "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap.",+ obj(+ json!({+ "ids": {"type": "array", "items": {"type": "integer"}},+ "offset": num("Gap between text and object (default 6 pt)"),+ "invert": {"type": "boolean"},+ "release": {"type": "boolean"},+ }),+ &[],+ ),+ false,+ ),+ tool("undo", "Undo", "Undo the last change (Edit → Undo). redo reapplies it.", empty(), false),+ tool("redo", "Redo", "Redo the last undone change (Edit → Redo): the change the last undo took back.", empty(), false),+ ]+ }diff --cc crates/mcp/src/tools/dispatch.rsindex 000000000,d5c11e85c..cd10d539amode 000000,100644..100644--- a/crates/mcp/src/tools/dispatch.rs+++ b/crates/mcp/src/tools/dispatch.rs@@@ -1,0 -1,456 +1,457 @@@+ use super::definitions::{INSPECT_KEYS, SAVE_FILE_OPTIONS, tool_definitions};+ use super::handlers::{+ Args, absolute_path, add_text, answer_dialog, apply_paint, draw_path, draw_shape, exec, image_result, max_side, need_ui, req_str, screenshot,+ select_ids, transform,+ };+ use super::*;++ /// The `menu` argument of the command listings.+ pub(super) const MENU_FILTER: &str =+ "Case-insensitive substring of the menu path, its levels joined with \" > \" (e.g. \"Object\", \"Object > Path\")";++ /// The `brief` argument of the command listings.+ pub(super) const BRIEF: &str =+ "Leave out each command's params description (the bulk of the catalogue); run command_list with the id as filter to read it";++ /// The `max_side` argument of the window captures.+ pub(super) const MAX_SIDE_WINDOW: &str =+ "Window capture only: longest side of the returned image in pixels; a larger capture is scaled down to it (default: the full capture)";++ /// The `traceViews` argument of the artboard renders.+ pub(super) const TRACE_VIEWS: &str = "Draw Image Trace objects in the view set with imageTrace.setView (outlines, the source image…), as the app's window does; by default they draw their tracing result, as exports do";++ /// `traceViews`: false when absent.+ pub(super) fn trace_views(a: &Args) -> Result<bool, String> {+ match a.get("traceViews") {+ None => Ok(false),+ Some(v) => v.as_bool().ok_or_else(|| "`traceViews` must be a boolean".into()),+ }+ }++ /// The command catalogue narrowed by the listing tools' arguments: `filter` (or `query`) on the+ /// id, label and menu path, `menu` on the menu path, `enabledOnly`, and `brief` (no `params`+ /// text: the full catalogue is too large for many clients, #2173).+ fn filter_commands(all: Value, a: &Args) -> Value {+ let text = |k: &str| a.get(k).and_then(Value::as_str).map(str::to_lowercase).filter(|s| !s.is_empty());+ let needle = text("filter").or_else(|| text("query"));+ let in_menu = text("menu");+ let enabled_only = a.get("enabledOnly").and_then(Value::as_bool).unwrap_or(false);+ let brief = a.get("brief").and_then(Value::as_bool).unwrap_or(false);+ let Value::Array(list) = all else { return all };+ let menu_path = |c: &Value, sep: &str| {+ c.get("menu")+ .and_then(Value::as_array)+ .map(|m| m.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(sep))+ .unwrap_or_default()+ .to_lowercase()+ };+ let hit = |c: &Value| {+ if enabled_only && c.get("enabled").and_then(Value::as_bool) == Some(false) {+ return false;+ }+ if let Some(m) = &in_menu+ && !menu_path(c, " > ").contains(m.as_str())+ {+ return false;+ }+ let Some(n) = &needle else { return true };+ let field = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or("").to_lowercase();+ field("id").contains(n.as_str()) || field("label").contains(n.as_str()) || menu_path(c, " ").contains(n.as_str())+ };+ Value::Array(+ list.into_iter()+ .filter(hit)+ .map(|mut c| {+ if brief && let Some(o) = c.as_object_mut() {+ o.remove("params");+ }+ c+ })+ .collect(),+ )+ }++ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<ToolResult, String> {+ let j = |v: Value| Ok(ToolResult::json(&v));+ match name {+ "command_list" => {+ let all = b.call("engine.commands", json!({}))?;+ let mut filters = a.clone();+ if let Some(v) = filters.remove("enabled_only") {+ filters.insert("enabledOnly".into(), v);+ }+ j(filter_commands(all, &filters))+ }+ "command_batch" => command_batch(b, a),+ "render_preview" => render_preview(b, a),+ "ui_screenshot" => {+ let mut args = a.clone();+ args.insert("window".into(), json!(true));+ screenshot(b, &args)+ }+ "list_commands" => {+ let all = b.call("engine.commands", json!({}))?;+ let list = filter_commands(all, a);+ j(json!({"count": list.as_array().map_or(0, Vec::len), "commands": list}))+ }+ "command_run" | "run_command" | "invoke_menu" => {+ let cmd = req_str(a, if name == "command_run" { "id" } else { "command" })?;+ let params = match a.get("params") {+ None | Some(Value::Null) => json!({}),+ Some(v @ Value::Object(_)) => v.clone(),+ Some(_) => return Err("`params` must be an object".into()),+ };+ let method = if name == "invoke_menu" && b.has_ui() { "ui.menu.invoke" } else { "engine.execute" };+ j(b.call(method, json!({"command": cmd, "params": params}))?)+ }+ "doc_inspect" | "inspect_document" => {+ // Only the slicing and scope options reach the command, which validates them.+ let slice: Map<String, Value> =+ a.iter().filter(|(k, _)| INSPECT_KEYS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();+ j(b.call("document.inspect", Value::Object(slice))?)+ }+ "ui_inspect" | "inspect_ui" => {+ need_ui(b, name)?;+ j(b.call("ui.inspect", json!({}))?)+ }+ "select_tool" => j(b.call("ui.tool.select", json!({"tool": req_str(a, "tool")?}))?),+ "pointer_gesture" => {+ let events = a.get("events").and_then(Value::as_array).filter(|e| !e.is_empty()).ok_or("`events` must be a non-empty array")?;+ for (i, e) in events.iter().enumerate() {+ let kind = e.get("kind").and_then(Value::as_str).unwrap_or("");+ if crate::headless::pointer_kind(kind).is_none() {+ return Err(format!("event {i}: unknown kind `{kind}` (down, drag, up, move, doubleclick)"));+ }+ if !e.get("x").is_some_and(Value::is_number) || !e.get("y").is_some_and(Value::is_number) {+ return Err(format!("event {i}: numeric `x` and `y` required"));+ }+ }+ if let Some(t) = a.get("tool").and_then(Value::as_str) {+ b.call("ui.tool.select", json!({"tool": t}))?;+ }+ let events: Vec<Value> = events+ .iter()+ .map(|e| {+ let mut e = e.clone();+ e["space"] = json!("doc");+ e+ })+ .collect();+ let mut p = json!({"events": events});+ if let Some(m) = a.get("mods") {+ p["mods"] = m.clone();+ }+ j(b.call("ui.pointer", p)?)+ }+ "draw_path" => j(draw_path(b, a)?),+ "draw_shape" => j(draw_shape(b, a)?),+ "set_paint" => {+ if !["fill", "stroke", "strokeWidth"].iter().any(|k| a.contains_key(*k)) {+ return Err("give at least one of `fill`, `stroke`, `strokeWidth`".into());+ }+ let (applied, objects) = apply_paint(b, a, a.get("ids").cloned())?;+ let mut reply = json!({"applied": applied, "objects": objects});+ if objects == 0 {+ reply["note"] = json!(+ "no object was painted (nothing selected, or `ids` is empty or holds no object this paint applies to): only the paint for new art changed"+ );+ }+ j(reply)+ }+ "press_key" => {+ let mut p = json!({"key": req_str(a, "key")?});+ if let Some(Value::Object(m)) = a.get("mods") {+ for (k, v) in m {+ p[k.as_str()] = v.clone();+ }+ }+ j(b.call("ui.key", p)?)+ }+ "type_text" => {+ need_ui(b, name)?;+ j(b.call("ui.text", json!({"text": req_str(a, "text")?}))?)+ }+ "answer_dialog" => {+ need_ui(b, name)?;+ j(answer_dialog(b, a)?)+ }+ "open_panel" => {+ need_ui(b, name)?;+ j(b.call("ui.set", json!({"panel": req_str(a, "panel")?}))?)+ }+ "screenshot" => screenshot(b, a),+ "open_file" => {+ let path = absolute_path(b, req_str(a, "path")?)?;+ j(b.call("app.open", json!({"path": path}))?)+ }+ "save_file" => {+ let mut p = json!({"path": a.get("path").and_then(Value::as_str).map(|p| absolute_path(b, p)).transpose()?});+ for k in SAVE_FILE_OPTIONS {+ if let Some(v) = a.get(k).filter(|v| !v.is_null()) {+ p[k] = v.clone();+ }+ }+ // The app writes the file before it replies, even with Background Save on, so a failed+ // save is this call's error.+ if b.has_ui() {+ p["wait"] = json!(true);+ }+ let mut r = b.call("app.save", p)?;+ let notes = save_file_warnings(a, r.get("format").and_then(Value::as_str));+ if let Some(o) = r.as_object_mut().filter(|_| !notes.is_empty()) {+ let mut all = o.get("warnings").and_then(Value::as_array).cloned().unwrap_or_default();+ all.extend(notes.into_iter().map(Value::from));+ o.insert("warnings".into(), Value::Array(all));+ }+ j(r)+ }+ "export" => {+ // One params object for every backend; the named arguments win over `options` (a named+ // artboard or range replaces every artboard choice in `options`).+ let mut params = a.get("options").and_then(Value::as_object).cloned().unwrap_or_default();+ if ["artboard", "range"].iter().any(|k| a.get(*k).is_some_and(|v| !v.is_null())) {+ for k in ARTBOARD_PARAMS {+ params.remove(k);+ }+ }+ for k in named_export_params(a) {+ if let Some(v) = a.get(*k).filter(|v| !v.is_null()) {+ params.insert((*k).into(), v.clone());+ }+ }+ if let Some(path) = params.get("path").and_then(Value::as_str) {+ let path = absolute_path(b, path)?;+ params.insert("path".into(), json!(path));+ }+ let cmd = if a.get("selection").and_then(Value::as_bool) == Some(true) { "document.exportSelection" } else { "document.export" };+ j(exec(b, cmd, Value::Object(params))?)+ }+ "add_text" => j(add_text(b, a)?),+ "apply_effect" => {+ let Some(effect) = a.get("effect").and_then(Value::as_str) else {+ let all = exec(b, "effect.list", json!({}))?;+ return j(json!({"catalog": all.get("catalog")}));+ };+ let mut p = json!({"effect": effect, "params": a.get("params").cloned().unwrap_or(json!({}))});+ if let Some(ids) = a.get("ids") {+ p["ids"] = ids.clone();+ }+ j(exec(b, "effect.apply", p)?)+ }+ "pathfinder" => {+ select_ids(b, a)?;+ j(exec(b, &format!("object.pathfinder.{}", req_str(a, "operation")?), json!({}))?)+ }+ "transform" => j(transform(b, a)?),+ "create_graph" => {+ let mut p = Value::Object(a.clone());+ if p.get("type").is_none() {+ p["type"] = json!("column");+ }+ j(exec(b, "graph.create", p)?)+ }+ "text_wrap" => {+ select_ids(b, a)?;+ if a.get("release").and_then(Value::as_bool) == Some(true) {+ return j(exec(b, "object.textWrap.release", json!({}))?);+ }+ let mut p = json!({});+ for k in ["offset", "invert"] {+ if let Some(v) = a.get(k) {+ p[k] = v.clone();+ }+ }+ j(exec(b, "object.textWrap.make", p)?)+ }+ "undo" => j(exec(b, "edit.undo", json!({}))?),+ "redo" => j(exec(b, "edit.redo", json!({}))?),+ other => Err(format!("unknown tool `{other}` (see tools/list)")),+ }+ }++ /// The named `export` arguments passed on to `document.export`. `scale` is raster pixels per+ /// point, so only a raster format gets it: DXF's own (drawing units per unit, given in `options`)+ /// would resize the drawing and leave its units unset.+ fn named_export_params(a: &Args) -> &'static [&'static str] {+ let format = writable_format(a.get("format").and_then(Value::as_str), a.get("path").and_then(Value::as_str));+ if format.is_ok_and(|f| f.raster) {+ &["path", "format", "scale", "artboard", "range", "outlineText"]+ } else {+ &["path", "format", "artboard", "range", "outlineText"]+ }+ }++ /// What `save_file` with arguments `a` adds to the save's `warnings`, for a file written in format+ /// `written` (none when nothing was written yet): each key in `options` that the format doesn't-/// read. The save itself warns about `compress`, `version` and `preview` given at the top level.++/// read. The save itself warns about `compress`, `version`, `preview` and `precision` given at the++/// top level.+ fn save_file_warnings(a: &Args, written: Option<&str>) -> Vec<String> {+ let Some(f) = written.and_then(format) else { return vec![] };+ let nested = a.get("options").and_then(Value::as_object);+ nested+ .into_iter()+ .flatten()+ .filter(|(key, v)| !v.is_null() && !save_reads_option(f, key))+ .map(|(key, _)| format!("`options.{key}` was not used: {} files don't read it", f.label))+ .collect()+ }++ /// Run one tool. Failures (unknown tool, bad arguments, command errors) come back as an+ /// `isError` result so the model can read and correct them.+ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {+ let empty = Map::new();+ let a = match args {+ Value::Object(o) => o,+ Value::Null => &empty,+ _ => return ToolResult::error("tool arguments must be a JSON object"),+ };+ match vectorcraft_engine::guard::catch_panic(|| dispatch(b, name, a)) {+ Ok(Ok(r)) => r,+ Ok(Err(e)) => ToolResult::error(format!("{name}: {e}")),+ Err(e) => ToolResult::error(format!("internal error in `{name}`: {e} (please report this bug)")),+ }+ }++ /// Most steps one `command_batch` may hold, and most bytes its kept step results may total.+ /// Batches run sequentially and every result is kept for later steps' `"$N.path"` references, so+ /// without caps one batch could do unbounded work and pile up an unbounded reply (#1727).+ pub(crate) const MAX_COMMAND_BATCH_STEPS: usize = 256;++ pub(crate) const MAX_COMMAND_BATCH_BYTES: usize = 8 * 1024 * 1024;++ /// Refuses an argument the tool's schema doesn't list, as `tools/call` does (#713).+ pub(crate) fn check_tool_arguments(name: &str, args: &Args) -> Result<(), String> {+ let defs = tool_definitions();+ let props =+ defs.iter().find(|t| t.get("name").and_then(Value::as_str) == Some(name)).and_then(|t| t.get("inputSchema")?.get("properties")?.as_object());+ match props.and_then(|p| args.keys().find(|k| !p.contains_key(*k))) {+ Some(key) => Err(format!("unknown argument `{key}` for `{name}`")),+ None => Ok(()),+ }+ }++ fn command_batch(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {+ let steps = a.get("steps").and_then(Value::as_array).ok_or("`steps` must be an array")?;+ if steps.len() > MAX_COMMAND_BATCH_STEPS {+ return Err(format!("`steps` holds {} steps; at most {MAX_COMMAND_BATCH_STEPS}", steps.len()));+ }+ let stop = match a.get("stop_on_error") {+ None => true,+ Some(v) => v.as_bool().ok_or("`stop_on_error` must be a boolean")?,+ };+ let atomic = match a.get("atomic") {+ None => false,+ Some(v) => v.as_bool().ok_or("`atomic` must be a boolean")?,+ };+ if atomic {+ let label = a.get("label").cloned().unwrap_or(Value::Null);+ b.call("engine.execute", json!({"command":"edit.undoGroup.begin","params":{"label":label}}))?;+ } else if a.get("label").is_some() {+ return Err("`label` names the undo step of an atomic batch: give atomic:true too".into());+ }+ let (mut completed, mut failed, mut results) = (0, 0, Vec::new());+ // Each step's result (null for a failed one), for later steps' `"$N.path"` references.+ let mut values: Vec<Value> = vec![];+ // The kept results all go back in the reply, so their total size is capped: one batch can't+ // pile up an unbounded answer (#1727).+ let mut kept_bytes = 0usize;+ // The objects the drawing steps made (#2113).+ let mut created: Vec<Value> = vec![];+ for step in steps {+ let result = vectorcraft_engine::guard::catch_panic(|| {+ let args = step.as_object().ok_or("each step must be an object")?;+ if args.keys().any(|k| k != "id" && k != "params") {+ return Err("unknown step argument (expected id, params)".into());+ }+ let id = req_str(args, "id")?;+ let params = match args.get("params") {+ None | Some(Value::Null) => json!({}),+ Some(v @ Value::Object(_)) => vectorcraft_engine::steps::resolve(v, &values)?,+ Some(_) => return Err("`params` must be an object".into()),+ };+ match id {+ // The drawing tools, with the arguments `tools/call` takes (#2113).+ "draw_path" | "draw_shape" => {+ let args = params.as_object().cloned().unwrap_or_default();+ check_tool_arguments(id, &args)?;+ let made = if id == "draw_path" { draw_path(b, &args)? } else { draw_shape(b, &args)? };+ if let Some(new) = made.get("id").filter(|v| v.is_u64()) {+ created.push(new.clone());+ }+ Ok(made)+ }+ _ => b.call("engine.execute", json!({"command":id,"params":params})),+ }+ })+ .unwrap_or_else(|e| Err(format!("internal error: {e}")));+ match result {+ Ok(v) => {+ let entry = json!({"ok": true, "result": v});+ let size = entry.to_string().len();+ if kept_bytes.saturating_add(size) > MAX_COMMAND_BATCH_BYTES {+ // The results already kept stay; this step ran, and its result is replaced by+ // the reason the batch stops (saying it ran, so nobody runs it again). The loop breaks either way — carrying on would defeat the cap —+ // and the atomic group below still closes, as for any stopped batch.+ failed += 1;+ values.push(Value::Null);+ results.push(json!({"ok": false, "error": format!("this step ran, but the batch's results exceed {MAX_COMMAND_BATCH_BYTES} bytes: its result is dropped and the batch stops here")}));+ break;+ }+ kept_bytes += size;+ completed += 1;+ values.push(entry["result"].clone());+ results.push(entry);+ }+ Err(e) => {+ failed += 1;+ values.push(Value::Null);+ results.push(json!({"ok":false,"error":e}));+ if stop {+ break;+ }+ }+ }+ }+ // The steps that ran stay, as one undo step.+ if atomic {+ b.call("engine.execute", json!({"command":"edit.undoGroup.end","params":{}}))?;+ }+ let mut r = ToolResult::json(&json!({"completed":completed,"failed":failed,"results":results,"created":created}));+ r.is_error = failed > 0;+ Ok(r)+ }++ fn render_preview(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {+ let max = max_side(a)?.unwrap_or(1024);+ let index = match a.get("artboard") {+ None => 0,+ Some(v) => v.as_u64().ok_or("`artboard` must be a 0-based artboard index")?,+ };+ let trace_views = trace_views(a)?;+ let doc = b.call("document.inspect", json!({"depth":0}))?;+ let board =+ doc.get("artboards").and_then(Value::as_array).and_then(|v| v.get(usize::try_from(index).ok()?)).ok_or(format!("no artboard {index}"))?;+ let width = board.get("width").and_then(Value::as_f64).ok_or("artboard has no width")?;+ let height = board.get("height").and_then(Value::as_f64).ok_or("artboard has no height")?;+ if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {+ return Err("invalid artboard dimensions".into());+ }+ // The headless renderer clamps scale at 0.01. Bound its allocation even for+ // a huge artboard, then downsize to the requested dimensions.+ let scale = (f64::from(max) / width.max(height)).clamp(0.01, 1.0);+ if width.max(height) * scale > 4096.0 {+ return Err("artboard is too large for a bounded preview".into());+ }+ let mut p = json!({"scale":scale, "artboard": index});+ if trace_views {+ p["traceViews"] = json!(true);+ }+ let r = b.call("ui.render", p)?;+ let encoded = r.get("pngBase64").and_then(Value::as_str).ok_or("renderer returned no image")?;+ let png = vectorcraft_format::base64_decode(encoded).ok_or("renderer returned bad base64")?;+ let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| format!("read preview: {e}"))?;+ let img = if img.width() > max || img.height() > max { img.thumbnail(max, max) } else { img };+ let mut out = std::io::Cursor::new(Vec::new());+ img.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("encode preview: {e}"))?;+ Ok(image_result(out.get_ref(), json!({"width":img.width(),"height":img.height()})))+ }diff --cc crates/ui-egui/src/dialogs/save_options/tests.rsindex 000000000,9c8ae60bb..0712b0a42mode 000000,100644..100644--- a/crates/ui-egui/src/dialogs/save_options/tests.rs+++ b/crates/ui-egui/src/dialogs/save_options/tests.rs@@@ -1,0 -1,334 +1,346 @@@+ use std::cell::RefCell;+ use std::rc::Rc;++ use vectorcraft_engine::Session;++ use super::*;+ use crate::{FilePick, Services, theme};++ type Written = Rc<RefCell<Vec<(String, Vec<u8>)>>>;++ /// A desktop app whose save panel answers `picked` and records what it was shown.+ fn desktop(picked: &'static str) -> (VectorcraftApp, Written, Rc<RefCell<Vec<FilePick>>>) {+ let (written, picks) = (Written::default(), Rc::new(RefCell::new(vec![])));+ let (w, p) = (written.clone(), picks.clone());+ let services = Services {+ pick_save: Some(Box::new(move |f: &FilePick| {+ p.borrow_mut().push(f.clone());+ Some(picked.to_string())+ })),+ write: Some(Box::new(move |path: &str, b: &[u8]| {+ w.borrow_mut().push((path.to_string(), b.to_vec()));+ Ok(())+ })),+ ..Default::default()+ };+ (with_art(services), written, picks)+ }++ /// A browser app: saves are downloads.+ fn web() -> (VectorcraftApp, Written) {+ let written = Written::default();+ let w = written.clone();+ let services = Services {+ download: Some(Box::new(move |name: &str, b: &[u8]| {+ w.borrow_mut().push((name.to_string(), b.to_vec()));+ Ok(())+ })),+ ..Default::default()+ };+ (with_art(services), written)+ }++ fn with_art(services: Services) -> VectorcraftApp {+ let mut app = VectorcraftApp::new(Session::new(), services);+ app.run("file.new", json!({"width": 100, "height": 80})).unwrap();+ app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();+ app+ }++ /// One headless frame of the dialog layer; `enter` presses OK.+ fn frame(app: &mut VectorcraftApp, enter: bool) {+ let ctx = egui::Context::default();+ theme::install_fonts(&ctx);+ let events = if enter {+ vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]+ } else {+ vec![]+ };+ let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx()));+ out.textures_delta.clear();+ }++ fn dialog(app: &VectorcraftApp) -> &Dialog {+ app.ui.dialog.as_ref().expect("a dialog is open")+ }++ #[test]+ fn save_as_svg_opens_svg_options_then_writes_svg() {+ let (mut app, written, picks) = desktop("art.svg");+ let r = app.run("file.saveAs", json!({})).unwrap();+ assert_eq!((r["pending"].as_str(), r["path"].as_str()), (Some("svgOptions"), Some("art.svg")));+ // The save panel offers every save format, the document's own first.+ let pick = &picks.borrow()[0];+ let labels: Vec<&str> = pick.filters.iter().map(|f| f.0.as_str()).collect();+ assert_eq!(labels, ["VectorCraft", "VectorCraft Template", "PDF", "SVG", "SVG Compressed", "PDF-compatible .ai"]);+ assert_eq!(pick.name, "Untitled-1.vectorcraft");+ let d = dialog(&app);+ assert_eq!((d.kind.as_str(), d.str("path").as_str(), d.str("mode").as_str()), ("svgOptions", "art.svg", "save"));+ assert!(written.borrow().is_empty(), "nothing is written before OK");+ frame(&mut app, false);+ assert!(app.ui.dialog.is_some(), "drawing keeps it open");+ app.ui.dialog.as_mut().unwrap().fields.insert("outlineText".into(), json!(true));+ frame(&mut app, true);+ assert!(app.ui.dialog.is_none());+ let (path, bytes) = written.borrow()[0].clone();+ assert_eq!(path, "art.svg");+ assert!(bytes.starts_with(b"<?xml"));+ let st = app.session.active().unwrap();+ assert_eq!((st.path.as_deref(), st.format, st.is_dirty()), (Some("art.svg"), "svg", false));+ assert_eq!((&st.save_options["outlineText"], &st.save_options["styling"]), (&json!(true), &json!("css")), "the SVG Options are remembered");+ assert!(app.ui.status.contains("SVG keeps the artwork"), "{}", app.ui.status);+ // Save writes it back as SVG, with the same options and no questions.+ assert!(!crate::menus::enabled(&app, "file.save"), "nothing to save");+ app.run("shape.ellipse", json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();+ assert!(crate::menus::enabled(&app, "file.save"));+ app.run("file.save", json!({})).unwrap();+ assert!(app.ui.dialog.is_none() && picks.borrow().len() == 1);+ assert!(written.borrow()[1].1.starts_with(b"<?xml"));+ }++ #[test]+ fn save_as_ai_version_7_writes_a_file_per_artboard() {+ let (mut app, written, _) = desktop("art.ai");+ app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 80, "name": "Back"})).unwrap();+ assert_eq!(app.run("file.saveAs", json!({})).unwrap()["pending"], KIND);+ assert_eq!(dialog(&app).str("aiVersion"), "pdf", "PDF-compatible unless asked");+ assert_eq!(dialog(&app).str("transparentImages"), "flatten");+ assert_eq!(dialog(&app).str("hiddenObjects"), "layer");+ assert!(!dialog(&app).bool("outlineText"));+ frame(&mut app, false);+ app.ui.dialog.as_mut().unwrap().fields.insert("aiVersion".into(), json!("7"));+ app.ui.dialog.as_mut().unwrap().fields.insert("transparentImages".into(), json!("omit"));+ app.ui.dialog.as_mut().unwrap().fields.insert("hiddenObjects".into(), json!("visible"));+ app.ui.dialog.as_mut().unwrap().fields.insert("outlineText".into(), json!(true));+ frame(&mut app, false);+ frame(&mut app, true);+ assert!(app.ui.dialog.is_none());+ let names: Vec<String> = written.borrow().iter().map(|(p, _)| p.clone()).collect();+ assert_eq!(names, ["art-Artboard-1.ai", "art-Back.ai"]);+ assert!(written.borrow().iter().all(|(_, b)| b.starts_with(b"%!PS")));+ let st = app.session.active().unwrap();+ assert_eq!((st.format, st.save_options["aiVersion"].clone()), ("ai", json!("7")), "Save remembers the version");+ assert_eq!(st.save_options["transparentImages"], json!("omit"));+ assert_eq!((st.save_options["hiddenObjects"].clone(), st.save_options["outlineText"].clone()), (json!("visible"), json!(true)));+ }++ /// An Illustrator file opened, then saved as `.ai`: the options dialog stays open through the+ /// Enter that closed the save panel, and only an Enter after it is let go confirms it.+ #[test]+ fn legacy_ai_saves_the_artboards_checked_in_its_picker() {+ let (mut app, written, _) = desktop("art.ai");+ for (i, name) in ["Back", "Side", "Top"].iter().enumerate() {+ let x = 200.0 * (i + 1) as f64;+ app.run("artboard.new", json!({"x": x, "y": 0, "width": 100, "height": 80 + 20 * i, "name": name})).unwrap();+ app.run("shape.ellipse", json!({"x": x + 10.0, "y": 10, "width": 40, "height": 40})).unwrap();+ }+ app.run("file.saveAs", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("aiVersion".into(), json!("7"));+ frame(&mut app, false);+ assert_eq!(dialog(&app).fields["boards"], json!([true, true, true, true]), "every artboard to start with");+ if let Some(dir) = std::env::var_os("CRAFT_UI_SAVE_OPTIONS_SHOT") {+ let mut ready = false;+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).wgpu().build_ui_state(+ move |ui, app: &mut VectorcraftApp| {+ if !ready {+ theme::install_fonts(ui.ctx());+ theme::apply(ui.ctx(), theme::Brightness::MediumDark);+ ready = true;+ return;+ }+ super::super::show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(6);+ h.render().unwrap().save(std::path::Path::new(&dir).join("legacy-ai-picker.png")).unwrap();+ let fields = &mut h.state_mut().ui.dialog.as_mut().unwrap().fields;+ fields.insert("path".into(), json!("desktop-ideas1-vc5.ai"));+ fields.insert("boards".into(), json!([false, false, false, false]));+ h.run_steps(2);+ h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("boards".into(), json!([true, true, false, true]));+ h.run_steps(2);+ h.render().unwrap().save(std::path::Path::new(&dir).join("legacy-ai-picker-long.png")).unwrap();+ h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("boards".into(), json!([false, false, false, false]));+ h.run_steps(2);+ h.render().unwrap().save(std::path::Path::new(&dir).join("legacy-ai-picker-none.png")).unwrap();+ app = h.into_state();+ app.ui.dialog.as_mut().unwrap().fields.insert("path".into(), json!("art.ai"));+ }+ // Clearing them all keeps the dialog open.+ app.ui.dialog.as_mut().unwrap().fields.insert("boards".into(), json!([false, false, false, false]));+ let d = dialog(&app).clone();+ assert!(!can_save(&app, &d), "OK is greyed out");+ frame(&mut app, true);+ assert!(app.ui.dialog.is_some(), "Enter does nothing");+ assert!(confirm(&mut app, &d).is_err());+ assert!(written.borrow().is_empty());+ app.ui.dialog.as_mut().unwrap().fields.insert("boards".into(), json!([true, false, true, false]));+ frame(&mut app, true);+ assert!(app.ui.dialog.is_none());+ let names: Vec<String> = written.borrow().iter().map(|(p, _)| p.clone()).collect();+ assert_eq!(names, ["art-Artboard-1.ai", "art-Side.ai"]);+ assert_eq!(board_files_of(&app, [true, false, true, false]), [Some("art-Artboard-1.ai".into()), None, Some("art-Side.ai".into()), None]);+ assert_eq!(board_files_of(&app, [false, true, false, false]), [None, Some("art.ai".into()), None, None], "one: the file itself");+ // Save As again starts from the artboards saved.+ assert_eq!(app.session.active().unwrap().save_options["range"], json!("1, 3"));+ app.run("file.saveAs", json!({})).unwrap();+ frame(&mut app, false);+ assert_eq!(dialog(&app).fields["boards"], json!([true, false, true, false]));+ }++ fn board_files_of(app: &VectorcraftApp, boards: [bool; 4]) -> Vec<Option<String>> {+ let d = Dialog { kind: KIND.into(), fields: [("path".to_string(), json!("art.ai"))].into_iter().collect() };+ board_files(app, &d, &boards)+ }++ #[test]+ fn the_enter_that_closed_the_save_panel_does_not_confirm_the_options() {+ let (mut app, written, _) = desktop("again.ai");+ let dir = vectorcraft_testkit::temp_dir("ai-options-enter");+ let orig = dir.join("orig.ai");+ std::fs::write(&orig, vectorcraft_testkit::ai::ai(&vectorcraft_testkit::ai::sample_data(), vectorcraft_testkit::ai::page_pdf())).unwrap();+ app.run("document.open", json!({"path": orig.to_string_lossy()})).unwrap();+ assert_eq!(app.run("file.saveAs", json!({})).unwrap()["pending"], KIND);+ frame(&mut app, true);+ assert!(app.ui.dialog.is_some(), "the panel's Enter doesn't confirm it");+ assert!(written.borrow().is_empty());+ // Let go, then pressed again: OK.+ frame(&mut app, false);+ frame(&mut app, true);+ assert!(app.ui.dialog.is_none());+ assert_eq!(written.borrow()[0].0, "again.ai");+ }++ #[test]+ fn save_a_copy_and_template_suggest_their_names() {+ let (mut app, written, picks) = desktop("copy.vectorcraft");+ let folder = vectorcraft_testkit::temp_dir("save-template-dialog");+ app.session.prefs.templates_folder = folder.to_string_lossy().into_owned();+ app.run("file.saveCopy", json!({})).unwrap();+ assert_eq!(picks.borrow()[0].name, "Untitled-1 copy.vectorcraft");+ assert!(app.ui.dialog.is_none(), "the native format has no options");+ assert!(vectorcraft_format::sniff(&written.borrow()[0].1));+ assert!(app.session.active().unwrap().path.is_none() && app.session.active().unwrap().is_dirty());+ app.run("file.saveAsTemplate", json!({})).unwrap();+ let pick = &picks.borrow()[1];+ assert_eq!(pick.name, "Untitled-1 template.vctemplate");+ assert_eq!(pick.folder.as_deref().map(std::path::Path::new), Some(folder.as_path()));+ assert_eq!(+ pick.filters,+ crate::FilePick::filters([("VectorCraft Template", &["vctemplate"][..]), ("PDF-compatible .ait template", &["ait"][..])])+ );+ assert_eq!(written.borrow()[1].0, "copy.vctemplate", "the picked name, its extension replaced with the template's");+ }++ #[test]+ fn save_as_template_writes_ait_when_it_is_picked() {+ let (mut app, written, _) = desktop("flyer.ait");+ app.session.prefs.templates_folder = vectorcraft_testkit::temp_dir("save-template-ait").to_string_lossy().into_owned();+ app.run("file.saveAsTemplate", json!({})).unwrap();+ assert!(app.ui.dialog.is_none(), "a template asks no options");+ let (path, bytes) = written.borrow()[0].clone();+ assert_eq!(path, "flyer.ait", "the picked name is kept");+ assert!(bytes.starts_with(b"%PDF") && vectorcraft_pdf::editing(&bytes).is_some(), "a PDF carrying the document");+ assert!(app.session.active().unwrap().path.is_none() && app.session.active().unwrap().is_dirty());+ // The web's dialog picks the format: .vctemplate first, .ait beside it.+ let (mut app, written) = web();+ app.run("file.saveAsTemplate", json!({})).unwrap();+ assert_eq!((heading(dialog(&app)).as_str(), dialog(&app).str("format").as_str()), ("Save as Template", "template"));+ assert_eq!(template_labels(), ["VectorCraft Template", "PDF-compatible .ait template"]);+ frame(&mut app, false);+ let mut d = app.ui.dialog.take().unwrap();+ switch_format(&mut app, &mut d, "ait");+ assert_eq!((d.str("path").as_str(), d.fields["pdfCompatible"].clone()), ("Untitled-1 template.ait", json!(true)));+ app.ui.dialog = Some(d);+ frame(&mut app, true);+ let (name, bytes) = written.borrow()[0].clone();+ assert_eq!(name, "Untitled-1 template.ait");+ assert!(bytes.starts_with(b"%PDF"));+ }++ /// The `.ait` template's options have no Version row: Save as Template writes it+ /// PDF-compatible only. A `.ai` file's options keep it.+ #[test]+ fn the_ait_template_options_have_no_version_row() {+ let names = |id: &str| shown(fileio::format(id).unwrap()).map(|o| o.name).collect::<Vec<_>>();+ assert!(names("ai").contains(&"aiVersion"), "{:?}", names("ai"));+ assert!(!names("ait").contains(&"aiVersion"), "{:?}", names("ait"));+ }+++/// The native options dialog has no row for `precision`, which agents give with the save++/// command; the rows it has stay.++#[test]++fn the_native_options_have_no_precision_row() {++ for id in ["vectorcraft", "template"] {++ let f = fileio::format(id).unwrap();++ assert!(f.options.iter().any(|o| o.name == "precision"), "{id}");++ let names: Vec<&str> = shown(f).map(|o| o.name).collect();++ assert!(!names.contains(&"precision") && names.contains(&"version") && names.contains(&"compress"), "{id}: {names:?}");++ }++}+++ /// A name typed in the Save as Template panel with a Save As format's extension has it+ /// replaced with the template's, as Save As replaces the extension of a format it doesn't write.+ #[test]+ fn save_as_template_replaces_a_save_formats_extension() {+ for (picked, saved) in [("card.pdf", "card.vctemplate"), ("card.vectorcraft", "card.vctemplate"), ("card.svg", "card.vctemplate")] {+ let (mut app, written, _) = desktop(picked);+ app.session.prefs.templates_folder = vectorcraft_testkit::temp_dir("save-template-ext").to_string_lossy().into_owned();+ app.run("file.saveAsTemplate", json!({})).unwrap();+ let (path, bytes) = written.borrow()[0].clone();+ assert_eq!(path, saved, "typed {picked}");+ assert!(vectorcraft_format::load(&bytes).is_ok_and(|d| d.template), "typed {picked}: a native template");+ }+ }++ #[test]+ fn web_save_as_names_the_file_and_picks_the_format() {+ let (mut app, written) = web();+ app.run("file.saveAs", json!({})).unwrap();+ let d = dialog(&app);+ assert_eq!((heading(d).as_str(), d.str("path").as_str(), d.str("format").as_str()), ("Save As", "Untitled-1.vectorcraft", "vectorcraft"));+ frame(&mut app, false);+ let mut d = app.ui.dialog.take().unwrap();+ switch_format(&mut app, &mut d, "pdf");+ assert_eq!((d.str("path").as_str(), d.str("format").as_str()), ("Untitled-1.pdf", "pdf"));+ assert_eq!(shown(fileio::format("pdf").unwrap()).count(), 0, "PDF options have their own dialog");+ app.ui.dialog = Some(d);+ frame(&mut app, true);+ // OK goes on to the Save PDF dialog, whose OK saves.+ assert_eq!((dialog(&app).kind.as_str(), dialog(&app).str("path").as_str()), ("savePdf", "Untitled-1.pdf"));+ assert!(written.borrow().is_empty());+ super::super::confirm(&mut app).unwrap();+ let (name, bytes) = written.borrow()[0].clone();+ assert_eq!(name, "Untitled-1.pdf");+ assert!(bytes.starts_with(b"%PDF"));+ assert_eq!(app.session.active().unwrap().format, "pdf");+ // A blank name isn't saved.+ app.run("file.saveCopy", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("path".into(), json!(" "));+ assert!(super::super::confirm(&mut app).is_err());+ }++ #[test]+ fn save_as_pdf_asks_with_the_save_pdf_dialog_and_remembers_its_options() {+ let (mut app, written, _) = desktop("art.pdf");+ assert_eq!(app.run("file.saveAs", json!({})).unwrap()["pending"], "savePdf");+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!((d.str("path").as_str(), d.str("__save").as_str()), ("art.pdf", "file.saveAs"));+ d.fields.insert("compatibility".into(), json!("1.5"));+ d.fields.insert("createLayers".into(), json!(true));+ super::super::confirm(&mut app).unwrap();+ assert!(app.ui.dialog.is_none());+ assert!(written.borrow()[0].1.starts_with(b"%PDF-1.5"));+ let st = app.session.active().unwrap();+ assert_eq!((st.path.as_deref(), st.format, st.is_dirty()), (Some("art.pdf"), "pdf", false));+ assert_eq!((st.save_options["compatibility"].clone(), st.save_options["createLayers"].clone()), (json!("1.5"), json!(true)));+ // Save writes the PDF again with those options, without asking.+ app.run("shape.ellipse", json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();+ app.run("file.save", json!({})).unwrap();+ assert!(app.ui.dialog.is_none() && written.borrow()[1].1.starts_with(b"%PDF-1.5"));+ // Save a Copy as PDF starts from them.+ app.run("file.saveCopy", json!({"format": "pdf"})).unwrap();+ assert_eq!(dialog(&app).str("compatibility"), "1.5");+ assert_eq!(dialog(&app).str("__save"), "file.saveCopy");+ }diff --cc docs/mcp.mdindex ae7d184c2,2bef0d6fb..84f5f0f30--- a/docs/mcp.md+++ b/docs/mcp.md@@@ -416,11 -418,12 +418,12 @@@ objects' fills or strokes differ (`fill| `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. || `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee). || `type_text` | `{text}` | Remote only. |+ | `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields}` (a missing `value` is `null`). The app stores all of them or none. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and `action` is not sent. Then `action` `confirm` (OK, `ui.dialog.confirm`) or `cancel` (`ui.dialog.cancel`). Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. || `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. Includes UI commands such as `view.*` and `window.*` in remote mode. || `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. |- | `screenshot` | `{path?, scale?, artboard?, window?, max_side?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. |+ | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. || `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP, Targa (`.tga`/`.vda`/`.icb`/`.vst`), PSD/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. |-| `save_file` | `{path?, compress?, version?, preview?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), and `preview: true` embeds a PNG of the first artboard. `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version` or `preview` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version` or `preview`). `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warning for a top-level `compress`, `version` or `preview`. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. |+| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version`, `preview` or `precision`). `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warning for a top-level `compress`, `version`, `preview` or `precision`. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. || `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF and WMF write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. || `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. || `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. |