From 342d082c2b79adbf7774661f290e9b7376354ad4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 17:26:30 -0800 Subject: [PATCH 01/15] =?UTF-8?q?Scripts:=20Window=20=E2=80=BA=20Script=20?= =?UTF-8?q?Console=20shows=20script=20output,=20errors=20and=20run=20repor?= =?UTF-8?q?ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Scripts write to a new Script Console with $.write(...values) and $.writeln(...values), each value as String(value) gives it. vc.log entries, a run's uncaught error as name:line:column: message, and a start, end and report line for each run go there too. The report line gives the run's time, host calls and slowest commands. - The console keeps at most 2,048 lines and 1 MiB of text, dropping the oldest and counting what it dropped. A line is cut at 4,096 bytes and a script's name at 256 bytes, with a count of cut lines. Line feeds, carriage returns and CRLF break lines; other control characters show as Unicode Control Pictures. - script.run's result and scriptReport gain runTimeMs, timingAvailable, hostCallCounts, slowestCommands and the run's own console. A failed run's report has them too. - script.console and script.console.clear read and empty the console; ui.copyScriptConsole {first?, last?} copies lines as the panel shows them. - The panel lays out only the rows in view, selects with click and Shift-click, and has Clear, Copy Selected and Copy All. Output goes on while it is closed, and Clear works during a run. Docs: docs/mcp.md, docs/gaps.md, docs/roadmap.md, docs/target-app-parity.md. --- crates/engine/src/cmd/scripts.rs | 28 +- crates/engine/src/lib.rs | 4 + crates/engine/src/script/console.rs | 315 ++++++++++++++++++ crates/engine/src/script/mod.rs | 245 +++++++++++++- crates/engine/src/session/documents.rs | 2 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_console.rs | 215 ++++++++++++ crates/js/src/heap.rs | 4 +- crates/js/src/host.rs | 40 ++- crates/js/src/host_tests.rs | 19 ++ crates/js/src/interp.rs | 4 +- crates/ui-egui/src/i18n/bg.tsv | 15 + crates/ui-egui/src/i18n/bs.tsv | 15 + crates/ui-egui/src/i18n/ca.tsv | 16 + crates/ui-egui/src/i18n/cs.tsv | 16 + crates/ui-egui/src/i18n/da.tsv | 15 + crates/ui-egui/src/i18n/de.tsv | 16 + crates/ui-egui/src/i18n/el.tsv | 16 + crates/ui-egui/src/i18n/es.tsv | 16 + crates/ui-egui/src/i18n/fi.tsv | 16 + crates/ui-egui/src/i18n/fr.tsv | 16 + crates/ui-egui/src/i18n/hi.tsv | 16 + crates/ui-egui/src/i18n/hu.tsv | 16 + crates/ui-egui/src/i18n/id.tsv | 15 + crates/ui-egui/src/i18n/it.tsv | 16 + crates/ui-egui/src/i18n/ja.tsv | 16 + crates/ui-egui/src/i18n/ka.tsv | 16 + crates/ui-egui/src/i18n/ko.tsv | 16 + crates/ui-egui/src/i18n/nl.tsv | 15 + crates/ui-egui/src/i18n/pl.tsv | 16 + crates/ui-egui/src/i18n/pt-br.tsv | 16 + crates/ui-egui/src/i18n/ru.tsv | 16 + crates/ui-egui/src/i18n/sv.tsv | 16 + crates/ui-egui/src/i18n/tr.tsv | 16 + crates/ui-egui/src/i18n/uk.tsv | 16 + crates/ui-egui/src/i18n/vi.tsv | 16 + crates/ui-egui/src/i18n/zh-hans.tsv | 16 + crates/ui-egui/src/i18n/zh-hant.tsv | 16 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/tree.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panels.rs | 5 + crates/ui-egui/src/panels/script_console.rs | 187 +++++++++++ .../src/panels/tests_script_console.rs | 98 ++++++ crates/ui-egui/src/state.rs | 1 + docs/gaps.md | 6 +- docs/mcp.md | 43 ++- docs/roadmap.md | 2 +- docs/target-app-parity.md | 1 + 49 files changed, 1625 insertions(+), 30 deletions(-) create mode 100644 crates/engine/src/script/console.rs create mode 100644 crates/engine/src/tests/script_console.rs create mode 100644 crates/ui-egui/src/panels/script_console.rs create mode 100644 crates/ui-egui/src/panels/tests_script_console.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b8b5448817..1ed75194bd 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error)}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -45,6 +45,24 @@ pub fn specs() -> Vec { always, stop ), + cmd!( + query "script.console", + "Script Console", + [], + None, + "{} the Script Console's lines, oldest first: each run's start, its $.write and $.writeln output, its vc.log entries, its uncaught error as name:line:column: message, its end and a report of its time, host calls and slowest commands; a session keeps at most 2048 lines and 1 MiB of text, dropping the oldest, a line at most 4096 bytes and a script's name in its lines at most 256 bytes, each cut with … (VectorCraft's own limits); line feeds, carriage returns and the two together break lines, other control characters show as their Unicode Control Pictures → {lines: [{run: the run's number in the session, name, kind: start|output|log|error|end|report, text}], droppedLines, truncatedLines} (an end line's text is ended: finished|error|fuel|hostLimit|limit|stopped|internal)", + always, + console_lines + ), + cmd!( + query "script.console.clear", + "Clear Script Console", + [], + None, + "{} empty the Script Console and set its dropped and cut counts to zero; a running script goes on writing, and scriptReport keeps the last run's console → {cleared: lines removed}", + always, + console_clear + ), cmd!( query "script.check", "Check Script", @@ -146,6 +164,14 @@ fn stop(s: &mut Session, _: &Value) -> Result { Ok(json!({"stopped": s.script_request_stop()})) } +fn console_lines(s: &mut Session, _: &Value) -> Result { + Ok(s.script_console().to_json()) +} + +fn console_clear(s: &mut Session, _: &Value) -> Result { + Ok(json!({"cleared": s.clear_script_console()})) +} + /// The folder a script is in, which its included files are read from. struct Folder { dir: std::path::PathBuf, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 043158c582..aa032dab42 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -259,6 +259,10 @@ pub struct Session { pub(crate) script_stop: vectorcraft_js::Interrupt, /// The report of the run that ended last. pub(crate) script_report: Option, + /// The Script Console's lines ([`script::console`]). + pub(crate) script_console: script::console::Console, + /// The runs started in this session, which numbers each run's console lines. + pub(crate) script_runs: u64, /// `script.run` starts the job and returns, and the frontend advances it once per frame /// ([`Session::script_pump`]). Off, `script.run` advances it to its end. pub script_frames: bool, diff --git a/crates/engine/src/script/console.rs b/crates/engine/src/script/console.rs new file mode 100644 index 0000000000..eda6feeb42 --- /dev/null +++ b/crates/engine/src/script/console.rs @@ -0,0 +1,315 @@ +//! The Script Console: what scripts write with `$.write` and `$.writeln`, what they log with +//! `vc.log`, their uncaught errors, and a start, an end and a report line for each run. +//! +//! A session keeps its own console, and each run keeps one more for its report. Each holds at most +//! [`MAX_CONSOLE_LINES`] lines and [`MAX_CONSOLE_BYTES`] of text, dropping its oldest lines first, +//! and a line holds at most [`MAX_LINE_BYTES`], cut at a character boundary and ended with +//! [`CUT_MARK`]. A script's name in its lines is cut the same way to [`MAX_NAME_BYTES`]. These are +//! VectorCraft's own limits. A line break is a line feed, a carriage +//! return or the two together. Other control characters show as their Unicode Control Pictures +//! (U+2400 to U+2421), and the line and paragraph separators as U+2424. + +use std::collections::VecDeque; +use std::sync::Arc; + +use serde_json::{Value, json}; + +/// The most lines a console keeps. +pub const MAX_CONSOLE_LINES: usize = 2_048; +/// The most bytes of text (UTF-8) a console keeps. +pub const MAX_CONSOLE_BYTES: usize = 1 << 20; +/// The most bytes (UTF-8) of one line, its cut mark included. +pub const MAX_LINE_BYTES: usize = 4_096; +/// The most bytes (UTF-8) of a script's name as console lines give it, its cut mark included. +pub const MAX_NAME_BYTES: usize = 256; +/// The end of a line that was cut. +pub const CUT_MARK: char = '…'; + +/// How a run ended, as its end line gives it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ending { + /// The script ran to its end and its changes were kept. + Finished, + /// An uncaught error or a syntax error. + Error, + /// The instructions ran out (`maxFuel`). + Fuel, + /// A host limit: host calls, data passed to commands, growth, or a command's fault. + HostLimit, + /// Another limit of the interpreter: heap, call depth or a nested run that could not pause. + Limit, + /// `script.stop`, Stop or a cancel from the caller. + Stopped, + /// A fault inside VectorCraft. + Internal, +} + +impl Ending { + /// The id `script.console` gives. + pub fn id(self) -> &'static str { + match self { + Ending::Finished => "finished", + Ending::Error => "error", + Ending::Fuel => "fuel", + Ending::HostLimit => "hostLimit", + Ending::Limit => "limit", + Ending::Stopped => "stopped", + Ending::Internal => "internal", + } + } +} + +/// A command among the slowest of a run: its id, how often it ran and how long it took. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Slow { + pub id: String, + pub calls: u64, + pub total_ms: u64, + pub max_ms: u64, +} + +/// What a console line holds. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Entry { + /// The run started. + Start, + /// A line of `$.write` and `$.writeln` output. + Output(String), + /// A `vc.log` entry: a string as it is, any other value as JSON. + Log(String), + /// The uncaught error that ended the run: `name:line:column: message`. + Error(String), + /// The run ended. + End(Ending), + /// The run's report: its time (when the platform has a clock), host calls and slowest commands. + Report { ms: Option, host_calls: u64, slowest: Vec }, +} + +impl Entry { + /// The id of the line's kind that `script.console` gives. + pub fn kind(&self) -> &'static str { + match self { + Entry::Start => "start", + Entry::Output(_) => "output", + Entry::Log(_) => "log", + Entry::Error(_) => "error", + Entry::End(_) => "end", + Entry::Report { .. } => "report", + } + } + + /// The line's text in English, as `script.console` and the run report give it. + pub fn text(&self) -> String { + match self { + Entry::Start => "started".to_string(), + Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.clone(), + Entry::End(e) => format!("ended: {}", e.id()), + Entry::Report { ms, host_calls, slowest } => { + let time = ms.map_or_else(|| "time unavailable".to_string(), |ms| format!("{ms} ms")); + let mut s = format!("{time}, {host_calls} host calls"); + if !slowest.is_empty() { + let list: Vec = slowest.iter().map(|c| format!("{} ×{} {} ms", c.id, c.calls, c.total_ms)).collect(); + s.push_str("; slowest: "); + s.push_str(&list.join(", ")); + } + s + } + } + } + + /// The bytes the line counts toward [`MAX_CONSOLE_BYTES`]. + fn bytes(&self) -> usize { + match self { + Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.len(), + Entry::Start | Entry::End(_) => 16, + Entry::Report { slowest, .. } => 48 + slowest.iter().map(|c| c.id.len() + 24).sum::(), + } + } +} + +/// A console line: the run it belongs to, by its number in the session, and the script's name. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConsoleLine { + pub run: u64, + pub name: Arc, + pub entry: Entry, +} + +/// A bounded store of console lines. +#[derive(Clone, Debug, Default)] +pub struct Console { + lines: VecDeque, + bytes: usize, + dropped: u64, + truncated: u64, + /// The number of the first line kept: every line the console was given has its own number, + /// counted from 0, which dropping and clearing do not change. + first: u64, +} + +impl Console { + /// The lines kept, oldest first. + pub fn lines(&self) -> &VecDeque { + &self.lines + } + + /// The number of [`Console::lines`]' first line; each line after it has the next number. + pub fn first_number(&self) -> u64 { + self.first + } + + /// The lines dropped to make room since the console was last cleared. + pub fn dropped_lines(&self) -> u64 { + self.dropped + } + + /// The lines cut to [`MAX_LINE_BYTES`] since the console was last cleared. + pub fn truncated_lines(&self) -> u64 { + self.truncated + } + + /// Removes every line and sets the counts to zero. + pub fn clear(&mut self) { + *self = Self { first: self.first + self.lines.len() as u64, ..Self::default() }; + } + + /// Adds a line, dropping the oldest ones past the limits. `cut`: the line's text was cut. + pub(crate) fn push(&mut self, line: ConsoleLine, cut: bool) { + if cut { + self.truncated = self.truncated.saturating_add(1); + } + let bytes = line.entry.bytes(); + while !self.lines.is_empty() && (self.lines.len() >= MAX_CONSOLE_LINES || self.bytes + bytes > MAX_CONSOLE_BYTES) { + if let Some(old) = self.lines.pop_front() { + self.bytes -= old.entry.bytes(); + self.dropped = self.dropped.saturating_add(1); + self.first += 1; + } + } + self.bytes += bytes; + self.lines.push_back(line); + } + + /// `{lines: [text…], droppedLines, truncatedLines}`, as a run report gives its console. + pub(crate) fn report(&self) -> Value { + let lines: Vec = self.lines.iter().map(|l| l.entry.text()).collect(); + json!({"lines": lines, "droppedLines": self.dropped, "truncatedLines": self.truncated}) + } + + /// `{lines: [{run, name, kind, text}…], droppedLines, truncatedLines}`, as `script.console` + /// gives it. + pub fn to_json(&self) -> Value { + let lines: Vec = + self.lines.iter().map(|l| json!({"run": l.run, "name": &*l.name, "kind": l.entry.kind(), "text": l.entry.text()})).collect(); + json!({"lines": lines, "droppedLines": self.dropped, "truncatedLines": self.truncated}) + } +} + +/// `c` as the console shows it: a control character as its Control Picture, a line or paragraph +/// separator as U+2424, anything else as it is. +fn shown(c: char) -> char { + match c { + '\u{0}'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'), + '\u{7f}' => '\u{2421}', + '\u{80}'..='\u{9f}' => '\u{fffd}', + '\u{2028}' | '\u{2029}' => '\u{2424}', + c => c, + } +} + +/// Adds `text` to `line` as the console shows it, up to [`MAX_LINE_BYTES`]. → `true` when part of +/// it did not fit. +fn append(line: &mut String, text: &str) -> bool { + for c in text.chars().map(shown) { + if line.len() + c.len_utf8() > MAX_LINE_BYTES { + return true; + } + line.push(c); + } + false +} + +/// A script's name as console lines give it: shown as a line shows its text, and cut to +/// [`MAX_NAME_BYTES`] with [`CUT_MARK`]. +pub(crate) fn line_name(name: &str) -> Arc { + let mut out = String::new(); + for c in name.chars().map(shown) { + if out.len() + c.len_utf8() > MAX_NAME_BYTES { + mark_cut(&mut out, MAX_NAME_BYTES); + break; + } + out.push(c); + } + Arc::from(out) +} + +/// Ends a line that was cut with [`CUT_MARK`], within `limit` bytes. +fn mark_cut(line: &mut String, limit: usize) { + let mut at = line.len().min(limit - CUT_MARK.len_utf8()); + while !line.is_char_boundary(at) { + at -= 1; + } + line.truncate(at); + line.push(CUT_MARK); +} + +/// What `$.write` has written of the line it has not ended yet. +#[derive(Debug, Default)] +pub(crate) struct Pending { + text: String, + /// Part of the line did not fit; the rest is left out until the line ends. + cut: bool, + /// The last text written ended with a carriage return, so a line feed next ends no line. + after_cr: bool, +} + +impl Pending { + /// Writes `text`, calling `done` with each line it ends and whether that line was cut. + pub(crate) fn write(&mut self, text: &str, mut done: impl FnMut(String, bool)) { + if text.is_empty() { + return; + } + let mut rest = text; + if self.after_cr && rest.starts_with('\n') { + rest = &rest[1..]; + } + self.after_cr = false; + while let Some(at) = rest.find(['\r', '\n']) { + self.add(&rest[..at]); + done(self.take_line(), self.cut); + self.cut = false; + let skip = if rest[at..].starts_with("\r\n") { 2 } else { 1 }; + if skip == 1 && rest[at..].starts_with('\r') && at + 1 == rest.len() { + self.after_cr = true; + } + rest = &rest[at + skip..]; + } + self.add(rest); + } + + /// Ends the current line, empty or not. + pub(crate) fn end_line(&mut self, mut done: impl FnMut(String, bool)) { + let cut = self.cut; + done(self.take_line(), cut); + self.cut = false; + self.after_cr = false; + } + + /// Is part of a line waiting for its end? + pub(crate) fn is_empty(&self) -> bool { + self.text.is_empty() && !self.cut + } + + fn add(&mut self, text: &str) { + if !self.cut && !text.is_empty() { + self.cut = append(&mut self.text, text); + } + } + + fn take_line(&mut self) -> String { + if self.cut { + mark_cut(&mut self.text, MAX_LINE_BYTES); + } + std::mem::take(&mut self.text) + } +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 9d0a47fbff..772f2c0164 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -20,7 +20,15 @@ //! The values here are VectorCraft's own limits: [`MAX_SOURCE_BYTES`], [`DEFAULT_FUEL`], //! [`MAX_FUEL`], [`SLICE_FUEL`], [`HEAP_BYTES`], [`MAX_HOST_CALLS`], [`GROWTH_OBJECTS`], //! [`GROWTH_BYTES`], [`MAX_CONTINUES`], [`MAX_LOG_LINES`], [`MAX_LOG_BYTES`], [`MAX_ARGS_BYTES`], -//! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default. +//! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default, +//! and the console's ([`console`]). +//! +//! A run writes to the Script Console with `$.write` and `$.writeln`, and `vc.log` adds a line +//! there too. The session's console gets a start line, the run's output, its uncaught error, an end +//! line and a report line; the run's report holds its own output and error, its time, its host +//! calls by kind and its slowest commands. + +pub mod console; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -72,7 +80,9 @@ const MAX_BRIDGE_BYTES: u64 = 4 << 30; /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; /// The features `vc.api.has` knows. -pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args"]; +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console"]; +/// The most commands a run's report lists in `slowestCommands`. +pub const SLOWEST_COMMANDS: usize = 5; /// What the step of a run's one undo step is called. pub const STEP_LABEL: &str = "Run Script"; @@ -446,9 +456,92 @@ struct Host { log: RefCell>, log_bytes: Cell, written: RefCell>, + /// The run's number in its session, and the script's name, which its console lines carry. + run: u64, + name: Arc, + /// The run's own output and error, for its report. + console: RefCell, + /// The line `$.write` has not ended yet. + pending: RefCell, + counts: Counts, + /// Each command `vc.run` ran: its calls, its total time and its longest call, in nanoseconds. + commands: RefCell>, + /// The time the run's slices took, in nanoseconds. + run_nanos: Cell, +} + +/// A run's host calls by kind, as its report gives them in `hostCallCounts`. +#[derive(Default)] +struct Counts { + vc_run: Cell, + document_reads: Cell, + command_list_reads: Cell, + vc_log: Cell, + console_writes: Cell, +} + +impl Counts { + fn json(&self) -> Value { + json!({ + "vcRun": self.vc_run.get(), + "documentReads": self.document_reads.get(), + "commandListReads": self.command_list_reads.get(), + "vcLog": self.vc_log.get(), + "consoleWrites": self.console_writes.get(), + }) + } +} + +fn bump(c: &Cell) { + c.set(c.get().saturating_add(1)); +} + +/// Now, where the platform has a clock (not in a wasm build). +fn clock() -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + Some(std::time::Instant::now()) + } + #[cfg(target_arch = "wasm32")] + { + None + } +} + +/// Whole milliseconds, rounded down. +fn millis(nanos: u128) -> u64 { + u64::try_from(nanos / 1_000_000).unwrap_or(u64::MAX) +} + +/// The [`SLOWEST_COMMANDS`] commands of `times` that took longest in all, longest first and then by +/// id. +pub(crate) fn slowest(times: &HashMap<&'static str, (u64, u128, u128)>) -> Vec { + let mut all: Vec<(&&str, &(u64, u128, u128))> = times.iter().collect(); + all.sort_by(|a, b| b.1.1.cmp(&a.1.1).then_with(|| a.0.cmp(b.0))); + all.into_iter() + .take(SLOWEST_COMMANDS) + .map(|(id, &(calls, total, max))| console::Slow { id: (*id).to_string(), calls, total_ms: millis(total), max_ms: millis(max) }) + .collect() } impl Host { + /// Adds a line to the run's console and, during a slice, to the session's. + fn line(&self, entry: console::Entry, cut: bool) { + let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry }; + if let Ok(mut s) = self.session.try_borrow_mut() { + s.script_console.push(line.clone(), cut); + } + self.console.borrow_mut().push(line, cut); + } + + /// `$.write` and `$.writeln`: `text`, then with `end` a line break. + fn write(&self, text: &str, end: bool) { + let mut pending = self.pending.borrow_mut(); + pending.write(text, |line, cut| self.line(console::Entry::Output(line), cut)); + if end { + pending.end_line(|line, cut| self.line(console::Entry::Output(line), cut)); + } + } fn over(&self, limit: &str) -> HostError { HostError::Abort(limit.to_string()) } @@ -706,11 +799,20 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result done, // A bug is not something a script can handle, and neither is a request to stop. @@ -778,10 +880,39 @@ fn vc_log(host: &Host, args: Vec) -> std::result::Result return Err(HostError::Range(LOG_FULL.to_string())); } host.log_bytes.set(host.log_bytes.get() + bytes); - host.log.borrow_mut().push(to_json(entry)); + let value = to_json(entry); + let text = match &value { + Value::String(s) => s.clone(), + v => v.to_string(), + }; + host.log.borrow_mut().push(value); + each_line(&text, |line, cut| host.line(console::Entry::Log(line), cut)); Ok(Data::Undefined) } +/// Calls `done` with each console line of `text` and whether that line was cut, one at a time. +fn each_line(text: &str, mut done: impl FnMut(String, bool)) { + let mut pending = console::Pending::default(); + pending.write(text, &mut done); + pending.end_line(done); +} + +/// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)` +/// gives them, one after another, and `$.writeln(...values)` does the same and ends the line. +fn dollar_object(host: &Rc) -> Vec<(String, HostItem)> { + let writer = |end: bool| { + let h = host.clone(); + HostItem::TextFunction(function(move |a| { + let text: String = a.iter().map(|d| if let Data::String(s) = d { s.as_str() } else { "" }).collect(); + h.charge_call(text.len() as u64 + 2)?; + bump(&h.counts.console_writes); + h.write(&text, end); + Ok(Data::Undefined) + })) + }; + vec![("write".into(), writer(false)), ("writeln".into(), writer(true))] +} + fn function(f: impl Fn(Vec) -> std::result::Result + 'static) -> HostFunction { Rc::new(f) } @@ -795,6 +926,7 @@ fn vc_object(host: &Rc, args: Data) -> Vec<(String, HostItem)> { let h = host.clone(); function(move |_| { h.charge_call(64)?; + bump(&h.counts.document_reads); vc_document(&h) }) }; @@ -804,6 +936,7 @@ fn vc_object(host: &Rc, args: Data) -> Vec<(String, HostItem)> { let size = data_size(&list); function(move |_| { h.charge_call(size)?; + bump(&h.counts.command_list_reads); Ok((*list).clone()) }) }; @@ -811,6 +944,7 @@ fn vc_object(host: &Rc, args: Data) -> Vec<(String, HostItem)> { let h = host.clone(); function(move |a| { h.charge_call(data_size(a.first().unwrap_or(&Data::Undefined)))?; + bump(&h.counts.vc_log); vc_log(&h, a) }) }; @@ -841,8 +975,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// `message`, with what to do about a failure that comes from a script written for another program. fn explained(kind: &RunErrorKind, message: &str, source: &str, line: u32) -> String { - const HOST_OBJECTS: &[&str] = - &["app", "$", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"]; + const HOST_OBJECTS: &[&str] = &["app", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"]; let names_host_object = message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); let directive = @@ -873,6 +1006,19 @@ impl Session { self.script_report.as_ref() } + /// The Script Console: the lines of this session's runs, oldest first. + pub fn script_console(&self) -> &console::Console { + &self.script_console + } + + /// Empties the Script Console and sets its counts to zero. The last run's report, and the + /// report of a running script, keep their lines. → the lines removed. + pub fn clear_script_console(&mut self) -> usize { + let n = self.script_console.lines().len(); + self.script_console.clear(); + n + } + /// The error text of the last run when it failed: its name, place, message and kind, and the /// files it left written. pub fn script_failure_text(&self) -> Option { @@ -962,6 +1108,7 @@ impl Session { let mut realm = Realm::with_options(options, limits); realm.share_interrupt(&self.script_stop); realm.set_data_limits(DataLimits::default()); + self.script_runs += 1; let host = Rc::new(Host { session: Rc::new(RefCell::new(Session::new())), pause: realm.pause_flag(), @@ -978,12 +1125,25 @@ impl Session { log: RefCell::new(Vec::new()), log_bytes: Cell::new(0), written: RefCell::new(Vec::new()), + run: self.script_runs, + name: console::line_name(&request.name), + console: RefCell::default(), + pending: RefCell::default(), + counts: Counts::default(), + commands: RefCell::default(), + run_nanos: Cell::new(0), }); let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) .map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?; - let started = realm.define_host_object("vc", vc_object(&host, args)).and_then(|()| realm.start(&request.source)); + let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start }; + self.script_console.push(line, false); + let started = realm + .define_host_object("vc", vc_object(&host, args)) + .and_then(|()| realm.define_host_object("$", dollar_object(&host))) + .and_then(|()| realm.start(&request.source)); if let Err(e) = started { - let report = failure_report(&request.name, &e, &request.source, &host, 0); + let mut report = failure_report(&request.name, &e, &request.source, &host, 0, 0); + close_run(self, &host, &mut report, ending(&e.kind)); let message = failure_text(&report); self.script_report = Some(report); return Err(EngineError::Other(message)); @@ -1033,7 +1193,9 @@ impl Session { } fn script_failed(&mut self, job: Job, e: &RunError) -> Result { - let report = failure_report(&job.name, e, "", &job.host, job.realm.fuel_left()); + let fuel_left = job.realm.fuel_left(); + let mut report = failure_report(&job.name, e, "", &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); + close_run(self, &job.host, &mut report, ending(&e.kind)); drop(job); raise_ids(self); self.script_stop.clear(); @@ -1106,7 +1268,7 @@ impl Session { self.reset_tool(); cmd::compositefonts::sync(self); let host = &job.host; - let report = json!({ + let mut report = json!({ "ok": true, "name": job.name, "changed": changed_names, @@ -1115,6 +1277,7 @@ impl Session { "fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(), "hostCalls": host.calls.get(), }); + close_run(self, host, &mut report, console::Ending::Finished); self.script_report = Some(report.clone()); Ok(report) } @@ -1147,7 +1310,7 @@ const LOG_FULL: &str = "vc.log: the log of this run is full"; const NO_RECOVERY_COPY: &str = "a recovery copy could not be written, so the script was not run"; /// The report of a run that failed. -fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left: u64) -> Value { +fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { json!({ "ok": false, "kind": kind_id(&e.kind), @@ -1158,9 +1321,67 @@ fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left "written": *host.written.borrow(), "log": *host.log.borrow(), "fuelLeft": fuel_left, + "fuelUsed": fuel_used, + "hostCalls": host.calls.get(), }) } +/// How the run that failed with `kind` ended, as its console end line gives it. +fn ending(kind: &RunErrorKind) -> console::Ending { + match kind { + RunErrorKind::Syntax | RunErrorKind::Thrown => console::Ending::Error, + RunErrorKind::Limit(LimitKind::Fuel) => console::Ending::Fuel, + RunErrorKind::Limit(LimitKind::Host) => console::Ending::HostLimit, + RunErrorKind::Limit(LimitKind::Interrupted) => console::Ending::Stopped, + RunErrorKind::Limit(_) => console::Ending::Limit, + RunErrorKind::Internal => console::Ending::Internal, + } +} + +/// Adds a line of `host`'s run to the session's console and to the run's own. +fn line_to(s: &mut Session, host: &Host, entry: console::Entry, cut: bool) { + let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry }; + s.script_console.push(line.clone(), cut); + host.console.borrow_mut().push(line, cut); +} + +/// Ends the console lines of `host`'s run: the line `$.write` left unended, then for a failed run +/// (`report["ok"]` false) its error as `name:line:column: message`, then an end line and a report +/// line in the session's console. Adds the run's time, host calls by kind, slowest commands and +/// console to `report`. +fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::Ending) { + let mut pending = std::mem::take(&mut *host.pending.borrow_mut()); + if !pending.is_empty() { + let mut last = None; + pending.end_line(|line, cut| last = Some((line, cut))); + if let Some((line, cut)) = last { + line_to(s, host, console::Entry::Output(line), cut); + } + } + if report["ok"] == false { + let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); + let message = report["message"].as_str().unwrap_or_default(); + let text = + if line > 0 { format!("{}:{line}:{column}: {message}", host.name) } else { format!("{}: location unavailable: {message}", host.name) }; + each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + let timing = clock().is_some(); + let ms = millis(host.run_nanos.get()); + let slow = slowest(&host.commands.borrow()); + let slow_json: Vec = slow.iter().map(|c| json!({"id": c.id, "calls": c.calls, "totalMs": c.total_ms, "maxMs": c.max_ms})).collect(); + let line = |entry| console::ConsoleLine { run: host.run, name: host.name.clone(), entry }; + s.script_console.push(line(console::Entry::End(ending)), false); + let summary = console::Entry::Report { ms: timing.then_some(ms), host_calls: host.calls.get(), slowest: slow }; + s.script_console.push(line(summary), false); + if let Some(o) = report.as_object_mut() { + o.insert("runTimeMs".into(), json!(if timing { ms } else { 0 })); + o.insert("timingAvailable".into(), json!(timing)); + o.insert("hostCallCounts".into(), host.counts.json()); + o.insert("slowestCommands".into(), Value::Array(slow_json)); + o.insert("console".into(), host.console.borrow().report()); + } +} + /// The text of a failed run's error. fn failure_text(report: &Value) -> String { let s = |k: &str| report[k].as_str().unwrap_or_default(); @@ -1187,6 +1408,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// The session console's `(run, kind, text)` lines. +fn lines(s: &mut Session) -> Vec<(u64, String, String)> { + let c = s.execute("script.console", &json!({})).unwrap(); + c["lines"] + .as_array() + .unwrap() + .iter() + .map(|l| (l["run"].as_u64().unwrap(), l["kind"].as_str().unwrap().to_string(), l["text"].as_str().unwrap().to_string())) + .collect() +} + +fn texts(s: &mut Session, kind: &str) -> Vec { + lines(s).into_iter().filter(|(_, k, _)| k == kind).map(|(_, _, t)| t).collect() +} + +#[test] +fn write_and_writeln_join_their_values_and_break_lines() { + let mut s = Session::new(); + run(&mut s, "$.write('a', 1, null, undefined, 1/0); $.write('b\\r\\nc\\rd\\n'); $.writeln(); $.write('x\\r'); $.write('\\ny'); $.writeln([1, 2], {}); $.write('p\\r'); $.write(''); $.write('\\nq'); $.writeln(); $.write('\\0\\t\\u2028\\x7f')").unwrap(); + let want = ["a1nullundefinedInfinityb", "c", "d", "", "x", "y1,2[object Object]", "p", "q", "\u{2400}\u{2409}\u{2424}\u{2421}"]; + assert_eq!(texts(&mut s, "output"), want); + let report = s.script_report().unwrap(); + assert_eq!(report["console"]["lines"], json!(want), "the run's own console holds the same output"); + assert_eq!(report["hostCallCounts"]["consoleWrites"], 11); +} + +#[test] +fn an_endless_writeln_stays_within_the_line_limit_and_counts_what_it_dropped() { + let mut s = Session::new(); + let e = s.execute("script.run", &json!({"source": "while (1) $.writeln('x')", "name": "t.js", "maxFuel": 2_000_000})).unwrap_err(); + assert!(e.to_string().ends_with("(limit)"), "{e}"); + let c = s.execute("script.console", &json!({})).unwrap(); + let kept = c["lines"].as_array().unwrap().len(); + assert_eq!(kept, MAX_CONSOLE_LINES); + let report = s.script_report().unwrap().clone(); + let writes = report["hostCallCounts"]["consoleWrites"].as_u64().unwrap(); + assert!(writes > MAX_CONSOLE_LINES as u64 * 2, "{writes} writes"); + // The session console holds a start line, the output, an error, an end and a report line. + assert_eq!(c["droppedLines"].as_u64().unwrap(), writes + 4 - MAX_CONSOLE_LINES as u64); + assert_eq!(report["console"]["lines"].as_array().unwrap().len(), MAX_CONSOLE_LINES); + assert_eq!(report["console"]["droppedLines"].as_u64().unwrap(), writes + 1 - MAX_CONSOLE_LINES as u64); + assert!(report["fuelUsed"].as_u64().unwrap() > 1_900_000); + assert_eq!(report["hostCalls"].as_u64().unwrap(), writes); + let tail = lines(&mut s); + let ends: Vec<&str> = tail.iter().rev().take(3).map(|(_, k, t)| if k == "error" { "error" } else { t.as_str() }).collect(); + assert_eq!(ends[1], "ended: fuel"); + assert_eq!(ends[2], "error", "{tail:?}"); +} + +#[test] +fn long_lines_stay_within_the_byte_limit() { + let mut s = Session::new(); + let source = "var l = new Array(4000).join('y'); for (var i = 0; i < 400; i++) $.writeln(l)"; + run(&mut s, source).unwrap(); + let c = s.execute("script.console", &json!({})).unwrap(); + let bytes: usize = c["lines"].as_array().unwrap().iter().map(|l| l["text"].as_str().unwrap().len()).sum(); + assert!(bytes <= MAX_CONSOLE_BYTES, "{bytes}"); + let kept = c["lines"].as_array().unwrap().len(); + assert!(kept < 400 && kept > 200, "{kept} lines"); + assert!(c["droppedLines"].as_u64().unwrap() > 100); +} + +#[test] +fn a_huge_line_is_cut_at_a_character_boundary_and_counted() { + let mut s = Session::new(); + run(&mut s, "$.writeln(new Array(5000).join('é')); $.write(new Array(3000).join('a')); $.write(new Array(3000).join('b')); $.writeln('c'); $.writeln('ok')") + .unwrap(); + let out = texts(&mut s, "output"); + assert_eq!(out.len(), 3); + for line in &out[..2] { + assert!(line.len() <= MAX_LINE_BYTES && line.len() > MAX_LINE_BYTES - 8, "{}", line.len()); + assert!(line.ends_with(CUT_MARK)); + } + assert!(!out[1].contains('c'), "the rest of a cut line is left out until it ends"); + assert_eq!(out[2], "ok"); + let c = s.execute("script.console", &json!({})).unwrap(); + assert_eq!(c["truncatedLines"], 2); + assert_eq!(s.script_report().unwrap()["console"]["truncatedLines"], 2); +} + +#[test] +fn a_long_script_name_is_cut_in_every_line_and_shows_its_control_characters() { + let mut s = Session::new(); + let name = format!("a\nb{}", "é".repeat(100_000)); + s.execute("script.run", &json!({"source": "$.writeln('x'); $.writeln('y')", "name": name})).unwrap(); + let c = s.execute("script.console", &json!({})).unwrap(); + let names: Vec<&str> = c["lines"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names.len(), 5); + for n in names { + assert!(n.len() <= MAX_NAME_BYTES && n.len() > MAX_NAME_BYTES - 8, "{}", n.len()); + assert!(n.starts_with("a\u{240a}b") && n.ends_with(CUT_MARK), "{n}"); + } + assert_eq!(s.script_report().unwrap()["name"].as_str().map(str::len), Some(name.len()), "the report keeps the name given"); +} + +#[test] +fn an_uncaught_error_shows_the_script_its_line_and_column() { + let mut s = Session::new(); + run(&mut s, "$.write('half');\n\n throw new Error('boom\\nsecond');").unwrap_err(); + let all = lines(&mut s); + let kinds: Vec<&str> = all.iter().map(|(_, k, _)| k.as_str()).collect(); + assert_eq!(kinds, ["start", "output", "error", "error", "end", "report"]); + assert_eq!(all[1].2, "half", "a line left unended still shows"); + assert_eq!(all[2].2, "t.js:3:3: Error: boom"); + assert_eq!(all[3].2, "second"); + assert_eq!(all[4].2, "ended: error"); + let report = s.script_report().unwrap(); + assert_eq!(report["console"]["lines"], json!(["half", "t.js:3:3: Error: boom", "second"])); + let mut s = Session::new(); + run(&mut s, "var = 1").unwrap_err(); + assert!(texts(&mut s, "error")[0].starts_with("t.js:1:"), "a syntax error has its place too"); + let mut s = Session::new(); + s.script_frames = true; + run(&mut s, "while (true) {}").unwrap(); + s.script_abandon(); + assert_eq!(texts(&mut s, "error"), ["t.js: location unavailable: limit reached: Interrupted"]); +} + +#[test] +fn the_result_and_the_report_agree_and_count_each_kind_of_host_call() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let source = "vc.run('shape.rectangle', {x:0,y:0,width:5,height:5}); vc.run('shape.rectangle', {x:9,y:0,width:5,height:5}); \ + try { vc.run('no.such', {}); } catch (e) {} var d = vc.document; var c = vc.commands; vc.log({a: 1}); vc.log('two\\nlines'); $.writeln('w');"; + let r = run(&mut s, source).unwrap(); + assert_eq!(&r, s.script_report().unwrap()); + assert_eq!(r["hostCallCounts"], json!({"vcRun": 3, "documentReads": 1, "commandListReads": 1, "vcLog": 2, "consoleWrites": 1})); + assert_eq!(r["timingAvailable"], true); + assert!(r["runTimeMs"].is_u64()); + let slow = r["slowestCommands"].as_array().unwrap(); + assert_eq!(slow.len(), 1, "an unknown command is not timed: {slow:?}"); + assert_eq!((slow[0]["id"].as_str(), slow[0]["calls"].as_u64()), (Some("shape.rectangle"), Some(2))); + assert!(slow[0]["maxMs"].as_u64() <= slow[0]["totalMs"].as_u64()); + assert_eq!(r["console"]["lines"], json!(["{\"a\":1}", "two", "lines", "w"])); + assert_eq!(texts(&mut s, "log"), ["{\"a\":1}", "two", "lines"]); + assert_eq!(texts(&mut s, "end"), ["ended: finished"]); + assert!(texts(&mut s, "report")[0].contains("host calls; slowest: shape.rectangle ×2"), "{:?}", texts(&mut s, "report")); + assert_eq!(r["log"], json!([{"a": 1}, "two\nlines"]), "the log keeps its values"); +} + +#[test] +fn a_stopped_run_reports_its_diagnostics_and_its_unended_line() { + let mut s = Session::new(); + s.script_frames = true; + run(&mut s, "$.write('so far'); vc.log(1); while (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + assert_eq!(texts(&mut s, "log"), ["1"], "a line shows while the run goes on"); + s.execute("script.stop", &json!({})).unwrap(); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!(report["kind"], "stopped"); + for key in ["runTimeMs", "hostCallCounts", "slowestCommands", "console", "fuelUsed", "hostCalls", "timingAvailable"] { + assert!(!report[key].is_null(), "{key}: {report}"); + } + assert_eq!(report["hostCalls"], 2); + assert_eq!(texts(&mut s, "output"), ["so far"]); + assert_eq!(texts(&mut s, "end"), ["ended: stopped"]); +} + +#[test] +fn runs_are_numbered_a_busy_run_adds_nothing_and_clear_keeps_the_report() { + let mut s = Session::new(); + for _ in 0..3 { + run(&mut s, "for (var i = 0; i < 1000; i++) $.writeln(i)").unwrap(); + } + let all = lines(&mut s); + assert_eq!(all.len(), MAX_CONSOLE_LINES); + assert_eq!(all.last().map(|l| l.0), Some(3)); + s.script_frames = true; + run(&mut s, "$.writeln('four'); while (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + let before = lines(&mut s); + assert!(matches!(run(&mut s, "$.writeln('five')"), Err(EngineError::Busy))); + assert_eq!(lines(&mut s), before, "a refused run adds no line"); + assert_eq!(s.execute("script.console.clear", &json!({})).unwrap()["cleared"], MAX_CONSOLE_LINES); + let c = s.execute("script.console", &json!({})).unwrap(); + assert_eq!((c["lines"].as_array().map(Vec::len), c["droppedLines"].as_u64()), (Some(0), Some(0))); + s.execute("script.stop", &json!({})).unwrap(); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!(report["console"]["lines"][0], "four", "a clear leaves the running script's own console"); + assert_eq!(texts(&mut s, "end"), ["ended: stopped"], "the run goes on writing after a clear"); + assert_eq!(lines(&mut s)[0].0, 4); + let mut other = Session::new(); + assert!(lines(&mut other).is_empty(), "each session has its own console"); +} + +#[test] +fn the_slowest_commands_are_the_longest_in_all_then_by_id() { + let times = std::collections::HashMap::from([ + ("a.one", (1, 5_000_000, 5_000_000)), + ("b.two", (3, 9_000_000, 4_000_000)), + ("c.three", (1, 5_000_000, 5_000_000)), + ("d", (1, 1, 1)), + ("e", (1, 2, 2)), + ("f", (1, 3, 3)), + ]); + let slow = script::slowest(×); + let ids: Vec<&str> = slow.iter().map(|c| c.id.as_str()).collect(); + assert_eq!(ids, ["b.two", "a.one", "c.three", "f", "e"]); + assert_eq!((slow[0].calls, slow[0].total_ms, slow[0].max_ms), (3, 9, 4)); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index a53721fc71..1399c05701 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -175,12 +175,14 @@ pub(crate) enum NativeKind { /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section /// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given. +/// `Data` is a host function given [`crate::Data`]; with `text`, each argument arrives as the +/// string `String(value)` gives. #[derive(Clone)] pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, Host { f: Rc, name: Rc }, - Data { f: DataFn, name: Rc }, + Data { f: DataFn, name: Rc, text: bool }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 457b2ce2e1..888fb3d95b 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -68,6 +68,8 @@ pub enum HostItem { /// A read-only copy of a value. Value(Data), Function(HostFunction), + /// A function whose arguments arrive as strings, each the string `String(value)` gives. + TextFunction(HostFunction), /// A property whose value the function gives each time it is read. Getter(HostFunction), /// A frozen object with these members. @@ -275,15 +277,31 @@ impl Interp { Ok(Value::Object(id)) } - /// Calls host function `f`: reads its arguments, runs it, and gives its result to the script. - pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value]) -> JsResult { + /// Calls host function `f`: reads its arguments (with `text`, each as the string `String(value)` + /// gives), runs it, and gives its result to the script. + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], text: bool) -> JsResult { let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; let mut data = Vec::with_capacity(args.len()); + // A conversion can run the script's own `toString`, which may collect garbage. + let mark = self.temp_roots.len(); + if text { + self.temp_roots.extend(args.iter().cloned()); + } + let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); - data.push(self.read_data(a, &mut reading)?); + let d = if text { self.read_text(a, &mut reading) } else { self.read_data(a, &mut reading) }; + match d { + Ok(d) => data.push(d), + Err(e) => { + read = Err(e); + break; + } + } reading.path.pop(); } + self.temp_roots.truncate(mark); + read?; match f(data) { Ok(d) => self.write_data(d, 0, false), Err(HostError::Abort(message)) => { @@ -296,6 +314,13 @@ impl Interp { } } + /// `v` as the string `String(v)` gives, within the limits of a crossing. + fn read_text(&mut self, v: &Value, r: &mut Reading) -> JsResult { + let s = self.to_str(v)?; + self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?; + Ok(Data::String(s.to_rust_string())) + } + /// The exception for a host error, charged to the heap. fn throw_host(&mut self, t: ErrorType, message: &str) -> JsResult { let bytes = string_bytes(message.encode_utf16().count()); @@ -332,16 +357,17 @@ impl Interp { let full = format!("{path}.{name}"); let prop = match item { HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE }, - HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full)), flags: ENUMERABLE }, - HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full)), set: None, flags: ENUMERABLE }, + HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, false)), flags: ENUMERABLE }, + HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, true)), flags: ENUMERABLE }, + HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, false)), set: None, flags: ENUMERABLE }, HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, }; self.define(o, key(&name), prop) } - fn host_function(&mut self, f: HostFunction, name: &str) -> ObjId { + fn host_function(&mut self, f: HostFunction, name: &str, text: bool) -> ObjId { let proto = self.intrinsics.function_proto; - self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into() }), Some(proto))) + self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), text }), Some(proto))) } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 85e178d879..93875f6d1f 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -223,6 +223,25 @@ fn a_getter_is_read_each_time() { assert_eq!(r.run("host.n + host.n").unwrap(), JsValue::Number(3.0)); } +#[test] +fn a_text_function_takes_each_argument_as_string_gives_it() { + let mut r = realm(1_000_000); + let seen: Rc>> = Rc::default(); + let log = seen.clone(); + let f: HostFunction = Rc::new(move |args| { + log.borrow_mut().extend(args); + Ok(Data::Undefined) + }); + r.define_host_object("host", vec![("text".into(), HostItem::TextFunction(f))]).unwrap(); + r.run("host.text(1 / 0, NaN, undefined, null, 0.1, [1, [2]], {toString: function () { return 'own'; }}, function f() {}, '\\ud800x')").unwrap(); + let texts: Vec = seen.borrow().iter().map(|d| if let Data::String(s) = d { s.clone() } else { format!("{d:?}") }).collect(); + assert_eq!(texts[..7], ["Infinity", "NaN", "undefined", "null", "0.1", "1,2", "own"]); + assert!(texts[7].starts_with("function f()"), "{}", texts[7]); + assert_eq!(texts[8], "\u{fffd}x", "a lone surrogate becomes U+FFFD"); + let e = r.run("host.text({toString: function () { throw new Error('no text'); }})").unwrap_err(); + assert!(e.message.contains("no text"), "{}", e.message); +} + #[test] fn errors_from_the_host_can_be_caught_and_an_abort_cannot() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f868149492..ee711ffb3a 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1846,10 +1846,10 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } - Func::Data { f, name } => { + Func::Data { f, name, text } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. - return Ok(Prepared::Done(self.call_data(&f, &name, &args)?)); + return Ok(Prepared::Done(self.call_data(&f, &name, &args, text)?)); } Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 354d811a34..751f18b221 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6461,3 +6461,18 @@ breakText Glyphs Глифи @msg side is left or right, not `{s}` side е left или right, а не `{s}` Edit Custom Dictionary Редактиране на потребителски речник Entry: Запис: +# Script Console + Script Console Конзола за скриптове + Clear Script Console Изчистване на конзолата за скриптове + Copy Script Console Копиране на конзолата за скриптове + Copy All Копиране на всичко + Copy Selected Копиране на избраното + Finished Завършен + Ended with an error Прекратен с грешка + Out of fuel Достигнат лимит на инструкциите + Ended at a host limit Прекратен при лимит на хоста + Ended at a limit Прекратен при лимит + Stopped Спрян + Ended by an internal fault Прекратен поради вътрешна грешка + {ms} ms, {calls} host calls {ms} ms, {calls} извиквания към хоста + {dropped} earlier lines dropped, {cut} lines cut {dropped} по-ранни реда премахнати, {cut} реда съкратени diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d1fc0ea540..1155833e80 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6512,3 +6512,18 @@ shape Open Otvoren @msg side is left or right, not `{s}` side je left ili right, a ne `{s}` Edit Custom Dictionary Uredi prilagođeni rječnik Entry: Unos: +# Script Console + Script Console Konzola skripti + Clear Script Console Očisti konzolu skripti + Copy Script Console Kopiraj konzolu skripti + Copy All Kopiraj sve + Copy Selected Kopiraj odabrano + Finished Završeno + Ended with an error Završeno s greškom + Out of fuel Dostignuto ograničenje instrukcija + Ended at a host limit Završeno na ograničenju hosta + Ended at a limit Završeno na ograničenju + Stopped Zaustavljeno + Ended by an internal fault Završeno zbog interne greške + {ms} ms, {calls} host calls {ms} ms, {calls} poziva hosta + {dropped} earlier lines dropped, {cut} lines cut {dropped} ranijih redova uklonjeno, {cut} redova skraćeno diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9e77ecb32f..fea272bc8a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6714,3 +6714,19 @@ breakText Glyphs Glifs No Suggestions No hi ha suggeriments Edit Custom Dictionary Edita el diccionari personalitzat Entry: Entrada: +# Script Console + Script Console Consola d’scripts + Clear Script Console Esborra la consola d’scripts + Copy Script Console Copia la consola d’scripts + Copy All Copia-ho tot + Copy Selected Copia la selecció + Finished Acabat + Ended with an error Acabat amb un error + Out of fuel Límit d’instruccions esgotat + Ended at a host limit Acabat en un límit de l’amfitrió + Ended at a limit Acabat en un límit + Stopped Aturat + Ended by an internal fault Acabat per un error intern + {ms} ms, {calls} host calls {ms} ms, {calls} crides a l’amfitrió + {dropped} earlier lines dropped, {cut} lines cut {dropped} línies anteriors descartades, {cut} línies tallades +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` han de ser números de línies que la consola conserva, `first` abans de `last` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index de1723b906..5466dec6f8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6733,3 +6733,19 @@ breakText Glyphs Glyfy No Suggestions Žádné návrhy Edit Custom Dictionary Upravit vlastní slovník Entry: Položka: +# Script Console + Script Console Konzole skriptů + Clear Script Console Vymazat konzoli skriptů + Copy Script Console Kopírovat konzoli skriptů + Copy All Kopírovat vše + Copy Selected Kopírovat vybrané + Finished Dokončeno + Ended with an error Ukončeno s chybou + Out of fuel Vyčerpán limit instrukcí + Ended at a host limit Ukončeno na limitu hostitele + Ended at a limit Ukončeno na limitu + Stopped Zastaveno + Ended by an internal fault Ukončeno vnitřní chybou + {ms} ms, {calls} host calls {ms} ms, {calls} volání hostitele + {dropped} earlier lines dropped, {cut} lines cut {dropped} starších řádků zahozeno, {cut} řádků zkráceno +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` a `last` musí být čísla řádků, které konzole uchovává, `first` před `last` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 77687493e5..0c70a17faf 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6475,3 +6475,18 @@ breakText Glyphs Glyffer @msg side is left or right, not `{s}` side er left eller right, ikke `{s}` Edit Custom Dictionary Redigér egen ordliste Entry: Opslag: +# Script Console + Script Console Scriptkonsol + Clear Script Console Ryd scriptkonsollen + Copy Script Console Kopiér scriptkonsollen + Copy All Kopiér alt + Copy Selected Kopiér markeret + Finished Færdig + Ended with an error Afsluttet med en fejl + Out of fuel Instruktionsgrænsen er nået + Ended at a host limit Afsluttet ved en værtsgrænse + Ended at a limit Afsluttet ved en grænse + Stopped Stoppet + Ended by an internal fault Afsluttet af en intern fejl + {ms} ms, {calls} host calls {ms} ms, {calls} værtskald + {dropped} earlier lines dropped, {cut} lines cut {dropped} tidligere linjer fjernet, {cut} linjer afkortet diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7e2619386b..b2ea6d789d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6320,3 +6320,19 @@ breakText Glyphs Glyphen No Suggestions Keine Vorschläge Edit Custom Dictionary Benutzerwörterbuch bearbeiten Entry: Eintrag: +# Script Console + Script Console Skriptkonsole + Clear Script Console Skriptkonsole leeren + Copy Script Console Skriptkonsole kopieren + Copy All Alles kopieren + Copy Selected Auswahl kopieren + Finished Beendet + Ended with an error Mit einem Fehler beendet + Out of fuel Anweisungslimit erreicht + Ended at a host limit An einem Host-Limit beendet + Ended at a limit An einem Limit beendet + Stopped Gestoppt + Ended by an internal fault Durch einen internen Fehler beendet + {ms} ms, {calls} host calls {ms} ms, {calls} Host-Aufrufe + {dropped} earlier lines dropped, {cut} lines cut {dropped} ältere Zeilen verworfen, {cut} Zeilen gekürzt +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` und `last` müssen Nummern von Zeilen sein, die die Konsole enthält, `first` vor `last` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a95d84be33..7068c6a74b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6685,3 +6685,19 @@ breakText Glyphs Γλύφοι No Suggestions Καμία πρόταση Edit Custom Dictionary Επεξεργασία προσαρμοσμένου λεξικού Entry: Λήμμα: +# Script Console + Script Console Κονσόλα σεναρίων + Clear Script Console Εκκαθάριση κονσόλας σεναρίων + Copy Script Console Αντιγραφή κονσόλας σεναρίων + Copy All Αντιγραφή όλων + Copy Selected Αντιγραφή επιλεγμένων + Finished Ολοκληρώθηκε + Ended with an error Τερματίστηκε με σφάλμα + Out of fuel Εξαντλήθηκε το όριο εντολών + Ended at a host limit Τερματίστηκε σε όριο του κεντρικού συστήματος + Ended at a limit Τερματίστηκε σε όριο + Stopped Διακόπηκε + Ended by an internal fault Τερματίστηκε λόγω εσωτερικού σφάλματος + {ms} ms, {calls} host calls {ms} ms, {calls} κλήσεις προς το κεντρικό σύστημα + {dropped} earlier lines dropped, {cut} lines cut {dropped} παλαιότερες γραμμές απορρίφθηκαν, {cut} γραμμές περικόπηκαν +@msg `first` and `last` must be numbers of lines the console holds, first before last Τα `first` και `last` πρέπει να είναι αριθμοί γραμμών που κρατά η κονσόλα, το `first` πριν από το `last` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e0903d19d7..3d6a0ffe91 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6676,3 +6676,19 @@ breakText Glyphs Glifos No Suggestions No hay sugerencias Edit Custom Dictionary Editar diccionario personalizado Entry: Entrada: +# Script Console + Script Console Consola de scripts + Clear Script Console Borrar consola de scripts + Copy Script Console Copiar consola de scripts + Copy All Copiar todo + Copy Selected Copiar selección + Finished Terminado + Ended with an error Terminado con un error + Out of fuel Límite de instrucciones agotado + Ended at a host limit Terminado en un límite del host + Ended at a limit Terminado en un límite + Stopped Detenido + Ended by an internal fault Terminado por un error interno + {ms} ms, {calls} host calls {ms} ms, {calls} llamadas al host + {dropped} earlier lines dropped, {cut} lines cut {dropped} líneas anteriores descartadas, {cut} líneas recortadas +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` y `last` deben ser números de líneas que la consola conserva, `first` antes que `last` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b593200aa5..075319a613 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6768,3 +6768,19 @@ breakText Glyphs Merkit No Suggestions Ei ehdotuksia Edit Custom Dictionary Muokkaa omaa sanastoa Entry: Merkintä: +# Script Console + Script Console Komentosarjakonsoli + Clear Script Console Tyhjennä komentosarjakonsoli + Copy Script Console Kopioi komentosarjakonsoli + Copy All Kopioi kaikki + Copy Selected Kopioi valitut + Finished Valmis + Ended with an error Päättyi virheeseen + Out of fuel Käskyraja täyttyi + Ended at a host limit Päättyi isännän rajaan + Ended at a limit Päättyi rajaan + Stopped Pysäytetty + Ended by an internal fault Päättyi sisäiseen virheeseen + {ms} ms, {calls} host calls {ms} ms, {calls} isäntäkutsua + {dropped} earlier lines dropped, {cut} lines cut {dropped} aiempaa riviä poistettu, {cut} riviä katkaistu +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` ja `last` on oltava konsolin säilyttämien rivien numeroita, `first` ennen arvoa `last` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6dd4e37a41..0a7e3e2e83 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6728,3 +6728,19 @@ breakText Glyphs Glyphes No Suggestions Aucune suggestion Edit Custom Dictionary Modifier le dictionnaire personnalisé Entry: Entrée : +# Script Console + Script Console Console de scripts + Clear Script Console Effacer la console de scripts + Copy Script Console Copier la console de scripts + Copy All Tout copier + Copy Selected Copier la sélection + Finished Terminé + Ended with an error Terminé avec une erreur + Out of fuel Limite d’instructions atteinte + Ended at a host limit Terminé à une limite de l’hôte + Ended at a limit Terminé à une limite + Stopped Arrêté + Ended by an internal fault Terminé par une erreur interne + {ms} ms, {calls} host calls {ms} ms, {calls} appels à l’hôte + {dropped} earlier lines dropped, {cut} lines cut {dropped} lignes antérieures supprimées, {cut} lignes coupées +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` et `last` doivent être des numéros de lignes que la console contient, `first` avant `last` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3397e7f347..3890f4c5cf 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8174,3 +8174,19 @@ theme Appearance अपीयरेंस No Suggestions कोई सुझाव नहीं Edit Custom Dictionary कस्टम शब्दकोश संपादित करें Entry: प्रविष्टि: +# Script Console + Script Console स्क्रिप्ट कंसोल + Clear Script Console स्क्रिप्ट कंसोल साफ़ करें + Copy Script Console स्क्रिप्ट कंसोल कॉपी करें + Copy All सब कॉपी करें + Copy Selected चयनित कॉपी करें + Finished पूरा हुआ + Ended with an error त्रुटि के साथ समाप्त + Out of fuel निर्देश सीमा समाप्त + Ended at a host limit होस्ट सीमा पर समाप्त + Ended at a limit सीमा पर समाप्त + Stopped रोका गया + Ended by an internal fault आंतरिक त्रुटि से समाप्त + {ms} ms, {calls} host calls {ms} ms, {calls} होस्ट कॉल + {dropped} earlier lines dropped, {cut} lines cut {dropped} पुरानी पंक्तियाँ हटाई गईं, {cut} पंक्तियाँ काटी गईं +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` और `last` कंसोल में रखी पंक्तियों की संख्याएँ होनी चाहिए, `first` पहले और `last` बाद में diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4b813215e0..ff3cb8a1e5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6717,3 +6717,19 @@ breakText Glyphs Glifák No Suggestions Nincs javaslat Edit Custom Dictionary Egyéni szótár szerkesztése Entry: Bejegyzés: +# Script Console + Script Console Parancsfájlkonzol + Clear Script Console Parancsfájlkonzol törlése + Copy Script Console Parancsfájlkonzol másolása + Copy All Összes másolása + Copy Selected Kijelölés másolása + Finished Befejeződött + Ended with an error Hibával ért véget + Out of fuel Elfogyott az utasításkeret + Ended at a host limit Gazdakorlátnál ért véget + Ended at a limit Korlátnál ért véget + Stopped Leállítva + Ended by an internal fault Belső hiba miatt ért véget + {ms} ms, {calls} host calls {ms} ms, {calls} gazdahívás + {dropped} earlier lines dropped, {cut} lines cut {dropped} korábbi sor elvetve, {cut} sor levágva +@msg `first` and `last` must be numbers of lines the console holds, first before last A `first` és a `last` a konzolban tárolt sorok számai legyenek, a `first` a `last` előtt diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 33d229c85a..ee4d8352e1 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6475,3 +6475,18 @@ breakText Glyphs Glif @msg side is left or right, not `{s}` side adalah left atau right, bukan `{s}` Edit Custom Dictionary Edit kamus kustom Entry: Entri: +# Script Console + Script Console Konsol Skrip + Clear Script Console Bersihkan Konsol Skrip + Copy Script Console Salin Konsol Skrip + Copy All Salin Semua + Copy Selected Salin yang Dipilih + Finished Selesai + Ended with an error Berakhir dengan galat + Out of fuel Batas instruksi tercapai + Ended at a host limit Berakhir pada batas host + Ended at a limit Berakhir pada batas + Stopped Dihentikan + Ended by an internal fault Berakhir karena galat internal + {ms} ms, {calls} host calls {ms} ms, {calls} panggilan host + {dropped} earlier lines dropped, {cut} lines cut {dropped} baris lama dibuang, {cut} baris dipotong diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b5fd752e9b..07955dcde5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6354,3 +6354,19 @@ breakText Glyphs Glifi No Suggestions Nessun suggerimento Edit Custom Dictionary Modifica dizionario personalizzato Entry: Voce: +# Script Console + Script Console Console script + Clear Script Console Cancella console script + Copy Script Console Copia console script + Copy All Copia tutto + Copy Selected Copia selezione + Finished Terminato + Ended with an error Terminato con un errore + Out of fuel Limite di istruzioni esaurito + Ended at a host limit Terminato a un limite dell'host + Ended at a limit Terminato a un limite + Stopped Interrotto + Ended by an internal fault Terminato per un errore interno + {ms} ms, {calls} host calls {ms} ms, {calls} chiamate all'host + {dropped} earlier lines dropped, {cut} lines cut {dropped} righe precedenti scartate, {cut} righe tagliate +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devono essere numeri di righe presenti nella console, `first` prima di `last` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 56fc8a5907..d96c77375b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6419,3 +6419,19 @@ breakText Glyphs 字形 No Suggestions 候補なし Edit Custom Dictionary カスタム辞書を編集 Entry: エントリ: +# Script Console + Script Console スクリプトコンソール + Clear Script Console スクリプトコンソールを消去 + Copy Script Console スクリプトコンソールをコピー + Copy All すべてコピー + Copy Selected 選択範囲をコピー + Finished 完了 + Ended with an error エラーで終了 + Out of fuel 命令数の上限に到達 + Ended at a host limit ホストの上限で終了 + Ended at a limit 上限で終了 + Stopped 停止 + Ended by an internal fault 内部エラーで終了 + {ms} ms, {calls} host calls {ms} ms、ホスト呼び出し {calls} 回 + {dropped} earlier lines dropped, {cut} lines cut 古い行 {dropped} 行を破棄、{cut} 行を切り詰め +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` と `last` には、コンソールが保持している行の番号を、`first` が `last` より前になるよう指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 388dd4a01e..921b9761b1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6794,3 +6794,19 @@ font-script Japanese იაპონური No Suggestions შემოთავაზებები არ არის Edit Custom Dictionary მომხმარებლის ლექსიკონის რედაქტირება Entry: ჩანაწერი: +# Script Console + Script Console სკრიპტების კონსოლი + Clear Script Console სკრიპტების კონსოლის გასუფთავება + Copy Script Console სკრიპტების კონსოლის კოპირება + Copy All ყველაფრის კოპირება + Copy Selected მონიშნულის კოპირება + Finished დასრულდა + Ended with an error დასრულდა შეცდომით + Out of fuel ინსტრუქციების ლიმიტი ამოიწურა + Ended at a host limit დასრულდა ჰოსტის ლიმიტზე + Ended at a limit დასრულდა ლიმიტზე + Stopped შეჩერდა + Ended by an internal fault დასრულდა შიდა შეცდომის გამო + {ms} ms, {calls} host calls {ms} ms, ჰოსტის {calls} გამოძახება + {dropped} earlier lines dropped, {cut} lines cut {dropped} ძველი სტრიქონი წაიშალა, {cut} სტრიქონი შემოკლდა +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` და `last` უნდა იყოს კონსოლში შენახული სტრიქონების ნომრები და `first` უნდა იყოს `last`-ზე წინ diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 03930932a7..9518987a09 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6315,3 +6315,19 @@ breakText Glyphs 글리프 No Suggestions 제안 없음 Edit Custom Dictionary 사용자 사전 편집 Entry: 항목: +# Script Console + Script Console 스크립트 콘솔 + Clear Script Console 스크립트 콘솔 지우기 + Copy Script Console 스크립트 콘솔 복사 + Copy All 모두 복사 + Copy Selected 선택 항목 복사 + Finished 완료됨 + Ended with an error 오류로 종료됨 + Out of fuel 명령 한도에 도달함 + Ended at a host limit 호스트 한도에서 종료됨 + Ended at a limit 한도에서 종료됨 + Stopped 중지됨 + Ended by an internal fault 내부 오류로 종료됨 + {ms} ms, {calls} host calls {ms} ms, 호스트 호출 {calls}회 + {dropped} earlier lines dropped, {cut} lines cut 이전 줄 {dropped}개 삭제됨, 줄 {cut}개 잘림 +@msg `first` and `last` must be numbers of lines the console holds, first before last `first`와 `last`는 콘솔에 있는 줄 번호여야 하며 `first`가 `last`보다 앞서야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c5151622d4..a24ac18157 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6526,3 +6526,18 @@ breakText Glyphs Glyphs @msg side is left or right, not `{s}` side is left of right, niet `{s}` Edit Custom Dictionary Aangepast woordenboek bewerken Entry: Item: +# Script Console + Script Console Scriptconsole + Clear Script Console Scriptconsole wissen + Copy Script Console Scriptconsole kopiëren + Copy All Alles kopiëren + Copy Selected Selectie kopiëren + Finished Voltooid + Ended with an error Beëindigd met een fout + Out of fuel Instructielimiet bereikt + Ended at a host limit Beëindigd bij een hostlimiet + Ended at a limit Beëindigd bij een limiet + Stopped Gestopt + Ended by an internal fault Beëindigd door een interne fout + {ms} ms, {calls} host calls {ms} ms, {calls} host-aanroepen + {dropped} earlier lines dropped, {cut} lines cut {dropped} eerdere regels verwijderd, {cut} regels ingekort diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 58016a4bd0..47a8420fc1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6589,3 +6589,19 @@ breakText Glyphs Glify No Suggestions Brak sugestii Edit Custom Dictionary Edytuj słownik użytkownika Entry: Wpis: +# Script Console + Script Console Konsola skryptów + Clear Script Console Wyczyść konsolę skryptów + Copy Script Console Kopiuj konsolę skryptów + Copy All Kopiuj wszystko + Copy Selected Kopiuj zaznaczenie + Finished Zakończono + Ended with an error Zakończono z błędem + Out of fuel Wyczerpano limit instrukcji + Ended at a host limit Zakończono na limicie hosta + Ended at a limit Zakończono na limicie + Stopped Zatrzymano + Ended by an internal fault Zakończono z powodu błędu wewnętrznego + {ms} ms, {calls} host calls {ms} ms, wywołania hosta: {calls} + {dropped} earlier lines dropped, {cut} lines cut Odrzucone wcześniejsze wiersze: {dropped}, skrócone wiersze: {cut} +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` muszą być numerami wierszy przechowywanych w konsoli, `first` przed `last` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b0d940693f..979d5c920f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6806,3 +6806,19 @@ swatch Yellow Green Verde-amarelado No Suggestions Nenhuma Sugestão Edit Custom Dictionary Editar Dicionário Personalizado Entry: Entrada: +# Script Console + Script Console Console de scripts + Clear Script Console Limpar console de scripts + Copy Script Console Copiar console de scripts + Copy All Copiar tudo + Copy Selected Copiar seleção + Finished Concluído + Ended with an error Encerrado com um erro + Out of fuel Limite de instruções esgotado + Ended at a host limit Encerrado em um limite do host + Ended at a limit Encerrado em um limite + Stopped Interrompido + Ended by an internal fault Encerrado por um erro interno + {ms} ms, {calls} host calls {ms} ms, {calls} chamadas ao host + {dropped} earlier lines dropped, {cut} lines cut {dropped} linhas anteriores descartadas, {cut} linhas cortadas +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devem ser números de linhas que o console mantém, `first` antes de `last` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a00325e8b8..4e6d96436d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6822,3 +6822,19 @@ shape Open Открытый No Suggestions Нет вариантов Edit Custom Dictionary Редактировать пользовательский словарь Entry: Запись: +# Script Console + Script Console Консоль скриптов + Clear Script Console Очистить консоль скриптов + Copy Script Console Копировать консоль скриптов + Copy All Копировать всё + Copy Selected Копировать выделенное + Finished Завершено + Ended with an error Завершено с ошибкой + Out of fuel Исчерпан лимит инструкций + Ended at a host limit Завершено на лимите хоста + Ended at a limit Завершено на лимите + Stopped Остановлено + Ended by an internal fault Завершено из-за внутренней ошибки + {ms} ms, {calls} host calls {ms} мс, вызовов хоста: {calls} + {dropped} earlier lines dropped, {cut} lines cut Отброшено прежних строк: {dropped}, обрезано строк: {cut} +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` и `last` должны быть номерами строк, которые хранит консоль, причём `first` не позже `last` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f2b24e7d08..805eb46f44 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8218,3 +8218,19 @@ digits Hindi Hindi No Suggestions Inga förslag Edit Custom Dictionary Redigera egen ordlista Entry: Post: +# Script Console + Script Console Skriptkonsol + Clear Script Console Rensa skriptkonsolen + Copy Script Console Kopiera skriptkonsolen + Copy All Kopiera allt + Copy Selected Kopiera markerade + Finished Klar + Ended with an error Avslutades med ett fel + Out of fuel Instruktionsgränsen nåddes + Ended at a host limit Avslutades vid en värdgräns + Ended at a limit Avslutades vid en gräns + Stopped Stoppad + Ended by an internal fault Avslutades av ett internt fel + {ms} ms, {calls} host calls {ms} ms, {calls} värdanrop + {dropped} earlier lines dropped, {cut} lines cut {dropped} tidigare rader borttagna, {cut} rader avkortade +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` och `last` måste vara nummer på rader som konsolen har kvar, `first` före `last` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 76d73994b5..ed53cd995d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6689,3 +6689,19 @@ breakText Glyphs Glifler No Suggestions Öneri Yok Edit Custom Dictionary Özel Sözlüğü Düzenle Entry: Giriş: +# Script Console + Script Console Betik Konsolu + Clear Script Console Betik Konsolunu Temizle + Copy Script Console Betik Konsolunu Kopyala + Copy All Tümünü Kopyala + Copy Selected Seçileni Kopyala + Finished Bitti + Ended with an error Bir hatayla sona erdi + Out of fuel Komut sınırına ulaşıldı + Ended at a host limit Bir ana bilgisayar sınırında sona erdi + Ended at a limit Bir sınırda sona erdi + Stopped Durduruldu + Ended by an internal fault Bir iç hata nedeniyle sona erdi + {ms} ms, {calls} host calls {ms} ms, {calls} ana bilgisayar çağrısı + {dropped} earlier lines dropped, {cut} lines cut {dropped} eski satır atıldı, {cut} satır kesildi +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` ve `last`, konsolun tuttuğu satırların numaraları olmalı ve `first`, `last` değerinden önce gelmeli diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4652ce4ca8..ea2efc2efc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6334,3 +6334,19 @@ breakText Glyphs Гліфи No Suggestions Немає варіантів Edit Custom Dictionary Редагувати словник користувача Entry: Запис: +# Script Console + Script Console Консоль скриптів + Clear Script Console Очистити консоль скриптів + Copy Script Console Копіювати консоль скриптів + Copy All Копіювати все + Copy Selected Копіювати виділене + Finished Завершено + Ended with an error Завершено з помилкою + Out of fuel Вичерпано ліміт інструкцій + Ended at a host limit Завершено на ліміті хоста + Ended at a limit Завершено на ліміті + Stopped Зупинено + Ended by an internal fault Завершено через внутрішню помилку + {ms} ms, {calls} host calls {ms} мс, викликів хоста: {calls} + {dropped} earlier lines dropped, {cut} lines cut Відкинуто попередніх рядків: {dropped}, обрізано рядків: {cut} +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` і `last` мають бути номерами рядків, які зберігає консоль, причому `first` не пізніше `last` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4c9dac833c..2bb8d86aae 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6335,3 +6335,19 @@ breakText Glyphs Glyph No Suggestions Không có gợi ý Edit Custom Dictionary Chỉnh sửa từ điển tùy chỉnh Entry: Mục nhập: +# Script Console + Script Console Bảng điều khiển tập lệnh + Clear Script Console Xóa bảng điều khiển tập lệnh + Copy Script Console Sao chép bảng điều khiển tập lệnh + Copy All Sao chép tất cả + Copy Selected Sao chép mục đã chọn + Finished Đã xong + Ended with an error Kết thúc do lỗi + Out of fuel Đã hết giới hạn lệnh + Ended at a host limit Kết thúc ở giới hạn của máy chủ + Ended at a limit Kết thúc ở giới hạn + Stopped Đã dừng + Ended by an internal fault Kết thúc do lỗi nội bộ + {ms} ms, {calls} host calls {ms} ms, {calls} lệnh gọi máy chủ + {dropped} earlier lines dropped, {cut} lines cut Đã bỏ {dropped} dòng cũ, đã cắt {cut} dòng +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` và `last` phải là số thứ tự của các dòng mà bảng điều khiển đang giữ, `first` đứng trước `last` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c62b176687..816491c4c9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6571,3 +6571,19 @@ breakText Glyphs 字形 @msg side is left or right, not `{s}` side 应为 left 或 right,而不是 `{s}` Edit Custom Dictionary 编辑自定义词典 Entry: 条目: +# Script Console + Script Console 脚本控制台 + Clear Script Console 清除脚本控制台 + Copy Script Console 复制脚本控制台 + Copy All 全部复制 + Copy Selected 复制所选内容 + Finished 已完成 + Ended with an error 因错误结束 + Out of fuel 已用尽指令上限 + Ended at a host limit 在宿主限制处结束 + Ended at a limit 在限制处结束 + Stopped 已停止 + Ended by an internal fault 因内部错误结束 + {ms} ms, {calls} host calls {ms} 毫秒,宿主调用 {calls} 次 + {dropped} earlier lines dropped, {cut} lines cut 已丢弃 {dropped} 行较早内容,已截断 {cut} 行 +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必须是控制台保留的行号,且 `first` 不能在 `last` 之后 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0b3a21250c..9fae98b2f1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6369,3 +6369,19 @@ breakText Glyphs 字符 @msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}` Edit Custom Dictionary 編輯自訂字典 Entry: 項目: +# Script Console + Script Console 指令碼主控台 + Clear Script Console 清除指令碼主控台 + Copy Script Console 複製指令碼主控台 + Copy All 全部複製 + Copy Selected 複製所選內容 + Finished 已完成 + Ended with an error 因錯誤結束 + Out of fuel 已用盡指令上限 + Ended at a host limit 在主機限制處結束 + Ended at a limit 在限制處結束 + Stopped 已停止 + Ended by an internal fault 因內部錯誤結束 + {ms} ms, {calls} host calls {ms} 毫秒,主機呼叫 {calls} 次 + {dropped} earlier lines dropped, {cut} lines cut 已捨棄 {dropped} 行較早內容,已截斷 {cut} 行 +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必須是主控台保留的行號,且 `first` 不能在 `last` 之後 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 98d4da9895..8ea13cf650 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -771,6 +771,7 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::trace_presets::open(app, p), "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), + "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), "window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p), "ui.libraryPanel" => crate::panels::library_panel::command(app, p), "ui.libraryPanel.locate" => crate::panels::library_panel::locate(app, p), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 97651d0740..d2489d7b84 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -664,6 +664,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { panel("Pathfinder", "pathfinder"), panel("Pattern Options", "patternOptions"), panel("Properties", "properties"), + panel("Script Console", crate::panels::script_console::ID), panel("Separations Preview", "separations"), panel("Stroke", "stroke"), panel("SVG Interactivity", crate::panels::svg_interactivity::ID), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fb78fc2075..2562898201 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -976,6 +976,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.copyScriptConsole", + "Copy Script Console", + "", + "{first?, last?: numbers of lines the Script Console holds, both or neither} copy those lines of the Script Console to the clipboard as the panel shows them, each with its run's number and script name; without them every line, after a line counting the lines it dropped and cut (Script Console panel: Copy Selected, Copy All; script.console gives the lines) → {lines: n}", + ), ( "window.graphicStyleLibrary", "Graphic Style Library", diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 2282633eb4..1106406bc0 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -37,6 +37,7 @@ pub mod paragraph; pub mod pathfinder; pub mod pattern_options; pub mod properties; +pub mod script_console; pub mod separations; pub mod stroke; pub mod svg_interactivity; @@ -183,6 +184,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { asset_export::ID => asset_export::show(app, ui), css_properties::ID => css_properties::show(app, ui), three_d::ID => three_d::show(app, ui), + script_console::ID => script_console::show(app, ui), crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), @@ -238,6 +240,7 @@ pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool asset_export::ID => asset_export::menu(app, ui), css_properties::ID => css_properties::menu(app, ui), variables::ID => variables::menu(app, ui), + script_console::ID => script_console::menu(app, ui), "actions" => actions::menu(app, ui), id if library_panel::parse(id).is_some() => library_panel::menu(app, ui, id), _ => return false, @@ -675,6 +678,8 @@ mod tests_long_popups; #[cfg(test)] mod tests_maskview; #[cfg(test)] +mod tests_script_console; +#[cfg(test)] mod tests_stroke; #[cfg(test)] mod tests_strokedepth; diff --git a/crates/ui-egui/src/panels/script_console.rs b/crates/ui-egui/src/panels/script_console.rs new file mode 100644 index 0000000000..35529b05f1 --- /dev/null +++ b/crates/ui-egui/src/panels/script_console.rs @@ -0,0 +1,187 @@ +//! Script Console panel (Window › Script Console): the lines of this session's script runs +//! (`script.console`), each marked with its run's number and its script's name: a start, the +//! script's `$.write` and `$.writeln` output and `vc.log` entries, its uncaught error, an end and a +//! report of its time and host calls. The panel lays out only the rows in view. A click selects a +//! line and Shift-click a range. Clear runs `script.console.clear`; Copy Selected and Copy All run +//! `ui.copyScriptConsole`. Closing the panel only hides it: runs go on writing to the console. + +use egui::{Sense, Ui, vec2}; +use serde_json::{Value, json}; +use vectorcraft_engine::script::console::{Console, ConsoleLine, Ending, Entry}; + +use crate::VectorcraftApp; +use crate::theme::Tokens; + +pub const ID: &str = "scriptConsole"; +/// Panel state: the selected lines, by their numbers ([`Console::first_number`]), first and last. +const SELECTION: &str = "script-console-selection"; +/// Panel state: how many rows the last frame laid out. +pub(crate) const DRAWN: &str = "script-console-drawn"; +const ROW_HEIGHT: f32 = 16.0; + +/// How a run ended, in the UI language. +fn ending_label(e: Ending) -> &'static str { + match e { + Ending::Finished => tl!("Finished"), + Ending::Error => tl!("Ended with an error"), + Ending::Fuel => tl!("Out of fuel"), + Ending::HostLimit => tl!("Ended at a host limit"), + Ending::Limit => tl!("Ended at a limit"), + Ending::Stopped => tl!("Stopped"), + Ending::Internal => tl!("Ended by an internal fault"), + } +} + +/// A line as the panel shows it, in the UI language: its run's number, its script and its text. +pub(crate) fn shown(line: &ConsoleLine) -> String { + let text = match &line.entry { + Entry::Start => "▶".to_string(), + Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.clone(), + Entry::End(e) => format!("■ {}", ending_label(*e)), + Entry::Report { ms, host_calls, slowest } => { + let ms = ms.map_or_else(|| "?".to_string(), |ms| ms.to_string()); + let mut s = crate::i18n::fmt(tl!("{ms} ms, {calls} host calls"), &[("ms", &ms), ("calls", &host_calls.to_string())]); + for c in slowest { + s.push_str(&format!("; {} ×{} {} ms", c.id, c.calls, c.total_ms)); + } + s + } + }; + format!("#{} {}: {}", line.run, line.name, text) +} + +/// The notice of the lines the console dropped and cut, or `None` when it has done neither. +fn notice(c: &Console) -> Option { + (c.dropped_lines() > 0 || c.truncated_lines() > 0).then(|| { + crate::i18n::fmt( + tl!("{dropped} earlier lines dropped, {cut} lines cut"), + &[("dropped", &c.dropped_lines().to_string()), ("cut", &c.truncated_lines().to_string())], + ) + }) +} + +/// `ui.copyScriptConsole {first?, last?}`: copy the console's lines numbered `first` to `last` +/// (both kept lines; default every line, with the notice of dropped and cut lines first) to the +/// clipboard, as the panel shows them → `{lines: n}`. +pub(crate) fn copy(app: &mut VectorcraftApp, p: &Value) -> Result { + let c = app.session.script_console(); + let start = c.first_number(); + let end = start + c.lines().len() as u64; + let (first, last) = (p.get("first"), p.get("last")); + let mut text: Vec = Vec::new(); + let (from, to) = if first.is_none() && last.is_none() { + text.extend(notice(c)); + (start, end) + } else { + let held = |v: Option<&Value>| v.and_then(Value::as_u64).filter(|n| (start..end).contains(n)); + match (held(first), held(last)) { + (Some(a), Some(b)) if a <= b => (a, b + 1), + _ => return Err("`first` and `last` must be numbers of lines the console holds, first before last".to_string()), + } + }; + let picked = c.lines().iter().skip((from - start) as usize).take((to - from) as usize); + let lines = picked.map(shown).collect::>(); + let n = lines.len(); + text.extend(lines); + app.clipboard_out = Some(text.join("\n")); + Ok(json!({"lines": n})) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + let c = app.session.script_console(); + let start = c.first_number(); + let count = c.lines().len(); + let mut selection: Option<(u64, u64)> = super::pstate(ui.ctx(), SELECTION); + // A selection whose lines were dropped or cleared is gone. + if selection.is_some_and(|(a, b)| a < start || b >= start + count as u64) { + selection = None; + } + if let Some(n) = notice(c) { + crate::widgets::dim_label(ui, &n); + } + let mut clicked: Option<(u64, bool)> = None; + let mut drawn = 0usize; + let height = crate::widgets::panel_list_height(ui, 260.0, 0.0); + crate::widgets::list_box(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + egui::ScrollArea::vertical().id_salt("script-console").max_height(height).stick_to_bottom(true).auto_shrink([false, true]).show_rows( + ui, + ROW_HEIGHT, + count, + |ui, range| { + drawn = range.len(); + for (i, line) in c.lines().range(range.clone()).enumerate() { + let number = start + (range.start + i) as u64; + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); + if selection.is_some_and(|(a, b)| (a..=b).contains(&number)) { + ui.painter().rect_filled(r, 0.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover); + } + let color = match line.entry { + Entry::Error(_) => t.error, + Entry::Start | Entry::End(_) | Entry::Report { .. } => t.text_dim, + Entry::Output(_) | Entry::Log(_) => t.text, + }; + let text = shown(line); + ui.painter().with_clip_rect(r).text( + r.left_center() + vec2(4.0, 0.0), + egui::Align2::LEFT_CENTER, + &text, + egui::FontId::monospace(11.5), + color, + ); + let resp = resp.on_hover_text(&text); + if resp.clicked() { + clicked = Some((number, ui.input(|i| i.modifiers.shift))); + } + } + }, + ); + }); + super::set_pstate(ui.ctx(), DRAWN, drawn); + if let Some((number, shift)) = clicked { + selection = Some(match (selection, shift) { + (Some((a, b)), true) => (a.min(number), b.max(number)), + _ => (number, number), + }); + } + super::set_pstate(ui.ctx(), SELECTION, selection); + crate::widgets::bottom_bar(ui, |ui| { + if ui.add_enabled(count > 0, egui::Button::new(tl!("Clear"))).clicked() { + run(app, "script.console.clear", json!({})); + } + if ui.add_enabled(selection.is_some(), egui::Button::new(tl!("Copy Selected"))).clicked() + && let Some((first, last)) = selection + { + run(app, "ui.copyScriptConsole", json!({"first": first, "last": last})); + } + if ui.add_enabled(count > 0, egui::Button::new(tl!("Copy All"))).clicked() { + run(app, "ui.copyScriptConsole", json!({})); + } + }); +} + +/// The panel menu: Clear, Copy Selected and Copy All. +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let count = app.session.script_console().lines().len(); + let selection: Option<(u64, u64)> = super::pstate(ui.ctx(), SELECTION); + if crate::widgets::menu_item(ui, tl!("Clear"), count > 0, false) { + run(app, "script.console.clear", json!({})); + } + if crate::widgets::menu_item(ui, tl!("Copy Selected"), selection.is_some(), false) + && let Some((first, last)) = selection + { + run(app, "ui.copyScriptConsole", json!({"first": first, "last": last})); + } + if crate::widgets::menu_item(ui, tl!("Copy All"), count > 0, false) { + run(app, "ui.copyScriptConsole", json!({})); + } +} + +fn run(app: &mut VectorcraftApp, id: &str, params: Value) { + if let Err(e) = app.run(id, params) { + app.ui.status = e; + } +} diff --git a/crates/ui-egui/src/panels/tests_script_console.rs b/crates/ui-egui/src/panels/tests_script_console.rs new file mode 100644 index 0000000000..414e1bb36c --- /dev/null +++ b/crates/ui-egui/src/panels/tests_script_console.rs @@ -0,0 +1,98 @@ +//! The Script Console panel drawn headless: a full console lays out only the rows in view, output +//! goes on while the panel is hidden, Clear works during a run, and Copy Selected and Copy All +//! through `ui.copyScriptConsole`. + +use serde_json::json; +use vectorcraft_engine::Session; + +use super::pstate; +use super::script_console::{DRAWN, ID, show}; +use crate::tests_labels::painted_text; +use crate::{Services, VectorcraftApp, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({})).unwrap(); + app +} + +/// Runs `source` to its end, a frame at a time, as the app does. +fn run(app: &mut VectorcraftApp, source: &str) { + app.session.script_frames = true; + app.run("script.run", json!({"source": source, "name": "c.js"})).unwrap(); + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + script_runs::poll(app); + } + panic!("the script did not end"); +} + +#[test] +fn a_full_console_lays_out_only_the_rows_in_view() { + let mut app = app(); + run(&mut app, "for (var i = 0; i < 3000; i++) $.writeln('line ' + i)"); + assert_eq!(app.session.script_console().lines().len(), vectorcraft_engine::script::console::MAX_CONSOLE_LINES); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut drawn = 0; + for _ in 0..2 { + ctx.run_ui(egui::RawInput::default(), |ui| { + show(&mut app, ui); + drawn = pstate::(ui.ctx(), DRAWN); + }) + .textures_delta + .clear(); + } + assert!(drawn > 0 && drawn < 40, "{drawn} rows laid out"); + let text = painted_text(&mut app, show); + assert!(text.contains("#1 c.js: line 2999"), "the newest line is in view: {text}"); + assert!(text.contains("lines dropped"), "the panel says lines were dropped: {text}"); +} + +#[test] +fn output_goes_on_while_the_panel_is_hidden_and_shows_when_it_opens() { + let mut app = app(); + assert!(crate::state::rail_panel(ID).is_some()); + run(&mut app, "$.writeln('hidden'); vc.log({n: 1}); throw new Error('late')"); + app.run("window.panel", json!({"panel": ID})).unwrap(); + let text = painted_text(&mut app, show); + for want in ["#1 c.js: ▶", "#1 c.js: hidden", "#1 c.js: {\"n\":1}", "#1 c.js: c.js:1:", "#1 c.js: ■ Ended with an error", "host calls"] { + assert!(text.contains(want), "{want} in {text}"); + } +} + +#[test] +fn clear_works_during_a_run_and_the_run_goes_on_writing() { + let mut app = app(); + app.session.script_frames = true; + app.run("script.run", json!({"source": "$.writeln('before'); while (true) {}", "name": "c.js"})).unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_running()); + assert_eq!(app.run("script.console.clear", json!({})).unwrap()["cleared"], 2); + app.run("script.stop", json!({})).unwrap(); + script_runs::poll(&mut app); + assert!(!app.session.script_running()); + let text = painted_text(&mut app, show); + assert!(!text.contains("before") && text.contains("■ Stopped"), "{text}"); +} + +#[test] +fn copy_all_and_copy_selected_put_the_lines_on_the_clipboard() { + let mut app = app(); + run(&mut app, "$.writeln('one'); $.writeln('two'); $.writeln('three')"); + assert_eq!(app.run("ui.copyScriptConsole", json!({})).unwrap()["lines"], 6); + let all = app.clipboard_out.take().unwrap(); + assert!(all.starts_with("#1 c.js: ▶\n#1 c.js: one\n#1 c.js: two\n"), "{all}"); + assert_eq!(app.run("ui.copyScriptConsole", json!({"first": 2, "last": 3})).unwrap()["lines"], 2); + assert_eq!(app.clipboard_out.take().as_deref(), Some("#1 c.js: two\n#1 c.js: three")); + for bad in [json!({"first": 3, "last": 2}), json!({"first": 1}), json!({"first": 0, "last": 99}), json!({"first": "1", "last": 2})] { + assert!(app.run("ui.copyScriptConsole", bad.clone()).is_err(), "{bad}"); + } + assert!(app.clipboard_out.is_none(), "a refused copy copies nothing"); + run(&mut app, "for (var i = 0; i < 2100; i++) $.writeln(i)"); + app.run("ui.copyScriptConsole", json!({})).unwrap(); + let all = app.clipboard_out.take().unwrap(); + assert!(all.lines().next().is_some_and(|l| l.contains("lines dropped")), "Copy All starts with the notice: {}", &all[..80]); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index dfe85768cf..59553120c8 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -208,6 +208,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::panels::css_properties::ID, "CSS Properties", "globe"), (crate::panels::three_d::ID, "3D and Materials", "dc-cube"), (crate::panels::variables::ID, "Variables", "chart-column"), + (crate::panels::script_console::ID, "Script Console", "message-circle"), (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), diff --git a/docs/gaps.md b/docs/gaps.md index ddc02a2d00..b16bed6080 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -689,9 +689,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the document object model for scripts, a script console, the Scripts folder and script - directives (#1183 is open). File › Scripts › Other Script… and `script.run` run JavaScript files over the - command registry. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and +- **Missing:** the document object model for scripts, the Scripts folder and script directives (#1183 is + open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, and + Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and export, and full agent control over MCP are done. - **Estimate:** 4–8 h. - **Done (2026-10-16):** the MCP server hears the client during a long call: `notifications/cancelled` stops a queued or running export (PDF pages, flattening, baking, drawing, artboards) without writing anything or changing the document, `ping` and the list methods answer at once, any other request that would wait behind a call running for two seconds or more is refused as busy (`-32003`, naming the call), and `_meta.progressToken` gets page progress (#2165, #2171, #2172). Reading the document during an export is not served (refused as busy); estimate unchanged. diff --git a/docs/mcp.md b/docs/mcp.md index bc20483938..5b0e42cf94 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1540,7 +1540,7 @@ describes that menu item. Pass exactly one of `path` and `source`. A `path` must case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and `ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the -app through one global object: +app through the global object `vc`, and writes to the Script Console through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it @@ -1549,7 +1549,9 @@ app through one global object: - `vc.document` is a snapshot of the active document, or `null` when none is open. A snapshot too large to cross throws a `RangeError`. - `vc.commands` lists the commands a script may run. -- `vc.log(value)` adds a value to the report. +- `vc.log(value)` adds a value to the report and a line to the Script Console. +- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and + `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `vc.args` is the `args` object. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. @@ -1588,13 +1590,23 @@ VectorCraft sets these limits itself: | A value crossing to or from a command | 16 MiB and 1,048,576 entries | | `args` as JSON | 1 MiB | | Log | 10,000 entries and 4 MiB | +| Script Console | 2,048 lines and 1 MiB of text; 4,096 bytes a line; 256 bytes of a script's name | | Growth before a person is asked | 100,000 objects and 512 MiB of new document data | In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends -with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls}`. -In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. -`answers` takes only an empty object, since scripts have no prompts yet. +with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, +runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console}`. In the app the reply is `{running: true, +name}`, and the report appears later as `scriptReport` in `ui.inspect`. The report of a failed run has the same +fields after `kind`, `message`, `line`, `column` and `fuelLeft`. `answers` takes only an empty object, since scripts +have no prompts yet. + +- `runTimeMs` is the time the script ran, its commands included. Waits between frames and for a person's answer are + left out. `timingAvailable` is false on the web, where `runTimeMs` is 0. +- `hostCallCounts` is `{vcRun, documentReads, commandListReads, vcLog, consoleWrites}`. +- `slowestCommands` lists at most 5 commands as `{id, calls, totalMs, maxMs}`, the longest in all first, then by id. +- `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as + text. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} @@ -1604,6 +1616,27 @@ In the app the reply is `{running: true, name}`, and the report appears later as vectorcraft-cli run --cmd script.run --params '{"path": "Tidy Layers.js", "args": {"margin": 12}}' ``` +Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and +`$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message`, its end, and a report of +its time, host calls and slowest commands. Each line shows the run's number and the script's name. Line feeds, +carriage returns and the two together break lines, and other control characters show as their Unicode Control +Pictures. The console keeps at most 2,048 lines and 1 MiB of text and drops the oldest lines past that. A line longer +than 4,096 bytes, and a script's name longer than 256 bytes, is cut with `…`. A note at the top counts the dropped and cut lines. The panel lays out only the +rows in view. Click a line to select it and Shift-click to extend the selection. Clear, Copy Selected and Copy All are +at the bottom of the panel and in its menu. Output goes on while the panel is closed. + +- `script.console {}` returns `{lines: [{run, name, kind, text}], droppedLines, truncatedLines}`. `run` is the + run's number in the session, and `kind` is `start`, `output`, `log`, `error`, `end` or `report`. An end line's text + is `ended: ` followed by `finished`, `error`, `fuel`, `hostLimit`, `limit`, `stopped` or `internal`. +- `script.console.clear {}` empties the console, sets its counts to zero and returns `{cleared}`. A running script + goes on writing, and `scriptReport` keeps the last run's console. +- `ui.copyScriptConsole {first?, last?}` copies lines `first` to `last` to the clipboard as the panel shows them, or + every line after a line with the counts when both are left out. Pass both or neither. It returns `{lines}`. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "$.writeln(\"layers: \", 3);"}' +``` + ## Transparency and opacity masks Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage diff --git a/docs/roadmap.md b/docs/roadmap.md index d79efc9f17..dba1b580f6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -160,7 +160,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files; the script document model and console and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | | M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6bf45e9c82..b67e2597a8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -722,6 +722,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. + - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). From ef07aecd960fd740f4263d793d0cb1f79dd973f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 17:36:46 -0800 Subject: [PATCH 02/15] Menus: a long menu stays in one place instead of jumping between two places A scrolling menu list took its height from its own top down to the window's bottom bars. egui picks a popup's side from its size on the previous frame and moves a popup that does not fit back into the window, so the list's height changed with where the popup was drawn. In a short window the Add New Effect menu and other long menus moved between two places while open, and a menu that did not fit crept a few points per frame. The list now takes its height from the room below and above the button, row or point it opens from: below while that side leaves the 120 pt minimum, otherwise on the side with more room. A submenu measures down from its row's top or up from its row's bottom. The change is in menu_scroll, so it applies to every menu built on it. --- crates/ui-egui/src/panels/appearance/tests.rs | 34 +++- .../ui-egui/src/panels/tests_long_popups.rs | 175 +++++++++++++++++- crates/ui-egui/src/widgets.rs | 25 ++- crates/ui-egui/src/widgets/dropdowns.rs | 99 +++++++++- 4 files changed, 325 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 12fd3155e7..d3050ad5e3 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -1,4 +1,6 @@ -use super::super::tests_long_popups::{PopupWindow, assert_last_row_scrolls_into_view, assert_short_list_does_not_scroll, fx_menu_ends}; +use super::super::tests_long_popups::{ + PopupWindow, assert_last_row_scrolls_into_view, assert_popup_stays_put, assert_short_list_does_not_scroll, fx_menu_ends, +}; use super::*; /// A selected rectangle, for the fill row's swatch picker and the Add Effect button. @@ -81,6 +83,36 @@ fn the_add_effect_popup_scrolls_inside_a_short_window() { assert_short_list_does_not_scroll(&mut app_with_a_selected_rectangle(), draw_bottom_bar, fx_button, &first, &last); } +/// The Add New Effect popup opened from a button `below` pt above the bottom of a window `height` +/// pt tall stays at one place on every frame, inside the window. +fn assert_add_effect_popup_stays_put(height: f32, below: f32) -> Rect { + let (first, _) = fx_menu_ends(); + let draw = move |app: &mut VectorcraftApp, ui: &mut Ui| { + ui.add_space((height - below - 24.0).max(0.0)); + draw_bottom_bar(app, ui); + }; + assert_popup_stays_put(&mut app_with_a_selected_rectangle(), height, draw, fx_button, &first) +} + +/// Opened from a button near the bottom of a short window, the Add New Effect popup stays at one +/// place instead of being drawn above and below the button on alternate frames. +#[test] +fn the_add_effect_popup_stays_put_near_the_bottom_of_a_short_window() { + for height in [200.0, 300.0, 400.0, 600.0] { + let row = assert_add_effect_popup_stays_put(height, 8.0); + assert!(row.bottom() < height - 32.0, "in a {height} pt window the popup opens above the button: {row:?}"); + } +} + +/// Opened from a button near the top of a window, the popup opens below it and stays there. +#[test] +fn the_add_effect_popup_stays_put_below_a_button_near_the_top() { + for height in [200.0, 400.0, 900.0] { + let row = assert_add_effect_popup_stays_put(height, height - 32.0); + assert!(row.top() > 24.0, "in a {height} pt window the popup opens below the button: {row:?}"); + } +} + /// Duplicating rows highlights the copies, each right above its original, as the Layers panel /// does: the active row's copy becomes active, the anchor's copy the anchor. #[test] diff --git a/crates/ui-egui/src/panels/tests_long_popups.rs b/crates/ui-egui/src/panels/tests_long_popups.rs index 8597ea995f..f12e91ab77 100644 --- a/crates/ui-egui/src/panels/tests_long_popups.rs +++ b/crates/ui-egui/src/panels/tests_long_popups.rs @@ -1,4 +1,5 @@ -//! A headless window for checking that a panel's popup with no fixed length stays inside the window. +//! A headless window for checking that a panel's popup with no fixed length stays inside the window, +//! and the tests of menus built on `widgets::menu_scroll` that no panel draws. use egui::{Event, PointerButton, Pos2, Rect, Ui, vec2}; @@ -92,6 +93,70 @@ impl<'a> PopupWindow<'a> { } } +/// The frames a popup is watched for after it opens. +const STEADY_FRAMES: usize = 12; + +/// In a window `height` pt tall, the popup of the button `pick` finds draws its row `first` at the +/// same place on every frame it is shown, from the click on, inside the window. With the pointer on +/// that row, the row's submenu opens and every text of both stays in place too. Returns where the +/// row is drawn. +pub(super) fn assert_popup_stays_put( + app: &mut VectorcraftApp, + height: f32, + draw: impl FnMut(&mut VectorcraftApp, &mut Ui), + pick: impl FnOnce(&PopupWindow) -> Pos2, + first: &str, +) -> Rect { + let opened = Opened { with: PointerButton::Primary, first, hover: first }; + assert_popup_opened_stays_put(app, height, draw, pick, opened).0 +} + +/// How a popup is opened and checked: the mouse button `with` opens it, `first` is its first row, +/// and the pointer then moves onto the row `hover` to open its submenu. +struct Opened<'s> { + with: PointerButton, + first: &'s str, + hover: &'s str, +} + +/// [`assert_popup_stays_put`] for a popup opened as `opened` says. Returns where the first row is +/// drawn and where every text is drawn with the submenu open. +fn assert_popup_opened_stays_put( + app: &mut VectorcraftApp, + height: f32, + draw: impl FnMut(&mut VectorcraftApp, &mut Ui), + pick: impl FnOnce(&PopupWindow) -> Pos2, + opened: Opened, +) -> (Rect, Vec<(String, Rect)>) { + let Opened { with, first, hover } = opened; + let mut window = PopupWindow::new(app, height, draw); + let at = pick(&window); + let button = |pressed| Event::PointerButton { pos: at, button: with, pressed, modifiers: Default::default() }; + window.frame(app, vec![Event::PointerMoved(at), button(true)]); + window.frame(app, vec![button(false)]); + let mut seen = vec![]; + for _ in 0..STEADY_FRAMES { + seen.extend(window.text(first).map(|row| row.min)); + window.frame(app, vec![]); + } + let row = window.text(first).unwrap_or_else(|| panic!("the popup's first row, {first}")); + seen.push(row.min); + assert!(seen.iter().all(|seen| *seen == row.min), "{first} is drawn at one place on every frame: {seen:?}"); + assert!(row.top() >= 0.0 && row.bottom() <= height, "{first} at {row:?} is inside the {height} pt window"); + let popup_texts = window.texts.clone(); + let over = window.text(hover).unwrap_or_else(|| panic!("the popup's row {hover}")); + window.frame(app, vec![Event::PointerMoved(over.center())]); + window.frames(app, OPEN_FRAMES); + let places = |window: &PopupWindow| window.texts.iter().map(|(text, rect)| (text.clone(), rect.min)).collect::>(); + let shown = places(&window); + assert!(shown.iter().any(|(text, _)| !popup_texts.iter().any(|(old, _)| old == text)), "the pointer on {hover} opens its submenu"); + for _ in 0..STEADY_FRAMES { + window.frame(app, vec![]); + assert_eq!(places(&window), shown, "the popup and its submenu stay in place"); + } + (row, window.texts.clone()) +} + /// The Add Effect popup's first and last rows with no plug-ins: the effect catalog's groups, in order. pub(super) fn fx_menu_ends() -> (String, String) { let mut groups: Vec<&str> = vec![]; @@ -145,3 +210,111 @@ pub(super) fn assert_short_list_does_not_scroll( window.wheel_down(app, before.0.center()); assert_eq!(shown(&window), before, "a list that fits does not scroll"); } + +/// Rows in each list of [`long_menu`]: more than any window in these tests holds. +const LONG: usize = 40; + +/// A menu of rows `Row 0`, `Row 1`…, each a submenu of as many items. +fn long_menu(ui: &mut Ui) { + menu_of(ui, LONG); +} + +/// A menu of `rows` rows `Row 0`, `Row 1`…, each a submenu of [`LONG`] items. +fn menu_of(ui: &mut Ui, rows: usize) { + crate::widgets::menu_scroll(ui, |ui| { + for row in 0..rows { + ui.menu_button(format!("Row {row}"), |ui| { + crate::widgets::menu_scroll(ui, |ui| { + for item in 0..LONG { + let _ = ui.button(format!("Item {row}.{item}")); + } + }) + }); + } + }); +} + +/// A blank document, for windows that draw no panel. +fn app() -> VectorcraftApp { + VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()) +} + +/// A long menu opened from a button `y` pt down a window stays at one place on every frame, and so +/// does its submenu, whether it opens below the button, above it, or in a window shorter than it. +#[test] +fn a_long_menu_stays_put_wherever_its_button_is() { + for height in [160.0, 300.0, 600.0] { + for y in [4.0, height / 2.0 - 12.0, height - 28.0] { + let draw = move |_: &mut VectorcraftApp, ui: &mut Ui| { + ui.add_space(y); + let button = ui.button("Open"); + egui::Popup::menu(&button).show(long_menu); + }; + let open = |window: &PopupWindow| window.text("Open").expect("the button").center(); + assert_popup_stays_put(&mut app(), height, draw, open, "Row 0"); + } + } +} + +/// A long context menu opened near the top, the middle or the bottom of a short window stays at +/// one place on every frame, and so does its submenu. +#[test] +fn a_long_context_menu_stays_put_wherever_it_opens() { + for height in [160.0, 300.0, 600.0] { + for y in [4.0, height / 2.0, height - 4.0] { + let draw = |_: &mut VectorcraftApp, ui: &mut Ui| { + let area = ui.interact(ui.max_rect(), egui::Id::unique("context-area"), egui::Sense::click()); + area.context_menu(long_menu); + }; + let at = move |_: &PopupWindow| Pos2::new(20.0, y); + let opened = Opened { with: PointerButton::Secondary, first: "Row 0", hover: "Row 0" }; + assert_popup_opened_stays_put(&mut app(), height, draw, at, opened); + } + } +} + +/// The long submenu of a row near the top of a window opens down from the row's top, and its list +/// reaches down to the window's bottom less the menu gap. +#[test] +fn a_long_submenu_of_a_high_row_reaches_down_to_the_window_bottom() { + for height in [300.0, 600.0] { + let draw = |_: &mut VectorcraftApp, ui: &mut Ui| { + ui.add_space(4.0); + let button = ui.button("Open"); + egui::Popup::menu(&button).show(|ui| menu_of(ui, 6)); + }; + let open = |window: &PopupWindow| window.text("Open").expect("the button").center(); + let mut app = app(); + let mut window = PopupWindow::new(&mut app, height, draw); + let at = open(&window); + window.click(&mut app, at); + let row = window.text("Row 0").expect("the menu's first row"); + window.frame(&mut app, vec![Event::PointerMoved(row.center())]); + window.frames(&mut app, OPEN_FRAMES); + let item = window.text("Item 0.0").expect("the submenu's first item"); + let areas = window.ctx.memory(|m| m.layer_ids().filter_map(|layer| m.area_rect(layer.id)).collect::>()); + let submenu = areas.into_iter().filter(|rect| rect.contains(item.center())).min_by(|a, b| a.area().total_cmp(&b.area())); + let submenu = submenu.expect("the submenu's area"); + assert!(item.top() < row.bottom(), "the submenu opens down from {row:?}: {item:?}"); + assert!((height - 12.0..=height).contains(&submenu.bottom()), "in a {height} pt window the submenu reaches its bottom: {submenu:?}"); + } +} + +/// The submenu of a row near the bottom of a window opens up from the row and stays at one place +/// on every frame. +#[test] +fn a_long_submenu_of_a_low_row_opens_up_and_stays_put() { + for height in [300.0, 600.0] { + let draw = move |_: &mut VectorcraftApp, ui: &mut Ui| { + ui.add_space(height - 28.0); + let button = ui.button("Open"); + egui::Popup::menu(&button).show(|ui| menu_of(ui, 6)); + }; + let open = |window: &PopupWindow| window.text("Open").expect("the button").center(); + let opened = Opened { with: PointerButton::Primary, first: "Row 0", hover: "Row 5" }; + let (_, texts) = assert_popup_opened_stays_put(&mut app(), height, draw, open, opened); + let at = |wanted: &str| texts.iter().rfind(|(text, _)| text.trim() == wanted).map(|(_, rect)| *rect); + let (row, item) = (at("Row 5").expect("the row"), at("Item 5.0").expect("the submenu's first item")); + assert!(item.top() < row.top() - 100.0, "in a {height} pt window the submenu opens up from {row:?}: {item:?}"); + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index be2965ef3c..2dd361a7d6 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -45,13 +45,13 @@ pub use drag::{ }; #[cfg(test)] use dropdowns::combo_button_id; -#[cfg(test)] -pub(crate) use dropdowns::menu_floor; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named, field_focused_in, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, }; +#[cfg(test)] +pub(crate) use dropdowns::{menu_floor, menu_room_either}; pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_label, section_header, section_toggle, section_toggle_name, subheader}; pub(crate) use labels::{label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; @@ -658,6 +658,27 @@ mod menu_room_tests { assert_eq!(menu_room(100.0, 24.0, 92.0), 92.0); } + /// A popup opens below its button while that leaves the minimum height, even when the list + /// then scrolls. + #[test] + fn a_menu_opens_below_while_that_side_has_the_minimum() { + assert_eq!(menu_room_either(300.0, 800.0, 980.0), 288.0); + assert_eq!(menu_room_either(132.0, 800.0, 980.0), 120.0); + } + + /// With less than the minimum below, the list takes the room above, up to the window's height. + #[test] + fn a_menu_opens_above_when_below_is_too_short() { + assert_eq!(menu_room_either(40.0, 500.0, 980.0), 488.0); + assert_eq!(menu_room_either(40.0, 500.0, 300.0), 300.0); + } + + /// With little room on either side, the list keeps the minimum height. + #[test] + fn a_menu_keeps_the_minimum_with_little_room_either_side() { + assert_eq!(menu_room_either(40.0, 60.0, 980.0), 120.0); + } + /// The floor one window records does not reach a menu in another window of the same context. #[test] fn the_menu_floor_applies_in_the_window_that_recorded_it() { diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index d5d914b7b6..28ed7c6fb1 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -284,12 +284,25 @@ pub(crate) fn menu_floor(ctx: &egui::Context) -> f32 { ctx.data(|d| d.get_temp::(id)).unwrap_or_else(|| ctx.content_rect().bottom()) } +/// The space a menu list leaves between its end and the window's edge or bars. +const MENU_GAP: f32 = 12.0; +/// The least height a menu list is given. +const MENU_MIN_HEIGHT: f32 = 120.0; + /// The height a menu list may take: from `top` down to `floor` less a small gap, at least 120 pt, /// and never more than `tallest`, the most that fits in the window. pub fn menu_room(floor: f32, top: f32, tallest: f32) -> f32 { - const BOTTOM_GAP: f32 = 12.0; - const MIN_HEIGHT: f32 = 120.0; - (floor - top - BOTTOM_GAP).max(MIN_HEIGHT).min(tallest) + (floor - top - MENU_GAP).max(MENU_MIN_HEIGHT).min(tallest) +} + +/// The height a menu list may take when its popup can open below or above the rect it opens from: +/// `below` and `above` are the heights each side leaves for the list. The list goes below while that +/// side has room for the minimum height, otherwise on the side with more room. It gets at least +/// 120 pt and never more than `tallest`. +pub(crate) fn menu_room_either(below: f32, above: f32, tallest: f32) -> f32 { + let (below, above) = (below - MENU_GAP, above - MENU_GAP); + let room = if below >= MENU_MIN_HEIGHT { below } else { below.max(above) }; + room.max(MENU_MIN_HEIGHT).min(tallest) } /// The scroll bar of a menu's list: slim, in a column of its own beside the items, so it never @@ -298,14 +311,92 @@ pub fn list_scroll_style() -> egui::style::ScrollStyle { egui::style::ScrollStyle { bar_width: 6.0, bar_inner_margin: 2.0, ..egui::style::ScrollStyle::solid() } } +/// The widget that opened a popup and whether it is a submenu's row (`None` when none was found), +/// the frame the popup was opened in, and the frame it was last drawn in. +type Opener = (Option<(egui::Id, bool)>, u64, u64); + +/// The frames after a popup opens in which a search that found no opener runs again. +const OPENER_RETRY_FRAMES: u64 = 3; + +/// The widget that opened `popup`: a button whose popup has egui's default id, or a submenu's row, +/// found among the widgets of this frame and the previous one. Once found, later frames of the same +/// opening reuse it; a search that finds nothing runs again for the first few frames. +fn popup_opener(ctx: &egui::Context, popup: egui::Id) -> Option<(egui::Id, bool)> { + let key = popup.with("menu-scroll-opener"); + let frame = ctx.cumulative_frame_nr(); + let cached = ctx.data(|d| d.get_temp::(key)).filter(|&(_, _, seen)| seen + 1 >= frame); + let opened = cached.map_or(frame, |(_, opened, _)| opened); + let opener = match cached { + Some((found, _, _)) if found.is_some() || frame >= opened + OPENER_RETRY_FRAMES => found, + _ => { + let found = ctx.viewport(|vp| { + [&vp.this_pass, &vp.prev_pass].into_iter().flat_map(|pass| pass.widgets.layers()).flat_map(|(_, widgets)| widgets.iter()).find_map( + |w| { + let submenu = egui::containers::menu::SubMenu::id_from_widget_id(w.id) == popup; + (submenu || w.id.with("popup") == popup).then_some((w.id, submenu)) + }, + ) + }); + found.filter(|&(widget, submenu)| { + submenu || ctx.read_response(widget).is_some_and(|response| egui::Popup::default_response_id(&response) == popup) + }) + } + }; + ctx.data_mut(|d| d.insert_temp::(key, (opener, opened, frame))); + opener +} + +/// Where the popup or menu that `ui` is drawn in opens from: the rect of the button or row that +/// opened it, or the point a context menu was opened at. The flag is true for a submenu, which +/// opens beside its row: down from the row's top, or up from its bottom. While the opening widget +/// is not drawn, the rect it last had is used. A popup with an id of its own (`Popup::id`) has no +/// anchor. +fn popup_anchor(ui: &Ui) -> Option<(Rect, bool)> { + let ctx = ui.ctx(); + let popup = ui.layer_id().id; + let root = ui.stack().iter().last()?; + if !matches!(root.kind(), Some(egui::UiKind::Menu | egui::UiKind::Popup)) { + return None; + } + if let Some(at) = egui::Popup::position_of_id(ctx, popup) { + return Some((Rect::from_pos(at), false)); + } + let (widget, submenu) = popup_opener(ctx, popup)?; + let key = popup.with("menu-scroll-anchor"); + let drawn = ctx.read_response(widget).and_then(|response| egui::PopupAnchor::from(&response).rect(popup, ctx)); + let rect = match drawn { + Some(rect) => { + ctx.data_mut(|d| d.insert_temp(key, rect)); + rect + } + None => ctx.data(|d| d.get_temp::(key))?, + }; + // A submenu opens from its row grown by half the menu's margin, as egui's `SubMenu` places it. + let grow = if submenu { egui::Frame::menu(ui.style()).total_margin().sum().y * 0.5 } else { 0.0 }; + Some((rect.expand2(vec2(0.0, grow)), submenu)) +} + /// The body of a menu or popup list: as tall as its items up to the bottom bars of the window it /// opens in, and scrolling only past that, so long menus (Window, Effect, a panel's menu) stay /// reachable on small windows and in a floating panel's short OS window. Its scroll bar has a column /// of its own, so it never covers the shortcuts or the submenu arrows (#2086, #5347). +/// +/// The list's height comes from the room below and above the button, row or point the popup opens +/// from. A popup with an id of its own measures from its own top instead. pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { let ctx = ui.ctx(); let tallest = (ctx.content_rect().height() - egui::Frame::popup(ui.style()).total_margin().sum().y).max(0.0); - let room = menu_room(menu_floor(ctx), ui.next_widget_position().y, tallest); + let top = ui.next_widget_position().y; + // The rows above the list (the popup's margin, a search field) move with the popup. + let popup_top = ui.stack().iter().last().map_or(top, |root| root.max_rect.top()); + let ahead = top - popup_top; + let (floor, window_top) = (menu_floor(ctx), ctx.content_rect().top()); + let room = if let Some((anchor, submenu)) = popup_anchor(ui) { + let (down_from, up_to) = if submenu { (anchor.top(), anchor.bottom()) } else { (anchor.bottom(), anchor.top()) }; + menu_room_either(floor - down_from - ahead, up_to - window_top - ahead, tallest) + } else { + menu_room(floor, top, tallest) + }; ui.scope(|ui| { ui.spacing_mut().scroll = list_scroll_style(); // The minimum lets the list grow past a popup's default 400 pt size; it still shrinks to From 6643991710d5e0b0bba156412d68bc906678f5fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 18:30:11 -0800 Subject: [PATCH 03/15] Docs: ui.copyScriptConsole adds the count line only after dropped or cut lines A copy of every Script Console line starts with the count of dropped and cut lines only when there are any, and the returned lines count leaves that line out. The end-line text is described without a code span that ends in a space. --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 2562898201..f3a032923c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -980,7 +980,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.copyScriptConsole", "Copy Script Console", "", - "{first?, last?: numbers of lines the Script Console holds, both or neither} copy those lines of the Script Console to the clipboard as the panel shows them, each with its run's number and script name; without them every line, after a line counting the lines it dropped and cut (Script Console panel: Copy Selected, Copy All; script.console gives the lines) → {lines: n}", + "{first?, last?: numbers of lines the Script Console holds, both or neither} copy those lines of the Script Console to the clipboard as the panel shows them, each with its run's number and script name; without them every line, after a line counting the lines it dropped and cut when it dropped or cut any, which n does not count (Script Console panel: Copy Selected, Copy All; script.console gives the lines) → {lines: n}", ), ( "window.graphicStyleLibrary", diff --git a/docs/mcp.md b/docs/mcp.md index 2bb06be9ee..42ff19007e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1636,11 +1636,12 @@ at the bottom of the panel and in its menu. Output goes on while the panel is cl - `script.console {}` returns `{lines: [{run, name, kind, text}], droppedLines, truncatedLines}`. `run` is the run's number in the session, and `kind` is `start`, `output`, `log`, `error`, `end` or `report`. An end line's text - is `ended: ` followed by `finished`, `error`, `fuel`, `hostLimit`, `limit`, `stopped` or `internal`. + is `ended:`, a space, and then `finished`, `error`, `fuel`, `hostLimit`, `limit`, `stopped` or `internal`. - `script.console.clear {}` empties the console, sets its counts to zero and returns `{cleared}`. A running script goes on writing, and `scriptReport` keeps the last run's console. - `ui.copyScriptConsole {first?, last?}` copies lines `first` to `last` to the clipboard as the panel shows them, or - every line after a line with the counts when both are left out. Pass both or neither. It returns `{lines}`. + every line when both are left out. When the console has dropped or cut any lines, a copy of every line starts with a + line that counts them. Pass both or neither. It returns `{lines}`, which does not count that line. ```sh vectorcraft-cli run --cmd script.run --params '{"source": "$.writeln(\"layers: \", 3);"}' From e4830a0e2c29b0fe3fe602a66843d02537b46f6e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 18:51:13 -0800 Subject: [PATCH 04/15] Docs: the Script Console note shows only after dropped or cut lines The panel's note and the doc comment on ui.copyScriptConsole now say the count of dropped and cut lines appears only when there are any, and the returned lines count leaves that line out. --- crates/ui-egui/src/panels/script_console.rs | 5 +++-- docs/mcp.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/script_console.rs b/crates/ui-egui/src/panels/script_console.rs index 35529b05f1..3a3a325000 100644 --- a/crates/ui-egui/src/panels/script_console.rs +++ b/crates/ui-egui/src/panels/script_console.rs @@ -61,8 +61,9 @@ fn notice(c: &Console) -> Option { } /// `ui.copyScriptConsole {first?, last?}`: copy the console's lines numbered `first` to `last` -/// (both kept lines; default every line, with the notice of dropped and cut lines first) to the -/// clipboard, as the panel shows them → `{lines: n}`. +/// (both kept lines; default every line, with the notice of dropped and cut lines first when the +/// console dropped or cut any) to the clipboard, as the panel shows them → `{lines: n}`, where `n` +/// does not count the notice. pub(crate) fn copy(app: &mut VectorcraftApp, p: &Value) -> Result { let c = app.session.script_console(); let start = c.first_number(); diff --git a/docs/mcp.md b/docs/mcp.md index 42ff19007e..ef636d3e38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1630,7 +1630,7 @@ Window › Script Console shows the session's script lines, oldest first: each r its time, host calls and slowest commands. Each line shows the run's number and the script's name. Line feeds, carriage returns and the two together break lines, and other control characters show as their Unicode Control Pictures. The console keeps at most 2,048 lines and 1 MiB of text and drops the oldest lines past that. A line longer -than 4,096 bytes, and a script's name longer than 256 bytes, is cut with `…`. A note at the top counts the dropped and cut lines. The panel lays out only the +than 4,096 bytes, and a script's name longer than 256 bytes, is cut with `…`. When the console has dropped or cut any lines, a note at the top counts them. The panel lays out only the rows in view. Click a line to select it and Shift-click to extend the selection. Clear, Copy Selected and Copy All are at the bottom of the panel and in its menu. Output goes on while the panel is closed. From 8f3f6a82d7df3b66d5aa328e0e0ef6d1f5ce557a Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 10 Nov 2026 20:44:39 +0000 Subject: [PATCH 05/15] .ai import: a warp of type opens as a mesh envelope on its saved grid A warp of type whose own warp doesn't draw as its drawn art is checked again as a mesh envelope on the grid the editing data saves for it, its points and handles as saved. Where that draws as the drawn art, it opens live in its place: the type stays editable in that shape, and the warp's style and bend are lost. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/ai/envelope.rs | 77 ++++++++++----- crates/eps/src/import/tests_native.rs | 137 +++++++++++++++++++++++++- 2 files changed, 190 insertions(+), 24 deletions(-) diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index c0da27f2a9..fe3ba51f4a 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -20,8 +20,9 @@ //! `(AIDeformArtKey)`) and the kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object). Then the //! distorted art on plain lines, and the plugin's `XP`. While the contents are edited, the group //! holds the contents and the dictionary the mesh. A top object's outline is the edge of its -//! one-patch mesh. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its -//! drawn art. +//! one-patch mesh. A warp's mesh is a grid of its shape: a warp of type whose own warp doesn't come +//! out as drawn opens as a mesh envelope on that grid where that does. An envelope whose parts don't +//! read, or that doesn't come out as drawn, keeps its drawn art. use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; @@ -269,6 +270,23 @@ fn unwrapped(mut nodes: Vec) -> Vec> { /// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art /// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. pub(super) fn live(o: &Obj, before: Option, inner: Vec) -> Option { + envelope_as(o, before, inner, false) +} + +/// Is the envelope of dictionary `o` a warp? +fn is_warp(o: &Obj) -> bool { + whole(o, "AIDeformStyle") == Some(Some(1)) +} + +/// [`live`] for a warp, as a mesh envelope on the grid its editing data saves (the mesh that shapes +/// it), its points and handles as saved: it draws as that grid does, without the warp's style, bend +/// and distortions. `None` for an envelope that isn't a warp, or whose grid doesn't read. +fn live_on_saved_grid(o: &Obj, before: Option, inner: Vec) -> Option { + envelope_as(o, before, inner, true) +} + +/// [`live`], or with `on_grid` [`live_on_saved_grid`]. +fn envelope_as(o: &Obj, before: Option, inner: Vec, on_grid: bool) -> Option { let editing = switch(o, "AIDeformEditModeKey")?; let (mut options, fidelity) = options(o)?; let before = before?; @@ -290,14 +308,14 @@ pub(super) fn live(o: &Obj, before: Option, inner: Vec) -> Option warp(o)?, - 2 => { + let kind = match (whole(o, "AIDeformStyle")??, on_grid) { + (1, false) => warp(o)?, + (1, true) | (2, false) => { let (rows, cols, pts) = upright(shape?)?; let (points, handles) = pts.into_iter().unzip(); EnvelopeKind::Mesh { rows, cols, points, handles } } - 3 => { + (3, false) => { let (rows, cols, pts) = upright(shape?)?; // The outline runs clockwise from the top left corner, one segment per grid edge. let corners = [0, cols, cols.checked_add(rows)?, cols.checked_mul(2)?.checked_add(rows)?]; @@ -448,10 +466,13 @@ impl WarpedType { /// Make each envelope of type live where it draws as its drawn art, its contents' text slots /// holding their type: `type_of` gives, for a slot's id, the hidden text object it became in /// `doc` and the type the contents take in its place (the slot's visibility and lock are the - /// type's). The live envelope takes its drawn art's place and the hidden type goes. Each check - /// uses one of the import's checks and, for an envelope that shows, adds to what the page check - /// allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't - /// available, the drawn art and the hidden type stay. + /// type's). The live envelope takes its drawn art's place and the hidden type goes. A warp that + /// doesn't draw as its drawn art is checked again as a mesh envelope on the grid the file saves + /// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays + /// editable in that shape, and the warp's style and bend are lost. Each check uses one of the + /// import's checks and, for an envelope that shows, adds to what the page check allows + /// ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't available, the + /// drawn art and the hidden type stay. pub(crate) fn settle_envelopes(&mut self, doc: &mut Document, type_of: impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>) -> TypedSettled { let mut settled = TypedSettled::default(); if self.envelopes.is_empty() { @@ -503,22 +524,34 @@ impl WarpedType { for n in before.iter_mut().chain(inner.iter_mut()) { put_type(n, &texts); } - let kind = live(&obj, before, inner).ok_or(TypeKept::Read)?; - if self.checks == 0 { - return Err(TypeKept::Budget); + // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the + // grid the file saves for it: then it opens as a mesh envelope on that grid. + let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone()) } else { None }; + let kinds: Vec = live(&obj, before, inner).into_iter().chain(on_grid).collect(); + if kinds.is_empty() { + return Err(TypeKept::Read); } - self.checks -= 1; - let mut envelope = art.clone(); - (envelope.id, envelope.kind) = (doc.alloc_id(), kind); - let layer = doc.alloc_id(); - let shared = Shared { patterns: &doc.patterns, images: &doc.images }; - let (mut live_one, mut plain) = (envelope.clone(), art.clone()); - (live_one.visible, live_one.opacity) = (true, 1.0); + let (id, layer) = (doc.alloc_id(), doc.alloc_id()); + let mut plain = art.clone(); (plain.visible, plain.opacity) = (true, 1.0); let page = self.page.filter(|_| shown.contains(&drawn)); - if !drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) { - return Err(TypeKept::Differs); + let mut alike = None; + for kind in kinds { + if self.checks == 0 { + return Err(TypeKept::Budget); + } + self.checks -= 1; + let mut envelope = art.clone(); + (envelope.id, envelope.kind) = (id, kind); + let shared = Shared { patterns: &doc.patterns, images: &doc.images }; + let mut live_one = envelope.clone(); + (live_one.visible, live_one.opacity) = (true, 1.0); + if drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) { + alike = Some(envelope); + break; + } } + let envelope = alike.ok_or(TypeKept::Differs)?; if doc.node(drawn).is_none() { return Err(TypeKept::Read); } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 867d36d1a2..e1b4f68e84 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5346,7 +5346,6 @@ fn type_envelope(keys: &str, drawn: &str) -> String { /// [`type_envelope`], with `after` (on plain lines, written on `%_` ones) after the text object in /// its contents, such as the text object's XML id. fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { - let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); let mesh = format!( "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", @@ -5355,9 +5354,16 @@ fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { corner(80.0, 70.0, 80.0, 60.0, 70.0, 70.0), corner(80.0, 40.0, 70.0, 40.0, 80.0, 50.0), ); + type_envelope_on(keys, &mesh, drawn, after) +} + +/// [`type_envelope_with`], with `shape` (on plain lines, written on `%_` ones) in the group before +/// its dictionary, where the editing data saves the envelope's mesh. +fn type_envelope_on(keys: &str, shape: &str, drawn: &str, after: &str) -> String { + let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; format!( "{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", - hidden(&format!("u\n{mesh}U\n")), + hidden(&format!("u\n{shape}U\n")), hidden(&format!("/ArtDictionary :\n{keys}")), hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(0))), ) @@ -5654,6 +5660,133 @@ fn an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art() { assert!(!r.warnings.iter().any(|n| n.contains("variable bindings")), "{:?}", r.warnings); } +/// A one-patch warp grid as the editing data saves it, which no warp style draws: its top edge +/// rises to the right and bulges up. In art space, corners (20, 40) (20, 73) (80, 61) (80, 40), each +/// with its handles towards the next corner and the previous one. +fn rising_grid() -> String { + let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); + format!( + "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", + corner(20.0, 40.0, 20.0, 51.0, 40.0, 40.0), + corner(20.0, 73.0, 40.0, 80.0, 20.0, 62.0), + corner(80.0, 61.0, 80.0, 54.0, 60.0, 72.0), + corner(80.0, 40.0, 60.0, 40.0, 80.0, 47.0), + ) +} + +/// [`rising_grid`] on the page axes as a mesh envelope reads it: its points from the top left, row +/// by row, and their handles (towards the next column, the previous one, the next row and the +/// previous one; none out of the grid). +fn rising_kind() -> vectorcraft_doc::live::EnvelopeKind { + use kurbo::{Point, Vec2}; + let z = Vec2::ZERO; + vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(20.0, 27.0), Point::new(80.0, 39.0), Point::new(20.0, 60.0), Point::new(80.0, 60.0)], + handles: vec![ + [Vec2::new(20.0, -7.0), z, Vec2::new(0.0, 11.0), z], + [z, Vec2::new(-20.0, -11.0), Vec2::new(0.0, 7.0), z], + [Vec2::new(20.0, 0.0), z, z, Vec2::new(0.0, -11.0)], + [z, Vec2::new(-20.0, 0.0), z, Vec2::new(0.0, -7.0)], + ], + } +} + +/// The anchors of the paths `n` draws once its live art is expanded. +fn drawn_anchors(n: &Node) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Path { path, .. } => out.extend(path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p))), + _ => n.children().into_iter().flatten().for_each(|c| walk(c, out)), + } + } + let mut out = vec![]; + walk(&vectorcraft_effects::expand_live_deep(None, n), &mut out); + out +} + +/// A warp of type whose own warp draws apart from its drawn art, where the grid the file saves for +/// it draws as that art, opens as a mesh envelope on that grid, its points and handles as saved: +/// the type is editable, and new text fills the same shape (#3179). +#[test] +fn a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes() { + use vectorcraft_doc::live::EnvelopeKind; + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let mut text = made_envelope_type(&doc); + text.visible = true; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let shaped = |text: Node| { + let content = vec![std::sync::Arc::new(text)]; + let kind = Box::new(rising_kind()); + Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind, fidelity: 50.0, editing: false, options, frame: Box::default() }, + ) + }; + let (drawn, page) = drawn_envelope(&shaped(text)); + let art = + native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); + let mut live = None; + r.document.walk(|n| { + if matches!(n.kind, NodeKind::Envelope { .. }) { + live = Some(n.clone()); + } + }); + let mut live = live.unwrap(); + let NodeKind::Envelope { kind, content, .. } = &mut live.kind else { panic!("not an envelope: {live:?}") }; + let (EnvelopeKind::Mesh { rows, cols, points, handles }, EnvelopeKind::Mesh { points: want, handles: want_h, .. }) = (&**kind, rising_kind()) + else { + panic!("not a mesh envelope: {kind:?}") + }; + assert_eq!((*rows, *cols), (1, 1)); + assert!(points.iter().zip(&want).all(|(p, q)| (*p - *q).hypot() < 1e-6), "{points:?}"); + assert!(handles.iter().flatten().zip(want_h.iter().flatten()).all(|(h, g)| (*h - *g).hypot() < 1e-6), "{handles:?}"); + // New text in the envelope fills the grid as the old did: "HIH", whose corners are its glyphs', + // reaches each corner of the grid. + let NodeKind::Text(t) = &mut std::sync::Arc::make_mut(&mut content[0]).kind else { panic!("type") }; + let style = t.runs[0].style.clone(); + t.runs = vec![vectorcraft_doc::TextRun::new("HIH", style)]; + (t.cached_bounds, t.cached_ink) = (None, None); + t.cached_baselines.clear(); + let anchors = drawn_anchors(&live); + for corner in want { + let near = anchors.iter().map(|a| (*a - corner).hypot()).fold(f64::INFINITY, f64::min); + assert!(near < 0.25, "{corner:?} is {near} from the new text"); + } +} + +/// A warp of type whose editing data saves no grid it can be shaped by keeps its drawn art and its +/// type, hidden, with the note, when its own warp draws apart from that art (#3179). +#[test] +fn a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let mut text = made_envelope_type(&doc); + text.visible = true; + let content = vec![std::sync::Arc::new(text)]; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, + ); + let (drawn, page) = drawn_envelope(&shaped); + let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), "", &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); + assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings); +} + /// The fill of the first run of type `n`. fn text_fill(n: &Node) -> Option { let NodeKind::Text(t) = &n.kind else { return None }; From 7504a0e2e45889545159a7257acb010895ff5b2b Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 10 Nov 2026 19:01:54 +0000 Subject: [PATCH 06/15] .ai import: an envelope mesh bent far round reads the way it runs An envelope's mesh is turned upright by which way its rows and columns run. That was read from the first row alone, so a warp bent past halfway (its end columns leaning more than 45 degrees) read as turned round and mapped its contents across instead of along. Read it from the first and last rows and columns added up instead. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/ai/envelope.rs | 20 +++++++++--- crates/eps/src/import/ai/tests.rs | 46 ++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index fe3ba51f4a..3a45bf3a16 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -189,9 +189,19 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { let mut pts: Vec = m.points.iter().map(|q| (q.p, q.handles)).collect(); let at = |pts: &[GridPoint], cols: u32, r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).map_or(Point::ZERO, |q| q.0); let remap = |h: [Vec2; 4], slots: [usize; 4]| slots.map(|s| h.get(s).copied().unwrap_or(Vec2::ZERO)); - // Columns that run down the page: the grid goes the other way round. - let along = at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0); - if along.y.abs() > along.x.abs() { + // How the grid runs along its rows (its first and last rows, end to end added up) and down its + // columns (its first and last columns): read from both sides, a grid bent far round (its end + // columns leaning more than halfway over) still reads the way it runs. + let runs = |pts: &[GridPoint], rows: u32, cols: u32| { + let along = (at(pts, cols, 0, cols) - at(pts, cols, 0, 0)) + (at(pts, cols, rows, cols) - at(pts, cols, rows, 0)); + let down = (at(pts, cols, rows, 0) - at(pts, cols, 0, 0)) + (at(pts, cols, rows, cols) - at(pts, cols, 0, cols)); + (along, down) + }; + // How much of a run is across the page. + let level = |v: Vec2| if v.hypot() > 0.0 { v.x.abs() / v.hypot() } else { 0.0 }; + // Columns that run across the page more than rows do: the grid goes the other way round. + let (along, down) = runs(&pts, rows, cols); + if level(down) > level(along) { let mut t = Vec::with_capacity(len); for r in 0..=cols { for c in 0..=rows { @@ -205,7 +215,7 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { (rows, cols) = (cols, rows); pts = t; } - if (at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0)).x < 0.0 { + if runs(&pts, rows, cols).0.x < 0.0 { for row in pts.chunks_mut(cols as usize + 1) { row.reverse(); for (_, h) in row.iter_mut() { @@ -213,7 +223,7 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { } } } - if (at(&pts, cols, rows, 0) - at(&pts, cols, 0, 0)).y < 0.0 { + if runs(&pts, rows, cols).1.y < 0.0 { let mut flipped: Vec = pts.chunks(cols as usize + 1).rev().flatten().copied().collect(); for (_, h) in &mut flipped { h.swap(H_DOWN, H_UP); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 2b127e275b..039f8e1a8a 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -7501,6 +7501,52 @@ fn a_mesh_envelope_opens_live_with_its_points_and_handles() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } +/// A mesh envelope bent far round, its end columns leaning more than halfway over (a warp's grid +/// bent into an arc), opens live the way it runs: its columns along the arc, as in the file. +#[test] +fn a_mesh_envelope_bent_far_round_opens_the_way_it_runs() { + use vectorcraft_doc::live::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP}; + // 3 columns along an arc round (100, 0) from 160 to 20 degrees, rows at radius 60 and 90: the + // end columns lean 70 degrees over. + let at = |(i, j): (usize, usize)| { + let (a, r) = ((160.0 - i as f64 * 140.0 / 3.0).to_radians(), 60.0 + j as f64 * 30.0); + (100.0 + r * a.cos(), r * a.sin()) + }; + let handle = |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + // Written with its first index across the arc and its second along it, so that the grid reads + // turned round and has to be turned upright. + let shape = mesh_text(1, 3, &|(i, j)| at((j, i)), &|p, q| handle((p.1, p.0), (q.1, q.0)), None); + // Row r of the envelope is row 1 - r of the file (art space has y up). + let doc_pt = |(x, y): (f64, f64)| Point::new(x, 100.0 - y); + let (mut points, mut handles) = (vec![], vec![]); + for r in 0..=1usize { + for c in 0..=3usize { + let g = (c, 1 - r); + let p = doc_pt(at(g)); + points.push(p); + let towards = |q: Option<(usize, usize)>| q.filter(|q| q.0 <= 3 && q.1 <= 1).map_or(kurbo::Vec2::ZERO, |q| doc_pt(handle(g, q)) - p); + let mut h = [kurbo::Vec2::ZERO; 4]; + h[H_RIGHT] = towards(Some((g.0 + 1, g.1))); + h[H_LEFT] = towards(g.0.checked_sub(1).map(|i| (i, g.1))); + h[H_UP] = towards(Some((g.0, g.1 + 1))); + h[H_DOWN] = towards(g.1.checked_sub(1).map(|j| (g.0, j))); + handles.push(h); + } + } + let want = EnvelopeKind::Mesh { rows: 1, cols: 3, points, handles }; + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let EnvelopeKind::Mesh { rows, cols, points: got, .. } = live_envelope(&a[0]).1 else { panic!("{a:#?}") }; + assert_eq!((*rows, *cols), (1, 3)); + let EnvelopeKind::Mesh { points: want, .. } = &want else { panic!("{want:?}") }; + assert!(got.iter().zip(want).all(|(p, q)| (*p - *q).hypot() < 1e-6), "{got:?}"); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + /// An envelope made with a top object opens as a live envelope whose top path is the edge of its /// one-patch mesh, an anchor on the edge included; its contents stay the rectangle. #[test] From 37e3c0215ac0b037da902259e3f94243aa2152e2 Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 10 Nov 2026 19:31:45 +0000 Subject: [PATCH 07/15] .ai import: type in an envelope may map from its bounds with strokes With Distort Appearance, an envelope's contents map from the box the file measured for them: their bounds with their strokes or without them. For type, the size the file saves for that box is often out of date, so it can't say which. Envelopes of type are now checked both ways: as before, and mapping from their bounds with their strokes. Whichever draws as the drawn art opens live. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/ai/envelope.rs | 40 +++++++++++++++++++++++---- crates/eps/src/import/tests_native.rs | 39 ++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 3a45bf3a16..461be66fc9 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -131,6 +131,25 @@ fn saved_margin(o: &Obj, content: &[Arc]) -> Option<[f32; 4]> { envelope_stroke_margin(stroked, plain) } +/// Envelope `kind` mapping from its contents' bounds with their strokes, for an envelope with +/// Distort Appearance whose contents have strokes it doesn't map from already; `None` otherwise. +fn with_strokes(kind: &NodeKind) -> Option { + let NodeKind::Envelope { content, options, .. } = kind else { return None }; + if !options.distort_appearance { + return None; + } + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY)?; + let margin = envelope_stroke_margin(stroked, plain)?; + if margin == options.bounds_margin || margin.iter().any(|m| *m < 0.0) || margin.iter().all(|m| *m == 0.0) { + return None; + } + let mut kind = kind.clone(); + if let NodeKind::Envelope { options, .. } = &mut kind { + options.bounds_margin = margin; + } + Some(kind) +} + /// A warp: its style, bend, distortions and orientation. fn warp(o: &Obj) -> Option { let style = whole(o, "DeformStyle")??; @@ -479,10 +498,11 @@ impl WarpedType { /// type's). The live envelope takes its drawn art's place and the hidden type goes. A warp that /// doesn't draw as its drawn art is checked again as a mesh envelope on the grid the file saves /// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays - /// editable in that shape, and the warp's style and bend are lost. Each check uses one of the - /// import's checks and, for an envelope that shows, adds to what the page check allows - /// ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't available, the - /// drawn art and the hidden type stay. + /// editable in that shape, and the warp's style and bend are lost. With Distort Appearance, each + /// is also checked mapping from its contents' bounds with their strokes ([`with_strokes`]). Each + /// check uses one of the import's checks and, for an envelope that shows, adds to what the page + /// check allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't + /// available, the drawn art and the hidden type stay. pub(crate) fn settle_envelopes(&mut self, doc: &mut Document, type_of: impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>) -> TypedSettled { let mut settled = TypedSettled::default(); if self.envelopes.is_empty() { @@ -537,7 +557,17 @@ impl WarpedType { // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the // grid the file saves for it: then it opens as a mesh envelope on that grid. let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone()) } else { None }; - let kinds: Vec = live(&obj, before, inner).into_iter().chain(on_grid).collect(); + // With Distort Appearance, a file's envelope may map its contents from their bounds with + // their strokes or without them, and for type the size the file saves for that box is often + // out of date (not the size of the type there now): each is checked. + let kinds: Vec = live(&obj, before, inner) + .into_iter() + .chain(on_grid) + .flat_map(|k| { + let stroked = with_strokes(&k); + std::iter::once(k).chain(stroked) + }) + .collect(); if kinds.is_empty() { return Err(TypeKept::Read); } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index e1b4f68e84..e8ad5a3f5e 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5763,6 +5763,45 @@ fn a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its } } +/// A warp of stroked type with Distort Appearance whose drawn art maps the type's bounds with its +/// strokes onto the grid the file saves (not its glyphs' bounds alone) opens live as a mesh envelope +/// mapping from that box (#3179). +#[test] +fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does() { + use vectorcraft_doc::live::{envelope_content_boxes, envelope_stroke_margin}; + let Some(family) = installed_family() else { return }; + // "FLUX" stroked 4 points wide in black. + let stroked = "/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> /54 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 0.0 0.0 1.0 ] >> >> /57 true /63 4.0"; + let doc = type_envelope_text(&family, None).replace("/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >>", stroked); + let mut text = made_envelope_type(&doc); + text.visible = true; + assert!(matches!(&text.kind, NodeKind::Text(t) if t.runs[0].style.stroke_width == 4.0), "{text:?}"); + let content = vec![std::sync::Arc::new(text)]; + let (with, without) = envelope_content_boxes(&content, kurbo::Affine::IDENTITY).unwrap(); + let mut options = vectorcraft_doc::live::EnvelopeOptions::NEW; + options.bounds_margin = envelope_stroke_margin(with, without).unwrap(); + assert!(options.bounds_margin.iter().all(|m| *m > 0.0), "{options:?}"); + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, + ); + let (drawn, page) = drawn_envelope(&shaped); + let art = + native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + let mut margin = None; + r.document.walk(|n| { + if let NodeKind::Envelope { options, .. } = &n.kind { + margin = Some(options.bounds_margin); + } + }); + assert_eq!(margin, Some(options.bounds_margin)); +} + /// A warp of type whose editing data saves no grid it can be shaped by keeps its drawn art and its /// type, hidden, with the note, when its own warp draws apart from that art (#3179). #[test] From 8820a15e20d38342b609ea73c17d81d7bd692b3e Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 10 Nov 2026 20:45:05 +0000 Subject: [PATCH 08/15] docs: warps of type as mesh envelopes on their saved grid Co-Authored-By: Claude Opus 5.5 --- docs/file-format-parity.md | 3 ++- docs/target-app-parity.md | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 06fac10691..0d110ad45f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -339,6 +339,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | `.ai` and EPS import: a warp of type (an envelope made with a warp around type) whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the warp grid the file saves, with the same drawn-art check, budget and page comparison as #6421: where it passes, the type is editable and keeps the file's shape, and the warp's settings (style, bend) are lost. Type in an envelope with Distort Appearance on and strokes is also tried mapped from its box with strokes. A mesh bent far round (its end columns leaning more than halfway over) now reads the way it runs, not turned a quarter round. Tests `tests_native::a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes`, `a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does`, `a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art`, `ai::tests::a_mesh_envelope_bent_far_round_opens_the_way_it_runs` (part of #3179) | | 2026-11-11 | minor | `.ai` and EPS import: type stroked in the text document keeps its stroke's cap, join and miter limit (keys 61, 62 and 64 of its character attributes, numbered as PostScript's `setlinecap` and `setlinejoin`: 0 butt or miter, 1 round, 2 projecting or bevel). They were left at a miter join with a limit of 10 whatever the file said, so type the file strokes with round joins, or with the usual limit of 4 or less, drew spikes at its sharp corners, some many points long. In users' files, used locally and never committed, the page strokes the type with the cap, join and miter limit these keys give; no file had a bevel join, which is read by the same numbering. A value that isn't one of theirs keeps the default, a miter limit past 500 is 500, and type without a stroke keeps the defaults. Dashes are not read: no file had dashed type to tell which keys hold them. Tests `ate::tests::a_run_keeps_its_stroke_cap_join_and_miter_limit`, `tests_native::stroked_type_keeps_its_cap_join_and_miter_limit`; scores unchanged | | 2026-11-10 | minor | `.ai` and EPS import: an envelope of type (a warp, a mesh or a top object around type) kept its drawn art, its type hidden, because the type is laid out from the text document only after the layers are read. It now waits for that: its text slots get their type, and where VectorCraft's own envelope of that type draws as the drawn art the file saves (the same check and budget as other envelopes, seen on white and on black), it opens live in the drawn art's place, its type editable in Edit Contents, and the hidden copy goes. As with other live envelopes, the layers with one are then compared with the page, which weighs the envelope as the art it draws (not as type laid out again, which the comparison allows more for), and when they don't draw as it the drawn art and the hidden type are put back. Layers used though they don't draw as the page (the editing data trusted, or the objects that differ coming in as the page's art) leave envelopes of type their drawn art and hidden type too. A `.ai` whose layers would open alone, without its PDF part, imports the PDF part to compare them with, and should they still not draw as it, or should no envelope of type open live, they open alone as before, with the envelopes' drawn art. Type in a font that isn't available, slots without type of their own (threaded, bound to a text or a visibility variable, a wrap object, type a look draws), envelopes in a symbol's or a pattern's art, and envelopes that draw differently keep their drawn art, with the note (#3179). Tests `tests_native::an_envelope_of_type_that_draws_as_its_drawn_art_opens_live`, `an_envelope_of_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone`, `an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live`, `trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art`, `layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art`, `an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art` | | 2026-11-10 | minor | `.ai` save: a variable font's record in the text document's font set names the type's place in the font's design space (`/4`, each `fvar` axis as 16.16 fixed: the named instance's setting, or the run's own Variable Font setting) and the font's version (`/5`). Without them, type in a named instance such as Bold opened at the font's default instance in the app that opens the file. Two settings of one font are now two fonts of the set; a static font's record is unchanged. The record's form comes from the public report in #6388. Test `ai_editing::tests::variable_font_instances_name_their_design_space` (#6388) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c15e19cda6..2635623b58 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (`.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -1416,7 +1416,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests. A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type in an envelope with Distort Appearance on and strokes is mapped from its glyph box and, where that doesn't draw as the drawn art, from its box with strokes; the drawn-art check decides.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). From 198bb6dffd5f7296f5ae9ca6584a00f195d87af1 Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 10 Nov 2026 21:53:21 +0000 Subject: [PATCH 09/15] .ai import: an envelope's grid reads its way round from every row and column Summing only the end rows and columns let a grid symmetric about its middle (a mesh bent halfway round) read by rounding, so it came out turned or not depending on where it sat on the page. Every row and column is now summed, a sum shorter than 1% of its parts (or than the grid's reach) counts as no direction and falls back to the first row or column, and the same comparison decides both cases. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/ai/envelope.rs | 35 +++++++++++++++----- crates/eps/src/import/ai/tests.rs | 49 ++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 8 deletions(-) diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 461be66fc9..a3396a251c 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -208,19 +208,38 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { let mut pts: Vec = m.points.iter().map(|q| (q.p, q.handles)).collect(); let at = |pts: &[GridPoint], cols: u32, r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).map_or(Point::ZERO, |q| q.0); let remap = |h: [Vec2; 4], slots: [usize; 4]| slots.map(|s| h.get(s).copied().unwrap_or(Vec2::ZERO)); - // How the grid runs along its rows (its first and last rows, end to end added up) and down its - // columns (its first and last columns): read from both sides, a grid bent far round (its end - // columns leaning more than halfway over) still reads the way it runs. + // How far the grid reaches: a run much shorter than that is rounding, not a direction. + let reach = { + let first = pts.first().map_or(Point::ZERO, |q| q.0); + let bounds = pts.iter().fold(Rect::from_points(first, first), |b, q| b.union_pt(q.0)); + bounds.width().hypot(bounds.height()) * 1e-6 + }; + // How the grid runs along its rows (every row end to end, added up) and down its columns (every + // column): read from all of them, a grid bent far round (its end columns leaning more than + // halfway over) still reads the way it runs. Each sum comes with how long its parts are: where + // they nearly cancel out, as in a ring, what is left is rounding, not a direction, and the grid + // reads by its first row or column instead. let runs = |pts: &[GridPoint], rows: u32, cols: u32| { - let along = (at(pts, cols, 0, cols) - at(pts, cols, 0, 0)) + (at(pts, cols, rows, cols) - at(pts, cols, rows, 0)); - let down = (at(pts, cols, rows, 0) - at(pts, cols, 0, 0)) + (at(pts, cols, rows, cols) - at(pts, cols, 0, cols)); - (along, down) + let (mut along, mut down, mut along_len, mut down_len) = (Vec2::ZERO, Vec2::ZERO, 0.0, 0.0); + for r in 0..=rows { + let v = at(pts, cols, r, cols) - at(pts, cols, r, 0); + (along, along_len) = (along + v, along_len + v.hypot()); + } + for c in 0..=cols { + let v = at(pts, cols, rows, c) - at(pts, cols, 0, c); + (down, down_len) = (down + v, down_len + v.hypot()); + } + let clear = |v: Vec2, len: f64| (v.hypot() >= len * 0.01 && v.hypot() > reach).then_some(v); + let first_row = at(pts, cols, 0, cols) - at(pts, cols, 0, 0); + let first_col = at(pts, cols, rows, 0) - at(pts, cols, 0, 0); + (clear(along, along_len).unwrap_or(first_row), clear(down, down_len).unwrap_or(first_col)) }; // How much of a run is across the page. let level = |v: Vec2| if v.hypot() > 0.0 { v.x.abs() / v.hypot() } else { 0.0 }; - // Columns that run across the page more than rows do: the grid goes the other way round. + // Columns that run across the page more than rows do: the grid goes the other way round. Nearly + // as much (a grid turned an eighth round) keeps the file's way round. let (along, down) = runs(&pts, rows, cols); - if level(down) > level(along) { + if level(down) > level(along) + 1e-3 { let mut t = Vec::with_capacity(len); for r in 0..=cols { for c in 0..=rows { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 039f8e1a8a..7b208caf38 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -7547,6 +7547,55 @@ fn a_mesh_envelope_bent_far_round_opens_the_way_it_runs() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } +/// A mesh envelope bent halfway round, its grid running down an arc from top to bottom so that its +/// end rows cancel out, opens the same way round wherever it sits on the page and whichever way +/// round the file writes it. +#[test] +fn a_mesh_envelope_bent_halfway_round_opens_the_same_way_wherever_it_is() { + use vectorcraft_doc::live::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP}; + for cx in [100.0, 100.1, 37.0, 250.3, 12.7] { + // 4 rows down an arc round (cx, 0) from 90 to 270 degrees, columns at radius 90 and 60. + let at = |(i, j): (usize, usize)| { + let (a, r) = ((90.0 + i as f64 * 45.0_f64).to_radians(), 60.0 + j as f64 * 30.0); + (cx + r * a.cos(), r * a.sin()) + }; + let handle = |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + // Row r of the envelope is the arc's point r from the top, column c the radius 1 - c: the + // outer one is on the left. + let doc_pt = |(x, y): (f64, f64)| Point::new(x, 100.0 - y); + let (mut points, mut handles) = (vec![], vec![]); + for r in 0..=4usize { + for c in 0..=1usize { + let g = (r, 1 - c); + let p = doc_pt(at(g)); + points.push(p); + let towards = |q: Option<(usize, usize)>| q.filter(|q| q.0 <= 4 && q.1 <= 1).map_or(kurbo::Vec2::ZERO, |q| doc_pt(handle(g, q)) - p); + let mut h = [kurbo::Vec2::ZERO; 4]; + h[H_DOWN] = towards(Some((g.0 + 1, g.1))); + h[H_UP] = towards(g.0.checked_sub(1).map(|i| (i, g.1))); + h[H_RIGHT] = towards(g.1.checked_sub(1).map(|j| (g.0, j))); + h[H_LEFT] = towards(Some((g.0, g.1 + 1))); + handles.push(h); + } + } + let want = EnvelopeKind::Mesh { rows: 4, cols: 1, points, handles }; + let along = mesh_text(4, 1, &at, &handle, None); + let across = mesh_text(1, 4, &|(i, j)| at((j, i)), &|p, q| handle((p.1, p.0), (q.1, q.0)), None); + for shape in [along, across] { + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let EnvelopeKind::Mesh { rows, cols, points: got, .. } = live_envelope(&a[0]).1 else { panic!("at {cx}: {a:#?}") }; + assert_eq!((*rows, *cols), (4, 1), "at {cx}"); + let EnvelopeKind::Mesh { points: want, .. } = &want else { panic!("{want:?}") }; + assert!(got.iter().zip(want).all(|(p, q)| (*p - *q).hypot() < 1e-6), "at {cx}: {got:?}"); + } + } +} + /// An envelope made with a top object opens as a live envelope whose top path is the edge of its /// one-patch mesh, an anchor on the edge included; its contents stay the rectangle. #[test] From d0c99cba4bd0bbc1489b33f215ee68e974e1eb82 Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 10 Nov 2026 21:53:21 +0000 Subject: [PATCH 10/15] .ai import: a warp of type's second try leaves checks for the envelopes after it A warp of type may now spend up to four checks (its warp and its saved grid, each with and without strokes). A try after the first is only made while more checks are left than there are envelopes of type and warped text objects still to come, so one envelope's retries don't use up the checks of the others. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/ai/envelope.rs | 20 ++++--- crates/eps/src/import/tests_native.rs | 76 +++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 6 deletions(-) diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index a3396a251c..9bd3e937ad 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -529,8 +529,11 @@ impl WarpedType { } let mut shown = BTreeSet::new(); doc.layers.iter().for_each(|l| collect_shown(l, &mut shown)); - for envelope in std::mem::take(&mut self.envelopes) { - match self.typed_live(doc, envelope, &type_of, &shown) { + let envelopes = std::mem::take(&mut self.envelopes); + let mut waiting = envelopes.len(); + for envelope in envelopes { + waiting -= 1; + match self.typed_live(doc, envelope, &type_of, &shown, waiting) { Ok(put_back) => { settled.live += 1; settled.put_back.push(put_back); @@ -541,14 +544,16 @@ impl WarpedType { settled } - /// [`Self::settle_envelopes`] for `envelope`, the shown objects of `doc` being `shown`: the live - /// envelope's id and what takes its place again, or why its drawn art stays. + /// [`Self::settle_envelopes`] for `envelope`, the shown objects of `doc` being `shown` and + /// `waiting` envelopes of type still to come: the live envelope's id and what takes its place + /// again, or why its drawn art stays. fn typed_live( &mut self, doc: &mut Document, envelope: TypedEnvelope, type_of: &impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>, shown: &BTreeSet, + waiting: usize, ) -> Result<(NodeId, Vec), TypeKept> { let TypedEnvelope { obj, mut before, mut inner, drawn } = envelope; let art = doc.node(drawn).cloned().ok_or(TypeKept::Read)?; @@ -595,8 +600,11 @@ impl WarpedType { (plain.visible, plain.opacity) = (true, 1.0); let page = self.page.filter(|_| shown.contains(&drawn)); let mut alike = None; - for kind in kinds { - if self.checks == 0 { + for (i, kind) in kinds.into_iter().enumerate() { + // A second try is only made while more checks are left than there are envelopes of + // type and warped text objects still to come (some of which may need none): one + // envelope's tries don't use up the checks of the others. + if self.checks == 0 || (i > 0 && self.checks <= waiting + self.looks.len()) { return Err(TypeKept::Budget); } self.checks -= 1; diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index e8ad5a3f5e..35ccdb5bd0 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5826,6 +5826,82 @@ fn a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art() { assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings); } +/// A warp of type tried again on its saved grid leaves a check for each envelope of type still to +/// come: with one check too few for both, the next envelope, whose first try opens it, gets it. +#[test] +fn a_warp_of_type_tried_again_leaves_the_next_envelope_its_check() { + use vectorcraft_doc::live::EnvelopeKind; + let Some(family) = installed_family() else { return }; + let story = ("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0); + let mut doc = text_document(&[story, story]).replace("(Helvetica)", &format!("({family})")); + // [`native_with_text`] writes 60 characters a line: the end of the data, `~>`, isn't split. + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let text = made_envelope_type(&doc); + // The first envelope, of story 0, draws as its saved grid and not as its warp: two checks. + let mut shown = text.clone(); + shown.visible = true; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { + content: vec![std::sync::Arc::new(shown)], + kind: Box::new(rising_kind()), + fidelity: 50.0, + editing: false, + options, + frame: Box::default(), + }, + ); + let (drawn_grid, page_grid) = drawn_envelope(&shaped); + let grid = type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn_grid, ""); + // The second, of story 1, draws as its warp: one check. + let (drawn_arc, page_arc) = drawn_envelope(&arc_envelope(&text, 30.0)); + let arc = type_envelope(&arc_keys(0.3), &drawn_arc).replace("%_0 /StoryIndex", "%_1 /StoryIndex"); + // Envelopes of art before them use all but `left` of the import's checks. + let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; + let rect = "20 5 m\n20 95 L\n80 95 L\n80 5 L\n20 5 L\n"; + let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); + let mesh = format!( + "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", + corner(20.0, 5.0, 20.0, 35.0, 40.0, 5.0), + corner(20.0, 95.0, 40.0, 95.0, 20.0, 65.0), + corner(80.0, 95.0, 80.0, 65.0, 60.0, 95.0), + corner(80.0, 5.0, 60.0, 5.0, 80.0, 35.0), + ); + let red = "0 1 1 0 1 0 0 Xa\n"; + let filler = format!( + "{}%_/ArtDictionary :\n%_131073 /Int (AIDeformOptionsKey) ,\n%_50 /Int (AIDeformFidelityKey) ,\n%_0 /Bool (AIDeformEditModeKey) ,\n%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\nu\n{red}{rect}f\nU\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden(&format!("u\n{mesh}U\n")), + hidden(&format!("u\n{red}{rect}f\nU\n")), + ); + let page = + format!("{}\n1 0 0 setrgbcolor 20 5 moveto 20 95 lineto 80 95 lineto 80 5 lineto closepath fill\n{page_grid}{page_arc}", page_square(10, 10)); + let file = |left: usize| { + let body = format!("{}\n{}{grid}{arc}", square(10, 10), filler.repeat(crate::import::ai::MAX_CHECKED - left)); + eps(&page, &native_with_text(&layer("Art", true, &body), &doc)) + }; + // The live envelopes of type, by kind. + let typed = |d: &Document| { + let mut out = vec![]; + d.walk(|n| { + if let NodeKind::Envelope { content, kind, .. } = &n.kind + && content.iter().any(|c| matches!(c.kind, NodeKind::Text(_))) + { + out.push(if matches!(**kind, EnvelopeKind::Mesh { .. }) { "mesh" } else { "warp" }); + } + }); + out + }; + let r = import(&file(3)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(typed(&r.document), ["mesh", "warp"], "{:?}", r.warnings); + let r = import(&file(2)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(typed(&r.document), ["warp"], "{:?}", r.warnings); +} + /// The fill of the first run of type `n`. fn text_fill(n: &Node) -> Option { let NodeKind::Text(t) = &n.kind else { return None }; From d85a967fb7481d12d4f23d54bca6ed96947fa8c6 Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 10 Nov 2026 21:53:21 +0000 Subject: [PATCH 11/15] docs: envelope grid orientation and retry budget for warps of type Co-Authored-By: Claude Opus 5.5 --- docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0d110ad45f..6ef0a1d863 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -339,7 +339,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| -| 2026-11-10 | minor | `.ai` and EPS import: a warp of type (an envelope made with a warp around type) whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the warp grid the file saves, with the same drawn-art check, budget and page comparison as #6421: where it passes, the type is editable and keeps the file's shape, and the warp's settings (style, bend) are lost. Type in an envelope with Distort Appearance on and strokes is also tried mapped from its box with strokes. A mesh bent far round (its end columns leaning more than halfway over) now reads the way it runs, not turned a quarter round. Tests `tests_native::a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes`, `a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does`, `a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art`, `ai::tests::a_mesh_envelope_bent_far_round_opens_the_way_it_runs` (part of #3179) | +| 2026-11-11 | minor | `.ai` and EPS import: a warp of type (an envelope made with a warp around type) whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the warp grid the file saves, with the same drawn-art check, budget and page comparison as #6421: where it passes, the type is editable and keeps the file's shape, and the warp's settings (style, bend) are lost. A second try is only made while more checks are left than there are envelopes of type and warped text objects still to come. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its box with strokes, where the size the file saves for it doesn't already give that box (a rule chosen by measuring real files). An envelope's grid (warp, mesh or top object) now reads its way round from all its rows and columns, not its first row alone: a mesh bent far round (its end columns leaning more than halfway over) reads the way it runs, not turned a quarter round, and a grid symmetric about its middle reads the same wherever it is on the page. Tests `tests_native::a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes`, `a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does`, `a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art`, `a_warp_of_type_tried_again_leaves_the_next_envelope_its_check`, `ai::tests::a_mesh_envelope_bent_far_round_opens_the_way_it_runs`, `a_mesh_envelope_bent_halfway_round_opens_the_same_way_wherever_it_is` (part of #3179) | | 2026-11-11 | minor | `.ai` and EPS import: type stroked in the text document keeps its stroke's cap, join and miter limit (keys 61, 62 and 64 of its character attributes, numbered as PostScript's `setlinecap` and `setlinejoin`: 0 butt or miter, 1 round, 2 projecting or bevel). They were left at a miter join with a limit of 10 whatever the file said, so type the file strokes with round joins, or with the usual limit of 4 or less, drew spikes at its sharp corners, some many points long. In users' files, used locally and never committed, the page strokes the type with the cap, join and miter limit these keys give; no file had a bevel join, which is read by the same numbering. A value that isn't one of theirs keeps the default, a miter limit past 500 is 500, and type without a stroke keeps the defaults. Dashes are not read: no file had dashed type to tell which keys hold them. Tests `ate::tests::a_run_keeps_its_stroke_cap_join_and_miter_limit`, `tests_native::stroked_type_keeps_its_cap_join_and_miter_limit`; scores unchanged | | 2026-11-10 | minor | `.ai` and EPS import: an envelope of type (a warp, a mesh or a top object around type) kept its drawn art, its type hidden, because the type is laid out from the text document only after the layers are read. It now waits for that: its text slots get their type, and where VectorCraft's own envelope of that type draws as the drawn art the file saves (the same check and budget as other envelopes, seen on white and on black), it opens live in the drawn art's place, its type editable in Edit Contents, and the hidden copy goes. As with other live envelopes, the layers with one are then compared with the page, which weighs the envelope as the art it draws (not as type laid out again, which the comparison allows more for), and when they don't draw as it the drawn art and the hidden type are put back. Layers used though they don't draw as the page (the editing data trusted, or the objects that differ coming in as the page's art) leave envelopes of type their drawn art and hidden type too. A `.ai` whose layers would open alone, without its PDF part, imports the PDF part to compare them with, and should they still not draw as it, or should no envelope of type open live, they open alone as before, with the envelopes' drawn art. Type in a font that isn't available, slots without type of their own (threaded, bound to a text or a visibility variable, a wrap object, type a look draws), envelopes in a symbol's or a pattern's art, and envelopes that draw differently keep their drawn art, with the note (#3179). Tests `tests_native::an_envelope_of_type_that_draws_as_its_drawn_art_opens_live`, `an_envelope_of_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone`, `an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live`, `trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art`, `layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art`, `an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art` | | 2026-11-10 | minor | `.ai` save: a variable font's record in the text document's font set names the type's place in the font's design space (`/4`, each `fvar` axis as 16.16 fixed: the named instance's setting, or the run's own Variable Font setting) and the font's version (`/5`). Without them, type in a named instance such as Bold opened at the font's default instance in the app that opens the file. Two settings of one font are now two fonts of the set; a static font's record is unchanged. The record's form comes from the public report in #6388. Test `ai_editing::tests::variable_font_instances_name_their_design_space` (#6388) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2635623b58..500208265b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (`.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -1416,7 +1416,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests. A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type in an envelope with Distort Appearance on and strokes is mapped from its glyph box and, where that doesn't draw as the drawn art, from its box with strokes; the drawn-art check decides.rs`, `crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its box with strokes, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). From beef32b8a30720e7146ea6f689d790304e44e953 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:37:17 -0800 Subject: [PATCH 12/15] Artboards: an artboard's guide label colors its own guides Each artboard can carry a guide label: one of the layer colors or a custom RGB. Guides that belong to an artboard draw in its label color, and guides without an artboard, or on an artboard without a label, keep the guide color from the preferences. Selected guides still draw in the selection color. - Artboard Options has a Guide Label row (None, the layer colors with swatches, or Custom with a color swatch). - artboard.new and artboard.setProps take guideLabel: null, a layer color's name, or #rrggbb. Any other value is an error. The inspect summary lists guideLabel when one is set. - The native format saves the label and skips it when unset; a preset index outside the layer colors reads as no label. - artboard.setProps no longer adds an undo step when nothing changes. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/doc/src/artboard.rs | 14 +- crates/doc/src/document.rs | 1 + crates/doc/src/node/ids.rs | 26 ++++ crates/doc/src/tests.rs | 47 +++++++ .../src/cmd/fileio/affinity/document.rs | 1 + crates/engine/src/cmd/fileio/encode.rs | 1 + crates/engine/src/cmd/layer.rs | 50 ++++++- crates/engine/src/cmd/menucmds.rs | 1 + crates/engine/src/cmd/newdoc.rs | 1 + crates/engine/src/inspect.rs | 6 +- crates/engine/src/tests/panelcmds.rs | 124 +++++++++++++++++- crates/eps/src/import/ai/read/document.rs | 2 + crates/pdf/src/import/entry.rs | 1 + crates/pdf/src/tests.rs | 4 + crates/pdf/src/tests/print.rs | 1 + crates/pdf/src/tests/webview.rs | 1 + crates/svg/src/import/layers.rs | 1 + crates/tools/src/rulerguide/tests.rs | 2 + crates/ui-egui/src/canvas.rs | 19 ++- crates/ui-egui/src/canvas/tests.rs | 67 ++++++++++ .../ui-egui/src/dialogs/artboard_options.rs | 75 ++++++++++- crates/ui-egui/src/dialogs/form.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 58 ++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 16 ++- docs/target-app-parity.md | 1 + 52 files changed, 557 insertions(+), 14 deletions(-) diff --git a/crates/doc/src/artboard.rs b/crates/doc/src/artboard.rs index d7bfcafca5..ac5db48c76 100644 --- a/crates/doc/src/artboard.rs +++ b/crates/doc/src/artboard.rs @@ -1,4 +1,4 @@ -use super::{Arc, Deserialize, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip}; +use super::{Arc, Deserialize, LayerColor, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Artboard { @@ -39,6 +39,18 @@ pub struct Artboard { /// it behind the art ([`super::Document::with_artboard_fills`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub color: Option, + /// Guide label (Artboard Options): the color the canvas draws the artboard's own ruler guides + /// in (a guide whose [`super::Guide::artboard`] is this artboard's id), a [`LayerColor`] preset + /// or a custom RGB. None (No label) draws them in the guide color preference, as canvas guides + /// are. Only the canvas uses it: the paper, exports and print don't. Written only when set; a + /// file's preset outside [`super::LAYER_COLORS`] reads as no label. + #[serde(default, deserialize_with = "label_within_palette", skip_serializing_if = "Option::is_none")] + pub guide_label: Option, +} + +/// A file's guide label: a preset index outside [`super::LAYER_COLORS`] reads as no label. +fn label_within_palette<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + Ok(Option::::deserialize(d)?.filter(|c| !matches!(c, LayerColor::Preset(i) if usize::from(*i) >= super::LAYER_COLORS.len()))) } /// The Video Ruler Pixel Aspect Ratios an artboard takes (Artboard Options): from a pixel ten times diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 2a2f8a8d7a..f3f159e531 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -208,6 +208,7 @@ impl Document { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }], layers: vec![], swatches: swatches.into(), diff --git a/crates/doc/src/node/ids.rs b/crates/doc/src/node/ids.rs index 9e09a47a95..58915eb663 100644 --- a/crates/doc/src/node/ids.rs +++ b/crates/doc/src/node/ids.rs @@ -56,4 +56,30 @@ impl LayerColor { LayerColor::Custom(c) => c, } } + + /// The color as text: a preset's name from [`LAYER_COLORS`], else `#rrggbb` (lowercase). + pub fn label_text(self) -> String { + let preset = match self { + LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(i)), + LayerColor::Custom(_) => None, + }; + preset.map_or_else( + || { + let [r, g, b] = self.rgb(); + format!("#{r:02x}{g:02x}{b:02x}") + }, + |(name, _)| (*name).to_string(), + ) + } + + /// The color [`LayerColor::label_text`] names: a preset's name exactly as [`LAYER_COLORS`] + /// spells it, or `#rrggbb` with six hex digits. None for anything else. + pub fn from_label_text(s: &str) -> Option { + if let Some(i) = LAYER_COLORS.iter().position(|(name, _)| *name == s) { + return u8::try_from(i).ok().map(LayerColor::Preset); + } + let hex = s.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))?; + let byte = |k: usize| u8::from_str_radix(&hex[k..k + 2], 16).ok(); + Some(LayerColor::Custom([byte(0)?, byte(2)?, byte(4)?])) + } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 4b75b01497..21fe8d7ce9 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -5,6 +5,52 @@ mod lookups; mod slices; mod units; +/// A guide label's text is a layer color's name or `#rrggbb`, and reads back as the same color; +/// other spellings, an alpha part and a short form are not labels. +#[test] +fn guide_label_text_names_a_layer_color_or_rgb() { + for (i, (name, _)) in LAYER_COLORS.iter().enumerate() { + let c = LayerColor::Preset(u8::try_from(i).unwrap()); + assert_eq!(c.label_text(), *name); + assert_eq!(LayerColor::from_label_text(name), Some(c)); + } + let custom = LayerColor::Custom([0x0a, 0xbc, 0xff]); + assert_eq!(custom.label_text(), "#0abcff"); + assert_eq!(LayerColor::from_label_text("#0ABCff"), Some(custom)); + // A preset past the layer colors has no name: its text is the color it draws in. + let [r, g, b] = LayerColor::Preset(200).rgb(); + assert_eq!(LayerColor::Preset(200).label_text(), format!("#{r:02x}{g:02x}{b:02x}")); + for bad in ["red", "Red ", "", "#", "#fff", "#0abcff00", "0abcff", "#0abcfg", "#0abcff"] { + assert_eq!(LayerColor::from_label_text(bad), None, "{bad:?}"); + } +} + +/// An artboard's guide label: none unless set, left out of the JSON when none, and a preset past +/// the layer colors reading as none. +#[test] +fn artboard_guide_label_defaults_and_skips_in_json() { + let mut a = Document::new(100.0, 100.0).artboards[0].clone(); + assert_eq!(a.guide_label, None); + let plain = serde_json::to_value(&a).unwrap(); + assert!(plain.get("guide_label").is_none(), "{plain}"); + a.guide_label = Some(LayerColor::Custom([1, 2, 3])); + let v = serde_json::to_value(&a).unwrap(); + assert_eq!(v["guide_label"], serde_json::json!({"Custom": [1, 2, 3]})); + assert_eq!(serde_json::from_value::(v).unwrap(), a); + let read = |label: serde_json::Value| { + let mut v = plain.clone(); + v["guide_label"] = label; + serde_json::from_value::(v).map(|a| a.guide_label) + }; + assert_eq!(read(serde_json::json!({"Preset": 26})).unwrap(), Some(LayerColor::Preset(26))); + assert_eq!(read(serde_json::json!({"Preset": 27})).unwrap(), None); + assert_eq!(read(serde_json::json!({"Preset": 255})).unwrap(), None); + assert_eq!(read(serde_json::Value::Null).unwrap(), None); + assert!(read(serde_json::json!({"Preset": -1})).is_err()); + assert!(read(serde_json::json!({"Tint": 1})).is_err()); + assert_eq!(serde_json::from_value::(plain).unwrap().guide_label, None, "older files have none"); +} + /// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch /// are binary fractions now, and the minor ticks between them stay binary too; every other /// unit is still read in tenths. @@ -146,6 +192,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let rect = |d: &mut Document, r: Rect, appearance: Appearance| { let id = d.alloc_id(); diff --git a/crates/engine/src/cmd/fileio/affinity/document.rs b/crates/engine/src/cmd/fileio/affinity/document.rs index e87e9ac0f0..9114e9a40f 100644 --- a/crates/engine/src/cmd/fileio/affinity/document.rs +++ b/crates/engine/src/cmd/fileio/affinity/document.rs @@ -88,6 +88,7 @@ impl Builder { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }) .collect(); if self.doc.artboards.is_empty() { diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1108d3e2ca..84188c313a 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -373,6 +373,7 @@ pub(crate) fn with_single_artboard(mut d: Document, rect: Rect, name: &str) -> D show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }]; d } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 25201db87e..07571ad320 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "New Artboard", ["Window", "Artboards"], None, - "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)", + "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), guideLabel?: name | \"#rrggbb\" | null (its guide label, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)", has_doc, artboard_new ), @@ -155,7 +155,7 @@ pub fn specs() -> Vec { "Artboard Options…", ["Window", "Artboards"], None, - "{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}", + "{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes", has_doc, artboard_set ), @@ -859,6 +859,22 @@ fn artboard_color(p: &Value, cmd: &str) -> Result Result>> { + match p.get("guideLabel") { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(v) => v + .as_str() + .and_then(LayerColor::from_label_text) + .map(|c| Some(Some(c))) + .ok_or_else(|| bad(cmd, "`guideLabel` is null, a layer color's name or #rrggbb")), + } +} + /// An artboard command's text param `key`: None when absent or null, else the string. Any other /// value, such as 5, is an error: "`{key}` must be a string". fn artboard_str<'a>(p: &'a Value, key: &str, cmd: &str) -> Result> { @@ -898,6 +914,7 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result { let last = d0.artboards.last().map(|a| a.rect).unwrap_or(Rect::new(0.0, 0.0, 612.0, 792.0)); let def = Rect::new(last.x1 + 20.0, last.y0, last.x1 + 20.0 + last.width(), last.y1); let color = artboard_color(p, "artboard.new")?.flatten(); + let guide_label = artboard_guide_label(p, "artboard.new")?.flatten(); check_switches(p, &["showCenterMark", "showCrossHairs", "showVideoSafeAreas"], "artboard.new")?; check_numbers(p, &["x", "y", "width", "height"], "artboard.new")?; let r = match artboard_side(p, "artboard.new")? { @@ -932,6 +949,7 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result { show_video_safe_areas, video_ruler_pixel_aspect_ratio, color, + guide_label, }); Ok(d.artboards.len() - 1) })?; @@ -1001,6 +1019,7 @@ struct ArtboardEdit<'a> { now: Rect, name: Option<&'a str>, color: Option>, + guide_label: Option>, lock: Option, center_mark: Option, cross_hairs: Option, @@ -1013,6 +1032,23 @@ struct ArtboardEdit<'a> { art: Vec, } +impl ArtboardEdit<'_> { + /// Does the edit change artboard `a` (the one at its index) or the art and guides on it? + fn changes(&self, a: &Artboard) -> bool { + let name = self.name.map(|n| if n.is_empty() { format!("Artboard {}", self.index + 1) } else { n.to_string() }); + self.now != a.rect + || self.transform.is_some() + || name.is_some_and(|n| n != a.name) + || self.color.is_some_and(|c| c != a.color) + || self.guide_label.is_some_and(|c| c != a.guide_label) + || self.lock.is_some_and(|l| l != a.locked) + || self.center_mark.is_some_and(|m| m != a.show_center_mark) + || self.cross_hairs.is_some_and(|c| c != a.show_cross_hairs) + || self.safe_areas.is_some_and(|v| v != a.show_video_safe_areas) + || self.pixel_aspect.is_some_and(|r| r != a.video_ruler_pixel_aspect_ratio) + } +} + fn artboard_set(s: &mut Session, p: &Value) -> Result { // One artboard (`index` and its fields), or several (`artboards`, each with its own fields). let entries: Vec<&Value> = match p.get("artboards") { @@ -1044,6 +1080,8 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result { let was = d.artboards.get(index).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?; // The background color: a color sets it, null clears it, absent leaves it as it is. let color = artboard_color(q, "artboard.setProps")?; + // The guide label likewise; a locked artboard's can change, as its name can. + let guide_label = artboard_guide_label(q, "artboard.setProps")?; let now = rect_from(q, was); let lock = q.get("locked").and_then(Value::as_bool); let (center_mark, cross_hairs) = (q.get("showCenterMark").and_then(Value::as_bool), q.get("showCrossHairs").and_then(Value::as_bool)); @@ -1070,6 +1108,7 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result { now, name: artboard_str(q, "name", "artboard.setProps")?.map(str::trim), color, + guide_label, lock, center_mark, cross_hairs, @@ -1082,6 +1121,10 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result { art, }); } + // Nothing to change: no undo step. + if !edits.iter().any(|e| d.artboards.get(e.index).is_none_or(|a| e.changes(a))) { + return if scale_art { Ok(json!({ "scaled": [] })) } else { ok() }; + } // Noted in the journal when art goes along, so a replay transforms the same objects whatever // the preference is then. if edits.iter().any(|e| e.transform.is_some()) { @@ -1102,6 +1145,9 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result { if let Some(c) = e.color { a.color = c; } + if let Some(c) = e.guide_label { + a.guide_label = c; + } if let Some(l) = e.lock { a.locked = l; } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 0a4c93dc5e..ed17677790 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -1319,6 +1319,7 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); converted.push(id); } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index d8f0681cc0..20dc187ab5 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -344,6 +344,7 @@ impl DocSettings { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }) .collect(); d diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 14df8529d7..c474e25756 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -133,7 +133,8 @@ pub fn document(s: &Session) -> Value { document_opts(s, SummaryOpts::default()) } -/// An artboard's name and rectangle, its background color (`#rrggbb`) when it has one, +/// An artboard's name and rectangle, its background color (`#rrggbb`) when it has one, its guide +/// label (a layer color's name or `#rrggbb`) when it has one, /// `locked: true` when it is locked, `showCenterMark: true`, `showCrossHairs: true` and /// `showVideoSafeAreas: true` when it shows them, and `videoRulerPixelAspectRatio` when it isn't 1. fn artboard_summary(a: &vectorcraft_doc::Artboard) -> Value { @@ -141,6 +142,9 @@ fn artboard_summary(a: &vectorcraft_doc::Artboard) -> Value { if let Some(c) = a.color { v["color"] = json!(c.to_hex()); } + if let Some(c) = a.guide_label { + v["guideLabel"] = json!(c.label_text()); + } for (key, on) in [ ("locked", a.locked), ("showCenterMark", a.show_center_mark), diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 239d6bee7b..4d549c31ef 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -2,7 +2,7 @@ use serde_json::json; use vectorcraft_color::{Color, GradientKind, Paint}; -use vectorcraft_doc::{AppearanceItem, NodeKind}; +use vectorcraft_doc::{AppearanceItem, LayerColor, NodeKind}; use crate::*; @@ -1387,6 +1387,128 @@ fn artboard_video_display_options_are_set_in_one_undo_step() { assert_eq!(video(&s, 1), (false, 10.0), "10 is in range"); } +/// Artboard Options' guide label: `artboard.setProps {guideLabel}` takes a layer color's name or +/// `#rrggbb` and null clears it, each change one undo step, also on a locked artboard (whose +/// rectangle stays locked) and for several artboards in one list; a value equal to the artboard's +/// adds no undo step. `artboard.new` takes it, a duplicate and an undone delete keep it, and +/// `inspect_document` reports it. A bad value anywhere in a list changes nothing. +#[test] +fn artboard_guide_labels_are_set_and_cleared_in_one_undo_step() { + let mut s = session(); + s.execute("artboard.new", &json!({})).unwrap(); + let label = |s: &Session, i: usize| s.doc().unwrap().doc.artboards[i].guide_label; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + assert_eq!((label(&s, 0), label(&s, 1)), (None, None), "no label by default"); + let u0 = undo(&s); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "Red"})).unwrap(); + assert_eq!((label(&s, 0), label(&s, 1)), (None, Some(LayerColor::Preset(1))), "only that artboard"); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "#12aBcd"})).unwrap(); + assert_eq!(label(&s, 1), Some(LayerColor::Custom([0x12, 0xab, 0xcd]))); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": null})).unwrap(); + assert_eq!(label(&s, 1), None, "null clears it"); + assert_eq!(undo(&s), u0 + 3, "one undo step each"); + for was in [Some(LayerColor::Custom([0x12, 0xab, 0xcd])), Some(LayerColor::Preset(1)), None] { + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(label(&s, 1), was); + } + s.execute("edit.redo", &json!({})).unwrap(); + // The same label again, or a list that changes nothing: no undo step. + let u = undo(&s); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "Red"})).unwrap(); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": null}, {"index": 1, "guideLabel": "Red"}]})).unwrap(); + assert_eq!(undo(&s), u, "nothing changed, no undo step"); + // A locked artboard takes a label; its rectangle stays locked. + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let rect0 = s.doc().unwrap().doc.artboards[0].rect; + s.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Gold"})).unwrap(); + assert_eq!(label(&s, 0), Some(LayerColor::Preset(15))); + assert!(s.execute("artboard.setProps", &json!({"index": 0, "x": 999, "guideLabel": "Teal"})).is_err()); + assert_eq!((s.doc().unwrap().doc.artboards[0].rect, label(&s, 0)), (rect0, Some(LayerColor::Preset(15)))); + let u = undo(&s); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Teal"}, {"index": 1, "guideLabel": "#000000"}]})).unwrap(); + assert_eq!((label(&s, 0), label(&s, 1)), (Some(LayerColor::Preset(11)), Some(LayerColor::Custom([0, 0, 0]))), "each its own"); + assert_eq!(undo(&s), u + 1, "in one undo step"); + let doc = crate::inspect::document(&s); + assert_eq!((doc["artboards"][0]["guideLabel"].clone(), doc["artboards"][1]["guideLabel"].clone()), (json!("Teal"), json!("#000000"))); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": null})).unwrap(); + assert!(crate::inspect::document(&s)["artboards"][1].get("guideLabel").is_none(), "no label isn't reported"); + let copy = s.execute("artboard.duplicate", &json!({"index": 0})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, copy), Some(LayerColor::Preset(11)), "a duplicate keeps it"); + let made = s.execute("artboard.new", &json!({"guideLabel": "Violet"})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, made), Some(LayerColor::Preset(14)), "a new artboard takes it"); + let plain = s.execute("artboard.new", &json!({})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, plain), None); + s.execute("artboard.delete", &json!({"index": made})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(label(&s, made), Some(LayerColor::Preset(14)), "undoing a delete brings it back"); + let before = s.doc().unwrap().doc.clone(); + let bads = [ + json!("red"), + json!(" Red"), + json!("#12345"), + json!("#1234567"), + json!("#12345678"), + json!("#fff"), + json!("#gg0000"), + json!(1), + json!([1, 2, 3]), + json!({"Preset": 1}), + json!(true), + ]; + for bad in bads { + assert!(s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": bad})).is_err(), "{bad}"); + assert!(s.execute("artboard.new", &json!({"guideLabel": bad})).is_err(), "{bad}"); + assert!( + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Red"}, {"index": 1, "guideLabel": bad}]})).is_err(), + "{bad}" + ); + } + assert!(s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "guideLabel": "Red"}, {"index": 1, "guideLabel": "Red"}]})).is_err()); + assert!(s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "guideLabel": "Red"}, {"index": 99, "guideLabel": "Red"}]})).is_err()); + assert_eq!(*s.doc().unwrap().doc, *before, "a bad value changes nothing"); +} + +/// The native format keeps the guide label, as `{"Preset": n}` or `{"Custom": [r, g, b]}`. An +/// artboard without one is written as before labels could be set, and a preset outside the layer +/// colors in a file reads as no label. Exports leave the label out. +#[test] +fn artboard_guide_labels_round_trip_through_the_native_format() { + let mut s = session(); + rect(&mut s); + s.execute("artboard.new", &json!({})).unwrap(); + let save = |s: &Session| vectorcraft_format::save(&s.doc().unwrap().doc, false); + let before = save(&s); + let plain = (*s.doc().unwrap().doc).clone(); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Green"}, {"index": 1, "guideLabel": "#102030"}]})).unwrap(); + let bytes = save(&s); + let saved: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let ab = |i: usize| saved["document"]["artboards"][i]["guide_label"].clone(); + assert_eq!((ab(0), ab(1)), (json!({"Preset": 2}), json!({"Custom": [16, 32, 48]}))); + let back = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(back.artboards, s.doc().unwrap().doc.artboards); + // Screen-only: SVG and PDF exports are the same as without the labels. + let on = (*s.doc().unwrap().doc).clone(); + assert_eq!(vectorcraft_svg::export(&on, &Default::default()), vectorcraft_svg::export(&plain, &Default::default())); + let options = vectorcraft_pdf::PdfOptions { created: Some(0), ..Default::default() }; + assert_eq!(crate::export_pdf(&on, &options).unwrap(), crate::export_pdf(&plain, &options).unwrap()); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": null}, {"index": 1, "guideLabel": null}]})).unwrap(); + assert_eq!(save(&s), before, "without labels, the file is as it was"); + // A file's labels as another writer might put them: a preset past the layer colors reads as + // none, and a label that isn't a layer color at all is refused. + let mut edited = saved.clone(); + edited["document"]["artboards"][0]["guide_label"] = json!({"Preset": 27}); + edited["document"]["artboards"][1]["guide_label"] = json!({"Preset": 26}); + let back = vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).unwrap(); + assert_eq!((back.artboards[0].guide_label, back.artboards[1].guide_label), (None, Some(LayerColor::Preset(26)))); + for bad in [json!({"Preset": 256}), json!({"Custom": [1, 2]}), json!("Red"), json!({"Custom": [1, 2, 300]})] { + edited["document"]["artboards"][0]["guide_label"] = bad.clone(); + assert!(vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).is_err(), "{bad}"); + } + edited["document"]["artboards"][0]["guide_label"] = json!(null); + let back = vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).unwrap(); + assert_eq!(back.artboards[0].guide_label, None); +} + /// The native format keeps Show Video Safe Areas and the Video Ruler Pixel Aspect Ratio. A /// document whose artboards hide the safe areas and have square pixels is written byte for byte as /// before they could be set, a file written without the two keys opens with the safe areas off diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 63e9f3df77..0e1ca67676 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1209,6 +1209,7 @@ impl<'a> Reader<'a> { show_video_safe_areas: b.safe_areas, video_ruler_pixel_aspect_ratio: b.par, color: None, + guide_label: None, }) .collect(); if doc.artboards.is_empty() { @@ -1223,6 +1224,7 @@ impl<'a> Reader<'a> { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }]; } doc.opened_artboard = active.and_then(|i| doc.artboards.get(i)).map(|a| a.id); diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 687fcb1566..38f22689a8 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -375,6 +375,7 @@ fn read_opened( show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let page_layer = |b: &mut Builder<'_>, art: Vec>, shown: bool| { let name = if shown { format!("Page {}", number + 1) } else { format!("Page {} (unsorted)", number + 1) }; diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 365b653890..af744437d5 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -131,6 +131,7 @@ fn one_page_per_artboard_with_sizes() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); d.artboards.push(Artboard { id: 3, @@ -142,6 +143,7 @@ fn one_page_per_artboard_with_sizes() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let bytes = export(&d, &PdfOptions::default()).unwrap(); let pdf = craft_pdf::syntax::Pdf::new(bytes).unwrap(); @@ -162,6 +164,7 @@ fn artboard_range_and_bad_index() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let bytes = export(&d, &PdfOptions { artboards: Some(vec![1]), ..Default::default() }).unwrap(); let pdf = craft_pdf::syntax::Pdf::new(bytes).unwrap(); @@ -893,6 +896,7 @@ fn import_max_pages_and_multi_page() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); add(&mut d, rect_node(Rect::new(10.0, 10.0, 50.0, 50.0), Color::BLACK)); add(&mut d, rect_node(Rect::new(310.0, 10.0, 350.0, 50.0), Color::BLACK)); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index daf2bab071..2f59563e70 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -33,6 +33,7 @@ fn artboard(id: u32, x: f64) -> Artboard { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, } } diff --git a/crates/pdf/src/tests/webview.rs b/crates/pdf/src/tests/webview.rs index 9a4659ddce..a40db425e7 100644 --- a/crates/pdf/src/tests/webview.rs +++ b/crates/pdf/src/tests/webview.rs @@ -31,6 +31,7 @@ fn doc(n: usize, image: bool, on_first: bool) -> Document { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); } let mut png = vec![]; diff --git a/crates/svg/src/import/layers.rs b/crates/svg/src/import/layers.rs index 04e3887945..15a77e37f0 100644 --- a/crates/svg/src/import/layers.rs +++ b/crates/svg/src/import/layers.rs @@ -146,6 +146,7 @@ pub(super) fn inkscape_pages(xml: &roxmltree::Document, user: Affine) -> Option< show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }) .collect(); (!pages.is_empty()).then_some(pages) diff --git a/crates/tools/src/rulerguide/tests.rs b/crates/tools/src/rulerguide/tests.rs index a4a91d24c5..4b4f1be72c 100644 --- a/crates/tools/src/rulerguide/tests.rs +++ b/crates/tools/src/rulerguide/tests.rs @@ -289,6 +289,7 @@ fn an_artboard_guide_is_picked_and_snapped_to_across_its_artboard_only() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); d.guides = vec![Guide { artboard: Some(id), ..Guide::new(false, 150.0) }]; let (s, p) = (Selection::default(), paint()); @@ -604,6 +605,7 @@ fn ruler_guide_readouts_count_from_the_active_artboard_with_artboard_rulers() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); doc.ruler_origin = Point::new(5.0, 5.0); let (paint, selection) = (paint(), Selection::default()); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c25acd07a6..63be246dac 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1087,11 +1087,14 @@ fn guide_lines(app: &VectorcraftApp, painter: &egui::Painter, xf: &Xf, rect: egu } } -/// The ruler guides of document `st`, its selected guides in the selection colour. +/// The ruler guides of document `st`, its selected guides in the selection colour. An artboard +/// guide of an artboard with a guide label ([`vectorcraft_doc::Artboard::guide_label`]) is drawn in +/// the label's color, in the guide preference's style; the others in the guide preference's color. fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, xf, t): (&egui::Painter, &Xf, &Tokens), rect: egui::Rect) { let doc = &st.doc; let look = LineLook::guides(&app.session.prefs, t); let picked = LineLook { color: t.selection, ..look }; + let labels = guide_labels(doc); let selected: &[usize] = &st.selection.guides; let key = st.selection.key_guide; let view = view_bounds(xf); @@ -1108,7 +1111,8 @@ fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, ends } }; - if selected.contains(&i) { picked } else { look }.guide(painter, a, b); + let own = g.artboard.and_then(|id| labels.get(&id)).map_or(look, |&color| LineLook { color, ..look }); + if selected.contains(&i) { picked } else { own }.guide(painter, a, b); // The key guide (Align to Key Object, #2143): thicker, as a key object's outline is. if key == Some(i) { painter.line_segment([a, b], Stroke::new(KEY_OUTLINE, picked.color)); @@ -1116,6 +1120,17 @@ fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, } } +/// The guide label colors of `doc`'s artboards that have one, by artboard id. +pub(super) fn guide_labels(doc: &vectorcraft_doc::Document) -> std::collections::HashMap { + doc.artboards + .iter() + .filter_map(|a| { + let [r, g, b] = a.guide_label?.rgb(); + Some((a.id, Color32::from_rgb(r, g, b))) + }) + .collect() +} + /// The selection's visuals and the tools' overlays, to be drawn. fn selection_visuals( app: &mut VectorcraftApp, diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index b76599a4bc..a9ef2c228d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1208,6 +1208,73 @@ fn a_drag_from_a_ruler_onto_the_canvas_makes_a_guide() { assert_eq!(app.session.active().unwrap().doc.art_bounds(), None, "the tool drew nothing"); } +/// An artboard's guide label colors its own guides only: a canvas guide, a guide of an artboard +/// without a label and a guide of a deleted artboard keep the guide color preference, and a +/// selected labeled guide takes the selection color. Hide Guides hides labeled guides too. +#[test] +fn artboard_guide_label_colors_only_its_own_guides() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("artboard.new", &json!({})).unwrap(); + app.session.execute("artboard.new", &json!({})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Red"})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 2, "guideLabel": "#00ff00"})).unwrap(); + // Vertical guides at x 100 (artboard 1, Red), 520 (artboard 2, no label) and 940 (artboard + // 3, whose artboard is then deleted), and a horizontal canvas guide at y 150. + for (pos, artboard) in [(100, json!(0)), (520, json!(1)), (940, json!(2))] { + app.session.execute("guide.add", &json!({"vertical": true, "pos": pos, "artboard": artboard})).unwrap(); + } + app.session.execute("guide.add", &json!({"vertical": false, "pos": 150})).unwrap(); + // Deleting artboard 3 deletes its guide; a guide still naming its id (as a file might) is an + // orphan, drawn across the canvas. + let gone = app.session.active().unwrap().doc.artboards[2].id; + app.session.execute("artboard.setProps", &json!({"index": 2, "guideLabel": null})).unwrap(); + app.session.execute("artboard.delete", &json!({"index": 2})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + { + let st = app.session.active_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + let last = doc.guides.len() - 1; + doc.guides[last].artboard = Some(gone); + } + app.ui.view.guides = true; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let t = Tokens::get(&ctx); + let pref = LineLook::guides(&app.session.prefs, &t).color; + let colors = |app: &mut VectorcraftApp, at: f64, vertical: bool| -> Vec { + shapes(app, &ctx) + .iter() + .filter_map(|s| match s { + Shape::LineSegment { points, stroke } => { + let (a, b) = (xf.to_doc(points[0]), xf.to_doc(points[1])); + let (u, v) = if vertical { (a.x, b.x) } else { (a.y, b.y) }; + ((u - at).abs() < 0.01 && (v - at).abs() < 0.01).then_some(stroke.color) + } + _ => None, + }) + .collect() + }; + let red = Color32::from_rgb(0xff, 0x4f, 0x4f); + assert_eq!(colors(&mut app, 100.0, true), [red], "the labeled artboard's guide"); + assert_eq!(colors(&mut app, 520.0, true), [pref], "an artboard without a label"); + assert_eq!(colors(&mut app, 150.0, false), [pref], "a canvas guide"); + assert!(colors(&mut app, 940.0, true).is_empty(), "deleted with its artboard"); + assert_eq!(colors(&mut app, 300.0, true), [pref], "a guide whose artboard is gone"); + assert_ne!(red, pref); + // Selected, it is drawn in the selection color; deselected, in the label's again. + app.session.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [t.selection], "selected"); + app.session.execute("guide.select", &json!({"indexes": []})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [red], "deselected"); + // A new label shows on the next frame. + app.session.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Black"})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [Color32::BLACK]); + app.ui.view.guides = false; + assert!(colors(&mut app, 100.0, true).is_empty(), "Hide Guides hides it"); +} + /// #4646: a guide dragged out of a ruler shows as a line across the canvas while it is dragged, /// also with Preferences › Performance › Real-time Drawing and Editing off (only its position /// label showed then). diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 0ce0de9350..1854eba4b9 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -1,7 +1,8 @@ //! Artboard Options (double-click with the Artboard tool, double-click the tool, or the Artboards //! panel's options icon or menu): the artboard's fields, sizes parsed with units, its position //! from a reference point, its background color (`color`: a color as the paint commands take -//! it, or null for none), Show Center Mark and Show Cross Hairs (`showCenterMark`, +//! it, or null for none), its guide label (`guideLabel`: the color its own guides are drawn in, a +//! layer color's name or `#rrggbb`, or null for none), Show Center Mark and Show Cross Hairs (`showCenterMark`, //! `showCrossHairs`), the display marks the canvas draws on the artboard //! (https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/modify-display-settings-of-artboards.html), //! and its video display options, Show Video Safe Areas and Video Ruler Pixel Aspect Ratio @@ -15,7 +16,7 @@ use serde_json::{Value, json}; use vectorcraft_color::Color; -use vectorcraft_doc::Unit; +use vectorcraft_doc::{LAYER_COLORS, LayerColor, Unit}; use vectorcraft_engine::cmd::color_value; use vectorcraft_geom::{Point, Rect}; @@ -32,7 +33,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, // A new artboard's dialog opens without these; its swatch, checkboxes and Video Ruler Pixel // Aspect Ratio field add them. The Global checkboxes' fields come from the preferences. - inputs: |_| &["color", "showCenterMark", "showCrossHairs", "showVideoSafeAreas", PIXEL_ASPECT, FADE, UPDATE_WHILE_DRAGGING], + inputs: |_| &["color", GUIDE_LABEL, "showCenterMark", "showCrossHairs", "showVideoSafeAreas", PIXEL_ASPECT, FADE, UPDATE_WHILE_DRAGGING], ..DialogSpec::FORM }; @@ -49,7 +50,7 @@ fn placed(d: &Dialog) -> Rect { /// as the Transform panel and the Control bar show an artboard's. A new Width or Height keeps the /// reference point where it was, as their sizes do. /// Then Background Color: the Fill list (None, White, Black; Custom for another color) and a swatch -/// that picks a color of its own, the Show Center Mark, Show Cross Hairs and Show Video Safe Areas +/// that picks a color of its own, the Guide Label row ([`guide_label_row`]), the Show Center Mark, Show Cross Hairs and Show Video Safe Areas /// checkboxes, and the Video Ruler Pixel Aspect Ratio field. Last, under Global, the Fade Region /// Outside Artboard and Update While Dragging checkboxes. fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { @@ -116,6 +117,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if let Some(c) = set { d.fields.insert("color".into(), c.as_ref().map_or(Value::Null, crate::panels::color_json)); } + guide_label_row(ui, d); ui.add_space(8.0); form::check(ui, d, "showCenterMark", tl!("Show Center Mark")); form::check(ui, d, "showCrossHairs", tl!("Show Cross Hairs")); @@ -137,6 +139,64 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// The field of the guide label, as `artboard.setProps` and `artboard.new` take it: a layer +/// color's name, `#rrggbb`, or null for none. +pub(super) const GUIDE_LABEL: &str = "guideLabel"; + +/// The size of the color chip before each name in the Guide Label list. +const CHIP: egui::Vec2 = egui::vec2(16.0, 10.0); + +/// The Guide Label row: a list of None, the layer colors (each after a chip of its color) and +/// Custom, and, while the artboard has a label, a swatch that picks a color of its own. Custom +/// keeps the label's color as a `#rrggbb` value. +fn guide_label_row(ui: &mut egui::Ui, d: &mut Dialog) { + let now = d.fields.get(GUIDE_LABEL).and_then(Value::as_str).and_then(LayerColor::from_label_text); + let shown = match now { + None => "None", + Some(LayerColor::Preset(i)) => LAYER_COLORS.get(usize::from(i)).map_or("Custom", |(n, _)| *n), + Some(LayerColor::Custom(_)) => "Custom", + }; + let mut set = None; + ui.horizontal(|ui| { + let row = form::row_label(ui, tl!("Guide Label:")); + ui.label_inputs_by(row.id, |ui| { + let border = crate::theme::Tokens::get(ui.ctx()).input_border; + let rows = std::iter::once(("None", None)).chain(LAYER_COLORS.iter().map(|(n, c)| (*n, Some(*c)))).chain([("Custom", None)]); + let picked = crate::widgets::combo(ui, "ab-options-guide-label", tl!(shown), 140.0, |ui| { + let mut chosen = None; + for (i, (name, rgb)) in rows.enumerate() { + let chip = egui::IdSalt::new(("ab-guide-label-chip", i)); + let r = egui::Button::selectable(name == shown, (egui::Atom::custom(chip, CHIP), tl!(name))).atom_ui(ui); + if let (Some(rect), Some([cr, cg, cb])) = (r.rect(chip), rgb) { + ui.painter().rect_filled(rect, 1.0, egui::Color32::from_rgb(cr, cg, cb)); + ui.painter().rect_stroke(rect, 1.0, egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); + } + if r.response.clicked() { + chosen = Some(i); + } + } + chosen + }); + match picked { + Some(0) => set = Some(None), + Some(i) if i <= LAYER_COLORS.len() => set = u8::try_from(i - 1).ok().map(|i| Some(LayerColor::Preset(i))), + Some(_) => set = Some(Some(LayerColor::Custom(now.map_or(LAYER_COLORS[0].1, LayerColor::rgb)))), + None => {} + } + if let Some(c) = now { + let mut rgb = c.rgb(); + let swatch_name = format!("{} {}", tl!("Guide Label:"), tl!("Swatches")); + if ui.name_inputs(swatch_name, |ui| ui.color_edit_button_srgb(&mut rgb)).changed() { + set = Some(Some(LayerColor::Custom(rgb))); + } + } + }); + }); + if let Some(c) = set { + d.fields.insert(GUIDE_LABEL.into(), c.map_or(Value::Null, |c| json!(c.label_text()))); + } +} + /// The preference and field of Fade Region Outside Artboard: while the Artboard tool is active, /// the canvas draws everything outside the artboards darker. const FADE: &str = "fadeRegionOutsideArtboard"; @@ -292,8 +352,10 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let a = st.doc.artboards.get(index).ok_or("no artboard")?; let r = a.rect; let color = a.color.as_ref().map(crate::panels::color_json); + let guide_label = a.guide_label.map(LayerColor::label_text); let fields = json!({ "index": index, "name": a.name, "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "color": color, + GUIDE_LABEL: guide_label, "showCenterMark": a.show_center_mark, "showCrossHairs": a.show_cross_hairs, "showVideoSafeAreas": a.show_video_safe_areas, PIXEL_ASPECT: a.video_ruler_pixel_aspect_ratio, }); @@ -374,7 +436,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { } /// OK for a new artboard: `artboard.new` with the fields (an empty name gives the default one), -/// the background color picked, the display marks ticked and the Video Ruler Pixel Aspect Ratio +/// the background color and guide label picked, the display marks ticked and the Video Ruler Pixel Aspect Ratio /// typed, and the new artboard becomes the active one. fn confirm_new(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut p = json!({}); @@ -388,6 +450,9 @@ fn confirm_new(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(c) = d.fields.get("color") { p["color"] = c.clone(); } + if let Some(c) = d.fields.get(GUIDE_LABEL).filter(|c| !c.is_null()) { + p[GUIDE_LABEL] = c.clone(); + } for k in ["showCenterMark", "showCrossHairs", "showVideoSafeAreas"] { if d.bool(k) { p[k] = json!(true); diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index c87cfb7e63..bbddd222f5 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -120,7 +120,7 @@ fn suffix(kind: &str, key: &str) -> Option<&'static str> { /// The fields of the form dialogs ([`grid`]) that the dialog's own body draws, by dialog kind. fn own_rows(kind: &str) -> &'static [&'static str] { match kind { - "artboardOptions" => &["color", super::artboard_options::PIXEL_ASPECT], + "artboardOptions" => &["color", super::artboard_options::GUIDE_LABEL, super::artboard_options::PIXEL_ASPECT], // The grids' Reference Point is their 9-point locator. "rectangularGrid" | "polarGrid" => &["reference"], _ => &[], diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index c5bdfea5c8..2ad8bdf213 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1755,6 +1755,64 @@ fn new_artboard_options_give_the_new_artboard_its_background_color() { } } +/// Artboard Options shows the artboard's guide label on its Guide Label: row (None, a layer color's +/// name, or Custom). OK sets a label picked there in one undo step, keeps it while another field +/// changes, and a null `guideLabel` clears it; Cancel leaves it. OK with nothing changed adds no +/// undo step, and a new artboard's Artboard Options gives it the label picked. +#[test] +fn artboard_options_shows_sets_and_clears_the_guide_label() { + let mut app = app(); + let label = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards[0].guide_label.map(vectorcraft_doc::LayerColor::label_text); + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let lines = |app: &mut VectorcraftApp| { + let text = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx())); + text.lines().map(str::trim).map(str::to_string).collect::>() + }; + crate::dialogs::artboard_options::open(&mut app).unwrap(); + let shown = lines(&mut app); + assert!(shown.iter().any(|l| l == "Guide Label:"), "{shown:?}"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["guideLabel"], json!(null)); + let u = undo(&app); + super::confirm(&mut app).unwrap(); + assert_eq!((label(&app), undo(&app)), (None, u), "OK with nothing changed"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("Orange")); + super::confirm(&mut app).unwrap(); + assert_eq!((label(&app).as_deref(), undo(&app)), (Some("Orange"), u + 1)); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["guideLabel"], json!("Orange")); + assert!(lines(&mut app).iter().any(|l| l == "Orange")); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("#123456")); + cancel(&mut app); + assert_eq!(label(&app).as_deref(), Some("Orange"), "Cancel leaves it"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert!(lines(&mut app).iter().any(|l| l == "Orange")); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("#123456")); + super::confirm(&mut app).unwrap(); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert!(lines(&mut app).iter().any(|l| l == "Custom")); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Card")); + super::confirm(&mut app).unwrap(); + assert_eq!(label(&app).as_deref(), Some("#123456"), "kept while another field changes"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("purple")); + assert!(super::confirm(&mut app).is_err(), "a name in other letter case is refused"); + assert_eq!(label(&app).as_deref(), Some("#123456")); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!(null)); + super::confirm(&mut app).unwrap(); + assert_eq!(label(&app), None); + for (picked, want) in [(Some(json!("Teal")), Some("Teal")), (None, None)] { + app.run("ui.newArtboard", json!({})).unwrap(); + if let Some(c) = picked { + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), c); + } + super::confirm(&mut app).unwrap(); + let ab = app.session.doc().unwrap().doc.artboards.last().cloned().unwrap(); + assert_eq!(ab.guide_label.map(vectorcraft_doc::LayerColor::label_text).as_deref(), want); + } +} + /// Artboard Options shows Show Center Mark and Show Cross Hairs, ticked as the artboard has them /// whether it opens from the Artboards panel or from a double-click with the Artboard tool. OK /// sets them in one undo step, and a new artboard's Artboard Options gives it the ones ticked. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2738281c30..1f8fa29f75 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -276,6 +276,7 @@ font-technology Variable Променливи Average… Усредняване… Axis: Ос: Background Color: Цвят на фона: + Guide Label: Етикет на водачите: Show Center Mark Показване на централен знак Show Cross Hairs Показване на кръстосани линии Show Video Safe Areas Показване на безопасните видеозони diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f6d0fe0771..cb38ec15bf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2623,6 +2623,7 @@ digits Malayalam Malajalam File Dimensions Dimenzije datoteke Transforms Transformacije Background Color: Boja pozadine: + Guide Label: Oznaka vodilica: Show Center Mark Prikaži oznaku centra Show Cross Hairs Prikaži končanicu Show Video Safe Areas Prikaži sigurne oblasti za video diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 017a0c4498..fb3a68880e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -428,6 +428,7 @@ antiAlias Sharp Nítid B5 B5 Back Enrere Background Color: Color de fons: + Guide Label: Etiqueta de les guies: Background Contents Contingut del fons Background Level Nivell de fons Background: Fons: @@ -5129,6 +5130,7 @@ digits Malayalam Malaiàlam @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis ha de ser "vertical", "horizontal" o un angle en graus, no `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" fons {other}: transparent, blanc, negre o un color com "#ff8800" @msg bad color {v} color incorrecte {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` és null, el nom d’un color de capa o #rrggbb @msg bad colour `{hex}` (#rrggbb) color incorrecte `{hex}` (#rrggbb) @msg bad page tree arbre de pàgines incorrecte @msg bad shortcut drecera incorrecta diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 28f70f1f2b..6f9190d3b0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2654,6 +2654,7 @@ digits Malayalam Malajálamské File Dimensions Rozměry souboru Transforms Transformace Background Color: Barva pozadí: + Guide Label: Štítek vodítek: Show Center Mark Zobrazit středovou značku Show Cross Hairs Zobrazit nitkový kříž Show Video Safe Areas Zobrazit bezpečné oblasti videa @@ -4594,6 +4595,7 @@ imageTrace Outline Obrys @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis musí být "vertical", "horizontal" nebo úhel ve stupních, ne `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" pozadí {other}: transparent, white, black nebo barva jako "#ff8800" @msg bad color {v} chybná barva {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` je null, název barvy vrstvy nebo #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio musí být číslo od 0,1 do 10 @msg the Color Picker is not open Výběr barvy není otevřený @msg the Simplify slider is not open Posuvník Zjednodušit není otevřený diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index dc580db9ea..160219a825 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2442,6 +2442,7 @@ digits Malayalam Malayalam File Dimensions Fildimensioner Transforms Transformationer Background Color: Baggrundsfarve: + Guide Label: Hjælpelinjeetiket: Show Center Mark Vis midtermærke Show Cross Hairs Vis trådkors Show Video Safe Areas Vis sikre videoområder diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1ca7293eab..3bffaab6cc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -264,6 +264,7 @@ font-technology Variable Variabel Average… Durchschnitt berechnen… Axis: Achse: Background Color: Hintergrundfarbe: + Guide Label: Farbmarkierung der Hilfslinien: Show Center Mark Mittelpunktmarke einblenden Show Cross Hairs Fadenkreuz einblenden Show Video Safe Areas Videosichere Bereiche einblenden @@ -4201,6 +4202,7 @@ theme Appearance Erscheinungsbild @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis muss "vertical", "horizontal" oder ein Winkel in Grad sein, nicht `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black oder eine Farbe wie "#ff8800" @msg bad color {v} ungültige Farbe {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` ist null, der Name einer Ebenenfarbe oder #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio muss eine Zahl von 0,1 bis 10 sein @msg the Color Picker is not open der Farbwähler ist nicht geöffnet @msg the Simplify slider is not open der Regler „Vereinfachen“ ist nicht geöffnet diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 13081c2248..adfd536b32 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -267,6 +267,7 @@ font-technology Variable Μεταβλητές Average… Μέσος όρος… Axis: Άξονας: Background Color: Χρώμα φόντου: + Guide Label: Ετικέτα οδηγών: Show Center Mark Εμφάνιση σημαδιού κέντρου Show Cross Hairs Εμφάνιση σταυρονήματος Show Video Safe Areas Εμφάνιση ασφαλών περιοχών βίντεο @@ -4245,6 +4246,7 @@ digits Malayalam Μαλαγιάλαμ @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` το axis πρέπει να είναι "vertical", "horizontal" ή γωνία σε μοίρες, όχι `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" φόντο {other}: transparent, white, black ή χρώμα όπως "#ff8800" @msg bad color {v} μη έγκυρο χρώμα {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb το `guideLabel` είναι null, όνομα χρώματος επιπέδου ή #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 Το videoRulerPixelAspectRatio πρέπει να είναι αριθμός από 0,1 έως 10 @msg bad colour `{hex}` (#rrggbb) μη έγκυρο χρώμα `{hex}` (#rrggbb) @msg bad page tree μη έγκυρο δέντρο σελίδων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 820daa8a60..7d889acf26 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -289,6 +289,7 @@ font-technology Variable Variables Average… Promediar… Axis: Eje: Background Color: Color de fondo: + Guide Label: Etiqueta de las guías: Show Center Mark Mostrar marca central Show Cross Hairs Mostrar líneas en cruz Show Video Safe Areas Mostrar áreas seguras de video @@ -4285,6 +4286,7 @@ axis Both Ambos @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis debe ser "vertical", "horizontal" o un ángulo en grados, no `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" fondo {other}: transparent, white, black o un color como "#ff8800" @msg bad color {v} color no válido {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` es null, el nombre de un color de capa o #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio debe ser un número de 0,1 a 10 @msg the Color Picker is not open el Selector de color no está abierto @msg the Simplify slider is not open el regulador de Simplificar no está abierto diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 986f29ca7b..3109ac7248 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2598,6 +2598,7 @@ digits Malayalam Malajalam File Dimensions Tiedoston mitat Transforms Muunnokset Background Color: Taustaväri: + Guide Label: Apuviivojen tunniste: Show Center Mark Näytä keskimerkki Show Cross Hairs Näytä hiusristikko Show Video Safe Areas Näytä videon turva-alueet @@ -4507,6 +4508,7 @@ imageTrace Outline Ääriviiva @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis-arvon on oltava "vertical", "horizontal" tai kulma asteina, ei `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" tausta {other}: transparent, white, black tai väri, kuten "#ff8800" @msg bad color {v} virheellinen väri {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` on null, tasovärin nimi tai #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio on oltava luku väliltä 0,1–10 @msg bad colour `{hex}` (#rrggbb) virheellinen väri `{hex}` (#rrggbb) @msg bad page tree virheellinen sivupuu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ac86d58038..6707f941bc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -290,6 +290,7 @@ font-technology Variable Variables Average… Alignement… Axis: Axe : Background Color: Couleur d’arrière-plan : + Guide Label: Étiquette des repères : Show Center Mark Afficher le repère central Show Cross Hairs Afficher le réticule Show Video Safe Areas Afficher les zones de sécurité vidéo @@ -4274,6 +4275,7 @@ axis Both Les deux @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis doit être "vertical", "horizontal" ou un angle en degrés, pas `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" arrière-plan {other} : transparent, white, black ou une couleur comme "#ff8800" @msg bad color {v} couleur non valide {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` est null, le nom d’une couleur de calque ou #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio doit être un nombre de 0,1 à 10 @msg the Color Picker is not open le Sélecteur de couleurs n’est pas ouvert @msg the Simplify slider is not open le curseur Simplifier n’est pas ouvert diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 1c8e722d9c..e74242c255 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -497,6 +497,7 @@ antiAlias Sharp शार्प B5 B5 Back वापस Background Color: बैकग्राउंड रंग: + Guide Label: गाइड लेबल: Background Contents बैकग्राउंड सामग्री Background Level बैकग्राउंड स्तर Background: बैकग्राउंड: @@ -6040,6 +6041,7 @@ antiAlias Sharp शार्प @msg bad base64 बुरा आधार64 @msg bad color {c} बुरा रंग {c} @msg bad color {v} बुरा रंग {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` null, किसी लेयर रंग का नाम या #rrggbb होता है @msg bad colour बुरा रंग @msg bad colour {v} बुरा रंग {v} @msg bad colour {v} in groupColors groupColors में अमान्य रंग {v} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2777645b2c..19af5e3a32 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -385,6 +385,7 @@ font-technology Variable Változó B4 B4 B5 B5 Background Color: Háttérszín: + Guide Label: Segédvonalak címkéje: Show Center Mark Középjel megjelenítése Show Cross Hairs Szálkereszt megjelenítése Show Video Safe Areas Biztonságos videoterületek megjelenítése @@ -4833,6 +4834,7 @@ imageTrace Outline Körvonal @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` az axis értéke "vertical", "horizontal" vagy fokban megadott szög lehet, ez nem az: `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black vagy egy szín, például "#ff8800" @msg bad color {v} hibás szín: {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb a `guideLabel` értéke null, egy rétegszín neve vagy #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio: 0,1 és 10 közötti szám kell @msg the Color Picker is not open a Színválasztó nincs megnyitva @msg the Simplify slider is not open az Egyszerűsítés csúszka nincs megnyitva diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bfa91456ba..0e1328833f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2442,6 +2442,7 @@ digits Malayalam Malayalam File Dimensions Dimensi file Transforms Transformasi Background Color: Warna latar belakang: + Guide Label: Label panduan: Show Center Mark Tampilkan tanda tengah Show Cross Hairs Tampilkan garis silang Show Video Safe Areas Tampilkan area aman video diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 00e9cbeb69..fc8de1649d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -289,6 +289,7 @@ font-technology Variable Variabili Average… Media… Axis: Asse: Background Color: Colore di sfondo: + Guide Label: Etichetta delle guide: Show Center Mark Mostra segno centrale Show Cross Hairs Mostra mirino Show Video Safe Areas Mostra aree sicure video @@ -4328,6 +4329,7 @@ axis Both Entrambi @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve essere "vertical", "horizontal" o un angolo in gradi, non `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" sfondo {other}: transparent, white, black o un colore come "#ff8800" @msg bad color {v} colore non valido {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` è null, il nome di un colore di livello o #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio deve essere un numero da 0,1 a 10 @msg the Color Picker is not open il Selettore colore non è aperto @msg the Simplify slider is not open il cursore Semplifica non è aperto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 2b2802a196..a3e7d44284 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1077,6 +1077,7 @@ antiAlias Sharp シャープ Average 平均 BLANK DOCUMENT PRESETS 空白のドキュメントプリセット Background Color: 背景色: + Guide Label: ガイドのラベル: Show Center Mark 中心マークを表示 Show Cross Hairs 十字線を表示 Show Video Safe Areas ビデオセーフエリアを表示 @@ -4684,6 +4685,7 @@ swatch Bright Violet ビビッドバイオレット @msg {label}… {label}… @msg no blend options ブレンドオプションがありません @msg bad color {v} カラー {v} が正しくありません +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` は null、レイヤーカラーの名前、または #rrggbb です @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio には 0.1 〜 10 の数値を指定してください @msg the Color Picker is not open カラーピッカーが開いていません @msg the Simplify slider is not open 単純化スライダーが開いていません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d7981d59f8..a9fd7ec120 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2343,6 +2343,7 @@ digits Malayalam მალაიალამური File Dimensions ფაილის ზომები Transforms გარდაქმნები Background Color: ფონის ფერი: + Guide Label: დამხმარე ხაზების იარლიყი: Show Center Mark ცენტრის ნიშნის ჩვენება Show Cross Hairs ჯვარედინი ხაზების ჩვენება Show Video Safe Areas ვიდეოს უსაფრთხო არეების ჩვენება @@ -4042,6 +4043,7 @@ font-technology Variable ცვლადი @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis უნდა იყოს "vertical", "horizontal" ან კუთხე გრადუსებში და არა `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" ფონი {other}: transparent, white, black ან ფერი, მაგალითად "#ff8800" @msg bad color {v} არასწორი ფერი {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` არის null, ფენის ფერის სახელი ან #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio უნდა იყოს რიცხვი 0,1-დან 10-მდე @msg bad colour `{hex}` (#rrggbb) არასწორი ფერი `{hex}` (#rrggbb) @msg bad page tree გვერდების არასწორი ხე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a25ffe1814..c7530e505f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1067,6 +1067,7 @@ antiAlias Sharp 날카롭게 Average 평균 BLANK DOCUMENT PRESETS 빈 문서 프리셋 Background Color: 배경색: + Guide Label: 안내선 레이블: Show Center Mark 중심 표시 보기 Show Cross Hairs 십자선 보기 Show Video Safe Areas 비디오 안전 영역 보기 @@ -4611,6 +4612,7 @@ theme Appearance 외관 @msg {label}… {label}… @msg no blend options 혼합 옵션이 없습니다 @msg bad color {v} 잘못된 색상 {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel`은 null, 레이어 색상 이름 또는 #rrggbb입니다 @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio은(는) 0.1에서 10 사이의 숫자여야 합니다 @msg the Color Picker is not open 색상 피커가 열려 있지 않습니다 @msg the Simplify slider is not open 단순화 슬라이더가 열려 있지 않습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3d3cc43619..40c9ce61c8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2456,6 +2456,7 @@ digits Malayalam Malayalam File Dimensions Bestandsafmetingen Transforms Transformaties Background Color: Achtergrondkleur: + Guide Label: Hulplijnlabel: Show Center Mark Middenmarkering tonen Show Cross Hairs Dradenkruis tonen Show Video Safe Areas Veilige videogebieden tonen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 26fe2d4ac1..16bf528970 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2567,6 +2567,7 @@ digits Malayalam Malajalam File Dimensions Wymiary pliku Transforms Przekształcenia Background Color: Kolor tła: + Guide Label: Etykieta linii pomocniczych: Show Center Mark Pokaż znacznik środka Show Cross Hairs Pokaż krzyż nitkowy Show Video Safe Areas Pokaż bezpieczne obszary wideo @@ -4417,6 +4418,7 @@ imageTrace Outline Kontur @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis musi mieć wartość "vertical", "horizontal" lub kąt w stopniach, nie `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" tło {other}: transparent, white, black lub kolor, np. "#ff8800" @msg bad color {v} nieprawidłowy kolor {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` to null, nazwa koloru warstwy lub #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio musi być liczbą od 0,1 do 10 @msg the Color Picker is not open Próbnik kolorów nie jest otwarty @msg the Simplify slider is not open Suwak Uprość nie jest otwarty diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c4bf2cb43c..1f451c285e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -275,6 +275,7 @@ antiAlias Sharp Nítido Average… Média… BLANK DOCUMENT PRESETS PREDEFINIDOS DE DOCUMENTO EM BRANCO Background Color: Cor do Plano de Fundo: + Guide Label: Rótulo das Guias: Show Center Mark Mostrar Marca Central Show Cross Hairs Mostrar Linhas Cruzadas Show Video Safe Areas Mostrar Áreas Seguras de Vídeo @@ -3841,6 +3842,7 @@ axis Both Ambos @msg at this scale the drawing is {w} × {h} pt, more than the canvas holds: choose a smaller scale or fit it to the artboard nesta escala o desenho tem {w} × {h} pt, mais do que a tela comporta: escolha uma escala menor ou ajuste-o à prancheta @msg background {other}: transparent, white, black or a colour such as "#ff8800" plano de fundo {other}: transparent, white, black ou uma cor como "#ff8800" @msg bad color {v} cor inválida {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` é null, o nome de uma cor de camada ou #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio deve ser um número de 0,1 a 10 @msg bad colour `{hex}` (#rrggbb) cor inválida `{hex}` (#rrggbb) @msg bad page tree árvore de páginas inválida diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 877699ff3a..c413cf8602 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -287,6 +287,7 @@ font-technology Variable Вариативные Average… Усреднить… Axis: Ось: Background Color: Цвет фона: + Guide Label: Метка направляющих: Show Center Mark Показать центральную метку Show Cross Hairs Показать перекрестие Show Video Safe Areas Показать безопасные зоны видео @@ -4322,6 +4323,7 @@ axis Both Оба @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis должно быть "vertical", "horizontal" или углом в градусах, а не `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" фон {other}: transparent, white, black или цвет, например "#ff8800" @msg bad color {v} недопустимый цвет {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` должен быть null, именем цвета слоя или #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio должно быть числом от 0,1 до 10 @msg the Color Picker is not open палитра цветов не открыта @msg the Simplify slider is not open ползунок «Упростить» не открыт diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9eebd4e53b..81731310ea 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -278,6 +278,7 @@ font-technology Variable Variabla Average… Medelvärde… Axis: Axel: Background Color: Bakgrundsfärg: + Guide Label: Stödlinjeetikett: Show Center Mark Visa mittmarkering Show Cross Hairs Visa hårkors Show Video Safe Areas Visa videosäkra områden @@ -4194,6 +4195,7 @@ axis Both Båda @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis måste vara "vertical", "horizontal" eller en vinkel i grader, inte `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black eller en färg som "#ff8800" @msg bad color {v} ogiltig färg {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` är null, namnet på en lagerfärg eller #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio måste vara ett tal från 0,1 till 10 @msg bad colour `{hex}` (#rrggbb) ogiltig färg `{hex}` (#rrggbb) @msg bad page tree ogiltigt sidträd diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 76ffbabccf..62e27ac6d8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -274,6 +274,7 @@ font-technology Variable Değişken Average… Ortalama… Axis: Eksen: Background Color: Arka Plan Rengi: + Guide Label: Kılavuz Etiketi: Show Center Mark Merkez İşaretini Göster Show Cross Hairs Artı Çizgilerini Göster Show Video Safe Areas Video Güvenli Alanlarını Göster @@ -4050,6 +4051,7 @@ axis Both Her İkisi @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis "vertical", "horizontal" veya derece cinsinden bir açı olmalıdır, `{v}` değil @msg background {other}: transparent, white, black or a colour such as "#ff8800" arka plan {other}: şeffaf, beyaz, siyah veya "#ff8800" gibi bir renk @msg bad color {v} kötü renk {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` null, bir katman renginin adı veya #rrggbb olur @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 0,1 ile 10 arasında bir sayı olmalıdır @msg the Color Picker is not open Renk Seçici açık değil @msg the screen color sampler is already open ekran rengi örnekleyici zaten açık diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 89c45d553b..5905e24190 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -283,6 +283,7 @@ font-technology Variable Варіативні Average… Усереднити… Axis: Вісь: Background Color: Колір тла: + Guide Label: Мітка напрямних: Show Center Mark Показати центральну позначку Show Cross Hairs Показати перехрестя Show Video Safe Areas Показати безпечні зони відео @@ -4312,6 +4313,7 @@ axis Both Обидві @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis має бути "vertical", "horizontal" або кутом у градусах, а не `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" фон {other}: transparent, white, black або колір, наприклад "#ff8800" @msg bad color {v} неприпустимий колір {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` має бути null, назвою кольору шару або #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio має бути числом від 0,1 до 10 @msg the Color Picker is not open палітра кольорів не відкрита @msg the Simplify slider is not open повзунок «Спростити» не відкрито diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b1c43edf35..fcd635b794 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -312,6 +312,7 @@ font-technology Variable Biến thiên Axis: Trục: Back Sau Background Color: Màu nền: + Guide Label: Nhãn đường căn: Show Center Mark Hiện dấu tâm Show Cross Hairs Hiện đường chữ thập Show Video Safe Areas Hiện vùng an toàn video @@ -4482,6 +4483,7 @@ theme Appearance Giao diện @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis phải là "vertical", "horizontal" hoặc góc theo độ, không phải `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black hoặc màu như "#ff8800" @msg bad color {v} màu không hợp lệ {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` là null, tên một màu lớp hoặc #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio phải là một số từ 0,1 đến 10 @msg the Color Picker is not open Bộ chọn màu chưa được mở @msg the Simplify slider is not open Thanh trượt Đơn giản hóa chưa được mở diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a587ad15fa..c6936442e8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -235,6 +235,7 @@ antiAlias Sharp 锐利 Average… 平均… Axis: 轴: Background Color: 背景颜色: + Guide Label: 参考线标签: Show Center Mark 显示中心标记 Show Cross Hairs 显示十字线 Show Video Safe Areas 显示视频安全区域 @@ -4396,6 +4397,7 @@ imageTrace Outline 轮廓 @msg {label}… {label}… @msg no blend options 没有混合选项 @msg bad color {v} 颜色 {v} 无效 +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` 应为 null、图层颜色名称或 #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 必须是 0.1 到 10 之间的数字 @msg the Color Picker is not open 拾色器未打开 @msg the Simplify slider is not open 简化滑块未打开 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e727056656..91b3a6f50b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -248,6 +248,7 @@ font-technology Variable 可變 Average… 平均… Axis: 軸: Background Color: 背景顏色: + Guide Label: 參考線標籤: Show Center Mark 顯示中心標記 Show Cross Hairs 顯示十字線 Show Video Safe Areas 顯示視訊安全區域 @@ -2224,6 +2225,7 @@ file-filter Templates 範本 @msg {label}… {label}… @msg no blend options 沒有漸變選項 @msg bad color {v} 顏色 {v} 無效 +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` 應為 null、圖層顏色名稱或 #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 必須是 0.1 到 10 之間的數字 @msg the Color Picker is not open 「顏色選擇器」未開啟 @msg the Simplify slider is not open 「簡化」滑桿未開啟 diff --git a/docs/mcp.md b/docs/mcp.md index 8363b44b75..ce4969fdf9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4786,7 +4786,7 @@ value: true}`; the Control bar's and Properties' Scale Artwork with Artboard che Artboard) makes its handle drags proportional and passes `scaleArt`, as do Properties' and the Transform panel's artboard size fields while the tool is in use. -`artboard.setProps {artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several +`artboard.setProps {artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several artboards in one undo step, each with its own fields; the other params apply to all of them. The art that moves or scales with each artboard is the art inside it before any of them changes, and an object inside several of them goes with the first one listed that moves or scales its art. An empty list and a list that names an artboard twice are @@ -4920,6 +4920,20 @@ is the width of one video pixel over its height, which `view.videoRulers` counts the native format keep both (written only when on or not 1), and `inspect_document` adds `showVideoSafeAreas: true` and `videoRulerPixelAspectRatio` to an artboard that has them. +Artboard Options' Guide Label: `artboard.setProps {index, guideLabel?: name | "#rrggbb" | null}` (or each entry of +`artboards`) gives the artboard a guide label, and `artboard.new` takes one too. The canvas draws the artboard's own +guides (`guide.add {artboard}`) in the label's color instead of the guide color preference, in the preference's style; +canvas guides, guides of an artboard without a label and guides whose artboard is gone keep the preference's color, and +selected guides are still drawn in the selection color. The value is a layer color's name, spelled exactly as Layer +Options lists it (`"Light Blue"`, `"Red"`, …), or `#rrggbb`; null clears it, and new artboards and older files have none. +The label is VectorCraft's own (no public documentation describes one): it is screen-only, so exports and print leave +it out, the paper and the artboard's background color stay as they are, and a locked artboard's label can change. +Anything else (a preset's index, another letter case, `#rrggbbaa`) is refused with "`guideLabel` is null, a layer +color's name or #rrggbb", and a list with a bad value anywhere changes nothing. Duplicates and copies keep it, the +native format writes it only when set (a preset index past the layer colors opens as none), and `inspect_document` adds +`guideLabel` (the name or `#rrggbb`) to an artboard that has one. `artboard.setProps` adds no undo step when nothing it +is given differs from the artboard. + Artboard Options' Global checkboxes are application preferences, not artboard properties: `fadeRegionOutsideArtboard` (Fade Region Outside Artboard) and `artboardUpdateWhileDragging` (Update While Dragging), both on by default (`prefs.set {values: {fadeRegionOutsideArtboard: false}}`; also Edit › Preferences › General › Artboard Options). With diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c15e19cda6..1710909377 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -651,6 +651,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Rulers (#1212):** drag the intersection to preview and set a document zero point, or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html). - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). +- **Artboard guide labels (#6414, in part):** Artboard Options' Guide Label gives an artboard a color label (`artboard.setProps`/`artboard.new` `guideLabel`: a layer color's name, `#rrggbb` or null), and the canvas draws that artboard's own guides in it; canvas guides, guides of an unlabeled artboard and guides whose artboard is gone keep the guide color preference, and selected guides keep the selection color. The [help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) describes guides restricted to an artboard, not a label, so the label, its palette and the color precedence are VectorCraft's own. It is screen-only (exports and print leave it out), written to the native format only when set, kept by duplicates and copies, and changeable on a locked artboard; `artboard.setProps` adds no undo step when nothing changes. This VectorCraft addition does not raise a score. Regression tests: `tests/panelcmds.rs` (`artboard_guide_labels_are_set_and_cleared_in_one_undo_step`, `artboard_guide_labels_round_trip_through_the_native_format`), `doc` `tests.rs` (`guide_label_text_names_a_layer_color_or_rgb`, `artboard_guide_label_defaults_and_skips_in_json`), `canvas::tests` (`artboard_guide_label_colors_only_its_own_guides`), `dialogs/tests.rs` (`artboard_options_shows_sets_and_clears_the_guide_label`). - **Fade Region Outside Artboard:** Artboard Options' Global checkboxes Fade Region Outside Artboard and Update While Dragging ([user guide, Artboard options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) are application preferences (`fadeRegionOutsideArtboard`, `artboardUpdateWhileDragging`), both on by default. While the Artboard tool is active the canvas draws everything outside the artboards, the pasteboard and the art on it, with each color channel at 60% of its value (VectorCraft's own amount), or only outside the box around all the artboards when crossing artboards would leave more than 4,096 rectangles in view; with Update While Dragging off it draws as usual during an artboard move or resize. Presentation Mode, exports and print do not change. Regression tests: `canvas::tests` (`the_artboard_tool_fades_the_pasteboard`, `presentation_mode_draws_no_fade`, `the_fade_darkens_art_on_the_pasteboard_and_not_on_the_artboard`, `outside_rects_cover_the_bounds_minus_the_boards`, `outside_rects_of_a_row_of_boards_stay_few`, `the_fade_of_crossing_boards_stays_bounded`, `update_while_dragging_keeps_or_drops_the_fade_during_an_artboard_drag`, `the_pasteboard_fade_leaves_exports_unchanged`), `dialogs/tests.rs` (`artboard_options_global_checkboxes_set_the_preferences`, `artboard_options_error_leaves_the_global_preferences_unchanged`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. From 8002598d64a31b1fbcbc0bb46b7fbcd11a1e6859 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:42:29 -0800 Subject: [PATCH 13/15] Native files: open reads the PDF preference in the same pass as the document Opening a native file read its JSON twice: once for the document and once more for the saved pdfCompatible preference. The format crate now takes the preference from craft-vectorcraft-format's Contents::read_with_pdf_preference (craft-libs#562), so a file is read in one pass. That method refuses a pdfCompatible that is not a boolean, which main opens by skipping the value and falling back to whether the file carries a PDF. Such a file, or one with any other data error, is read again with Contents::read and scanned for the preference as before, so the files that open today still open with the same result. The craft-vectorcraft-format pin moves to 1b34eba41e, the craft-libs revision craft-update already uses. --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/format/src/lib.rs | 60 +++++++++++++++++++++++++++++++++++----- 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b77485ae02..c3a087e845 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1096,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "flate2", "serde", diff --git a/Cargo.toml b/Cargo.toml index 9b4b99c92d..2d53acdc39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637 # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } # internal diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 5d7aabd077..1da653311a 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -510,20 +510,32 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result // at `MAX_READ_ANCHORS` anchors together, the document at `MAX_READ_NODES` objects, and the // fields read before an object's type at `MAX_BUFFERED_VALUES` values. The preview and the // PDF are skipped without being kept. - let read = || { - vectorcraft_doc::node::with_node_budget(max_nodes, || { - vectorcraft_doc::node::with_buffered_value_budget(max_values, || Contents::::read(file.json())) + fn within_budgets(max_nodes: usize, max_values: usize, read: impl FnOnce() -> T) -> T { + vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, || { + vectorcraft_doc::node::with_node_budget(max_nodes, || vectorcraft_doc::node::with_buffered_value_budget(max_values, read)) }) - }; - let mut f = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| match e { + } + let read_error = |e| match e { ReadError::Json(e) => { let why = if e.to_string().contains("recursion limit") { format!("its objects are nested too deep ({e})") } else { e.to_string() }; FormatError::NotVectorcraft(why) } ReadError::Envelope(e) => e.into(), e => FormatError::NotVectorcraft(e.to_string()), - })?; - let pdf_compatible = pdf_member(file.json()).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?; + }; + // The document and the saved PDF preference come from one pass over the JSON. + let (mut f, pdf_compatible) = match within_budgets(max_nodes, max_values, || Contents::::read_with_pdf_preference(file.json())) { + Ok(read) => read, + // That pass refuses a `pdfCompatible` that is not a boolean, and any other data error. + // The file is read again without the preference, and only then is its JSON scanned for + // the preference a second time, so such a file opens as before. + Err(ReadError::Json(e)) if e.is_data() => { + let f = within_budgets(max_nodes, max_values, || Contents::::read(file.json())).map_err(read_error)?; + let pdf_compatible = pdf_member(file.json()).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?; + (f, pdf_compatible) + } + Err(e) => return Err(read_error(e)), + }; let info = FileInfo { version: f.version, legacy: f.format == LEGACY_EXTENSION, pdf_compatible }; // A version 1 document saved before VectorCraft 0.21.0, or for an app before it (an older file // version): its Twist angles turned the other way. The app that wrote it is read from the JSON @@ -615,9 +627,17 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result Ok(NativeFile { doc, depth_notes, info, profiles }) } +#[cfg(test)] +thread_local! { + /// Tests: how many times a file's JSON was scanned again for its PDF preference on this thread. + static PDF_MEMBER_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The saved PDF preference, falling back to the presence of its payload without retaining or /// decoding it. The array form has neither member. Repeated members use their last value. fn pdf_member(json: &[u8]) -> Result { + #[cfg(test)] + PDF_MEMBER_SCANS.with(|n| n.set(n.get() + 1)); struct PdfMember; impl<'de> Visitor<'de> for PdfMember { type Value = bool; @@ -801,6 +821,32 @@ mod tests { } } + #[test] + fn only_a_preference_that_is_not_a_boolean_scans_the_json_again() { + let scans_for = |bytes: &[u8]| { + PDF_MEMBER_SCANS.with(|n| n.set(0)); + let compatible = load_info(bytes).unwrap().1.pdf_compatible; + (compatible, PDF_MEMBER_SCANS.with(|n| n.get())) + }; + let d = Document::new(10.0, 10.0); + assert_eq!(scans_for(&save(&d, false)), (false, 0)); + assert_eq!(scans_for(&save(&d, true)), (false, 0)); + for compatible in [false, true] { + let bytes = save_with(&d, &SaveOptions { pdf_compatible: Some(compatible), ..SaveOptions::default() }).unwrap(); + assert_eq!(scans_for(&bytes), (compatible, 0)); + } + let with_pdf = save_with(&d, &SaveOptions { pdf: Some(vec![7; 1024]), ..SaveOptions::default() }).unwrap(); + assert_eq!(scans_for(&with_pdf), (true, 0)); + let mut value: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + for odd in [serde_json::json!("yes"), serde_json::json!(1), serde_json::json!([true])] { + value["pdfCompatible"] = odd.clone(); + assert_eq!(scans_for(&serde_json::to_vec(&value).unwrap()), (false, 1), "{odd}"); + } + // A document that can't be read still fails, after the second read. + value["document"] = serde_json::json!("not a document"); + assert!(load_info(&serde_json::to_vec(&value).unwrap()).is_err()); + } + #[test] fn file_info_keeps_the_pdf_preference_without_artboards() { let mut d = Document::new(10.0, 10.0); From 2faadd28f4b06f4b2a10a92c6fceb3c2a9893fab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 20:09:28 -0800 Subject: [PATCH 14/15] Symbols: Break Link keeps a hidden or locked instance's art hidden or locked Break Link to Symbol on a selected group, and Delete Symbol with its instances expanded, turned a hidden or locked instance into visible, unlocked art. The art now keeps the instance's hidden and locked state, as Object > Expand does, and Break Link leaves hidden or locked art out of the selection. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 13 ++++--- crates/engine/src/tests/brushsym.rs | 47 +++++++++++++++++++++++ docs/mcp.md | 3 +- 4 files changed, 58 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 13b6ab8814..85c1412f0c 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -208,7 +208,7 @@ pub fn specs() -> Vec { "Break Link to Symbol", [], None, - "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask → {ids}", + "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask; a hidden or locked instance's art stays hidden or locked and is not selected → {ids}", has_selection, symbol_break_link ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 60353921e4..ee4487ba72 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -390,9 +390,9 @@ fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 { most.saturating_add(1).saturating_add(mask) } -/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the -/// art's ids. Fails before any edit when the instances together would make more than -/// [`MAX_EXPAND_NODES`] objects. +/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). A hidden or +/// locked instance's art stays hidden or locked. Returns the art's ids. Fails before any edit when +/// the instances together would make more than [`MAX_EXPAND_NODES`] objects. fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result> { let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, own))); if total > MAX_EXPAND_NODES as u64 { @@ -401,8 +401,10 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result Result { } let out = s.edit("Break Link to Symbol", |d, sel| { let out = break_links(d, &ids, true)?; - sel.set(out.iter().copied()); + // Hidden or locked art is left out of the selection. + sel.set(out.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.visible && !n.locked))); Ok(out) })?; Ok(json!({ "ids": ids_json(&out) })) diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 638b7a1f4b..34f2cc4b0b 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1321,6 +1321,53 @@ fn break_link_counts_the_instances_mask_art() { assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "it stays an instance"); } +/// A hidden, a locked and a plain instance of one symbol in a group, the group selected. +fn group_with_hidden_and_locked_instances(s: &mut Session) -> (NodeId, String) { + let (shown, name, _) = make_symbol(s); + let hidden = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap()); + let locked = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 100})).unwrap()["id"].as_u64().unwrap()); + select(s, &[shown, hidden, locked]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(hidden).unwrap().visible = false; + doc.node_mut(locked).unwrap().locked = true; + select(s, &[group]); + (group, name) +} + +/// The visibility and lock state of the children of `group`, in paint order. +fn shown_and_locked(s: &Session, group: NodeId) -> Vec<(bool, bool)> { + let g = node(s, group); + let NodeKind::Group { children, .. } = &g.kind else { panic!("a group: {}", g.kind_label()) }; + assert!(children.iter().all(|c| !matches!(c.kind, NodeKind::SymbolInstance { .. })), "every instance is expanded"); + children.iter().map(|c| (c.visible, c.locked)).collect() +} + +/// Break Link to Symbol on a selected group keeps a hidden instance's art hidden and a locked +/// instance's art locked, and selects only the art that can be selected. +#[test] +fn break_link_keeps_hidden_and_locked_instances_hidden_and_locked() { + let mut s = session(); + let (group, _) = group_with_hidden_and_locked_instances(&mut s); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 3, "{r}"); + assert_eq!(shown_and_locked(&s, group), vec![(true, false), (false, false), (true, true)]); + let d = &s.doc().unwrap().doc; + let selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(selected.len(), 1, "{selected:?}"); + assert!(selected.iter().all(|id| d.node(*id).is_some_and(|n| n.visible && !n.locked)), "{selected:?}"); +} + +/// Delete Symbol, expanding the instances, keeps a hidden instance's art hidden and a locked +/// instance's art locked. +#[test] +fn delete_symbol_keeps_hidden_and_locked_instances_hidden_and_locked() { + let mut s = session(); + let (group, name) = group_with_hidden_and_locked_instances(&mut s); + s.execute("symbol.delete", &json!({"name": name})).unwrap(); + assert_eq!(shown_and_locked(&s, group), vec![(true, false), (false, false), (true, true)]); +} + #[test] fn delete_duplicate_and_replace_symbols() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 14a5bfb6cf..749ddb2661 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2014,7 +2014,8 @@ already walks Image Trace. Short agent entry points: a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), - `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask), `symbol.replace`, + `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask; a hidden or locked instance's + art stays hidden or locked and is not selected), `symbol.replace`, `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the From aaf27e1ec6129cfc73ed364cd4900c33833a1ebc Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:57:54 +0100 Subject: [PATCH 15/15] Keep blank value row in single-column graph CSV round trip Found while testing crates/engine/src/cmd/graph/data.rs:51 (parse_csv); written by crates/doc/src/graph.rs:497 (GraphSpec::to_csv) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/graph.rs | 4 +++- crates/engine/src/cmd/graph/data.rs | 4 ++++ crates/engine/src/cmd/graph/tests.rs | 9 +++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 15f04ce156..72b066a06e 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -525,7 +525,9 @@ impl GraphSpec { out.push_str(&field(self.categories.get(i).map(String::as_str).unwrap_or_default(), true)); out.push(','); } - out.push_str(&r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::>().join(",")); + let line = r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::>().join(","); + // A lone blank value would be an empty line, which readers skip; a quoted empty field keeps the row. + out.push_str(if line.is_empty() && !labelled { "\"\"" } else { &line }); out.push('\n'); } out diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 3e21223497..f4eb3ef83c 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -50,6 +50,10 @@ pub(super) fn parse_csv(csv: &str) -> (Vec, Vec, Vec 1 { tabs } else { split_unquoted(l, ',') }; parts.into_iter().map(cell).collect() diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 650a4275ab..6cb36431e4 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -4210,3 +4210,12 @@ fn character_formats_are_kept_and_bigger_labels_space_out() { fn csv_leading_byte_order_mark_is_ignored() { assert_eq!(super::parse_csv("\u{feff}1,2\n3,4"), super::parse_csv("1,2\n3,4")); } + +#[test] +fn csv_round_trip_keeps_blank_row_in_single_column_graph() { + let mut g = GraphSpec::default(); + g.set_cells(vec![vec![Some(1.0)], vec![None], vec![Some(3.0)]]); + let (_, c, r) = super::parse_csv(&g.to_csv()); + assert!(c.is_empty()); + assert_eq!(r, g.cells()); +}