From 58292d605af4e21822b7f4d0bcf7aa94a2a2838e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:23:19 -0800 Subject: [PATCH 001/103] Scripts: app.showColorPicker asks for a color app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor and returns the color picked for OK. Cancel, and OK with the color unchanged, return a new object of the color the script gave. Anything else throws a TypeError. - In the app the run waits at the picker, which previews nothing on the selection. Stop and quitting end the run as at the other script dialogs and close the picker. - A run with nobody to ask takes {kind: "colorPicker", value: color | null} from answers. The report lists the picker with the color it opened on and the answer. - script.run's params text, docs/mcp.md and the Scripts line in docs/target-app-parity.md describe it. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 112 +++++++++++++++++---- crates/engine/src/script/dom.rs | 10 ++ crates/engine/src/script/dom/colors.rs | 14 ++- crates/engine/src/tests/script_dialogs.rs | 72 +++++++++++++ crates/ui-egui/src/dialogs/color_picker.rs | 99 +++++++++++++----- crates/ui-egui/src/dialogs/script_run.rs | 26 ++++- crates/ui-egui/src/script_runs.rs | 17 +++- crates/ui-egui/src/tests/script_dialogs.rs | 107 +++++++++++++++++++- docs/mcp.md | 18 +++- docs/target-app-parity.md | 1 + 11 files changed, 425 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..56bf96195f 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), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), 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; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), 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; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK in a CMYK document), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..afda864f6a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -5,12 +5,14 @@ //! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the //! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and //! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel. +//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and +//! returns the color picked for OK, or a new object of the color it was given for Cancel. //! //! In the app the run waits at the call for the person's answer, and spends no fuel while it -//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with -//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no -//! answer left, or with the next answer for another kind of dialog, ends the run. The report's -//! `dialogs` lists each dialog and its answer. +//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts +//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s +//! `answers`; a call with no answer left, or with the next answer for another kind of dialog, +//! ends the run. The report's `dialogs` lists each dialog and its answer. //! //! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`], //! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and @@ -21,6 +23,7 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_color::Color; use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; use super::{Host, console}; @@ -48,21 +51,33 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// `app.showColorPicker`. + ColorPicker, } impl DialogKind { - /// The function's name, which is also the `kind` of an answer and of a report's dialog. + /// The `kind` of an answer and of a report's dialog, which is also the function's name for + /// `alert`, `confirm` and `prompt`. pub fn id(self) -> &'static str { match self { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::ColorPicker => "colorPicker", + } + } + + /// The function's name, as its errors give it. + fn function(self) -> &'static str { + match self { + Self::ColorPicker => "showColorPicker", + k => k.id(), } } } /// A dialog a script opened, which waits for its answer. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub struct ScriptDialog { pub kind: DialogKind, pub message: String, @@ -74,10 +89,12 @@ pub struct ScriptDialog { pub no_as_default: bool, /// `prompt`: the text its field starts with. pub preset: String, + /// `showColorPicker`: the color the picker starts with. `None` for the other dialogs. + pub color: Option, } /// The answer to a [`ScriptDialog`]. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub enum DialogAnswer { /// OK, for `alert`. Ok, @@ -85,6 +102,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// OK with the color picked, or Cancel (`None`), for `showColorPicker`. + ColorPicker(Option), } impl DialogAnswer { @@ -93,29 +112,51 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::ColorPicker(_) => DialogKind::ColorPicker, } } - /// What the function returns. - fn data(&self) -> Data { + /// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it + /// started with. + fn data(&self, d: &ScriptDialog) -> Data { match self { Self::Ok => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, + Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data), } } - /// The answer as a report gives it: `"ok"`, a boolean, a string or `null`. + /// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands + /// take it, or `null`. fn json(&self) -> Value { match self { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json), } } } +/// `c` as the paint commands take it. +fn color_json(c: &Color) -> Value { + serde_json::to_value(c).unwrap_or(Value::Null) +} + +/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from +/// -128 to 128, as a script's `LabColor` takes them? +fn in_range(c: &Color) -> bool { + let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x)); + match *c { + Color::Rgb { r, g, b } => unit(&[r, g, b]), + Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]), + Color::Gray { k } => unit(&[k]), + Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)), + } +} + /// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together /// is a line break; every other control character, and with `lines` false every line break too, /// shows as its Unicode Control Picture, as the Script Console shows it. @@ -148,7 +189,8 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "colorPicker", value: color | +/// null}`, the color in any form the paint commands take. An empty object, which the parameter /// took before dialogs existed, is an empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { @@ -180,7 +222,12 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + (Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)), + (Some("colorPicker"), v) => match crate::cmd::color_value(v).filter(in_range) { + Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))), + None => Err("is a color picker's answer, whose `value` must be a color or null"), + }, + _ => Err("must have `kind` alert, confirm, prompt or colorPicker"), } } @@ -245,8 +292,9 @@ impl Dialogs { let mut waiting = self.waiting.borrow_mut(); let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; self.record(d, answer.json()); + let data = answer.data(d); *waiting = None; - if let Err(e) = realm.answer(answer.data()) { + if let Err(e) = realm.answer(data) { *self.failed.borrow_mut() = Some(e); } true @@ -263,12 +311,15 @@ impl Dialogs { self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); - r.insert("message".into(), json!(d.message)); - r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + if d.kind != DialogKind::ColorPicker { + r.insert("message".into(), json!(d.message)); + r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + } match d.kind { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)), }; r.insert("answer".into(), answer); let r = Value::Object(r); @@ -319,7 +370,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result host.charge_call(args.iter().map(super::data_size).sum())?; let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) }; let (title, error_icon, no_as_default, preset) = match kind { - DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()), + // `showColorPicker` opens through `show_color_picker`, not here. + DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()), DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()), DialogKind::Prompt => { let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; @@ -335,7 +387,29 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset }; + wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None }) +} + +/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, +/// and a new object of `color` for Cancel. +pub(super) fn show_color_picker(host: &Host, color: Color) -> Result { + let dialog = ScriptDialog { + kind: DialogKind::ColorPicker, + message: String::new(), + title: None, + error_icon: false, + no_as_default: false, + preset: String::new(), + color: Some(color), + }; + wait_or_answer(host, dialog) +} + +/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of +/// `answers`. +fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result { + let kind = dialog.kind; + let name = kind.function(); let d = &host.dialogs; if d.framed { if !d.can_wait.get() { @@ -350,11 +424,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result match next { Some(a) if a.kind() == kind => { d.record(&dialog, a.json()); - Ok(a.data()) + Ok(a.data(&dialog)) } Some(a) => { d.record(&dialog, json!("missing")); - Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id()))) + Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id()))) } None => { d.record(&dialog, json!("missing")); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8b2267a5d8..0a7eb82ef5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -41,6 +41,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; mod paths; +pub(super) use colors::of_color as color_data; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -691,6 +693,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`, +/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]). +fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer { + let color = colors::solid(arg(a, 1), "showColorPicker's color")?; + super::dialogs::show_color_picker(h, color) +} + /// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter /// or a `\`) letters in one case. fn path_key(p: &str) -> String { @@ -1883,6 +1892,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", get(l, app_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("showColorPicker", method(l, app_show_color_picker)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 34c1496054..da34e8cf31 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -66,7 +66,7 @@ fn shown(v: f32, scale: f64) -> f64 { } /// The color object for a solid color. -fn of_color(c: &Color) -> Data { +pub(in crate::script) fn of_color(c: &Color) -> Data { match *c { Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]), Color::Cmyk { c, m, y, k } => color_object( @@ -131,6 +131,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result std::result::Result { + let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor")); + match assigned(d, what) { + Ok(Some(c)) => Ok(c), + // A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error. + Ok(None) | Err(HostError::Error(_)) => Err(not_solid()), + Err(e) => Err(e), + } +} + /// `color` as `paint.setFill` and `paint.setStroke` take it. pub(super) fn param(color: &Color) -> Value { serde_json::to_value(color).unwrap_or(Value::Null) diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index baa8989208..aa373d09bb 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -177,6 +177,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { error_icon: false, no_as_default: true, preset: String::new(), + color: None, }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); @@ -319,3 +320,74 @@ fn a_dialog_in_a_callback_throws_in_the_app() { assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}"); assert_eq!(r["dialogCount"], 0); } + +/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns. +const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() { + let mut s = one_doc(); + let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());"); + let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})])) + .unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}"); + let dialogs = r["dialogs"].as_array().unwrap(); + assert_eq!(dialogs.len(), 2); + assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}"); + assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null"); + let cmyk = headless( + &mut s, + "var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);", + answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]), + ) + .unwrap(); + assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}"); +} + +#[test] +fn the_color_picker_ends_the_run_when_no_answer_is_left() { + let mut s = one_doc(); + let before = art(&s); + let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] { + let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}"); + let e = headless(&mut s, &source, given).unwrap_err().to_string(); + assert!(e.contains("showColorPicker") && e.contains(says), "{e}"); + assert_eq!(art(&s), before, "the run's edit goes back"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } + let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string(); + assert!(a.contains("is for colorPicker, not alert"), "{a}"); +} + +#[test] +fn the_color_picker_refuses_what_is_not_a_solid_color() { + let mut s = one_doc(); + let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\ + try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\ + try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());"; + let r = headless(&mut s, source, json!([])).unwrap(); + assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}"); + assert_eq!(r["dialogCount"], 0, "no picker opened"); + for bad in [json!("not a color"), json!([255, 0, 0]), json!({"model": "lab", "l": 120, "a": 0, "b": 0}), json!(true)] { + let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); + assert!(e.contains("color picker's answer"), "{bad}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_the_color_picker() { + let mut s = one_doc(); + framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);")); + let d = s.script_dialog().unwrap(); + assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); + assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))))); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given"); + assert!(s.script_answer(DialogAnswer::ColorPicker(None))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}"); +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index af1b318728..4060b26d40 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -27,6 +27,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::swatchlib; +use vectorcraft_engine::script::DialogAnswer; use super::preview::LivePreview; use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values}; @@ -45,6 +46,8 @@ pub(crate) enum Target { Artboard(usize), /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, + /// The answer to a running script's `app.showColorPicker`, which opened it on this colour. + Script(Color), } /// One open Color Picker: what the dialog itself does not know. @@ -152,28 +155,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; let dialogs = app.dialogs().ok_or("no window")?; let start = srgba(&color); - let mut dialog = ColorPickerDialog::new( - match (artboard, stroke) { - (Some(_), _) => "artboard", - (None, true) => "stroke", - (None, false) => "fill", - }, - tl!("Color Picker"), - start, - ) - .eyedropper(true) - .add_to_swatches(false) - .gamut(gamut(app)) - .working_rgb(WorkingRgb) - .swatch_view(swatch_view(app)); - if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) - && let Some(converter) = working_cmyk() - { - dialog = dialog.cmyk(&converter); - } - if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { - dialog = dialog.kept(model_values(&color)); - } + let key = match (artboard, stroke) { + (Some(_), _) => "artboard", + (None, true) => "stroke", + (None, false) => "fill", + }; + let mut dialog = picker(app, key, &color); // PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target. if let Some((i, _)) = artboard { dialog = dialog.instance(i); @@ -196,6 +183,58 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's +/// swatches and libraries, and in a CMYK document the working CMYK inks. +fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { + let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color)) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); + if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) + && let Some(converter) = working_cmyk() + { + dialog = dialog.cmyk(&converter); + } + if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { + dialog = dialog.kept(model_values(color)); + } + dialog +} + +/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`. It +/// previews nothing; its OK and Cancel answer the run ([`finish`]). +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color) { + let Some(dialogs) = app.dialogs() else { return }; + // The given colour's own values, so that OK can tell an untouched pick from another model's. + let dialog = picker(app, SCRIPT_KEY, &color).kept(model_values(&color)); + let id = dialogs.with(|h| h.open(dialog)); + app.color_dialogs.pickers.retain(|o| o.id != id); + app.color_dialogs.pickers.push(Open { id, target: Target::Script(color), start: srgba(&color), keep: false, preview: LivePreview::default() }); +} + +/// The key of the Color Picker a script opens. +pub(crate) const SCRIPT_KEY: &str = "script"; + +/// The id of the Color Picker a running script waits at, while it is open or its answer is not +/// yet given. +pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { + app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script(_))).map(|o| o.id) +} + +/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. +pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(id) = script_picker(app) else { return }; + app.color_dialogs.pickers.retain(|o| o.id != id); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| { + h.cancel_by_id(ctx, id); + let _ = h.take_by_id::(id); + }); + } +} + /// Once per frame (after the shell pass): opens a picker for each dialog's colour request, previews /// each open picker's colour on the art, hands it the screen picks, and settles the ones that /// closed. @@ -259,6 +298,15 @@ fn finish( dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } } + // OK on the colour it opened with, in the model it opened with, gives that colour back. + (Some(DialogResult::Ok(r)), Target::Script(given)) => { + let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); + let picked = if untouched { *given } else { in_document_model(app, color_of(&r.picked)) }; + app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); + } + (_, Target::Script(_)) => { + app.session.script_answer(DialogAnswer::ColorPicker(None)); + } (Some(DialogResult::Ok(r)), _) => { if let Err(e) = commit(app, open, preview, &r.picked) { app.status(e); @@ -273,7 +321,7 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })), Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Fill | Target::Answer { .. } | Target::Script(_) => ("paint.setFill", json!({ "color": color_json(&c) })), } } @@ -291,8 +339,9 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// preview. Nothing previews until the colour first changes, nor without a selection (the colour /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { - // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) { + // A picker over a command dialog only fills a row; the dialog previews it. A script's picker + // only answers the script. + if matches!(open.target, Target::Answer { .. } | Target::Script(_)) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..65b7c92e1a 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -29,6 +29,7 @@ use std::path::Path; +use craft::color_ui::ui::ColorPickerDialog; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; @@ -46,6 +47,7 @@ use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; +use super::color_picker; use crate::VectorcraftApp; use crate::file_asks::{self, Owner}; @@ -430,6 +432,22 @@ pub(crate) fn forget(app: &VectorcraftApp) { }); } +/// [`forget`] for the Color Picker a script's `app.showColorPicker` opened. +pub(crate) fn forget_color_picker(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if color_picker::script_picker(app).is_none() { + return; + } + let asking = with_host(app, |host, _| host.is_open::()).unwrap_or(false); + color_picker::forget_script(app, &ctx); + if asking { + with_host(app, |host, _| { + let _ = host.take::(); + host.open(close_question()); + }); + } +} + /// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file. pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { if p.get("path").is_some() || p.get("source").is_some() { @@ -514,8 +532,13 @@ pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) { /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { + let picker = color_picker::script_picker(app); with_host(app, |host, _| { - let own = host.get::().map(StackDialog::id).or_else(|| host.get::().map(StackDialog::id)); + let own = host + .get::() + .map(StackDialog::id) + .or_else(|| host.get::().map(StackDialog::id)) + .or_else(|| picker.filter(|&id| host.get_by_id::(id).is_some())); match own { Some(parent) if host.stack().is_top(parent) => { host.open_child(close_question(), parent); @@ -585,6 +608,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { crate::script_runs::failed(app, error); forget::(app); forget::(app); + forget_color_picker(app); app.sync_views(); } if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index b08a8f2e93..e4f6303fab 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,9 +1,13 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, `app.showColorPicker` or a `File` or `Folder` file dialog, waits +//! for the person's answer. + +use vectorcraft_engine::script::DialogKind; use crate::VectorcraftApp; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; /// Advances the running script by one slice, or asks what its growth needs asked. @@ -47,13 +51,22 @@ fn ask(app: &mut VectorcraftApp) -> bool { } script_run::forget::(app); if let Some(dialog) = app.session.script_dialog() { - if !script_run::busy(app) { + if dialog.kind == DialogKind::ColorPicker { + // A picker that closed this frame answers the run in its own pump. + if color_picker::script_picker(app).is_none() + && !script_run::busy(app) + && let Some(color) = dialog.color + { + color_picker::open_for_script(app, color); + } + } else if !script_run::busy(app) { script_run::open_notice(app, &dialog); } return true; } // A run asked to stop no longer waits at its dialog. script_run::forget::(app); + script_run::forget_color_picker(app); if app.session.script_waiting() { if !script_run::busy(app) { script_run::open_growth(app); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 94e1bb9311..3417c5580b 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -1,12 +1,14 @@ //! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons, //! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers -//! given by a run with nobody to ask. The helpers over the dialog host are shared with the other -//! script tests. +//! given by a run with nobody to ask; and the Color Picker of `app.showColorPicker`. The helpers +//! over the dialog host are shared with the other script tests. +use craft::color_ui::ui::{ColorPickerDialog, PickedColor}; use craft::ui::dialog::{DialogId, StackDialog, StandardPrompt}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, CLOSE_KIND, CloseQuestion, NOTICE_KIND, ScriptNotice}; use crate::{VectorcraftApp, menus, script_runs}; @@ -315,3 +317,104 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { assert_eq!(framed["dialogs"], headless["dialogs"]); assert_eq!(framed["log"], json!([true, "p", "done"])); } + +/// Is the Color Picker of the script's `app.showColorPicker` open? +fn picker_open(app: &VectorcraftApp) -> bool { + let id = color_picker::script_picker(app); + id.is_some_and(|id| script_run::with_host(app, |host, _| host.get_by_id::(id).is_some()).unwrap()) +} + +/// Polls the run until it ends, or until its Color Picker is open (true). +fn until_picker(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if picker_open(app) { + return true; + } + } + panic!("the script neither ended nor opened the Color Picker"); +} + +/// Answers the script's Color Picker with OK (or Cancel), then runs the frame's picker pump. +fn answer_picker(app: &mut VectorcraftApp, ok: bool) { + let id = color_picker::script_picker(app).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let done = script_run::with_host(app, |host, ctx| if ok { host.confirm_by_id(ctx, id) } else { host.cancel_by_id(ctx, id) }).unwrap(); + assert!(done); + color_picker::pump(app, &ctx); +} + +#[test] +fn the_color_picker_waits_and_answers_the_run() { + let mut app = app(); + let gray = "var g = new GrayColor(); g.gray = 40;"; + start( + &mut app, + &format!( + "{DRAW} var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join()); \ + {gray} var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join()); var r = app.showColorPicker(g); vc.log([r.typename, r.gray].join());" + ), + ); + assert!(until_picker(&mut app)); + assert!(!is_open::(&app), "the picker opens in place of a notice"); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + color_picker::pump(&mut app, &ctx); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app), "the next call opens the picker again"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app)); + answer_picker(&mut app, false); + assert!(!until_picker(&mut app)); + assert_eq!( + log(&app), + json!(["RGBColor,0,255,0", "GrayColor,40", "GrayColor,40"]), + "OK gives the color picked, untouched its own color, Cancel the color given" + ); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "OK paints nothing"); + let dialogs = app.session.script_report().unwrap()["dialogs"].clone(); + assert_eq!(dialogs[2]["answer"], Value::Null, "Cancel is listed as null"); +} + +#[test] +fn the_same_color_set_in_another_model_is_a_new_pick() { + let mut app = app(); + start(&mut app, "var g = new GrayColor(); g.gray = 40; var p = app.showColorPicker(g); vc.log(p.typename);"); + assert!(until_picker(&mut app)); + // The gray's own sRGB, set as a plain color, as a screen sample sets one. + let open = app.color_dialogs.pickers.iter().find(|o| Some(o.id) == color_picker::script_picker(&app)).map(|o| (o.id, o.start)).unwrap(); + script_run::with_host(&app, |host, _| host.get_mut_by_id::(open.0).map(|d| d.set_color(PickedColor::rgb(open.1)))).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor"]), "the same sRGB as a plain color is an RGB pick, not the gray the script gave"); +} + +#[test] +fn stopping_or_quitting_the_run_closes_its_color_picker() { + let source = format!("{DRAW} var c = new RGBColor(); app.showColorPicker(c); vc.log('after');"); + let mut app = app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert!(!picker_open(&app), "no picker is left for the stopped run"); + assert!(color_picker::script_picker(&app).is_none()); + assert_eq!(objects(&app), 0, "the run's edit goes back"); + assert_eq!(log(&app), json!([])); + let mut app = self::app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + script_run::ask_to_close(&mut app); + assert!(is_open::(&app), "quitting asks over the picker"); + cancel(&mut app, CLOSE_KIND); + assert!(picker_open(&app), "Cancel shows the picker again"); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + assert!(!app.session.script_running()); + assert!(!picker_open(&app), "no picker is left for the abandoned run"); + assert_eq!(objects(&app), 0); +} diff --git a/docs/mcp.md b/docs/mcp.md index da2ab72029..5321b74f87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2667,7 +2667,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + `app.selection`, `app.coordinateSystem`, `app.getIsFileOpen(path)` and `app.showColorPicker(color)`, described + with the dialogs below. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -3048,7 +3049,9 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and + run ended at, or `"missing"` for a dialog `answers` had no answer for. `app.showColorPicker` is listed as `{kind: + "colorPicker", color, answer}`, with the color it opened on and the color picked, `null` for Cancel or + `"missing"`, each color as `paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at its limit. ```json @@ -3096,6 +3099,17 @@ left, when the next answer is for another kind of dialog, or when the script end and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an empty object are the same. +`app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at +https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, +`CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in a CMYK +document an RGB pick is returned as CMYK. OK with the color unchanged and Cancel return a new object of the color the +script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting +end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: +"colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its +range, or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and +`ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. + ```sh vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff2ebf0bf4..864cff266f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1036,6 +1036,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, and Cancel a new object of the color given. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.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`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 88fe4e979629e7aa275f3334feeaa72744976113 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:52:31 -0800 Subject: [PATCH 002/103] Tests: list app.showColorPicker in the script host inventory --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 22f0b8b0b0..af193b5d56 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -84,7 +84,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + selection showColorPicker typename", ), ("DocumentPreset.", "prototype"), ( From e4d1dabf9e3c670a9b530ab0f7be706c287ab901 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:31:48 -0800 Subject: [PATCH 003/103] Scripts: path point reads scale with subpaths; the script color picker keeps its color - app.showColorPicker opens on the script's color even when an earlier picker left Only Web Colors on, and a changed RGB pick takes the model of the run's own active document, which may be one the script made. - Point reads and edits look a point up in a cached layout of where each subpath's points start, so a loop over a path with many subpaths no longer counts every subpath for each point. selectedPathPoints walks the selected anchors of a partial selection instead of every point. - PathPoint.selected writes the waiting point changes whenever any of them added or removed points of the path. - The path creators read the new path's id from the command's own result, so an id above 2^53 stays exact. - typename of a stale PathPoint or PathPoints throws as the other members do. - pageItems, pathItems and documents look up a key that reads as a number but is not an index, such as "-1", by name first. - artboardLayout keeps the columns the rows gave the current artboards when a new layout replaces the rows without its own columns. - Docs: pathItems.add() and the shape creators follow isolation; reading another path's points does not write the waiting changes; a gray within about 1e-14 % of white reads as 100; assigning documents throws in strict mode; when showColorPicker keeps the given color's model. --- crates/engine/src/cmd/newdoc.rs | 5 + crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 9 +- crates/engine/src/script/dom.rs | 37 ++++ crates/engine/src/script/dom/colors.rs | 4 +- crates/engine/src/script/dom/paths.rs | 230 +++++++++++++------- crates/engine/src/script/mod.rs | 3 + crates/engine/src/tests/script_dialogs.rs | 1 + crates/engine/src/tests/script_dom.rs | 16 ++ crates/engine/src/tests/script_dom_paths.rs | 91 ++++++++ crates/ui-egui/src/dialogs/color_picker.rs | 52 +++-- crates/ui-egui/src/script_runs.rs | 2 +- crates/ui-egui/src/tests/script_dialogs.rs | 61 ++++++ docs/mcp.md | 18 +- docs/target-app-parity.md | 2 +- 15 files changed, 423 insertions(+), 110 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index f672799325..743eaab2a7 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -372,6 +372,11 @@ impl DocSettings { /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); + // The columns that rows give the artboards as they are now, which a layout that replaces the + // rows without its own `columns` keeps. + if self.grid_rows().is_some() { + self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); + } if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; if self.layout != ArtboardLayout::GridByColumn { diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2ee3718b3a..7a7e81cf82 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), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), 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; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK in a CMYK document), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), 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; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index afda864f6a..27d22598d9 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -91,6 +91,9 @@ pub struct ScriptDialog { pub preset: String, /// `showColorPicker`: the color the picker starts with. `None` for the other dialogs. pub color: Option, + /// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app + /// gives an RGB pick back as CMYK. False for the other dialogs. + pub cmyk_document: bool, } /// The answer to a [`ScriptDialog`]. @@ -387,12 +390,15 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None }) + wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false }) } /// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, /// and a new object of `color` for Cancel. pub(super) fn show_color_picker(host: &Host, color: Color) -> Result { + // During a slice the session holds the run's working copy, whose active document may be one + // the script made; between slices the app sees the documents as they were before the run. + let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk); let dialog = ScriptDialog { kind: DialogKind::ColorPicker, message: String::new(), @@ -401,6 +407,7 @@ pub(super) fn show_color_picker(host: &Host, color: Color) -> Result)>>, + /// How many times the run has started point changes of a path, or added or removed points of + /// the path whose changes wait ([`paths::layout`]). + relayouts: Cell, + /// The waiting point changes add or remove points of their path. + relaid: Cell, + /// The last two point layouts the run worked out, the newest first ([`paths::layout`]). + layouts: RefCell)>>, /// How many times the points the run read of each path went stale, by document uid and path id /// ([`paths`]). point_cuts: RefCell>, @@ -946,6 +953,9 @@ fn front_docs(s: &Session) -> impl Iterator { /// `documents[i]`, and `documents["name"]` as `getByName` reads it. fn docs_at(h: &Host, a: &[Data]) -> Answer { + if let Some(r) = by_number_name(a, |a| docs_by_name(h, a)) { + return r; + } let s = h.session.borrow(); let at = match arg(a, 1) { Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)), @@ -1608,8 +1618,35 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } +/// The name a collection's indexer key reads as, when the key is a number that is not an array +/// index. The indexer passes a name that reads as a number, such as `"-1"` or `"1.5"`, as that +/// number, so a collection looks the name up first and gives `undefined` when nothing has it. +fn number_name(d: &Data) -> Option { + match d { + Data::Number(n) if !(n.fract() == 0.0 && (0.0..4_294_967_295.0).contains(n)) => Some(vectorcraft_js::number_to_string(*n)), + _ => None, + } +} + +/// Looks the indexer key of `a` up with `by_name` when it is a name that reads as a number +/// ([`number_name`]). → `None` for any other key. +fn by_number_name(a: &[Data], by_name: impl FnOnce(&[Data]) -> Answer) -> Option { + let name = number_name(arg(a, 1))?; + let mut named = a.to_vec(); + if let Some(key) = named.get_mut(1) { + *key = Data::String(name); + } + Some(match by_name(&named) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }) +} + /// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. fn items_at(h: &Host, a: &[Data]) -> Answer { + if let Some(r) = by_number_name(a, |a| items_by_name(h, a)) { + return r; + } let doc = items_doc(h, a)?; if let Data::String(_) = arg(a, 1) { return match items_by_name(h, a) { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index da34e8cf31..68a4052441 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -13,7 +13,9 @@ //! VectorCraft's own rules, which the help pages do not state: components left out count as 0; //! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` //! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page -//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not +//! says. A color read from an object gives that object the same color when it is assigned back, +//! except a gray within about 1e-14 % of white: one number cannot hold it, so it reads as 100 and +//! assigning it back makes the gray white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not //! assigned yet. use std::rc::Rc; diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 823ed46d41..e9e3285d3c 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -8,8 +8,9 @@ //! point's index, counted across the path's subpaths in order. Each read looks the path up again. //! Every change runs one command inside the run's one undo step, and a change that changes nothing //! runs no command. Changes to the points of one path wait in the run's [`super::State`] and are -//! written together with one `path.setAnchors` ([`flush`]) before any other member, command or -//! path's points are read or changed, and when the script ends. +//! written together with one `path.setAnchors` ([`flush`]) before any other member or command is +//! used or another path's points are changed, and when the script ends. Reading the points of +//! another path does not write them. //! //! VectorCraft's own rules, which the help pages do not state: //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside @@ -24,7 +25,8 @@ //! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes //! them all. //! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever -//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! the drawing mode, or where drawing puts a new path while an object is isolated (in an +//! isolated group, for example), painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. @@ -69,7 +71,7 @@ use vectorcraft_tools::params::gradient_params; use super::{ Answer, Coords, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, - point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, + point, point_get, point_method, point_property, property, text, this_doc, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -140,20 +142,72 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) } -/// How many points a path with the subpaths `subs` has. -fn point_count(subs: &[SubPath]) -> usize { - subs.iter().map(|sp| sp.anchors.len()).sum() +/// Where the points of each subpath of a path start among the path's points, and how many points +/// the path has. +pub(super) struct Layout { + starts: Vec, + total: usize, } -/// The subpath and the place in it of point `i`, among the subpaths `subs`. -fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { - for (s, sp) in subs.iter().enumerate() { - if i < sp.anchors.len() { - return Some((s, i)); +impl Layout { + fn of(subs: &[SubPath]) -> Self { + #[cfg(test)] + crate::script::LAYOUTS_BUILT.with(|n| n.set(n.get() + 1)); + let mut starts = Vec::with_capacity(subs.len()); + let mut total = 0usize; + for sp in subs { + starts.push(total); + total = total.saturating_add(sp.anchors.len()); } - i -= sp.anchors.len(); + Self { starts, total } } - None + + /// The subpath and the place in it of point `i`. + fn locate(&self, i: usize) -> Option<(usize, usize)> { + if i >= self.total { + return None; + } + // The last subpath that starts at or before `i`; a subpath with no points starts where the + // next one does, so the one found holds `i`. + let s = self.starts.partition_point(|start| *start <= i).checked_sub(1)?; + Some((s, i - self.starts.get(s)?)) + } +} + +/// What a [`Layout`] the run keeps was worked out from: the waiting point changes of a path, as +/// they were after [`super::State`]'s count of relayouts reached the number given, or the path as +/// a document held it. +pub(super) enum LayoutOf { + Waiting(Item, u64), + Stored(Item, Arc), +} + +impl LayoutOf { + fn same(&self, other: &Self) -> bool { + match (self, other) { + (Self::Waiting(a, n), Self::Waiting(b, m)) => same_path(*a, *b) && n == m, + (Self::Stored(a, d), Self::Stored(b, e)) => same_path(*a, *b) && Arc::ptr_eq(d, e), + _ => false, + } + } +} + +/// The layout of the points of the path of `item`, its waiting point changes included. The last +/// two layouts are kept, so that reading or changing point after point does not count the points +/// of every subpath each time. +fn layout(h: &super::Host, item: Item) -> std::result::Result, HostError> { + let of = match &*h.dom.pending.borrow() { + Some((waiting, _)) if same_path(*waiting, item) => LayoutOf::Waiting(item, h.dom.relayouts.get()), + _ => LayoutOf::Stored(item, with_doc(h, item.doc, |_, st| st.doc.clone())), + }; + if let Some((_, l)) = h.dom.layouts.borrow().iter().find(|(kept, _)| kept.same(&of)) { + return Ok(l.clone()); + } + let l = Rc::new(read_points(h, item, Layout::of)?); + let mut kept = h.dom.layouts.borrow_mut(); + kept.insert(0, (of, l.clone())); + kept.truncate(2); + Ok(l) } fn anchor_json(a: &Anchor) -> Value { @@ -174,15 +228,20 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) read_path(h, item, |_, _, pd| f(&pd.subpaths)) } -/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with -/// the path's other point changes until [`flush`] writes them. The first change of a path writes -/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or -/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object -/// that is, is written at once, so that its points read as the grid snaps them. -fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { +/// Changes the subpaths of the path of `item` with `f`, which adds or removes points when +/// `relayout`. The change waits in [`super::State`] with the path's other point changes until +/// [`flush`] writes them. The first change of a path writes the waiting changes of another path +/// first, and throws `Cannot edit` when the path is hidden or locked, unless it changes nothing. A +/// path that is aligned to the pixel grid, or is in an object that is, is written at once, so that +/// its points read as the grid snaps them. +fn edit_points(h: &super::Host, item: Item, relayout: bool, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { + if relayout { + h.dom.relayouts.set(h.dom.relayouts.get().wrapping_add(1)); + h.dom.relaid.set(true); + } return Ok(f(subs)); } flush(h)?; @@ -198,6 +257,8 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) return Err(cannot_edit(item.id)); } *h.dom.pending.borrow_mut() = Some((item, subs)); + h.dom.relayouts.set(h.dom.relayouts.get().wrapping_add(1)); + h.dom.relaid.set(relayout); if aligned { flush(h)?; } @@ -207,7 +268,7 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) /// Gives the path of `item` the subpaths `subs` ([`edit_points`]). fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { - edit_points(h, item, |s| *s = subs) + edit_points(h, item, true, |s| *s = subs) } /// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless @@ -237,7 +298,8 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) } /// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active -/// layer, then puts the drawing mode back. +/// layer, or where drawing puts a new path while an object is isolated, then puts the drawing mode +/// back. fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); let r = f(); @@ -305,6 +367,11 @@ fn items_length(h: &super::Host, a: &[Data]) -> Answer { Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) } +fn items_typename(h: &super::Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("PathItems")) +} + fn items_parent(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) @@ -312,6 +379,9 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { /// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { + if let Some(r) = super::by_number_name(a, |a| items_by_name(h, a)) { + return r; + } let doc = items_doc(h, a)?; if let Data::String(_) = arg(a, 1) { return match items_by_name(h, a) { @@ -372,20 +442,19 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object. -fn made_id(r: &Data) -> std::result::Result { - let id = match r { - Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), - _ => None, - }; - id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// Runs the command `id` that makes an object, with `params`. → the new object's id, read from the +/// command's own result, so that an id above 2^53 stays exact. +fn make_object(h: &super::Host, id: &str, params: &Value) -> std::result::Result { + let (_, value) = super::command_value(h, id, params)?; + value.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } -/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, -/// and reverses the new path's direction when `reversed`. → the new path. +/// Runs the command `id` that makes a path in `doc` on top of the active layer (or where drawing +/// puts a new path while an object is isolated), the selection kept, and reverses the new path's +/// direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { - let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; + let id = drawing_normally(h, || make_object(h, id, params))?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -534,7 +603,8 @@ fn items_star(h: &super::Host, a: &[Data]) -> Answer { make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) } -/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with +/// `pathItems.add()`: a path with no points on top of the active layer (or where drawing puts a new +/// path while an object is isolated), from `path.create` with /// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open /// path is set back to none in the same step. fn items_add(h: &super::Host, a: &[Data]) -> Answer { @@ -544,7 +614,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; + let id = drawing_normally(h, || make_object(h, "path.create", &json!({"d": ""})))?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -571,7 +641,7 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points(h, item, false, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; Ok(Data::Undefined) } @@ -1139,7 +1209,12 @@ fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result Answer { let item = points_path(h, a)?; - read_points(h, item, |subs| num(float(point_count(subs) as u64))) + Ok(num(float(layout(h, item)?.total as u64))) +} + +fn points_typename(h: &super::Host, a: &[Data]) -> Answer { + points_path(h, a)?; + Ok(text("PathPoints")) } fn points_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -1263,7 +1338,7 @@ fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - let n = read_points(h, item, point_count)?; + let n = layout(h, item)?.total; Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) } @@ -1281,7 +1356,8 @@ fn points_index(h: &super::Host, a: &[Data]) -> Answer { fn points_add(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0]))); - let (n, last) = read_points(h, item, |subs| (point_count(subs), subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p)))?; + let n = layout(h, item)?.total; + let last = read_points(h, item, |subs| subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p))?; if n >= MAX_POINTS { return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); } @@ -1289,7 +1365,7 @@ fn points_add(h: &super::Host, a: &[Data]) -> Answer { Some(p) => p, None => origin?, }; - edit_points(h, item, |subs| match subs.last_mut() { + edit_points(h, item, true, |subs| match subs.last_mut() { Some(sp) => sp.anchors.push(Anchor::corner(p)), None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)), })?; @@ -1315,8 +1391,7 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It return Err(HostError::Error(STALE_POINT.into())); } let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - let n = read_points(h, item, point_count)?; - if i >= n { + if i >= layout(h, item)?.total { return Err(HostError::Error(STALE_POINT.into())); } Ok((item, i)) @@ -1327,8 +1402,9 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, let (item, i) = this_point(h, a)?; let c = h.dom.coords.get(); let fr = with_doc(h, item.doc, |_, st| frame(st))?; + let at = layout(h, item)?.locate(i); read_points(h, item, |subs| { - let anchor = locate(subs, i).and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); + let anchor = at.and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) })? } @@ -1337,8 +1413,9 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { let (item, i) = this_point(h, a)?; - edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) + let at = layout(h, item)?.locate(i); + edit_points(h, item, false, |subs| { + if let Some((s, j)) = at && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { f(an); @@ -1395,6 +1472,12 @@ fn pt_set_type(h: &super::Host, a: &[Data]) -> Answer { edit_point(h, a, |an| an.kind = kind) } +/// `typename`, which throws as the other members do for a point that is stale. +fn pt_typename(h: &super::Host, a: &[Data]) -> Answer { + this_point(h, a)?; + Ok(text("PathPoint")) +} + fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { let (item, _) = this_point(h, a)?; Ok(path_ref(h, item)) @@ -1406,11 +1489,11 @@ fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) - d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer()))) } -/// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every +/// The point at subpath and place `at` is a selected anchor point of the path `id` in `sel`: every /// point of a path selected as a whole is (a path is when a group or compound path that holds it /// is selected, `held`), and of a path with direct-selected anchors only those anchors are. The /// endpoints of selected segments are not. -fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[SubPath], i: usize) -> bool { +fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, at: Option<(usize, usize)>) -> bool { if held { return true; } @@ -1419,31 +1502,23 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[ } match sel.partial(id) { None => true, - Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + Some(picked) => at.is_some_and(|r| picked.contains(&r)), } } -/// Whether the subpaths `a` and `b` have the same number of points in the same subpaths, so that a -/// point index names the same anchor in both. -fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { - a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.anchors.len() == y.anchors.len()) -} - /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point /// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in -/// [`super::State`] are written first only when they add or remove points of this path, since -/// the selection names anchors by their place in the document's path. +/// [`super::State`] are written first when any of them added or removed points of this path, since +/// the selection names anchors by their place in the document's path; changes that only move +/// points or handles stay waiting. fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - let moved = match &*h.dom.pending.borrow() { - Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, - _ => false, - }; + let moved = h.dom.relaid.get() && h.dom.pending.borrow().as_ref().is_some_and(|(waiting, _)| same_path(*waiting, item)); if moved { super::flush(h)?; } - let on = - read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), &pd.subpaths, i))?; + let at = layout(h, item)?.locate(i); + let on = read_path(h, item, |st, _, _| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), at))?; Ok(Data::String(if on { "PathPointSelection.ANCHORPOINT" } else { "PathPointSelection.NOSELECTION" }.into())) } @@ -1468,13 +1543,13 @@ fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { _ => return Err(HostError::Type("selected must be a PathPointSelection value".into())), }; let (item, i) = this_point(h, a)?; - let (now, at, selectable, held, guide) = with_doc(h, item.doc, |_, st| { + let at = layout(h, item)?.locate(i); + let (now, selectable, held, guide) = with_doc(h, item.doc, |_, st| { let node = st.doc.node(item.id); - let subs = node.and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]); let guide = node.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })); let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id); let held = held_selected(&st.doc, &st.selection, item.id); - (anchor_selected(&st.selection, item.id, held, subs, i), locate(subs, i), selectable, held, guide) + (anchor_selected(&st.selection, item.id, held, at), selectable, held, guide) }); if now == on { return Ok(Data::Undefined); @@ -1501,20 +1576,22 @@ fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { /// order of `pathPoints`. fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; + let lay = layout(h, item)?; let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; let held = held_selected(&st.doc, sel, item.id); if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { return Vec::new(); } - let mut out = Vec::new(); - let mut first = 0; - for (s, sp) in pd.subpaths.iter().enumerate() { - let n = sp.anchors.len(); - out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); - first += n; + match sel.partial(item.id).filter(|_| !held) { + // Direct-selected anchors, in subpath and anchor order, which is the order of `pathPoints`. + Some(anchors) => anchors + .iter() + .filter(|(s, j)| pd.subpaths.get(*s).is_some_and(|sp| *j < sp.anchors.len())) + .filter_map(|(s, j)| lay.starts.get(*s).map(|first| first + j)) + .collect(), + None => (0..lay.total).collect(), } - out })?; h.charge_call(picked.len() as u64)?; let [high, low] = id_parts(item.id); @@ -1526,8 +1603,9 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) + let at = layout(h, item)?.locate(i); + edit_points(h, item, true, |subs| { + if let Some((s, j)) = at && let Some(sp) = subs.get_mut(s) { sp.anchors.remove(j); @@ -1581,7 +1659,7 @@ pub(super) fn classes(l: &Link) -> Vec { "PathItems", None, named(vec![ - ("typename", typename_of("PathItems")), + ("typename", get(l, items_typename)), ("length", get(l, items_length)), ("parent", get(l, items_parent)), ("index", method(l, items_index)), @@ -1600,7 +1678,7 @@ pub(super) fn classes(l: &Link) -> Vec { "PathPoints", None, named(vec![ - ("typename", typename_of("PathPoints")), + ("typename", point_get(l, points_typename)), ("length", point_get(l, points_length)), ("parent", point_get(l, points_parent)), ("index", point_method(l, points_index)), @@ -1613,7 +1691,7 @@ pub(super) fn classes(l: &Link) -> Vec { "PathPoint", None, named(vec![ - ("typename", typename_of("PathPoint")), + ("typename", point_get(l, pt_typename)), ("parent", point_get(l, pt_parent)), ("anchor", point_property(l, pt_anchor, pt_set_anchor)), ("leftDirection", point_property(l, pt_left, pt_set_left)), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 3a39c71ba4..73806a7e7f 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2744,6 +2744,9 @@ thread_local! { pub(crate) static TEST_GROWTH_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; + /// Tests: how many times the object model worked out where the points of each subpath of a + /// path start. + pub(crate) static LAYOUTS_BUILT: Cell = const { Cell::new(0) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index aa373d09bb..af1d07f06a 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -178,6 +178,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { no_as_default: true, preset: String::new(), color: None, + cmyk_document: false, }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index b940b93325..46d530e122 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -707,6 +707,22 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); } +/// A layout that replaces the rows keeps the columns the rows gave the artboards there are now, +/// whether or not the change of artboards came with a layout of its own. +#[test] +fn replacing_rows_keeps_the_columns_of_the_artboards_there_are_now() { + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + for change in [json!({"artboards": 9}), json!({"artboards": 9, "artboardLayout": {"spacing": 20}})] { + let more = settings.clone().with_params(&change, "file.new").unwrap(); + for layout in [json!("gridByRow"), json!({"layout": "gridByRow"})] { + let by_row = more.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); + assert_eq!(by_row.grid_columns(), 3, "{change} then {layout}"); + } + } +} + #[test] fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index edd359282e..0945f15374 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::Point; use vectorcraft_geom::path::AnchorKind; use crate::*; @@ -262,6 +263,9 @@ fn path_point_setters_edit_one_anchor() { for i in [0, 2, 3] { assert_eq!(anchors[i], anchors_before[i], "point {i} did not change"); } + // The 300 pt tall document's y runs down, so script y 285 is document y 15. + let edited = &anchors[1]; + assert_eq!((edited.p, edited.h_in, edited.h_out), (Point::new(45.0, 15.0), Point::new(35.0, 15.0), Point::new(55.0, 15.0))); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite")); @@ -1207,3 +1211,90 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } + +/// Reading and moving each point of a path with many subpaths works out where the subpaths' points +/// start a few times for the whole loop, not once or more for each point. +#[test] +fn reading_and_moving_points_counts_the_subpaths_a_few_times() { + let (mut s, _, _) = doc(); + let d: String = (0..500).map(|i| format!("M{x} 10 L{x} 20 ", x = i % 300)).collect(); + let id = NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + crate::script::LAYOUTS_BUILT.with(|n| n.set(0)); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints;\ + for (var i = 0; i < pp.length; i++) { var q = pp[i]; q.anchor = [q.anchor[0], q.anchor[1] + 1]; }\ + vc.log(pp.length);", + ); + assert_eq!(out, vec![json!(1000)]); + let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get); + assert!(built < 10, "{built} layouts for 1000 points"); + let n = node(&s, id); + assert!(n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).all(|an| an.p.y == 9.0 || an.p.y == 19.0), "every point moved up"); +} + +/// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the +/// order of `pathPoints`, whatever order they were selected in. +#[test] +fn selected_path_points_follow_the_order_of_path_points_across_subpaths() { + let (mut s, _, _) = doc(); + let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L10 0 L10 10 M20 0 L30 0"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[1, 1], [0, 2], [0, 0]], "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var sp = app.activeDocument.pathItems[0].selectedPathPoints, x = [];\ + for (var i = 0; i < sp.length; i++) x.push(sp[i].anchor[0]); vc.log(x);", + ); + assert_eq!(out, vec![json!([0, 10, 30])]); +} + +/// `pageItems` and `pathItems` find a name that reads as a number but is not an index, and such a +/// key that nothing has reads as `undefined`. +#[test] +fn collections_find_names_that_read_as_numbers() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "1.5"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.pageItems, p = d.pathItems;\ + vc.log([g['-1'].name, g[1.5].name, '-1' in g, p['-1'].name, p[-1].name, '1.5' in p]);\ + vc.log([g[-2] === undefined, '-2' in p, p[2.5] === undefined, p[0].name, p[1].name]);", + ); + assert_eq!(out, vec![json!(["-1", "1.5", true, "-1", "-1", true]), json!([true, false, true, "-1", "1.5"])]); +} + +/// `typename` of a point or a point list throws for one that is stale, as the other members do. +#[test] +fn stale_points_throw_on_typename() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[3]; vc.log(q.typename); pp[0].remove();\ + try { q.typename; vc.log('read'); } catch (e) { vc.log(e.message); }\ + var p = app.activeDocument.pathItems[0], ps = p.pathPoints; vc.log(ps.typename); p.remove();\ + try { ps.typename; vc.log('read'); } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point"), json!("PathPoints"), json!("Stale page item")]); +} + +/// A path the creators make in a document whose ids are past 2^53 is the new path, not one whose +/// id a double rounds to. +#[test] +fn made_paths_keep_ids_past_two_to_the_53() { + let (mut s, _, _) = doc(); + let big = 1u64 << 53; + s.edit("Raise Ids", |d, _| { + d.raise_next_id(big); + Ok(()) + }) + .unwrap(); + let old = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + assert_eq!(old.0, big); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems; p.add().name = 'made'; p.rectangle(50, 50, 10, 10, true).name = 'reversed';"); + assert_eq!(node(&s, old).name, None); + assert_eq!(node(&s, NodeId(big + 1)).name.as_deref(), Some("made")); + assert_eq!(node(&s, NodeId(big + 2)).name.as_deref(), Some("reversed")); +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index e030723a16..9b64bd2dd6 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -48,8 +48,9 @@ pub(crate) enum Target { Artboard { document: u64, reverts: u64, index: usize }, /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, - /// The answer to a running script's `app.showColorPicker`, which opened it on this colour. - Script(Color), + /// The answer to a running script's `app.showColorPicker`, which opened it on `color`; `cmyk`: + /// the run's active document is in CMYK. + Script { color: Color, cmyk: bool }, } impl Target { @@ -62,7 +63,7 @@ impl Target { Self::Fill { document, reverts } | Self::Stroke { document, reverts } => (*document, *reverts), Self::Artboard { document, reverts, .. } => (Some(*document), *reverts), // A script's picker answers the run whichever document is active. - Self::Answer { .. } | Self::Script(_) => return None, + Self::Answer { .. } | Self::Script { .. } => return None, }; match (app.session.active(), document) { (None, None) => None, @@ -195,7 +196,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { (None, true) => "stroke", (None, false) => "fill", }; - let mut dialog = picker(app, key, &color); + let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk); + let mut dialog = picker(app, key, &color, cmyk); // The host replaces a picker only for the same document and artboard. if let Some((document, _, index, _)) = artboard { dialog = dialog.instance((document, index)); @@ -221,17 +223,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } /// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's -/// swatches and libraries, and in a CMYK document the working CMYK inks. -fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { +/// swatches and libraries, and with `cmyk` (a CMYK document) the working CMYK inks. +fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPickerDialog { let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color)) .eyedropper(true) .add_to_swatches(false) .gamut(gamut(app)) .working_rgb(WorkingRgb) .swatch_view(swatch_view(app)); - if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) - && let Some(converter) = working_cmyk() - { + if cmyk && let Some(converter) = working_cmyk() { dialog = dialog.cmyk(&converter); } if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { @@ -240,15 +240,18 @@ fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { dialog } -/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`. It +/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`: +/// the run's own active document is in CMYK, which the session does not show between slices. It /// previews nothing; its OK and Cancel answer the run ([`finish`]). -pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color) { +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool) { let Some(dialogs) = app.dialogs() else { return }; // The given colour's own values, so that OK can tell an untouched pick from another model's. - let dialog = picker(app, SCRIPT_KEY, &color).kept(model_values(&color)); + // The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given. + let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false); let id = dialogs.with(|h| h.open(dialog)); app.color_dialogs.pickers.retain(|o| o.id != id); - app.color_dialogs.pickers.push(Open { id, target: Target::Script(color), start: srgba(&color), keep: false, preview: LivePreview::default() }); + let target = Target::Script { color, cmyk }; + app.color_dialogs.pickers.push(Open { id, target, start: srgba(&color), keep: false, preview: LivePreview::default() }); } /// The key of the Color Picker a script opens. @@ -257,7 +260,7 @@ pub(crate) const SCRIPT_KEY: &str = "script"; /// The id of the Color Picker a running script waits at, while it is open or its answer is not /// yet given. pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { - app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script(_))).map(|o| o.id) + app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script { .. })).map(|o| o.id) } /// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. @@ -355,12 +358,12 @@ fn finish( } } // OK on the colour it opened with, in the model it opened with, gives that colour back. - (Some(DialogResult::Ok(r)), Target::Script(given)) => { + (Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk }) => { let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); - let picked = if untouched { *given } else { in_document_model(app, color_of(&r.picked)) }; + let picked = if untouched { *given } else { in_model(*cmyk, color_of(&r.picked)) }; app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); } - (_, Target::Script(_)) => { + (_, Target::Script { .. }) => { app.session.script_answer(DialogAnswer::ColorPicker(None)); } (Some(DialogResult::Ok(r)), _) => { @@ -377,14 +380,19 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })), Target::Stroke { .. } => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill { .. } | Target::Answer { .. } | Target::Script(_) => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Fill { .. } | Target::Answer { .. } | Target::Script { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), } } -/// The picked colour as the document takes it: an RGB colour is CMYK in a CMYK document; CMYK, -/// grey and Lab colours stay as they are. +/// The picked colour as the active document takes it ([`in_model`]). fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { - if matches!(c, Color::Rgb { .. }) && app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) { + in_model(app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk), c) +} + +/// The picked colour as a document takes it: an RGB colour is CMYK in a CMYK document (`cmyk`); +/// CMYK, grey and Lab colours stay as they are. +fn in_model(cmyk: bool, c: Color) -> Color { + if cmyk && matches!(c, Color::Rgb { .. }) { let [cy, m, y, k] = c.to_cmyk_managed(cms::active().settings().intent); return Color::cmyk(cy, m, y, k); } @@ -397,7 +405,7 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { // A picker over a command dialog only fills a row; the dialog previews it. A script's picker // only answers the script. - if matches!(open.target, Target::Answer { .. } | Target::Script(_)) || !open.target.in_active_document(app) { + if matches!(open.target, Target::Answer { .. } | Target::Script { .. }) || !open.target.in_active_document(app) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7951fc4a7e..7f27a225a8 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -118,7 +118,7 @@ fn ask(app: &mut VectorcraftApp) -> bool { && !script_run::busy(app) && let Some(color) = dialog.color { - color_picker::open_for_script(app, color); + color_picker::open_for_script(app, color, dialog.cmyk_document); } } else if !script_run::busy(app) { script_run::open_notice(app, &dialog); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index ca5d67b800..5dfa72ff39 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -420,3 +420,64 @@ fn stopping_or_quitting_the_run_closes_its_color_picker() { assert!(!picker_open(&app), "no picker is left for the abandoned run"); assert_eq!(objects(&app), 0); } + +#[test] +fn the_color_picker_opens_on_the_scripts_color_with_only_web_colors_left_on() { + let mut app = app(); + let ctx = app.ui_ctx.clone().unwrap(); + // A frame of the window's dialogs starts the open pickers with the app's host, whose settings + // keep what a picker remembers. + let frame = |app: &mut VectorcraftApp| { + let _ = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + }); + }; + // A fill picker closed with Only Web Colors on, which later fill pickers recall. + color_picker::open(&mut app, &json!({})).unwrap(); + frame(&mut app); + set(&app, "fill", "webColors", json!(true)).unwrap(); + let id = open_id(&app, "fill"); + assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap()); + color_picker::pump(&mut app, &ctx); + color_picker::open(&mut app, &json!({})).unwrap(); + frame(&mut app); + assert_eq!(fields(&app, "fill")["webColors"], json!(true), "the next fill picker recalls Only Web Colors"); + let id = open_id(&app, "fill"); + assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap()); + color_picker::pump(&mut app, &ctx); + // A frame without the picker drops its overlay. + frame(&mut app); + assert!(!script_run::busy(&app), "no picker is left open"); + start( + &mut app, + "var c = new RGBColor(); c.red = 18; c.green = 52; c.blue = 86; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());", + ); + assert!(until_picker(&mut app)); + frame(&mut app); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor,18,52,86"]), "untouched OK gives the script's color, not its nearest web color"); +} + +#[test] +fn a_pick_takes_the_model_of_the_document_the_script_made() { + for (doc, made, want) in [("{}", "CMYK", "CMYKColor"), ("{\"colorMode\": \"cmyk\"}", "RGB", "RGBColor")] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), crate::Services::default())); + app.run("file.new", serde_json::from_str(doc).unwrap()).unwrap(); + app.session.prefs.show_external_script_warning = false; + start( + &mut app, + &format!( + "app.documents.add(DocumentColorSpace.{made}, 50, 60, 1); var c = new RGBColor(); c.red = 255; \ + var p = app.showColorPicker(c); vc.log(p.typename);" + ), + ); + assert!(until_picker(&mut app)); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!([want]), "an RGB pick in the {made} document the script made"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index be0c4e9c3f..e35ba44e66 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2782,7 +2782,7 @@ other files through `$`: describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level `var selection = ...` does the same and does not make a variable of the script. Assigning `documents` keeps its - value. `app.documents` + value; in strict-mode code it throws a `TypeError`. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -2909,7 +2909,8 @@ other files through `$`: radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing - mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + mode, which stays as it was, or, while an object is isolated, where drawing puts a new path (in an isolated group, + for example). A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to @@ -2919,8 +2920,8 @@ other files through `$`: stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one - `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the - script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points + `path.setAnchors` before the script uses any other member or command, or changes the points of another path, and + when the script ends (reading the points of another path does not write them); a path aligned to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and @@ -2933,7 +2934,8 @@ other files through `$`: `NOSELECTION` removes it, through `select.anchorsMany`, with the other selected objects and anchors kept. `selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as - https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` + https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it; a gray within about 1e-14 % of white reads as + 100, so assigning it back makes it white), `new LabColor()` and `new NoColor()` (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. @@ -3341,8 +3343,10 @@ empty object are the same. `app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, `CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a -`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in a CMYK -document an RGB pick is returned as CMYK. OK with the color unchanged and Cancel return a new object of the color the +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; when the +run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so the +color's `typename` can differ from the picker's model and from the color given. The picker opens on the color as +given, whatever Only Web Colors was left at in another picker. OK with the color unchanged and Cancel return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: "colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 292d08a18e..0a79cddfbf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1092,7 +1092,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. - - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, and Cancel a new object of the color given. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.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`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. From 51ad0b8eecbda5f85dfb8ea6ada36210ce49be9a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:07:02 -0800 Subject: [PATCH 004/103] MCP: ui.paramDialog without a command it can open is an error ui.paramDialog with no command, a null, empty or non-string command, or a command id that names no command opened a parameter dialog for that id (an empty key with no rows) and replied with success. It now replies with an error and opens nothing, and a dialog already open stays open. A label that is not a string and params that are not an object are errors too; a null label or params reads as left out. tool.options without a tool, or with a tool that is not a string, now says "missing `tool`" or "`tool` must be a string" instead of "unknown tool ``". --- crates/ui-egui/src/dialogs/command.rs | 52 +++++++++++++++++++++++++ crates/ui-egui/src/menus/run.rs | 55 +++++++++++++++++++-------- 2 files changed, 92 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6d8741d342..cb2161d9fa 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -1192,4 +1192,56 @@ mod tests { assert!(lengths("select.object.hairlineSlivers").contains(&"width")); assert_eq!(length_range("object.path.cleanUp", "sliverWidth"), Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE)); } + + /// The dialogs `ui.inspect` lists, by kind. + fn inspected_kinds(app: &VectorcraftApp) -> Vec { + let dialogs = app.dialogs().unwrap().with(|host| craft::automation::dialogs::inspect(host)); + dialogs.as_array().unwrap().iter().map(|d| d["kind"].clone()).collect() + } + + /// `ui.paramDialog` without a command it can open, or with a label or params of the wrong type, is an error that + /// opens no dialog and leaves the dialog already open in place. + #[test] + fn param_dialog_refuses_a_missing_empty_or_unknown_command() { + let mut app = windowed(); + let refused = [ + (json!({}), "missing `command`"), + (json!({"command": null, "params": {}}), "missing `command`"), + (json!({"command": "", "params": {}}), "`command` must name a command"), + (json!({"command": 5, "params": {}}), "`command` must be a string"), + (json!({"command": "no.such", "params": {}}), "unknown command `no.such`"), + (json!({"command": "gradient.presets.save", "label": 7, "params": {"name": "a"}}), "`label` must be a string"), + (json!({"command": "gradient.presets.save", "params": ["a"]}), "`params` must be an object"), + (json!({"command": "edit.findReplace", "params": "a"}), "`params` must be an object"), + ]; + for (params, want) in &refused { + let e = app.run("ui.paramDialog", params.clone()).unwrap_err(); + assert!(e.contains(want), "{params}: {e}"); + assert!(app.command_dialog.open.is_none(), "{params}: no dialog opens"); + assert_eq!(inspected_kinds(&app), Vec::::new(), "{params}: ui.inspect lists no dialog"); + } + app.run("ui.paramDialog", json!({"command": "gradient.presets.save", "label": "Gradient Preset", "params": {"name": "a"}})).unwrap(); + pump(&mut app); + let (id, kinds) = (id_of(&app), inspected_kinds(&app)); + assert_eq!(kinds.len(), 1, "{kinds:?}"); + for (params, want) in &refused { + let e = app.run("ui.paramDialog", params.clone()).unwrap_err(); + assert!(e.contains(want), "{params}: {e}"); + assert_eq!(id_of(&app), id, "{params}: the open dialog stays"); + assert_eq!(inspected_kinds(&app), kinds, "{params}: ui.inspect lists the same dialog"); + } + } + + /// `tool.options` without a tool, or with one that is not a string, is an error that names the parameter. + #[test] + fn tool_options_refuses_a_missing_or_wrongly_typed_tool() { + let mut app = windowed(); + for (params, want) in + [(json!({}), "missing `tool`"), (json!({"tool": null}), "missing `tool`"), (json!({"tool": 3}), "`tool` must be a string")] + { + let e = app.run("tool.options", params.clone()).unwrap_err(); + assert!(e.contains(want), "{params}: {e}"); + assert_eq!(inspected_kinds(&app), Vec::::new(), "{params}: ui.inspect lists no dialog"); + } + } } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 11975b7c24..e041e86126 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -801,20 +801,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::recolor::open(app, p), "ui.cropImage" if !selected_image(app, |_| true) => Err("select an image".into()), "ui.cropImage" => app.try_select_tool(vectorcraft_tools::cropimage::ID).map(|()| json!({"tool": app.session.tool_id()})), - // Create Object Mosaic… has a dialog of its own, opened on the selected image. - "ui.paramDialog" if s("command").as_deref() == Some(crate::dialogs::object_mosaic::COMMAND) => { - crate::dialogs::object_mosaic::open(app, p.get("params").unwrap_or(&Value::Null)) - } - "ui.paramDialog" => { - let cmd = s("command").unwrap_or_default(); - let fields = p.get("params").and_then(Value::as_object).cloned().unwrap_or_default(); - // Find and Replace has a dialog of its own, which stays open from match to match. - if cmd == crate::dialogs::find_replace::COMMAND { - return Some(crate::dialogs::find_replace::open(app, &fields)); - } - let label = s("label").unwrap_or(cmd.clone()); - crate::dialogs::command::open(app, &cmd, &label, fields) - } + "ui.paramDialog" => param_dialog(app, p), "effect.applyLast" => match app.last_effect.clone() { Some((e, params)) => app.run("effect.apply", json!({"effect": e, "params": params})), None => Err("no effect applied yet".into()), @@ -827,6 +814,40 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Result { + let cmd = match p.get("command") { + None | Some(Value::Null) => return Err("missing `command`".into()), + Some(Value::String(c)) if c.is_empty() => return Err("`command` must name a command".into()), + Some(Value::String(c)) => c.clone(), + Some(_) => return Err("`command` must be a string".into()), + }; + if vectorcraft_engine::find_command(&cmd).is_none() && !UI_COMMANDS.iter().any(|c| c.0 == cmd) { + return Err(format!("unknown command `{cmd}`")); + } + let label = match p.get("label") { + None | Some(Value::Null) => None, + Some(Value::String(l)) => Some(l.clone()), + Some(_) => return Err("`label` must be a string".into()), + }; + let fields = match p.get("params") { + None | Some(Value::Null) => serde_json::Map::new(), + Some(Value::Object(m)) => m.clone(), + Some(_) => return Err("`params` must be an object".into()), + }; + // Create Object Mosaic… has a dialog of its own, opened on the selected image. + if cmd == crate::dialogs::object_mosaic::COMMAND { + return crate::dialogs::object_mosaic::open(app, p.get("params").unwrap_or(&Value::Null)); + } + // Find and Replace has a dialog of its own, which stays open from match to match. + if cmd == crate::dialogs::find_replace::COMMAND { + return crate::dialogs::find_replace::open(app, &fields); + } + let label = label.unwrap_or_else(|| cmd.clone()); + crate::dialogs::command::open(app, &cmd, &label, fields) +} + /// UI commands, part 7. fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); @@ -913,7 +934,11 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::new_brush::open(app, p.get("ids").cloned()), "ui.brushOptions" => crate::dialogs::brush_options::open(app, s("name").as_deref()), "ui.brushObjectOptions" => crate::dialogs::brush_options::open_object(app), - "tool.options" => crate::toolbar::open_options(app, &s("tool").unwrap_or_default()), + "tool.options" => match p.get("tool") { + None | Some(Value::Null) => Err("missing `tool`".into()), + Some(Value::String(t)) => crate::toolbar::open_options(app, t), + Some(_) => Err("`tool` must be a string".into()), + }, _ => return None, }; Some(r) From 9e7e97b763f0441b632c7014d58bce63b5299342 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:59:22 -0800 Subject: [PATCH 005/103] MCP: ui.paramDialog params text says an unknown command is an error The params text of ui.paramDialog, in both catalogs, and docs/mcp.md now say that a missing, empty, non-string or unknown command, a label that is not a string or params that are not an object is an error, and no dialog opens. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..5a6ac10171 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1006,7 +1006,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is not a string or params that are not an object is an error, and no dialog opens. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..9f4155a006 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1007,7 +1007,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is not a string or params that are not an object is an error, and no dialog opens. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..59158565c8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13678,7 +13678,9 @@ wrong type runs no action and returns the error. For other command dialogs, `params.__doc` can supply a document uid. The dialog previews and confirms only while that document is active. Confirming after a document switch closes the dialog without running its command. Canceling or replacing that dialog does not cancel an interaction in another document. A supplied `__doc` must be -an unsigned integer; omitting it preserves the command dialog's existing behavior. +an unsigned integer; omitting it preserves the command dialog's existing behavior. `ui.paramDialog` with a missing, +empty, non-string or unknown `command`, a `label` that is not a string or `params` that are not an object is an +error, and no dialog opens. ## Justification options From 8fd404632898186b86e0fb57848eb25ddcca8f73 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 21:30:27 -0800 Subject: [PATCH 006/103] MCP: ui.paramDialog text says a null label or params is treated as omitted The params text in both catalogs, docs/mcp.md and the param_dialog doc comment now mark params optional and say that a null label or params is handled the same as an omitted one, as the code does. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/run.rs | 5 +++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 5a6ac10171..8d39c30641 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1006,7 +1006,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is not a string or params that are not an object is an error, and no dialog opens. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index e041e86126..a7c096116f 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -814,8 +814,9 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Result { let cmd = match p.get("command") { None | Some(Value::Null) => return Err("missing `command`".into()), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 9f4155a006..4177d327b0 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1007,7 +1007,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is not a string or params that are not an object is an error, and no dialog opens. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/docs/mcp.md b/docs/mcp.md index 59158565c8..9a3ae4f7fa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13679,8 +13679,8 @@ For other command dialogs, `params.__doc` can supply a document uid. The dialog that document is active. Confirming after a document switch closes the dialog without running its command. Canceling or replacing that dialog does not cancel an interaction in another document. A supplied `__doc` must be an unsigned integer; omitting it preserves the command dialog's existing behavior. `ui.paramDialog` with a missing, -empty, non-string or unknown `command`, a `label` that is not a string or `params` that are not an object is an -error, and no dialog opens. +empty, non-string or unknown `command`, a `label` that is neither a string nor null, or `params` that are neither an +object nor null is an error, and no dialog opens. A null `label` or `params` is treated as omitted. ## Justification options From bdb753eef968a24beb8b44cb2450e61d8a52f517 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 21:40:40 -0800 Subject: [PATCH 007/103] Scripts: a color picker answer refuses out-of-range color keys A headless colorPicker answer written as a color key, such as "rgb 300 0 0" or "rgb 255.000001 0 0", was clamped into range and accepted, while the same color as an array or object was refused. The key's components are now checked as written, in f64, before the key is read. The near-white gray note in docs/mcp.md and colors.rs now says which paint keeps its color when the read-back gray is assigned. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 27 ++++++++++++++++++++++- crates/engine/src/script/dom/colors.rs | 7 +++--- crates/engine/src/tests/script_dialogs.rs | 15 ++++++++++++- docs/mcp.md | 5 +++-- docs/target-app-parity.md | 2 +- 6 files changed, 49 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b2812cb8c2..b3cc43bed3 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 script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), 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; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), 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; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 04fb0b49f7..5daae5bb1d 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -168,6 +168,31 @@ fn in_range(c: &Color) -> bool { } } +/// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key +/// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components +/// into their ranges. +fn answer_color(v: &Value) -> Option { + if let Value::String(s) = v + && Color::from_hex(s).is_none() + { + let mut it = s.split_whitespace(); + let model = it.next()?.to_ascii_lowercase(); + // Parsed as f64, so that a value just past a limit is not rounded onto it. + let n: Vec = it.map(|t| t.parse::().ok().filter(|x| x.is_finite())).collect::>()?; + let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x)); + let written_in_range = match (model.as_str(), n.as_slice()) { + ("rgb", [_, _, _]) => within(&n, 0.0, 255.0), + ("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0), + ("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0), + _ => return None, + }; + if !written_in_range { + return None; + } + } + crate::cmd::color_value(v).filter(in_range) +} + /// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together /// is a line break; every other control character, and with `lines` false every line break too, /// shows as its Unicode Control Picture, as the Script Console shows it. @@ -242,7 +267,7 @@ fn known_answer(o: &Map) -> Result { (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), (Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)), - (Some("colorPicker"), v) => match crate::cmd::color_value(v).filter(in_range) { + (Some("colorPicker"), v) => match answer_color(v) { Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))), None => Err("is a color picker's answer, whose `value` must be a color or null"), }, diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 8f04ed384c..00bcdfa6f6 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -13,9 +13,10 @@ //! VectorCraft's own rules, which the help pages do not state: components left out count as 0; //! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` //! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page -//! says. A color read from an object gives that object the same color when it is assigned back, -//! except a gray within about 1e-14 % of white: one number cannot hold it, so it reads as 100 and -//! assigning it back makes the gray white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not +//! says. A color read from an object gives that object the same color when it is assigned back. +//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it +//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to +//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not //! assigned yet. use std::rc::Rc; diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index af1d07f06a..dbd727e33c 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -372,10 +372,23 @@ fn the_color_picker_refuses_what_is_not_a_solid_color() { let r = headless(&mut s, source, json!([])).unwrap(); assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}"); assert_eq!(r["dialogCount"], 0, "no picker opened"); - for bad in [json!("not a color"), json!([255, 0, 0]), json!({"model": "lab", "l": 120, "a": 0, "b": 0}), json!(true)] { + for bad in [ + json!("not a color"), + json!([255, 0, 0]), + json!({"model": "lab", "l": 120, "a": 0, "b": 0}), + json!(true), + json!("rgb 300 0 0"), + json!("cmyk 0 0 0 101"), + json!("gray -1"), + json!("lab 50 200 0"), + json!("rgb 255.000001 0 0"), + ] { let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); assert!(e.contains("color picker's answer"), "{bad}: {e}"); } + for good in [json!("rgb 255 0 0"), json!("cmyk 0 100 100 0"), json!("gray 100"), json!("lab 50 -128 128")] { + assert!(headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": good})])).is_ok(), "{good}"); + } } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index c2ceaff161..dd885ea436 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3136,7 +3136,8 @@ through `$`: `selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it; a gray within about 1e-14 % of white reads as - 100, so assigning it back makes it white), `new LabColor()` and `new NoColor()` + 100; assigning it to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it + to any other paint gives white), `new LabColor()` and `new NoColor()` (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. @@ -3726,7 +3727,7 @@ given, whatever Only Web Colors was left at in another picker. OK with the color script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: "colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its -range, or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and +range (a color key such as `"rgb 300 0 0"` is refused, not clamped), or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and `ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. ```sh diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 17c88f6361..ab023f4b05 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1129,7 +1129,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. From da7df61b3ab1bbf7a72ef265cfd0b721085dce61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 22:07:25 -0800 Subject: [PATCH 008/103] Tests: ui.paramDialog refusals keep the same opening of the open dialog The test read a `kind` field that ui.inspect does not report, so it compared only the dialog count. It now compares each dialog's id and key, and the host's open serial, which changes when a dialog is opened again. --- crates/ui-egui/src/dialogs/command.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index cb2161d9fa..3059d0b833 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -1193,10 +1193,10 @@ mod tests { assert_eq!(length_range("object.path.cleanUp", "sliverWidth"), Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE)); } - /// The dialogs `ui.inspect` lists, by kind. + /// The dialogs `ui.inspect` lists, by id and key. fn inspected_kinds(app: &VectorcraftApp) -> Vec { let dialogs = app.dialogs().unwrap().with(|host| craft::automation::dialogs::inspect(host)); - dialogs.as_array().unwrap().iter().map(|d| d["kind"].clone()).collect() + dialogs.as_array().unwrap().iter().map(|d| json!([d["id"], d["key"]])).collect() } /// `ui.paramDialog` without a command it can open, or with a label or params of the wrong type, is an error that @@ -1223,11 +1223,16 @@ mod tests { app.run("ui.paramDialog", json!({"command": "gradient.presets.save", "label": "Gradient Preset", "params": {"name": "a"}})).unwrap(); pump(&mut app); let (id, kinds) = (id_of(&app), inspected_kinds(&app)); + // Which opening of the dialog shows: the host numbers every open, so a dialog opened again has a new number. + let shown_serial = |app: &VectorcraftApp, id: DialogId| app.dialogs().unwrap().with(|host| host.open_serial(id)); + let serial = shown_serial(&app, id); assert_eq!(kinds.len(), 1, "{kinds:?}"); + assert!(serial.is_some()); for (params, want) in &refused { let e = app.run("ui.paramDialog", params.clone()).unwrap_err(); assert!(e.contains(want), "{params}: {e}"); assert_eq!(id_of(&app), id, "{params}: the open dialog stays"); + assert_eq!(shown_serial(&app, id), serial, "{params}: the same opening of the dialog stays"); assert_eq!(inspected_kinds(&app), kinds, "{params}: ui.inspect lists the same dialog"); } } From bd5e900f192187d9db83fbda20b40dc540e46dfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 21:58:44 -0800 Subject: [PATCH 009/103] Arrange Tools: replay scales corners as the recorded run did Match Objects, Set Size of Each, Swap Objects, Replace with Top Object and Sort Objects record the Scale Corners value in their journal entry, but read the current preference again when the entry is replayed. A rounded rectangle resized with Scale Corners on then kept its radius on replay with the preference off. Each command now reads the recorded value, falling back to the preference, and uses it both to solve the bounds and to apply the transform. --- crates/engine/src/cmd/addons/arrange.rs | 69 +++++++++++-------- crates/engine/src/cmd/addons/arrange/tests.rs | 38 ++++++++++ docs/mcp.md | 13 ++-- 3 files changed, 88 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index c1e99bb155..c898a0e415 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Swap Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", + "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", exactly_two, swap ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Replace with Top Object", ["Object", "Plug-ins", "Arrange Tools"], None, - "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", + "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", has_multi, replace ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Set Size of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", + "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", has_selection, size ), @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Sort Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), corners?: the Scale Corners preference, ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", has_multi, sort ), @@ -154,10 +154,10 @@ fn size_param(p: &Value, key: &str, cmd: &str) -> Result> { p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose() } -/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes` -/// and, when given, a width and height. -fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { - let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes }); +/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`, +/// Scale Corners `corners` and, when given, a width and height. +fn place(at: Point, size: Option<(f64, f64)>, strokes: bool, corners: bool) -> Value { + let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes, "corners": corners }); if let Some((w, h)) = size { q["width"] = json!(w); q["height"] = json!(h); @@ -166,14 +166,15 @@ fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { } /// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects -/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says. -/// When every transform is (within rounding) the identity, nothing changes. -fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { +/// scaling with Scale Strokes & Effects `strokes`, corners with Scale Corners `corners`, pattern +/// tiles as Transform Pattern Tiles says. When every transform is (within rounding) the identity, +/// nothing changes. +fn transform_each(s: &mut Session, label: &str, strokes: bool, corners: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); if xfs.iter().all(|(_, xf)| still(xf)) { return Ok(()); } - let p = json!({ "strokes": strokes }); + let p = json!({ "strokes": strokes, "corners": corners }); let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &ids)?; @@ -195,6 +196,14 @@ fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result { Ok(on) } +/// The `corners` value of a replayed journal entry, else the Scale Corners preference. The value +/// joins the command's journal entry, so replaying it scales corners the same way. +fn scale_corners(s: &mut Session, p: &Value, cmd: &str) -> Result { + let on = switch_or(p, "corners", s.prefs.scale_corners, cmd)?; + s.note_journal("corners", json!(on)); + Ok(on) +} + /// The box of object `id` as `object.setBounds` measures it. fn box_of(s: &Session, id: NodeId) -> Result { s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into())) @@ -252,7 +261,7 @@ fn grid(s: &mut Session, p: &Value) -> Result { .enumerate() .filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center())))) .collect(); - transform_each(s, "Arrange in Grid", false, &xfs)?; + transform_each(s, "Arrange in Grid", false, s.prefs.scale_corners, &xfs)?; Ok(json!({ "count": n })) } @@ -288,7 +297,7 @@ fn offset(s: &mut Session, p: &Value) -> Result { (id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) })) }) .collect(); - transform_each(s, "Offset Objects", false, &xfs)?; + transform_each(s, "Offset Objects", false, s.prefs.scale_corners, &xfs)?; Ok(json!({ "count": items.len() })) } @@ -296,12 +305,13 @@ fn swap(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.swap"; let size = switch_or(p, "size", false, C)?; let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let roots = selected_roots(s)?; let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) }; let (ba, bb) = (box_of(s, a)?, box_of(s, b)?); - let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes); + let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes, corners); let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)]; - transform_each(s, "Swap Objects", strokes, &xfs)?; + transform_each(s, "Swap Objects", strokes, corners, &xfs)?; Ok(json!({})) } @@ -309,6 +319,7 @@ fn replace(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.replace"; let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep"); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let keep = switch_or(p, "keep", false, C)?; let roots = selected_roots(s)?; let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else { @@ -328,9 +339,9 @@ fn replace(s: &mut Session, p: &Value) -> Result { } _ => None, }; - xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?)); + xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes, corners), top)?)); } - let p = json!({ "strokes": strokes }); + let p = json!({ "strokes": strokes, "corners": corners }); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &[top])?; let ids = s.edit("Replace with Top Object", |d, sel| { @@ -360,7 +371,8 @@ fn size(s: &mut Session, p: &Value) -> Result { let proportional = switch_or(p, "proportional", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); let strokes = scale_strokes(s, p, C)?; - let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }); + let corners = scale_corners(s, p, C)?; + let mut q = json!({ "reference": reference, "strokes": strokes, "corners": corners, "proportional": proportional && (width.is_none() || height.is_none()) }); if let Some(w) = width { q["width"] = json!(w); } @@ -373,7 +385,7 @@ fn size(s: &mut Session, p: &Value) -> Result { xfs.push((id, object_bounds_transform(s, &q, id)?)); } } - transform_each(s, "Set Size of Each", strokes, &xfs)?; + transform_each(s, "Set Size of Each", strokes, corners, &xfs)?; Ok(json!({ "count": xfs.len() })) } @@ -405,6 +417,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let stacking = switch_or(p, "stacking", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?; if size == "none" && !rotate && !stacking { return Err(bad(C, "give `size`, `rotate` or `stacking`")); @@ -452,6 +465,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let mut q = q.clone(); q["reference"] = json!(reference); q["strokes"] = json!(strokes); + q["corners"] = json!(corners); xf = object_bounds_transform(s, &q, id)?; } if turn.abs() > 1e-9 { @@ -460,7 +474,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { xf = Affine::rotate_about(-turn.to_radians(), at) * xf; } if wanted.is_some() { - let sc = scaling(s, &json!({ "strokes": strokes })); + let sc = scaling(s, &json!({ "strokes": strokes, "corners": corners })); let d = &s.doc()?.doc; let symbols = d.symbol_boxes(); let measure = |xf| { @@ -508,7 +522,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { if xfs.is_empty() && !restack { return Ok(count); } - let q = json!({ "strokes": strokes, "patterns": patterns }); + let q = json!({ "strokes": strokes, "corners": corners, "patterns": patterns }); let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &q); sc.patterns = transform_patterns(s, &q, &ids)?; @@ -676,6 +690,7 @@ fn sort(s: &mut Session, p: &Value) -> Result { let distribute = switch_or(p, "distribute", false, C)?; let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let ids = checked_ids_or_selection(s, p, C)?; if ids.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); @@ -758,17 +773,17 @@ fn sort(s: &mut Session, p: &Value) -> Result { let q = match apply { "x" => json!({ "x": v, "reference": 0 }), "y" => json!({ "y": v, "reference": 0 }), - "width" => json!({ "width": v, "strokes": strokes }), - "height" => json!({ "height": v, "strokes": strokes }), + "width" => json!({ "width": v, "strokes": strokes, "corners": corners }), + "height" => json!({ "height": v, "strokes": strokes, "corners": corners }), // An area: both sides in proportion; an object without one keeps its size. _ => { let (w, h) = (o.b.rect.width(), o.b.rect.height()); let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 }; - json!({ "width": w * k, "height": h * k, "strokes": strokes }) + json!({ "width": w * k, "height": h * k, "strokes": strokes, "corners": corners }) } }; xfs.push((o.id, object_bounds_transform(s, &q, o.id)?)); } - transform_each(s, "Sort Objects", strokes, &xfs)?; + transform_each(s, "Sort Objects", strokes, corners, &xfs)?; Ok(count) } diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 265ab50a6a..032f350c7a 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -577,6 +577,44 @@ fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) { assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s)); } +/// Running `cmd` with Scale Corners on doubles the 2 pt corner radius of a 10 pt rounded square, +/// and replaying its journal entry after the preference is turned off scales the corners the same way. +fn replays_the_corner_scaling_it_ran_with(cmd: &str, p: Value) { + let mut s = session(); + let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10, "radius": 2})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + let radius = |s: &Session| match s.doc().unwrap().doc.node(a).unwrap().live_shape() { + Some(vectorcraft_doc::LiveShape::Rectangle { radii, xf, .. }) => radii[0] * xf.as_coeffs()[0], + _ => panic!("not a live rectangle"), + }; + select(&mut s, &[a, b]); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap(); + s.execute(cmd, &p).unwrap(); + assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", radius(&s)); + let (id, q) = s.journal.last().unwrap().clone(); + assert_eq!(id, cmd); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap(); + select(&mut s, &[a, b]); + s.replay(&id, &q).unwrap(); + assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", radius(&s)); +} + +#[test] +fn match_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); +} + +#[test] +fn set_size_of_each_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20})); +} + +#[test] +fn swap_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.swap", json!({"size": true})); +} + #[test] fn match_stacking_leaves_a_clipping_path_in_place() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..da701dabb0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17573,18 +17573,21 @@ Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes sele `addon.arrange.*`, and in the desktop app it lives in Object › Plug-ins › Arrange Tools. Each command acts on the top-level selected objects and is one undo step; a run that moves nothing makes no step. Places and sizes are measured as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds. +Swap Objects, Replace with Top Object, Set Size of Each, Match Objects, and Sort Objects scale corner radii according +to the `corners` parameter, which defaults to the Scale Corners preference. For these commands, the journal entry +records the value used, and a replay of that entry scales corners the same way whatever the preference is then. | Command | Parameters (default) | Does | |---|---|---| | `addon.arrange.grid` | `layout`: `grid`, `row`, `column` (`grid`); `columns`: 1…10000 (⌈√count⌉, never more than the count); `gapX` pt (10), `gapY` pt (`gapX`), each −1000000…1000000; `centerOnArtboard` (false) | Lays the objects out in their stacking order from the back, left to right and top to bottom. Each cell is as wide as the widest object in its column and as tall as the tallest in its row, and each object is centred in its cell. The grid starts at the selection's top-left, or is centred on the artboard under the selection's centre (the first artboard when none is there). → `{count}` | | `addon.arrange.offset` | `direction`: `row` (left to right), `column` (top to bottom) (`row`); `gap` pt, −1000000…1000000 (10; negative overlaps the objects); `order`: `stacking` (stacking order from the back), `position` (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (`stacking`); `reverse` (false) | Chains the objects one after another in that order: the first stays where it is, and each later one moves only along the direction so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Measured by visual bounds, a clipping group by its mask. Needs two objects or more. → `{count}` | -| `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | -| `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | -| `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference); `corners` (the Scale Corners preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | +| `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `corners` (the Scale Corners preference); `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | +| `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes`; `corners` (the Scale Corners preference) | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `corners` (the Scale Corners preference); `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | -| `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | +| `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `corners` (the Scale Corners preference); `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, From 0db31a67384e96e3563033b2a0eb6d98f2603302 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:12:15 -0800 Subject: [PATCH 010/103] MCP: ui.paramDialog waits for plug-ins still loading before refusing their commands While plug-ins load in the background, a plug-in command is not registered yet, so the new unknown-command check refused a valid id that running the command waits for. A plug-in command id that is not known yet now waits for the pending loads, as Session::execute does. Built-in commands, ids that cannot name a plug-in command and bad label or params are answered without waiting. The params text and docs/mcp.md say so. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/command.rs | 24 ++++++++++++++++++++++++ crates/ui-egui/src/menus/run.rs | 11 ++++++++--- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 3 ++- 5 files changed, 36 insertions(+), 6 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 8d39c30641..d1d1e480db 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1006,7 +1006,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 3059d0b833..dbfb59875d 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -1237,6 +1237,30 @@ mod tests { } } + /// `ui.paramDialog` on the command of a plug-in still loading in the background waits for the plug-in to install and + /// opens its dialog, as running the command waits for it. + #[test] + fn param_dialog_waits_for_a_plug_in_still_loading() { + use vectorcraft_plugins::wat as tpl; + let id = "test.ui.paramdialogloading"; + let dir = std::env::temp_dir().join(format!("vectorcraft-ui-param-dialog-loading-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","commands":[{{"id":"look","label":"Look"}}]}}"#); + std::fs::write(dir.join(format!("{id}.wasm")), wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let mut app = windowed(); + app.session.load_plugins_in_background(true); + app.session.attach_plugin_store(dir.clone()); + let loading = app.session.plugins_loading(); + let opened = app.run("ui.paramDialog", json!({"command": format!("plugin.{id}.look"), "params": {}})); + let shown = app.command_dialog.open.is_some(); + vectorcraft_plugins::registry::remove(id); + let _ = std::fs::remove_dir_all(&dir); + assert!(loading, "the store loads in the background"); + opened.unwrap(); + assert!(shown, "the plug-in's dialog opens"); + } + /// `tool.options` without a tool, or with one that is not a string, is an error that names the parameter. #[test] fn tool_options_refuses_a_missing_or_wrongly_typed_tool() { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index a7c096116f..5679e7c1f0 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -824,9 +824,6 @@ fn param_dialog(app: &mut VectorcraftApp, p: &Value) -> Result { Some(Value::String(c)) => c.clone(), Some(_) => return Err("`command` must be a string".into()), }; - if vectorcraft_engine::find_command(&cmd).is_none() && !UI_COMMANDS.iter().any(|c| c.0 == cmd) { - return Err(format!("unknown command `{cmd}`")); - } let label = match p.get("label") { None | Some(Value::Null) => None, Some(Value::String(l)) => Some(l.clone()), @@ -837,6 +834,14 @@ fn param_dialog(app: &mut VectorcraftApp, p: &Value) -> Result { Some(Value::Object(m)) => m.clone(), Some(_) => return Err("`params` must be an object".into()), }; + // A plug-in command is known once the plug-ins still loading are installed, as `Session::execute` waits for them. + let known = |cmd: &str| vectorcraft_engine::find_command(cmd).is_some() || UI_COMMANDS.iter().any(|c| c.0 == cmd); + if !known(&cmd) && app.session.plugins_loading() && vectorcraft_engine::cmd::plugin::is_command_id(&cmd) { + app.session.finish_plugin_loads(); + } + if !known(&cmd) { + return Err(format!("unknown command `{cmd}`")); + } // Create Object Mosaic… has a dialog of its own, opened on the selected image. if cmd == crate::dialogs::object_mosaic::COMMAND { return crate::dialogs::object_mosaic::open(app, p.get("params").unwrap_or(&Value::Null)); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4177d327b0..5626f3d318 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1007,7 +1007,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/docs/mcp.md b/docs/mcp.md index 9a3ae4f7fa..ba3253052b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13680,7 +13680,8 @@ that document is active. Confirming after a document switch closes the dialog wi Canceling or replacing that dialog does not cancel an interaction in another document. A supplied `__doc` must be an unsigned integer; omitting it preserves the command dialog's existing behavior. `ui.paramDialog` with a missing, empty, non-string or unknown `command`, a `label` that is neither a string nor null, or `params` that are neither an -object nor null is an error, and no dialog opens. A null `label` or `params` is treated as omitted. +object nor null is an error, and no dialog opens. A null `label` or `params` is treated as omitted. A plug-in +command that is not installed yet waits for the plug-ins still loading before it is checked. ## Justification options From fc30737f7339770bb1c2298cabbd3e3ac272acfa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:21:26 -0800 Subject: [PATCH 011/103] Match Objects: sizes fit after the turn, reach any scale and replay with their corner scaling Match Objects measured a target's new size before it was turned, refused sizes that pixel-aligned art reaches before it snaps, and checked only the requested side of a proportional match. A stroke or effect that does not turn with the art, such as a Transform effect's copy, then made a reachable size fail. Each target is now measured in the frame it ends in, before pixel snapping, against both sides; when it misses, the scales in that frame are fitted from the turned object and its reference point is kept in place. A fit that leaves the target at its old angle is refused. The 1e-4 smallest scale of object.setBounds no longer applies, so a 20,000 pt object can be matched down to 1 pt. Match Objects, Set Size of Each, Swap Objects, Replace with Top Object and Sort Objects now pass the journaled Scale Corners (and Transform Pattern Tiles) values to both the size solver and the transform, so a replay scales corners as the run did. Follows up #10072. --- ROADMAP.md | 2 +- crates/engine/src/cmd/addons/arrange.rs | 167 +++++++++++++----- crates/engine/src/cmd/addons/arrange/tests.rs | 142 +++++++++++++++ crates/engine/src/cmd/object.rs | 2 +- crates/engine/src/cmd/object/bounds.rs | 19 +- docs/mcp.md | 2 +- 6 files changed, 285 insertions(+), 49 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index e317f148d8..25caa796ef 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -163,7 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). -- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). Sizes are measured in each object's bounding-box frame after it is turned, with no smallest scale. A side that follows in proportion follows the object's box before the match. Pixel-aligned art is measured before it snaps. A VectorCraft addition: headline numbers unchanged. - 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index c1e99bb155..b77ffe796b 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -27,7 +27,9 @@ use super::super::colorcmds::edit_if_changed; use super::super::edit::selected_roots; use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; -use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; +use super::super::object::{ + choice, object_bounds_transform, object_bounds_transform_keeping, refit_drawn, scaling, transform_node, transform_patterns, +}; use super::super::typecmd::refresh_bounds_of; use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; use crate::{EngineError, Result, Session}; @@ -95,7 +97,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -168,12 +170,12 @@ fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { /// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects /// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says. /// When every transform is (within rounding) the identity, nothing changes. -fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { +fn transform_each(s: &mut Session, label: &str, p: &Value, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); if xfs.iter().all(|(_, xf)| still(xf)) { return Ok(()); } - let p = json!({ "strokes": strokes }); + let p = scaling_params(p, strokes); let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &ids)?; @@ -187,6 +189,28 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A }) } +/// The params [`scaling`] and [`transform_patterns`] read: Scale Strokes & Effects `strokes`, and +/// the `corners` and `patterns` values of the command's params `p`. Those two are absent on a first +/// run, which takes the preferences, and present when its journal entry is replayed. +fn scaling_params(p: &Value, strokes: bool) -> Value { + let mut q = json!({ "strokes": strokes }); + for k in ["corners", "patterns"] { + if let Some(v) = p.get(k).filter(|v| v.is_boolean()) { + q[k] = v.clone(); + } + } + q +} + +/// `object.setBounds` params `q` with the `corners` value of the command's params `p`, when it has +/// one, so a replay measures corners as the run did. +fn with_corners(mut q: Value, p: &Value) -> Value { + if let Some(v) = p.get("corners").filter(|v| v.is_boolean()) { + q["corners"] = v.clone(); + } + q +} + /// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the /// command's journal entry, so replaying it scales the same way whatever the preference is then. fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result { @@ -252,7 +276,7 @@ fn grid(s: &mut Session, p: &Value) -> Result { .enumerate() .filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center())))) .collect(); - transform_each(s, "Arrange in Grid", false, &xfs)?; + transform_each(s, "Arrange in Grid", p, false, &xfs)?; Ok(json!({ "count": n })) } @@ -288,7 +312,7 @@ fn offset(s: &mut Session, p: &Value) -> Result { (id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) })) }) .collect(); - transform_each(s, "Offset Objects", false, &xfs)?; + transform_each(s, "Offset Objects", p, false, &xfs)?; Ok(json!({ "count": items.len() })) } @@ -300,8 +324,9 @@ fn swap(s: &mut Session, p: &Value) -> Result { let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) }; let (ba, bb) = (box_of(s, a)?, box_of(s, b)?); let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes); + let to = |o: &OrientedBox| with_corners(to(o), p); let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)]; - transform_each(s, "Swap Objects", strokes, &xfs)?; + transform_each(s, "Swap Objects", p, strokes, &xfs)?; Ok(json!({})) } @@ -328,9 +353,9 @@ fn replace(s: &mut Session, p: &Value) -> Result { } _ => None, }; - xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?)); + xfs.push((id, object_bounds_transform(s, &with_corners(place(b.center(), size, strokes), p), top)?)); } - let p = json!({ "strokes": strokes }); + let p = scaling_params(p, strokes); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &[top])?; let ids = s.edit("Replace with Top Object", |d, sel| { @@ -360,7 +385,8 @@ fn size(s: &mut Session, p: &Value) -> Result { let proportional = switch_or(p, "proportional", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); let strokes = scale_strokes(s, p, C)?; - let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }); + let mut q = + with_corners(json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }), p); if let Some(w) = width { q["width"] = json!(w); } @@ -373,7 +399,7 @@ fn size(s: &mut Session, p: &Value) -> Result { xfs.push((id, object_bounds_transform(s, &q, id)?)); } } - transform_each(s, "Set Size of Each", strokes, &xfs)?; + transform_each(s, "Set Size of Each", p, strokes, &xfs)?; Ok(json!({ "count": xfs.len() })) } @@ -449,39 +475,21 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { }; let mut xf = Affine::IDENTITY; if let Some(q) = &wanted { - let mut q = q.clone(); + let mut q = with_corners(q.clone(), p); q["reference"] = json!(reference); q["strokes"] = json!(strokes); - xf = object_bounds_transform(s, &q, id)?; + // Any scale the source's size asks for, however small. + xf = object_bounds_transform_keeping(s, &q, id, 0.0)?; } + // Rotation and the fit below keep the reference point in place. + let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); + let turned = Affine::rotate_about(-turn.to_radians(), at); if turn.abs() > 1e-9 { - // Rotation uses the reference point that sizing keeps in place. - let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); - xf = Affine::rotate_about(-turn.to_radians(), at) * xf; + xf = turned * xf; } if wanted.is_some() { - let sc = scaling(s, &json!({ "strokes": strokes })); - let d = &s.doc()?.doc; - let symbols = d.symbol_boxes(); - let measure = |xf| { - d.node(id).and_then(|n| { - let mut n = n.clone(); - transform_node(&mut n, xf, sc, true); - let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO }; - effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure()) - }) - }; - let misses = |measured: Option| { - measured.is_none_or(|r| match size { - "width" => (r.width() - w).abs() > 1e-6, - "height" => (r.height() - h).abs() > 1e-6, - _ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6, - }) - }; - // The sized and turned object, measured in its final frame, must have the size asked for. - if misses(measure(xf)) { - return Err(bad(C, format!("object {} can't take the requested size", id.0))); - } + let fit = Fit { at, refi: reference as usize, goal: match_goal(size, (w, h), b.rect), strokes }; + xf = fit_turned(s, p, id, (xf, turned), fit).ok_or_else(|| bad(C, format!("object {} can't take the requested size", id.0)))?; } xfs.push((id, xf)); } @@ -508,7 +516,8 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { if xfs.is_empty() && !restack { return Ok(count); } - let q = json!({ "strokes": strokes, "patterns": patterns }); + let mut q = scaling_params(p, strokes); + q["patterns"] = json!(patterns); let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &q); sc.patterns = transform_patterns(s, &q, &ids)?; @@ -529,6 +538,82 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { Ok(count) } +/// The size a target of Match Objects ends with: for `size` "width" ("height") the source's width +/// `w` (height `h`), the other side following in proportion to the target's box `b`; for "both", the +/// source's width and height. +fn match_goal(size: &str, (w, h): (f64, f64), b: Rect) -> [f64; 2] { + let follow = |side: f64, from: f64, to: f64| if from > 1e-9 { side * to / from } else { side }; + match size { + "width" => [w, follow(b.height(), b.width(), w)], + "height" => [follow(b.width(), b.height(), h), h], + _ => [w, h], + } +} + +/// What [`fit_turned`] fits a target of Match Objects to. +struct Fit { + /// The target's reference point, which stays in place. + at: Point, + /// That point's index on the 9-point grid. + refi: usize, + /// The width and height wanted ([`match_goal`]). + goal: [f64; 2], + /// Scale Strokes & Effects. + strokes: bool, +} + +/// `xf`, which sizes and turns object `id`, made to give the object the size `fit.goal` (within +/// 1e-6 of the larger of 1 and each side) as `object.setBounds` measures it in the frame the object +/// ends in. When it misses, for example when a stroke or an effect does not turn with the art, +/// scales in that frame are fitted with [`refit_drawn`] from the object turned by `turned` alone, +/// and point `fit.refi` of the fitted box goes to `fit.at`. The object is measured before Align to +/// Pixel Grid snaps it, as every transform snaps it after. `None` when no scale gives the size. +fn fit_turned(s: &mut Session, p: &Value, id: NodeId, (xf, turned): (Affine, Affine), fit: Fit) -> Option { + let Fit { at, refi, goal, strokes } = fit; + let sc = scaling(s, &scaling_params(p, strokes)); + let how = s.bounds_measure(); + let d = &s.doc().ok()?.doc; + let symbols = d.symbol_boxes(); + let n = d.node(id)?; + let moved = |xf: Affine| { + let mut n = n.clone(); + n.transform(xf, sc); + n + }; + // The frame the turn gives; sizing can leave the art without a width or a height to show it. + let frame = OrientedBox { angle: moved(turned).bbox_angle, rect: Rect::ZERO }; + let to_local = frame.to_doc().inverse(); + let measure = |xf: Affine| effects::preview::bounds_in_with(&symbols, &moved(xf), to_local, how); + let tolerances = goal.map(|side| 1e-6 * side.max(1.0)); + let fits = |r: Rect| [r.width(), r.height()].into_iter().zip(goal).zip(tolerances).all(|((v, g), t)| (v - g).abs() <= t); + let keeps_angle = |xf: Affine| vectorcraft_geom::normalize_deg(moved(xf).bbox_angle - frame.angle).abs() <= 1e-6; + let rp = frame.to_local(at); + // `xf` with point `refi` of the box as measured moved to the reference point's place: a stroke + // or an effect that does not turn with the art moves it. + let placed = |xf: Affine| -> Option<(Affine, Rect)> { + let b = measure(xf)?; + let correction = rp - vectorcraft_geom::reference_point(b, refi); + if correction.x.abs() <= 1e-12 && correction.y.abs() <= 1e-12 { + return Some((xf, b)); + } + let xf = frame.conjugate(Affine::translate(correction)) * xf; + Some((xf, measure(xf)?)) + }; + if let Some((xf, _)) = placed(xf).filter(|(xf, b)| fits(*b) && keeps_angle(*xf)) { + return Some(xf); + } + // The sizing above can leave the art without a width or a height that the turned object needs, + // so the fit starts again from the object as it is, turned. + let scaled = |sx: f64, sy: f64| { + frame.conjugate(Affine::translate(rp.to_vec2()) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-rp.to_vec2())) * turned + }; + let now = measure(turned)?; + let ratio = |g: f64, v: f64| if v > 1e-9 { g / v } else { 1.0 }; + let start = (ratio(goal[0], now.width()), ratio(goal[1], now.height())); + let (sx, sy, _) = refit_drawn(|sx, sy| measure(scaled(sx, sy)), refi, goal, start, [true, true], Some(tolerances))?; + placed(scaled(sx, sy)).filter(|(xf, b)| fits(*b) && keeps_angle(*xf)).map(|(xf, _)| xf) +} + /// The sets of two or more of `items` (each in the order given) whose rects overlap or touch, /// chains included, among items of the same key (parent). A sweep along x: only the rects still /// open where each one starts are compared with it. @@ -767,8 +852,8 @@ fn sort(s: &mut Session, p: &Value) -> Result { json!({ "width": w * k, "height": h * k, "strokes": strokes }) } }; - xfs.push((o.id, object_bounds_transform(s, &q, o.id)?)); + xfs.push((o.id, object_bounds_transform(s, &with_corners(q, p), o.id)?)); } - transform_each(s, "Sort Objects", strokes, &xfs)?; + transform_each(s, "Sort Objects", p, strokes, &xfs)?; Ok(count) } diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 265ab50a6a..b87d30af42 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -603,6 +603,16 @@ fn match_size_refuses_a_target_with_no_width() { assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line)); } +#[test] +fn match_size_refuses_a_target_with_no_width_for_a_narrow_tall_source() { + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 100.0, 0.0, 0.05, 100000.0); + select(&mut s, &[line, b]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"size": "both"})]); +} + #[test] fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() { let mut s = session(); @@ -704,6 +714,138 @@ fn swap_replays_with_the_stroke_scaling_it_ran_with() { replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true})); } +/// Running `cmd` with Scale Corners on scales the 2 pt corners of two rounded squares with them, +/// and replaying its journal entry after the preference is turned off scales them the same way. +fn replays_the_corner_scaling_it_ran_with(cmd: &str, p: Value) { + let mut s = session(); + let square = |s: &mut Session, x: f64, w: f64| { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": w, "height": w, "radius": 2})).unwrap()["id"].as_u64().unwrap()) + }; + let a = square(&mut s, 0.0, 10.0); + let b = square(&mut s, 100.0, 20.0); + let shapes = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind))); + out.sort(); + out + }; + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap(); + select(&mut s, &[a, b]); + s.execute(cmd, &p).unwrap(); + let ran = shapes(&s); + let (id, q) = s.journal.last().unwrap().clone(); + assert_eq!(id, cmd); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap(); + select(&mut s, &[a, b]); + s.replay(&id, &q).unwrap(); + assert_eq!(shapes(&s), ran, "{cmd} replayed with other corners"); +} + +#[test] +fn match_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); +} + +#[test] +fn set_size_of_each_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.size", json!({"width": 30, "height": 30})); +} + +#[test] +fn swap_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.swap", json!({"size": true})); +} + +#[test] +fn replace_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.replace", json!({"fit": "bounds"})); +} + +#[test] +fn match_size_reaches_a_size_that_pixel_alignment_then_snaps() { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + select(&mut s, &[target]); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 15.5, 15.5); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "width"})).unwrap(); + let b = bounds(&s, target); + assert!((b.width() - 15.5).abs() <= 1.0 && (b.height() - 15.5).abs() <= 1.0, "{b:?}"); +} + +#[test] +fn match_size_fits_a_transform_copy_once_the_target_is_turned() { + for size in ["width", "both"] { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 30.0, 20.0); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": size, "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}"); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}"); + if size == "both" { + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}"); + } + } +} + +#[test] +fn match_size_fits_a_turned_target_whose_copy_fills_the_height_before_the_turn() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveV": 10, "copies": 1}})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 20.0, 5.0); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}"); +} + +#[test] +fn match_size_keeps_the_center_of_a_turned_target_whose_copy_stays_on_the_page() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 2000.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap(); + let center = s.transform_box(&[target]).unwrap().center(); + let source = rect(&mut s, 100.0, 100.0, 11.0, 20.0); + s.execute("object.rotate", &json!({"angle": 180})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.center() - center).hypot() < 1e-6, "{measured:?} {center:?}"); +} + +#[test] +fn match_size_takes_a_huge_object_down_to_a_point() { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 20000.0, 20000.0); + let source = rect(&mut s, 100.0, 0.0, 1.0, 1.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap(); + let b = bounds(&s, target); + assert!((b.width() - 1.0).abs() < 1e-6 && (b.height() - 1.0).abs() < 1e-6, "{b:?}"); +} + #[test] fn match_refuses_bad_params() { let mut s = session(); diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index b2d857a464..7d91648946 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -33,7 +33,7 @@ mod transform; pub(crate) use align::choice; pub(crate) use arrange::group_nodes; -pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; +pub(crate) use bounds::{bounds_rewrite, object_bounds_transform, object_bounds_transform_keeping, refit_drawn}; pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index a24e71c9a6..205ee265e9 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -45,7 +45,13 @@ pub(crate) fn bounds_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<( /// `object.setBounds` measures them (Use Preview Bounds, `strokes`, `reference`, `proportional`), /// whatever anchors are direct-selected. The art keeps at least 1e-4 of its width and height. pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Result { - match bounds_transform(s, p, vec![id], 1e-4, false)? { + object_bounds_transform_keeping(s, p, id, 1e-4) +} + +/// [`object_bounds_transform`] with the art keeping at least `least` of its width and height +/// (0: any scale the values ask for). +pub(crate) fn object_bounds_transform_keeping(s: &Session, p: &Value, id: NodeId, least: f64) -> Result { + match bounds_transform(s, p, vec![id], least, false)? { Bounds::Objects(_, xf) => Ok(xf), Bounds::Anchors(..) => Err(EngineError::Other("no bounds".into())), } @@ -163,7 +169,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor // smaller than that reach. Strokes and effects that scale shrink the reach with the art, so // the search then starts from the size wanted over the size as drawn. let seed = |s: f64, size: f64, now: f64| if s <= 0.0 && size > 0.0 && now > 1e-9 { size / now } else { s }; - refit_drawn(measure, refi, [w, h], (seed(sx, w, v.width()), seed(sy, h, v.height())), [g.width() > 1e-9, g.height() > 1e-9]) + refit_drawn(measure, refi, [w, h], (seed(sx, w, v.width()), seed(sy, h, v.height())), [g.width() > 1e-9, g.height() > 1e-9], None) } else { Spans::measure(d, &ids, &frame, strokes).refit(rp, refi, [w, h], (sx, sy, new_rp)) }; @@ -187,23 +193,26 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor /// scale that `free` marks false stays as it is. The search stops when both sizes are within 1e-9 /// of the sizes wanted (of the largest of 1 and those sizes), when no scale moves, when `measure` /// finds no box, or after 16 steps, and returns the scales that came nearest. `None` when `measure` -/// finds no box for `start`. -fn refit_drawn( +/// finds no box for `start`. Each stopping tolerance in `tolerances`, when given, is capped at +/// the default tolerance. +pub(crate) fn refit_drawn( measure: impl Fn(f64, f64) -> Option, refi: usize, size: [f64; 2], start: (f64, f64), free: [bool; 2], + tolerances: Option<[f64; 2]>, ) -> Option<(f64, f64, Point)> { let [w, h] = size; let tolerance = 1e-9 * w.max(h).max(1.0); + let tolerances = tolerances.unwrap_or([tolerance; 2]).map(|t| t.min(tolerance)); let miss = |b: Rect| (b.width() - w).abs() + (b.height() - h).abs(); let (mut sx, mut sy) = start; let mut b = measure(sx, sy)?; let mut best = (sx, sy, b); for _ in 0..16 { let f = [b.width() - w, b.height() - h]; - if f[0].abs() <= tolerance && f[1].abs() <= tolerance { + if f[0].abs() <= tolerances[0] && f[1].abs() <= tolerances[1] { break; } // How the width and the height change with the x scale (`a`) and the y scale (`c`). diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..78e18a75f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17581,7 +17581,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame after it is turned, with no smallest scale; the side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. A replay of the command's journal entry scales strokes, corners and pattern tiles as the run did. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | From 77ec5ee65de928e53c82b8a19e0bb9b48cb324b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:22:46 -0800 Subject: [PATCH 012/103] MCP: tool.options params text names its missing and wrongly typed tool errors --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index d1d1e480db..5bbbb75fe8 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens (a missing or null tool is an error, and so is one that is not a string):hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5626f3d318..d4bfc9751f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1193,7 +1193,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens (a missing or null tool is an error, and so is one that is not a string):hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/docs/mcp.md b/docs/mcp.md index ba3253052b..101353cc93 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15637,7 +15637,7 @@ are also the ones an Alt smoothing drag with the Pencil, Paintbrush or Blob Brus in points. `tool.options {tool}` opens what double-clicking the tool's button opens (its params doc lists every tool), in the -desktop app. The Flare tool's are its Flare Tool Options (dialog `flareOptions`): `diameter` and `pathLength` (pt), +desktop app. A missing or null `tool` is an error, and so is a `tool` that is not a string. The Flare tool's are its Flare Tool Options (dialog `flareOptions`): `diameter` and `pathLength` (pt), `opacity`, `brightness`, `growth`, `fuzziness`, `longest`, `rayFuzziness` and `largest` (%), `rays`, `rings`, `direction` (°), and `raysOn` and `ringsOn` (the Rays and Rings checkboxes; off, the flare has none). While Alt (Option on macOS) is held, the dialog's Cancel button reads Reset. Reset puts every option back to the tool's default, From c7cb678fd074a979e69181367e5a379690ee5472 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:43:16 -0800 Subject: [PATCH 013/103] Tests: the plug-in param dialog test checks the command registers during the call --- crates/ui-egui/src/dialogs/command.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index dbfb59875d..902afd5865 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -1251,13 +1251,17 @@ mod tests { let mut app = windowed(); app.session.load_plugins_in_background(true); app.session.attach_plugin_store(dir.clone()); + let command = format!("plugin.{id}.look"); let loading = app.session.plugins_loading(); - let opened = app.run("ui.paramDialog", json!({"command": format!("plugin.{id}.look"), "params": {}})); - let shown = app.command_dialog.open.is_some(); + let before = vectorcraft_engine::find_command(&command).is_some(); + let opened = app.run("ui.paramDialog", json!({"command": command, "params": {}})); + let (after, shown) = (vectorcraft_engine::find_command(&command).is_some(), app.command_dialog.open.is_some()); vectorcraft_plugins::registry::remove(id); let _ = std::fs::remove_dir_all(&dir); assert!(loading, "the store loads in the background"); + assert!(!before, "the plug-in's command is not registered while it loads"); opened.unwrap(); + assert!(after, "the plug-in installed before the dialog opened"); assert!(shown, "the plug-in's dialog opens"); } From 9990ba7cdee54a5c51f2af317a19a98ba8191b9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:37:24 -0800 Subject: [PATCH 014/103] Match Objects: refuse sizes a fixed effect keeps a target from reaching A size that a stroke or an effect that does not scale keeps a target from reaching, alone or together with the other side, was accepted within the old 1e-6 fit tolerance. Fits now must land within 1e-9 of each side, so such a match is refused. The fit's angle checks use transformed_angle instead of transforming the whole target, keeping a layer's own angle. --- ROADMAP.md | 2 +- crates/engine/src/cmd/addons/arrange.rs | 24 ++++++++------ crates/engine/src/cmd/addons/arrange/tests.rs | 31 +++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 47 insertions(+), 12 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 25caa796ef..d435157c57 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -163,7 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). -- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). Sizes are measured in each object's bounding-box frame after it is turned, with no smallest scale. A side that follows in proportion follows the object's box before the match. Pixel-aligned art is measured before it snaps. A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). Sizes are measured in each object's bounding-box frame after it is turned, with no smallest scale. A side that follows in proportion follows the object's box before the match. Pixel-aligned art is measured before it snaps. A size that a stroke or an effect that does not scale keeps a target from reaching is refused. A VectorCraft addition: headline numbers unchanged. - 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 0880d22b2d..0e30f07638 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -97,7 +97,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -565,7 +565,7 @@ struct Fit { } /// `xf`, which sizes and turns object `id`, made to give the object the size `fit.goal` (within -/// 1e-6 of the larger of 1 and each side) as `object.setBounds` measures it in the frame the object +/// 1e-9 of the larger of 1 and each side) as `object.setBounds` measures it in the frame the object /// ends in. When it misses, for example when a stroke or an effect does not turn with the art, /// scales in that frame are fitted with [`refit_drawn`] from the object turned by `turned` alone, /// and point `fit.refi` of the fitted box goes to `fit.at`. The object is measured before Align to @@ -582,14 +582,20 @@ fn fit_turned(s: &mut Session, id: NodeId, (xf, turned): (Affine, Affine), fit: n.transform(xf, sc); n }; + // The angle the object's box ends at after `xf`, as `Node::transform` sets it (a layer keeps its own). + let angle_after = |xf: Affine| if n.is_layer() { n.bbox_angle } else { vectorcraft_doc::orient::transformed_angle(n.bbox_angle, xf) }; // The frame the turn gives; sizing can leave the art without a width or a height to show it. - let frame = OrientedBox { angle: moved(turned).bbox_angle, rect: Rect::ZERO }; + let frame = OrientedBox { angle: angle_after(turned), rect: Rect::ZERO }; let to_local = frame.to_doc().inverse(); let measure = |xf: Affine| effects::preview::bounds_in_with(&symbols, &moved(xf), to_local, how); - let tolerances = goal.map(|side| 1e-6 * side.max(1.0)); + let tolerances = goal.map(|side| 1e-9 * side.max(1.0)); let fits = |r: Rect| [r.width(), r.height()].into_iter().zip(goal).zip(tolerances).all(|((v, g), t)| (v - g).abs() <= t); - let keeps_angle = |xf: Affine| vectorcraft_geom::normalize_deg(moved(xf).bbox_angle - frame.angle).abs() <= 1e-6; + let keeps_angle = |xf: Affine| vectorcraft_geom::normalize_deg(angle_after(xf) - frame.angle).abs() <= 1e-6; let rp = frame.to_local(at); + // The object turned by `turned`, then scaled by `sx` and `sy` in the frame about the reference point. + let scaled = |sx: f64, sy: f64| { + frame.conjugate(Affine::translate(rp.to_vec2()) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-rp.to_vec2())) * turned + }; // `xf` with point `refi` of the box as measured moved to the reference point's place: a stroke // or an effect that does not turn with the art moves it. let placed = |xf: Affine| -> Option<(Affine, Rect)> { @@ -601,19 +607,17 @@ fn fit_turned(s: &mut Session, id: NodeId, (xf, turned): (Affine, Affine), fit: let xf = frame.conjugate(Affine::translate(correction)) * xf; Some((xf, measure(xf)?)) }; - if let Some((xf, _)) = placed(xf).filter(|(xf, b)| fits(*b) && keeps_angle(*xf)) { + let accepts = |xf: Affine, b: Rect| fits(b) && keeps_angle(xf); + if let Some((xf, _)) = placed(xf).filter(|(xf, b)| accepts(*xf, *b)) { return Some(xf); } // The sizing above can leave the art without a width or a height that the turned object needs, // so the fit starts again from the object as it is, turned. - let scaled = |sx: f64, sy: f64| { - frame.conjugate(Affine::translate(rp.to_vec2()) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-rp.to_vec2())) * turned - }; let now = measure(turned)?; let ratio = |g: f64, v: f64| if v > 1e-9 { g / v } else { 1.0 }; let start = (ratio(goal[0], now.width()), ratio(goal[1], now.height())); let (sx, sy, _) = refit_drawn(|sx, sy| measure(scaled(sx, sy)), refi, goal, start, [true, true], Some(tolerances))?; - placed(scaled(sx, sy)).filter(|(xf, b)| fits(*b) && keeps_angle(*xf)).map(|(xf, _)| xf) + placed(scaled(sx, sy)).filter(|(xf, b)| accepts(*xf, *b)).map(|(xf, _)| xf) } /// The sets of two or more of `items` (each in the order given) whose rects overlap or touch, diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 7a66aef2c2..904e0461bb 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -872,6 +872,37 @@ fn match_size_keeps_the_center_of_a_turned_target_whose_copy_stays_on_the_page() assert!((measured.center() - center).hypot() < 1e-6, "{measured:?} {center:?}"); } +#[test] +fn match_size_refuses_a_width_below_a_fixed_transform_copy() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 100000.05, "copies": 1}})).unwrap(); + let before = s.transform_box(&[target]).unwrap(); + assert!((before.rect.width() - 100020.05).abs() < 1e-6, "{before:?}"); + let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let out = s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})); + assert!(out.is_err(), "{out:?} {:?}", s.transform_box(&[target])); +} + +#[test] +fn match_size_refuses_dimensions_a_fixed_rotated_copy_cannot_reach_together() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute( + "effect.apply", + &json!({"effect": "distort.transform", "item": null, "params": {"rotate": 90, "reference": 4, "moveH": 99990.05, "copies": 1}}), + ) + .unwrap(); + let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]); +} + #[test] fn match_size_takes_a_huge_object_down_to_a_point() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index f2cdb5c108..34c67ccd29 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17584,7 +17584,7 @@ records the value used, and a replay of that entry scales corners the same way w | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference); `corners` (the Scale Corners preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `corners` (the Scale Corners preference); `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes`; `corners` (the Scale Corners preference) | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `corners` (the Scale Corners preference); `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame after it is turned, with no smallest scale; the side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `corners` (the Scale Corners preference); `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame after it is turned, with no smallest scale; the side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, a `size` that takes a width or a height the source or a target does not have, a `size` that a stroke or an effect that does not scale keeps a target from reaching, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `corners` (the Scale Corners preference); `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | From 99cf25f90c4c26ad6d79472165fef6de63964933 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:33:39 -0800 Subject: [PATCH 015/103] Scripts: closing a Color Picker ends only the screen sample it started Stopping or quitting the run that waits at app.showColorPicker, and closing any Color Picker, now ends a screen color sample that picker started and drops a sampled color it has not taken yet. A sample started for the fill, the stroke or another picker keeps running. The test that the script's picker shows no preview now has a selected object and checks that no preview edit begins, so it fails when the picker's Target::Script exclusion is removed. --- crates/ui-egui/src/dialogs/color_picker.rs | 5 +++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/screen_color.rs | 32 ++++++++++++++++++++++ crates/ui-egui/src/screen_color/tests.rs | 29 ++++++++++++++++++++ crates/ui-egui/src/tests/script_dialogs.rs | 28 +++++++++++++++++++ docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 7 files changed, 98 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 9b64bd2dd6..7cb567b731 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -263,10 +263,12 @@ pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script { .. })).map(|o| o.id) } -/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. +/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. A +/// screen pick the picker started ends with it; a pick another owner started keeps running. pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(id) = script_picker(app) else { return }; app.color_dialogs.pickers.retain(|o| o.id != id); + screen_color::cancel_for(app, ctx, owner(id)); if let Some(dialogs) = app.dialogs() { dialogs.with(|h| { h.cancel_by_id(ctx, id); @@ -316,6 +318,7 @@ fn settle(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &craft::ui::sh }) }); let Some((current, gesture)) = live else { + screen_color::cancel_for(app, ctx, owner(open.id)); let result = dialogs.with(|h| h.take_by_id::(open.id)); finish(app, dialogs, open, result); return false; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..f08a6a35d3 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1121,7 +1121,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.sampleScreenColor", "Sample Color from Screen", "", - "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", + "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", ), ( "ui.newBrush", diff --git a/crates/ui-egui/src/screen_color.rs b/crates/ui-egui/src/screen_color.rs index c644b9b7a2..d7495adb83 100644 --- a/crates/ui-egui/src/screen_color.rs +++ b/crates/ui-egui/src/screen_color.rs @@ -41,6 +41,33 @@ fn remember_doc(app: &VectorcraftApp, ctx: &egui::Context) { ctx.data_mut(|d| d.insert_temp(doc_key(), uid)); } +/// Where the owner of the running pick is kept, as a hash of its key. +fn owner_key() -> egui::Id { + egui::Id::unique("screen-color-owner") +} + +fn owner_hash(owner: impl Hash) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + owner.hash(&mut hasher); + hasher.finish() +} + +fn remember_owner(ctx: &egui::Context, owner: impl Hash) { + let key = owner_hash(owner); + ctx.data_mut(|d| d.insert_temp(owner_key(), key)); +} + +/// Ends the running pick when `owner` started it, and drops a color `owner` has not taken yet; a +/// pick another owner started keeps running. The next pass finishes a capture the cancel ends. +pub(crate) fn cancel_for(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash) { + let started_by = ctx.data(|d| d.get_temp::(owner_key())); + if app.screen_pick.busy() && started_by == Some(owner_hash(&owner)) { + app.screen_pick.cancel(); + ctx.request_repaint(); + } + let _ = app.screen_pick.take(owner); +} + /// The platform can capture the screen: the shell's capabilities say so and no capture has said it /// cannot. Without a window there is nothing to capture. pub fn available(app: &VectorcraftApp) -> bool { @@ -65,6 +92,10 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result { } if let Some(ctx) = app.ui_ctx.clone() { remember_doc(app, &ctx); + match picker { + Some(id) => remember_owner(&ctx, crate::dialogs::color_picker::owner(id)), + None => remember_owner(&ctx, if stroke { STROKE } else { FILL }), + } } match picker { Some(id) => app.screen_pick.start(crate::dialogs::color_picker::owner(id)), @@ -78,6 +109,7 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result { pub(crate) fn hold(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash, gesture: ScreenPickGesture) -> Option { if !app.screen_pick.busy() { remember_doc(app, ctx); + remember_owner(ctx, &owner); } app.screen_pick.hold(ctx, owner, gesture) } diff --git a/crates/ui-egui/src/screen_color/tests.rs b/crates/ui-egui/src/screen_color/tests.rs index f36e669422..414a1a41c0 100644 --- a/crates/ui-egui/src/screen_color/tests.rs +++ b/crates/ui-egui/src/screen_color/tests.rs @@ -89,6 +89,35 @@ fn the_color_pickers_eyedropper_samples_into_it() { assert_eq!(paints(&app).0, "#123456"); } +/// Closing the Color Picker ends the sample its eyedropper started. +#[test] +fn closing_the_color_picker_ends_its_sample() { + let (mut app, ctx) = app(); + app.run("ui.colorPicker", json!({})).unwrap(); + let id = app.color_dialogs.pickers.last().unwrap().id; + assert_eq!(hold(&mut app, &ctx, crate::dialogs::color_picker::owner(id), ScreenPickGesture::Clicked), None); + assert!(app.screen_pick.busy()); + assert!(app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id))); + let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::color_picker::pump(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.color_dialogs.pickers.is_empty()); + assert!(!app.screen_pick.busy(), "the sample ends with the picker"); +} + +/// Ending a picker's pick drops the color it sampled and has not taken yet; another owner's color +/// stays. +#[test] +fn ending_a_pick_drops_the_color_its_owner_has_not_taken() { + let (mut app, ctx) = app(); + for own in [true, false] { + assert_eq!(hold(&mut app, &ctx, "picker", ScreenPickGesture::Clicked), None); + finish(&mut app, &ctx, Ok(srgba("#123456"))); + assert!(!app.screen_pick.busy(), "the capture finished"); + cancel_for(&mut app, &ctx, if own { "picker" } else { "other" }); + assert_eq!(take(&mut app, &ctx, "picker").is_some(), !own, "own {own}"); + } +} + /// A canceled capture changes nothing; a failed one reaches the status line. #[test] fn cancel_and_errors_leave_the_art_alone() { diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 5dfa72ff39..832a96e875 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -352,6 +352,8 @@ fn answer_picker(app: &mut VectorcraftApp, ok: bool) { #[test] fn the_color_picker_waits_and_answers_the_run() { let mut app = app(); + // A selected object, which a picker that previews would paint. + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap(); let gray = "var g = new GrayColor(); g.gray = 40;"; start( &mut app, @@ -364,7 +366,10 @@ fn the_color_picker_waits_and_answers_the_run() { assert!(!is_open::(&app), "the picker opens in place of a notice"); set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); let ctx = app.ui_ctx.clone().unwrap(); + app.ui.status.clear(); color_picker::pump(&mut app, &ctx); + // A preview would begin an edit, which the running script refuses with a status message. + assert_eq!(app.ui.status, "", "the picker starts no preview"); assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview"); answer_picker(&mut app, true); assert!(until_picker(&mut app), "the next call opens the picker again"); @@ -421,6 +426,29 @@ fn stopping_or_quitting_the_run_closes_its_color_picker() { assert_eq!(objects(&app), 0); } +#[test] +fn stopping_the_run_ends_only_the_screen_pick_its_color_picker_started() { + use craft::color_ui::ui::ScreenPickGesture; + let source = "var c = new RGBColor(); app.showColorPicker(c);"; + for own in [true, false] { + let mut app = app(); + start(&mut app, source); + assert!(until_picker(&mut app)); + let ctx = app.ui_ctx.clone().unwrap(); + let id = color_picker::script_picker(&app).unwrap(); + let started = if own { + crate::screen_color::hold(&mut app, &ctx, color_picker::owner(id), ScreenPickGesture::Clicked) + } else { + crate::screen_color::hold(&mut app, &ctx, "fill", ScreenPickGesture::Clicked) + }; + assert_eq!(started, None); + assert!(app.screen_pick.busy()); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert_eq!(app.screen_pick.busy(), !own, "own pick {own}: only the picker's own pick ends with it"); + } +} + #[test] fn the_color_picker_opens_on_the_scripts_color_with_only_web_colors_left_on() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index dd885ea436..d14c51a78b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3725,7 +3725,9 @@ run's active document (a document the script made included) is in CMYK, an RGB p color's `typename` can differ from the picker's model and from the color given. The picker opens on the color as given, whatever Only Web Colors was left at in another picker. OK with the color unchanged and Cancel return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting -end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: +end the run as they do at the other dialogs, and close the picker. They also end a screen color sample +(`ui.sampleScreenColor` with `picker`, or the picker's eyedropper) that the picker started, and drop a sampled color +it has not taken; a sample started for the fill, the stroke or another picker keeps running. A run with nobody to ask takes `{kind: "colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its range (a color key such as `"rgb 300 0 0"` is refused, not clamped), or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and `ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ab023f4b05..9986490a00 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1129,7 +1129,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. From 1c5a86785542d506f59e74a41b8ae80ee9a33e64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:47:05 -0800 Subject: [PATCH 016/103] =?UTF-8?q?3D:=20Render=20Settings=20=E2=80=BA=20R?= =?UTF-8?q?endered=20draws=20the=20solid=20as=20a=20lit=20image=20with=20s?= =?UTF-8?q?hadows=20from=20every=20light?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extrude & Bevel, Revolve, Inflate and Rotate take render.mode "rendered", with quality (low, medium or high: 1, 2 x 2 or 3 x 3 samples a pixel), resolution (null for Document Raster Effects Settings, or 1 to 2400 ppi) and background (transparent or white). The effect then draws its solid as one image made with craft-raster3d: a depth buffer, the effect's lights in linear light with the material's roughness and metallic, and shadow maps for each light, over the effect's vector shadow. The image lies where the vector faces lie: each mesh point goes through the projection the effect draws its faces with (MeshProjection). The shaded faces are drawn instead, and the status bar and the effect.apply and effect.setParams results carry a "warning", when the image would pass 16,777,216 pixels at one sample a pixel, or when the solid is painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, and for Revolve on a group or on a fill or stroke. The warning check measures the image without rasterizing it. The 3D and Materials panel's Render Settings menu gains Rendered and Low, Medium and High Quality. Each choice is one undo step for the selection, and each object keeps its other render settings. The effect-art cache now includes the document's raster resolution, so changing Document Raster Effects Settings redraws rendered images. Every craft-libs rev moves to 64383b59, which adds crates/raster3d. Docs: docs/three-d.md, docs/mcp.md, docs/target-app-parity.md. --- Cargo.lock | 226 +++++---- Cargo.toml | 80 +-- apps/vectorcraft-web/Cargo.toml | 2 +- crates/effects/Cargo.toml | 5 + crates/effects/src/catalog.rs | 8 +- crates/effects/src/lib.rs | 14 +- crates/effects/src/revolve.rs | 51 +- crates/effects/src/solids.rs | 65 ++- crates/effects/src/solids/rendered.rs | 490 ++++++++++++++++++ crates/effects/src/solids/rendered/tests.rs | 502 +++++++++++++++++++ crates/effects/src/solids/tests_shadow.rs | 2 +- crates/effects/src/solids/wireframe.rs | 93 +++- crates/effects/src/solids/wireframe/tests.rs | 31 +- crates/engine/src/cmd/effectcmd.rs | 19 +- crates/engine/src/tests/effectedit.rs | 23 + crates/render/src/fx/entries.rs | 1 + crates/render/src/fx/pixels.rs | 16 +- crates/render/src/fx/tests.rs | 31 ++ crates/render/src/live.rs | 13 +- crates/three-d/src/lib.rs | 20 +- crates/three-d/src/mesh.rs | 52 +- crates/three-d/src/solid.rs | 5 + crates/ui-egui/src/panels/tests_three_d.rs | 52 ++ crates/ui-egui/src/panels/three_d.rs | 72 ++- docs/mcp.md | 22 +- docs/target-app-parity.md | 1 + docs/three-d.md | 25 +- xtask/src/pdf_deps.rs | 2 +- 28 files changed, 1689 insertions(+), 234 deletions(-) create mode 100644 crates/effects/src/solids/rendered.rs create mode 100644 crates/effects/src/solids/rendered/tests.rs diff --git a/Cargo.lock b/Cargo.lock index f934cdf0b4..15dda43ef0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -626,12 +626,6 @@ dependencies = [ "cpufeatures 0.3.1", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -725,6 +719,17 @@ dependencies = [ "brotli-decompressor 5.0.3", ] +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.2", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -1184,19 +1189,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -1239,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-automation", "craft-behavior", @@ -1280,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "crc32fast", "flate2", @@ -1291,18 +1283,19 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "block2 0.6.2", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-graphics", "objc2-foundation 0.3.2", ] [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "rustix 1.1.6", ] @@ -1310,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1335,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1353,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-docpath", @@ -1371,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "crc32fast", "flate2", @@ -1380,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "egui", ] @@ -1388,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "md-5", "rayon", @@ -1397,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-cms", @@ -1422,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1433,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1443,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "rayon", ] @@ -1451,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1477,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "blake3", "craft-ecproj-format", @@ -1493,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "serde", ] @@ -1501,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1520,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-codepage", "encoding_rs", @@ -1532,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "serde", "serde_json", @@ -1542,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1562,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1581,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1590,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "cap-primitives", "craft-atomic", @@ -1613,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "gif", ] @@ -1626,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "flate2", ] @@ -1634,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1647,8 +1640,10 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ + "brotli 9.1.3", + "brotli-decompressor 6.3.2", "chrono", "fixed_decimal", "icu_calendar", @@ -1675,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-dds", "craft-jpeg", @@ -1702,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1720,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "thiserror 2.0.21", ] @@ -1728,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1739,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-host", "craft-i18n", @@ -1754,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-i18n", @@ -1768,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-host", @@ -1786,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1798,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "encoding_rs", "image", @@ -1809,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "chrono", "craft-codepage", @@ -1819,15 +1814,16 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ + "uds_windows", "winsafe", ] [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-keymap", @@ -1843,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1852,7 +1848,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "flate2", "serde", @@ -1863,7 +1859,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1875,12 +1871,12 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "async-channel", "async-io", "async-process", - "core-graphics2", + "craft-appkit", "craft-atomic", "craft-docpath", "craft-host", @@ -1890,6 +1886,8 @@ dependencies = [ "js-sys", "log", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "rfd", "serde", "serde_json", @@ -1906,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1915,7 +1913,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-host", @@ -1939,7 +1937,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1950,7 +1948,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-eps", "flate2", @@ -1964,7 +1962,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "encoding_rs", "flate2", @@ -1975,7 +1973,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "dispatch2", "egui", @@ -1985,10 +1983,19 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-raster3d" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2007,7 +2014,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-atomic", "craft-host", @@ -2024,7 +2031,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "fax", "hayro-ccitt", @@ -2035,7 +2042,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2056,7 +2063,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-keymap", @@ -2068,7 +2075,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2093,7 +2100,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "thiserror 2.0.21", ] @@ -2101,7 +2108,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2116,7 +2123,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-atomic", "craft-behavior", @@ -2131,7 +2138,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "serde", "thiserror 2.0.21", @@ -2141,7 +2148,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "serde", "thiserror 2.0.21", @@ -2150,7 +2157,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-keymap", @@ -2165,12 +2172,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2184,7 +2191,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-i18n", @@ -2200,7 +2207,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "accesskit", "craft-behavior", @@ -2238,7 +2245,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2249,7 +2256,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-host", @@ -2267,7 +2274,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-host", @@ -2288,7 +2295,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-host", @@ -2309,7 +2316,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-behavior", "craft-host", @@ -2328,7 +2335,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "base64 0.22.1", "chrono", @@ -2360,7 +2367,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "flate2", "serde", @@ -2371,7 +2378,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2381,7 +2388,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "js-sys", "serde_json", @@ -2392,7 +2399,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "winsafe", ] @@ -2400,7 +2407,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "craft-appkit", "craft-atomic", @@ -2432,7 +2439,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3787,16 +3794,16 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ - "brotli", + "brotli 8.0.4", "hayro-postscript", ] [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3814,7 +3821,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3832,12 +3839,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "flate2", "hayro-ccitt", @@ -4820,7 +4827,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4977,7 +4984,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=64383b5906b5a0a14fa4bea21dac379f2deae4bc#64383b5906b5a0a14fa4bea21dac379f2deae4bc" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -8697,6 +8704,7 @@ name = "vectorcraft-effects" version = "0.25.0" dependencies = [ "craft-image-codecs", + "craft-raster3d", "craft-svg", "image", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index fd73c23805..bff10fea65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,53 +10,55 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. -craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps. +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -196,13 +198,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index ce4d1d3d44..b12c246194 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "64383b5906b5a0a14fa4bea21dac379f2deae4bc", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml index e737bc5ad8..679284ff97 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -24,6 +24,11 @@ craft-svg = { workspace = true, features = ["tree-render"] } # The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg). svgtypes = "0.16" serde_json = { workspace = true } +# Render Settings › Rendered: the 3D effects' solids drawn as an image with depth and shadow maps. +craft-raster3d = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +craft-raster3d = { workspace = true, features = ["parallel"] } [dev-dependencies] vectorcraft-color = { workspace = true } diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index a71269ce58..1024d6fe0a 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,28 +241,28 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light with the shadows each casts on the solid, over the effect's shadow, and draws the shaded faces when the image can't be made; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Painted with the top fill (else the top stroke).", json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aef398c64e..5f87b5ac2a 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -97,14 +97,16 @@ pub use reshape::{ pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, }; +pub use solids::rendered::rendered_warning; pub use solids::{ BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic, - MeshGraphics, RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, - classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, - is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, - rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, - three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, - validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, + MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings, + SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, + graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, + names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, render_settings, rendered, renders_image, renders_wireframe, solid_art, + solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, + three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, + validate_three_d_params, view_options, with_graphic, }; pub use solids::{ GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 5d49c52de2..3f36ddb206 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -845,7 +845,7 @@ pub fn revolve_art(n: &Node) -> Option { /// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be /// resolved. pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { - art(doc, n, false) + art_reporting(doc, n, false, false, &mut None) } /// [`expand_revolve_art_in`] without a document. @@ -857,7 +857,7 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option { /// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared /// command and UI remain unchanged. pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { - art(doc, n, true) + art_reporting(doc, n, true, false, &mut None) } /// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on @@ -918,8 +918,9 @@ fn surface_meshes( graphics: bool, ) -> Result, String> { let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params)); + let projection = Some(vectorcraft_three_d::revolve_mesh_projection(b, options)); surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics) - .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, ..m }).collect()) + .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, projection, ..m }).collect()) } /// [`surface_meshes`] in the default material. @@ -1083,13 +1084,13 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, n: &Node, expand: bool) -> Option { +pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option) -> Option { if !has_revolve(n) { return None; } let n = &*resolve_for(doc, n, "Revolve", false).ok()?; if is_container(n) { - return group_art(doc, n, expand); + return group_art(doc, n, expand, check_only, warning); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -1103,7 +1104,31 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - if crate::solids::renders_wireframe(fx) { + let p = merged_params(&fx.id, &fx.params); + // Rendered, the surface's image over its shadow; the shaded faces when it can't be made. + let image = crate::render_settings(&fx.id, &p).and_then(|settings| { + let result = if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) { + let b = path.bounds()?; + let (paint, opacity, _) = paint_of(item); + surface_meshes(&path, rule, b, fx, rule_options(fx, rule), (&paint, opacity, 1.0), true).and_then(|meshes| { + crate::solids::rendered::art(doc, n.id, &crate::solids::rendered::lighting(&fx.id, &p), &meshes, settings, check_only) + }) + } else { + Err(crate::solids::rendered::OPAQUE_ONLY.into()) + }; + crate::solids::rendered::reported(result, warning) + }); + if check_only { + return None; + } + if let Some(image) = image { + if let Some(b) = path.bounds() + && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), None).ok()? + { + children.push(Arc::new(shadow)); + } + children.push(image); + } else if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of the faces, with no shadow. children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?); } else { @@ -1132,6 +1157,12 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { for (original, item) in originals.into_iter().zip(&items) { if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = item.effects().get(index)?; + if crate::renders_image(fx) { + warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into()); + } + if check_only { + continue; + } let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); if crate::solids::renders_wireframe(fx) { @@ -1284,9 +1315,15 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool { /// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them, /// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when /// the effect is only on the group's own fills or strokes or when its members can't be revolved. -fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { +fn group_art(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option) -> Option { let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?; let fx = n.appearance.effects.get(index)?; + if crate::renders_image(fx) { + warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into()); + } + if check_only { + return None; + } let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); let b = union_bounds(&shapes)?; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 331352f6ae..988dc71430 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -41,7 +41,12 @@ pub use vectorcraft_three_d::SurfaceKind; pub(crate) mod shadow; pub(crate) mod wireframe; -pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in}; +pub use wireframe::{ + RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, renders_wireframe, + three_d_wireframe_in, +}; + +pub mod rendered; pub(crate) mod material; pub use material::MATERIAL; @@ -2036,12 +2041,38 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it /// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every /// surface of the object, and the surfaces. -fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option { +fn art_for( + doc: Option<&Document>, + n: &Node, + fx: &Effect, + shapes: &[Profile], + check_only: bool, + warning: &mut Option, +) -> Option { + if check_only && !crate::renders_image(fx) { + return Some((vec![], vec![])); + } // In wireframe mode the effect draws the edges of the faces it builds, with no shadow. if wireframe::renders_wireframe(fx) { return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?)); } let p = crate::merged_params(&fx.id, &fx.params); + // Rendered, the solids' image over the effect's shadow; the shaded faces when it can't be made. + if let Some(settings) = wireframe::render_settings(&fx.id, &p) { + let image = if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(|s| &s.items), has_masks(shapes)) { + meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES) + .and_then(|meshes| rendered::art(doc, n.id, &rendered::lighting(&fx.id, &p), &meshes, settings, check_only)) + } else { + Err(rendered::OPAQUE_ONLY.into()) + }; + let image = rendered::reported(image, warning); + if check_only { + return Some((vec![], vec![])); + } + if let Some(image) = image { + return Some((shadow_for(n.id, fx, shapes).ok()?, vec![image])); + } + } let cast = casts_shadow(&fx.id, &p); let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?; // A shadow past the limits draws the source path, as a solid past them does; commands report @@ -2806,12 +2837,16 @@ pub fn solid_art(n: &Node) -> Option { /// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be /// resolved. pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { + solid_art_reporting(doc, n, false, &mut None) +} + +pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only: bool, warning: &mut Option) -> Option { if !has_solid(n) { return None; } let n = &*resolve(doc, n, "").ok()?; if is_container(n) { - return group_solid_art(doc, n); + return group_solid_art(doc, n, check_only, warning); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -2820,7 +2855,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { let remaining: Vec; if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?; + let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], check_only, warning)?; children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. remaining = past_effect(&n.appearance.effects, index); @@ -2836,7 +2871,8 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { for (source, item) in sources.into_iter().zip(&paints) { if let Some((index, fx)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item))); - let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; + let (shadow, surfaces) = + art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], check_only, warning)?; let later: Vec = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); let with_later = |mut art: Arc| { Arc::make_mut(&mut art).appearance.effects = later.clone(); @@ -2865,11 +2901,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { /// geometry effects before it reshape the members, those after it bend the result as a whole; the /// group's own fills and strokes are not drawn. `None` when the effect is only on one of the /// group's own fills or strokes, or when its members can't become solids. -fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option { +fn group_solid_art(doc: Option<&Document>, n: &Node, check_only: bool, warning: &mut Option) -> Option { let (index, fx) = solid(&n.appearance.effects)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?; + let (shadow, surfaces) = art_for(doc, n, fx, &shapes, check_only, warning)?; let children = shadow.into_iter().chain(surfaces).collect(); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); @@ -3178,12 +3214,15 @@ pub struct SolidMesh { /// The surface's Roughness and Metallic ([`MATERIAL`]); [`vectorcraft_three_d::Material::DEFAULT`] /// for the 3D (Classic) effects. pub material: vectorcraft_three_d::Material, + /// The projection that takes the mesh's points to where the effect draws them on the page; + /// `None` when it is not known. + pub projection: Option, } impl SolidMesh { - /// A mesh painted `color`, with no graphics, in the default material. + /// A mesh painted `color`, with no graphics, in the default material, with no projection. pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self { - Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT } + Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT, projection: None } } } @@ -3288,17 +3327,17 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let material = material::of(&fx.id, &p); let mut out = vec![]; // A solid's parts with and without graphics count together against the limit. - let mut keep = |out: &mut Vec, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| { + let mut keep = |out: &mut Vec, (mesh, projection): (Mesh, _), (paint, opacity): (&Paint, f32), bounds: Rect| { split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity)) .into_iter() - .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, ..part }, limit)) + .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, projection, ..part }, limit)) }; if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (paint, opacity, _) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?; + keep(&mut out, vectorcraft_three_d::plane_meshed(&area, rule, b, view)?, (&paint, opacity), b)?; } } return Ok(out); @@ -3335,7 +3374,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) match solid.mesh() { Ok(mesh) => { let (paint, opacity, _) = paint_of(item, *member); - keep(&mut out, mesh, (&paint, opacity), bounds)?; + keep(&mut out, (mesh, solid.projection()), (&paint, opacity), bounds)?; } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} Err(e) => return Err(e), diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs new file mode 100644 index 0000000000..803e93d631 --- /dev/null +++ b/crates/effects/src/solids/rendered.rs @@ -0,0 +1,490 @@ +//! Render Settings › Rendered: the solids of a 3D effect drawn as one image, with a depth buffer, +//! the metallic-roughness shading of every light and the shadows each light casts on the solids, +//! instead of the shaded vector faces. The image lies on the page where the vector faces lie: each +//! mesh point goes through the projection the effect draws its faces with +//! ([`vectorcraft_three_d::MeshProjection`]). +use std::io::Cursor; +use std::sync::Arc; + +use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps}; +use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_three_d::{Light, MeshProjection}; + +use super::SolidMesh; +use super::wireframe::RenderSettings; + +/// The message a rendered image that can't be made is reported with; the effect then draws its +/// shaded faces. +pub const TOO_LARGE: &str = "The 3D render is too large; showing the shaded faces instead"; + +/// The message for a solid painted with something other than an opaque solid color in Normal +/// blending, or with graphics; the effect then draws its shaded faces. +pub const OPAQUE_ONLY: &str = "The 3D render shows opaque solid colors only; showing the shaded faces instead"; + +/// The message for Revolve on a group or on a fill or stroke, which draws its shaded faces. +pub const OBJECTS_ONLY: &str = "Revolve renders on a single object only; showing the shaded faces instead"; + +/// Why a visible 3D effect in rendered mode on `n` draws shaded faces instead of an image. +/// Messages are English, to be translated when displayed. `None` when no rendered effect falls back. +pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option { + let rendered = |fx: &vectorcraft_doc::Effect| fx.visible && crate::renders_image(fx); + if !n.appearance.effects.iter().any(rendered) && !n.appearance.items.iter().any(|i| i.effects().iter().any(rendered)) { + return None; + } + let mut warning = None; + if crate::has_revolve(n) { + let _ = crate::revolve::art_reporting(Some(doc), n, false, true, &mut warning); + } else { + let _ = super::solid_art_reporting(Some(doc), n, true, &mut warning); + } + warning +} + +/// The rendered image of `result`, or `None` after a successful check. An error keeps its message +/// in `warning` when no earlier reason is there; the caller then draws its shaded faces. +pub(crate) fn reported(result: Result>, String>, warning: &mut Option) -> Option> { + match result { + Ok(image) => image, + Err(message) => { + warning.get_or_insert(message); + None + } + } +} + +/// The lights a rendered image is shaded with, as the effect's shaded faces are. +#[derive(Clone, Debug, PartialEq)] +pub struct Lighting { + /// The directional lights ([`vectorcraft_three_d::Revolve::active_lights`]). + pub lights: Vec, + /// The ambient light, 0 to 2. + pub ambient: f64, + /// Shading on: off, the solids show their paint unlit, as the shaded faces do. + pub shade: bool, +} + +/// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page, +/// made with `samples` × `samples` samples a pixel. +#[derive(Clone, Debug, PartialEq)] +pub struct Rendered { + pub rect: Rect, + pub cols: u32, + pub rows: u32, + pub samples: u32, + pub pixels: Vec, +} + +/// The margin, as a share of the depth range, the solids' nearest and farthest points keep from the +/// ends of the depth buffer. +const DEPTH_MARGIN: f64 = 0.01; + +/// The largest share of the eye's distance a point may lie in front of the projection origin: at it +/// the vector faces stop growing ([`vectorcraft_three_d::MeshProjection::project`]). +const NEAREST: f64 = 0.999; + +/// The image of `meshes` lit by `lighting`, with `settings`, at the document's raster effects +/// resolution `doc_ppi` when the settings take it, within `limits`. An error ([`TOO_LARGE`]) when a +/// mesh has no projection or a different one, when a point lies at or behind the eye, when the +/// image has more pixels than `limits` allow even at one sample a pixel, or when the rasterizer +/// refuses the scene. `draft` takes one sample a pixel and draft shadow maps, as Low quality does. +pub fn render( + meshes: &[SolidMesh], + lighting: &Lighting, + settings: RenderSettings, + doc_ppi: f64, + draft: bool, + limits: &Limits, +) -> Result { + let too_large = || TOO_LARGE.to_string(); + let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, settings, doc_ppi, draft, limits)?; + let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k)).ok_or_else(too_large)?; + scene.ssaa = k; + #[cfg(test)] + RASTERIZATIONS.with(|n| n.set(n.get() + 1)); + if lighting.shade { + try_shadow_maps(&mut scene, low, limits).map_err(|_| too_large())?; + } + let (mut image, _) = try_render_cpu(&scene, limits).map_err(|_| too_large())?; + try_encode(&mut image).map_err(|_| too_large())?; + let pixels = image + .data + .iter() + .flat_map(|p| { + let p = if settings.white { [p[0] + 1.0 - p[3], p[1] + 1.0 - p[3], p[2] + 1.0 - p[3], 1.0] } else { *p }; + let a = p[3].clamp(0.0, 1.0); + let straight = |c: f32| if a > 0.0 { (c / a).clamp(0.0, 1.0) } else { 0.0 }; + [straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8) + }) + .collect(); + Ok(Rendered { rect, cols, rows, samples: k, pixels }) +} + +#[cfg(test)] +thread_local! { + /// How many rendered images enter the rasterizing path on this thread. + static RASTERIZATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The projection, clip matrix and raster dimensions within the image's sample budget. +struct Measured { + projection: MeshProjection, + rect: Rect, + z: [f64; 2], + clip: [[f32; 4]; 4], + cols: u32, + rows: u32, + samples: u32, + low: bool, +} + +/// Measure the image and choose its samples without building a scene or producing pixels. +fn measure(meshes: &[SolidMesh], settings: RenderSettings, doc_ppi: f64, draft: bool, limits: &Limits) -> Result { + let too_large = || TOO_LARGE.to_string(); + let projection = meshes.first().and_then(|m| m.projection).ok_or_else(too_large)?; + if meshes.iter().any(|m| m.projection != Some(projection)) { + return Err(too_large()); + } + let (bounds, z) = extent(meshes, projection).ok_or_else(too_large)?; + let cell = 72.0 / settings.resolution.unwrap_or(doc_ppi).clamp(1.0, 2400.0); + let (cols, rows) = ((bounds.width() / cell).ceil().max(1.0), (bounds.height() / cell).ceil().max(1.0)); + let pixels = cols * rows; + if pixels.is_nan() || pixels > limits.max_pixels as f64 { + return Err(too_large()); + } + let (cols, rows) = (cols as u32, rows as u32); + let rect = Rect::new(bounds.x0, bounds.y0, bounds.x0 + f64::from(cols) * cell, bounds.y0 + f64::from(rows) * cell); + let low = draft || settings.quality == 0; + let mut k = if low { 1 } else { settings.samples() }; + while k > 1 && pixels * f64::from(k * k) > limits.max_pixels as f64 { + k -= 1; + } + let clip = clip(projection, rect, z).ok_or_else(too_large)?; + Ok(Measured { projection, rect, z, clip, cols, rows, samples: k, low }) +} + +/// Check scene limits without allocating raster or shadow depth buffers. The counts follow +/// craft-raster3d at 64383b5906b5a0a14fa4bea21dac379f2deae4bc: lib.rs:178-223, +/// scene.rs:242-278,325-328, raster.rs:245-281,307-385,740-747 and +/// shadow.rs:109-135,262-276,316-356,413-449,500-515,533-538,576-657. +/// Measured solids lie inside the clip volume and use opaque, visible materials and directional +/// lights only, so each source triangle contributes one bounding box, without clipping or an +/// alpha-discard search. Raster and shadow work have separate budgets, as in the renderer. +fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> { + let m = measure(meshes, settings, ppi, false, limits)?; + let s = scene(meshes, lighting, m.projection, m.z, m.clip, (m.cols * m.samples, m.rows * m.samples)).ok_or(TOO_LARGE)?; + limits.check(s.width, s.height).map_err(|_| TOO_LARGE)?; + if s.indices.len() as u64 / 3 > limits.max_triangles || s.vertices.len() as u64 > limits.max_vertices || s.lights.len() > limits.max_lights { + return Err(TOO_LARGE.into()); + } + let transform = + |matrix: &[[f32; 4]], p: [f32; 3], row: usize| matrix[row][0] * p[0] + matrix[row][1] * p[1] + matrix[row][2] * p[2] + matrix[row][3]; + let mut work = 0u64; + for tri in s.indices.as_chunks::<3>().0 { + let mut points = [[0.0; 2]; 3]; + for (point, &i) in points.iter_mut().zip(tri) { + let p = s.vertices[i as usize].pos; + let c = [0, 1, 2, 3].map(|r| transform(&s.clip, p, r)); + // Refuse transforms whose rounding escapes the measured clip volume. + if !c.iter().all(|v| v.is_finite()) || c[3] <= 0.0 || c[2] < 0.0 || c[2] > c[3] { + return Err(TOO_LARGE.into()); + } + let iw = 1.0 / c[3]; + *point = [(f64::from(c[0] * iw) + 1.0) * 0.5 * f64::from(s.width), (1.0 - f64::from(c[1] * iw)) * 0.5 * f64::from(s.height)]; + } + let area = (0..3).map(|i| points[i][0] * points[(i + 1) % 3][1] - points[(i + 1) % 3][0] * points[i][1]).sum::(); + if !area.is_finite() { + return Err(TOO_LARGE.into()); + } + if area != 0.0 { + let pixels = bounding_work(points, [s.width, s.height]); + if pixels > 0 { + work = work.saturating_add(pixels + 1); + } + } + if work > limits.max_work { + return Err(TOO_LARGE.into()); + } + } + if s.lights.is_empty() || s.indices.is_empty() { + return Ok(()); + } + let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); + for v in &s.vertices { + for k in 0..3 { + lo[k] = lo[k].min(f64::from(v.pos[k])); + hi[k] = hi[k].max(f64::from(v.pos[k])); + } + } + let center = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5); + let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0; + let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &vec![1; s.lights.len()]); + let mut work = 0u64; + for (light, size) in s.lights.iter().zip(sizes) { + let Some(size) = size else { continue }; + let dir = light.dir.map(f64::from); + let eye = [0, 1, 2].map(|k| center[k] - dir[k] * radius * 2.0); + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let unit = |v: [f64; 3]| v.map(|x| x / dot(v, v).sqrt()); + let forward = unit(dir); + let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }; + let down = unit([0, 1, 2].map(|k| hint[k] - forward[k] * dot(hint, forward))); + let right = unit([ + down[1] * forward[2] - down[2] * forward[1], + down[2] * forward[0] - down[0] * forward[2], + down[0] * forward[1] - down[1] * forward[0], + ]); + let view = [right, down].map(|row| [row[0] as f32, row[1] as f32, row[2] as f32, (-dot(row, eye)) as f32]); + let focal = (f64::from(size) * 0.5 / radius) as f32; + for tri in s.indices.as_chunks::<3>().0 { + let points = [0, 1, 2].map(|k| { + let p = s.vertices[tri[k] as usize].pos; + [0, 1].map(|r| f64::from(transform(&view, p, r) * focal + size as f32 * 0.5)) + }); + let [a, b, c] = points; + let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + if !area.is_finite() { + return Err(TOO_LARGE.into()); + } + let texels = if area.abs() < 1e-12 { 0 } else { bounding_work(points, [size; 2]) }; + work = work.saturating_add(texels + 1); + if work > limits.max_work { + return Err(TOO_LARGE.into()); + } + } + } + Ok(()) +} + +/// The pixels inside a triangle's bounding box, clamped to the raster. +fn bounding_work(points: [[f64; 2]; 3], size: [u32; 2]) -> u64 { + [0, 1] + .map(|k| { + let lo = points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min).floor().clamp(0.0, f64::from(size[k])) as u64; + let hi = points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max).ceil().clamp(0.0, f64::from(size[k])) as u64; + hi.saturating_sub(lo) + }) + .into_iter() + .product() +} + +/// The page bounds the points of `meshes` project to, and the range of their depths. `None` with no +/// point, a point that isn't finite, or one at or behind the eye. +fn extent(meshes: &[SolidMesh], projection: MeshProjection) -> Option<(Rect, [f64; 2])> { + let mut bounds: Option = None; + let mut z = [f64::INFINITY, f64::NEG_INFINITY]; + for p in meshes.iter().flat_map(|m| &m.mesh.positions) { + if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) { + return None; + } + let at = projection.project(*p); + let r = Rect::from_points(at, at); + bounds = Some(bounds.map_or(r, |b| b.union(r))); + z = [z[0].min(p[2]), z[1].max(p[2])]; + } + bounds.filter(|b| b.width().is_finite() && b.height().is_finite()).map(|b| (b, z)) +} + +/// The row-major clip matrix that takes a point of the solids' world space (mesh space with y down, +/// about the projection origin) to the image `rect` as [`MeshProjection::project`] places it, with +/// depths `z` kept inside the depth buffer and nearer points deeper in it. `None` when no depth +/// mapping keeps them in order. +fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4]; 4]> { + let (rw, rh) = (rect.width(), rect.height()); + let a = 2.0 * (projection.origin.x - rect.x0) / rw - 1.0; + let b = 1.0 - 2.0 * (projection.origin.y - rect.y0) / rh; + // w = 1 − z / eye without perspective's eye: 1. + let inv_eye = projection.eye.map_or(0.0, |e| 1.0 / e); + let (z0, z1) = if z[1] > z[0] { (z[0], z[1]) } else { (z[0] - 0.5, z[0] + 0.5) }; + let w = |z: f64| 1.0 - z * inv_eye; + // ndc depth (dz · z + d0) / w: the farthest at DEPTH_MARGIN, the nearest at 1 − DEPTH_MARGIN. + let (lo, hi) = (DEPTH_MARGIN * w(z0), (1.0 - DEPTH_MARGIN) * w(z1)); + let dz = (hi - lo) / (z1 - z0); + let d0 = lo - dz * z0; + if !(dz > 0.0 && dz.is_finite() && d0.is_finite()) { + return None; + } + let m = [[2.0 / rw, 0.0, -a * inv_eye, a], [0.0, -2.0 / rh, -b * inv_eye, b], [0.0, 0.0, dz, d0], [0.0, 0.0, -inv_eye, 1.0]]; + let m = m.map(|row| row.map(|v| v as f32)); + m.iter().flatten().all(|v| v.is_finite()).then_some(m) +} + +/// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: every triangle in world +/// space (mesh space with y down, as the page is), opaque ones first, then +/// those of see-through solids from back to front; one material for each mesh; one parallel light, +/// casting shadows, for each of `lighting`'s lights. +fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection, z: [f64; 2], clip: [[f32; 4]; 4], size: (u32, u32)) -> Option { + let eye = projection.eye.unwrap_or(z[1] + 1.0); + let mut vertices = vec![]; + let mut opaque: Vec<[u32; 3]> = vec![]; + let mut clear: Vec<([u32; 3], f64)> = vec![]; + let mut materials = vec![]; + for (index, m) in meshes.iter().enumerate() { + let [r, g, b, alpha] = m.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 }); + materials.push(craft_raster3d::Material { + base: [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), 1.0], + metallic: m.material.metallic() as f32, + roughness: m.material.roughness() as f32, + opacity: alpha, + double_sided: true, + unlit: !lighting.shade, + casts_shadows: true, + ..Default::default() + }); + let base = vertices.len() as u32; + let mesh = &m.mesh; + for (i, p) in mesh.positions.iter().enumerate() { + let n = mesh.normals.get(i).copied().unwrap_or([0.0, 0.0, 1.0]); + vertices.push(Vertex { + pos: [p[0] as f32, -p[1] as f32, p[2] as f32], + normal: [n[0] as f32, -n[1] as f32, n[2] as f32], + uv: mesh.uvs.get(i).map_or([0.0; 2], |uv| [uv[0] as f32, uv[1] as f32]), + tangent: [1.0, 0.0, 0.0, 1.0], + material: index as u32, + }); + } + for t in &mesh.triangles { + if t.iter().any(|&i| i as usize >= mesh.positions.len()) { + return None; + } + let tri = t.map(|i| base + i); + if alpha >= 1.0 { + opaque.push(tri); + } else { + let depth = t.iter().map(|&i| mesh.positions[i as usize][2]).sum::() / 3.0; + clear.push((tri, depth)); + } + } + } + clear.sort_by(|a, b| a.1.total_cmp(&b.1)); + // Later meshes paint over earlier ones in the shaded faces. Submit their opaque triangles + // first so the strict depth test keeps that paint when surfaces share a depth. + let opaque_count = (opaque.len() * 3) as u32; + let indices = opaque.into_iter().rev().flatten().chain(clear.into_iter().flat_map(|(t, _)| t)).collect(); + let lights = lighting + .lights + .iter() + .filter(|_| lighting.shade) + .map(|l| { + // The direction the light travels: away from it. + let [x, y, z] = l.direction().map(|v| -v); + let len = (x * x + y * y + z * z).sqrt(); + craft_raster3d::Light { + kind: 0, + pos: [0.0; 3], + dir: [(x / len) as f32, (y / len) as f32, (z / len) as f32], + color: l.color.map(|c| srgb_to_linear((c * l.intensity).clamp(0.0, 1.0) as f32)), + cos_inner: 1.0, + cos_outer: 1.0, + falloff: 0, + radius: 0.0, + falloff_distance: 0.0, + shadow: 0, + shadow_darkness: 1.0, + shadow_diffusion: l.softness as f32, + } + }) + .collect(); + // Ambient light up to 100% goes through the sRGB curve; above it, the linear value scales with + // the intensity, as the shaded faces' ambient term does. + let ambient = lighting.ambient.clamp(0.0, 2.0) as f32; + let ambient = srgb_to_linear(ambient.min(1.0)) * ambient.max(1.0); + Some(Scene { + width: size.0, + height: size.1, + ssaa: 1, + clip, + // Camera depth: the distance in front of the eye, on the z axis. + view: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, eye as f32], [0.0, 0.0, 0.0, 1.0]], + eye: [0.0, 0.0, eye as f32], + cam_fwd: [0.0, 0.0, -1.0], + ortho: projection.eye.is_none(), + vertices, + indices, + opaque_count, + materials, + textures: vec![], + texels: vec![], + lights, + shadows: vec![], + shadow_texels: vec![], + env: None, + ambient: [ambient; 3], + linear_io: false, + }) +} + +/// `image` as an image object of `id`'s art, holding its pixels as a PNG; `None` when it can't be +/// encoded. +pub fn image_node(id: NodeId, image: &Rendered) -> Option> { + let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?; + let mut png = vec![]; + raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let blob = ImageBlob::png(png); + let cell = image.rect.width() / f64::from(image.cols); + let object = ImageObject { + key: blob.content_key(), + width: image.cols, + height: image.rows, + xf: Affine::new([cell, 0.0, 0.0, image.rect.height() / f64::from(image.rows), image.rect.x0, image.rect.y0]), + link: None, + placement: Default::default(), + pixels: Some(Arc::new(blob)), + }; + Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))) +} + +/// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with +/// the raster effects resolution of `doc` (72 ppi without one). An error when it can't be made: the +/// effect then draws its shaded faces. With `check_only`, validate the colors and scene limits +/// without producing pixels, returning `Ok(None)` when it fits. +pub(crate) fn art( + doc: Option<&vectorcraft_doc::Document>, + id: NodeId, + lighting: &Lighting, + meshes: &[SolidMesh], + settings: RenderSettings, + check_only: bool, +) -> Result>, String> { + // Mapped graphics and see-through solids keep their shaded faces, which draw the graphics and + // apply a solid's opacity once to the whole surface. + if meshes.iter().any(|m| m.graphics.is_some() || m.color[3].is_nan() || m.color[3] < 1.0) { + return Err(OPAQUE_ONLY.into()); + } + let ppi = doc.map_or(72.0, |d| d.raster_ppi()); + if check_only { + check(meshes, lighting, settings, ppi, &Limits::default())?; + return Ok(None); + } + image_node(id, &render(meshes, lighting, settings, ppi, false, &Limits::default())?).map(Some).ok_or_else(|| TOO_LARGE.into()) +} + +/// Can the solids of `items` be drawn as a rendered image: is each painted with a solid color (or +/// nothing) in Normal blending, with no member's opacity mask or blending mode applying to them +/// (`masked`)? Otherwise the effect draws its shaded faces, which keep gradients, patterns, mapped +/// graphics, masks and blending. +pub(crate) fn takes<'a>(items: impl IntoIterator, masked: bool) -> bool { + use vectorcraft_doc::AppearanceItem; + use vectorcraft_doc::color::Paint; + !masked + && items.into_iter().all(|i| match i { + AppearanceItem::Fill(f) => matches!(f.paint, Paint::Solid { .. } | Paint::None) && f.blend == Default::default(), + AppearanceItem::Stroke(s) => matches!(s.paint, Paint::Solid { .. } | Paint::None) && s.blend == Default::default(), + }) +} + +/// The lights a 3D effect with parameters `p` shades its faces with: Revolve's ([`crate::revolve_options`]) +/// for Revolve, the other effects' ([`super::view_options`]) otherwise. +pub(crate) fn lighting(id: &str, p: &serde_json::Value) -> Lighting { + if id == crate::REVOLVE { + let o = crate::revolve_options(p); + Lighting { lights: o.active_lights(), ambient: o.ambient, shade: o.shade } + } else { + let v = super::view_options(p); + Lighting { lights: v.active_lights(), ambient: v.ambient, shade: v.shade } + } +} + +#[cfg(test)] +#[path = "rendered/tests.rs"] +mod tests; diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs new file mode 100644 index 0000000000..13f14714c1 --- /dev/null +++ b/crates/effects/src/solids/rendered/tests.rs @@ -0,0 +1,502 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; + +use super::*; + +fn square(x: f64, y: f64, size: f64) -> PathData { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + size, y)); + b.line_to((x + size, y + size)); + b.line_to((x, y + size)); + b.close_path(); + PathData::from_bezpath(&b) +} + +/// A 100 pt square filled `color`, with effect `id` and `params`. +fn solid_square(id: &str, color: Color, params: Value) -> Node { + let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(color), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + n +} + +/// The art the canvas draws for `n`: Revolve's, else the other 3D effects'. +fn drawn(n: &Node) -> Node { + crate::revolve_art(n).or_else(|| super::super::solid_art(n)).unwrap_or_else(|| panic!("no art for {n:?}")) +} + +/// The image objects in `art`. +fn images(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |c| { + if let NodeKind::Image(i) = &c.kind { + out.push((**i).clone()); + } + }); + out +} + +/// The bounds of every filled path in `art`. +fn faces_bounds(art: &Node) -> Option { + let mut out: Option = None; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + out = Some(out.map_or(b, |o| o.union(b))); + } + }); + out +} + +/// The straight-alpha RGBA8 pixel at column `x`, row `y` of `image`. +fn pixel(image: &Rendered, x: u32, y: u32) -> [u8; 4] { + let i = 4 * (y * image.cols + x) as usize; + [image.pixels[i], image.pixels[i + 1], image.pixels[i + 2], image.pixels[i + 3]] +} + +/// The meshes and lights of `n`'s 3D effect, as the rendered image takes them. +fn scene_of(n: &Node) -> (Vec, Lighting) { + let fx = &n.appearance.effects[0]; + let p = crate::merged_params(&fx.id, &fx.params); + (crate::three_d_meshes(n).unwrap(), lighting(&fx.id, &p)) +} + +const MEDIUM: RenderSettings = RenderSettings { quality: 1, resolution: None, white: false }; + +const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, super::super::ROTATE]; + +/// The projection each mesh carries takes its points onto the page where the vector faces of the +/// same solid lie: every corner of every facet is a projected mesh point, with and without +/// perspective. +#[test] +fn projected_mesh_points_land_on_the_facets() { + for perspective in [0.0, 60.0] { + let path = square(100.0, 100.0, 100.0); + let b = path.bounds().unwrap(); + let view = vectorcraft_three_d::View { perspective, ..Default::default() }; + let solid = vectorcraft_three_d::extrude_meshed(&path, FillRule::NonZero, b, Default::default(), view).unwrap(); + let projection = solid.projection().unwrap(); + let points: Vec = solid.mesh().unwrap().positions.iter().map(|p| projection.project(*p)).collect(); + let corners: Vec = solid.facets.iter().flat_map(|f| f.contours.iter().flatten().copied()).collect(); + assert!(!corners.is_empty()); + for c in corners { + let near = points.iter().map(|p| p.distance(c)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "perspective {perspective}: facet corner {c:?} is {near} pt from every projected mesh point"); + } + } +} + +/// Rendered, each of the panel's four effects draws one image in place of its shaded faces, over +/// the area the shaded faces cover: at most one pixel larger on each side. +#[test] +fn rendered_mode_draws_one_image_over_the_shaded_faces() { + for id in FOUR { + let shaded = faces_bounds(&drawn(&solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({})))).unwrap(); + let art = drawn(&solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}}))); + let list = images(&art); + assert_eq!(list.len(), 1, "{id}"); + assert!(faces_bounds(&art).is_none(), "{id}: the shaded faces are drawn too"); + let i = &list[0]; + let rect = Rect::new(i.xf.as_coeffs()[4], i.xf.as_coeffs()[5], 0.0, 0.0); + let (x0, y0) = (rect.x0, rect.y0); + let (x1, y1) = (x0 + f64::from(i.width) * i.xf.as_coeffs()[0], y0 + f64::from(i.height) * i.xf.as_coeffs()[3]); + // At 72 ppi one pixel is one point. + for (got, want, grows) in [(x0, shaded.x0, false), (y0, shaded.y0, false), (x1, shaded.x1, true), (y1, shaded.y1, true)] { + let off = if grows { got - want } else { want - got }; + assert!((-1e-6..=1.0 + 1e-6).contains(&off), "{id}: image edge {got} against the faces' {want}"); + } + } +} + +/// With ambient light alone at 100 %, the rendered surface shows its paint unchanged, as the shaded +/// faces do (brightness 1 times the paint); with no light at all it is black, as they are. +#[test] +fn ambient_light_alone_shows_the_paint_as_the_shaded_faces_do() { + let paint = Color::rgb(0.2, 0.5, 0.8); + for (ambient, want) in [(100.0, [51u8, 128, 204]), (0.0, [0, 0, 0])] { + let n = solid_square( + super::super::ROTATE, + paint, + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightIntensity": 0, "ambient": ambient}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + for c in 0..3 { + assert!(center[c].abs_diff(want[c]) <= 1, "ambient {ambient}: {center:?} against {want:?}"); + } + assert_eq!(center[3], 255); + } +} + +#[test] +fn coplanar_opaque_paints_keep_the_shaded_faces_order() { + use vectorcraft_doc::{AppearanceItem, FillLayer}; + + let lower = Color::rgb(0.8, 0.2, 0.1); + let upper = Color::rgb(0.1, 0.3, 0.9); + let params = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false, "render": {"mode": "rendered"}}); + let mut fills = solid_square(super::super::ROTATE, lower, params.clone()); + fills.appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(upper)))); + let mut group = Node::group( + NodeId(3), + vec![ + Arc::new(Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(lower), Paint::None, 0.0))), + Arc::new(Node::path(NodeId(2), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(upper), Paint::None, 0.0))), + ], + ); + group.appearance.effects.push(crate::new_effect(super::super::ROTATE, ¶ms).unwrap()); + for n in [fills, group] { + let mut shaded = n.clone(); + shaded.appearance.effects[0].params["render"]["mode"] = json!("shaded"); + let mut top = None; + drawn(&shaded).walk(&mut |face| { + if face.path_data().is_some() { + for item in &face.appearance.items { + if let AppearanceItem::Fill(f) = item { + top = f.paint.color(); + } + } + } + }); + assert_eq!(top, Some(upper)); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + let want = top.unwrap().to_rgb().map(|c| (c * 255.0).round() as u8); + assert!(center[..3].iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 1), "{center:?} against {want:?}"); + assert_eq!(center[3], 255); + } +} + +#[test] +fn side_mapped_graphics_draw_the_shaded_faces_and_report_the_fallback() { + let mut doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mark = Node::path(NodeId(0), square(0.0, 0.0, 10.0), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) }); + let n = solid_square( + super::super::EXTRUDE, + Color::rgb(0.5, 0.5, 0.5), + json!({ + "rotationX": -90, "rotationY": 0, "rotationZ": 0, "shade": false, + "graphics": [{"symbol": "Mark", "face": "side"}], "render": {"mode": "rendered"} + }), + ); + let art = super::super::solid_art_in(Some(&doc), &n).unwrap(); + assert!(images(&art).is_empty()); + assert!(faces_bounds(&art).is_some()); + let mut graphic_drawn = false; + art.walk(&mut |face| { + graphic_drawn |= face + .appearance + .items + .iter() + .any(|item| matches!(item, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint.color() == Some(Color::rgb(1.0, 0.0, 0.0)))); + }); + assert!(graphic_drawn); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY)); +} + +/// Ambient intensity retains the upper half of its range even where no directional light falls. +#[test] +fn ambient_200_percent_is_brighter_than_100_percent() { + let level = |ambient| { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.2, 0.3, 0.4), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightIntensity": 0, "ambient": ambient}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + pixel(&image, image.cols / 2, image.rows / 2) + }; + let (normal, bright) = (level(100.0), level(200.0)); + assert_eq!(normal[3], 255); + assert_eq!(bright[3], 255); + for c in 0..3 { + assert!(bright[c] > normal[c] + 10, "channel {c}: 100% {normal:?}, 200% {bright:?}"); + } +} + +/// The arms of an extruded U cast shadows across its recess under a light from the right. +#[test] +fn a_concave_solid_casts_a_shadow_on_itself() { + let mut path = BezPath::new(); + path.move_to((100.0, 100.0)); + for p in [(125.0, 100.0), (125.0, 175.0), (175.0, 175.0), (175.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)] { + path.line_to(p); + } + path.close_path(); + let mut n = Node::path(NodeId(1), PathData::from_bezpath(&path), Appearance::basic(Paint::solid(Color::rgb(0.7, 0.7, 0.7)), Paint::None, 0.0)); + n.appearance.effects.push( + crate::new_effect( + super::super::EXTRUDE, + &json!({ + "depth": 80, "rotationX": -30, "rotationY": -30, "rotationZ": 0, + "lightRotation": 0, "lightHeight": 25, "lightIntensity": 100, "ambient": 10 + }), + ) + .unwrap(), + ); + let (meshes, lighting) = scene_of(&n); + assert_eq!(meshes.len(), 1, "the caster and receiver belong to the same solid"); + let projection = meshes[0].projection.unwrap(); + let (rect, z) = extent(&meshes, projection).unwrap(); + let mut shadowed = scene(&meshes, &lighting, projection, z, clip(projection, rect, z).unwrap(), (160, 160)).unwrap(); + let mut unshadowed = shadowed.clone(); + for material in &mut unshadowed.materials { + material.casts_shadows = false; + } + let limits = Limits::default(); + let draw = |scene: &mut Scene| { + try_shadow_maps(scene, false, &limits).unwrap(); + try_render_cpu(scene, &limits).unwrap().0 + }; + let (shadowed, unshadowed) = (draw(&mut shadowed), draw(&mut unshadowed)); + let (at, darkening) = shadowed + .data + .iter() + .zip(&unshadowed.data) + .enumerate() + .filter(|(_, (a, b))| a[3] == 1.0 && b[3] == 1.0) + .map(|(i, (a, b))| (i, b[0] - a[0])) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .unwrap(); + assert!(darkening > 0.05, "pixel ({}, {}): shadow darkens linear red by {darkening}", at % 160, at / 160); +} + +/// Shading off, the surface shows its paint unlit, as the shaded faces do. +#[test] +fn unshaded_surfaces_show_their_paint() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"shade": false})); + let (meshes, lighting) = scene_of(&n); + assert!(!lighting.shade); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + assert!(center[..3].iter().zip([51u8, 128, 204]).all(|(a, b)| a.abs_diff(b) <= 1), "{center:?}"); +} + +/// A face turned toward the light is lit more than one turned away from it, and a light straight +/// in front of a face lights it more than one that grazes it. +#[test] +fn a_face_toward_the_light_is_brighter() { + let level = |height: f64| { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.5, 0.5, 0.5), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": height, "lightIntensity": 100, "ambient": 0}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + pixel(&image, image.cols / 2, image.rows / 2)[0] + }; + let (front, grazing) = (level(90.0), level(10.0)); + assert!(front > grazing + 40, "front {front}, grazing {grazing}"); + assert!(grazing > 0); +} + +/// Low, Medium and High take 1, 2 × 2 and 3 × 3 samples a pixel; a quality whose samples would +/// pass the pixel limit takes fewer, and an image past the limit at one sample a pixel is refused, +/// when the effect draws its shaded faces instead. +#[test] +fn quality_sets_the_samples_within_the_pixel_limit() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + for (quality, k) in [(0, 1), (1, 2), (2, 3)] { + let image = render(&meshes, &lighting, RenderSettings { quality, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap(); + assert_eq!(image.samples, k, "quality {quality}"); + } + let one = render(&meshes, &lighting, RenderSettings { quality: 2, ..MEDIUM }, 72.0, true, &Limits::default()).unwrap(); + assert_eq!(one.samples, 1, "a draft takes one sample"); + let pixels = u64::from(one.cols) * u64::from(one.rows); + let mut limits = Limits::default(); + limits.max_pixels = pixels * 4; + let image = render(&meshes, &lighting, RenderSettings { quality: 2, ..MEDIUM }, 72.0, false, &limits).unwrap(); + assert_eq!(image.samples, 2); + limits.max_pixels = pixels - 1; + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &limits), Err(TOO_LARGE.to_string())); +} + +/// The resolution sets the image's pixels: 144 ppi gives twice the columns and rows of 72 ppi over +/// the same area, and without one the document's raster effects resolution applies. +#[test] +fn resolution_sets_the_image_grid() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + let at = |resolution: Option, doc: f64| { + render(&meshes, &lighting, RenderSettings { resolution, ..MEDIUM }, doc, false, &Limits::default()).unwrap() + }; + let (base, fine, doc) = (at(Some(72.0), 300.0), at(Some(144.0), 300.0), at(None, 144.0)); + assert!( + fine.cols.abs_diff(2 * base.cols) <= 1 && fine.rows.abs_diff(2 * base.rows) <= 1, + "{}x{} against {}x{}", + fine.cols, + fine.rows, + base.cols, + base.rows + ); + assert_eq!((doc.cols, doc.rows), (fine.cols, fine.rows)); +} + +/// A white background makes every pixel opaque, white where no surface is; transparent, those +/// pixels are clear. +#[test] +fn the_background_is_white_or_clear() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + let clear = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let white = render(&meshes, &lighting, RenderSettings { white: true, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap(); + let corners = |i: &Rendered| [(0, 0), (i.cols - 1, 0), (0, i.rows - 1), (i.cols - 1, i.rows - 1)].map(|(x, y)| pixel(i, x, y)); + assert!(corners(&clear).iter().any(|p| p[3] == 0), "{:?}", corners(&clear)); + assert!(white.pixels.chunks(4).all(|p| p[3] == 255)); + assert!(corners(&white).contains(&[255; 4]), "{:?}", corners(&white)); +} + +/// A mesh without a projection, or meshes with different ones, can't be placed: the image is refused. +#[test] +fn meshes_without_one_projection_are_refused() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (mut meshes, lighting) = scene_of(&n); + let mut other = meshes[0].clone(); + other.projection = other.projection.map(|p| MeshProjection { origin: Point::new(p.origin.x + 1.0, p.origin.y), ..p }); + meshes.push(other); + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); + meshes[0].projection = None; + assert_eq!(render(&meshes[..1], &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); + assert_eq!(render(&[], &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); +} + +/// A solid painted with a gradient, in a blending mode other than Normal or with an opacity below +/// 100% draws its shaded faces, which keep that paint: the image shows opaque solid colors only. +#[test] +fn gradients_and_blending_draw_the_shaded_faces() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + for id in FOUR { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + n.appearance.items[0] = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new( + GradientPaint::new(Gradient::new(GradientKind::Linear, stops)), + )))); + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: gradient"); + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.blend = vectorcraft_doc::color::BlendMode::Multiply; + } + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: blending"); + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = 0.5; + } + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: opacity"); + } +} + +/// A loaded file whose `render` breaks the rules draws the shaded faces. +#[test] +fn an_invalid_loaded_render_draws_shaded() { + let mut n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + n.appearance.effects[0].params["render"] = json!({"mode": "rendered", "quality": "ultra"}); + let art = drawn(&n); + assert!(images(&art).is_empty()); + assert!(faces_bounds(&art).is_some()); +} + +#[test] +fn rendered_warning_reports_the_fallback() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in FOUR { + let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}: plain solid"); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + n.appearance.items[0] = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new( + GradientPaint::new(Gradient::new(GradientKind::Linear, stops)), + )))); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "{id}: gradient"); + } + let mut large = Node::path(NodeId(2), square(0.0, 0.0, 100_000.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + large.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &large).as_deref(), Some(TOO_LARGE)); +} + +#[test] +fn rendered_warning_does_not_rasterize() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in FOUR { + let n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + let before = RASTERIZATIONS.with(|count| count.get()); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{id}: warning rasterizes"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + assert!(RASTERIZATIONS.with(|count| count.get()) > before, "{id}: drawing rasterizes"); + } +} + +#[test] +fn check_only_reports_rasterizer_limits_after_measure_succeeds() { + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false})); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + let measured = measure(&meshes, settings, 72.0, false, &Limits::default()).unwrap(); + let triangles = meshes.iter().map(|m| m.mesh.triangles.len() as u64).sum::(); + let vertices = meshes.iter().map(|m| m.mesh.positions.len() as u64).sum::(); + for limit in ["triangles", "vertices", "work"] { + let mut limits = Limits::default(); + match limit { + "triangles" => limits.max_triangles = triangles - 1, + "vertices" => limits.max_vertices = vertices - 1, + _ => limits.max_work = u64::from(measured.cols) * u64::from(measured.rows), + } + assert!(measure(&meshes, settings, 72.0, false, &limits).is_ok(), "{limit}: image fits"); + let before = RASTERIZATIONS.with(|count| count.get()); + let checked = check(&meshes, &lighting, settings, 72.0, &limits); + assert_eq!(checked.as_ref().map_err(String::as_str), Err(TOO_LARGE), "{limit}"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{limit}: check rasterizes"); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits).map(|_| ()), checked, "{limit}"); + } +} + +#[test] +fn check_only_counts_shadow_work_and_lights() { + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90})); + let (meshes, lighting) = scene_of(&n); + assert!(!lighting.lights.is_empty()); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + for limit in ["lights", "shadow work"] { + let mut limits = Limits::default(); + if limit == "lights" { + limits.max_lights = 0; + } else { + // The 512-square draft shadow map takes more work than the 100-square image. + limits.max_work = 30_000; + let mut unlit = lighting.clone(); + unlit.shade = false; + assert!(check(&meshes, &unlit, settings, 72.0, &limits).is_ok()); + assert!(render(&meshes, &unlit, settings, 72.0, false, &limits).is_ok()); + } + assert!(measure(&meshes, settings, 72.0, false, &limits).is_ok()); + assert_eq!(check(&meshes, &lighting, settings, 72.0, &limits), Err(TOO_LARGE.into()), "{limit}"); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.into()), "{limit}"); + } +} + +#[test] +fn check_only_art_reports_overlapping_faces_past_the_work_limit() { + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false})); + let (mut meshes, lighting) = scene_of(&n); + for p in &mut meshes[0].mesh.positions { + p[0] *= 40.0; + p[1] *= 40.0; + } + let meshes = vec![meshes[0].clone(); 200]; + let settings = RenderSettings { quality: 0, ..MEDIUM }; + assert!(measure(&meshes, settings, 72.0, false, &Limits::default()).is_ok()); + let before = RASTERIZATIONS.with(|count| count.get()); + assert_eq!(art(None, NodeId(1), &lighting, &meshes, settings, true).map(|_| ()), Err(TOO_LARGE.into())); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &Limits::default()), Err(TOO_LARGE.into())); +} diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 12ab29423f..ebe082b488 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -356,7 +356,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() let (path, rule) = profile(&n).unwrap(); vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] }; - let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap(); + let (drawn, _) = art_for(None, &n, fx, &shapes, false, &mut None).unwrap(); let p = crate::merged_params(&fx.id, &fx.params); let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 9541d5020f..55dae0b5d6 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -21,12 +21,84 @@ use crate::{GeomContext, is_geometry}; pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000; /// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of -/// [`RENDER_MODES`]. +/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution` and +/// `background` ([`RENDER_BACKGROUNDS`]). pub const RENDER: &str = "render"; /// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every -/// face ([`renders_wireframe`]). -pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"]; +/// face ([`renders_wireframe`]), and `rendered` an image of the lit solid with the shadows of its +/// lights ([`render_settings`]). +pub const RENDER_MODES: [&str; 3] = ["shaded", "wireframe", "rendered"]; + +/// The qualities of the rendered image, from fastest to finest: 1, 2 × 2 and 3 × 3 samples a pixel +/// ([`RenderSettings::samples`]). VectorCraft's own values. +pub const RENDER_QUALITIES: [&str; 3] = ["low", "medium", "high"]; + +/// What the rendered image shows where no surface is: nothing, or white. +pub const RENDER_BACKGROUNDS: [&str; 2] = ["transparent", "white"]; + +/// The index in [`RENDER_QUALITIES`] of the quality a `render` without one takes (VectorCraft's own +/// default). +const DEFAULT_QUALITY: usize = 1; + +/// The settings of a 3D effect's rendered image ([`render_settings`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RenderSettings { + /// The quality, as an index into [`RENDER_QUALITIES`] (0 low, 1 medium, 2 high). + pub quality: usize, + /// Pixels per inch, 1 to 2400; `None` takes Document Raster Effects Settings › Resolution. + pub resolution: Option, + /// A white background, which makes the image opaque; otherwise it is transparent where no + /// surface or shadow is. + pub white: bool, +} + +impl RenderSettings { + /// The samples a pixel takes along each side at this quality: 1, 2 or 3. + pub fn samples(&self) -> u32 { + self.quality.min(2) as u32 + 1 + } +} + +/// The settings of the image 3D effect `id` with parameters `p` draws, when its `render` passes +/// [`validate_render`] and sets `mode` to `rendered`; `None` otherwise, when the effect draws its +/// shaded faces or its wireframe (a loaded file whose `render` breaks the rules draws shaded). +pub fn render_settings(id: &str, p: &Value) -> Option { + let render = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id))?; + if check_render(render).is_err() || render.get("mode").and_then(Value::as_str) != Some("rendered") { + return None; + } + let quality = render.get("quality").and_then(Value::as_str).and_then(|q| RENDER_QUALITIES.iter().position(|k| *k == q)); + Some(RenderSettings { + quality: quality.unwrap_or(DEFAULT_QUALITY), + resolution: render.get("resolution").and_then(Value::as_f64), + white: render.get("background").and_then(Value::as_str) == Some("white"), + }) +} + +/// Does effect `fx` draw as a rendered image ([`render_settings`])? +pub fn renders_image(fx: &Effect) -> bool { + render_settings(&fx.id, &fx.params).is_some() +} + +/// The message a `render` that breaks the rules of [`validate_render`] is refused with. +const RENDER_RULES: &str = "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), \ + resolution (null or a number from 1 to 2400) and background (transparent or white)"; + +/// Check one `render` value against [`RENDER_RULES`]. +fn check_render(render: &Value) -> Result<(), String> { + let one_of = |v: &Value, list: &[&str]| v.as_str().is_some_and(|s| list.contains(&s)); + let valid = render.as_object().is_some_and(|fields| { + fields.iter().all(|(key, value)| match key.as_str() { + "mode" => one_of(value, &RENDER_MODES), + "quality" => one_of(value, &RENDER_QUALITIES), + "background" => one_of(value, &RENDER_BACKGROUNDS), + "resolution" => value.is_null() || value.as_f64().is_some_and(|r| (1.0..=2400.0).contains(&r)), + _ => false, + }) + }); + if valid { Ok(()) } else { Err(RENDER_RULES.into()) } +} /// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve, /// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface. @@ -50,17 +122,14 @@ pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool { } /// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the -/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a -/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take. +/// effects in [`TAKES_RENDER`], is an object that holds only `mode` (one of [`RENDER_MODES`]), +/// `quality` (one of [`RENDER_QUALITIES`]), `resolution` (`null`, or a number from 1 to 2400 pixels +/// per inch) and `background` (one of [`RENDER_BACKGROUNDS`]). A key left out takes its default: +/// `shaded`, `medium`, the document's raster effects resolution and `transparent`. The 3D (Classic) +/// effects refuse it as a parameter they do not take. pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> { let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) }; - let valid = render - .as_object() - .is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m)))); - if !valid { - return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into()); - } - Ok(()) + check_render(render) } /// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index cb92d59e72..4def42a37e 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -418,12 +418,23 @@ fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() { assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT))); } -/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and -/// only on the panel's four effects. +/// `render` is checked before an edit: an object holding only `mode` (shaded, wireframe or +/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400) and `background` +/// (transparent or white), and only on the panel's four effects. #[test] fn render_settings_are_validated() { for id in WIRE { - for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] { + for good in [ + json!({}), + json!({"render": {}}), + json!({"render": {"mode": "shaded"}}), + json!({"render": {"mode": "wireframe"}}), + json!({"render": {"mode": "rendered"}}), + json!({"render": {"mode": "rendered", "quality": "high", "resolution": 300, "background": "white"}}), + json!({"render": {"mode": "rendered", "quality": "low", "resolution": null, "background": "transparent"}}), + json!({"render": {"resolution": 1}}), + json!({"render": {"resolution": 2400}}), + ] { assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}"); } for bad in [ @@ -431,10 +442,20 @@ fn render_settings_are_validated() { json!({"render": null}), json!({"render": {"mode": "raytrace"}}), json!({"render": {"mode": true}}), - json!({"render": {"mode": "wireframe", "quality": "high"}}), + json!({"render": {"mode": "rendered", "quality": "ultra"}}), + json!({"render": {"mode": "rendered", "resolution": 0.5}}), + json!({"render": {"mode": "rendered", "resolution": 2401}}), + json!({"render": {"mode": "rendered", "resolution": "300"}}), + json!({"render": {"mode": "rendered", "background": "black"}}), + json!({"render": {"mode": "rendered", "samples": 4}}), ] { let e = crate::validate_three_d_params(id, &bad).unwrap_err(); - assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}"); + assert_eq!( + e, + "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), resolution (null \ + or a number from 1 to 2400) and background (transparent or white)", + "{id} {bad}" + ); } // The command check on the object refuses it too. let n = solid_square(id, json!({})); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index e5463f6c44..808486071d 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -288,6 +288,15 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result { Ok(json!({"refreshed": counts.refreshed, "stillDeferred": counts.still_deferred, "failed": counts.failed})) } +/// Report the first rendered 3D effect that keeps its shaded faces after an edit. +fn with_render_warning(s: &Session, ids: &[NodeId], mut out: Value) -> Result { + let d = &s.doc()?.doc; + if let Some(message) = ids.iter().filter_map(|id| d.node(*id)).find_map(|n| effects::rendered_warning(d, n)) { + out["warning"] = json!(message); + } + Ok(out) +} + fn ids_json(ids: &[NodeId]) -> Value { json!(ids.iter().map(|i| i.0).collect::>()) } @@ -567,7 +576,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { }; let landed = first.and_then(|n| at.effects_item(&n.appearance, C).ok().flatten()); let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1)); - Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed })) + with_render_warning(s, &ids, json!({ "ids": ids_json(&ids), "index": index, "item": landed })) } /// The selected objects a Pathfinder effect should group before it applies: it combines the @@ -846,7 +855,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let ids: Vec<&str> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index).map(|e| e.id.as_str())).collect(); if !ids.is_empty() && ids.iter().all(|id| *id == to) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // Pathfinder effects given the values they already evaluate with, and nothing else to change, @@ -855,7 +864,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect(); if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, ¶ms)) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // An SVG filter is named by its id: another filter renames the effect. @@ -902,7 +911,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect(); if !fx.is_empty() && fx.iter().all(|e| three_d_edit_changes_nothing(e, ¶ms)) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // The effect edited, when every target has one at `index` and all are the same: a dialog's @@ -937,7 +946,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { true }) })?; - Ok(json!({ "ids": ids_json(&ids) })) + with_render_warning(s, &ids, json!({ "ids": ids_json(&ids) })) } /// Does effect `id` take a `bevel` (Extrude & Bevel, Extrude & Bevel (Classic)), which may be a diff --git a/crates/engine/src/tests/effectedit.rs b/crates/engine/src/tests/effectedit.rs index 34e01bf31e..889d2f74a4 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -181,3 +181,26 @@ fn warps_keep_the_map_their_version_names() { } assert_eq!(node(&s, id).appearance.effects.len(), 2); } + +#[test] +fn rendered_warning_is_in_effect_command_results() { + let (mut s, _) = session_with_rect(); + run( + &mut s, + "paint.setFill", + json!({"gradient": {"kind": "linear", "stops": [ + {"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"} + ]}}), + ); + let warning = vectorcraft_render::effects::rendered::OPAQUE_ONLY; + let applied = run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered"}}})); + assert_eq!(applied["warning"], warning); + let shaded = run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "shaded"}}})); + assert!(shaded.get("warning").is_none()); + let params = json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered"}}}); + assert_eq!(run(&mut s, "effect.setParams", params.clone())["warning"], warning); + assert_eq!(run(&mut s, "effect.setParams", params)["warning"], warning, "unchanged settings still report the fallback"); + run(&mut s, "paint.setFill", json!({"color": "#338ad6"})); + let plain = run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}})); + assert!(plain.get("warning").is_none()); +} diff --git a/crates/render/src/fx/entries.rs b/crates/render/src/fx/entries.rs index 24fcf0e38d..64c1cf5ad9 100644 --- a/crates/render/src/fx/entries.rs +++ b/crates/render/src/fx/entries.rs @@ -344,6 +344,7 @@ pub(crate) struct DocInputs { /// may name (`crate::live`). pub(crate) names: u64, pub(crate) cms: usize, + pub(crate) raster_ppi: u64, /// Whether an object in a pattern's or a symbol's art, or in an opacity mask there, has a /// visible plug-in effect. pub(super) plugins: bool, diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index ceead2a01e..41194874b3 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -501,15 +501,25 @@ impl Renderer { } }); let names = paint_names(doc); - let found = (patterns, symbols, images, names, Arc::as_ptr(&cms) as usize); + let raster_ppi = doc.raster_ppi().to_bits(); + let found = (patterns, symbols, images, names, Arc::as_ptr(&cms) as usize, raster_ppi); let d = match &self.doc_inputs { - Some((_, d)) if (d.patterns, d.symbols, d.images, d.names, d.cms) == found => d.clone(), + Some((_, d)) if (d.patterns, d.symbols, d.images, d.names, d.cms, d.raster_ppi) == found => d.clone(), _ => { let doc_art = || doc.patterns.iter().flat_map(|p| &p.art).chain(doc.symbols.iter().map(|s| &s.art)); let art = doc_art().map(Arc::downgrade).collect(); let pixels = doc.images.values().flat_map(|b| std::iter::once(&b.bytes).chain(&b.proxy)).map(Arc::downgrade).collect(); let plugins = doc_art().any(|a| crate::holds_plugin_effect(a)); - Arc::new(DocInputs { patterns, symbols, images, names, cms: found.4, plugins, _held: (art, pixels, Arc::downgrade(&cms)) }) + Arc::new(DocInputs { + patterns, + symbols, + images, + names, + cms: found.4, + raster_ppi, + plugins, + _held: (art, pixels, Arc::downgrade(&cms)), + }) } }; self.doc_inputs = Some((at, d.clone())); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 757290ed1f..8b2b1336d1 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -2231,3 +2231,34 @@ fn geometry_effects_work_from_bounds_that_hold_lone_anchors() { } } } + +#[test] +fn rendered_art_follows_document_raster_resolution() { + let mut d = Document::new(200.0, 200.0); + d.raster_effects_ppi = 36.0; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(50.0, 50.0, 100.0, 100.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects.push(crate::effects::new_effect("threeD.extrude", &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + let n = Arc::new(n); + let mut renderer = Renderer::new(); + let image_width = |art: &Node| { + let mut width = 0; + art.walk(&mut |n| { + if let vectorcraft_doc::NodeKind::Image(image) = &n.kind { + width = image.width; + } + }); + width + }; + let before = renderer.fx_art(&d.symbol_boxes(), &n, true); + d.raster_effects_ppi = 144.0; + renderer.stamp += 1; + let measured = renderer.measured_fx_art(&d.symbol_boxes(), &n); + let after = renderer.fx_art(&d.symbol_boxes(), &n, true); + assert!(image_width(&before) > 0); + assert!(image_width(&after) > image_width(&before)); + assert!(Arc::ptr_eq(&measured, &after)); +} diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 2884e9c4d8..602a32e4d0 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -119,7 +119,7 @@ fn resources_key(symbols: &SymbolBoxes, cms: usize, names: u64, n: &Node) -> (u6 let mut shown = Shown::default(); hash_resources(symbols, n, &mut shown, &mut h); let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins }; - (walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) + (walked.key(cms, names, symbols.document().raster_ppi().to_bits()), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) } /// What [`hash_resources`] found in a node: the hash of what it walked, whether it found type or @@ -135,10 +135,10 @@ impl Walked { /// The [`resources_key`] of the node walked: the walk's hash, the layout inputs (fonts and /// hyphenation exceptions, [`vectorcraft_text::layout_inputs`]) when it found type or a placed /// file, the plug-in revision and the hash of the document's swatch and pattern - /// names (`names`) when it found a plug-in effect, and the color settings `cms`. Whether a - /// plug-in paints its pieces depends on the plug-ins installed, so the names count for every - /// plug-in effect. - fn key(self, cms: usize, names: u64) -> u64 { + /// names (`names`) when it found a plug-in effect, the color settings `cms` and the document's + /// raster resolution `raster_ppi`. Whether a plug-in paints its pieces depends on the plug-ins + /// installed, so the names count for every plug-in effect. + fn key(self, cms: usize, names: u64, raster_ppi: u64) -> u64 { let mut h = DefaultHasher::new(); self.hash.hash(&mut h); if self.text { @@ -149,6 +149,7 @@ impl Walked { names.hash(&mut h); } cms.hash(&mut h); + raster_ppi.hash(&mut h); h.finish() } } @@ -484,7 +485,7 @@ impl Renderer { && std::ptr::eq(node.as_ptr(), Arc::as_ptr(n)) && read.same_art(&inputs) { - return (walked.key(inputs.cms, inputs.names), inputs, vec![]); + return (walked.key(inputs.cms, inputs.names, inputs.raster_ppi), inputs, vec![]); } #[cfg(test)] { diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f561c0b7c6..226b490531 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -26,7 +26,8 @@ pub use material::{Highlight, Material}; mod caps; mod mesh; pub use mesh::{ - Mesh, MeshPart, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface, + Mesh, MeshPart, MeshProjection, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, plane_meshed, + revolve_mesh, revolve_mesh_projection, revolve_mesh_surface, }; mod shadow; pub use shadow::{ @@ -313,6 +314,23 @@ impl Revolve { [ch * cr, -ch * sr, if o.light_behind { -sh } else { sh }] } + /// The directional lights the surface is shaded with: its [`Revolve::lights`], or the one light + /// its single-light settings describe. + pub fn active_lights(self) -> Vec { + let o = self.sanitized(); + match o.lights { + Some(lights) => lights.iter().copied().collect(), + None => vec![Light { + rotation: o.light_rotation, + height: o.light_height, + behind: o.light_behind, + color: o.light_color, + intensity: o.light_intensity, + softness: o.light_softness, + }], + } + } + /// Light-direction orbits as (centre, cosine basis, sine basis), in view space. /// The first changes the Rotation at the current Height: a circle on the page. The second /// changes the Height at the current Rotation; its parameter runs 0..90 degrees. diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 53e1cb5786..95c86f1d3c 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -128,7 +128,39 @@ pub fn extrude_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Extr /// Rotate's plane ([`crate::plane`]) as a mesh. pub fn plane_mesh(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result { - plane_faces(path, rule, bounds, view, Keep::Faces).and_then(|(_, faces, _)| mesh(&faces?)) + plane_meshed(path, rule, bounds, view).map(|(mesh, _)| mesh) +} + +/// [`plane_mesh`] with the projection its faces are drawn with ([`MeshProjection`]). +pub fn plane_meshed(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result<(Mesh, Option), String> { + let (_, faces, projection) = plane_faces(path, rule, bounds, view, Keep::Faces)?; + Ok((mesh(&faces?)?, projection.map(MeshProjection::of))) +} + +/// Where the points of a mesh land on the page, as the effect projects the faces it draws: the +/// page point the mesh's origin draws at, and the eye's distance in front of it (`None` without +/// perspective). A point `z` in front of the origin is scaled by `eye / (eye − z)`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshProjection { + pub origin: Point, + pub eye: Option, +} + +impl MeshProjection { + pub(crate) fn of(p: crate::shadow::Projection) -> Self { + Self { origin: p.origin, eye: p.eye } + } + + /// The page point mesh point `p` (x right, y up, z toward the viewer) draws at. + pub fn project(&self, p: [f64; 3]) -> Point { + let f = crate::perspective_scale(self.eye, p[2]); + Point::new(self.origin.x + p[0] * f, self.origin.y - p[1] * f) + } +} + +/// The projection Revolve's mesh ([`revolve_mesh`]) of a profile with bounds `bounds` is drawn with. +pub fn revolve_mesh_projection(bounds: Rect, options: Revolve) -> MeshProjection { + MeshProjection::of(crate::revolve_projection(bounds, options.sanitized())) } /// Inflate's solids for several shapes of one object ([`crate::inflate_together`]) as meshes, one @@ -150,12 +182,13 @@ pub struct MeshedSolid { pub facets: Vec, /// The faces before projection, or the error the mesh alone gives when there are too many. faces: Result, String>, + projection: Option, } /// A solid with no facets and an empty mesh. impl Default for MeshedSolid { fn default() -> Self { - Self { facets: vec![], faces: Ok(vec![]) } + Self { facets: vec![], faces: Ok(vec![]), projection: None } } } @@ -164,12 +197,22 @@ impl MeshedSolid { pub fn mesh(&self) -> Result { mesh(self.faces.as_ref().map_err(String::clone)?) } + + /// The projection the solid's facets are drawn with, which takes its mesh's points to the page; + /// `None` for a solid with no faces. + pub fn projection(&self) -> Option { + self.projection + } } /// Extrude & Bevel's solid ([`crate::extrude`]) and its mesh ([`extrude_mesh`]) from one build. An /// error where [`crate::extrude`] gives one. pub fn extrude_meshed(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result { - extrude_faces(path, rule, bounds, options, view, Keep::Both).map(|(facets, faces, _)| MeshedSolid { facets, faces }) + extrude_faces(path, rule, bounds, options, view, Keep::Both).map(|(facets, faces, projection)| MeshedSolid { + facets, + faces, + projection: projection.map(MeshProjection::of), + }) } /// Inflate's solids for several shapes of one object ([`crate::inflate_each`]) and their meshes @@ -181,7 +224,8 @@ pub fn inflate_meshed( options: Inflate, view: View, ) -> impl Iterator> + use<> { - inflate_faces(shapes, bounds, options, view, Keep::Both).map(|r| r.map(|(facets, faces, _)| MeshedSolid { facets, faces })) + inflate_faces(shapes, bounds, options, view, Keep::Both) + .map(|r| r.map(|(facets, faces, projection)| MeshedSolid { facets, faces, projection: projection.map(MeshProjection::of) })) } /// Revolve's surface ([`crate::revolve`]) as a mesh. As the effect draws it, a sweep of less than diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index deeaab4dde..1d5c442254 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -93,6 +93,11 @@ impl View { view.lights.map_or(view.light_color != [1.0; 3], |lights| lights.iter().any(|light| light.color != [1.0; 3])) } + /// The directional lights the view shades with ([`Revolve::active_lights`]). + pub fn active_lights(self) -> Vec { + self.revolve().active_lights() + } + /// Whether the view shades with a material other than [`crate::Material::DEFAULT`], which also /// needs RGB shading: its highlight ([`Facet::highlight`]) and a metal's tint. pub fn shades_material(self) -> bool { diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 45bac489a0..867ce33747 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -207,6 +207,37 @@ fn render_settings_wireframe_turns_the_mode_on_and_off_for_the_selection() { assert!(!painted_text(&mut app, show).contains("Render Settings")); } +/// Render Settings › Rendered and its qualities: each sets `render` on the selection in one undo +/// step, and turning Wireframe on keeps the chosen quality. +#[test] +fn render_settings_rendered_sets_the_mode_and_quality() { + let mut app = app(); + set_type(&mut app, "extrude").unwrap(); + let render = |app: &VectorcraftApp| target(app).unwrap().params.get("render").cloned().unwrap_or(Value::Null); + let history = undo_len(&app); + super::set_render(&mut app, "rendered", None); + assert_eq!(undo_len(&app), history + 1); + assert_eq!(render(&app)["mode"], "rendered"); + super::set_render(&mut app, "rendered", Some("high")); + assert_eq!((render(&app)["mode"].as_str(), render(&app)["quality"].as_str()), (Some("rendered"), Some("high"))); + super::set_wireframe(&mut app, true); + assert_eq!((render(&app)["mode"].as_str(), render(&app)["quality"].as_str()), (Some("wireframe"), Some("high"))); + assert!(painted_text(&mut app, show).contains("Render Settings")); + // Each selected object keeps its own other render settings. + let a = app.session.active().unwrap().selection.objects[0].0; + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + app.run("effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "shaded", "background": "white"}}})).unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + super::set_render(&mut app, "rendered", Some("low")); + let of = |app: &VectorcraftApp, id: u64| { + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + n.appearance.effects[0].params["render"].clone() + }; + assert_eq!(of(&app, a), json!({"mode": "rendered", "quality": "low"})); + assert_eq!(of(&app, b), json!({"mode": "rendered", "quality": "low", "background": "white"})); +} + #[test] fn a_drag_previews_and_records_one_undo_step_when_released() { let mut app = app(); @@ -1530,3 +1561,24 @@ fn the_materials_sliders_commit_typing_dragging_and_resetting() { assert_eq!(after["metallic"], before["metallic"]); } } + +#[test] +fn rendered_warning_reaches_the_status_bar() { + let mut app = app(); + let a = app.session.active().unwrap().selection.objects[0].0; + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run( + "paint.setFill", + json!({"gradient": {"kind": "linear", "stops": [ + {"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"} + ]}}), + ) + .unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + set_type(&mut app, "extrude").unwrap(); + super::set_render(&mut app, "rendered", None); + assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); + app.ui.status.clear(); + super::set_render(&mut app, "rendered", Some("low")); + assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); +} diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index 180ec53909..16b300b010 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -235,6 +235,12 @@ pub(crate) fn send(app: &mut VectorcraftApp, changed: Map, phase: params.insert(vectorcraft_effects::MATERIAL.into(), Value::Object(material)); } } + // The edited render fields go into each target's own render settings. + if let Some(Value::Object(edited)) = params.get(vectorcraft_effects::RENDER) { + let mut render = render_of(t); + render.extend(edited.iter().map(|(k, v)| (k.clone(), v.clone()))); + params.insert(vectorcraft_effects::RENDER.into(), Value::Object(render)); + } (!params.is_empty()) .then(|| json!({"command": "effect.setParams", "params": {"ids": [id], "index": t.index, "item": t.item, "params": params}})) }) @@ -463,31 +469,79 @@ fn takes_render(id: &str) -> bool { } /// Is target `t`'s 3D effect drawn as a wireframe (`render.mode` is `wireframe`)? +#[cfg(test)] pub(crate) fn wireframe_on(t: &Target) -> bool { let p = vectorcraft_effects::merged_params(&t.effect, &t.params); p.get(vectorcraft_effects::RENDER).and_then(|r| r.get("mode")).and_then(Value::as_str) == Some("wireframe") } +/// Target `t`'s 3D effect's render settings (`render`), empty when it has none. +fn render_of(t: &Target) -> Map { + let p = vectorcraft_effects::merged_params(&t.effect, &t.params); + p.get(vectorcraft_effects::RENDER).and_then(Value::as_object).cloned().unwrap_or_default() +} + /// The Render Settings menu at the top of the panel: Wireframe, checked while the first selected -/// object's 3D effect draws the edges of its faces. Choosing it turns wireframe on or off for every -/// selected object's 3D effect ([`set_wireframe`]). +/// object's 3D effect draws the edges of its faces; Rendered, checked while it draws an image of +/// the lit solid; and the rendered image's Low, Medium and High quality. Choosing Wireframe or +/// Rendered turns that mode on or off, and choosing a quality renders at it ([`set_render`]), for +/// every selected object's 3D effect. fn render_settings(app: &mut VectorcraftApp, ui: &mut Ui, t: &Target) { - let on = wireframe_on(t); + let render = render_of(t); + let mode = render.get("mode").and_then(Value::as_str).unwrap_or("shaded"); + let quality = render.get("quality").and_then(Value::as_str).unwrap_or("medium"); + let rendered = mode == "rendered"; let opener = Button::new(tl!("Render Settings")).show(ui); - let entries = [Entry::new((), tl!("Wireframe")).checked(on)]; - if Menu::new(tl!("Render Settings")).values().opened_by(&opener, Trigger::Press).pick(ui, &entries).picked.is_some() { - set_wireframe(app, !on); + let entries = [ + Entry::new(0usize, tl!("Wireframe")).checked(mode == "wireframe"), + Entry::new(1, tl!("Rendered")).checked(rendered), + Entry::new(2, tl!("Low Quality")).checked(rendered && quality == "low"), + Entry::new(3, tl!("Medium Quality")).checked(rendered && quality == "medium"), + Entry::new(4, tl!("High Quality")).checked(rendered && quality == "high"), + ]; + let picked = Menu::new(tl!("Render Settings")).values().opened_by(&opener, Trigger::Press).pick(ui, &entries).picked; + match picked { + Some(0) => set_render(app, if mode == "wireframe" { "shaded" } else { "wireframe" }, None), + Some(1) => set_render(app, if rendered { "shaded" } else { "rendered" }, None), + Some(k @ 2..=4) => set_render(app, "rendered", vectorcraft_effects::RENDER_QUALITIES.get(k - 2).copied()), + _ => {} } } /// Render Settings › Wireframe: sets `render.mode` of each selected object's 3D effect to -/// `wireframe` (`on`) or `shaded`, as one undo step (`effect.setParams`). Objects whose effect does -/// not take render settings are left as they are. +/// `wireframe` (`on`) or `shaded` ([`set_render`]). +#[cfg(test)] pub(crate) fn set_wireframe(app: &mut VectorcraftApp, on: bool) { + set_render(app, if on { "wireframe" } else { "shaded" }, None); +} + +/// Sets `render.mode` and, when given, `render.quality` of each selected object's 3D effect, as one +/// undo step (`effect.setParams`); each object keeps its other render settings. Objects whose +/// effect does not take render settings are left as they are. +pub(crate) fn set_render(app: &mut VectorcraftApp, mode: &str, quality: Option<&str>) { finish(app); + let mut render = Map::new(); + render.insert("mode".into(), json!(mode)); + if let Some(quality) = quality { + render.insert("quality".into(), json!(quality)); + } let mut changed = Map::new(); - changed.insert(vectorcraft_effects::RENDER.into(), json!({"mode": if on { "wireframe" } else { "shaded" }})); + changed.insert(vectorcraft_effects::RENDER.into(), Value::Object(render)); send(app, changed, Live::Released); + if mode == "rendered" + && let Some(st) = app.session.active() + && let Some(message) = st + .selection + .objects + .iter() + .filter_map(|id| st.doc.node(*id)) + .filter(|n| { + find(n).is_some_and(|t| vectorcraft_effects::default_params(&t.effect).is_some_and(|p| p.get(vectorcraft_effects::RENDER).is_some())) + }) + .find_map(|n| vectorcraft_effects::rendered_warning(&st.doc, n)) + { + app.ui.status = message; + } } /// Runs what a click in the Materials page's Graphics asked for: maps the graphic onto the selected diff --git a/docs/mcp.md b/docs/mcp.md index 34eee5adae..7f39ec7d82 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6441,8 +6441,9 @@ a hard shadow as a path and turns a blurred one into an image. Extrude & Bevel ( ## 3D render mode -Revolve, Extrude & Bevel, Inflate and Rotate take `render`, an object whose `mode` is `"shaded"` (the default) or -`"wireframe"` (**Window › 3D and Materials** › Render Settings › Wireframe), set with `effect.apply` or +Revolve, Extrude & Bevel, Inflate and Rotate take `render`, an object whose `mode` is `"shaded"` (the default), +`"wireframe"` (**Window › 3D and Materials** › Render Settings › Wireframe) or `"rendered"` (Render Settings › +Rendered), set with `effect.apply` or `effect.setParams` in one undo step. In wireframe mode the effect stays live and draws the edges of the faces it builds instead of its shaded surface: each edge once, in the paths [Expand as Wireframes](#expand-as-wireframes) gives for the 3D effect, with a 0.5 pt black stroke, round joins and no fill (VectorCraft's own choice), and no shadow or graphics. @@ -6451,13 +6452,22 @@ object's own opacity, blending mode and opacity mask apply to them as a whole. Geometry effects after the 3D effect reshape the drawn edges. Expand as Wireframes reshapes each face before it joins the edges, so with such an effect its paths can differ from the drawn ones. The mode is saved in the native file, SVG and PDF exports draw the edges, and `effect.expandAppearance` keeps them as paths. Past 1,000,000 edges the source path is drawn, as -it is for a solid past its limits. A `render` that is not an object, a key other than `mode`, another mode, and -`render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) are refused before the document -changes. In wireframe mode the graphics' art is not checked against the graphics limits, so art too complex for the -shaded surface does not refuse the wireframe. See [three-d.md](three-d.md#3d-and-materials-panel). +it is for a solid past its limits. In rendered mode the effect draws its solid as one image with a depth buffer, lit +by every light, with the shadows each light casts on the solid, over the effect's shadow. `render` then also takes +`quality` (`"low"`, `"medium"` or `"high"`: 1, 2 × 2 or 3 × 3 samples a pixel, default `"medium"`, VectorCraft's own +values), `resolution` (`null` for Document Raster Effects Settings › Resolution, the default, or 1..2400 ppi) and +`background` (`"transparent"`, the default, or `"white"`). A quality whose samples would pass 16,777,216 pixels +takes fewer, and an image past that limit at one sample a pixel draws the shaded faces, as do solids painted with +a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal. The status bar and +the command result's `warning` field report when the shaded faces are drawn instead. A `render` that is not an +object, another key, another value, and `render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) +are refused before the document changes. In wireframe mode the graphics' art is not checked against the graphics +limits, so art too complex for the shaded surface does not refuse the wireframe. See +[three-d.md](three-d.md#3d-and-materials-panel). ```json {"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"render":{"mode":"wireframe"}}}}} +{"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"render":{"mode":"rendered","quality":"high","background":"white"}}}}} ``` ## 3D material diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2970f8a02b..0e85401faa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -746,6 +746,7 @@ since 2026-10-01. - 3D and Materials › Object › Bevel › Reset: the button next to Extrude & Bevel's Bevel heading, in the options dialog and the panel, sets Bevel Shape, Width, Height, Repeat, Space, Bevel Inside and Bevel both sides back to their defaults and leaves the other settings as they are, as one undo step in the panel; it is unavailable while every bevel setting is at its default ([three-d.md](three-d.md#extrude--bevel)); `crates/ui-egui/src/dialogs/revolve/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. +- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light, with shadow maps ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Materials › Properties: Roughness and Metallic sliders set `material: {roughness, metallic}` on Extrude & Bevel, Revolve, Inflate and Rotate; any material other than the default (1 and 0) is shaded with craft-pbr's glTF 2.0 metallic-roughness BRDF, its highlight screened over each face, and glTF and USD exports write the two factors ([three-d.md](three-d.md#material-properties)); `crates/three-d/src/material.rs`, `crates/effects/src/solids/tests_material.rs`, `crates/engine/src/cmd/fileio/mesh3d/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Export 3D Object: the panel's button adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`), one undo step and none when each is an asset already, selects their assets and shows the Asset Export panel ([three-d.md](three-d.md#3d-and-materials-panel)); `panels::three_d::tests::{export_3d_object_adds_the_selected_3d_objects_to_asset_export, export_3d_object_leaves_out_a_3d_object_inside_another}` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. diff --git a/docs/three-d.md b/docs/three-d.md index 30dbe3eb4b..f30b170747 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -53,6 +53,25 @@ pages describe it. not drawn. The mode is saved with the effect and drawn in every output, and Expand Appearance gives the edges as paths. Choosing Wireframe again draws the shaded surface. The 3D (Classic) effects keep their own Wireframe surface. +- **Render Settings › Rendered** draws each selected 3D object as one image of the lit solid instead of its vector + faces, and **Low Quality**, **Medium Quality** and **High Quality** set the image's quality, as the public + [Render 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/render-3d-vector-artwork.html) + page describes Render Settings customizing rendering quality. Choosing a quality also turns Rendered on, and each + choice is one undo step for every selected Extrude & Bevel, Revolve, Inflate and Rotate (`effect.setParams` with + `render`). The image is drawn with a depth buffer, so solids that pass through each other show where they meet; + every light lights it with its color and intensity, with the Roughness and Metallic of the material, and each + light casts shadows on the solid with shadow maps. The effect's shadow ([Shadows](#shadows)) is drawn behind the + image. Low takes one sample a pixel, Medium 2 × 2 and High 3 × 3 (VectorCraft's own values), at the effect's + `resolution` or, without one, at Document Raster Effects Settings › Resolution. A quality whose samples would pass + 16,777,216 pixels takes fewer; past that limit at one sample a pixel, or when the solid can't be placed in one + image, the effect draws its shaded faces. The image keeps transparency where no surface is, or is white with + `background: white`. The image shows opaque solid colors only: a solid painted with a gradient or a pattern, one + with graphics, a paint with an opacity below 100% or in a blending mode other than Normal, and a group member whose opacity mask or blending mode + applies to its solid draw the shaded faces, as do Revolve on a group and Revolve on a fill or stroke. The mode + is saved with the effect. The status bar and the command result's `warning` field report when the shaded faces + are drawn instead. The lighting follows the same lights as the shaded faces but in linear light, so lit + areas differ from the shaded faces' colors. Ambient Light keeps its full range from 0 to 200%; + at 100% with no directional light, the image keeps the paint's colors. - Below them are the Object, Rotation and Lighting tabs of the effect's options dialog, with the same controls and ranges, showing the 3D effect of the first selected object (its own effects first, then those of its fills and strokes). A changed setting goes to the 3D effect of each selected object whose effect takes that setting; @@ -740,8 +759,10 @@ with `symbol` (the name of a document symbol), `face` (`front`, `back` or `side` `threeD.revolve` take `front` only, and `threeD.inflate` `front` or `back`), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, default 0). Other keys, values out of range and graphics on the other 3D effects are rejected before editing. All four take `render` ([3D and Materials panel](#3d-and-materials-panel)): an object whose `mode` is `shaded` (the -default) or `wireframe`. A `render` that is not an object, a key other than `mode`, another mode, and `render` on -the 3D (Classic) effects are rejected before editing. +default), `wireframe` or `rendered`, with `quality` (`low`, `medium` or `high`, default `medium`), `resolution` +(`null`, the default, or 1..2400 ppi) and `background` (`transparent`, the default, or `white`). A `render` that is +not an object, another key, another value, and `render` on the 3D (Classic) effects are rejected before editing; a +file whose `render` breaks these rules draws the shaded faces. All four take `material` ([Material properties](#material-properties)): an object with `roughness` (0..1, default 1) and `metallic` (0..1, default 0); a key left out takes its default. A `material` that is not an object, another key, a value that is not a number from 0 to 1, and `material` on the 3D (Classic) effects are rejected before diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index f4f02f8627..61bee0b431 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "186a229c8da8db5916f8a863dfd894f1879af735"; +const REV: &str = "64383b5906b5a0a14fa4bea21dac379f2deae4bc"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 344545f623d65784937cb9cf40ae6f79e4433554 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:27:51 -0800 Subject: [PATCH 017/103] MCP: regenerate ui_catalog for the showColorPicker description The merge of main left crates/mcp/src/ui_catalog.rs without the sentence the branch added to the screen sampler's description in crates/ui-egui/src/menus/ui_commands.rs, so the gate's ui-commands step failed. The file is regenerated with cargo xtask ui-commands. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..efd3c19495 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1120,7 +1120,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.sampleScreenColor", "Sample Color from Screen", "", - "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", + "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", ), ( "ui.newBrush", From d14a3682db271ad1844731265e96cf75f011e1d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:00:56 -0800 Subject: [PATCH 018/103] Match Objects: sizes fit after the turn, reach any scale and replay with their corner scaling Match Objects measured a target's new size before it was turned, refused sizes that pixel-aligned art reaches before it snaps, and checked only the requested side of a proportional match. A stroke or effect that does not turn with the art, such as a Transform effect's copy, then made a reachable size fail. Each target is now measured in the frame it ends in, before pixel snapping, against both sides; when it misses, the scales in that frame are fitted from the turned object and its reference point is kept in place. A fit that leaves the target at its old angle is refused. The 1e-4 smallest scale of object.setBounds no longer applies, so a 20,000 pt object can be matched down to 1 pt. Match Objects, Set Size of Each, Swap Objects, Replace with Top Object and Sort Objects now pass the journaled Scale Corners (and Transform Pattern Tiles) values to both the size solver and the transform, so a replay scales corners as the run did. Follows up #10072. --- crates/engine/src/cmd/object/bounds.rs | 36 +++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index 205ee265e9..b184dbeccb 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -192,7 +192,8 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor /// change with the y scale and the height with the x scale (a geometry effect can turn the art). A /// scale that `free` marks false stays as it is. The search stops when both sizes are within 1e-9 /// of the sizes wanted (of the largest of 1 and those sizes), when no scale moves, when `measure` -/// finds no box, or after 16 steps, and returns the scales that came nearest. `None` when `measure` +/// finds no box, or after 16 steps. It returns the scales whose box met both stopping tolerances, +/// and otherwise the scales whose box came nearest. `None` when `measure` /// finds no box for `start`. Each stopping tolerance in `tolerances`, when given, is capped at /// the default tolerance. pub(crate) fn refit_drawn( @@ -207,14 +208,15 @@ pub(crate) fn refit_drawn( let tolerance = 1e-9 * w.max(h).max(1.0); let tolerances = tolerances.unwrap_or([tolerance; 2]).map(|t| t.min(tolerance)); let miss = |b: Rect| (b.width() - w).abs() + (b.height() - h).abs(); + let met = |b: Rect| (b.width() - w).abs() <= tolerances[0] && (b.height() - h).abs() <= tolerances[1]; let (mut sx, mut sy) = start; let mut b = measure(sx, sy)?; let mut best = (sx, sy, b); for _ in 0..16 { - let f = [b.width() - w, b.height() - h]; - if f[0].abs() <= tolerances[0] && f[1].abs() <= tolerances[1] { + if met(b) { break; } + let f = [b.width() - w, b.height() - h]; // How the width and the height change with the x scale (`a`) and the y scale (`c`). let change = |x: bool| -> Option<[f64; 2]> { let (on, s) = if x { (free[0], sx) } else { (free[1], sy) }; @@ -244,7 +246,8 @@ pub(crate) fn refit_drawn( } let Some(next) = measure(nx, ny) else { break }; (sx, sy, b) = (nx, ny, next); - if miss(b) < miss(best.2) { + // A box that meets both tolerances wins over a nearer sum that misses one of them. + if met(b) || miss(b) < miss(best.2) { best = (sx, sy, b); } } @@ -300,3 +303,28 @@ fn scaling_box(d: &Document, ids: &[NodeId], frame: &OrientedBox) -> Option Date: Mon, 30 Nov 2026 09:40:13 -0800 Subject: [PATCH 019/103] 3D: rendered images take every light's shadows and a Raster Settings dialog - With Shadows on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, black at 50%, with each light's Softness widening its edge; with Shadows off none does. - Selection, Use Preview Bounds, Align, hit testing and snapping measure the shaded faces without rasterizing. Painted bounds hold the whole image, measured without rasterizing. Images are cached by their inputs. - Expand Appearance and baking keep the rendered image; PDF export in a CMYK document writes it as raster effects are written. - Render Settings gains Raster Settings... (resolution and background), built on the framework's parameter dialog; settings the selection holds differently open blank and are kept. The menu checks a choice only when every selected object has it. - Tests for the clip matrix, coverage, depth order, the shading formula, limits, work bounds, edge values, masks and Revolve's objects-only rule. Docs: docs/three-d.md, docs/mcp.md, effect params text. --- crates/effects/src/bake.rs | 6 +- crates/effects/src/catalog.rs | 2 +- crates/effects/src/lib.rs | 7 +- crates/effects/src/revolve.rs | 51 +- crates/effects/src/solids.rs | 80 ++- crates/effects/src/solids/rendered.rs | 340 ++++++++++-- crates/effects/src/solids/rendered/tests.rs | 559 +++++++++++++++++++- crates/effects/src/solids/shadow.rs | 16 +- crates/effects/src/solids/tests_shadow.rs | 2 +- crates/engine/src/tests/effectedit.rs | 134 +++++ crates/render/src/fx/bounds.rs | 2 +- crates/render/src/fx/renderer.rs | 2 +- crates/render/src/fx/tests.rs | 41 ++ crates/three-d/src/shadow.rs | 86 ++- crates/ui-egui/src/panels/tests_three_d.rs | 142 +++++ crates/ui-egui/src/panels/three_d.rs | 66 ++- crates/ui-egui/src/panels/three_d/raster.rs | 151 ++++++ docs/mcp.md | 3 +- docs/three-d.md | 18 +- 19 files changed, 1576 insertions(+), 132 deletions(-) create mode 100644 crates/ui-egui/src/panels/three_d/raster.rs diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 8138474736..a89005aa21 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -354,7 +354,7 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { if let Some(m) = crate::addons::halftone::halftone_art(d, n) { return Some(bake_pieces(d, m)); } - if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { + if let Some(m) = crate::revolve_art_drawn_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -871,7 +871,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, & /// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and /// effects are dropped. `None` for other kinds of objects. pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option { - if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { + if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -963,7 +963,7 @@ pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option { /// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`]. fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option { - if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) { + if let Some(m) = crate::revolve_art_drawn_in(doc, n).or_else(|| crate::solid_art_drawn_in(doc, n)) { return Some(m); } if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) { diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 1024d6fe0a..31037ccc05 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,7 +241,7 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light with the shadows each casts on the solid, over the effect's shadow, and draws the shaded faces when the image can't be made; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 5f87b5ac2a..0165a000a8 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -95,16 +95,17 @@ pub use reshape::{ has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ - CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, + CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_drawn_in, revolve_art_in, revolve_options, validate_revolve, + validate_revolve_in, }; -pub use solids::rendered::rendered_warning; +pub use solids::rendered::{rendered_warning, three_d_bounds_art_in}; pub use solids::{ BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, render_settings, rendered, renders_image, renders_wireframe, solid_art, - solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, + solid_art_drawn_in, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, }; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 3f36ddb206..3fb7eb6c0a 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -10,7 +10,7 @@ use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; use crate::solids::{ - Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds, + Build, Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds, }; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params}; @@ -845,7 +845,7 @@ pub fn revolve_art(n: &Node) -> Option { /// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be /// resolved. pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { - art_reporting(doc, n, false, false, &mut None) + art_reporting(doc, n, false, Build::Vector, &mut None) } /// [`expand_revolve_art_in`] without a document. @@ -854,10 +854,11 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option { expand_revolve_art_in(None, n) } -/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared -/// command and UI remain unchanged. +/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]): in +/// Render Settings › Rendered, the rendered image where it can be made. The shared command and UI +/// remain unchanged. pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { - art_reporting(doc, n, true, false, &mut None) + art_reporting(doc, n, true, Build::Draw, &mut None) } /// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on @@ -1084,7 +1085,17 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, n: &Node, expand: bool, check_only: bool, warning: &mut Option) -> Option { +/// The art [`revolve_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, +/// the image of the lit surface where it can be made, in place of the shaded faces that +/// [`revolve_art_in`] keeps for bounds, hit testing and snapping. +pub fn revolve_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option { + art_reporting(doc, n, false, Build::Draw, &mut None) +} + +/// [`revolve_art_in`], or with `expand` Revolve's Expand Appearance art, built for `build`, with +/// the reason a rendered image can't be made kept in `warning`. +pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option) -> Option { + let check_only = build == Build::Check; if !has_revolve(n) { return None; } @@ -1105,13 +1116,28 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, chec let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); let p = merged_params(&fx.id, &fx.params); - // Rendered, the surface's image over its shadow; the shaded faces when it can't be made. - let image = crate::render_settings(&fx.id, &p).and_then(|settings| { + // Rendered, the surface's image, with the shadows of every light on the surface and on the + // shadow plane; the shaded faces when it can't be made, and for vector measurements. + let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| { let result = if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) { let b = path.bounds()?; let (paint, opacity, _) = paint_of(item); - surface_meshes(&path, rule, b, fx, rule_options(fx, rule), (&paint, opacity, 1.0), true).and_then(|meshes| { - crate::solids::rendered::art(doc, n.id, &crate::solids::rendered::lighting(&fx.id, &p), &meshes, settings, check_only) + let options = rule_options(fx, rule); + surface_meshes(&path, rule, b, fx, options, (&paint, opacity, 1.0), true).and_then(|meshes| { + let lighting = crate::solids::rendered::lighting(&fx.id, &p); + let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) { + Some(shadow) => { + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let faces = cast_surface(&mut caster, &path, b, options, None)?; + crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces]) + } + None => lighting, + }; + if build == Build::Bounds { + crate::solids::rendered::bounds_art(doc, n.id, &lighting, &meshes, settings) + } else { + crate::solids::rendered::art(doc, n.id, &lighting, &meshes, settings, check_only) + } }) } else { Err(crate::solids::rendered::OPAQUE_ONLY.into()) @@ -1122,11 +1148,6 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, chec return None; } if let Some(image) = image { - if let Some(b) = path.bounds() - && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), None).ok()? - { - children.push(Arc::new(shadow)); - } children.push(image); } else if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of the faces, with no shadow. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 988dc71430..500adff788 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -2046,10 +2046,10 @@ fn art_for( n: &Node, fx: &Effect, shapes: &[Profile], - check_only: bool, + build: Build, warning: &mut Option, ) -> Option { - if check_only && !crate::renders_image(fx) { + if build == Build::Check && !crate::renders_image(fx) { return Some((vec![], vec![])); } // In wireframe mode the effect draws the edges of the faces it builds, with no shadow. @@ -2057,20 +2057,36 @@ fn art_for( return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?)); } let p = crate::merged_params(&fx.id, &fx.params); - // Rendered, the solids' image over the effect's shadow; the shaded faces when it can't be made. - if let Some(settings) = wireframe::render_settings(&fx.id, &p) { + // Rendered, the solids' image, with the shadows of every light on the solids and on the shadow + // plane; the shaded faces when it can't be made, and for vector measurements. + if build != Build::Vector + && let Some(settings) = wireframe::render_settings(&fx.id, &p) + { let image = if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(|s| &s.items), has_masks(shapes)) { - meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES) - .and_then(|meshes| rendered::art(doc, n.id, &rendered::lighting(&fx.id, &p), &meshes, settings, check_only)) + meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| { + let lighting = rendered::lighting(&fx.id, &p); + let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? { + Some((caster, shadow, cast)) => { + let faces: Vec> = cast.iter().map(|c| c.2.clone()).collect(); + rendered::with_receiver(lighting, &caster, shadow, &faces) + } + None => lighting, + }; + if build == Build::Bounds { + rendered::bounds_art(doc, n.id, &lighting, &meshes, settings) + } else { + rendered::art(doc, n.id, &lighting, &meshes, settings, build == Build::Check) + } + }) } else { Err(rendered::OPAQUE_ONLY.into()) }; let image = rendered::reported(image, warning); - if check_only { + if build == Build::Check { return Some((vec![], vec![])); } if let Some(image) = image { - return Some((shadow_for(n.id, fx, shapes).ok()?, vec![image])); + return Some((vec![], vec![image])); } } let cast = casts_shadow(&fx.id, &p); @@ -2105,10 +2121,20 @@ pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result< /// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to /// the part of the shadow they cast too ([`shadow::scoped_art`]). fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result>, String> { + cast_shadow_with(id, p, shapes, shadow::options(p)) +} + +/// [`cast_shadow`] with the shadow settings `settings` in place of those of `p`. +fn cast_shadow_with<'a>( + id: &str, + p: &Value, + shapes: &'a [Profile], + settings: Option, +) -> Result>, String> { if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE { return Ok(None); } - let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) }; + let (Some(settings), Some(b)) = (settings, union_bounds(shapes)) else { return Ok(None) }; let view = view_options(p); let mut caster = vectorcraft_three_d::ShadowCaster::new(); // The faces each solid of visible art added, with its member's scopes and its ink (opacity @@ -2837,16 +2863,38 @@ pub fn solid_art(n: &Node) -> Option { /// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be /// resolved. pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { - solid_art_reporting(doc, n, false, &mut None) + solid_art_reporting(doc, n, Build::Vector, &mut None) } -pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only: bool, warning: &mut Option) -> Option { +/// The art [`solid_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, the +/// image of the lit solids where it can be made ([`rendered`]), in place of the shaded faces that +/// [`solid_art_in`] keeps for bounds, hit testing and snapping. +pub fn solid_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option { + solid_art_reporting(doc, n, Build::Draw, &mut None) +} + +/// What a 3D effect's art is built for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Build { + /// The vector art: the shaded faces and the vector shadow, in every mode but wireframe. No + /// rendered image is made. + Vector, + /// Painted measurement art, with rendered images represented by their rectangles and no pixels. + Bounds, + /// Only whether the rendered image can be made, with the reason in the warning when it can't: + /// no art and no pixels. + Check, + /// The art drawn and exported: the rendered image where it can be made. + Draw, +} + +pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { if !has_solid(n) { return None; } let n = &*resolve(doc, n, "").ok()?; if is_container(n) { - return group_solid_art(doc, n, check_only, warning); + return group_solid_art(doc, n, build, warning); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -2855,7 +2903,7 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only: let remaining: Vec; if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], check_only, warning)?; + let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?; children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. remaining = past_effect(&n.appearance.effects, index); @@ -2872,7 +2920,7 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only: if let Some((index, fx)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item))); let (shadow, surfaces) = - art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], check_only, warning)?; + art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], build, warning)?; let later: Vec = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); let with_later = |mut art: Arc| { Arc::make_mut(&mut art).appearance.effects = later.clone(); @@ -2901,11 +2949,11 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only: /// geometry effects before it reshape the members, those after it bend the result as a whole; the /// group's own fills and strokes are not drawn. `None` when the effect is only on one of the /// group's own fills or strokes, or when its members can't become solids. -fn group_solid_art(doc: Option<&Document>, n: &Node, check_only: bool, warning: &mut Option) -> Option { +fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { let (index, fx) = solid(&n.appearance.effects)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - let (shadow, surfaces) = art_for(doc, n, fx, &shapes, check_only, warning)?; + let (shadow, surfaces) = art_for(doc, n, fx, &shapes, build, warning)?; let children = shadow.into_iter().chain(surfaces).collect(); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs index 803e93d631..a87e5d1fa3 100644 --- a/crates/effects/src/solids/rendered.rs +++ b/crates/effects/src/solids/rendered.rs @@ -34,13 +34,44 @@ pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option, n: &Node) -> Option { + crate::revolve::art_reporting(doc, n, false, super::Build::Bounds, &mut None) + .or_else(|| super::solid_art_reporting(doc, n, super::Build::Bounds, &mut None)) +} + +/// The image rectangle for painted measurements, with the same eligibility and scene limits as +/// the rendered image, without rasterizing or adding an image to the cache. +pub(crate) fn bounds_art( + doc: Option<&vectorcraft_doc::Document>, + id: NodeId, + lighting: &Lighting, + meshes: &[SolidMesh], + settings: RenderSettings, +) -> Result>, String> { + art(doc, id, lighting, meshes, settings, true)?; + let m = measure(meshes, lighting, settings, doc.map_or(72.0, |d| d.raster_ppi()), false, &Limits::default())?; + let object = ImageObject { + key: String::new(), + width: m.cols, + height: m.rows, + xf: Affine::new([m.rect.width() / f64::from(m.cols), 0.0, 0.0, m.rect.height() / f64::from(m.rows), m.rect.x0, m.rect.y0]), + link: None, + placement: Default::default(), + pixels: None, + }; + Ok(Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object)))))) +} + /// The rendered image of `result`, or `None` after a successful check. An error keeps its message /// in `warning` when no earlier reason is there; the caller then draws its shaded faces. pub(crate) fn reported(result: Result>, String>, warning: &mut Option) -> Option> { @@ -58,10 +89,53 @@ pub(crate) fn reported(result: Result>, String>, warning: &mut pub struct Lighting { /// The directional lights ([`vectorcraft_three_d::Revolve::active_lights`]). pub lights: Vec, + /// Each light's shadow diffusion in points, in the same order as `lights`. + pub diffusion: Vec, /// The ambient light, 0 to 2. pub ambient: f64, /// Shading on: off, the solids show their paint unlit, as the shaded faces do. pub shade: bool, + /// Shadows on: each light that lights the art casts shadows on the solids and on + /// [`Lighting::receiver`]. Off, no light casts one. + pub shadows: bool, + /// The part of the shadow plane the shadows fall on, as four corners in mesh space (y up), in + /// order round it ([`receiver`]); `None` without one. + pub receiver: Option<[[f64; 3]; 4]>, +} + +impl Lighting { + /// Does light `l` cast shadows in the image: Shading and Shadows are on and it lights the art? + fn casts(&self, l: &Light) -> bool { + self.shade && self.shadows && l.intensity > 0.0 + } +} + +/// The opacity of the black the shadow plane shows where a shadow falls, as the effect's vector +/// shadow paints it. +const PLANE_SHADOW: f32 = 0.5; + +/// How far the shadow plane reaches past the shadows on it, as a share of the solids' largest size, +/// so a soft edge is not cut. VectorCraft's own value. +const PLANE_MARGIN: f64 = 0.05; + +/// `lighting` with the part of the shadow plane the shadows of the faces in `faces` of `caster` +/// fall on, with settings `shadow`, for every light that casts one ([`Lighting::casts`]). +pub(crate) fn with_receiver( + mut lighting: Lighting, + caster: &vectorcraft_three_d::ShadowCaster, + shadow: vectorcraft_three_d::Shadow, + faces: &[std::ops::Range], +) -> Lighting { + let toward: Vec<[f64; 3]> = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.direction()).collect(); + lighting.diffusion = lighting + .lights + .iter() + .map(|l| caster.shadow_blur(vectorcraft_three_d::Shadow { softness: l.softness, ..shadow }, faces).unwrap_or(0.0)) + .collect(); + let softness = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.softness).fold(0.0, f64::max); + let shadow = vectorcraft_three_d::Shadow { softness, ..shadow }; + lighting.receiver = caster.receiver(shadow, faces, &toward, PLANE_MARGIN).map(|q| q.map(|[x, y, z]| [x, -y, z])); + lighting } /// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page, @@ -97,12 +171,13 @@ pub fn render( limits: &Limits, ) -> Result { let too_large = || TOO_LARGE.to_string(); - let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, settings, doc_ppi, draft, limits)?; - let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k)).ok_or_else(too_large)?; + let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, lighting, settings, doc_ppi, draft, limits)?; + let scale = f64::from(cols * k) / rect.width(); + let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k), scale).ok_or_else(too_large)?; scene.ssaa = k; #[cfg(test)] RASTERIZATIONS.with(|n| n.set(n.get() + 1)); - if lighting.shade { + if scene.lights.iter().any(|l| l.shadow >= 0) { try_shadow_maps(&mut scene, low, limits).map_err(|_| too_large())?; } let (mut image, _) = try_render_cpu(&scene, limits).map_err(|_| too_large())?; @@ -138,14 +213,22 @@ struct Measured { low: bool, } -/// Measure the image and choose its samples without building a scene or producing pixels. -fn measure(meshes: &[SolidMesh], settings: RenderSettings, doc_ppi: f64, draft: bool, limits: &Limits) -> Result { +/// Measure the image of `meshes` and the shadow plane `lighting` places, and choose its samples, +/// without building a scene or producing pixels. +fn measure( + meshes: &[SolidMesh], + lighting: &Lighting, + settings: RenderSettings, + doc_ppi: f64, + draft: bool, + limits: &Limits, +) -> Result { let too_large = || TOO_LARGE.to_string(); let projection = meshes.first().and_then(|m| m.projection).ok_or_else(too_large)?; if meshes.iter().any(|m| m.projection != Some(projection)) { return Err(too_large()); } - let (bounds, z) = extent(meshes, projection).ok_or_else(too_large)?; + let (bounds, z) = extent(meshes, receiver(lighting), projection).ok_or_else(too_large)?; let cell = 72.0 / settings.resolution.unwrap_or(doc_ppi).clamp(1.0, 2400.0); let (cols, rows) = ((bounds.width() / cell).ceil().max(1.0), (bounds.height() / cell).ceil().max(1.0)); let pixels = cols * rows; @@ -164,15 +247,16 @@ fn measure(meshes: &[SolidMesh], settings: RenderSettings, doc_ppi: f64, draft: } /// Check scene limits without allocating raster or shadow depth buffers. The counts follow -/// craft-raster3d at 64383b5906b5a0a14fa4bea21dac379f2deae4bc: lib.rs:178-223, +/// craft-raster3d at 2680a3b3fe464c7afa3d260b33a828fa94e12f6d: lib.rs:178-223, /// scene.rs:242-278,325-328, raster.rs:245-281,307-385,740-747 and /// shadow.rs:109-135,262-276,316-356,413-449,500-515,533-538,576-657. -/// Measured solids lie inside the clip volume and use opaque, visible materials and directional -/// lights only, so each source triangle contributes one bounding box, without clipping or an -/// alpha-discard search. Raster and shadow work have separate budgets, as in the renderer. +/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque, visible +/// materials, the plane's two triangles hold no texture and the lights are directional, so each +/// source triangle contributes one bounding box, without clipping or an alpha-discard search. Raster and shadow work have separate budgets, as in the renderer. fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> { - let m = measure(meshes, settings, ppi, false, limits)?; - let s = scene(meshes, lighting, m.projection, m.z, m.clip, (m.cols * m.samples, m.rows * m.samples)).ok_or(TOO_LARGE)?; + let m = measure(meshes, lighting, settings, ppi, false, limits)?; + let size = (m.cols * m.samples, m.rows * m.samples); + let s = scene(meshes, lighting, m.projection, m.z, m.clip, size, f64::from(size.0) / m.rect.width()).ok_or(TOO_LARGE)?; limits.check(s.width, s.height).map_err(|_| TOO_LARGE)?; if s.indices.len() as u64 / 3 > limits.max_triangles || s.vertices.len() as u64 > limits.max_vertices || s.lights.len() > limits.max_lights { return Err(TOO_LARGE.into()); @@ -206,7 +290,15 @@ fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, pp return Err(TOO_LARGE.into()); } } - if s.lights.is_empty() || s.indices.is_empty() { + // Shadow maps are made only for the lights that cast shadows, from the triangles that cast them. + let casters: Vec<&[u32; 3]> = s + .indices + .as_chunks::<3>() + .0 + .iter() + .filter(|t| s.materials.get(s.vertices[t[0] as usize].material as usize).is_some_and(|m| m.casts_shadows)) + .collect(); + if casters.is_empty() || s.lights.iter().all(|l| l.shadow < 0) { return Ok(()); } let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); @@ -218,10 +310,15 @@ fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, pp } let center = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5); let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0; - let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &vec![1; s.lights.len()]); + let kinds: Vec = s.lights.iter().map(|l| u32::from(l.shadow >= 0)).chain(std::iter::once(0)).collect(); + let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &kinds); + let maps = sizes.iter().flatten().count() as u64; + if maps.saturating_mul(casters.len() as u64) > limits.max_work { + return Err(TOO_LARGE.into()); + } let mut work = 0u64; for (light, size) in s.lights.iter().zip(sizes) { - let Some(size) = size else { continue }; + let (Some(size), true) = (size, light.shadow >= 0) else { continue }; let dir = light.dir.map(f64::from); let eye = [0, 1, 2].map(|k| center[k] - dir[k] * radius * 2.0); let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; @@ -236,7 +333,7 @@ fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, pp ]); let view = [right, down].map(|row| [row[0] as f32, row[1] as f32, row[2] as f32, (-dot(row, eye)) as f32]); let focal = (f64::from(size) * 0.5 / radius) as f32; - for tri in s.indices.as_chunks::<3>().0 { + for tri in &casters { let points = [0, 1, 2].map(|k| { let p = s.vertices[tri[k] as usize].pos; [0, 1].map(|r| f64::from(transform(&view, p, r) * focal + size as f32 * 0.5)) @@ -268,12 +365,19 @@ fn bounding_work(points: [[f64; 2]; 3], size: [u32; 2]) -> u64 { .product() } -/// The page bounds the points of `meshes` project to, and the range of their depths. `None` with no -/// point, a point that isn't finite, or one at or behind the eye. -fn extent(meshes: &[SolidMesh], projection: MeshProjection) -> Option<(Rect, [f64; 2])> { +/// The corners of the shadow plane of `lighting`, in mesh space; none without one. +fn receiver(lighting: &Lighting) -> &[[f64; 3]] { + lighting.receiver.as_ref().map_or(&[], |q| q.as_slice()) +} + +/// The page bounds the points of `meshes` and the shadow plane's corners `plane` project to, and +/// the range of their depths. `None` with no mesh point, a point that isn't finite, or one at or +/// behind the eye. +fn extent(meshes: &[SolidMesh], plane: &[[f64; 3]], projection: MeshProjection) -> Option<(Rect, [f64; 2])> { let mut bounds: Option = None; let mut z = [f64::INFINITY, f64::NEG_INFINITY]; - for p in meshes.iter().flat_map(|m| &m.mesh.positions) { + meshes.iter().flat_map(|m| &m.mesh.positions).next()?; + for p in meshes.iter().flat_map(|m| &m.mesh.positions).chain(plane) { if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) { return None; } @@ -312,8 +416,17 @@ fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4] /// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: every triangle in world /// space (mesh space with y down, as the page is), opaque ones first, then /// those of see-through solids from back to front; one material for each mesh; one parallel light, -/// casting shadows, for each of `lighting`'s lights. -fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection, z: [f64; 2], clip: [[f32; 4]; 4], size: (u32, u32)) -> Option { +/// casting shadows, for each of `lighting`'s lights. `scale` is raster pixels per point, including +/// the samples per image pixel. +fn scene( + meshes: &[SolidMesh], + lighting: &Lighting, + projection: MeshProjection, + z: [f64; 2], + clip: [[f32; 4]; 4], + size: (u32, u32), + scale: f64, +) -> Option { let eye = projection.eye.unwrap_or(z[1] + 1.0); let mut vertices = vec![]; let mut opaque: Vec<[u32; 3]> = vec![]; @@ -357,15 +470,48 @@ fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection, } } clear.sort_by(|a, b| a.1.total_cmp(&b.1)); + // The shadow plane: drawn only where a shadow falls on it, black at the vector shadow's + // opacity, behind every surface, so first in the see-through range. + let mut plane = vec![]; + if let Some(q) = lighting.receiver.filter(|_| lighting.shade && lighting.shadows) { + let edge = |a: [f64; 3], b: [f64; 3]| [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let (e1, e2) = (edge(q[0], q[1]), edge(q[0], q[3])); + let n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + if len.is_finite() && len > 0.0 { + let material = materials.len() as u32; + materials.push(craft_raster3d::Material { + base: [0.0, 0.0, 0.0, 1.0], + opacity: PLANE_SHADOW, + double_sided: true, + shadows_only: true, + receives_shadows: true, + casts_shadows: false, + ..Default::default() + }); + let base = vertices.len() as u32; + for p in q { + vertices.push(Vertex { + pos: [p[0] as f32, -p[1] as f32, p[2] as f32], + normal: [(n[0] / len) as f32, (-n[1] / len) as f32, (n[2] / len) as f32], + uv: [0.0; 2], + tangent: [1.0, 0.0, 0.0, 1.0], + material, + }); + } + plane = vec![[base, base + 1, base + 2], [base, base + 2, base + 3]]; + } + } // Later meshes paint over earlier ones in the shaded faces. Submit their opaque triangles // first so the strict depth test keeps that paint when surfaces share a depth. let opaque_count = (opaque.len() * 3) as u32; - let indices = opaque.into_iter().rev().flatten().chain(clear.into_iter().flat_map(|(t, _)| t)).collect(); + let indices = opaque.into_iter().rev().flatten().chain(plane.into_iter().flatten()).chain(clear.into_iter().flat_map(|(t, _)| t)).collect(); let lights = lighting .lights .iter() + .enumerate() .filter(|_| lighting.shade) - .map(|l| { + .map(|(i, l)| { // The direction the light travels: away from it. let [x, y, z] = l.direction().map(|v| -v); let len = (x * x + y * y + z * z).sqrt(); @@ -379,9 +525,10 @@ fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection, falloff: 0, radius: 0.0, falloff_distance: 0.0, - shadow: 0, + // With Shadows off no light casts one, on the solids or on a plane. + shadow: if lighting.casts(l) { 0 } else { -1 }, shadow_darkness: 1.0, - shadow_diffusion: l.softness as f32, + shadow_diffusion: lighting.diffusion.get(i).map_or(l.softness, |blur| blur * scale) as f32, } }) .collect(); @@ -417,12 +564,17 @@ fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection, /// `image` as an image object of `id`'s art, holding its pixels as a PNG; `None` when it can't be /// encoded. pub fn image_node(id: NodeId, image: &Rendered) -> Option> { + Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(image_object(image)?))))) +} + +/// `image` as an image object holding its pixels as a PNG; `None` when it can't be encoded. +fn image_object(image: &Rendered) -> Option { let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?; let mut png = vec![]; raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; let blob = ImageBlob::png(png); let cell = image.rect.width() / f64::from(image.cols); - let object = ImageObject { + Some(ImageObject { key: blob.content_key(), width: image.cols, height: image.rows, @@ -430,8 +582,7 @@ pub fn image_node(id: NodeId, image: &Rendered) -> Option> { link: None, placement: Default::default(), pixels: Some(Arc::new(blob)), - }; - Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))) + }) } /// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with @@ -456,7 +607,115 @@ pub(crate) fn art( check(meshes, lighting, settings, ppi, &Limits::default())?; return Ok(None); } - image_node(id, &render(meshes, lighting, settings, ppi, false, &Limits::default())?).map(Some).ok_or_else(|| TOO_LARGE.into()) + let key = image_key(meshes, lighting, settings, ppi); + let made = match cached(key) { + Some(made) => made, + None => { + let made = render(meshes, lighting, settings, ppi, false, &Limits::default()) + .and_then(|image| image_object(&image).ok_or_else(|| TOO_LARGE.to_string())); + keep(key, &made); + made + } + }; + made.map(|object| Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object)))))) +} + +/// Most rendered images [`art`] keeps for reuse, and most PNG bytes they hold together. VectorCraft's +/// own values. +const KEPT_IMAGES: usize = 32; +const KEPT_BYTES: usize = 64 << 20; + +/// What [`art`] made, newest last, under the key of what it was made from ([`image_key`]). +type Kept = Vec<(u128, Result)>; + +#[cfg(not(test))] +static KEPT: std::sync::Mutex = std::sync::Mutex::new(Vec::new()); + +#[cfg(test)] +thread_local! { + /// Each test thread keeps its own images, so a test's count of rasterizations doesn't depend on + /// what other tests drew. + static KEPT: std::cell::RefCell = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Run `f` on the kept images; `None` when they can't be reached. +fn with_kept(f: impl FnOnce(&mut Kept) -> T) -> Option { + #[cfg(not(test))] + { + KEPT.lock().ok().map(|mut kept| f(&mut kept)) + } + #[cfg(test)] + { + KEPT.with(|kept| kept.try_borrow_mut().ok().map(|mut kept| f(&mut kept))) + } +} + +/// The image kept under `key`, moved to the newest place. +fn cached(key: u128) -> Option> { + with_kept(|kept| { + let at = kept.iter().position(|(k, _)| *k == key)?; + let entry = kept.remove(at); + let made = entry.1.clone(); + kept.push(entry); + Some(made) + }) + .flatten() +} + +/// Keep `made` under `key`, letting the oldest go past [`KEPT_IMAGES`] or [`KEPT_BYTES`]. +fn keep(key: u128, made: &Result) { + let bytes = |m: &Result| m.as_ref().ok().and_then(|o| o.pixels.as_ref()).map_or(0, |b| b.bytes.len()); + if bytes(made) > KEPT_BYTES { + return; + } + with_kept(|kept| { + kept.retain(|(k, _)| *k != key); + kept.push((key, made.clone())); + while kept.len() > KEPT_IMAGES || kept.iter().map(|(_, m)| bytes(m)).sum::() > KEPT_BYTES { + drop(kept.remove(0)); + } + }); +} + +/// A 128-bit hash of everything a rendered image is made from: every mesh's points, normals, +/// texture coordinates, triangles, color, material and projection, the lights, ambient light, +/// shading, shadows and shadow plane, the render settings and the resolution. Moving, turning or +/// reshaping the object, or changing any setting, changes it; panning and redrawing do not. +fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64) -> u128 { + use std::hash::{Hash, Hasher}; + let half = |seed: u8| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + seed.hash(&mut h); + let mut f = |v: f64| v.to_bits().hash(&mut h); + for m in meshes { + let mesh = &m.mesh; + mesh.positions.iter().chain(&mesh.normals).flatten().for_each(|v| f(*v)); + mesh.uvs.iter().flatten().for_each(|v| f(*v)); + m.color.iter().for_each(|c| f(f64::from(*c))); + f(m.material.roughness()); + f(m.material.metallic()); + if let Some(p) = m.projection { + [p.origin.x, p.origin.y, p.eye.unwrap_or(f64::NAN)].into_iter().for_each(&mut f); + } + f(mesh.positions.len() as f64); + f(mesh.triangles.len() as f64); + } + for l in &lighting.lights { + [l.rotation, l.height, l.intensity, l.softness, f64::from(u8::from(l.behind))].into_iter().chain(l.color).for_each(&mut f); + } + lighting.receiver.iter().flatten().flatten().for_each(|v| f(*v)); + lighting.diffusion.iter().for_each(|v| f(*v)); + f(lighting.diffusion.len() as f64); + [lighting.ambient, f64::from(u8::from(lighting.shade)), f64::from(u8::from(lighting.shadows)), lighting.lights.len() as f64] + .into_iter() + .for_each(&mut f); + [settings.quality as f64, settings.resolution.unwrap_or(f64::NAN), f64::from(u8::from(settings.white)), ppi].into_iter().for_each(&mut f); + for m in meshes { + m.mesh.triangles.hash(&mut h); + } + h.finish() + }; + (u128::from(half(1)) << 64) | u128::from(half(2)) } /// Can the solids of `items` be drawn as a rendered image: is each painted with a solid color (or @@ -476,13 +735,22 @@ pub(crate) fn takes<'a>(items: impl IntoIterator Lighting { - if id == crate::REVOLVE { + let (lights, ambient, shade) = if id == crate::REVOLVE { let o = crate::revolve_options(p); - Lighting { lights: o.active_lights(), ambient: o.ambient, shade: o.shade } + (o.active_lights(), o.ambient, o.shade) } else { let v = super::view_options(p); - Lighting { lights: v.active_lights(), ambient: v.ambient, shade: v.shade } - } + (v.active_lights(), v.ambient, v.shade) + }; + let lit = lights.iter().any(|l| l.intensity > 0.0); + let shadows = super::shadow::rendered_options(p, lit).is_some(); + Lighting { lights, diffusion: vec![], ambient, shade, shadows, receiver: None } +} + +/// The shadow settings a rendered image of a 3D effect with parameters `p` and lights `lighting` +/// draws its shadow plane with; `None` with Shadows off or no light lighting the art. +pub(crate) fn plane_settings(p: &serde_json::Value, lighting: &Lighting) -> Option { + super::shadow::rendered_options(p, lighting.lights.iter().any(|l| l.intensity > 0.0)) } #[cfg(test)] diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index 13f14714c1..965ddeed96 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -24,7 +24,7 @@ fn solid_square(id: &str, color: Color, params: Value) -> Node { /// The art the canvas draws for `n`: Revolve's, else the other 3D effects'. fn drawn(n: &Node) -> Node { - crate::revolve_art(n).or_else(|| super::super::solid_art(n)).unwrap_or_else(|| panic!("no art for {n:?}")) + crate::revolve_art_drawn_in(None, n).or_else(|| super::super::solid_art_drawn_in(None, n)).unwrap_or_else(|| panic!("no art for {n:?}")) } /// The image objects in `art`. @@ -183,7 +183,7 @@ fn side_mapped_graphics_draw_the_shaded_faces_and_report_the_fallback() { "graphics": [{"symbol": "Mark", "face": "side"}], "render": {"mode": "rendered"} }), ); - let art = super::super::solid_art_in(Some(&doc), &n).unwrap(); + let art = super::super::solid_art_drawn_in(Some(&doc), &n).unwrap(); assert!(images(&art).is_empty()); assert!(faces_bounds(&art).is_some()); let mut graphic_drawn = false; @@ -219,9 +219,8 @@ fn ambient_200_percent_is_brighter_than_100_percent() { } } -/// The arms of an extruded U cast shadows across its recess under a light from the right. -#[test] -fn a_concave_solid_casts_a_shadow_on_itself() { +/// An extruded U under a light from the right, with Shadows `shadow`. +fn concave_u(shadow: bool) -> Node { let mut path = BezPath::new(); path.move_to((100.0, 100.0)); for p in [(125.0, 100.0), (125.0, 175.0), (175.0, 175.0), (175.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)] { @@ -234,36 +233,45 @@ fn a_concave_solid_casts_a_shadow_on_itself() { super::super::EXTRUDE, &json!({ "depth": 80, "rotationX": -30, "rotationY": -30, "rotationZ": 0, - "lightRotation": 0, "lightHeight": 25, "lightIntensity": 100, "ambient": 10 + "lightRotation": 0, "lightHeight": 25, "lightIntensity": 100, "ambient": 10, "shadow": shadow }), ) .unwrap(), ); - let (meshes, lighting) = scene_of(&n); + n +} + +/// The most the solids' own shadows darken a pixel's linear red in the image of `n`, against the +/// same scene with no material casting shadows. +fn self_shadow_darkening(n: &Node) -> f32 { + let (meshes, lighting) = scene_of(n); assert_eq!(meshes.len(), 1, "the caster and receiver belong to the same solid"); let projection = meshes[0].projection.unwrap(); - let (rect, z) = extent(&meshes, projection).unwrap(); - let mut shadowed = scene(&meshes, &lighting, projection, z, clip(projection, rect, z).unwrap(), (160, 160)).unwrap(); + let (rect, z) = extent(&meshes, &[], projection).unwrap(); + let mut shadowed = scene(&meshes, &lighting, projection, z, clip(projection, rect, z).unwrap(), (160, 160), 160.0 / rect.width()).unwrap(); let mut unshadowed = shadowed.clone(); for material in &mut unshadowed.materials { material.casts_shadows = false; } let limits = Limits::default(); let draw = |scene: &mut Scene| { - try_shadow_maps(scene, false, &limits).unwrap(); + if scene.lights.iter().any(|l| l.shadow >= 0) { + try_shadow_maps(scene, false, &limits).unwrap(); + } try_render_cpu(scene, &limits).unwrap().0 }; let (shadowed, unshadowed) = (draw(&mut shadowed), draw(&mut unshadowed)); - let (at, darkening) = shadowed - .data - .iter() - .zip(&unshadowed.data) - .enumerate() - .filter(|(_, (a, b))| a[3] == 1.0 && b[3] == 1.0) - .map(|(i, (a, b))| (i, b[0] - a[0])) - .max_by(|a, b| a.1.total_cmp(&b.1)) - .unwrap(); - assert!(darkening > 0.05, "pixel ({}, {}): shadow darkens linear red by {darkening}", at % 160, at / 160); + shadowed.data.iter().zip(&unshadowed.data).filter(|(a, b)| a[3] == 1.0 && b[3] == 1.0).map(|(a, b)| b[0] - a[0]).fold(0.0, f32::max) +} + +/// With Shadows on, the arms of an extruded U cast shadows across its recess under a light from +/// the right; with Shadows off the solid casts none on itself. +#[test] +fn a_concave_solid_casts_a_shadow_on_itself() { + let on = self_shadow_darkening(&concave_u(true)); + assert!(on > 0.05, "Shadows on: the solid's own shadow darkens linear red by {on}"); + let off = self_shadow_darkening(&concave_u(false)); + assert_eq!(off, 0.0, "Shadows off: the solid shadows itself by {off}"); } /// Shading off, the surface shows its paint unlit, as the shaded faces do. @@ -441,7 +449,7 @@ fn check_only_reports_rasterizer_limits_after_measure_succeeds() { let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false})); let (meshes, lighting) = scene_of(&n); let settings = RenderSettings { quality: 0, ..MEDIUM }; - let measured = measure(&meshes, settings, 72.0, false, &Limits::default()).unwrap(); + let measured = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); let triangles = meshes.iter().map(|m| m.mesh.triangles.len() as u64).sum::(); let vertices = meshes.iter().map(|m| m.mesh.positions.len() as u64).sum::(); for limit in ["triangles", "vertices", "work"] { @@ -451,7 +459,7 @@ fn check_only_reports_rasterizer_limits_after_measure_succeeds() { "vertices" => limits.max_vertices = vertices - 1, _ => limits.max_work = u64::from(measured.cols) * u64::from(measured.rows), } - assert!(measure(&meshes, settings, 72.0, false, &limits).is_ok(), "{limit}: image fits"); + assert!(measure(&meshes, &lighting, settings, 72.0, false, &limits).is_ok(), "{limit}: image fits"); let before = RASTERIZATIONS.with(|count| count.get()); let checked = check(&meshes, &lighting, settings, 72.0, &limits); assert_eq!(checked.as_ref().map_err(String::as_str), Err(TOO_LARGE), "{limit}"); @@ -462,9 +470,11 @@ fn check_only_reports_rasterizer_limits_after_measure_succeeds() { #[test] fn check_only_counts_shadow_work_and_lights() { - let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90})); + let n = + solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadow": true})); let (meshes, lighting) = scene_of(&n); assert!(!lighting.lights.is_empty()); + assert!(lighting.shadows); let settings = RenderSettings { quality: 0, ..MEDIUM }; for limit in ["lights", "shadow work"] { let mut limits = Limits::default(); @@ -477,8 +487,13 @@ fn check_only_counts_shadow_work_and_lights() { unlit.shade = false; assert!(check(&meshes, &unlit, settings, 72.0, &limits).is_ok()); assert!(render(&meshes, &unlit, settings, 72.0, false, &limits).is_ok()); + // With Shadows off, no shadow map is made, so the same limit fits. + let mut unshadowed = lighting.clone(); + unshadowed.shadows = false; + assert!(check(&meshes, &unshadowed, settings, 72.0, &limits).is_ok()); + assert!(render(&meshes, &unshadowed, settings, 72.0, false, &limits).is_ok()); } - assert!(measure(&meshes, settings, 72.0, false, &limits).is_ok()); + assert!(measure(&meshes, &lighting, settings, 72.0, false, &limits).is_ok()); assert_eq!(check(&meshes, &lighting, settings, 72.0, &limits), Err(TOO_LARGE.into()), "{limit}"); assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.into()), "{limit}"); } @@ -494,9 +509,503 @@ fn check_only_art_reports_overlapping_faces_past_the_work_limit() { } let meshes = vec![meshes[0].clone(); 200]; let settings = RenderSettings { quality: 0, ..MEDIUM }; - assert!(measure(&meshes, settings, 72.0, false, &Limits::default()).is_ok()); + assert!(measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).is_ok()); let before = RASTERIZATIONS.with(|count| count.get()); assert_eq!(art(None, NodeId(1), &lighting, &meshes, settings, true).map(|_| ()), Err(TOO_LARGE.into())); assert_eq!(RASTERIZATIONS.with(|count| count.get()), before); assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &Limits::default()), Err(TOO_LARGE.into())); } + +/// The page cells (1 pt squares, by their top-left corner) where the rendered image of `n` shows +/// a shadow: covered past alpha 16 outside the bounds of `n`'s shaded faces without a shadow. +fn shadow_cells(n: &Node) -> Vec<(i64, i64)> { + let mut bare = n.clone(); + bare.appearance.effects[0].params["shadow"] = json!(false); + bare.appearance.effects[0].params["render"] = json!({"mode": "shaded"}); + let solid = faces_bounds(&drawn(&bare)).unwrap(); + let list = images(&drawn(n)); + assert_eq!(list.len(), 1, "one image"); + let i = &list[0]; + let decoded = image::load_from_memory(&i.pixels.as_ref().unwrap().bytes).unwrap().to_rgba8(); + let [sx, _, _, sy, x0, y0] = i.xf.as_coeffs(); + let mut out = vec![]; + for (x, y, p) in decoded.enumerate_pixels() { + let (px, py) = (x0 + (f64::from(x) + 0.5) * sx, y0 + (f64::from(y) + 0.5) * sy); + if p[3] > 16 && !solid.inflate(1.0, 1.0).contains(Point::new(px, py)) { + out.push((px.floor() as i64, py.floor() as i64)); + } + } + out +} + +/// A 100 pt square extruded face-on under two low lights, from the right and from the left, at +/// Intensity `right` and `left` (percent), with Shadows `shadow`, rendered. +fn two_lights(right: f64, left: f64, shadow: bool) -> Node { + solid_square( + super::super::EXTRUDE, + Color::rgb(0.7, 0.7, 0.7), + json!({ + "depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, "shadow": shadow, + "lights": [{"rotation": 0, "height": 30, "intensity": right}, {"rotation": 180, "height": 30, "intensity": left}], + "render": {"mode": "rendered", "quality": "low"} + }), + ) +} + +/// Rendered with Shadows on, each light casts its own shadow on the shadow plane: two lights from +/// opposite sides darken one region on each side of the solid. With Shadows off neither appears, +/// and a light at Intensity 0 casts none. +#[test] +fn every_light_casts_a_shadow_on_the_plane() { + let center = 150.0; + let sides = |cells: &[(i64, i64)]| { + let left = cells.iter().filter(|c| (c.0 as f64) < center).count(); + (left, cells.len() - left) + }; + let (left, right) = sides(&shadow_cells(&two_lights(100.0, 100.0, true))); + assert!(left > 50 && right > 50, "two lights: {left} shadow cells on the left, {right} on the right"); + let (left, right) = sides(&shadow_cells(&two_lights(100.0, 0.0, true))); + assert!(left > 50, "the light from the right casts {left} cells to the left"); + assert_eq!(right, 0, "the light at Intensity 0 casts {right} cells to the right"); + let (left, right) = sides(&shadow_cells(&two_lights(0.0, 100.0, true))); + assert!(right > 50 && left == 0, "the light from the left alone: {left} left, {right} right"); + assert_eq!(shadow_cells(&two_lights(100.0, 100.0, false)), vec![], "Shadows off"); +} + +/// Full Softness widens the shadow's transition on the plane by several image pixels at both +/// resolutions, including when the image uses multiple samples per pixel. +#[test] +fn softness_widens_the_shadow_edge_on_the_plane() { + for (resolution, quality) in [(72.0, "low"), (144.0, "medium")] { + let transition = |softness| { + let n = solid_square( + super::super::EXTRUDE, + Color::rgb(0.7, 0.7, 0.7), + json!({ + "depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, + "shadow": true, "shadowDistance": 50, "lightHeight": 45, "lightRotation": 0, + "lightIntensity": 100, "lightSoftness": softness, + "render": {"mode": "rendered", "quality": quality, "resolution": resolution} + }), + ); + let list = images(&drawn(&n)); + assert_eq!(list.len(), 1); + let image = &list[0]; + let decoded = image::load_from_memory(&image.pixels.as_ref().unwrap().bytes).unwrap().to_rgba8(); + let [sx, _, _, sy, x0, y0] = image.xf.as_coeffs(); + let y = ((150.0 - y0) / sy).floor() as u32; + assert!(y < decoded.height()); + let alpha: Vec = + (0..decoded.width()).filter(|x| x0 + (f64::from(*x) + 0.5) * sx < 99.0).map(|x| decoded.get_pixel(x, y)[3]).collect(); + assert!(alpha.contains(&0), "the plane includes an unshadowed region"); + assert!(alpha.iter().any(|a| *a >= 120), "the plane includes a fully shadowed region"); + alpha.iter().filter(|a| **a > 8 && **a < 120).count() + }; + let (hard, soft) = (transition(0), transition(100)); + assert!(soft > hard + (8.0 * resolution / 72.0) as usize, "{resolution} ppi, {quality}: {hard} hard transition pixels, {soft} soft"); + } +} + +/// Measuring the selection with Use Preview Bounds builds the vector art of a rendered 3D object +/// and makes no image; drawing it makes one. +#[test] +fn preview_bounds_do_not_rasterize() { + let mut doc = vectorcraft_doc::Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + for (k, id) in FOUR.into_iter().enumerate() { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + n.id = NodeId(100 + k as u64); + doc.insert(Some(layer), k, n).unwrap(); + } + let ids: Vec = (0..4).map(|k| NodeId(100 + k)).collect(); + let before = RASTERIZATIONS.with(|count| count.get()); + assert!(crate::preview::bounds_of(&doc, &ids, true).is_some()); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "measuring rasterizes"); + for id in &ids { + assert_eq!(images(&drawn(doc.node(*id).unwrap())).len(), 1, "{id:?}"); + } + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before + 4, "drawing rasterizes once for each object"); +} + +/// Painted measurements include the image rectangle under opposite lights without rasterizing, +/// while preview measurements keep the vector art. +#[test] +fn painted_bounds_include_every_lights_shadow_without_rasterizing() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = two_lights(100.0, 100.0, true); + n.appearance.effects[0].id = id.into(); + let before = RASTERIZATIONS.with(|count| count.get()); + let measured = crate::three_d_bounds_art_in(Some(&doc), &n).unwrap(); + let bounds = measured.visual_bounds().unwrap(); + let measured_images = images(&measured); + assert_eq!(measured_images.len(), 1, "{id}: measures the rendered image"); + assert!(measured_images[0].pixels.is_none(), "{id}: no pixels for measurement"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{id}: measuring rasterizes"); + let drawn_images = images(&drawn(&n)); + assert_eq!(drawn_images.len(), 1, "{id}: draws the rendered image"); + let image = Node::new(n.id, NodeKind::Image(Box::new(drawn_images[0].clone()))).visual_bounds().unwrap(); + assert!(bounds.x0 <= image.x0 && bounds.y0 <= image.y0 && bounds.x1 >= image.x1 && bounds.y1 >= image.y1, "{id}: {bounds:?} holds {image:?}"); + let mut bare = n.clone(); + bare.appearance.effects[0].params["shadow"] = json!(false); + let bare = crate::three_d_bounds_art_in(Some(&doc), &bare).unwrap().visual_bounds().unwrap(); + assert!(bounds.x0 < bare.x0 && bounds.x1 > bare.x1, "{id}: shadows extend on both sides"); + let vector = crate::revolve_art_in(Some(&doc), &n).or_else(|| crate::solid_art_in(Some(&doc), &n)).unwrap(); + assert!(images(&vector).is_empty(), "{id}: preview keeps vector art"); + } +} + +/// Drawing the same object again reuses its image; changing its geometry, its material, the +/// resolution or the document's raster resolution makes a new one. +#[test] +fn rendered_images_are_reused_until_an_input_changes() { + let count = || RASTERIZATIONS.with(|count| count.get()); + let base = json!({"render": {"mode": "rendered", "quality": "low"}}); + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), base.clone()); + let doc = |ppi: f64| { + let mut d = vectorcraft_doc::Document::new(400.0, 400.0); + d.raster_effects_ppi = ppi; + d + }; + let draw = |d: &vectorcraft_doc::Document, n: &Node| images(&super::super::solid_art_drawn_in(Some(d), n).unwrap()).len(); + let start = count(); + assert_eq!(draw(&doc(72.0), &n), 1); + assert_eq!(count(), start + 1); + assert_eq!(draw(&doc(72.0), &n), 1); + assert_eq!(count(), start + 1, "a redraw rasterizes again"); + let mut moved = Node::path(NodeId(1), square(130.0, 100.0, 100.0), Appearance::default()); + moved.appearance = n.appearance.clone(); + assert_eq!(draw(&doc(72.0), &moved), 1); + assert_eq!(count(), start + 2, "moving the object reuses the image"); + let mut rough = n.clone(); + rough.appearance.effects[0].params["material"] = json!({"roughness": 0.9}); + assert_eq!(draw(&doc(72.0), &rough), 1); + assert_eq!(count(), start + 3, "a new roughness reuses the image"); + let mut fine = n.clone(); + fine.appearance.effects[0].params["render"] = json!({"mode": "rendered", "quality": "low", "resolution": 144}); + assert_eq!(draw(&doc(72.0), &fine), 1); + assert_eq!(count(), start + 4, "a new resolution reuses the image"); + assert_eq!(draw(&doc(150.0), &n), 1); + assert_eq!(count(), start + 5, "a new document resolution reuses the image"); +} + +/// A group whose 3D effect holds a member with a blending mode or an opacity mask draws the shaded +/// faces, which apply them; without either, the group draws the image. +#[test] +fn masked_or_blended_members_draw_the_shaded_faces() { + for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] { + let group = |member: Node| { + let mut g = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]); + g.appearance.effects.push(crate::new_effect(id, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + g + }; + let member = + || Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + let art = drawn(&group(member())); + assert_eq!(images(&art).len(), 1, "{id}: plain member"); + let mut blended = member(); + blended.blend = vectorcraft_doc::color::BlendMode::Multiply; + let art = drawn(&group(blended)); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: blended member"); + let mut masked = member(); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(member(), false))); + let art = drawn(&group(masked)); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: masked member"); + } +} + +/// Revolve on a group, or on a fill or stroke, draws the shaded faces and reports why. +#[test] +fn revolve_on_a_group_or_a_paint_reports_objects_only() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let rendered = || crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap(); + let member = || Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member())]); + group.appearance.effects.push(rendered()); + assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OBJECTS_ONLY), "group"); + assert!(images(&drawn(&group)).is_empty(), "group"); + let mut fill = member(); + fill.appearance.items[0].effects_mut().push(rendered()); + assert_eq!(crate::rendered_warning(&doc, &fill).as_deref(), Some(OBJECTS_ONLY), "fill"); + assert!(images(&drawn(&fill)).is_empty(), "fill"); + assert_eq!(crate::rendered_warning(&doc, &solid_square(crate::REVOLVE, Color::BLACK, json!({"render": {"mode": "rendered"}}))), None); +} + +/// Baking a rendered object's appearance, as an envelope with Distort Appearance does, keeps its +/// image, for Revolve and the other 3D effects. +#[test] +fn baked_appearance_keeps_the_rendered_image() { + for id in FOUR { + let n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + let baked = crate::bake_appearance(None, &n).unwrap_or_else(|| panic!("{id}: nothing baked")); + assert_eq!(images(&baked).len(), 1, "{id}: the baked appearance has no image"); + } +} + +/// The page point the clip matrix `m` takes mesh point `p` to over image `rect`: the point goes +/// into the scene's frame (y down), through `m`, and from the image's normalized coordinates onto +/// the page. +fn clipped(m: [[f32; 4]; 4], rect: Rect, p: [f64; 3]) -> Point { + let v = [p[0], -p[1], p[2], 1.0]; + let row = |r: usize| (0..4).map(|c| f64::from(m[r][c]) * v[c]).sum::(); + let w = row(3); + let (x, y) = (row(0) / w, row(1) / w); + Point::new(rect.x0 + (x + 1.0) / 2.0 * rect.width(), rect.y0 + (1.0 - y) / 2.0 * rect.height()) +} + +/// The scene's clip matrix places every mesh point where the effect's projection draws it, within +/// 1e-3 pt, for each of the four effects without perspective and at 60 and 160 degrees. +#[test] +fn the_clip_matrix_places_every_mesh_point_where_the_projection_does() { + for id in FOUR { + for perspective in [0.0, 60.0, 160.0] { + let n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"perspectiveAngle": perspective})); + let (meshes, lighting) = scene_of(&n); + let m = measure(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap_or_else(|e| panic!("{id} {perspective}: {e}")); + let mut worst = 0.0f64; + for p in meshes.iter().flat_map(|s| &s.mesh.positions) { + worst = worst.max(clipped(m.clip, m.rect, *p).distance(m.projection.project(*p))); + } + assert!(worst < 1e-3, "{id} at {perspective} degrees: a mesh point lands {worst} pt from its projected point"); + } + } +} + +/// A square facing the viewer covers every pixel more than one pixel inside its outline and none +/// more than one pixel outside it. +#[test] +fn the_image_covers_the_area_the_faces_cover() { + let n = solid_square(super::super::ROTATE, Color::rgb(0.2, 0.5, 0.8), json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let face = faces_bounds(&super::super::solid_art_in(None, &n).unwrap()).unwrap(); + let (mut inside, mut outside) = (0, 0); + for y in 0..image.rows { + for x in 0..image.cols { + let center = Point::new(image.rect.x0 + f64::from(x) + 0.5, image.rect.y0 + f64::from(y) + 0.5); + let a = pixel(&image, x, y)[3]; + if face.inset(-1.0).contains(center) { + inside += 1; + assert_eq!(a, 255, "pixel {x}, {y} inside the face"); + } else if !face.inset(1.0).contains(center) { + outside += 1; + assert_eq!(a, 0, "pixel {x}, {y} outside the face"); + } + } + } + assert!(inside > 9000, "{inside} pixels inside"); + assert!(outside + inside > 0); +} + +/// The depth buffer decides which surface shows: with the mesh's triangles in reverse order, every +/// pixel inside the turned solid shows the same surface. +#[test] +fn the_nearer_surface_shows_whatever_order_the_triangles_come_in() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"rotationX": 40, "rotationY": 50, "rotationZ": 0, "shade": true})); + let (meshes, lighting) = scene_of(&n); + let mut reversed = meshes.clone(); + for m in &mut reversed { + m.mesh.triangles.reverse(); + } + let a = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let b = render(&reversed, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + assert_eq!((a.cols, a.rows), (b.cols, b.rows)); + let differ = a + .pixels + .chunks(4) + .zip(b.pixels.chunks(4)) + .filter(|(p, q)| p[3] == 255 && q[3] == 255 && p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > 2)) + .count(); + let covered = a.pixels.chunks(4).filter(|p| p[3] == 255).count(); + assert!(covered > 5000, "{covered}"); + assert!(differ * 100 <= covered, "{differ} of {covered} covered pixels change with the triangle order"); +} + +/// Cook-Torrance with GGX, Smith-Schlick `k = (r + 1)² / 8` and Schlick's Fresnel, times N·L, for +/// linear base color `base`, `metallic` and `rough` along unit normal `n`, view `v` and light `l`. +fn cook_torrance(base: f64, metallic: f64, rough: f64, n: [f64; 3], v: [f64; 3], l: [f64; 3]) -> f64 { + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let h = [v[0] + l[0], v[1] + l[1], v[2] + l[2]]; + let len = dot(h, h).sqrt(); + let h = h.map(|c| c / len); + let (n_l, n_v, n_h, v_h) = (dot(n, l), dot(n, v), dot(n, h), dot(v, h)); + let a2 = (rough * rough).powi(2); + let d = a2 / (std::f64::consts::PI * (n_h * n_h * (a2 - 1.0) + 1.0).powi(2)); + let k = (rough + 1.0).powi(2) / 8.0; + let g = (n_v / (n_v * (1.0 - k) + k)) * (n_l / (n_l * (1.0 - k) + k)); + let f0 = 0.04 * (1.0 - metallic) + base * metallic; + let f = f0 + (1.0 - f0) * (1.0 - v_h).powi(5); + let spec = d * g / (4.0 * n_v * n_l); + let kd = (1.0 - f) * (1.0 - metallic); + (kd * base / std::f64::consts::PI + f * spec) * n_l * std::f64::consts::PI +} + +/// A face toward the viewer under one light at 45 degrees, Ambient 0, Roughness 0.5, Metallic 0 +/// and 1: its center equals the Cook-Torrance formula times the light's color, within 1e-3 linear. +#[test] +fn a_lit_face_matches_the_shading_formula() { + for metallic in [0.0, 1.0] { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.5, 0.5, 0.5), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 45, "lightIntensity": 100, "ambient": 0, + "material": {"roughness": 0.5, "metallic": metallic}}), + ); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + let scene = scene(&meshes, &lighting, m.projection, m.z, m.clip, (m.cols, m.rows), f64::from(m.cols) / m.rect.width()).unwrap(); + assert_eq!(scene.lights.len(), 1); + let light = &scene.lights[0]; + let target = craft_raster3d::try_render(&scene, &Limits::default()).unwrap(); + let got = target.color[(m.rows / 2 * m.cols + m.cols / 2) as usize]; + let l = light.dir.map(|c| -f64::from(c)); + let base = f64::from(srgb_to_linear(0.5)); + let want = cook_torrance(base, metallic, 0.5, [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], l) * f64::from(light.color[0]); + assert!((f64::from(got[0]) - want).abs() < 1e-3, "metallic {metallic}: {} against {want}", got[0]); + assert_eq!(got[3], 1.0); + } +} + +/// With the default light, Ambient 0, the default material and Softness 0, a face square to the +/// light has the color of the same shaded face within 3 levels. +#[test] +fn a_face_square_to_the_light_has_the_shaded_faces_color() { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.2, 0.5, 0.8), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "ambient": 0, "lightSoftness": 0}), + ); + let mut face = None; + super::super::solid_art_in(None, &n).unwrap().walk(&mut |c| { + if c.path_data().is_some() + && let Some(Paint::Solid { color, .. }) = c.appearance.items.iter().map(|i| i.paint()).find(|p| matches!(p, Paint::Solid { .. })) + { + face.get_or_insert(color.to_rgba8(1.0)); + } + }); + let face = face.unwrap(); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + for c in 0..3 { + assert!(center[c].abs_diff(face[c]) <= 3, "{center:?} against the shaded face's {face:?}"); + } +} + +/// The specular term of the shaded faces (the separable Smith visibility of glTF 2.0) and of the +/// rendered image (Smith-Schlick with `k = (r + 1)² / 8`) differ by at most 0.002 of the light over +/// Roughness 0.05 to 1 and light angles of 0 to 80 degrees from the normal, at a view along it. +#[test] +fn the_two_specular_terms_differ_within_a_bound() { + let mut worst = (0.0f64, 0.0, 0.0); + for r in (1..=20).map(|i| f64::from(i) * 0.05) { + for degrees in (0..=8).map(|i| f64::from(i) * 10.0) { + let t = degrees.to_radians(); + let (n_l, n_v) = (t.cos(), 1.0); + let h_len = (2.0 + 2.0 * n_l).sqrt(); + let n_h = (1.0 + n_l) / h_len; + let a2 = (r * r).powi(2); + let d = a2 / (std::f64::consts::PI * (n_h * n_h * (a2 - 1.0) + 1.0).powi(2)); + let k = (r + 1.0).powi(2) / 8.0; + let schlick = (n_v / (n_v * (1.0 - k) + k)) * (n_l / (n_l * (1.0 - k) + k)) / (4.0 * n_v * n_l); + let one = |x: f64| x + (a2 + (1.0 - a2) * x * x).sqrt(); + let separable = 1.0 / (one(n_l) * one(n_v)); + // F0 0.04, the dielectric default, at the half vector. + let v_h = h_len / 2.0; + let f = 0.04 + 0.96 * (1.0 - v_h).powi(5); + let diff = (d * f * (schlick - separable) * n_l * std::f64::consts::PI).abs(); + if diff > worst.0 { + worst = (diff, r, degrees); + } + } + } + println!("largest specular difference {:.4} at roughness {:.2}, {} degrees", worst.0, worst.1, worst.2); + assert!(worst.0 <= 0.002, "{worst:?}"); +} + +/// An image past the pixel limit at one sample a pixel draws the shaded faces and reports why; the +/// largest mesh the effects make fits the rasterizer's triangle limit. +#[test] +fn an_image_past_the_limits_draws_the_shaded_faces() { + assert!(super::super::MAX_MESH_TRIANGLES as u64 <= Limits::default().max_triangles); + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mut n = Node::path(NodeId(1), square(0.0, 0.0, 3000.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + n.appearance + .effects + .push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "quality": "low", "resolution": 2400}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(TOO_LARGE)); + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some()); +} + +/// Rendering a 40 × 80 pt Extrude at 300 ppi, Medium (2 × 2 samples), fits a work limit of twice +/// the samples its triangles' bounding boxes cover plus one for each triangle, and a limit of half +/// those samples is refused. +#[test] +fn a_medium_render_stays_within_its_work_bound() { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((40.0, 0.0)); + b.line_to((40.0, 80.0)); + b.line_to((0.0, 80.0)); + b.close_path(); + let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "resolution": 300}})).unwrap()); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 1, resolution: Some(300.0), white: false }; + let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + assert_eq!(m.samples, 2); + let samples = u64::from(m.cols) * u64::from(m.rows) * 4; + // Each triangle's bounding box in raster samples, clipped to the raster. + let per_point = f64::from(m.cols * 2) / m.rect.width(); + let mut boxes = 0u64; + let mut triangles = 0u64; + for s in &meshes { + for t in &s.mesh.triangles { + let at: Vec = t.iter().map(|&i| m.projection.project(s.mesh.positions[i as usize])).collect(); + let span = |f: fn(&Point) -> f64, origin: f64, size: f64| { + let lo = at.iter().map(f).fold(f64::INFINITY, f64::min); + let hi = at.iter().map(f).fold(f64::NEG_INFINITY, f64::max); + (((hi - origin) * per_point).ceil().min(size) - ((lo - origin) * per_point).floor().max(0.0) + 1.0).max(0.0) as u64 + }; + boxes += span(|p| p.x, m.rect.x0, f64::from(m.cols * 2)) * span(|p| p.y, m.rect.y0, f64::from(m.rows * 2)); + triangles += 1; + } + } + let mut limits = Limits::default(); + limits.max_work = 2 * boxes + triangles; + assert!(render(&meshes, &lighting, settings, 72.0, false, &limits).is_ok(), "{samples} samples, {boxes} box samples, {triangles} triangles"); + limits.max_work = boxes / 2; + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.to_string()), "the work is counted"); + println!("work bound: {samples} image samples, {boxes} box samples, {triangles} triangles"); +} + +/// Edge values: art with no area makes no image, a mesh with zero-area triangles renders, lights +/// with values that are not numbers are refused, resolutions 1 and 2400 render, and a solid behind +/// the eye at Perspective 160 is refused. +#[test] +fn edge_values_render_or_are_refused() { + let mut empty = Node::path(NodeId(1), PathData::from_bezpath(&BezPath::new()), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + empty.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}})).unwrap()); + assert!(super::super::solid_art_drawn_in(None, &empty).is_none_or(|a| images(&a).is_empty())); + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (mut meshes, mut lighting) = scene_of(&n); + let first = meshes[0].mesh.triangles[0]; + meshes[0].mesh.triangles.push([first[0], first[0], first[1]]); + assert!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).is_ok(), "zero-area triangle"); + for resolution in [1.0, 2400.0] { + let settings = RenderSettings { quality: 0, resolution: Some(resolution), white: false }; + let image = render(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + assert!(image.cols >= 1 && image.rows >= 1, "{resolution} ppi"); + } + lighting.lights[0].intensity = f64::NAN; + lighting.lights[0].rotation = f64::INFINITY; + let bad = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()); + assert!(matches!(bad.as_ref().map_err(String::as_str), Ok(_) | Err(TOO_LARGE)), "{bad:?}"); + let behind = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"perspectiveAngle": 160})); + let (mut meshes, lighting) = scene_of(&behind); + let eye = meshes[0].projection.and_then(|p| p.eye).unwrap(); + meshes[0].mesh.positions[0][2] = eye * 2.0; + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); +} diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs index 7b84214d29..dbdfbb9c30 100644 --- a/crates/effects/src/solids/shadow.rs +++ b/crates/effects/src/solids/shadow.rs @@ -25,12 +25,24 @@ pub(crate) fn options(p: &Value) -> Option { let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied()); let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity); let lit = flag(p, "shade", true) && intensity > 0.0; - (lit && flag(p, "shadow", false)).then(|| Shadow { + (lit && flag(p, "shadow", false)).then(|| settings(p, first)) +} + +/// The shadow a rendered image of `p` draws, in which every light casts one: as [`options`], but on +/// when any light lights the art (`lit`), not only the first. +pub(crate) fn rendered_options(p: &Value, lit: bool) -> Option { + let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied()); + (lit && flag(p, "shade", true) && flag(p, "shadow", false)).then(|| settings(p, first)) +} + +/// The plane settings of `p`, with the softness of light `first` (the single light's without one). +fn settings(p: &Value, first: Option) -> Shadow { + Shadow { position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(), distance: num(p, "shadowDistance", 0.0) / 100.0, bounds: num(p, "shadowBounds", 100.0) / 100.0, softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness), - }) + } } /// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind. diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index ebe082b488..8db614abd7 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -356,7 +356,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() let (path, rule) = profile(&n).unwrap(); vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] }; - let (drawn, _) = art_for(None, &n, fx, &shapes, false, &mut None).unwrap(); + let (drawn, _) = art_for(None, &n, fx, &shapes, Build::Vector, &mut None).unwrap(); let p = crate::merged_params(&fx.id, &fx.params); let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); diff --git a/crates/engine/src/tests/effectedit.rs b/crates/engine/src/tests/effectedit.rs index 889d2f74a4..1eaa7a9764 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -204,3 +204,137 @@ fn rendered_warning_is_in_effect_command_results() { let plain = run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}})); assert!(plain.get("warning").is_none()); } + +/// The color space of each color image (not a soft mask) in PDF `bytes`, in order. +fn image_spaces(bytes: &[u8]) -> Vec { + let text = String::from_utf8_lossy(bytes); + let mut out = vec![]; + for (at, _) in text.match_indices("/Subtype/Image") { + let start = text[..at].rfind(" obj").unwrap_or(0); + let end = text[at..].find("stream").map_or(text.len(), |e| at + e); + let dict = &text[start..end]; + let Some(cs) = dict.find("/ColorSpace") else { continue }; + let name = dict[cs + "/ColorSpace".len()..].trim_start_matches(['[', ' ', '/']); + let space: String = name.chars().take_while(|c| c.is_ascii_alphanumeric()).collect(); + if space != "DeviceGray" { + out.push(space); + } + } + out +} + +/// In a CMYK document, PDF export writes a rendered 3D object as it writes a raster effect: one +/// image in the color space a drop shadow's image takes, kept in RGB by default and converted to +/// CMYK by Press Quality. +#[test] +fn a_rendered_3d_object_in_a_cmyk_pdf_is_written_as_raster_effects_are() { + let spaces = |effect: &str, params: Value, preset: Option<&str>| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + run(&mut s, "paint.setStroke", json!({"none": true})); + run(&mut s, "paint.setFill", json!({"color": "#338ad6"})); + run(&mut s, "effect.apply", json!({"effect": effect, "item": null, "params": params})); + let v = s.execute("document.exportPdf", &preset.map_or(json!({}), |name| json!({"preset": name}))).unwrap(); + image_spaces(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()) + }; + let rendered = json!({"render": {"mode": "rendered", "quality": "low"}}); + let shadow = json!({"x": 6.0, "y": 6.0, "blur": 3.0, "opacity": 75.0}); + for preset in [None, Some("Press Quality")] { + let three_d = spaces("threeD.extrude", rendered.clone(), preset); + let dropped = spaces("stylize.dropShadow", shadow.clone(), preset); + assert_eq!(three_d.len(), 1, "{preset:?}: one image of the rendered object: {three_d:?}"); + assert_eq!(dropped.len(), 1, "{preset:?}: {dropped:?}"); + assert_eq!(three_d, dropped, "{preset:?}: the rendered image takes the drop shadow's color space"); + } + assert_eq!(spaces("threeD.extrude", rendered, Some("Press Quality")), vec!["DeviceCMYK".to_string()]); +} + +/// A selected 100 pt square filled blue with no stroke, rendered by Extrude at Low quality, and +/// `after` (effect, params) applied after it. +fn rendered_square(after: &[(&str, Value)]) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + run(&mut s, "paint.setStroke", json!({"none": true})); + run(&mut s, "paint.setFill", json!({"color": "#338ad6"})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}})); + for (effect, params) in after { + run(&mut s, "effect.apply", json!({"effect": effect, "item": null, "params": params})); + } + s +} + +/// The `/Width` of each color image (not a soft mask) in PDF `bytes`. +fn image_widths(bytes: &[u8]) -> Vec { + let text = String::from_utf8_lossy(bytes); + let mut out = vec![]; + for (at, _) in text.match_indices("/Subtype/Image") { + let start = text[..at].rfind(" obj").unwrap_or(0); + let end = text[at..].find("stream").map_or(text.len(), |e| at + e); + let dict = &text[start..end]; + if dict.contains("/DeviceGray") { + continue; + } + if let Some(w) = dict.find("/Width") { + out.push(dict[w + "/Width".len()..].trim_start().chars().take_while(char::is_ascii_digit).collect::().parse().unwrap()); + } + } + out +} + +/// PDF and SVG export write one image for a rendered 3D object, and Expand Appearance leaves one +/// embedded image of the same size in pixels that covers the object. +#[test] +fn export_and_expand_write_one_image_of_a_rendered_3d_object() { + let mut s = rendered_square(&[]); + let pdf = s.execute("document.exportPdf", &json!({})).unwrap(); + let widths = image_widths(&vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap()); + assert_eq!(widths.len(), 1, "{widths:?}"); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert_eq!(svg.matches("= 200.0 - 1e-6, "the image spans {x0} to {x1}"); +} + +/// The page bounds, in whole points, of the pixels the canvas covers in session `s`. +fn covered(s: &Session) -> (Vec, [u32; 4]) { + let img = + vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, vectorcraft_geom::Rect::new(0.0, 0.0, 300.0, 300.0), 1.0, false); + let mut b = [u32::MAX, u32::MAX, 0, 0]; + for (i, p) in img.pixels.chunks(4).enumerate() { + if p[3] > 8 { + let (x, y) = (i as u32 % img.width, i as u32 / img.width); + b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)]; + } + } + (img.pixels, b) +} + +/// Effects after a rendered 3D effect apply to its image: Gaussian Blur spreads it past its edges, +/// Transform moves it, and Roughen leaves it as it is. +#[test] +fn effects_after_a_rendered_3d_effect_apply_to_its_image() { + let (plain, at) = covered(&rendered_square(&[])); + let (_, blurred) = covered(&rendered_square(&[("blur.gaussian", json!({"radius": 5.0}))])); + assert!(blurred[0] + 2 <= at[0] && blurred[2] >= at[2] + 2, "blurred {blurred:?} against {at:?}"); + let (_, moved) = covered(&rendered_square(&[("distort.transform", json!({"moveH": 50.0}))])); + assert_eq!([moved[0], moved[2]], [at[0] + 50, at[2] + 50], "moved {moved:?} against {at:?}"); + let (rough, _) = covered(&rendered_square(&[("distort.roughen", json!({"size": 5.0}))])); + assert!(rough == plain, "Roughen changes the rendered image"); +} diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2eece1125f..28b7966ea4 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -804,7 +804,7 @@ fn three_d_bounds(symbols: &SymbolBoxes, n: &Node) -> Option> { return None; } let doc = Some(symbols.document()); - let art = effects::revolve_art_in(doc, n).or_else(|| effects::solid_art_in(doc, n))?; + let art = effects::three_d_bounds_art_in(doc, n)?; Some(three_d_art_bounds(symbols, &art)) } diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 67b80e6b41..c119ef8b64 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -715,7 +715,7 @@ impl Renderer { let art = match effects::crop_marks_art(a) .or_else(|| crate::addons::halftone::art(doc, a)) .or_else(|| { - let art = effects::revolve_art_in(Some(doc), a).or_else(|| effects::solid_art_in(Some(doc), a)); + let art = effects::revolve_art_drawn_in(Some(doc), a).or_else(|| effects::solid_art_drawn_in(Some(doc), a)); self.stats.three_d_built += usize::from(art.is_some()); three_d |= art.is_some(); art diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 8b2b1336d1..cfe4fd4066 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -9,6 +9,47 @@ use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, f use crate::tests_fontchange::{fonts_steady, with_fonts_unchanged}; use crate::{RenderOptions, Rendered, Renderer}; +/// Rasterize and culling include the complete rendered image under lights from opposite sides. +#[test] +fn rendered_three_d_painted_bounds_hold_both_shadows() { + let d = Document::new(400.0, 400.0); + for id in [vectorcraft_effects::EXTRUDE, vectorcraft_effects::REVOLVE] { + let mut n = Node::path( + vectorcraft_doc::NodeId(100), + shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + n.appearance.effects.push( + vectorcraft_effects::new_effect( + id, + &json!({ + "depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, "shadow": true, + "lights": [{"rotation": 0, "height": 30, "intensity": 100}, {"rotation": 180, "height": 30, "intensity": 100}], + "render": {"mode": "rendered", "quality": "low"} + }), + ) + .unwrap(), + ); + let rasterize = crate::drawn_bounds(&d, &n).unwrap(); + let culling = crate::painted_bounds(&d, &n).unwrap(); + let art = vectorcraft_effects::revolve_art_drawn_in(Some(&d), &n).or_else(|| vectorcraft_effects::solid_art_drawn_in(Some(&d), &n)).unwrap(); + let mut images = 0; + art.walk(&mut |piece| { + if matches!(piece.kind, vectorcraft_doc::NodeKind::Image(_)) { + images += 1; + let image = piece.visual_bounds().unwrap(); + for bounds in [rasterize, culling] { + assert!( + bounds.x0 <= image.x0 && bounds.y0 <= image.y0 && bounds.x1 >= image.x1 && bounds.y1 >= image.y1, + "{id}: {bounds:?} holds {image:?}" + ); + } + } + }); + assert_eq!(images, 1, "{id}: draws the rendered image"); + } +} + /// The hash renderers compare to redraw art linked to swatches changes with a global swatch's /// color and spot flag and with the Spot Colors option. #[test] diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 8a89f5e3cc..137c0c4996 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -61,6 +61,13 @@ impl Default for Shadow { } impl Shadow { + /// The blur radius in points for a solid whose largest size is `size`. + fn blur(self, size: f64) -> f64 { + let s = self.sanitized(); + let blur = (s.softness * size * (BLUR_NEAR + BLUR_PER_DISTANCE * s.distance)).min(MAX_SHADOW_BLUR); + if blur.is_finite() { blur } else { 0.0 } + } + fn sanitized(self) -> Self { Self { distance: finite(self.distance, 0.0, 0.0, 1.0), @@ -149,6 +156,20 @@ impl ShadowPlane { } } +/// Where a shadow's plane lies ([`ShadowCaster::placement`]): its unit normal toward the object and +/// two unit axes along it, its level along the normal, the foot of the object's center on it, half +/// the side of the square it ends at, and the object's largest size. +#[derive(Clone, Copy, Debug)] +struct Placement { + n: V3, + u: V3, + w: V3, + level: f64, + foot: V3, + half: f64, + size: f64, +} + /// The faces of one object's solids, gathered to cast one shadow. The solids of one object share /// their bounds and view, so they share a projection: the first solid's is kept. Each solid added /// returns the range of its faces, so that the shadow of some of them can be drawn on the plane @@ -261,6 +282,19 @@ impl ShadowCaster { let p = self.projection?; let light = p.light()?; let s = shadow.sanitized(); + let Placement { n, u, w, level, foot, half, size } = self.placement(s, faces)?; + let reach = n.dot(light); + if !reach.is_finite() || reach < MIN_LIGHT { + return None; + } + let blur = s.blur(size); + Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half, blur }) + } + + /// Where the plane of sanitized settings `s` lies for the faces in the ranges `faces`, whatever + /// lights it: `None` when there are none. + fn placement(&self, s: Shadow, faces: &[Range]) -> Option { + let p = self.projection?; let corners = || self.within(faces).flat_map(|face| face.contours.iter().flatten()); let first = *corners().next()?; let (lo, hi) = corners() @@ -274,17 +308,55 @@ impl ShadowCaster { (r(V3(0.0, -1.0, 0.0)), r(V3(1.0, 0.0, 0.0)), r(V3(0.0, 0.0, 1.0))) } }; - let reach = n.dot(light); - if !reach.is_finite() || reach < MIN_LIGHT { - return None; - } // The plane: every corner at least `distance` × size in front of it. let level = corners().map(|v| n.dot(*v)).fold(f64::INFINITY, f64::min) - s.distance * size; let centre = V3((lo.0 + hi.0) / 2.0, (lo.1 + hi.1) / 2.0, (lo.2 + hi.2) / 2.0); let foot = add(centre, scale(n, level - n.dot(centre))); - let blur = (s.softness * size * (BLUR_NEAR + BLUR_PER_DISTANCE * s.distance)).min(MAX_SHADOW_BLUR); - let blur = if blur.is_finite() { blur } else { 0.0 }; - Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half: 2.0 * s.bounds * size, blur }) + Some(Placement { n, u, w, level, foot, half: 2.0 * s.bounds * size, size }) + } + + /// The blur radius in points for `shadow` and the faces in the ranges `faces`, regardless of + /// the light direction; `None` when there are no faces. + pub fn shadow_blur(&self, shadow: Shadow, faces: &[Range]) -> Option { + Some(shadow.blur(self.placement(shadow.sanitized(), faces)?.size)) + } + + /// The rectangle of the plane `shadow` falls on that holds the shadows the faces in the ranges + /// `faces` cast toward each of the lights in `toward` (directions toward a light, in view space, + /// with y down), widened on each side by the blur radius plus `margin` times the faces' largest + /// size and cut where the plane ends: its four corners in view space, in order round it. Every light counts, not only the + /// first. `None` when there are no faces, when no light reaches the plane, or when no shadow falls + /// within it. + pub fn receiver(&self, shadow: Shadow, faces: &[Range], toward: &[[f64; 3]], margin: f64) -> Option<[[f64; 3]; 4]> { + let Placement { n, u, w, level, foot, half, size } = self.placement(shadow.sanitized(), faces)?; + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for t in toward { + let light = V3(t[0], t[1], t[2]).unit(); + let reach = n.dot(light); + if !reach.is_finite() || reach < MIN_LIGHT { + continue; + } + for v in self.within(faces).flat_map(|face| face.contours.iter().flatten()) { + let d = add(*v, scale(light, -(n.dot(*v) - level) / reach)).sub(foot); + let q = [u.dot(d), w.dot(d)]; + for k in 0..2 { + lo[k] = lo[k].min(q[k]); + hi[k] = hi[k].max(q[k]); + } + } + } + let m = shadow.blur(size) + if margin.is_finite() { margin.max(0.0) * size } else { 0.0 }; + let [a0, b0] = [0, 1].map(|k| (lo[k] - m).clamp(-half, half)); + let [a1, b1] = [0, 1].map(|k| (hi[k] + m).clamp(-half, half)); + if !(a1 > a0 && b1 > b0) { + return None; + } + let at = |a: f64, b: f64| { + let p = add(foot, add(scale(u, a), scale(w, b))); + [p.0, p.1, p.2] + }; + let corners = [at(a0, b0), at(a1, b0), at(a1, b1), at(a0, b1)]; + corners.iter().flatten().all(|v| v.is_finite()).then_some(corners) } /// The shadow the faces in the ranges `faces` cast on `plane`, on the page, filled with the diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 5f99fdf05e..4a61d5ba22 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1624,3 +1624,145 @@ fn rendered_warning_reaches_the_status_bar() { super::set_render(&mut app, "rendered", Some("low")); assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); } + +/// The panel with the window's dialogs run and their held answers applied, as in the app's frame. +fn show_with_dialogs(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + app.ui_ctx = Some(ui.ctx().clone()); + show(app, ui); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + crate::dialogs::host::pump(app, ui.ctx()); +} + +/// Two squares with Extrude & Bevel, `a` with the default render settings and `b` rendered at +/// High quality, 150 ppi, on white, selected `b` first. Returns the app and their ids. +fn two_renders() -> (VectorcraftApp, u64, u64) { + let mut app = app(); + let a = app.session.active().unwrap().selection.objects[0].0; + set_type(&mut app, "extrude").unwrap(); + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + let render = json!({"mode": "rendered", "quality": "high", "resolution": 150, "background": "white"}); + app.run("effect.setParams", json!({"index": 0, "item": null, "params": {"render": render}})).unwrap(); + app.run("select.set", json!({"ids": [b, a]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects[0].0, b); + (app, a, b) +} + +/// Object `id`'s 3D effect's render settings. +fn render_of(app: &VectorcraftApp, id: u64) -> Value { + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params["render"].clone() +} + +/// Render Settings lists Wireframe, Rendered, the three qualities and Raster Settings…. A mode or +/// quality the selected objects hold differently shows no check; choosing one sets it on every +/// object in one undo step, and choosing what every object already holds records none. +#[test] +fn render_settings_menu_shows_a_mixed_selection_unchecked() { + use craft::behavior::Mixed; + + use crate::tests::panel_harness::Panel; + + let (app, a, b) = two_renders(); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + for name in ["Wireframe", "Rendered", "Low Quality", "Medium Quality", "High Quality", "Raster Settings…"] { + assert!(panel.shows(name), "the menu lists {name}"); + } + for name in ["Wireframe", "Rendered", "High Quality"] { + assert_ne!(panel.toggled(name), Some(Mixed::Same(true)), "a mixed selection checks {name}"); + } + let history = undo_len(&panel.app()); + panel.click("High Quality"); + assert_eq!(undo_len(&panel.app()), history + 1, "the choice is one undo step for the selection"); + for id in [a, b] { + let render = render_of(&panel.app(), id); + assert_eq!((render["mode"].as_str(), render["quality"].as_str()), (Some("rendered"), Some("high")), "{id}"); + } + panel.click("Render Settings"); + assert_eq!(panel.toggled("Rendered"), Some(Mixed::Same(true))); + assert_eq!(panel.toggled("High Quality"), Some(Mixed::Same(true))); + panel.click("High Quality"); + assert_eq!(undo_len(&panel.app()), history + 1, "choosing what every object holds records no undo step"); +} + +/// Raster Settings… opens blank on the settings the selected objects hold differently, and OK +/// leaves those as each object has them. OK sets the edited settings on every object in one undo +/// step, and records none when every object already holds them. +#[test] +fn raster_settings_sets_resolution_and_background() { + use craft::ui::dialog::dialog_id; + use craft::ui::patterns::form_dialogs::HostedParamDialog; + + use crate::tests::panel_harness::Panel; + + let (app, a, b) = two_renders(); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + let (id, ctx) = (dialog_id(super::raster::KIND), panel.ctx().clone()); + let is_open = |panel: &Panel| panel.app().dialogs().is_some_and(|d| d.with(|host| host.get_mut_by_id::(id).is_some())); + let set = |panel: &Panel, key: &str, value: Value| panel.app().dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, key, value)).unwrap(); + let ok = |panel: &mut Panel| { + panel.app().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + panel.frame(); + panel.frame(); + }; + let open = |panel: &mut Panel| { + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + assert!(is_open(panel)); + }; + open(&mut panel); + for name in ["Use Document Raster Effects Resolution", "Transparent", "White"] { + assert!(panel.shows(name), "the dialog shows {name}"); + } + // One object takes the document's resolution and the other 150 ppi: the switch is blank, the + // resolution field shows the one resolution given, and neither background is picked. + use craft::behavior::Mixed; + let switch = panel.toggled("Use Document Raster Effects Resolution"); + assert!(!matches!(switch, Some(Mixed::Same(_))), "the switch shows {switch:?} for a mixed selection"); + for name in ["Transparent", "White"] { + assert_ne!(panel.toggled(name), Some(Mixed::Same(true)), "{name} is shown picked for a mixed selection"); + } + let role = craft::ui::contract::Role::SPIN_BUTTON; + assert_eq!(panel.value_role("Resolution (ppi)", role).as_deref(), Some("150")); + let history = undo_len(&panel.app()); + let renders = |panel: &Panel| { + let app = panel.app(); + (render_of(&app, a), render_of(&app, b)) + }; + let before = renders(&panel); + ok(&mut panel); + assert!(!is_open(&panel)); + assert_eq!(undo_len(&panel.app()), history, "OK with every field blank changes nothing"); + assert_eq!(renders(&panel), before); + open(&mut panel); + set(&panel, "background", json!("white")); + ok(&mut panel); + assert_eq!(undo_len(&panel.app()), history + 1, "OK is one undo step for the selection"); + assert_eq!(render_of(&panel.app(), a).get("resolution"), None, "a blank resolution stays as the object has it"); + assert_eq!(render_of(&panel.app(), b)["resolution"], 150); + for id in [a, b] { + assert_eq!(render_of(&panel.app(), id)["background"], "white", "{id}"); + } + open(&mut panel); + set(&panel, "document", json!(false)); + set(&panel, "resolution", json!(300)); + ok(&mut panel); + assert_eq!(undo_len(&panel.app()), history + 2); + for id in [a, b] { + assert_eq!(render_of(&panel.app(), id)["resolution"].as_f64(), Some(300.0), "{id}"); + } + open(&mut panel); + ok(&mut panel); + assert_eq!(undo_len(&panel.app()), history + 2, "OK with what every object holds records no undo step"); + open(&mut panel); + set(&panel, "document", json!(true)); + ok(&mut panel); + for id in [a, b] { + assert_eq!(render_of(&panel.app(), id)["resolution"], Value::Null, "{id}"); + } +} diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index cacaef0ec8..0aa40b8b55 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -33,6 +33,7 @@ use crate::dialogs::three_d_materials as materials; pub(crate) mod handles; pub(crate) use handles::FrameKey; +pub(crate) mod raster; /// The panel's id (`window.panel`). pub const ID: &str = "threeD"; @@ -359,7 +360,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; if takes_render(&t.effect) { - render_settings(app, ui, &t); + render_settings(app, ui); } let (params, fields) = rows(app, &t); let out = ParamRows::new(tl!("3D and Materials"), ¶ms, Bind::given(fields.clone())).show(ui); @@ -499,29 +500,62 @@ fn render_of(t: &Target) -> Map { p.get(vectorcraft_effects::RENDER).and_then(Value::as_object).cloned().unwrap_or_default() } -/// The Render Settings menu at the top of the panel: Wireframe, checked while the first selected -/// object's 3D effect draws the edges of its faces; Rendered, checked while it draws an image of -/// the lit solid; and the rendered image's Low, Medium and High quality. Choosing Wireframe or -/// Rendered turns that mode on or off, and choosing a quality renders at it ([`set_render`]), for -/// every selected object's 3D effect. -fn render_settings(app: &mut VectorcraftApp, ui: &mut Ui, t: &Target) { - let render = render_of(t); - let mode = render.get("mode").and_then(Value::as_str).unwrap_or("shaded"); - let quality = render.get("quality").and_then(Value::as_str).unwrap_or("medium"); - let rendered = mode == "rendered"; +/// Render setting `key` in `render`, or the value it takes when it is left out. +fn render_value(render: &Map, key: &str) -> Value { + render.get(key).cloned().unwrap_or_else(|| match key { + "mode" => json!("shaded"), + "quality" => json!("medium"), + "background" => json!("transparent"), + _ => Value::Null, + }) +} + +/// The render settings of each selected object whose 3D effect takes them. +fn selected_renders(app: &VectorcraftApp) -> Vec> { + let Some(st) = app.session.active() else { return vec![] }; + st.selection.objects.iter().filter_map(|id| find(st.doc.node(*id)?)).filter(|t| takes_render(&t.effect)).map(|t| render_of(&t)).collect() +} + +/// The value render setting `key` has in every one of `renders`; `None` when they hold it +/// differently, or with none. +fn shared_render(renders: &[Map], key: &str) -> Option { + let mut values = renders.iter().map(|r| render_value(r, key)); + let first = values.next()?; + values.all(|v| v == first).then_some(first) +} + +/// The Render Settings menu at the top of the panel: Wireframe, checked while every selected +/// object's 3D effect draws the edges of its faces; Rendered, checked while every one draws an +/// image of the lit solid; the rendered image's Low, Medium and High quality, checked while every +/// one renders at it; and Raster Settings… ([`raster`]). A setting the selected objects hold +/// differently shows no check. Choosing Wireframe or Rendered turns that mode on, or off when it +/// is checked, and choosing a quality renders at it ([`set_render`]), for every selected object's +/// 3D effect. +fn render_settings(app: &mut VectorcraftApp, ui: &mut Ui) { + let renders = selected_renders(app); + let (mode, quality) = (shared_render(&renders, "mode"), shared_render(&renders, "quality")); + let is = |v: &Option, s: &str| v.as_ref().and_then(Value::as_str) == Some(s); + let (wireframe, rendered) = (is(&mode, "wireframe"), is(&mode, "rendered")); let opener = Button::new(tl!("Render Settings")).show(ui); let entries = [ - Entry::new(0usize, tl!("Wireframe")).checked(mode == "wireframe"), + Entry::new(0usize, tl!("Wireframe")).checked(wireframe), Entry::new(1, tl!("Rendered")).checked(rendered), - Entry::new(2, tl!("Low Quality")).checked(rendered && quality == "low"), - Entry::new(3, tl!("Medium Quality")).checked(rendered && quality == "medium"), - Entry::new(4, tl!("High Quality")).checked(rendered && quality == "high"), + Entry::new(2, tl!("Low Quality")).checked(rendered && is(&quality, "low")), + Entry::new(3, tl!("Medium Quality")).checked(rendered && is(&quality, "medium")), + Entry::new(4, tl!("High Quality")).checked(rendered && is(&quality, "high")), + Entry::new(5, tl!("Raster Settings…")), ]; let picked = Menu::new(tl!("Render Settings")).values().opened_by(&opener, Trigger::Press).pick(ui, &entries).picked; match picked { - Some(0) => set_render(app, if mode == "wireframe" { "shaded" } else { "wireframe" }, None), + Some(0) => set_render(app, if wireframe { "shaded" } else { "wireframe" }, None), Some(1) => set_render(app, if rendered { "shaded" } else { "rendered" }, None), Some(k @ 2..=4) => set_render(app, "rendered", vectorcraft_effects::RENDER_QUALITIES.get(k - 2).copied()), + Some(5) => { + finish(app); + if let Err(e) = raster::open(app) { + app.ui.status = e; + } + } _ => {} } } diff --git a/crates/ui-egui/src/panels/three_d/raster.rs b/crates/ui-egui/src/panels/three_d/raster.rs new file mode 100644 index 0000000000..b13523c5bd --- /dev/null +++ b/crates/ui-egui/src/panels/three_d/raster.rs @@ -0,0 +1,151 @@ +//! Render Settings › Raster Settings…: the resolution and background of the rendered image of each +//! selected object's 3D effect. +//! +//! Fields: `document` (Use Document Raster Effects Resolution), `resolution` (1 to 2400 ppi) and +//! `background` (`transparent` or `white`). A field the selected objects hold differently opens +//! blank, and OK leaves it as each object has it. OK runs one `effect.setParams` over the +//! selection, one undo step, which records none when every object already holds what it sets. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use serde_json::{Map, Value, json}; + +use super::{Live, finish, selected_renders, send, shared_render}; +use crate::VectorcraftApp; +use crate::dialogs::host::open_held; + +/// The dialog's key. +pub(crate) const KIND: &str = "threeDRasterSettings"; + +/// The message OK shows when Use Document Raster Effects Resolution is off and no resolution is +/// given. +const NO_RESOLUTION: &str = "Type a resolution from 1 to 2400 ppi"; + +/// Opens Raster Settings on the selected objects' render settings. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result<(), String> { + let renders = selected_renders(app); + if renders.is_empty() { + return Err("select an object with a 3D effect".into()); + } + let ppi = app.session.active().map_or(72.0, |st| st.doc.raster_ppi()); + let resolutions: Vec> = renders.iter().map(|r| r.get("resolution").and_then(Value::as_f64)).collect(); + let mut fields = DialogFields::new(); + let document = if resolutions.iter().all(Option::is_none) { + Some(true) + } else if resolutions.iter().all(Option::is_some) { + Some(false) + } else { + None + }; + match document { + Some(d) => fields.set("document", FieldValue::Bool(d)), + None => fields.set_mixed("document"), + } + let mut given = resolutions.iter().flatten(); + let opening = match given.next() { + None => Some(ppi), + Some(first) if given.all(|r| r == first) => Some(*first), + Some(_) => None, + }; + match opening { + Some(r) => fields.set("resolution", FieldValue::Number(r)), + None => fields.set_mixed("resolution"), + } + match shared_render(&renders, "background").as_ref().and_then(Value::as_str) { + Some(b) => fields.set("background", FieldValue::Text(b.into())), + None => fields.set_mixed("background"), + } + let ctx = app.ui_ctx.clone().ok_or("no window")?; + let dialog = HostedParamDialog::new(&ctx, KIND, fields, |fields| dialog().values(Bind::bound(fields))); + let opened = Opened { document, resolution: opening }; + open_held(app, dialog, move |app, answer| ok(app, answer, opened)).ok_or("no window")?; + Ok(()) +} + +/// The dialog over its rows. +fn dialog<'a>() -> ParamDialog<'a> { + let backgrounds = vec![("transparent".to_owned(), tl!("Transparent").into()), ("white".to_owned(), tl!("White").into())]; + let params = vec![ + Param::new("document", tl!("Use Document Raster Effects Resolution"), ParamKind::bool(true)), + Param::number("resolution", tl!("Resolution (ppi):"), 72.0, 1.0, 0).bounds(Some(1.0), Some(2400.0)).enabled_when("document", false), + Param::new("background", tl!("Background:"), ParamKind::radio(backgrounds, None)), + ]; + ParamDialog::new(KIND, tl!("Raster Settings"), params) +} + +/// The values the dialog opened on; `None` for a field that opened blank. +#[derive(Clone, Copy, Debug)] +struct Opened { + document: Option, + resolution: Option, +} + +/// The render settings the answer `f` sets, given the values the dialog opened on: a field left +/// blank sets nothing, and a resolution sets only when it was changed or the document's resolution +/// was switched off. +fn edited(f: &DialogFields, opened: Opened) -> Result, String> { + let mut render = Map::new(); + let resolution = f.number("resolution"); + match f.bool("document") { + Some(true) => { + render.insert("resolution".into(), Value::Null); + } + // Every object already has its own resolution: a blank one leaves each as it is. + Some(false) if opened.document == Some(false) && resolution.is_none() => {} + Some(false) => { + render.insert("resolution".into(), json!(resolution.ok_or(NO_RESOLUTION)?)); + } + None => { + if let Some(r) = resolution.filter(|r| Some(*r) != opened.resolution) { + render.insert("resolution".into(), json!(r)); + } + } + } + if let Some(background) = f.text("background") { + render.insert("background".into(), json!(background)); + } + Ok(render) +} + +/// OK: sets the edited render settings on every selected object's 3D effect, one undo step. +fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: Opened) -> Result<(), String> { + let render = edited(&answer.fields, opened)?; + if render.is_empty() { + return Ok(()); + } + finish(app); + let mut changed = Map::new(); + changed.insert(vectorcraft_effects::RENDER.into(), Value::Object(render)); + send(app, changed, Live::Released); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fields(set: &[(&str, FieldValue)]) -> DialogFields { + let mut f = DialogFields::new(); + for (key, value) in set { + f.set(*key, value.clone()); + } + f + } + + /// With the document's resolution switched off and no resolution given, OK keeps the dialog + /// open with the reason; when every object already had its own resolutions, which differ, a + /// blank resolution keeps them and Background alone is set. With the switch blank, an unchanged + /// resolution sets nothing and a changed one sets it. + #[test] + fn ok_needs_a_resolution_and_keeps_blank_fields() { + let on = Opened { document: Some(true), resolution: Some(72.0) }; + assert_eq!(edited(&fields(&[("document", FieldValue::Bool(false))]), on), Err(NO_RESOLUTION.to_string())); + let own = Opened { document: Some(false), resolution: None }; + let kept = edited(&fields(&[("document", FieldValue::Bool(false)), ("background", FieldValue::Text("white".into()))]), own).unwrap(); + assert_eq!(kept, Map::from_iter([("background".to_string(), json!("white"))])); + let mixed = Opened { document: None, resolution: Some(150.0) }; + assert_eq!(edited(&fields(&[("resolution", FieldValue::Number(150.0))]), mixed), Ok(Map::new())); + let changed = edited(&fields(&[("resolution", FieldValue::Number(200.0))]), mixed).unwrap(); + assert_eq!(changed.get("resolution").and_then(Value::as_f64), Some(200.0)); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index e2ffe5008b..3ea1024775 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6453,7 +6453,8 @@ Geometry effects after the 3D effect reshape the drawn edges. Expand as Wirefram joins the edges, so with such an effect its paths can differ from the drawn ones. The mode is saved in the native file, SVG and PDF exports draw the edges, and `effect.expandAppearance` keeps them as paths. Past 1,000,000 edges the source path is drawn, as it is for a solid past its limits. In rendered mode the effect draws its solid as one image with a depth buffer, lit -by every light, with the shadows each light casts on the solid, over the effect's shadow. `render` then also takes +by every light. With `shadow` on, every light with an intensity above 0 casts shadows on the solid and on the +effect's shadow plane, drawn in the image; with it off, none does. `render` then also takes `quality` (`"low"`, `"medium"` or `"high"`: 1, 2 × 2 or 3 × 3 samples a pixel, default `"medium"`, VectorCraft's own values), `resolution` (`null` for Document Raster Effects Settings › Resolution, the default, or 1..2400 ppi) and `background` (`"transparent"`, the default, or `"white"`). A quality whose samples would pass 16,777,216 pixels diff --git a/docs/three-d.md b/docs/three-d.md index ff01d818ef..e365dd52eb 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -59,10 +59,20 @@ pages describe it. page describes Render Settings customizing rendering quality. Choosing a quality also turns Rendered on, and each choice is one undo step for every selected Extrude & Bevel, Revolve, Inflate and Rotate (`effect.setParams` with `render`). The image is drawn with a depth buffer, so solids that pass through each other show where they meet; - every light lights it with its color and intensity, with the Roughness and Metallic of the material, and each - light casts shadows on the solid with shadow maps. The effect's shadow ([Shadows](#shadows)) is drawn behind the - image. Low takes one sample a pixel, Medium 2 × 2 and High 3 × 3 (VectorCraft's own values), at the effect's - `resolution` or, without one, at Document Raster Effects Settings › Resolution. A quality whose samples would pass + every light lights it with its color and intensity, with the Roughness and Metallic of the material. With + [Shadows](#shadows) on, every light with an Intensity above 0 casts shadows, on the solid itself and on the plane + the effect's Position, Distance and Shadow Bounds place, where they show in black at 50% (VectorCraft's own value); + the public + [Create 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-vector-artwork.html) + page describes the shadows of all the lights appearing in a full render, while the preview shows one. With Shadows + off, no light casts a shadow. Low takes one sample a pixel, Medium 2 × 2 and High 3 × 3 (VectorCraft's own + values), at the effect's `resolution` or, without one, at Document Raster Effects Settings › Resolution. + **Render Settings › Raster Settings…** sets Use Document Raster Effects Resolution, Resolution (1 to 2400 ppi) and + Background (Transparent or White) for every selected object in one undo step, as the Render 3D vector artwork page + describes Raster Settings changing the resolution and background. A setting the selected objects hold differently + opens blank and is left as each object has it; Rendered and the qualities show unchecked for such a selection. + The selection box, Use Preview Bounds, Align, hit testing and snapping measure the shaded faces, and the image is + made only when the object is drawn, then reused until an input to it changes. A quality whose samples would pass 16,777,216 pixels takes fewer; past that limit at one sample a pixel, or when the solid can't be placed in one image, the effect draws its shaded faces. The image keeps transparency where no surface is, or is white with `background: white`. The image shows opaque solid colors only: a solid painted with a gradient or a pattern, one From ee5463ff2b6d8157079a6091c888149c4efb0c0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 10:11:48 -0800 Subject: [PATCH 020/103] 3D: Raster Settings shows why a rendered image falls back OK in Raster Settings now shows the reason in the status bar when the new settings make the rendered image fall back to the shaded faces, as the Render Settings menu does. --- crates/ui-egui/src/panels/tests_three_d.rs | 29 +++++++++++++++++++++ crates/ui-egui/src/panels/three_d.rs | 10 +++++-- crates/ui-egui/src/panels/three_d/raster.rs | 3 ++- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 4a61d5ba22..f5775cf804 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1625,6 +1625,35 @@ fn rendered_warning_reaches_the_status_bar() { assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); } +/// Raster Settings OK shows why a rendered image falls back to shaded faces at a higher resolution. +#[test] +fn raster_settings_rendered_warning_reaches_the_status_bar() { + use craft::ui::dialog::dialog_id; + + use crate::tests::panel_harness::Panel; + + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 3000, "height": 3000})).unwrap()["id"].as_u64().unwrap(); + app.run( + "effect.apply", + json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered", "quality": "low", "resolution": 1}}}), + ) + .unwrap(); + app.ui.status.clear(); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + let (dialog, ctx) = (dialog_id(super::raster::KIND), panel.ctx().clone()); + panel.app().dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog, "resolution", json!(2400))).unwrap(); + panel.app().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + panel.frame(); + panel.frame(); + assert_eq!(render_of(&panel.app(), id)["resolution"].as_f64(), Some(2400.0)); + assert_eq!(panel.app().ui.status, vectorcraft_effects::rendered::TOO_LARGE); +} + /// The panel with the window's dialogs run and their held answers applied, as in the app's frame. fn show_with_dialogs(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.ui_ctx = Some(ui.ctx().clone()); diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index 0aa40b8b55..85549c7af7 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -580,8 +580,14 @@ pub(crate) fn set_render(app: &mut VectorcraftApp, mode: &str, quality: Option<& let mut changed = Map::new(); changed.insert(vectorcraft_effects::RENDER.into(), Value::Object(render)); send(app, changed, Live::Released); - if mode == "rendered" - && let Some(st) = app.session.active() + if mode == "rendered" { + show_rendered_warning(app); + } +} + +/// Shows the first rendered fallback warning for selected objects whose effects take render settings. +pub(crate) fn show_rendered_warning(app: &mut VectorcraftApp) { + if let Some(st) = app.session.active() && let Some(message) = st .selection .objects diff --git a/crates/ui-egui/src/panels/three_d/raster.rs b/crates/ui-egui/src/panels/three_d/raster.rs index b13523c5bd..1f91e959ed 100644 --- a/crates/ui-egui/src/panels/three_d/raster.rs +++ b/crates/ui-egui/src/panels/three_d/raster.rs @@ -10,7 +10,7 @@ use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use serde_json::{Map, Value, json}; -use super::{Live, finish, selected_renders, send, shared_render}; +use super::{Live, finish, selected_renders, send, shared_render, show_rendered_warning}; use crate::VectorcraftApp; use crate::dialogs::host::open_held; @@ -117,6 +117,7 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: Opened) -> Result< let mut changed = Map::new(); changed.insert(vectorcraft_effects::RENDER.into(), Value::Object(render)); send(app, changed, Live::Released); + show_rendered_warning(app); Ok(()) } From 8107acadf22439ef4cd46b70fd449d103887968b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 10:50:24 -0800 Subject: [PATCH 021/103] Scripts: a color picker answer refuses out-of-range arrays and objects An answer given as an array or object, such as [1.00000001, 0, 0] or {c: 100.000001, m: 0, y: 0, k: 0}, was narrowed to f32 before its range check, so a component just past a limit rounded onto it and passed. Its components are now checked as written, in f64 and on the scale paint.setFill reads them in, as color keys already were. Boundary values are still accepted. docs/mcp.md and script.run's params text list "stop" as a colorPicker answer, which a run stopped at the picker records. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 58 ++++++++++++++++------- crates/engine/src/tests/script_dialogs.rs | 18 ++++++- docs/mcp.md | 5 +- 4 files changed, 62 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b3cc43bed3..37d3c52c8f 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 script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), 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; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), 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; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 5daae5bb1d..bcb6e1a551 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -170,25 +170,49 @@ fn in_range(c: &Color) -> bool { /// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key /// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components -/// into their ranges. +/// into their ranges. An array or object is checked as written too, in f64 and with the scale +/// [`crate::cmd::color_value`] reads it in, so that a component just past a limit is not rounded +/// onto it when it narrows to f32. fn answer_color(v: &Value) -> Option { - if let Value::String(s) = v - && Color::from_hex(s).is_none() - { - let mut it = s.split_whitespace(); - let model = it.next()?.to_ascii_lowercase(); - // Parsed as f64, so that a value just past a limit is not rounded onto it. - let n: Vec = it.map(|t| t.parse::().ok().filter(|x| x.is_finite())).collect::>()?; - let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x)); - let written_in_range = match (model.as_str(), n.as_slice()) { - ("rgb", [_, _, _]) => within(&n, 0.0, 255.0), - ("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0), - ("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0), - _ => return None, - }; - if !written_in_range { - return None; + // Parsed as f64, so that a value just past a limit is not rounded onto it. + let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x)); + let num = |o: &serde_json::Map, key: &str| o.get(key).and_then(Value::as_f64); + let written_in_range = match v { + Value::String(s) if Color::from_hex(s).is_none() => { + let mut it = s.split_whitespace(); + let model = it.next()?.to_ascii_lowercase(); + let n: Vec = it.map(|t| t.parse::().ok().filter(|x| x.is_finite())).collect::>()?; + match (model.as_str(), n.as_slice()) { + ("rgb", [_, _, _]) => within(&n, 0.0, 255.0), + ("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0), + ("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0), + _ => return None, + } } + Value::Array(a) if a.len() >= 3 => within(&[a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?], 0.0, 1.0), + Value::Object(o) => { + if let (Some(c), Some(m), Some(y), Some(k)) = (num(o, "c"), num(o, "m"), num(o, "y"), num(o, "k")) { + let scale = if [c, m, y, k].iter().any(|x| *x > 1.0) { 100.0 } else { 1.0 }; + within(&[c, m, y, k], 0.0, scale) + } else if let Some(g) = o.get("gray") { + let g = g.as_f64()?; + within(&[if g > 1.0 { g / 100.0 } else { g }], 0.0, 1.0) + } else if let (Some(l), Some(a), Some(b), None) = (num(o, "l"), num(o, "a"), num(o, "b"), o.get("model")) { + within(&[l], 0.0, 100.0) && within(&[a, b], -128.0, 128.0) + } else { + match o.get("model").and_then(Value::as_str) { + Some("rgb") => within(&[num(o, "r")?, num(o, "g")?, num(o, "b")?], 0.0, 1.0), + Some("cmyk") => within(&[num(o, "c")?, num(o, "m")?, num(o, "y")?, num(o, "k")?], 0.0, 1.0), + Some("gray") => within(&[num(o, "k")?], 0.0, 1.0), + Some("lab") => within(&[num(o, "l")?], 0.0, 100.0) && within(&[num(o, "a")?, num(o, "b")?], -128.0, 128.0), + _ => true, + } + } + } + _ => true, + }; + if !written_in_range { + return None; } crate::cmd::color_value(v).filter(in_range) } diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index dbd727e33c..7b154e607a 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -382,11 +382,27 @@ fn the_color_picker_refuses_what_is_not_a_solid_color() { json!("gray -1"), json!("lab 50 200 0"), json!("rgb 255.000001 0 0"), + json!([1.00000001, 0, 0]), + json!({"c": 100.000001, "m": 0, "y": 0, "k": 0}), + json!({"gray": 100.000001}), + json!({"l": 100.000001, "a": 0, "b": 0}), + json!({"model": "rgb", "r": 1.00000001, "g": 0, "b": 0}), + json!({"model": "lab", "l": 50, "a": -128.000001, "b": 0}), ] { let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); assert!(e.contains("color picker's answer"), "{bad}: {e}"); } - for good in [json!("rgb 255 0 0"), json!("cmyk 0 100 100 0"), json!("gray 100"), json!("lab 50 -128 128")] { + for good in [ + json!("rgb 255 0 0"), + json!("cmyk 0 100 100 0"), + json!("gray 100"), + json!("lab 50 -128 128"), + json!([1, 0, 0]), + json!({"c": 0, "m": 100, "y": 100, "k": 0}), + json!({"gray": 100}), + json!({"l": 100, "a": -128, "b": 128}), + json!({"model": "rgb", "r": 1, "g": 0, "b": 0}), + ] { assert!(headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": good})])).is_ok(), "{good}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index f0cb382b42..d38719f8f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3669,8 +3669,9 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"` for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a `show()` that ended with an error. `app.showColorPicker` is listed as `{kind: "colorPicker", color, answer}`, with - the color it opened on and the color picked, `null` for Cancel or `"missing"`, each color as `paint.setFill` takes - it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at its limit. + the color it opened on and the color picked, `null` for Cancel, `"stop"` or `"missing"`, each color as + `paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at + its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} From 45050b07d9b5def6ae4d469acfa4d2c571bf8c18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 20:30:56 -0800 Subject: [PATCH 022/103] 3D: a later effect that reshapes paths keeps the shaded faces A rendered Extrude & Bevel, Rotate or Revolve followed by a visible geometry effect that reshapes paths but not images, such as Pucker & Bloat or Roughen, now draws and measures the shaded faces so the later effect still applies, and the status bar reports why. Transform, Warp and raster effects keep the rendered image. --- crates/effects/src/catalog.rs | 2 +- crates/effects/src/revolve.rs | 4 ++- crates/effects/src/solids.rs | 28 +++++++++++------ crates/effects/src/solids/rendered.rs | 13 ++++++++ crates/effects/src/solids/rendered/tests.rs | 29 ++++++++++++++++++ crates/effects/src/solids/tests_shadow.rs | 2 +- crates/engine/src/tests/effectedit.rs | 34 +++++++++++++++++---- docs/mcp.md | 3 +- docs/three-d.md | 3 +- 9 files changed, 98 insertions(+), 20 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 31037ccc05..96c53b8d10 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,7 +241,7 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 3fb7eb6c0a..601706a0ca 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -1119,7 +1119,9 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil // Rendered, the surface's image, with the shadows of every light on the surface and on the // shadow plane; the shaded faces when it can't be made, and for vector measurements. let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| { - let result = if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) { + let result = if crate::solids::rendered::reshapes_paths_only(&n.appearance.effects[index + 1..]) { + Err(crate::solids::rendered::PATHS_ONLY.into()) + } else if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) { let b = path.bounds()?; let (paint, opacity, _) = paint_of(item); let options = rule_options(fx, rule); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 500adff788..1db067c786 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -2044,11 +2044,12 @@ type ShadowAndSurfaces = (Vec>, Vec>); fn art_for( doc: Option<&Document>, n: &Node, - fx: &Effect, + effects: &[Effect], shapes: &[Profile], build: Build, warning: &mut Option, ) -> Option { + let (fx, later) = effects.split_first()?; if build == Build::Check && !crate::renders_image(fx) { return Some((vec![], vec![])); } @@ -2062,7 +2063,9 @@ fn art_for( if build != Build::Vector && let Some(settings) = wireframe::render_settings(&fx.id, &p) { - let image = if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(|s| &s.items), has_masks(shapes)) { + let image = if rendered::reshapes_paths_only(later) { + Err(rendered::PATHS_ONLY.into()) + } else if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(|s| &s.items), has_masks(shapes)) { meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| { let lighting = rendered::lighting(&fx.id, &p); let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? { @@ -2901,9 +2904,10 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build let (sources, paints) = solid_paint_sources(n); let mut children = vec![]; let remaining: Vec; - if let Some((index, fx)) = solid(&n.appearance.effects) { + if let Some((index, _)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?; + let (shadow, surfaces) = + art_for(doc, n, &n.appearance.effects[index..], &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?; children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. remaining = past_effect(&n.appearance.effects, index); @@ -2917,10 +2921,16 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build // Every item's shadow goes behind every item's art. let mut shadows = vec![]; for (source, item) in sources.into_iter().zip(&paints) { - if let Some((index, fx)) = solid(item.effects()) { + if let Some((index, _)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item))); - let (shadow, surfaces) = - art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], build, warning)?; + let (shadow, surfaces) = art_for( + doc, + n, + &item.effects()[index..], + &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], + build, + warning, + )?; let later: Vec = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); let with_later = |mut art: Arc| { Arc::make_mut(&mut art).appearance.effects = later.clone(); @@ -2950,10 +2960,10 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build /// group's own fills and strokes are not drawn. `None` when the effect is only on one of the /// group's own fills or strokes, or when its members can't become solids. fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { - let (index, fx) = solid(&n.appearance.effects)?; + let (index, _) = solid(&n.appearance.effects)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - let (shadow, surfaces) = art_for(doc, n, fx, &shapes, build, warning)?; + let (shadow, surfaces) = art_for(doc, n, &n.appearance.effects[index..], &shapes, build, warning)?; let children = shadow.into_iter().chain(surfaces).collect(); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs index a87e5d1fa3..e085950000 100644 --- a/crates/effects/src/solids/rendered.rs +++ b/crates/effects/src/solids/rendered.rs @@ -22,6 +22,19 @@ pub const TOO_LARGE: &str = "The 3D render is too large; showing the shaded face /// blending, or with graphics; the effect then draws its shaded faces. pub const OPAQUE_ONLY: &str = "The 3D render shows opaque solid colors only; showing the shaded faces instead"; +/// The message for a later geometry effect that reshapes paths but leaves images unchanged. +pub const PATHS_ONLY: &str = "A later effect reshapes the 3D object's paths; showing the shaded faces instead"; + +/// Do any visible effects reshape paths without also reshaping images in `reshape_leaves`? +pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool { + effects.iter().any(|e| { + e.visible + && crate::is_geometry(&e.id) + && e.id != "distort.transform" + && e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).is_none() + }) +} + /// The message for Revolve on a group or on a fill or stroke, which draws its shaded faces. pub const OBJECTS_ONLY: &str = "Revolve renders on a single object only; showing the shaded faces instead"; diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index 965ddeed96..d92a33bb55 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -109,6 +109,35 @@ fn rendered_mode_draws_one_image_over_the_shaded_faces() { } } +/// Later path deformations keep shaded faces for drawing and bounds and report the fallback. +/// Hidden deformations, Gaussian Blur, Transform and Warp keep the rendered image. +#[test] +fn later_geometry_keeps_shaded_faces_only_when_images_cannot_take_it() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + n.appearance.effects.push(crate::new_effect("distort.puckerBloat", &json!({"amount": 20.0})).unwrap()); + let art = drawn(&n); + assert!(images(&art).is_empty(), "{id}"); + assert!(faces_bounds(&art).is_some(), "{id}"); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(PATHS_ONLY), "{id}"); + let measured = crate::three_d_bounds_art_in(Some(&doc), &n).unwrap(); + assert!(images(&measured).is_empty(), "{id}: bounds use shaded faces"); + assert!(faces_bounds(&measured).is_some(), "{id}"); + + n.appearance.effects[1].visible = false; + assert_eq!(images(&drawn(&n)).len(), 1, "{id}: hidden deformation"); + assert!(crate::rendered_warning(&doc, &n).is_none(), "{id}"); + for (later, params) in + [("blur.gaussian", json!({"radius": 5.0})), ("distort.transform", json!({"moveH": 10.0})), ("warp.arc", json!({"bend": 20.0}))] + { + n.appearance.effects[1] = crate::new_effect(later, ¶ms).unwrap(); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}: {later}"); + assert!(crate::rendered_warning(&doc, &n).is_none(), "{id}: {later}"); + } + } +} + /// With ambient light alone at 100 %, the rendered surface shows its paint unchanged, as the shaded /// faces do (brightness 1 times the paint); with no light at all it is black, as they are. #[test] diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 8db614abd7..8170a3bfa7 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -356,7 +356,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() let (path, rule) = profile(&n).unwrap(); vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] }; - let (drawn, _) = art_for(None, &n, fx, &shapes, Build::Vector, &mut None).unwrap(); + let (drawn, _) = art_for(None, &n, std::slice::from_ref(fx), &shapes, Build::Vector, &mut None).unwrap(); let p = crate::merged_params(&fx.id, &fx.params); let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); diff --git a/crates/engine/src/tests/effectedit.rs b/crates/engine/src/tests/effectedit.rs index 1eaa7a9764..4056eec502 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -326,15 +326,37 @@ fn covered(s: &Session) -> (Vec, [u32; 4]) { (img.pixels, b) } -/// Effects after a rendered 3D effect apply to its image: Gaussian Blur spreads it past its edges, -/// Transform moves it, and Roughen leaves it as it is. +/// Gaussian Blur spreads a rendered 3D image past its edges and Transform moves it. Roughen +/// draws the shaded faces instead and reports why. #[test] -fn effects_after_a_rendered_3d_effect_apply_to_its_image() { - let (plain, at) = covered(&rendered_square(&[])); +fn effects_after_a_rendered_3d_effect_keep_the_image_or_reshape_the_faces() { + let (_, at) = covered(&rendered_square(&[])); let (_, blurred) = covered(&rendered_square(&[("blur.gaussian", json!({"radius": 5.0}))])); assert!(blurred[0] + 2 <= at[0] && blurred[2] >= at[2] + 2, "blurred {blurred:?} against {at:?}"); let (_, moved) = covered(&rendered_square(&[("distort.transform", json!({"moveH": 50.0}))])); assert_eq!([moved[0], moved[2]], [at[0] + 50, at[2] + 50], "moved {moved:?} against {at:?}"); - let (rough, _) = covered(&rendered_square(&[("distort.roughen", json!({"size": 5.0}))])); - assert!(rough == plain, "Roughen changes the rendered image"); + let rough = rendered_square(&[("distort.roughen", json!({"size": 5.0}))]); + let doc = &rough.doc().unwrap().doc; + let mut object = None; + for layer in &doc.layers { + layer.walk(&mut |n| { + if n.appearance.effects.iter().any(|e| e.id == "threeD.extrude") { + object = Some(n.clone()); + } + }); + } + let object = object.unwrap(); + let art = vectorcraft_render::effects::solid_art_drawn_in(Some(doc), &object).unwrap(); + let mut has_image = false; + let mut has_faces = false; + art.walk(&mut |n| { + has_image |= matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)); + has_faces |= n.path_data().is_some(); + }); + assert!(!has_image); + assert!(has_faces); + assert_eq!( + vectorcraft_render::effects::rendered_warning(doc, &object).as_deref(), + Some("A later effect reshapes the 3D object's paths; showing the shaded faces instead") + ); } diff --git a/docs/mcp.md b/docs/mcp.md index 3ea1024775..c9aac0e166 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6459,7 +6459,8 @@ effect's shadow plane, drawn in the image; with it off, none does. `render` then values), `resolution` (`null` for Document Raster Effects Settings › Resolution, the default, or 1..2400 ppi) and `background` (`"transparent"`, the default, or `"white"`). A quality whose samples would pass 16,777,216 pixels takes fewer, and an image past that limit at one sample a pixel draws the shaded faces, as do solids painted with -a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal. The status bar and +a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, or a later geometry +effect that reshapes paths but leaves images unchanged. The status bar and the command result's `warning` field report when the shaded faces are drawn instead. A `render` that is not an object, another key, another value, and `render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) are refused before the document changes. In wireframe mode the graphics' art is not checked against the graphics diff --git a/docs/three-d.md b/docs/three-d.md index e365dd52eb..043249626a 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -77,7 +77,8 @@ pages describe it. image, the effect draws its shaded faces. The image keeps transparency where no surface is, or is white with `background: white`. The image shows opaque solid colors only: a solid painted with a gradient or a pattern, one with graphics, a paint with an opacity below 100% or in a blending mode other than Normal, and a group member whose opacity mask or blending mode - applies to its solid draw the shaded faces, as do Revolve on a group and Revolve on a fill or stroke. The mode + applies to its solid draw the shaded faces, as do Revolve on a group, Revolve on a fill or stroke, and a later + geometry effect that reshapes paths but leaves images unchanged. The mode is saved with the effect. The status bar and the command result's `warning` field report when the shaded faces are drawn instead. The lighting follows the same lights as the shaded faces but in linear light, so lit areas differ from the shaded faces' colors. Ambient Light keeps its full range from 0 to 200%; From 25f9a53d78caa039acac378f24d62900fff46511 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 23:00:30 -0800 Subject: [PATCH 023/103] 3D: shadow docs and params text say which mode each rule covers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shaded faces show the first light's shadow, and Render Settings › Rendered draws the shadows of every light with an Intensity above 0. The Shadows table, its notes, the differences list, the effects summary, docs/mcp.md and the shadow params text of Extrude & Bevel, Revolve, Inflate and Rotate now say which mode they describe. A new test checks that PNG export gives the pixels the canvas draws at export quality, and that the rendered image has as many pixels as the shaded faces' bounds times the resolution over 72, rounded up as a raster effect's image is. --- crates/effects/src/catalog.rs | 8 ++-- crates/engine/src/tests/effectedit.rs | 59 +++++++++++++++++++++++++++ docs/effects-parity.md | 4 +- docs/mcp.md | 4 +- docs/three-d.md | 19 +++++---- 5 files changed, 79 insertions(+), 15 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 96c53b8d10..efc85eab29 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,28 +241,28 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Painted with the top fill (else the top stroke).", json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( diff --git a/crates/engine/src/tests/effectedit.rs b/crates/engine/src/tests/effectedit.rs index 4056eec502..23f703af6a 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::Node; +use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use crate::*; @@ -312,6 +313,64 @@ fn export_and_expand_write_one_image_of_a_rendered_3d_object() { assert!(x0 <= 100.0 + 1e-6 && x1 >= 200.0 - 1e-6, "the image spans {x0} to {x1}"); } +/// PNG export draws a rendered 3D object as the canvas draws it at export quality. The rendered image takes as many +/// pixels as the shaded faces' bounds times the resolution over 72, rounded up to whole pixels as a +/// raster effect's image is (`effect_region` in `crates/engine/src/cmd/rasterfx.rs`), at the +/// effect's own resolution and at the document's raster effects resolution. +#[test] +fn png_export_matches_the_canvas_and_the_image_takes_the_raster_effect_size() { + for (doc_ppi, resolution) in [(72.0, Some(150.0)), (150.0, None), (300.0, Some(37.0))] { + let what = format!("document {doc_ppi} ppi, effect {resolution:?}"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300, "rasterEffectsPpi": doc_ppi})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + run(&mut s, "paint.setStroke", json!({"none": true})); + run(&mut s, "paint.setFill", json!({"color": "#338ad6"})); + let render = json!({"mode": "rendered", "quality": "low", "resolution": resolution}); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": render}})); + let png = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap(); + let png = image::load_from_memory(&vectorcraft_format::base64_decode(png["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8(); + let doc = &s.doc().unwrap().doc; + // The canvas drawn at export quality (precise, supersampled and with templates left out) and + // at the resolution PNG export takes by default, the document's raster resolution. + let quality = RasterExportOptions::default().render_options(RasterFormat::Png); + let canvas = vectorcraft_render::Renderer::new().render_region_with(doc, doc.artboards[0].rect, doc_ppi / 72.0, &quality); + assert_eq!((png.width(), png.height()), (canvas.width, canvas.height), "{what}"); + let changed = png.as_raw().chunks(4).zip(canvas.to_straight().chunks(4)).filter(|(a, b)| a != b).count(); + assert_eq!(changed, 0, "{what}: pixels of the PNG export that differ from the canvas"); + let drawn = |s: &Session| { + let doc = &s.doc().unwrap().doc; + let mut object = None; + for layer in &doc.layers { + layer.walk(&mut |n| { + if n.appearance.effects.iter().any(|e| e.id == "threeD.extrude") { + object = Some(n.clone()); + } + }); + } + vectorcraft_render::effects::solid_art_drawn_in(Some(doc), &object.unwrap()).unwrap() + }; + let mut images = vec![]; + drawn(&s).walk(&mut |n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + images.push((**im).clone()); + } + }); + assert_eq!(images.len(), 1, "{what}"); + run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "shaded"}}})); + let mut faces: Option = None; + drawn(&s).walk(&mut |n| { + if let Some(b) = n.path_data().and_then(vectorcraft_geom::PathData::bounds) { + faces = Some(faces.map_or(b, |f| f.union(b))); + } + }); + let faces = faces.unwrap(); + let scale = resolution.unwrap_or(doc_ppi) / 72.0; + let expected = ((faces.width() * scale).ceil().max(1.0) as u32, (faces.height() * scale).ceil().max(1.0) as u32); + assert_eq!((images[0].width, images[0].height), expected, "{what}: the image's pixels for faces {faces:?}"); + } +} + /// The page bounds, in whole points, of the pixels the canvas covers in session `s`. fn covered(s: &Session) -> (Vec, [u32; 4]) { let img = diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 30bd572efa..3704d05be9 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -180,13 +180,13 @@ VectorCraft choices; an original approximation, never compared with another appl |---|---| | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, a ring of them broken at one of its own faces, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, a ring of overlapping faces broken at one of its own faces (Extrude & Bevel and Inflate), depth, twist, taper, solid or hollow caps, five original bevel shapes and custom bevels drawn as open paths in the bevels file ([add custom bevel paths](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/add-custom-bevel-paths.html), [three-d.md](three-d.md#custom-bevels)), Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | -| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side, and carried onto Inflate's puffed front and back ([three-d.md](three-d.md#graphics)); the Materials tab's Properties, Roughness and Metallic from 0 to 1, shaded with glTF 2.0's metallic-roughness BRDF and written into glTF and USD exports ([three-d.md](three-d.md#material-properties)); no base-material library or ray tracing | +| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, Render Settings › Rendered with Low, Medium and High Quality and Raster Settings…, which draws the solid as one lit image with a depth buffer and, with Shadows on, the shadows of every light with an Intensity above 0, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; in the shaded faces, shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)), and in Rendered from every light; the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side, and carried onto Inflate's puffed front and back ([three-d.md](three-d.md#graphics)); the Materials tab's Properties, Roughness and Metallic from 0 to 1, shaded with glTF 2.0's metallic-roughness BRDF and written into glTF and USD exports ([three-d.md](three-d.md#material-properties)); no base-material library or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes and the custom bevels with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art for Extrude & Bevel (Classic) and Revolve (Classic): one document symbol on each numbered surface, surface navigation with visible and hidden marks and a red outline on the artboard, move, scale and rotate on the surface laid out flat, Scale to Fit, Clear, Clear All, Shade Artwork, Invisible Geometry, kept by Expand Appearance and exports, `threeD.mapArt` ([map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)) | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit, and the graphics on Revolve's side as a texture of the side unrolled; every corner carries texture coordinates and a normal, smoothed across a curved bevel and over Inflate's puff ([three-d.md](three-d.md#3d-meshes)); glTF and USD carry each solid's Roughness and Metallic as its roughness and metallic factors ([three-d.md](three-d.md#material-properties)); no other materials and no lighting ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; -the effects crate turns them into art. What's left (base and Substance materials, shadows from lights after the first, +the effects crate turns them into art. What's left (base and Substance materials, shadows from lights after the first in the shaded faces, ray-traced rendering, exact visibility, Turntable) is 25–45 h. ## Revision history diff --git a/docs/mcp.md b/docs/mcp.md index 3d4ca278d3..71f5412ca0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6524,7 +6524,9 @@ The document stores their numeric settings; manual edits remain possible through Revolve, Extrude & Bevel, Inflate and Rotate take `shadow` (boolean, default false), `shadowPosition` (`"behind"` or `"below"`, default `"behind"`), `shadowDistance` (0..100%, default 0) and `shadowBounds` (10..400%, default 100), -set with `effect.apply` or `effect.setParams` in one undo step. With `shadow` on, the first light casts a +set with `effect.apply` or `effect.setParams` in one undo step. With `shadow` and `shade` on and `render.mode` +`"rendered"`, every light with an intensity above 0 casts shadows in the image instead ([3D render mode](#3d-render-mode)); the rest of this +section covers the shaded faces. With `shadow` on, the first light casts a shadow of the solid, drawn behind the solid as one path filled black at 50% opacity times the opacity of the art that casts it, in that art's blending mode. At the first light's `softness` (or `lightSoftness`) 0 the path is hard-edged; above 0 it carries a Gaussian Blur of radius softness × the object's largest size × (5% + 20% × diff --git a/docs/three-d.md b/docs/three-d.md index 7a60b0d63f..9a97fc6258 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -529,12 +529,13 @@ Inflate and Rotate has a **Shadows** switch with those three settings below it. | Option | | |---|---| -| Shadows | Off by default. On, the first light casts a shadow of the solid, drawn behind it: hard-edged at the light's Softness 0 %, blurred above it. | +| Shadows | Off by default. On, the shaded faces show a shadow of the solid cast by the first light, drawn behind it: hard-edged at the light's Softness 0 %, blurred above it. In Render Settings › Rendered, every light with an Intensity above 0 casts shadows ([3D and Materials panel](#3d-and-materials-panel)). | | Position | **Behind Object** (the default): on a plane square to the view, behind the object. **Below Object**: on the floor under the object, square to its own vertical axis and turned with it. | | Distance from Object | 0–100 %, default 0 %: how far the plane is from the object, as a share of the object's largest size. | | Shadow Bounds | 10–400 %, default 100 %: how far the plane reaches. At 100 % it is a square four times the object's largest size across, about the foot of the object's center; the shadow is cut at its edges. | -Our reading: +Our reading, for the shadow the shaded faces show (Render Settings › Rendered draws the shadows in its image, as +[3D and Materials panel](#3d-and-materials-panel) describes): - The shadow is one path, filled black at 50 % opacity with the nonzero rule: every face of every solid of the object (its fill and its strokes, or the members of a group) projected along the first light onto the plane. @@ -550,8 +551,8 @@ Our reading: it the blur radius is Softness × the object's largest size × (5 % + 20 % × Distance from Object), at most 1,000 pt. At 100 % Softness a 100 pt object casts a shadow blurred by 5 pt on a plane that touches it and by 25 pt at 100 % Distance. This mapping is our own. The blur scales with the object, and it draws, takes room and - exports as a Gaussian Blur effect does. Only the first light casts a - shadow. + exports as a Gaussian Blur effect does. In the shaded faces only the first light casts a + shadow; in Render Settings › Rendered every light with an Intensity above 0 does. - A shadow is cast from at most 327,680 faces, the solids of one object together (our own limit). Past it, a command is refused with "The 3D shadow is too complex; turn Shadows off or simplify the art", and a loaded file draws the source path. A command checks the shadow from the same builds that check the solids, as @@ -787,10 +788,12 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or out, perspective). No Adobe software, assets, presets or bevel shapes were used. -- **Adobe Substance materials**, adding and deleting materials, shadows of lights after the first, and - **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or stroke the - solid is built for ([Fills and strokes](#fills-and-strokes)), with the base material's Roughness and Metallic - ([Material properties](#material-properties)), and only the first light casts a shadow ([Shadows](#shadows)). +- **Adobe Substance materials**, adding and deleting materials, shadows of lights after the first in the shaded + faces, and **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or + stroke the solid is built for ([Fills and strokes](#fills-and-strokes)), with the base material's Roughness and + Metallic ([Material properties](#material-properties)), and in the shaded faces only the first light casts a + shadow ([Shadows](#shadows)); Render Settings › Rendered takes the shadows of every light with an Intensity + above 0 ([3D and Materials panel](#3d-and-materials-panel)). Graphics map onto planar faces, Extrude & Bevel's side as one surface unrolled flat, and Revolve's side and Inflate's puffed front and back only ([Graphics](#graphics)). - The bevel shapes and their names are our own. Custom bevels come from VectorCraft's own bevels file From 73d0b1560533376931d97c30abaabf7fae1d5f73 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:05:26 -0800 Subject: [PATCH 024/103] 3D: highlight curved faces' seams; Render Settings for any selected render - A material's highlight over a curved face now covers the face's seam, as the face's clip does, so curved faces no longer show a dark fringe. The outline is validated flattened, split at its extrema, with a clearance for the flattening error; a face that folds over itself keeps its outline alone. - Render Settings shows while any selected object's 3D effect takes it, whatever the selection order and whether the first object has an effect. - Raster Settings OK leaves out values equal to what every object already holds (the document's resolution, a shared custom resolution, a shared background), so an unchanged OK records no undo step. - meshes_carry_the_material requires the default-material meshes to build and be non-empty. - docs/mcp.md and the progress-doc line list every case that draws the shaded faces instead of the rendered image. --- crates/effects/src/lighting.rs | 187 +++++++++++++++++++- crates/effects/src/solids/tests_material.rs | 4 +- crates/ui-egui/src/panels/tests_three_d.rs | 17 ++ crates/ui-egui/src/panels/three_d.rs | 13 +- crates/ui-egui/src/panels/three_d/raster.rs | 68 +++++-- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 7 files changed, 266 insertions(+), 33 deletions(-) diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 9ce14bbf47..fcabeeaded 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -172,8 +172,9 @@ fn highlight_fills(highlight: vectorcraft_three_d::Highlight) -> Vec Option { + use kurbo::{ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Shape}; + let bez = path.to_bezpath(); + let elements = bez.elements(); + if elements.len() > SEAMED_FILL_EDGES + 2 || !elements.iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))) { + return None; + } + let mut flat = vectorcraft_geom::BezPath::new(); + let mut overflow = false; + let mut last = kurbo::Point::ZERO; + for el in elements { + if overflow { + break; + } + let from = last; + let controls = match el { + PathEl::QuadTo(a, b) => Some([from, *a, *b, *b]), + PathEl::CurveTo(a, b, c) => Some([from, *a, *b, *c]), + _ => None, + }; + if let Some(controls) = controls { + let length: f64 = controls.windows(2).map(|pair| pair[0].distance(pair[1])).sum(); + if !length.is_finite() + || length > HIGHLIGHT_FLATNESS * vectorcraft_geom::MAX_FLATTEN_PER_CURVE.powi(2) + || controls.iter().any(|p| !(p.x.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH && p.y.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH)) + { + return None; + } + } + last = match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => *p, + PathEl::ClosePath => last, + }; + let curve = match el { + PathEl::QuadTo(a, b) => Some(PathSeg::Quad(kurbo::QuadBez::new(from, *a, *b))), + PathEl::CurveTo(a, b, c) => Some(PathSeg::Cubic(kurbo::CubicBez::new(from, *a, *b, *c))), + _ => None, + }; + // Each curve piece is monotonic in both coordinates before flattening. + let pieces = curve.map_or_else( + || vec![(from, *el)], + |curve| { + curve + .extrema_ranges() + .into_iter() + .map(|range| { + let piece = curve.subsegment(range); + (piece.start(), piece.as_path_el()) + }) + .collect() + }, + ); + for (from, el) in pieces { + if overflow { + break; + } + let start = [PathEl::MoveTo(from)].into_iter().filter(|_| !matches!(el, PathEl::MoveTo(_))); + let mut skip = usize::from(!matches!(el, PathEl::MoveTo(_))); + vectorcraft_geom::flatten(start.chain([el]), HIGHLIGHT_FLATNESS, |e| { + if skip > 0 { + skip -= 1; + } else if flat.elements().len() > SEAMED_FILL_EDGES + 2 { + overflow = true; + } else { + flat.push(e); + } + }); + } + } + if overflow { + return None; + } + // Each flattened edge may be HIGHLIGHT_FLATNESS away from its curve. + seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), seam, 2.0 * HIGHLIGHT_FLATNESS)?; + let fill = footprint(&bez, seam); + (fill.bounding_box().is_finite() && fill.area().abs() >= bez.area().abs()).then(|| vectorcraft_geom::PathData::from_bezpath(&fill)) +} + /// `face`, the art of a face of outline `path` closed by a seam `seam` wide, with `highlight` /// screened over it: a group of the face and the highlight's path on the face and its seam /// ([`highlight_over`]). An opacity mask on the face moves to the group, so it covers the @@ -255,7 +343,13 @@ const SEAMED_FILL_EDGES: usize = 256; /// a seam that is not a positive finite width, or a footprint with no finite bounds or less area /// than the facet. pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option { - use kurbo::{PathEl, Point, Shape}; + seamed_fill_with_clearance(path, seam, 0.0) +} + +/// [`seamed_fill`], also `None` when two edges that are not neighbors come within `clearance` of +/// each other. +fn seamed_fill_with_clearance(path: &vectorcraft_geom::PathData, seam: f64, clearance: f64) -> Option { + use kurbo::{Line, ParamCurveNearest, PathEl, Point, Shape}; if !(seam.is_finite() && seam > 0.0) { return None; } @@ -294,6 +388,19 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio if touch(a, b, c, d) { return None; } + if clearance > 0.0 { + let ab = Line::new(a, b); + let cd = Line::new(c, d); + let distance_sq = ab + .nearest(c, 1e-6) + .distance_sq + .min(ab.nearest(d, 1e-6).distance_sq) + .min(cd.nearest(a, 1e-6).distance_sq) + .min(cd.nearest(b, 1e-6).distance_sq); + if distance_sq <= clearance * clearance { + return None; + } + } } } let fill = footprint(&bez, seam); @@ -690,6 +797,78 @@ mod tests { } } + /// A material's highlight over a curved face reaches its seam too, as the face's clip does, + /// wound one way so a nonzero fill screens it once. A curved face that folds over itself keeps + /// its outline alone. + #[test] + fn a_highlight_over_a_curved_face_covers_its_seam() { + use kurbo::Shape; + let circle = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for path in [circle.clone(), vectorcraft_geom::PathData::from_bezpath(&circle.to_bezpath().reverse_subpaths())] { + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + let Some(shape) = over.path_data() else { panic!("a path") }; + let bez = shape.to_bezpath(); + assert_ne!(bez.winding(Point::new(5.0, 10.4)), 0, "the seam past the bottom edge"); + assert_ne!(bez.winding(Point::new(5.0, 5.0)), 0, "the face"); + assert_eq!(bez.winding(Point::new(5.0, 11.0)), 0, "past the seam"); + assert!(bez.elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count() >= 2); + } + // A curved face that folds over itself keeps its outline alone, as its own nonzero fill. + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.quad_to((5.0, -1.0), (10.0, 10.0)); + folded.line_to((10.0, 0.0)); + folded.quad_to((5.0, 1.0), (0.0, 10.0)); + folded.close_path(); + let folded = vectorcraft_geom::PathData::from_bezpath(&folded); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &folded, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&folded)); + } + + /// A curved face whose fold is smaller than the flattening tolerance, so that its flattened + /// outline does not cross itself, still keeps its outline alone, wound either way. + #[test] + fn a_highlight_over_a_fold_smaller_than_flatness_keeps_its_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.line_to((10.0, 0.0)); + folded.line_to((10.0, 10.0)); + folded.line_to((0.0, 10.0)); + folded.line_to((0.0, 0.01)); + folded.quad_to((5.0, -0.03), (9.0, 0.01)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the fold"); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&path)); + } + } + + /// A face with a collinear cubic that reverses direction keeps its highlight outline. + #[test] + fn a_highlight_over_a_retraced_cubic_keeps_its_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.curve_to((-8.0, 0.0), (-4.0, 0.0), (12.0, 0.0)); + folded.line_to((12.0, 10.0)); + folded.line_to((0.0, 10.0)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the reversal"); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&path)); + } + } + /// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the /// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound /// either way and in a concave notch. A facet whose footprint would gain or lose area under a diff --git a/crates/effects/src/solids/tests_material.rs b/crates/effects/src/solids/tests_material.rs index 1c7141dc8d..17f1878fa9 100644 --- a/crates/effects/src/solids/tests_material.rs +++ b/crates/effects/src/solids/tests_material.rs @@ -398,5 +398,7 @@ fn meshes_carry_the_material() { let mut n = square_node(); let Some(fx) = crate::new_effect(EXTRUDE, &json!({})) else { panic!("extrude") }; n.appearance.effects.push(fx); - assert!(three_d_meshes(&n).unwrap_or_default().iter().all(|m| m.material.is_default())); + let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("extrude: {e}")); + assert!(!meshes.is_empty(), "extrude"); + assert!(meshes.iter().all(|m| m.material.is_default())); } diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index f5775cf804..d668e76054 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -207,6 +207,23 @@ fn render_settings_wireframe_turns_the_mode_on_and_off_for_the_selection() { assert!(!painted_text(&mut app, show).contains("Render Settings")); } +/// Render Settings is shown while any selected object's 3D effect takes it, whichever object was +/// selected first: a 3D (Classic) effect or a plain path beside one that takes it does not hide +/// the menu. +#[test] +fn render_settings_shows_for_a_mixed_selection_in_either_order() { + let mut app = app(); + let a = app.session.active().unwrap().selection.objects[0].0; + set_type(&mut app, "extrude").unwrap(); + let c = app.run("shape.rectangle", json!({"x": 100, "y": 250, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.classicExtrude", "item": null})).unwrap(); + let p = app.run("shape.rectangle", json!({"x": 250, "y": 250, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + for ids in [[a, c], [c, a], [a, p], [p, a]] { + app.run("select.set", json!({ "ids": ids })).unwrap(); + assert!(painted_text(&mut app, show).contains("Render Settings"), "{ids:?}"); + } +} + /// Render Settings › Rendered and its qualities: each sets `render` on the selection in one undo /// step, and turning Wireframe on keeps the chosen quality. #[test] diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index 85549c7af7..56847a4639 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -345,6 +345,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.ui.status = e; } } + // Shown while any selected object's 3D effect takes render settings, whichever is first. + let renders = selected_renders(app); + if !renders.is_empty() { + render_settings(app, ui, &renders); + } let Some(t) = target else { // The selection changed during a gesture: it ends with what it previewed. finish(app); @@ -359,9 +364,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { export_button(app, ui); return; }; - if takes_render(&t.effect) { - render_settings(app, ui); - } let (params, fields) = rows(app, &t); let out = ParamRows::new(tl!("3D and Materials"), ¶ms, Bind::given(fields.clone())).show(ui); apply(app, ¶ms, &fields, &out.events); @@ -531,9 +533,8 @@ fn shared_render(renders: &[Map], key: &str) -> Option { /// differently shows no check. Choosing Wireframe or Rendered turns that mode on, or off when it /// is checked, and choosing a quality renders at it ([`set_render`]), for every selected object's /// 3D effect. -fn render_settings(app: &mut VectorcraftApp, ui: &mut Ui) { - let renders = selected_renders(app); - let (mode, quality) = (shared_render(&renders, "mode"), shared_render(&renders, "quality")); +fn render_settings(app: &mut VectorcraftApp, ui: &mut Ui, renders: &[Map]) { + let (mode, quality) = (shared_render(renders, "mode"), shared_render(renders, "quality")); let is = |v: &Option, s: &str| v.as_ref().and_then(Value::as_str) == Some(s); let (wireframe, rendered) = (is(&mode, "wireframe"), is(&mode, "rendered")); let opener = Button::new(tl!("Render Settings")).show(ui); diff --git a/crates/ui-egui/src/panels/three_d/raster.rs b/crates/ui-egui/src/panels/three_d/raster.rs index 1f91e959ed..e25aa6588b 100644 --- a/crates/ui-egui/src/panels/three_d/raster.rs +++ b/crates/ui-egui/src/panels/three_d/raster.rs @@ -51,14 +51,15 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<(), String> { Some(r) => fields.set("resolution", FieldValue::Number(r)), None => fields.set_mixed("resolution"), } - match shared_render(&renders, "background").as_ref().and_then(Value::as_str) { - Some(b) => fields.set("background", FieldValue::Text(b.into())), + let background = shared_render(&renders, "background").as_ref().and_then(Value::as_str).map(str::to_owned); + match &background { + Some(b) => fields.set("background", FieldValue::Text(b.clone())), None => fields.set_mixed("background"), } let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KIND, fields, |fields| dialog().values(Bind::bound(fields))); - let opened = Opened { document, resolution: opening }; - open_held(app, dialog, move |app, answer| ok(app, answer, opened)).ok_or("no window")?; + let opened = Opened { document, resolution: opening, background }; + open_held(app, dialog, move |app, answer| ok(app, answer, &opened)).ok_or("no window")?; Ok(()) } @@ -74,24 +75,28 @@ fn dialog<'a>() -> ParamDialog<'a> { } /// The values the dialog opened on; `None` for a field that opened blank. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] struct Opened { document: Option, resolution: Option, + background: Option, } /// The render settings the answer `f` sets, given the values the dialog opened on: a field left -/// blank sets nothing, and a resolution sets only when it was changed or the document's resolution -/// was switched off. -fn edited(f: &DialogFields, opened: Opened) -> Result, String> { +/// blank or unchanged sets nothing, and a resolution sets only when it was changed or the +/// document's resolution was switched off. +fn edited(f: &DialogFields, opened: &Opened) -> Result, String> { let mut render = Map::new(); let resolution = f.number("resolution"); match f.bool("document") { + // Every object already uses the document's resolution. + Some(true) if opened.document == Some(true) => {} Some(true) => { render.insert("resolution".into(), Value::Null); } // Every object already has its own resolution: a blank one leaves each as it is. - Some(false) if opened.document == Some(false) && resolution.is_none() => {} + // ... and an unchanged shared one is left as it is too. + Some(false) if opened.document == Some(false) && (resolution.is_none() || resolution == opened.resolution) => {} Some(false) => { render.insert("resolution".into(), json!(resolution.ok_or(NO_RESOLUTION)?)); } @@ -101,14 +106,14 @@ fn edited(f: &DialogFields, opened: Opened) -> Result, String } } } - if let Some(background) = f.text("background") { + if let Some(background) = f.text("background").filter(|b| opened.background.as_deref() != Some(*b)) { render.insert("background".into(), json!(background)); } Ok(render) } /// OK: sets the edited render settings on every selected object's 3D effect, one undo step. -fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: Opened) -> Result<(), String> { +fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: &Opened) -> Result<(), String> { let render = edited(&answer.fields, opened)?; if render.is_empty() { return Ok(()); @@ -139,14 +144,41 @@ mod tests { /// resolution sets nothing and a changed one sets it. #[test] fn ok_needs_a_resolution_and_keeps_blank_fields() { - let on = Opened { document: Some(true), resolution: Some(72.0) }; - assert_eq!(edited(&fields(&[("document", FieldValue::Bool(false))]), on), Err(NO_RESOLUTION.to_string())); - let own = Opened { document: Some(false), resolution: None }; - let kept = edited(&fields(&[("document", FieldValue::Bool(false)), ("background", FieldValue::Text("white".into()))]), own).unwrap(); + let on = Opened { document: Some(true), resolution: Some(72.0), background: Some("transparent".into()) }; + assert_eq!(edited(&fields(&[("document", FieldValue::Bool(false))]), &on), Err(NO_RESOLUTION.to_string())); + let own = Opened { document: Some(false), resolution: None, background: Some("transparent".into()) }; + let kept = edited(&fields(&[("document", FieldValue::Bool(false)), ("background", FieldValue::Text("white".into()))]), &own).unwrap(); assert_eq!(kept, Map::from_iter([("background".to_string(), json!("white"))])); - let mixed = Opened { document: None, resolution: Some(150.0) }; - assert_eq!(edited(&fields(&[("resolution", FieldValue::Number(150.0))]), mixed), Ok(Map::new())); - let changed = edited(&fields(&[("resolution", FieldValue::Number(200.0))]), mixed).unwrap(); + let mixed = Opened { document: None, resolution: Some(150.0), background: None }; + assert_eq!(edited(&fields(&[("resolution", FieldValue::Number(150.0))]), &mixed), Ok(Map::new())); + let changed = edited(&fields(&[("resolution", FieldValue::Number(200.0))]), &mixed).unwrap(); assert_eq!(changed.get("resolution").and_then(Value::as_f64), Some(200.0)); } + + /// OK on the values the dialog opened on sets nothing: the document's resolution that every + /// object already uses and the background they already share are left out. A switch to the + /// document's resolution or a new background still sets them, and a background picked over a + /// mixed one sets it. + #[test] + fn ok_on_unchanged_values_sets_nothing() { + let on = Opened { document: Some(true), resolution: Some(72.0), background: Some("transparent".into()) }; + let unchanged = fields(&[ + ("document", FieldValue::Bool(true)), + ("resolution", FieldValue::Number(72.0)), + ("background", FieldValue::Text("transparent".into())), + ]); + assert_eq!(edited(&unchanged, &on), Ok(Map::new())); + let own = Opened { document: Some(false), resolution: Some(150.0), background: Some("transparent".into()) }; + let kept = fields(&[("document", FieldValue::Bool(false)), ("resolution", FieldValue::Number(150.0))]); + assert_eq!(edited(&kept, &own), Ok(Map::new())); + let raised = edited(&fields(&[("document", FieldValue::Bool(false)), ("resolution", FieldValue::Number(200.0))]), &own).unwrap(); + assert_eq!(raised, Map::from_iter([("resolution".to_string(), json!(200.0))])); + let switched = edited(&fields(&[("document", FieldValue::Bool(true))]), &own).unwrap(); + assert_eq!(switched, Map::from_iter([("resolution".to_string(), Value::Null)])); + let white = edited(&fields(&[("background", FieldValue::Text("white".into()))]), &on).unwrap(); + assert_eq!(white, Map::from_iter([("background".to_string(), json!("white"))])); + let mixed = Opened { document: Some(true), resolution: Some(72.0), background: None }; + let picked = edited(&fields(&[("background", FieldValue::Text("transparent".into()))]), &mixed).unwrap(); + assert_eq!(picked, Map::from_iter([("background".to_string(), json!("transparent"))])); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 71f5412ca0..e272b13274 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6570,9 +6570,11 @@ effect's shadow plane, drawn in the image; with it off, none does. `render` then `quality` (`"low"`, `"medium"` or `"high"`: 1, 2 × 2 or 3 × 3 samples a pixel, default `"medium"`, VectorCraft's own values), `resolution` (`null` for Document Raster Effects Settings › Resolution, the default, or 1..2400 ppi) and `background` (`"transparent"`, the default, or `"white"`). A quality whose samples would pass 16,777,216 pixels -takes fewer, and an image past that limit at one sample a pixel draws the shaded faces, as do solids painted with -a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, or a later geometry -effect that reshapes paths but leaves images unchanged. The status bar and +takes fewer, and an image past that limit at one sample a pixel draws the shaded faces. The shaded faces are also +drawn for a scene past the renderer's limits on triangles, vertices, lights or work, for a mesh point at or behind +the eye, for Revolve on a group or on a fill or stroke, for solids painted with a gradient, a pattern, graphics, an +opacity below 100% or a blending mode other than Normal, and for a later geometry effect that reshapes paths but +leaves images unchanged. The status bar and the command result's `warning` field report when the shaded faces are drawn instead. A `render` that is not an object, another key, another value, and `render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) are refused before the document changes. In wireframe mode the graphics' art is not checked against the graphics diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index be65d451fb..323f80eedd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -735,7 +735,7 @@ since 2026-10-01. - 3D and Materials › Object › Bevel › Reset: the button next to Extrude & Bevel's Bevel heading, in the options dialog and the panel, sets Bevel Shape, Width, Height, Repeat, Space, Bevel Inside and Bevel both sides back to their defaults and leaves the other settings as they are, as one undo step in the panel; it is unavailable while every bevel setting is at its default ([three-d.md](three-d.md#extrude--bevel)); `crates/ui-egui/src/dialogs/revolve/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. -- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light, with shadow maps ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. +- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light, with shadow maps; solids painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, a later geometry effect that reshapes paths only, Revolve on a group, fill or stroke, and an image past the renderer's limits draw the shaded faces instead, with a warning ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Materials › Properties: Roughness and Metallic sliders set `material: {roughness, metallic}` on Extrude & Bevel, Revolve, Inflate and Rotate; with Shading on and outside Wireframe mode, any material other than the default (1 and 0) is shaded with craft-pbr's glTF 2.0 metallic-roughness BRDF, its highlight screened over each face; in every mode glTF exports write both factors, and USD exports write roughness and write metallic only when it is not the default 0 ([three-d.md](three-d.md#material-properties)); `crates/three-d/src/material.rs`, `crates/effects/src/solids/tests_material.rs`, `crates/engine/src/cmd/fileio/mesh3d/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Export 3D Object: the panel's button adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`), one undo step and none when each is an asset already, selects their assets and shows the Asset Export panel ([three-d.md](three-d.md#3d-and-materials-panel)); `panels::three_d::tests::{export_3d_object_adds_the_selected_3d_objects_to_asset_export, export_3d_object_leaves_out_a_3d_object_inside_another}` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. From c4f102e99384bbc37c80fb978110c3f24bee69ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:29:14 -0800 Subject: [PATCH 025/103] Docs: limit the first-light shadow rule to shaded output The 3D row and the shadows entry in docs/target-app-parity.md said only the first light casts a shadow. Rendered mode draws a shadow for every light with an Intensity above 0 when it draws its image, so the rule now applies to shaded output only, and Classic shadows are listed as their own gap. --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 323f80eedd..9d2abc46cb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -359,7 +359,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: other apps ignore dynamic symbol instance overrides in the `.ai` editing copy, and VectorCraft restores them on instances the copy keeps live, within the limits the File formats row lists (fill and stroke changes to type are not reproduced, none of an instance's changes is written when they take more than 1 MiB together, and a change can apply to a different part when the copy leaves out an earlier one), further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guide settings in the standard SVG data and in the `.ai` editing data written for other apps (the scaled appearance is kept, and `.ai` or SVG saves that embed the VectorCraft document reopen with editable guides when the embedded document is current and readable); Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | | Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep; large images trace with a warning or are downsampled, and images beyond the size and decode limits in `crates/trace/src/raster.rs` are rejected; Auto Color keeps rare distinct colors in coherent regions when the Automatic palette classifies the image as flat artwork) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; runtime pending). | | Live vector effects | 5 | 90% | depth of individual effects | 4–8 | measured count 50/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | -| 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows from lights after the first and in Classic effects (only the first light can cast a shadow in Revolve, Extrude & Bevel, Inflate and Rotate), ray tracing, Turntable views, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object) | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests; `a_3d_row_sets_its_param_previews_and_applies_in_one_step` in `crates/ui-egui/src/dialogs/revolve/tests.rs` checks its Angle preview, OK, Cancel and single-step undo; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | +| 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows in Classic effects, shadows from lights after the first in shaded output (unless Render Settings › Rendered draws its image rather than the shaded fallback, only the first light can cast a shadow in Revolve, Extrude & Bevel, Inflate and Rotate), ray tracing, Turntable views, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object) | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests; `a_3d_row_sets_its_param_previews_and_applies_in_one_step` in `crates/ui-egui/src/dialogs/revolve/tests.rs` checks its Angle preview, OK, Cancel and single-step undo; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | | Layers, artboards, document setup | 5 | 82% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: managing artboards from the canvas (artboard locking and colors, #2532 and #2403, Layers row menus and blend spine row menus are done; guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated; Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | @@ -726,7 +726,7 @@ since 2026-10-01. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. - 3D lighting widget: the Lighting tab of the 3D and Materials panel shows every light on a sphere at its Rotation and Height; a drag moves a light in one undo step, a press selects it, Move Light to Back and Move Light to Front change its side, and the arrow keys move the focused light ([three-d.md](three-d.md#lighting-widget)). `crates/ui-egui/src/panels/tests_three_d.rs` covers the drag, selection, side and keyboard. -- 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance. Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. The shadows of lights after the first are not built; the first light's Softness blurs the shadow (next entry). Scores unchanged. +- 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); in shaded output the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance (a Rendered image carries its shadows inside the image). Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. When Render Settings › Rendered draws its image (not the shaded fallback), every light with an Intensity above 0 casts a shadow-mapped shadow while Shading and Shadows are on; otherwise the shadows of lights after the first are not built; the first light's Softness blurs the shadow (next entry). Scores unchanged. - 3D shadows: with Shadows on, Revolve, Extrude & Bevel, Inflate and Rotate cast the shadow from the faces kept by the build that draws each solid, so drawing an object builds each of its solids once. The art and the shadow are unchanged. Evidence: `crates/three-d/src/shadow/tests.rs` (`a_solid_and_its_shadow_are_built_once` and the tests that compare each solid and its shadow with the two built apart), `solids::tests_shadow::a_shadowed_3d_object_builds_each_solid_once`, `solids::tests_shadow::the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it`, `revolve::tests::the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it`. Scores unchanged. - 3D shadows: the first light's Softness blurs the shadow of Revolve, Extrude & Bevel, Inflate and Rotate with a Gaussian Blur whose radius grows with Softness and Distance from Object and scales with the object (VectorCraft's own mapping; at 0 % the shadow stays hard-edged), on the canvas, in the art's bounds and in exports, and Expand Appearance keeps it as an image ([three-d.md](three-d.md#shadows)). Evidence: `shadow::tests::softness_blurs_the_shadow_more_the_farther_the_plane_is` (three-d), `solids::tests_shadow::the_first_lights_softness_blurs_the_shadow`, `solids::tests_shadow::a_fills_own_3d_effect_keeps_the_blur_below_its_later_effects`, `effectcmd::tests::a_soft_3d_shadow_is_drawn_measured_exported_and_expanded_blurred`. Scores unchanged. - 3D shadows: a command that applies or edits Extrude & Bevel, Inflate or Rotate with Shadows on checks the shadow from the faces kept by the builds that check the solids, as drawing casts it, so it builds each solid once instead of building it again for the shadow. A stroke whose solid is left out of the art past its own limits casts no shadow. Evidence: `solids::tests::the_check_builds_each_drawn_solid_once`, `solids::tests_shadow::a_stroke_left_out_of_the_art_casts_no_shadow`, `solids::tests_shadow::the_check_accepts_the_shadowed_objects_that_draw`. Scores unchanged. From 331d72f49da500b2939c7b31907d71dbae045a00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:24:16 -0800 Subject: [PATCH 026/103] Arrange: Match Objects keeps the proportion of very thin targets A width-only or height-only match left the other side unchanged when the target's measured side was 1e-9 pt or less, so a 1e-10 by 1 target matched to a width of 1 became a 1 by 1 square. The other side now follows the target's proportion whenever that side is above zero. --- crates/engine/src/cmd/addons/arrange.rs | 2 +- crates/engine/src/cmd/addons/arrange/tests.rs | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 26eed86fc6..df7c798efc 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -557,7 +557,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { /// `w` (height `h`), the other side following in proportion to the target's box `b`; for "both", the /// source's width and height. fn match_goal(size: &str, (w, h): (f64, f64), b: Rect) -> [f64; 2] { - let follow = |side: f64, from: f64, to: f64| if from > 1e-9 { side * to / from } else { side }; + let follow = |side: f64, from: f64, to: f64| if from > 0.0 { side * to / from } else { side }; match size { "width" => [w, follow(b.height(), b.width(), w)], "height" => [follow(b.width(), b.height(), h), h], diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 426a2d60a9..7a475b2ff8 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -378,6 +378,19 @@ fn match_gives_the_others_the_key_objects_size() { assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c)); } +#[test] +fn match_keeps_the_proportion_of_a_very_thin_target() { + let b = Rect::new(0.0, 0.0, 1e-10, 1.0); + let [w, h] = super::match_goal("width", (1.0, 5.0), b); + assert_eq!(w, 1.0); + assert!((h - 1e10).abs() <= 1.0, "{h}"); + let [w, h] = super::match_goal("height", (5.0, 1.0), Rect::new(0.0, 0.0, 1.0, 1e-10)); + assert!((w - 1e10).abs() <= 1.0, "{w}"); + assert_eq!(h, 1.0); + // A target with no width keeps its height. + assert_eq!(super::match_goal("width", (1.0, 5.0), Rect::new(0.0, 0.0, 0.0, 3.0)), [1.0, 3.0]); +} + #[test] fn match_takes_the_top_or_the_bottom_object_without_a_key() { let mut s = session(); From cbf78cae4c9e5e1962238498267b02b62c705577 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:27:56 -0800 Subject: [PATCH 027/103] Docs: remove leftover merge markers from the Arrange Tools section The merge of main left `=======` and `>>>>>>>` lines and a duplicate of the bounds-measurement lines in docs/mcp.md. --- docs/mcp.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 16d7854f25..9ed42b8ddf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17777,10 +17777,6 @@ with strokes and vector effects included and raster effects left out (see its ro Swap Objects, Replace with Top Object, Set Size of Each, Match Objects, and Sort Objects scale corner radii according to the `corners` parameter, which defaults to the Scale Corners preference. For these commands, the journal entry records the value used, and a replay of that entry scales corners the same way whatever the preference is then. -======= -as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds, and Group by Row, which always uses visual bounds -with strokes and vector effects included and raster effects left out (see its row). ->>>>>>> refs/check/threads10203-main | Command | Parameters (default) | Does | |---|---|---| From 00b3d4ca063ce900a92c6f9a955d286156813ada Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 02:11:55 -0800 Subject: [PATCH 028/103] 3D: rendered mode keeps perspective depths close to the eye The clip matrix refused a depth range whose depth slope came out negative, which happens when the nearest point is close to the eye (eye 100, depths 0 to 99.5), and the solid fell back to shaded faces. The mapped depth rises between the two ends whenever w is positive at both, so the check now tests w and the mapped depths instead of the slope. A test covers that range and a range that reaches the eye. The resolution test also checks that the rendered image carries its pixels, and docs/mcp.md and docs/target-app-parity.md say that rendered shadows need both Shading and Shadows on. --- crates/effects/src/solids/rendered.rs | 10 ++++++++-- crates/effects/src/solids/rendered/tests.rs | 17 +++++++++++++++++ crates/render/src/fx/tests.rs | 2 ++ docs/mcp.md | 4 ++-- docs/target-app-parity.md | 2 +- 5 files changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs index 3bcd361d39..7de6d4f2fb 100644 --- a/crates/effects/src/solids/rendered.rs +++ b/crates/effects/src/solids/rendered.rs @@ -415,10 +415,16 @@ fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4] let (z0, z1) = if z[1] > z[0] { (z[0], z[1]) } else { (z[0] - 0.5, z[0] + 0.5) }; let w = |z: f64| 1.0 - z * inv_eye; // ndc depth (dz · z + d0) / w: the farthest at DEPTH_MARGIN, the nearest at 1 − DEPTH_MARGIN. - let (lo, hi) = (DEPTH_MARGIN * w(z0), (1.0 - DEPTH_MARGIN) * w(z1)); + // With w positive over [z0, z1] the ndc depth is a linear-fractional function of z, so it rises + // monotonically between those two ends even when dz itself is negative (a near eye). + let (w0, w1) = (w(z0), w(z1)); + if !(w0 > 0.0 && w1 > 0.0) { + return None; + } + let (lo, hi) = (DEPTH_MARGIN * w0, (1.0 - DEPTH_MARGIN) * w1); let dz = (hi - lo) / (z1 - z0); let d0 = lo - dz * z0; - if !(dz > 0.0 && dz.is_finite() && d0.is_finite()) { + if !(dz.is_finite() && d0.is_finite() && hi / w1 > lo / w0) { return None; } let m = [[2.0 / rw, 0.0, -a * inv_eye, a], [0.0, -2.0 / rh, -b * inv_eye, b], [0.0, 0.0, dz, d0], [0.0, 0.0, -inv_eye, 1.0]]; diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index d92a33bb55..e1d953a563 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -404,6 +404,23 @@ fn meshes_without_one_projection_are_refused() { assert_eq!(render(&[], &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); } +/// Depths reaching close to a near eye still map in order: with the eye at 100 and depths 0 to 99.5 +/// the farthest point lands at the depth margin and the nearest at one minus it. +#[test] +fn depths_close_to_a_near_eye_keep_a_clip_matrix() { + let projection = MeshProjection { origin: Point::new(50.0, 50.0), eye: Some(100.0) }; + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let Some(m) = clip(projection, rect, [0.0, 99.5]) else { panic!("a perspective range in front of the eye maps") }; + let ndc = |z: f64| { + let row = |r: [f32; 4]| f64::from(r[2]) * z + f64::from(r[3]); + row(m[2]) / row(m[3]) + }; + assert!((ndc(0.0) - DEPTH_MARGIN).abs() < 1e-3, "{}", ndc(0.0)); + assert!((ndc(99.5) - (1.0 - DEPTH_MARGIN)).abs() < 1e-3, "{}", ndc(99.5)); + assert!(ndc(50.0) > ndc(0.0) && ndc(99.5) > ndc(50.0)); + assert!(clip(projection, rect, [0.0, 100.0]).is_none()); +} + /// A solid painted with a gradient, in a blending mode other than Normal or with an opacity below /// 100% draws its shaded faces, which keep that paint: the image shows opaque solid colors only. #[test] diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 9c3bf00bfb..073f72b519 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -2287,10 +2287,12 @@ fn rendered_art_follows_document_raster_resolution() { n.appearance.effects.push(crate::effects::new_effect("threeD.extrude", &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); let n = Arc::new(n); let mut renderer = Renderer::new(); + // The width of the art's image, counted only when the image carries its pixels. let image_width = |art: &Node| { let mut width = 0; art.walk(&mut |n| { if let vectorcraft_doc::NodeKind::Image(image) = &n.kind { + assert!(image.pixels.is_some(), "the rendered image has no pixels"); width = image.width; } }); diff --git a/docs/mcp.md b/docs/mcp.md index 761e6e9f5f..9f798950f4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6657,8 +6657,8 @@ Geometry effects after the 3D effect reshape the drawn edges. Expand as Wirefram joins the edges, so with such an effect its paths can differ from the drawn ones. The mode is saved in the native file, SVG and PDF exports draw the edges, and `effect.expandAppearance` keeps them as paths. Past 1,000,000 edges the source path is drawn, as it is for a solid past its limits. In rendered mode the effect draws its solid as one image with a depth buffer, lit -by every light. With `shadow` on, every light with an intensity above 0 casts shadows on the solid and on the -effect's shadow plane, drawn in the image; with it off, none does. `render` then also takes +by every light. With `shadow` and `shade` both on, every light with an intensity above 0 casts shadows on the solid and on the +effect's shadow plane, drawn in the image; with either off, none does. `render` then also takes `quality` (`"low"`, `"medium"` or `"high"`: 1, 2 × 2 or 3 × 3 samples a pixel, default `"medium"`, VectorCraft's own values), `resolution` (`null` for Document Raster Effects Settings › Resolution, the default, or 1..2400 ppi) and `background` (`"transparent"`, the default, or `"white"`). A quality whose samples would pass 16,777,216 pixels diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3dba22e1f2..617c608886 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -739,7 +739,7 @@ since 2026-10-01. - 3D and Materials › Object › Bevel › Reset: the button next to Extrude & Bevel's Bevel heading, in the options dialog and the panel, sets Bevel Shape, Width, Height, Repeat, Space, Bevel Inside and Bevel both sides back to their defaults and leaves the other settings as they are, as one undo step in the panel; it is unavailable while every bevel setting is at its default ([three-d.md](three-d.md#extrude--bevel)); `crates/ui-egui/src/dialogs/revolve/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. -- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light, with shadow maps; solids painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, a later geometry effect that reshapes paths only, Revolve on a group, fill or stroke, and an image past the renderer's limits draw the shaded faces instead, with a warning ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. +- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light, with shadow maps while Shading and Shadows are both on; solids painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, a later geometry effect that reshapes paths only, Revolve on a group, fill or stroke, and an image past the renderer's limits draw the shaded faces instead, with a warning ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Materials › Properties: Roughness and Metallic sliders set `material: {roughness, metallic}` on Extrude & Bevel, Revolve, Inflate and Rotate; with Shading on and outside Wireframe mode, any material other than the default (1 and 0) is shaded with craft-pbr's glTF 2.0 metallic-roughness BRDF, its highlight screened over each face; in every mode glTF exports write both factors, and USD exports write roughness and write metallic only when it is not the default 0 ([three-d.md](three-d.md#material-properties)); `crates/three-d/src/material.rs`, `crates/effects/src/solids/tests_material.rs`, `crates/engine/src/cmd/fileio/mesh3d/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Export 3D Object: the panel's button adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`), one undo step and none when each is an asset already, selects their assets and shows the Asset Export panel ([three-d.md](three-d.md#3d-and-materials-panel)); `panels::three_d::tests::{export_3d_object_adds_the_selected_3d_objects_to_asset_export, export_3d_object_leaves_out_a_3d_object_inside_another}` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. From 37a8aa85e5f0261803f915e5349c5125df3b46b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:35:52 -0800 Subject: [PATCH 029/103] 3D: rendered mode checks the paints it draws and reports Pathfinder fallback - Rendered eligibility reads only the top fill and strokes, the same items the solids are built from, so a lower gradient fill no longer blocks it. - A later Pathfinder effect falls back to shaded faces with the paths-only warning, as geometry effects do. - Live 3D edits show the fallback warning for one or several objects. - Raster Settings shows the resolution field as mixed when the selected objects' effective resolutions differ. - A curved highlight edge that crosses its neighbor keeps the outline. --- crates/effects/src/lighting.rs | 49 +++++++++++++++++++++ crates/effects/src/solids.rs | 10 +++-- crates/effects/src/solids/rendered.rs | 2 +- crates/effects/src/solids/rendered/tests.rs | 34 ++++++++++++++ crates/ui-egui/src/panels.rs | 13 +++++- crates/ui-egui/src/panels/tests_three_d.rs | 34 ++++++++++++-- crates/ui-egui/src/panels/three_d/raster.rs | 25 ++++++++--- 7 files changed, 152 insertions(+), 15 deletions(-) diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index fcabeeaded..ffbecebb17 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -205,6 +205,35 @@ fn curved_seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option SEAMED_FILL_EDGES + 2 || !elements.iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))) { return None; } + let segments: Vec = bez.segments().collect(); + for (i, a) in segments.iter().enumerate() { + let b = &segments[(i + 1) % segments.len()]; + if matches!((a, b), (PathSeg::Line(_), PathSeg::Line(_))) { + continue; + } + let controls = |s: &PathSeg| match s { + PathSeg::Line(s) => vec![s.p0, s.p1], + PathSeg::Quad(s) => vec![s.p0, s.p1, s.p2], + PathSeg::Cubic(s) => vec![s.p0, s.p1, s.p2, s.p3], + }; + let seam = a.end(); + let directions: Vec<_> = controls(a) + .into_iter() + .map(|p| p - seam) + .chain(controls(b).into_iter().map(|p| seam - p)) + .filter(|v| v.hypot() > 0.0) + .map(|v| v / v.hypot()) + .collect(); + let separated = directions.iter().any(|a| { + directions.iter().any(|b| { + let axis = *a + *b; + directions.iter().all(|v| axis.dot(*v) > 1e-12) + }) + }); + if !separated { + return None; + } + } let mut flat = vectorcraft_geom::BezPath::new(); let mut overflow = false; let mut last = kurbo::Point::ZERO; @@ -869,6 +898,26 @@ mod tests { } } + #[test] + fn a_curved_edge_crossing_its_neighbor_keeps_the_highlight_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.line_to((1000.0, 1000.0)); + folded.quad_to((500.0, 499.999), (0.0, 0.2)); + folded.line_to((-1000.0, 1000.0)); + folded.line_to((-1000.0, -1000.0)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0, 2.0 * HIGHLIGHT_FLATNESS).is_some()); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let over = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)).unwrap(); + assert_eq!(over.path_data(), Some(&path)); + } + } + /// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the /// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound /// either way and in a concave notch. A facet whose footprint would gain or lose area under a diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index e31260599f..883366a97f 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1008,6 +1008,11 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, /// fill rule, its shape's scopes and the index of its shape. type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope], usize); +fn solid_items(shape: &Profile) -> impl Iterator { + let top_fill = shape.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); + shape.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| i) +} + /// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes, /// a group's members from the back up, each with its shape's opacity, the region it paints and its /// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any): @@ -1017,8 +1022,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec>, Rect) { .iter() .enumerate() .flat_map(|(member, s)| { - let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); - s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(move |(_, i)| { + solid_items(s).map(move |i| { let (area, rule) = region(&s.path, s.rule, i); (i, s.opacity, area, rule, s.scopes.as_slice(), member) }) @@ -2082,7 +2086,7 @@ fn art_for( { let image = if rendered::reshapes_paths_only(later) { Err(rendered::PATHS_ONLY.into()) - } else if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(|s| &s.items), has_masks(shapes)) { + } else if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(solid_items), has_masks(shapes)) { meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| { let lighting = rendered::lighting(&fx.id, &p); let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? { diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs index 7de6d4f2fb..59b425da48 100644 --- a/crates/effects/src/solids/rendered.rs +++ b/crates/effects/src/solids/rendered.rs @@ -29,7 +29,7 @@ pub const PATHS_ONLY: &str = "A later effect reshapes the 3D object's paths; sho pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool { effects.iter().any(|e| { e.visible - && crate::is_geometry(&e.id) + && (crate::is_geometry(&e.id) || crate::is_pathfinder(&e.id)) && e.id != "distort.transform" && e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).is_none() }) diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index e1d953a563..845fd294c9 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -66,6 +66,40 @@ const MEDIUM: RenderSettings = RenderSettings { quality: 1, resolution: None, wh const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, super::super::ROTATE]; +#[test] +fn rendered_eligibility_ignores_fills_below_the_top_fill() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] { + let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new( + Gradient::new(GradientKind::Linear, stops), + ))))); + n.appearance.items.insert(0, lower); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + n.appearance.items.swap(0, 1); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "{id}"); + assert!(images(&drawn(&n)).is_empty(), "{id}"); + } +} + +#[test] +fn later_pathfinder_uses_shaded_faces_and_reports_the_fallback() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + n.appearance.effects.push(crate::new_effect("pathfinder.add", &json!({})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(PATHS_ONLY), "{id}"); + assert!(images(&drawn(&n)).is_empty(), "{id}"); + assert!(faces_bounds(&drawn(&n)).is_some(), "{id}"); + n.appearance.effects[1].visible = false; + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + } +} + /// The projection each mesh carries takes its points onto the page where the vector faces of the /// same solid lie: every corner of every facet is a projected mesh point, with and without /// perspective. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index aaabbaa41e..f6143391a7 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -958,8 +958,17 @@ pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: if let Some(it) = app.session.active_mut().and_then(|st| st.interaction.as_mut()) { it.keep_on_switch = true; } - if let Err(e) = app.session.preview(cmd, ¶ms) { - app.ui.status = e.to_string(); + match app.session.preview(cmd, ¶ms) { + Ok(answer) => { + let warning = answer + .get("warning") + .and_then(Value::as_str) + .or_else(|| answer.get("results")?.as_array()?.iter().find_map(|step| step.get("warning").and_then(Value::as_str))); + if let Some(warning) = warning { + app.status(warning.to_string()); + } + } + Err(e) => app.ui.status = e.to_string(), } if phase == Live::Released && let Err(e) = app.session.commit_interaction() diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index d668e76054..9e6ddb35f9 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1642,6 +1642,34 @@ fn rendered_warning_reaches_the_status_bar() { assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); } +#[test] +fn live_rendered_edits_report_fallback_for_single_and_batched_targets() { + for count in [1, 2] { + let mut app = app(); + let a = app.session.active().unwrap().selection.objects[0].0; + let mut ids = vec![a]; + if count == 2 { + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + ids.push(b); + } + app.run("select.set", json!({"ids": ids})).unwrap(); + app.run( + "paint.setFill", + json!({"gradient": {"kind": "linear", "stops": [ + {"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"} + ]}}), + ) + .unwrap(); + set_type(&mut app, "extrude").unwrap(); + super::set_render(&mut app, "rendered", Some("low")); + for phase in [Live::Dragging, Live::Released] { + app.ui.status.clear(); + send(&mut app, Map::from_iter([("depth".into(), json!(40))]), phase); + assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY, "{count} targets"); + } + } +} + /// Raster Settings OK shows why a rendered image falls back to shaded faces at a higher resolution. #[test] fn raster_settings_rendered_warning_reaches_the_status_bar() { @@ -1765,8 +1793,8 @@ fn raster_settings_sets_resolution_and_background() { for name in ["Use Document Raster Effects Resolution", "Transparent", "White"] { assert!(panel.shows(name), "the dialog shows {name}"); } - // One object takes the document's resolution and the other 150 ppi: the switch is blank, the - // resolution field shows the one resolution given, and neither background is picked. + // One object takes the document's resolution and the other 150 ppi. The switch and resolution + // field are mixed, and neither background is picked. use craft::behavior::Mixed; let switch = panel.toggled("Use Document Raster Effects Resolution"); assert!(!matches!(switch, Some(Mixed::Same(_))), "the switch shows {switch:?} for a mixed selection"); @@ -1774,7 +1802,7 @@ fn raster_settings_sets_resolution_and_background() { assert_ne!(panel.toggled(name), Some(Mixed::Same(true)), "{name} is shown picked for a mixed selection"); } let role = craft::ui::contract::Role::SPIN_BUTTON; - assert_eq!(panel.value_role("Resolution (ppi)", role).as_deref(), Some("150")); + assert_eq!(panel.value_role("Resolution (ppi)", role).as_deref(), Some(""), "a mixed resolution field is blank"); let history = undo_len(&panel.app()); let renders = |panel: &Panel| { let app = panel.app(); diff --git a/crates/ui-egui/src/panels/three_d/raster.rs b/crates/ui-egui/src/panels/three_d/raster.rs index e25aa6588b..c00dfab2b3 100644 --- a/crates/ui-egui/src/panels/three_d/raster.rs +++ b/crates/ui-egui/src/panels/three_d/raster.rs @@ -41,12 +41,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<(), String> { Some(d) => fields.set("document", FieldValue::Bool(d)), None => fields.set_mixed("document"), } - let mut given = resolutions.iter().flatten(); - let opening = match given.next() { - None => Some(ppi), - Some(first) if given.all(|r| r == first) => Some(*first), - Some(_) => None, - }; + let opening = opening_resolution(&resolutions, ppi); match opening { Some(r) => fields.set("resolution", FieldValue::Number(r)), None => fields.set_mixed("resolution"), @@ -63,6 +58,14 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<(), String> { Ok(()) } +fn opening_resolution(resolutions: &[Option], ppi: f64) -> Option { + let mut effective = resolutions.iter().map(|r| r.unwrap_or(ppi)); + let Some(first) = effective.next() else { + return Some(ppi); + }; + effective.all(|r| r == first).then_some(first) +} + /// The dialog over its rows. fn dialog<'a>() -> ParamDialog<'a> { let backgrounds = vec![("transparent".to_owned(), tl!("Transparent").into()), ("white".to_owned(), tl!("White").into())]; @@ -130,6 +133,16 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: &Opened) -> Result mod tests { use super::*; + #[test] + fn opening_resolution_compares_document_and_explicit_ppi() { + assert_eq!(opening_resolution(&[None, Some(150.0)], 72.0), None); + assert_eq!(opening_resolution(&[Some(150.0), None], 72.0), None); + assert_eq!(opening_resolution(&[None, Some(150.0)], 150.0), Some(150.0)); + assert_eq!(opening_resolution(&[None, None], 72.0), Some(72.0)); + assert_eq!(opening_resolution(&[], 72.0), Some(72.0)); + assert_eq!(opening_resolution(&[Some(72.0), Some(150.0)], 72.0), None); + } + fn fields(set: &[(&str, FieldValue)]) -> DialogFields { let mut f = DialogFields::new(); for (key, value) in set { From df3950f5759d79bc3391690f530a893ab2820126 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:12:47 -0800 Subject: [PATCH 030/103] Import PDF: linked pages keep an explicit Crop Box for a file with editing data With Import PDF Pages as Links on, a file with editing data opened every page on its trim box even when Crop Box was picked: document.open's linkPages path turned a crop-box request into a trim box without asking whether the box was named. A request that names the crop box (cropTo or crop) now keeps the crop boxes; a file that names no box still opens on its trim boxes, as it does when opened as art. Follows #7723. --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/pdfimport.rs | 11 ++-- crates/engine/src/tests/placed_document.rs | 62 ++++++++++++++++++++++ docs/mcp.md | 9 ++-- 4 files changed, 74 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index e902f4185a..7e7340989a 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF or PDF-compatible .ai with its editor's private data uses trim boxes when no box is named; an explicit crop uses crop boxes), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF or PDF-compatible .ai with its editor's private data: its trim box when no box is named; a PDF with only a VectorCraft native attachment: its crop box by default; an explicit crop: its crop box; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 954a345ae0..005cc4a557 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -176,8 +176,8 @@ impl LoadOptions { self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages } - /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible - /// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default, + /// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible + /// `.ai` with Illustrator private data opens on its trim boxes by default, /// with the bleed around them. An explicit crop-box request uses its crop box. fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { @@ -257,7 +257,7 @@ pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page /// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box; -/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the +/// a PDF-compatible `.ai` that names no box gets its trim box, as it opens), in a row from the /// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box, /// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the /// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens @@ -289,8 +289,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?, }; let bounding = o.crop == CropTo::Bounding; - // A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]). - let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop }; + // A PDF-compatible `.ai` that names no box opens on its trim boxes ([`LoadOptions::import_options`]); + // an explicit crop-box request keeps its crop boxes. + let crop = if !o.explicit_crop_box && o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop }; let mut doc = Document::new(1.0, 1.0); let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?; doc.artboards.clear(); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 3dd4959489..5166c820c4 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -731,6 +731,68 @@ fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() { assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins"); } +#[test] +fn linked_pages_of_a_file_with_editing_data_keep_an_explicit_crop_box() { + let dir = Folder::new("open-pdf-link-pages-explicit-crop"); + let src = dir.file("editable.ai"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": src, "format": "ai", "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&src).unwrap(), None)); + let board = |s: &Session| { + let r = s.doc().unwrap().doc.artboards[0].rect; + (r.width(), r.height()) + }; + // No box named: the trim box, as the file opens as art. + s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); + // An explicit crop box is the crop box, which takes in the bleed. + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "crop"})).unwrap(); + let (w, h) = board(&s); + assert!(w > 100.0 && h > 50.0, "{w} x {h}"); + s.execute("document.open", &json!({"path": src, "linkPages": true, "crop": "crop"})).unwrap(); + assert_eq!(board(&s), (w, h)); +} + +#[test] +fn linked_pages_with_only_a_native_attachment_default_to_crop_boxes() { + let dir = Folder::new("open-pdf-link-pages-native-crop"); + let src = dir.file("editable.pdf"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "document.exportPdf", + &json!({"path": src, "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + let bytes = std::fs::read(&src).unwrap(); + assert!(vectorcraft_pdf::editing(&bytes).is_some_and(|e| e.intact)); + assert!(!vectorcraft_pdf::has_illustrator_data(&bytes, None)); + let board = |s: &Session| { + let r = s.doc().unwrap().doc.artboards[0].rect; + (r.width(), r.height()) + }; + s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap(); + let (w, h) = board(&s); + assert!(w > 100.0 && h > 50.0, "{w} x {h}"); + for key in ["cropTo", "crop"] { + let mut params = json!({"path": src, "linkPages": true}); + params[key] = json!("crop"); + s.execute("document.open", ¶ms).unwrap(); + assert_eq!(board(&s), (w, h), "{key}"); + } + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); +} + #[test] fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() { use vectorcraft_testkit::pdf::{PdfPage, pdf}; diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..7f0b7c3aa1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1744,8 +1744,8 @@ unknown label is refused. The `warnings` of the result name the first three such Opening a PDF (or `.ai`) imports every page as an artboard and layer; `document.open` takes `pages` ("2-3, 5", 1-based), `cropTo` (`bounding` (the art's bounds), `art`, `crop` (default), `trim`, `bleed`, `media`: the box each artboard gets; -with `trim` the bleed box round it becomes the document's bleed and the artboards are 36 pt apart plus that bleed on both sides, and a PDF-compatible `.ai` or a PDF saved with its editing data opens on its trim boxes for -`crop`, its crop box taking the bleed in) and `password` for an encrypted file. `document.pdfInfo` reads a file without opening it: the page count, each page's +with `trim` the bleed box round it becomes the document's bleed and the artboards are 36 pt apart plus that bleed on both sides; a PDF or PDF-compatible `.ai` with Illustrator private data uses trim boxes when no box is named; +an explicit `crop` uses crop boxes) and `password` for an encrypted file. `document.pdfInfo` reads a file without opening it: the page count, each page's size and boxes, `needsPassword`, and with `thumbnail: n` a PNG of page n. It reads a PostScript file (an EPS, a `.ps` file, a `.ai` in PostScript form) as one page the size of its bounding box (a US Letter page without one), with an empty `boxes`, and `thumbnail: 1` shows what that page prints. A page whose `UserUnit` (PDF 1.6) is above 1 @@ -1755,8 +1755,9 @@ such a page opens from that data at the page's size. `linkPages: true` (File › Open's Import PDF dialog: Import PDF pages as links) opens each page `pages` picks as a placed document linked to that page of the file, as `file.place` with `link` places one, instead of as editable art. Each page gets an artboard of its `cropTo` box (`bounding`: its art's bounds; a blank page gets its crop box), in a row from the left 36 pt apart, and -a layer named after the page (`Page 2`). A PDF-compatible `.ai` with `cropTo: "crop"` gets its trim boxes, as it does -when it opens as art. A page on its trim box shows its bleed box round the artboard, and the pages give the document +a layer named after the page (`Page 2`). A PDF or PDF-compatible `.ai` with Illustrator private data +that names no box gets its trim boxes, as it does when it opens as art. A PDF with only a VectorCraft native attachment (Preserve Editing) defaults to crop boxes for linked pages. +`cropTo: "crop"` (or `crop: "crop"`) gives either file its crop boxes. A page on its trim box shows its bleed box round the artboard, and the pages give the document their bleed; the artboards are then 36 pt apart plus the bleed on both sides. The document opens in CMYK when most of those pages are painted mostly in CMYK, unless `colorMode` names a mode. All the pages' objects share one copy of the file. The Links panel lists each page, and `links.embed` makes a page editable art. The command's `linkPages` defaults to false; the dialog checks the From 48dbc41f35d152e32da6355c164780b688d4b39a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:34:51 -0800 Subject: [PATCH 031/103] 3D: a live preview without a warning clears the one an earlier preview showed live_run showed a preview's warning in the status bar but nothing removed it, so the rendered fallback message stayed after a later preview no longer fell back. The status bar now remembers the command and status write that showed the warning. A later preview of the same command with no warning clears it, unless the status line has been written since. --- crates/ui-egui/src/panels.rs | 10 +++++++ crates/ui-egui/src/panels/tests_three_d.rs | 34 ++++++++++++++++++++++ crates/ui-egui/src/state.rs | 7 +++++ 3 files changed, 51 insertions(+) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index f6143391a7..3920644995 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -964,8 +964,18 @@ pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: .get("warning") .and_then(Value::as_str) .or_else(|| answer.get("results")?.as_array()?.iter().find_map(|step| step.get("warning").and_then(Value::as_str))); + let shown = app.ui.live_warning.take(); if let Some(warning) = warning { app.status(warning.to_string()); + app.ui.live_warning = Some((cmd.to_string(), app.ui.status_sets, warning.to_string())); + } else if let Some((shown_cmd, sets, text)) = shown { + // Only a preview of the same command rechecks what warned, and only while + // nothing else has written the status line since. + if shown_cmd != cmd { + app.ui.live_warning = Some((shown_cmd, sets, text)); + } else if app.ui.status_sets == sets &&app.ui.status == text { + app.ui.status.clear(); + } } } Err(e) => app.ui.status = e.to_string(), diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 9e6ddb35f9..f0a8626eb2 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1670,6 +1670,40 @@ fn live_rendered_edits_report_fallback_for_single_and_batched_targets() { } } +/// A live edit whose preview has no warning clears the warning an earlier preview showed, and +/// leaves a status line that something else set in between. +#[test] +fn a_live_edit_without_a_warning_clears_the_earlier_one() { + let gradient = json!({"gradient": {"kind": "linear", "stops": [ + {"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"} + ]}}); + let mut app = app(); + app.run("paint.setFill", gradient.clone()).unwrap(); + set_type(&mut app, "extrude").unwrap(); + super::set_render(&mut app, "rendered", Some("low")); + send(&mut app, Map::from_iter([("depth".into(), json!(40))]), Live::Released); + assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + send(&mut app, Map::from_iter([("depth".into(), json!(50))]), Live::Released); + assert_eq!(app.ui.status, ""); + + app.run("paint.setFill", gradient.clone()).unwrap(); + send(&mut app, Map::from_iter([("depth".into(), json!(60))]), Live::Released); + assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); + app.status("Something else"); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + send(&mut app, Map::from_iter([("depth".into(), json!(70))]), Live::Released); + assert_eq!(app.ui.status, "Something else"); + + // A newer status line with the same text is kept too. + app.run("paint.setFill", gradient.clone()).unwrap(); + send(&mut app, Map::from_iter([("depth".into(), json!(80))]), Live::Released); + app.status(vectorcraft_effects::rendered::OPAQUE_ONLY); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + send(&mut app, Map::from_iter([("depth".into(), json!(90))]), Live::Released); + assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); +} + /// Raster Settings OK shows why a rendered image falls back to shaded faces at a higher resolution. #[test] fn raster_settings_rendered_warning_reaches_the_status_bar() { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index eeef403f06..db9f333710 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -727,6 +727,12 @@ pub struct UiState { /// The Replace Font request behind the status bar's warning ([`ReplaceFontWarning`]). Not saved. #[serde(skip)] pub replace_font_warning: Option, + /// The warning a live control's last preview put in the status bar ([`crate::panels::live_run`]): + /// the command previewed, [`Self::status_sets`] after the warning was shown, and its text. A later + /// preview of the same command without a warning clears it while the status line still holds it. + /// Not saved. + #[serde(skip)] + pub live_warning: Option<(String, u64, String)>, /// The last Find and Replace search ([`crate::dialogs::find_replace`]): the dialog's Find and /// Replace With text, its options and the place the search reached (the walk, `found`), which /// Edit › Find Next goes on from while the dialog is closed. Not saved. @@ -1526,6 +1532,7 @@ impl Default for UiState { status: String::new(), status_sets: 0, replace_font_warning: None, + live_warning: None, last_find: None, status_notes: None, startup_notes: Vec::new(), From a4b11dc37fbb6baca66fd29f7ece649f5f3a3cbd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:16:43 -0800 Subject: [PATCH 032/103] 3D: format the live-warning status check The gate's fmt step failed on 48dbc41f: the status comparison added in that commit lacked a space after `&&` in crates/ui-egui/src/panels.rs. --- crates/ui-egui/src/panels.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 3920644995..b378152215 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -973,7 +973,7 @@ pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: // nothing else has written the status line since. if shown_cmd != cmd { app.ui.live_warning = Some((shown_cmd, sets, text)); - } else if app.ui.status_sets == sets &&app.ui.status == text { + } else if app.ui.status_sets == sets && app.ui.status == text { app.ui.status.clear(); } } From 20a5e4255503a8fb760abf6dec48f603b79adb82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:25:17 -0800 Subject: [PATCH 033/103] 3D: check the unshaded pixel with a test-lint-clean assertion The gate's test-lint step failed on `unshaded_surfaces_show_their_paint`: its `assert!(...all(...))` had no length or emptiness check. The test now takes the largest channel difference and asserts it is `Some(0..=1)`, so an empty comparison fails and the one-unit tolerance per channel is unchanged. --- crates/effects/src/solids/rendered/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index 845fd294c9..275a747edc 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -345,7 +345,8 @@ fn unshaded_surfaces_show_their_paint() { assert!(!lighting.shade); let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); let center = pixel(&image, image.cols / 2, image.rows / 2); - assert!(center[..3].iter().zip([51u8, 128, 204]).all(|(a, b)| a.abs_diff(b) <= 1), "{center:?}"); + let worst = center[..3].iter().zip([51u8, 128, 204]).map(|(a, b)| a.abs_diff(b)).max(); + assert!(matches!(worst, Some(0..=1)), "{center:?}"); } /// A face turned toward the light is lit more than one turned away from it, and a light straight From 8930d9d5dc91ca8fe4d7d965479151851df713ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:31:07 -0800 Subject: [PATCH 034/103] Scripts: say the Color Picker's CMYK rule applies in the app An answer to app.showColorPicker taken from script.run's answers keeps the color model it was given; only the app's picker returns an RGB pick as CMYK in a CMYK document. --- docs/mcp.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 8907f40796..fed7676f0a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4011,9 +4011,10 @@ empty object are the same. `app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, `CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a -`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; when the -run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so the -color's `typename` can differ from the picker's model and from the color given. The picker opens on the color as +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in the app, +when the run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so +the color's `typename` can differ from the picker's model and from the color given. An answer taken from `answers` +keeps the color model it was given. The picker opens on the color as given, whatever Only Web Colors was left at in another picker. OK with the color unchanged and Cancel return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting end the run as they do at the other dialogs, and close the picker. They also end a screen color sample From c9ef0845a553eecc0a3d87f84638f7f9a6931587 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:04:50 -0800 Subject: [PATCH 035/103] xtask: test-lint census rule follows closure writes, async blocks and nested guards The census rule leaves out a loop that feeds each entry into a computation, so it needs to know which calls and assignments in the loop body run. It misjudged these shapes: - A parameter of an async closure (`async |mut c: Command| { ... }`) or one whose type contains `->` did not shadow the entry. - An async block awaited where it is written (`async { ... }.await`, `(async { ... }).await`) or passed straight to `block_on` counted as never run, for both calls and assignments. An `||` before it still guards it, and an `async move` block still writes only its own copies. - An inner binding assigned the entry stayed hidden by a shadow of an outer binding of the same name. - `ready || accept({ 0 }, wrap(app.run(c)))` lost the `||` guard. - A closure with parameters stored in `Some(...)` counted as called. - A closure call was found past the end of the block that binds the closure. - An assignment in a closure dropped with `let _` or stored in parentheses (`let _saved = (|| { ... });`) ended the entry alias. - An assignment in a closure that is called only conditionally kept the alias. Assignments now use a "may run" mode of the same check that finds calls, so a call that may be skipped still counts and a call that can never run does not. --- xtask/src/test_lint.rs | 475 ++++++++++++++++++++++++++++++++++------- 1 file changed, 403 insertions(+), 72 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e517292e73..1485cfc600 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2163,19 +2163,13 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { if b[at] != b'|' || b.get(at + 1) == Some(&b'|') { continue; } - let head = b[from..at].trim_ascii_end(); - let head = head.strip_suffix(b"move").unwrap_or(head).trim_ascii_end(); + // `move` and `async` may come before the parameters (`async |mut c: Command| …`). + let text = String::from_utf8_lossy(b[from..at].trim_ascii_end()); + let head = strip_closure_keywords(&text).0.as_bytes(); if !head.is_empty() && !matches!(head.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) { continue; } - let Some(end) = (at + 1..to).find(|&i| b[i] == b'|') else { continue }; - // Parameters may carry types (`|c: Command|`, `|p: &[u8]|`). - if !b[at + 1..end] - .iter() - .all(|&c| is_ident(c) || c.is_ascii_whitespace() || matches!(c, b',' | b'&' | b':' | b'<' | b'>' | b'(' | b')' | b'[' | b']' | b'\'')) - { - continue; - } + let Some(end) = closure_params_end(b, at, to) else { continue }; let mut until = skip_ws(b, end + 1); if b.get(until) == Some(&b'{') { until = matching(b, until).unwrap_or(to).min(to); @@ -2268,18 +2262,25 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { .max_by_key(|&(since, _)| since) .map_or(to, |(_, until)| until); // Assignments in move closures leave outer bindings unchanged. Assignments in async - // blocks or uncalled closures do not run; conditional assignments do not make aliases. - if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { + // blocks that are not awaited, or in closures that nothing calls, do not run; + // conditional assignments do not make aliases. + if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || !runs_with_assertion_within(b, from, to, at, &[], true) { continue; } if live(value_start(eq, end), end, &derived, &shadows) { if !runs_with_assertion(b, from, to, at) { continue; } - // Assigning the entry again ends what earlier assignments in the same scope stored. - for s in shadows.iter_mut().filter(|s| s.0 == name && s.1 <= at && at < s.2 && s.2 == until) { + // Assigning the entry again ends what earlier assignments in the same scope stored, + // and suspends the shadows of outer bindings of the name until this binding's scope ends. + let mut resumed = vec![]; + for s in shadows.iter_mut().filter(|s| s.0 == name && s.1 <= at && at < s.2 && s.2 >= until) { + if until < s.2 { + resumed.push((s.0.clone(), until, s.2)); + } s.2 = end; } + shadows.extend(resumed); derived.push((name, end, until)); } else if derived.iter().any(|(d, _, _)| *d == name) && !empty_bodies.iter().any(|&(open, close)| open < at && at < close) { shadows.push((name, end, until)); @@ -2523,18 +2524,18 @@ fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { /// that closure ([`closure_calls`]), and a call in a closure that is not bound does not count. A call /// in a nested `for` body counts only when the loop's source yields an item ([`literal_source_yields`]). fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { - runs_with_assertion_within(b, from, to, start, &[]) + runs_with_assertion_within(b, from, to, start, &[], false) } -/// [`runs_with_assertion`], where `active` holds the calls whose check is in progress, so a closure -/// that calls itself does not recurse without end. -fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { +/// Checks whether `start` runs whenever assertions pass, or may run at all when `may_run` is true. +/// `active` holds positions being checked so recursive closure calls terminate. +fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize], may_run: bool) -> bool { if active.contains(&start) { return false; } let mut active = active.to_vec(); active.push(start); - if in_uncalled_closure(b, from, to, start, &active) { + if in_uncalled_closure(b, from, to, start, &active, may_run) { return false; } // Check enclosing blocks independently of the call's statement: an earlier semicolon inside @@ -2555,21 +2556,31 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac _ => {} } } + let prefix_at = skip_ws(b, head).min(open); let prefix = b[head..open].trim_ascii(); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); + // Where the `async` of an async block starts. + let async_kw = [b"async".as_slice(), b"async move"] + .iter() + .find(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident)) + .map(|kw| prefix_at + prefix.len() - kw.len()); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { - if !runs_with_assertion_within(b, from, to, open, &active) { + if !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; } - } else if nested_for && literal_source_yields(prefix) != Some(true) { + } else if nested_for && !literal_source_yields(prefix).unwrap_or(may_run) { // A nested `for` body runs only when its source yields an item. return false; - } else if !prefix.ends_with(b"|") + } else if let Some(kw) = async_kw { + // An async block needs polling where it is written, by await or block_on. + let polled = polled_in_place(b, from, kw, open); + if !polled || !runs_with_assertion_within(b, from, to, kw, &active, may_run) { + return false; + } + } else if !may_run + && !prefix.ends_with(b"|") && !nested_for && (prefix.ends_with(b"=>") - || [b"async".as_slice(), b"async move"] - .iter() - .any(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident)) || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) || (!words(prefix, b"loop", 0, prefix.len()).is_empty() && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) @@ -2583,10 +2594,12 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac // the operand of `||` or `&&`. let mut stmt = from; let mut braces = 0usize; - // The parenthesis or bracket that most closely encloses the call: a block after it is an - // earlier argument or element (`accept({ 0 }, app.run(c))`), not an earlier statement. - let group = (from..start).rev().find(|&i| matches!(b[i], b'(' | b'[' | b'{') && matching(b, i).is_none_or(|close| start < close)); - let group = group.filter(|&i| b[i] != b'{'); + // The outermost parenthesis or bracket that encloses the call inside its innermost block: a block + // after it is an earlier argument or element (`accept({ 0 }, app.run(c))`, also + // `accept({ 0 }, wrap(app.run(c)))`), not an earlier statement. + let encloses = |i: usize| matching(b, i).is_none_or(|close| start < close); + let block = (from..start).rev().find(|&i| b[i] == b'{' && encloses(i)); + let group = (block.map_or(from, |open| open + 1)..start).find(|&i| matches!(b[i], b'(' | b'[') && encloses(i)); for i in (from..start).rev() { match b[i] { b'}' if braces == 0 && group.is_some_and(|g| g < i) => braces += 1, @@ -2621,21 +2634,27 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. // Earlier sibling elements cannot skip the call, but guards around their group still can. let mut depth = 0usize; - let params = (stmt..start).find_map(|pipe| { - if b[pipe] != b'|' { - return None; - } - let head = String::from_utf8_lossy(b[stmt..pipe].trim_ascii()); - let head = strip_closure_keywords(&head).0.as_bytes(); - if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) { - return None; - } - (pipe + 1..start).find(|&end| b[end] == b'|').map(|end| (pipe, end)) - }); - let mut closure = params.map(|(pipe, _)| pipe); + // The parameter lists of closures with parameters (`let run = |c: Command| …`, + // `Some(|_: ()| …)`): a `|` where an expression starts, up to the next `|`. + let params: Vec<(usize, usize)> = (stmt..start) + .filter(|&pipe| b[pipe] == b'|' && b.get(pipe + 1) != Some(&b'|') && pipe.checked_sub(1).is_none_or(|p| b[p] != b'|')) + .filter(|&pipe| { + let head = String::from_utf8_lossy(b[stmt..pipe].trim_ascii()); + let head = strip_closure_keywords(&head).0.as_bytes(); + head.is_empty() + || matches!(head.last(), Some(b'(' | b'[' | b'{' | b',')) + || head.ends_with(b"=") && !matches!(head.get(head.len().wrapping_sub(2)), Some(b'=' | b'!' | b'<' | b'>')) + }) + .filter_map(|pipe| closure_params_end(b, pipe, start).map(|end| (pipe, end))) + .collect(); + let mut closure = None; let mut sibling = false; for i in (stmt + 1..start).rev() { - if params.is_some_and(|(pipe, end)| pipe <= i && i <= end) { + if let Some(&(pipe, _)) = params.iter().find(|&&(pipe, end)| pipe <= i && i <= end) { + // A closure that encloses the call at its own level, not a sibling element. + if i == pipe && depth == 0 && !sibling { + closure = Some(pipe); + } continue; } match b[i] { @@ -2656,7 +2675,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>') { break; } - if b[i] == b'&' + if !may_run + && b[i] == b'&' && b[i - 1] == b'&' && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) && !asserted_conjunction(b, from, to, i - 1) @@ -2672,6 +2692,9 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac && !asynchronous && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) { + if may_run { + continue; + } return false; } closure = Some(stmt + prefix.len()); @@ -2683,29 +2706,19 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let head = String::from_utf8_lossy(&b[stmt..end]); let (bare, asynchronous) = strip_closure_keywords(head.trim_end()); // Unwrap parentheses whose outer closing parenthesis ends the initializer. - let unwrapped = (|| { - let mut head = bare; - let mut inner_close = None; - while let Some(prefix) = head.strip_suffix('(') { - let close = matching(b, stmt + prefix.len())?; - if close < start || inner_close.is_some_and(|inner| !b[inner + 1..close].trim_ascii().is_empty()) { - return None; - } - inner_close = Some(close); - head = prefix.trim_end(); - } - inner_close.filter(|&close| b.get(skip_ws(b, close + 1)) == Some(&b';')).map(|_| head) - })(); + let unwrapped = parenthesized_closure_binding_head(b, stmt, start, bare); let binding_head = unwrapped.unwrap_or(bare); let Some(binding) = binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| h.starts_with(char::is_whitespace)) else { + // Other callees may invoke or retain a callback, but an unused constructor only stores it. + let may_call = may_run && !asynchronous && closure_body_end(b, end, to).is_some_and(|close| !stored_closure(b, bare, close, to)); // `(|| app.run(c))()` calls the closure where it is written. let open = stmt + bare.len(); - let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return false }; + let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return may_call }; let call = skip_ws(b, close + 1); if b.get(call) != Some(&b'(') { - return false; + return may_call; } // An async closure's future runs when it is passed straight to `block_on` or awaited. A `|` // before `block_on` may open a closure around it (`let _saved = || block_on(…);`) that @@ -2726,7 +2739,50 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac return b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); }; let Some(name) = pattern_names(binding).last() else { return false }; - closure_calls(b, &name, skip_ws(b, stmt), end, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, &active)) + closure_calls(b, &name, skip_ws(b, stmt), end, to, asynchronous) + .into_iter() + .any(|at| runs_with_assertion_within(b, from, to, at, &active, may_run)) +} + +/// Finds the last non-whitespace byte of the closure body after the parameters opened at `pipe`. +fn closure_body_end(b: &[u8], pipe: usize, to: usize) -> Option { + let body = skip_ws(b, closure_params_end(b, pipe, to)? + 1); + let mut after = body; + while after < to && !matches!(b[after], b',' | b';' | b')' | b']' | b'}') { + let next = skip_turbofish(b, after); + after = if next != after { + next + } else if matches!(b[after], b'(' | b'[' | b'{') { + matching(b, after).unwrap_or(to) + 1 + } else { + after + 1 + }; + } + let close = body + b[body..after.min(to)].trim_ascii_end().len(); + (close > body).then(|| close - 1) +} + +/// The head before parentheses around a closure initializer, when each pair encloses `start` +/// and the outer closing parenthesis ends the statement. +fn parenthesized_closure_binding_head<'a>(b: &[u8], stmt: usize, start: usize, mut head: &'a str) -> Option<&'a str> { + let mut inner_close = None; + while let Some(prefix) = head.strip_suffix('(') { + let close = matching(b, stmt + prefix.len())?; + if close < start || inner_close.is_some_and(|inner| !b[inner + 1..close].trim_ascii().is_empty()) { + return None; + } + inner_close = Some(close); + head = prefix.trim_end(); + } + inner_close.filter(|&close| b.get(skip_ws(b, close + 1)) == Some(&b';')).map(|_| head) +} + +/// The `|` that closes the closure parameter list opened by the `|` at `pipe`, before `to`, when the +/// text between them can be a parameter list. Parameters may carry types (`|c: Command|`, +/// `|p: &[u8; 4]|`, `|f: fn() -> bool|`), but not a block, a string, a method call or an assignment. +fn closure_params_end(b: &[u8], pipe: usize, to: usize) -> Option { + let end = (pipe + 1..to).find(|&i| b[i] == b'|')?; + (!b[pipe + 1..end].iter().any(|c| matches!(c, b'{' | b'}' | b'"' | b'.' | b'='))).then_some(end) } /// The head before a closure's parameters with a trailing `move` and `async` removed, and whether @@ -2744,10 +2800,12 @@ fn strip_closure_keywords(head: &str) -> (&str, bool) { } /// Where `b[after..to]` calls the closure that the `let` at `bound` binds to `name`: `name(…)`, not -/// a method (`other.run()`), and not after a later `let` of the same name that is still in scope. -/// Calling an async closure only makes a future, so its call counts only when the future is -/// awaited (`run().await`) or passed to `block_on`. +/// a method (`other.run()`), not after the end of the block that holds the `let`, and not after a +/// later `let` of the same name that is still in scope. Calling an async closure only makes a +/// future, so its call counts only when the future is awaited (`run().await`) or passed to +/// `block_on`. fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, asynchronous: bool) -> Vec { + let to = to.min(block_close(b, bound)); let rebinds = |l: usize, at: usize| { let eq = (l + 3..at).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')); // The new name is in scope from the end of its statement (`let run = run();` still calls the @@ -2776,6 +2834,15 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as .collect() } +/// Whether the expression `b[start..end]` is the only argument of a `block_on` call +/// (`block_on(run())`, also `block_on (run())`, `executor::block_on(run())` or with a trailing +/// comma), not of another function whose name ends in `block_on`. +fn passed_to_block_on(b: &[u8], start: usize, end: usize) -> bool { + let Some(open) = b[..start].trim_ascii_end().len().checked_sub(1).filter(|&o| b[o] == b'(') else { return false }; + b[..open].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + && matching(b, open).is_some_and(|close| close >= end && matches!(b[end..close].trim_ascii(), b"" | b",")) +} + /// Whether an `&&` is at the top level of an assertion's first argument. fn asserted_conjunction(b: &[u8], from: usize, to: usize, at: usize) -> bool { macro_calls(b, from, to).iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())).any(|a| { @@ -2813,13 +2880,41 @@ fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: b.get(open) == Some(&b'(') && matching(b, open) == close.checked_sub(1) && required_conjunction(b, open, close, at, depth + 1) } -/// Whether `start` lies in the body of an `async` or `async move` block. +/// Whether `start` lies in the body of an `async move` block, which writes to its own copies of the +/// captures, or of an `async` block that is not polled where it is written ([`polled_in_place`]). fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { - (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { - let head = b[from..open].trim_ascii_end(); - let head = head.strip_suffix(b"move").filter(|h| h.last().is_some_and(u8::is_ascii_whitespace)).unwrap_or(head).trim_ascii_end(); - head.strip_suffix(b"async").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) - }) + (from..start) + .filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) + .any(|open| async_block_keyword(b, from, open).is_some_and(|(kw, moved)| moved || !polled_in_place(b, from, kw, open))) +} + +/// The position of `async` before the block at `open`, and whether it captures by move. +fn async_block_keyword(b: &[u8], from: usize, open: usize) -> Option<(usize, bool)> { + let head = b[from..open].trim_ascii_end(); + let moved = head.strip_suffix(b"move").filter(|h| h.last().is_some_and(u8::is_ascii_whitespace)); + let head = moved.unwrap_or(head).trim_ascii_end(); + head.strip_suffix(b"async").filter(|h| !h.last().copied().is_some_and(is_ident)).map(|h| (from + h.len(), moved.is_some())) +} + +/// Whether the async block whose `async` starts at `kw` and whose body opens at `open` is polled +/// where it is written, by awaiting it or passing it straight to `block_on` (with optional +/// parentheses around the block), so its body has run before the next statement. +fn polled_in_place(b: &[u8], from: usize, kw: usize, open: usize) -> bool { + let Some(mut close) = matching(b, open) else { return false }; + let mut start = kw; + let mut before = from + b[from..kw].trim_ascii_end().len(); + // Unwrap parentheses around the block, but not the parentheses of a call (`wrap(async { … })`). + while before > from + && b[before - 1] == b'(' + && !b[from..before - 1].trim_ascii_end().last().copied().is_some_and(|c| is_ident(c) || matches!(c, b')' | b']' | b'>')) + { + let Some(paren) = matching(b, before - 1).filter(|&c| c > close && b[close + 1..c].trim_ascii().is_empty()) else { break }; + start = before - 1; + close = paren; + before = from + b[from..before - 1].trim_ascii_end().len(); + } + let next = skip_ws(b, close + 1); + (b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident)) || passed_to_block_on(b, start, close + 1) } /// Whether `start` lies in the block or expression body of a move closure that captures `name`: @@ -2854,9 +2949,10 @@ fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) - } /// Whether `start` lies in the block body of a closure bound with `let` in `b[from..to]` -/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds, or of -/// a closure that a `let` stores without a call ([`stored_closure`]). -fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { +/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds that +/// runs (or may run, when `may_run` is true), or of a closure that a `let` stores without a call +/// ([`stored_closure`]). +fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize], may_run: bool) -> bool { let mut depth = 0usize; for i in (from..start).rev() { match b[i] { @@ -2868,6 +2964,8 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); + // Parentheses around the whole initializer (`let _saved = (|| { … });`), not a call's. + let head = parenthesized_closure_binding_head(b, from, start, head).filter(|h| h.ends_with('=')).unwrap_or(head); let close = matching(b, i).unwrap_or(to); let binding = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b); let stored = binding.is_none() && stored_closure(b, head, close, to); @@ -2876,7 +2974,7 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & if stored || !closure_calls(b, &name, bound, close, to, asynchronous) .into_iter() - .any(|at| runs_with_assertion_within(b, from, to, at, active)) + .any(|at| runs_with_assertion_within(b, from, to, at, active, may_run)) { return true; } @@ -10487,6 +10585,239 @@ mod tests { assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); } + #[test] + fn census_finds_the_closure_a_call_names() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let _saved = Some(|_: ()| app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "a stored closure with parameters is not called" + ); + assert_eq!( + census("let _run = |_: fn() -> bool| app.run(c); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled closure whose parameter has a function type" + ); + assert_eq!( + census( + "let run = |f: fn() -> bool, mut c: Command| { c = fallback(); f() }; run(ok, default()); app.run(c); assert!(menu(c).is_some());" + ), + [], + "a parameter after a function type shadows the entry" + ); + assert_eq!( + census("let _ = (|_: ()| app.run(c))(()); assert!(menu(c).is_some());"), + [], + "a closure with parameters called where it is written runs" + ); + assert_eq!( + census("let run = || (); { let run = || { app.run(c); }; } run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a call after the block calls the outer closure" + ); + assert_eq!( + census("let run = || { app.run(c); }; { let run = || (); } run(); assert!(menu(c).is_some());"), + [], + "a call after a nested shadow ends calls the outer closure" + ); + assert_eq!( + census("let _saved = (|| { app.run(c) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a saved parenthesized block closure does not run its call" + ); + } + + #[test] + fn census_follows_writes_in_closures_and_async_blocks() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _pair = (|| (), reset()); app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a call in a sibling tuple element runs the closure it names" + ); + assert_eq!( + census("let mut input = c; let _saved = (|| { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [], + "a saved parenthesized block closure does not run its assignment" + ); + assert_eq!( + census("let mut input = c; let _ = (|| { input = fallback(); })(); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "a parenthesized block closure called in place runs its assignment" + ); + assert_eq!( + census("let run = async |mut c: Command| { c = fallback(); }; run(default()).await; app.run(c); assert!(menu(c).is_some());"), + [], + "an async closure parameter ends with its scope" + ); + assert_eq!( + census("let mut input = c; (async { input = fallback(); }).await; app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an awaited async block has run its assignment" + ); + assert_eq!( + census("let mut input = c; async { input = fallback(); }.await; app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an async block awaited without parentheses has run its assignment" + ); + assert_eq!( + census("let mut input = c; let _ = block_on(async { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an async block passed to block_on has run its assignment" + ); + assert_eq!( + census("let mut input = c; let _ = discard_block_on(async { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [], + "an async block passed to another function does not run its assignment" + ); + assert_eq!( + census("let mut input = c; (async move { input = fallback(); }).await; app.run(input); assert!(menu(c).is_some());"), + [], + "an awaited async move block assigns its own copy" + ); + assert_eq!( + census("let mut input = c; let _f = wrap(async { input = fallback(); }).await; app.run(input); assert!(menu(c).is_some());"), + [], + "an async block passed to a call is not awaited where it is written" + ); + assert_eq!(census("assert!((async { app.run(c) }).await.is_ok());"), [], "an awaited async block runs its call"); + assert_eq!(census("assert!(block_on(async { app.run(c) }).is_ok());"), [], "an async block passed to block_on runs its call"); + assert_eq!( + census("let _ = ready || async { app.run(c); true }.await; assert!(menu(c).is_some());"), + [(2, "census")], + "an || before an awaited async block can skip it" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _saved = || reset(); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a call in a closure that nothing calls does not run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _ = Some(|| reset()); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a call in a closure stored in a constructor does not run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _ = ready || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a call after || may run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; match ready { true => reset(), false => () } app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a call in a match arm may run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _saved = (|| reset()); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a saved parenthesized closure does not run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _ = (|| reset())(); app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a parenthesized closure called in place runs the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _future = async { reset(); }; app.run(input); assert!(menu(c).is_some());" + ), + [], + "an unpolled future does not run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; async { reset(); }.await; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "an async block awaited in place runs the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; (async { reset(); }).await; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a parenthesized async block awaited in place runs the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; async move { reset(); }.await; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "an async move block awaited in place runs the capturing closure" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; (async move { reset(); }).await; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a parenthesized async move block awaited in place runs the capturing closure" + ); + assert_eq!( + census("let input = c; let input = fallback(); { let mut input = fallback(); input = c; app.run(input); } assert!(menu(c).is_some());"), + [], + "an inner binding assigned the entry holds it inside its block" + ); + assert_eq!( + census("let input = c; let input = fallback(); { let mut input = fallback(); input = c; } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "the outer binding holds its own value after the block" + ); + assert_eq!( + census("let mut input = c; let _ = || { input = fallback(); }; app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in a closure dropped with let _ does not end an alias" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; if ready { reset(); } app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "an assignment in a closure that may be called ends an alias" + ); + assert_eq!( + census("let mut input = fallback(); let mut set = || { input = c; }; if ready { set(); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a closure that may be skipped does not make an alias" + ); + } + + #[test] + fn census_keeps_guards_around_nested_arguments() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let _ = ready || accept({ 0 }, wrap(app.run(c))); assert!(menu(c).is_some());"), + [(2, "census")], + "a block in an earlier argument keeps the enclosing || around a nested call" + ); + assert_eq!( + census("let _ = accept({ 0 }, wrap(app.run(c))); assert!(menu(c).is_some());"), + [], + "a block in an earlier argument does not skip a nested call" + ); + assert_eq!( + census("{ { 0 }; prepare(); } let _ = ready || wrap(app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an earlier statement's block does not hide the ||" + ); + } + #[test] fn census_keeps_diagnostics_for_fixed_range_arguments() { for range in ["1..4", "1..=4", "-4..-1", "1..(2 + 2)"] { From e12e9074f1f3b7f06e5fc1f2370df5dcf1619f5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:10:55 -0800 Subject: [PATCH 036/103] Tests: check the point count before checking every point moved MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's test-lint step failed the gate's sixth test shard: the all-unguarded rule flagged reading_and_moving_points_counts_the_subpaths_a_few_times, whose assert!(…all(…)) would also pass on a path with no anchors. The test now asserts the path still has 1000 anchors first. --- crates/engine/src/tests/script_dom_paths.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index f2f148408c..ac8ecc128e 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1669,7 +1669,9 @@ fn reading_and_moving_points_counts_the_subpaths_a_few_times() { let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get); assert!(built < 10, "{built} layouts for 1000 points"); let n = node(&s, id); - assert!(n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).all(|an| an.p.y == 9.0 || an.p.y == 19.0), "every point moved up"); + let ys: Vec = n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).map(|an| an.p.y).collect(); + assert_eq!(ys.len(), 1000); + assert!(ys.iter().all(|&y| y == 9.0 || y == 19.0), "every point moved up"); } /// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the From ae9ad685b274f11a6577798c5bdc5e419b26ba76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:23:08 -0800 Subject: [PATCH 037/103] JavaScript: block functions look up top-level function names in a set Deciding whether a block function gets an Annex B variable compared its name with every top-level function declaration, so a script with N top-level functions and M block functions made N x M comparisons (1,000,000 for 1,000 of each). The names are now gathered into a set once, the first time a block function needs them, and each block function makes one lookup. Hoisting results are unchanged. The scan came in with #9131. --- crates/js/src/compiler.rs | 21 ++++++++++++++++++++- crates/js/src/es2015_tests.rs | 13 +++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index f13677ca52..488823940a 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -33,6 +33,13 @@ use pattern::Mode; /// enough for a 1 MiB stack. pub(crate) const MAX_DEPTH: u32 = 600; +#[cfg(test)] +thread_local! { + /// Tests: the top-level function names that deciding the variables of block functions has + /// gathered or looked up. + pub(crate) static FUN_DECL_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Why code could not be compiled. #[derive(Debug)] pub(crate) enum CompileFail { @@ -409,6 +416,7 @@ impl<'a> FnCompiler<'a> { | Stmt::DefaultXmlNamespace(_) => {} } } + let mut top_names: Option> = None; for (k, scope, id) in annex { let mut cur = Some(scope); let mut clash = params.contains(&k) || *k == *key_of("arguments"); @@ -422,7 +430,18 @@ impl<'a> FnCompiler<'a> { } if !clash { self.annex.insert(id); - if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) { + if seen.contains(&k) { + continue; + } + // The top-level function names, gathered the first time a block function needs them. + let top = top_names.get_or_insert_with(|| { + #[cfg(test)] + FUN_DECL_CHECKS.with(|c| c.set(c.get() + out.fun_decls.len() as u64)); + out.fun_decls.iter().map(|(name, _)| name).collect::>() + }); + #[cfg(test)] + FUN_DECL_CHECKS.with(|c| c.set(c.get() + 1)); + if !top.contains(&k) && annex_seen.insert(k.clone()) { out.annex_vars.push(k); } } diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 1a076c43c1..2071b2063f 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -203,6 +203,19 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); } +#[test] +fn block_function_variables_look_up_each_top_level_function_name_once() { + // 1,000 top-level functions and 1,000 block functions: each block function's variable is + // decided with one lookup in the names gathered once, not by comparing it with every + // top-level function. + let top = (0..1_000).map(|i| format!("function t{i}() {{ return {i}; }}")).collect::(); + let blocks = (0..1_000).map(|i| format!("{{ function b{i}() {{ return {i}; }} }}")).collect::(); + crate::compiler::FUN_DECL_CHECKS.with(|c| c.set(0)); + assert_eq!(run(&format!("{top}{blocks}t999() + b999()")), JsValue::Number(1_998.0)); + let checks = crate::compiler::FUN_DECL_CHECKS.with(std::cell::Cell::get); + assert_eq!(checks, 2_000, "top-level function names gathered and looked up for 1,000 block functions"); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); From f52ff9b4ec62d44542665c921d7aeb12d4f6a39e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:08:07 -0800 Subject: [PATCH 038/103] Docs: gaps.md no longer lists script tracing as missing The Scripts entry said tracing images from scripts was still missing and listed placed and raster images twice. Scripts trace images with `trace()` since #9062 (`crates/engine/src/script/dom/tracing.rs`), as the same entry says a few lines later, so the earlier sentence drops the duplicate and the stale claim. Rasterizing and capturing images stay listed as missing. --- docs/gaps.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index fdf8eb1dcc..f1b74be261 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -861,9 +861,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection, its page items, layers, groups, compound paths and artboards, its text frames with their text ranges and character and paragraph attributes, their links to each other and the stories they form, its character and - paragraph styles, the installed fonts, each document's variables, data sets and variable libraries, and its - linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, - rasterizing and capturing images are still missing. + paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries. `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms. Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a document's `fullName`, `path` and `saved`, and close it with `Document.close`. From dc11714200d5d3c795f22f4af3adf6c53663aec6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:25:37 -0800 Subject: [PATCH 039/103] Scripts: removeAll cannot leave an image first in a group named Image Trace groupItems.removeAll() and compoundPathItems.removeAll() could delete the bottom object of an ordinary group named "Image Trace" and leave an image first in it, which made that group read as a tracing. They now throw "Only Image Trace can make a tracing" before anything is deleted, as move, remove() and zOrder do. The check came in with #9048's collection removeAll. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/layers.rs | 15 +++++-- crates/engine/src/tests/script_dom_tracing.rs | 39 +++++++++++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 4328c1bad2..1e2c7a6123 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -789,10 +789,11 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { /// `removeAll()`: deletes every object the collection lists (those inside another listed one go /// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or /// one on a locked artboard stops it before anything is deleted, as the document's -/// `pageItems.removeAll()` is stopped. +/// `pageItems.removeAll()` is stopped, and so does an image the deletion would leave first in an +/// ordinary group named as a tracing. fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| { let all = art_list(h, st, kind, c)?; let d = &st.doc; let listed: std::collections::HashSet = all.iter().copied().collect(); @@ -817,7 +818,12 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { .map(|i| i.0) .take(20) .collect(); - Ok::<_, HostError>((ids, refused, on_locked, masks)) + // An image left first in an ordinary group named as a tracing would make that group one. + let parents: std::collections::HashSet = ids.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !going.contains(p)).collect(); + let tracing = parents.into_iter().filter(|p| super::named_as_tracing(d, *p)).any(|p| { + d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) + }); + Ok::<_, HostError>((ids, refused, on_locked, masks, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -833,6 +839,9 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" ))); } + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; } diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..ccd9229f72 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -135,6 +135,45 @@ fn added_group_named_as_seam_fills_is_counted() { let _ = std::fs::remove_dir_all(base); } +/// `groupItems.removeAll()` of a group and the document's `compoundPathItems.removeAll()` refuse +/// to leave an image at the bottom of an ordinary group named as a tracing, before the document +/// changes. +#[test] +fn group_and_compound_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let compound = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\ + vc.run('object.compoundPath.make'); return d.pageItems[0]; })()"; + let group = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); return d.pageItems[0]; })()"; + for (name, bottom, list) in + [("group-remove-all-groups", group, "groupItems[0].groupItems"), ("remove-all-compounds", compound, "compoundPathItems")] + { + let base = folder(name); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + &format!( + "var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);" + ), + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(d.pageItems[0].typename);" + ), + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}"); + assert!(traces(&s).is_empty(), "{list}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}"); + assert_eq!(undo_steps(&s), steps, "{list}"); + let _ = std::fs::remove_dir_all(base); + } +} + #[test] fn trace_image_resolution_is_one_number_or_none() { let base = folder("resolution"); diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..5b4d7d914c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3144,7 +3144,8 @@ through `$`: its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with - nothing changed, when they would leave an image at the bottom of such a group. An object of + nothing changed, when they would leave an image at the bottom of such a group, and so do `groupItems.removeAll()` + and `compoundPathItems.removeAll()`. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b5bad4ebc..2bf3353d84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1118,7 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()` or `compoundPathItems.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. From 7803df68bc55e867af8f3f33c5b891db2142f50b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 19:06:57 -0800 Subject: [PATCH 040/103] Print: CUPS_SERVER IPv6 addresses and IPP_PORT reach the right scheduler An IPv6 address named as the CUPS server without brackets (`fd00::cafe`, or `fd00::cafe:8631` with a port) produced an IPP queue URI with the address unbracketed, which ipptool rejects, so a queue with no PPD and no lpoptions sizes listed no paper sizes. ipp_queue_uri now splits the host and port as cupsSetServer does, brackets an IPv6 host and encodes a zone separator as %25. The local PPD check ignored IPP_PORT, so `CUPS_SERVER=localhost` with `IPP_PORT=8631` read this machine's PPDs for another scheduler's queues. A server named without a port now takes the IPP_PORT port before the check. The IPP fallback and the local PPD check came in #10581. --- apps/vectorcraft/src/printing.rs | 19 ++++++++++ crates/ui-egui/src/dialogs/tests_print.rs | 26 ++++++++++++++ crates/ui-egui/src/print.rs | 44 ++++++++++++++++++++--- docs/mcp.md | 6 ++++ 4 files changed, 91 insertions(+), 4 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 4eb39067a0..ea572a64dc 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -252,8 +252,16 @@ mod system { /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. + /// A server named without a port gets the one `IPP_PORT` sets, so `localhost` with `IPP_PORT=8631` is a second + /// scheduler rather than the local one. #[cfg(not(windows))] fn cups_server() -> Option { + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + named_cups_server().map(|server| vectorcraft_ui_egui::print::server_with_ipp_port(&server, port)) + } + /// The scheduler `cups_server` names, as written. + #[cfg(not(windows))] + fn named_cups_server() -> Option { if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) { return Some(server.trim().to_string()); } @@ -652,6 +660,17 @@ mod client_conf_tests { } } + #[test] + fn a_loopback_server_on_another_ipp_port_is_not_local() { + use vectorcraft_ui_egui::print::server_with_ipp_port; + for named in ["localhost", "127.0.0.1", "[::1]", "localhost/version=1.1"] { + assert!(!scheduler_is_local(Some(&server_with_ipp_port(named, Some(8631)))), "{named}"); + assert!(scheduler_is_local(Some(&server_with_ipp_port(named, Some(631)))), "{named}"); + } + assert!(scheduler_is_local(Some(&server_with_ipp_port("localhost:631", Some(8631)))), "a port in the server name wins"); + assert!(scheduler_is_local(Some(&server_with_ipp_port("/run/cups/cups.sock", Some(8631))))); + } + #[test] fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com")); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 35675bda64..1bc5c137d1 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -722,6 +722,32 @@ fn the_ipp_lookup_uses_ipp_port_for_a_server_without_a_port() { assert_eq!(ipp_queue_uri(Some("print.example.com"), ipp_port(Some("x")), "Lab").as_deref(), Some("ipp://print.example.com/printers/Lab")); } +#[test] +fn a_bare_ipv6_server_gets_brackets_in_the_queue_uri() { + use crate::print::ipp_queue_uri; + assert_eq!(ipp_queue_uri(Some("2001:db8::beef"), None, "Lab").as_deref(), Some("ipp://[2001:db8::beef]/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("2001:db8::beef"), Some(8631), "Lab").as_deref(), Some("ipp://[2001:db8::beef]:8631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("fd00::cafe/version=1.1"), None, "Lab").as_deref(), Some("ipp://[fd00::cafe]/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("fd00::cafe:8631"), None, "Lab").as_deref(), Some("ipp://[fd00::cafe]:8631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("fd00::cafe:8631"), Some(631), "Lab").as_deref(), Some("ipp://[fd00::cafe]:8631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("fe80::abcd%eth0"), None, "Lab").as_deref(), Some("ipp://[fe80::abcd%25eth0]/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("print.example.com:8631"), Some(631), "Lab").as_deref(), Some("ipp://print.example.com:8631/printers/Lab")); +} + +#[test] +fn ipp_port_completes_a_server_named_without_a_port() { + use crate::print::server_with_ipp_port; + assert_eq!(server_with_ipp_port("localhost", Some(8631)), "localhost:8631"); + assert_eq!(server_with_ipp_port("localhost/version=1.1", Some(8631)), "localhost:8631/version=1.1"); + assert_eq!(server_with_ipp_port("fd00::cafe", Some(8631)), "[fd00::cafe]:8631"); + assert_eq!(server_with_ipp_port("2001:db8::1", Some(8631)), "2001:db8::1", "CUPS reads a last group of digits as the port"); + assert_eq!(server_with_ipp_port("[::1]", Some(8631)), "[::1]:8631"); + assert_eq!(server_with_ipp_port("localhost:631", Some(8631)), "localhost:631", "a port in the server name wins"); + assert_eq!(server_with_ipp_port("[::1]:631", Some(8631)), "[::1]:631"); + assert_eq!(server_with_ipp_port("/run/cups/cups.sock", Some(8631)), "/run/cups/cups.sock", "a domain socket has no port"); + assert_eq!(server_with_ipp_port("localhost", None), "localhost"); +} + /// What the paper-keyword service was asked to print on: each job's paper. type SentPapers = Rc>>>; diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index c318aa4aa7..6f6bc1ac14 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -252,15 +252,51 @@ pub fn ipp_queue_uri(server: Option<&str>, port: Option, printer: &str) -> name.push_str(&format!("%{b:02X}")); } } - let has_port = match host.strip_prefix('[') { - Some(rest) => rest.split_once(']').is_some_and(|(_, after)| after.starts_with(':')), - None => host.contains(':'), + let (host, suffix) = if host.starts_with('[') { + (host, "") + } else { + host.rsplit_once(':') + .filter(|(_, last)| last.starts_with(|c: char| c.is_ascii_digit())) + .map_or((host, ""), |(name, _)| host.split_at(name.len())) }; + let has_port = + !suffix.is_empty() || host.strip_prefix('[').and_then(|rest| rest.split_once(']')).is_some_and(|(_, after)| after.starts_with(':')); + let host = if !host.starts_with('[') && host.contains(':') { format!("[{host}]") } else { host.to_string() }; + let host = host.replace('%', "%25"); let port = match port { Some(port) if !has_port => format!(":{port}"), _ => String::new(), }; - Some(format!("ipp://{host}{port}/printers/{name}")) + Some(format!("ipp://{host}{suffix}{port}/printers/{name}")) +} + +/// The server CUPS reaches for `server` (`CUPS_SERVER` or a `ServerName`) when `IPP_PORT` gives `port`: a server +/// named without a port of its own gets `port`, before any `/version=` suffix, and a bare IPv6 address gets brackets +/// around it. A domain socket (a path), a server with a port, and any server when `port` is `None` stay as named. +pub fn server_with_ipp_port(server: &str, port: Option) -> String { + let Some(port) = port else { return server.to_string() }; + if server.starts_with('/') { + return server.to_string(); + } + let (host, suffix) = server.find('/').map_or((server, ""), |at| server.split_at(at)); + let host = match host.strip_prefix('[') { + Some(rest) if rest.split_once(']').is_some_and(|(_, after)| after.starts_with(':')) => return server.to_string(), + Some(_) => host.to_string(), + None if is_bare_ipv6(host) => format!("[{host}]"), + None if host.contains(':') || host.is_empty() => return server.to_string(), + None => host.to_string(), + }; + format!("{host}:{port}{suffix}") +} + +/// Whether `host` is an IPv6 address without brackets and without a port. CUPS (`cupsSetServer`) reads the text +/// after the last `:` of an unbracketed server as its port when it starts with a digit, so `::1` and `2001:db8::1` +/// are a host and a port there; an address whose last group starts with a letter (`fd00::cafe`) is the whole host, +/// and a URI needs it in brackets. +fn is_bare_ipv6(host: &str) -> bool { + !host.starts_with('[') + && host.matches(':').count() > 1 + && !host.rsplit_once(':').is_some_and(|(_, last)| last.starts_with(|c: char| c.is_ascii_digit())) } /// The port CUPS clients use for a server named without one, from the value of `IPP_PORT`: `None` when it is unset, diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..41f1556261 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13535,6 +13535,12 @@ server is asked as `localhost` on port 631; another socket path is not asked. In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once. The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available. +A scheduler named without a port is on the port in `IPP_PORT` when it is set. This overrides the "no port or port 631" +rule above: a loopback name without a port counts as local only when `IPP_PORT` is unset or 631. With `localhost` and +`IPP_PORT=8631`, the printer sizes come from that server instead of the local PPD folder. An IPv6 +address named as the server without brackets (`fd00::cafe`) is asked in brackets (`ipp://[fd00::cafe]/printers/`); +as in CUPS, a last group that starts with a digit (`2001:db8::1`) is read as the port, so such an address needs brackets. +Scoped addresses encode the zone separator as `%25`, as in `ipp://[fe80::abcd%25eth0]/printers/`. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} From 0998156ce04b1a9ba12716bf5c01a2c7f7ba5533 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 19:36:41 -0800 Subject: [PATCH 041/103] Print: with no scheduler named, IPP_PORT decides whether local PPDs apply With no CUPS_SERVER or ServerName and no CUPS domain socket, CUPS uses localhost on the IPP_PORT port. The local PPD check treated that case as local on any port, so with IPP_PORT=8631 the Print dialog listed the local PPD's sizes instead of those of the scheduler on 8631. The check now resolves the implicit scheduler the way the IPP lookup does: a CUPS socket is local, and otherwise localhost on IPP_PORT is local only on port 631. --- apps/vectorcraft/src/printing.rs | 32 ++++++++++++++++++++++++++++---- docs/mcp.md | 3 ++- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index ea572a64dc..cbbc5bcd9a 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -179,7 +179,8 @@ mod system { let named = cups_server(); // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, // so its sizes come from the server. - if scheduler_is_local(named.as_deref()) { + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + if named_scheduler_is_local(named.as_deref(), port, |s| std::path::Path::new(s).exists()) { const PPD_CAP: u64 = 16 << 20; let mut bytes = Vec::new(); let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); @@ -198,7 +199,6 @@ mod system { return papers; } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. - let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); let server = ipp_server(named, |s| std::path::Path::new(s).exists()); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; @@ -250,7 +250,8 @@ mod system { } } /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or - /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` + /// `/etc/cups/client.conf`; `None` when none is named, where CUPS uses its domain socket when one exists and + /// `localhost` on `IPP_PORT` otherwise ([`named_scheduler_is_local`] resolves that case). macOS does not read `ServerName` /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. /// A server named without a port gets the one `IPP_PORT` sets, so `localhost` with `IPP_PORT=8631` is a second /// scheduler rather than the local one. @@ -276,6 +277,17 @@ mod system { client_conf_server_name(&text) }) } + /// Whether the scheduler CUPS uses runs on this machine, given the server `cups_server` names, the `IPP_PORT` + /// port and whether a path exists. With no server named, CUPS uses its domain socket when one exists, which is + /// local, and otherwise `localhost` on the `IPP_PORT` port, which is local only on port 631. + #[cfg(not(windows))] + pub(super) fn named_scheduler_is_local(named: Option<&str>, port: Option, exists: impl Fn(&str) -> bool) -> bool { + match named { + Some(server) => scheduler_is_local(Some(server)), + None if CUPS_SOCKETS.iter().any(|s| exists(s)) => true, + None => scheduler_is_local(Some(&vectorcraft_ui_egui::print::server_with_ipp_port("localhost", port))), + } + } /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, /// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback /// name on another port is a second scheduler, whose queues the local PPD folder does not describe. @@ -612,7 +624,19 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, ipp_server, scheduler_is_local}; + use super::system::{client_conf_server_name, ipp_server, named_scheduler_is_local, scheduler_is_local}; + + #[test] + fn with_no_server_named_the_implicit_scheduler_decides_locality() { + let none = |_: &str| false; + let socket = |s: &str| s == "/run/cups/cups.sock"; + assert!(!named_scheduler_is_local(None, Some(8631), none), "localhost:8631 is a second scheduler"); + assert!(named_scheduler_is_local(None, Some(631), none)); + assert!(named_scheduler_is_local(None, None, none)); + assert!(named_scheduler_is_local(None, Some(8631), socket), "CUPS's socket is the local scheduler"); + assert!(!named_scheduler_is_local(Some("print.example.com"), None, socket)); + assert!(named_scheduler_is_local(Some("localhost:631"), Some(8631), none)); + } #[test] fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { diff --git a/docs/mcp.md b/docs/mcp.md index 41f1556261..b44e468579 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13527,7 +13527,8 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, -`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), or when no scheduler is named, CUPS has no domain +socket and `IPP_PORT` sets a port other than 631, lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the From 4bb9f7dc92d8ee0859302dd8d9a7b2b21b7627e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 03:08:31 -0800 Subject: [PATCH 042/103] xtask: test-lint census rule skips writes that cannot run - An async block whose `async` and `move` are separated by a comment or extra spaces is found with `async_block_keyword`. - A write inside an `async move` block to a local the block declares counts as a write; only writes to captures are skipped. - A literal `false` left of `&&` or `true` left of `||` keeps the right side from running, also when the lint asks whether a write may run. `a && true || ...` is not a literal left operand. - A closure passed to `drop` (or `mem::drop`, `std::mem::drop`, `core::mem::drop`) is not called. --- xtask/src/test_lint.rs | 136 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 120 insertions(+), 16 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 1485cfc600..7927f48eaa 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2264,7 +2264,10 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { // Assignments in move closures leave outer bindings unchanged. Assignments in async // blocks that are not awaited, or in closures that nothing calls, do not run; // conditional assignments do not make aliases. - if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || !runs_with_assertion_within(b, from, to, at, &[], true) { + if in_move_closure(b, from, to, at, &name) + || in_async_block(b, from, at, &name) + || !runs_with_assertion_within(b, from, to, at, &[], true) + { continue; } if live(value_start(eq, end), end, &derived, &shadows) { @@ -2559,11 +2562,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let prefix_at = skip_ws(b, head).min(open); let prefix = b[head..open].trim_ascii(); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); - // Where the `async` of an async block starts. - let async_kw = [b"async".as_slice(), b"async move"] - .iter() - .find(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident)) - .map(|kw| prefix_at + prefix.len() - kw.len()); + // Where the `async` of an async block starts, with any whitespace before `move`. + let async_kw = async_block_keyword(b, prefix_at, open).map(|(kw, _)| kw); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; @@ -2675,11 +2675,12 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>') { break; } - if !may_run - && b[i] == b'&' + if b[i] == b'&' && b[i - 1] == b'&' - && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) - && !asserted_conjunction(b, from, to, i - 1) + && ((!may_run + && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + && !asserted_conjunction(b, from, to, i - 1)) + || (may_run && literal_operand(b, stmt, i - 1, b"false"))) { return false; } @@ -2692,7 +2693,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac && !asynchronous && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) { - if may_run { + // A literal `true` always skips the right side; any other operand may let it run. + if may_run && !literal_operand(b, stmt, i - 1, b"true") { continue; } return false; @@ -2712,7 +2714,10 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| h.starts_with(char::is_whitespace)) else { // Other callees may invoke or retain a callback, but an unused constructor only stores it. - let may_call = may_run && !asynchronous && closure_body_end(b, end, to).is_some_and(|close| !stored_closure(b, bare, close, to)); + let may_call = may_run + && !asynchronous + && !discarding_call(bare) + && closure_body_end(b, end, to).is_some_and(|close| !stored_closure(b, bare, close, to)); // `(|| app.run(c))()` calls the closure where it is written. let open = stmt + bare.len(); let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return may_call }; @@ -2882,10 +2887,51 @@ fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: /// Whether `start` lies in the body of an `async move` block, which writes to its own copies of the /// captures, or of an `async` block that is not polled where it is written ([`polled_in_place`]). -fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { - (from..start) - .filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) - .any(|open| async_block_keyword(b, from, open).is_some_and(|(kw, moved)| moved || !polled_in_place(b, from, kw, open))) +/// A write to `name` that a `let` in the block before `start` declares is a write to the block's own +/// local, not to a capture. +fn in_async_block(b: &[u8], from: usize, start: usize, name: &str) -> bool { + (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { + async_block_keyword(b, from, open) + .is_some_and(|(kw, moved)| (moved && !declared_in(b, open + 1, start, name)) || !polled_in_place(b, from, kw, open)) + }) +} + +/// Whether a `let` in `b[body..start]` whose scope reaches `start` binds `name`. +fn declared_in(b: &[u8], body: usize, start: usize, name: &str) -> bool { + words(b, b"let", body, start).into_iter().any(|l| { + block_close(b, l) > start + && (l + 3..start) + .find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + .is_some_and(|eq| pattern_names(&String::from_utf8_lossy(&b[l + 3..eq])).any(|n| n == name)) + }) +} + +/// Whether the left operand of the `&&` or `||` at `op` in the statement starting at `stmt` is the +/// literal `lit` (`false && …`, `true || …`), which decides the operator without its right side. +fn literal_operand(b: &[u8], stmt: usize, op: usize, lit: &[u8]) -> bool { + let left = b[stmt..op].trim_ascii_end(); + let Some(rest) = left.strip_suffix(lit) else { return false }; + if rest.last().copied().is_some_and(is_ident) { + return false; + } + let rest = rest.trim_ascii_end(); + match rest.last() { + None | Some(b'(' | b'{' | b',' | b';') => true, + Some(b'=') => !matches!(rest.get(rest.len().wrapping_sub(2)), Some(b'=' | b'!' | b'<' | b'>')), + // `a && true || …` has `a && true` as its left operand, while `a && false && …` is still false. + Some(b'&') => lit == b"false" && rest.ends_with(b"&&"), + Some(b'|') => rest.ends_with(b"||"), + _ => false, + } +} + +/// Whether `head`, the text before a closure's parameters, ends with a call to `drop`, which +/// discards the closure without calling it. A bare `drop` is the prelude's, as in [`value_kept`]. +fn discarding_call(head: &str) -> bool { + head.strip_suffix('(').map(str::trim_end).is_some_and(|callee| { + let path_len = callee.bytes().rev().take_while(|&c| is_ident(c) || c == b':').count(); + matches!(&callee[callee.len() - path_len..], "drop" | "mem::drop" | "std::mem::drop" | "core::mem::drop") + }) } /// The position of `async` before the block at `open`, and whether it captures by move. @@ -10797,6 +10843,64 @@ mod tests { ); } + #[test] + fn census_skips_writes_that_cannot_run_and_async_block_locals() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let _future = async /* deferred */ move { app.run(c); }; assert!(menu(c).is_some());"), + [(2, "census")], + "a comment between async and move still marks an unpolled async block" + ); + assert_eq!( + census("block_on(async move { let mut input = fallback(); input = c; app.run(input); }); assert!(menu(c).is_some());"), + [], + "a write to a local declared inside an async move block makes an alias" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; false && { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [], + "a literal false left of && never runs the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; true || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [], + "a literal true left of || never runs the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; ready && { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "an unknown left operand of && may run the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; std::mem::drop(|| reset()); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a closure passed to drop is never called" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; on_change(|| reset()); app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a closure passed to another callee may be called" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; ready && true || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a literal true after && is not the whole left operand of ||" + ); + } + #[test] fn census_keeps_guards_around_nested_arguments() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); From 9d7d310e839690f7fddb2fd5515ef9f95caf922b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 03:31:08 -0800 Subject: [PATCH 043/103] Save: a checked save opens an existing file without creating one When the rename is refused, a checked save on Unix copied the new content into the existing file, opened with `O_CREAT` after a separate check that the file was there. A file removed between the check and the open was created again before the final check of the folder, so a folder moved out of the write root could be left holding an empty file. The existing file is now opened without `O_CREAT`; a missing one is created only after the final check, as before. The open is non-blocking and only a regular file is written, so a FIFO at the name fails at once. The rule that Linux's `fs.protected_regular` applied to the `O_CREAT` open is kept: in a sticky folder that the group or others can write to, a file owned by neither this user nor the folder's owner is refused. --- crates/format/Cargo.toml | 2 +- crates/format/src/atomic.rs | 121 ++++++++++++++++++++++++++++++++++-- 2 files changed, 116 insertions(+), 7 deletions(-) diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index e020dda9c3..f48032c020 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -22,7 +22,7 @@ flate2 = { workspace = true } # file's access ACL on Linux (`keep_permissions`). Already in Cargo.lock (tempfile), so this adds # no new crate. [target.'cfg(unix)'.dependencies] -rustix = { workspace = true, features = ["std", "fs"] } +rustix = { workspace = true, features = ["std", "fs", "process"] } [dev-dependencies] vectorcraft-testkit = { workspace = true } diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index dd0cd4cc6c..39e14aa08c 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -153,13 +153,19 @@ pub fn write_atomic_checked( flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) }; let open_target = |write: bool| -> io::Result { - // A missing target is created by `create_target`, after the last check. An existing one is - // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. - if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) { - return Err(io::ErrorKind::NotFound.into()); + // Opened without `O_CREAT`: a missing target, one removed meanwhile included, is created + // only by `create_target`, after the last check. + #[cfg(test)] + if write && let Some(hook) = BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()) { + hook(); } - let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; - Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) + // `O_NONBLOCK`: a FIFO at the name fails the regular-file check instead of waiting for a reader. + let flags = if write { OFlags::WRONLY | OFlags::NONBLOCK } else { OFlags::RDONLY }; + let file = File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?); + if write { + protected_regular(&dir, &file)?; + } + Ok(file) }; let create_target = || -> io::Result { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) }; match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { @@ -265,6 +271,31 @@ pub fn write_atomic_checked( } } +/// The target [`write_atomic_checked`] opened without `O_CREAT`, checked as Linux's strictest +/// `fs.protected_regular` checks an `O_CREAT` open of an existing file: anything but a regular +/// file is refused, and so is a file in a sticky folder that others or the group can write to +/// when neither this process nor the folder's owner owns it. +#[cfg(unix)] +fn protected_regular(dir: &std::os::fd::OwnedFd, file: &File) -> io::Result<()> { + let (folder, opened) = (rustix::fs::fstat(dir)?, rustix::fs::fstat(file)?); + if rustix::fs::FileType::from_raw_mode(opened.st_mode) != rustix::fs::FileType::RegularFile { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")); + } + if refused_in_sticky_folder(rustix::fs::Mode::from_raw_mode(folder.st_mode), folder.st_uid, opened.st_uid, rustix::process::geteuid().as_raw()) { + return Err(io::ErrorKind::PermissionDenied.into()); + } + Ok(()) +} + +/// Whether a file owned by `owner` in a folder with mode `folder_mode` owned by `folder_owner` is +/// refused to the user `me`: the folder is sticky, others or the group can write to it, and +/// neither `me` nor `folder_owner` owns the file. +#[cfg(unix)] +fn refused_in_sticky_folder(folder_mode: rustix::fs::Mode, folder_owner: u32, owner: u32, me: u32) -> bool { + use rustix::fs::Mode; + folder_mode.contains(Mode::SVTX) && folder_mode.intersects(Mode::WGRP | Mode::WOTH) && owner != me && owner != folder_owner +} + /// See the Unix version. #[cfg(not(unix))] pub fn write_atomic_checked( @@ -767,6 +798,9 @@ thread_local! { /// Tests: [`write_atomic_checked`]'s folder refuses the rename. #[cfg(unix)] static RENAME_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: run once right before [`write_atomic_checked`] opens its target for writing. + #[cfg(unix)] + static BEFORE_TARGET_OPEN: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// A symbolic link keeps pointing at its file: write the file it names. @@ -1246,6 +1280,81 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A target removed after the write starts is not created again before the last check: when its + /// folder has moved outside by then, nothing is left there. + #[cfg(unix)] + #[test] + fn a_checked_write_creates_no_target_removed_while_it_is_opened() { + let (d, root, outside) = checked_folders("checked-removed-target"); + let path = root.join("inside/doc.txt"); + std::fs::write(&path, b"old").unwrap(); + let (inside, moved) = (root.join("inside"), outside.join("inside")); + let (from, to) = (inside.clone(), moved.clone()); + BEFORE_TARGET_OPEN.with(|h| { + *h.borrow_mut() = Some(Box::new(move || { + std::fs::remove_file(from.join("doc.txt")).unwrap(); + std::fs::rename(&from, &to).unwrap(); + })) + }); + RENAME_REFUSED.with(|c| c.set(true)); + let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()); + assert!(r.is_err(), "{r:?}"); + assert!(!moved.join("doc.txt").exists(), "the removed target was created again"); + assert!(!inside.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// An existing regular file this process owns passes the check. + #[cfg(unix)] + #[test] + fn protected_regular_allows_a_file_this_process_owns() { + let d = std::fs::canonicalize(dir("protected-regular")).unwrap(); + std::fs::write(d.join("doc.txt"), b"old").unwrap(); + let folder: std::os::fd::OwnedFd = File::open(&d).unwrap().into(); + let file = OpenOptions::new().write(true).open(d.join("doc.txt")).unwrap(); + protected_regular(&folder, &file).unwrap(); + let _ = std::fs::remove_dir_all(d); + } + + /// A FIFO at the name is not written into when the rename is refused: without a reader the + /// write fails at once instead of waiting for one (without `O_NONBLOCK` this test does not + /// return), and with a reader nothing reaches it. + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_does_not_write_into_a_fifo_at_its_name() { + use rustix::fs::{Mode, OFlags}; + use std::io::Read as _; + let (d, root, _) = checked_folders("checked-fifo"); + let path = root.join("inside/doc.txt"); + rustix::fs::mknodat(rustix::fs::CWD, &path, rustix::fs::FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap(); + RENAME_REFUSED.with(|c| c.set(true)); + let alone = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + let reader = File::from(rustix::fs::open(&path, OFlags::RDONLY | OFlags::NONBLOCK, Mode::empty()).unwrap()); + let read = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + assert!(alone.is_err() && read.is_err(), "{alone:?} {read:?}"); + let mut got = [0u8; 8]; + assert!((&reader).read(&mut got).map_or(true, |n| n == 0), "nothing is written into the FIFO"); + let _ = std::fs::remove_dir_all(d); + } + + /// A file in a sticky folder that others or the group can write to is refused when neither this + /// user nor the folder's owner owns it. + #[cfg(unix)] + #[test] + fn a_file_owned_by_someone_else_in_a_shared_sticky_folder_is_refused() { + let (me, folder_owner, other) = (1000, 0, 2000); + let mode = rustix::fs::Mode::from_raw_mode; + assert!(refused_in_sticky_folder(mode(0o1777), folder_owner, other, me)); + assert!(refused_in_sticky_folder(mode(0o1770), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o1755), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o0777), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, me, me)); + assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, folder_owner, me)); + } + /// A file created by another writer at the final check is preserved whether that check succeeds or fails. #[cfg(unix)] #[test] From cfebc3e61b65fbb15826d75afea1322597062b91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 04:08:03 -0800 Subject: [PATCH 044/103] xtask: test-lint census rule follows early exits and captured writes A polled async block, a called closure or a nested for body can be left before the call: a return or ? leaves a closure or async block, and a break or continue leaves a nested for body. The census exemption no longer counts a call after such an exit. Exits inside a nested closure, async block or inner loop leave only that one, and a closure with a return type is recognized as nested. A write to a capture inside an async move block or a move closure now changes the block's own copy until the block ends, instead of being skipped. A later call in the block that receives the replaced value no longer counts as feeding the entry, while the outer binding keeps it. --- xtask/src/test_lint.rs | 184 +++++++++++++++++++++++++++++++++-------- 1 file changed, 148 insertions(+), 36 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 7927f48eaa..50c4187406 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2261,15 +2261,15 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { ) .max_by_key(|&(since, _)| since) .map_or(to, |(_, until)| until); - // Assignments in move closures leave outer bindings unchanged. Assignments in async - // blocks that are not awaited, or in closures that nothing calls, do not run; - // conditional assignments do not make aliases. - if in_move_closure(b, from, to, at, &name) - || in_async_block(b, from, at, &name) - || !runs_with_assertion_within(b, from, to, at, &[], true) - { + // Assignments in async blocks that are not awaited, or in closures that nothing calls, + // do not run; conditional assignments do not make aliases. + if in_async_block(b, from, at) || !runs_with_assertion_within(b, from, to, at, &[], true) { continue; } + // Assignments to a capture in a move closure or an `async move` block change the + // block's own copy, so they end at the block and leave the outer binding unchanged. + let until = + move_closure_copy_end(b, from, to, at, &name).into_iter().chain(async_move_copy_end(b, from, at, &name)).fold(until, usize::min); if live(value_start(eq, end), end, &derived, &shadows) { if !runs_with_assertion(b, from, to, at) { continue; @@ -2564,26 +2564,30 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); // Where the `async` of an async block starts, with any whitespace before `move`. let async_kw = async_block_keyword(b, prefix_at, open).map(|(kw, _)| kw); + // A closure body, an async block or a nested `for` body can be left before the call + // (`block_on(async { if skip { return; } app.run(c); })`) while the loop's assertions still run. + let left_early = !may_run && (async_kw.is_some() || nested_for || closure_params_head(prefix)) && exits_before(b, open, start, nested_for); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { - if !runs_with_assertion_within(b, from, to, open, &active, may_run) { + if left_early || !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; } - } else if nested_for && !literal_source_yields(prefix).unwrap_or(may_run) { + } else if nested_for && (left_early || !literal_source_yields(prefix).unwrap_or(may_run)) { // A nested `for` body runs only when its source yields an item. return false; } else if let Some(kw) = async_kw { // An async block needs polling where it is written, by await or block_on. let polled = polled_in_place(b, from, kw, open); - if !polled || !runs_with_assertion_within(b, from, to, kw, &active, may_run) { + if !polled || left_early || !runs_with_assertion_within(b, from, to, kw, &active, may_run) { return false; } - } else if !may_run - && !prefix.ends_with(b"|") - && !nested_for - && (prefix.ends_with(b"=>") - || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) - || (!words(prefix, b"loop", 0, prefix.len()).is_empty() - && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) + } else if left_early + || (!may_run + && !prefix.ends_with(b"|") + && !nested_for + && (prefix.ends_with(b"=>") + || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) + || (!words(prefix, b"loop", 0, prefix.len()).is_empty() + && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty())))) { // A nested `for` body whose source yields an item runs, like the loop body itself; // [`feeds_entry`] keeps its own bindings apart. @@ -2885,15 +2889,65 @@ fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: b.get(open) == Some(&b'(') && matching(b, open) == close.checked_sub(1) && required_conjunction(b, open, close, at, depth + 1) } -/// Whether `start` lies in the body of an `async move` block, which writes to its own copies of the -/// captures, or of an `async` block that is not polled where it is written ([`polled_in_place`]). -/// A write to `name` that a `let` in the block before `start` declares is a write to the block's own -/// local, not to a capture. -fn in_async_block(b: &[u8], from: usize, start: usize, name: &str) -> bool { - (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { - async_block_keyword(b, from, open) - .is_some_and(|(kw, moved)| (moved && !declared_in(b, open + 1, start, name)) || !polled_in_place(b, from, kw, open)) - }) +/// Whether `start` lies in the body of an `async` block that is not polled where it is written +/// ([`polled_in_place`]). +fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { + (from..start) + .filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) + .any(|open| async_block_keyword(b, from, open).is_some_and(|(kw, _)| !polled_in_place(b, from, kw, open))) +} + +/// The close of the innermost `async move` block around `start` that captures `name`: a write to +/// `name` there changes the block's own copy, which ends with the block. A write to `name` that a +/// `let` in the block before `start` declares is a write to the block's own local, not to a capture. +fn async_move_copy_end(b: &[u8], from: usize, start: usize, name: &str) -> Option { + (from..start) + .rev() + .filter(|&i| b[i] == b'{') + .filter_map(|open| matching(b, open).filter(|&close| start < close).map(|close| (open, close))) + .find(|&(open, _)| async_block_keyword(b, from, open).is_some_and(|(_, moved)| moved && !declared_in(b, open + 1, start, name))) + .map(|(_, close)| close) +} + +/// Whether `head`, the text of a statement before a `{`, ends with a closure's parameter list +/// (`let run = ||`, `move |c: Command|`), not with a logical OR (`ready ||`). +fn closure_params_head(head: &[u8]) -> bool { + // A return type follows the parameters (`|| -> bool`, `|c: Command| -> Result<(), E>`). + let head = match head.iter().rposition(|&c| c == b'|') { + Some(p) if head[p + 1..].trim_ascii_start().starts_with(b"->") => &head[..=p], + _ => head, + }; + let Some(rest) = head.strip_suffix(b"||") else { + return head.ends_with(b"|"); + }; + let rest = rest.trim_ascii_end(); + rest.is_empty() + || matches!(rest.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"async"].iter().any(|kw| rest.strip_suffix(*kw).is_some_and(|h| !h.last().copied().is_some_and(is_ident))) +} + +/// Whether the block opening at `open` can be left before `start`: a closure body or async block by +/// a `return` or a `?`, and a loop body (`loop_body`) by a `break` or a `continue` (a `return` or `?` +/// there leaves the test, and the assertions with it). An exit inside a nested closure or async +/// block leaves only that one, and a `break` or `continue` inside a nested loop leaves only that loop. +fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool) -> bool { + let nested = |at: usize, loops: bool| { + (open + 1..at).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).any(|inner| { + let stmt = (open + 1..inner).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); + let head = b[stmt..inner].trim_ascii(); + closure_params_head(head) + || async_block_keyword(b, stmt, inner).is_some() + || (loops + && [b"for".as_slice(), b"while", b"loop"] + .iter() + .any(|kw| head.starts_with(kw) && !head.get(kw.len()).copied().is_some_and(is_ident))) + }) + }; + let returns = words(b, b"return", open + 1, start).into_iter().any(|at| !nested(at, false)); + let tries = (open + 2..start).any(|i| b[i] == b'?' && (is_ident(b[i - 1]) || matches!(b[i - 1], b')' | b']')) && !nested(i, false)); + let loops = + loop_body && [b"break".as_slice(), b"continue"].iter().any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true))); + if loop_body { loops } else { returns || tries } } /// Whether a `let` in `b[body..start]` whose scope reaches `start` binds `name`. @@ -2963,15 +3017,13 @@ fn polled_in_place(b: &[u8], from: usize, kw: usize, open: usize) -> bool { (b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident)) || passed_to_block_on(b, start, close + 1) } -/// Whether `start` lies in the block or expression body of a move closure that captures `name`: -/// neither the closure's parameters nor a `let` in its body before `start` binds `name`. -fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) -> bool { - words(b, b"move", from, start).into_iter().any(|at| { - let pipe = skip_ws(b, at + 4); - if b.get(pipe) != Some(&b'|') { - return false; - } - let Some(end) = (pipe + 1..to).find(|&i| b[i] == b'|') else { return false }; +/// Where the body of the innermost move closure around `start` that captures `name` ends: neither +/// the closure's parameters nor a `let` in its body before `start` binds `name`. A write to `name` +/// there changes the closure's own copy, which ends with the body. +fn move_closure_copy_end(b: &[u8], from: usize, to: usize, start: usize, name: &str) -> Option { + words(b, b"move", from, start).into_iter().rev().find_map(|at| { + let pipe = Some(skip_ws(b, at + 4)).filter(|&pipe| b.get(pipe) == Some(&b'|'))?; + let end = (pipe + 1..to).find(|&i| b[i] == b'|')?; let body = skip_ws(b, end + 1); let mut until = body; if b.get(body) == Some(&b'{') { @@ -2990,7 +3042,7 @@ fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) - .find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) .is_some_and(|eq| binds(&b[l + 3..eq])) }); - inside && !binds(&b[pipe + 1..end]) && !local + (inside && !binds(&b[pipe + 1..end]) && !local).then_some(until) }) } @@ -10857,6 +10909,66 @@ mod tests { [], "a write to a local declared inside an async move block makes an alias" ); + assert_eq!( + census("block_on(async { if skip { return; } app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return before the call leaves a polled async block without running it" + ); + assert_eq!( + census("block_on(async { prepare()?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? before the call can leave a polled async block" + ); + assert_eq!( + census("block_on(async { let _f = || { return; }; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a nested closure does not leave the polled async block" + ); + assert_eq!( + census("let run = || { if skip { return; } app.run(c); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a return before the call leaves a called closure without running it" + ); + assert_eq!( + census("for _ in [1] { if skip { continue; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue before the call skips it in a nested for body" + ); + assert_eq!( + census("for _ in [1] { for _ in [2] { break; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a break in an inner loop does not leave the nested for body" + ); + assert_eq!( + census("for _ in [1] { prepare()?; app.run(c); } assert!(menu(c).is_some());"), + [], + "a ? in a nested for body fails the test instead of skipping the call" + ); + assert_eq!( + census("block_on(async { let _ready = || -> bool { return true; }; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a nested closure with a return type does not leave the async block" + ); + assert_eq!( + census("let mut input = c; block_on(async move { input = fallback(); render(input, offset); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a write to a capture in an async move block replaces the entry inside the block" + ); + assert_eq!( + census("let mut input = c; let run = move || { input = fallback(); render(input, offset); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a write to a capture in a move closure replaces the entry inside the closure" + ); + assert_eq!( + census("let input = c; block_on(async move { render(input, offset); }); assert!(menu(c).is_some());"), + [], + "an async move block that renders the captured entry feeds it" + ); + assert_eq!( + census("let mut input = c; block_on(async move { input = fallback(); }); render(input, offset); assert!(menu(c).is_some());"), + [], + "the outer binding keeps the entry after an async move block writes its copy" + ); assert_eq!( census( "let mut input = c; let mut reset = || { input = fallback(); }; false && { reset(); true }; app.run(input); assert!(menu(c).is_some());" From 45388081a86c1adc60bb084167631e7c6aaede30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 04:40:25 -0800 Subject: [PATCH 045/103] xtask: test-lint census exits ignore closure bodies and return operands When the census rule asks whether a write can run at all, a return statement directly before it in the closure or async block now rules it out, while a return inside a condition still leaves it possibly executed. A return or ? in an expression-bodied closure (`let _f = || return;`) leaves only that closure, not the enclosing async block. The operand of a return (`return app.run(c);`) runs before the return, and a call after a bare return in a tuple element does not. A ? after whitespace or a comment (`prepare() ?;`) is still an exit. --- xtask/src/test_lint.rs | 121 +++++++++++++++++++++++++++++++++++------ 1 file changed, 105 insertions(+), 16 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 50c4187406..1cc0760571 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2566,7 +2566,9 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let async_kw = async_block_keyword(b, prefix_at, open).map(|(kw, _)| kw); // A closure body, an async block or a nested `for` body can be left before the call // (`block_on(async { if skip { return; } app.run(c); })`) while the loop's assertions still run. - let left_early = !may_run && (async_kw.is_some() || nested_for || closure_params_head(prefix)) && exits_before(b, open, start, nested_for); + // When `may_run` asks whether the call can run at all, only an exit that always runs first + // (`|| { return; input = fallback(); }`) rules it out. + let left_early = (async_kw.is_some() || nested_for || closure_params_head(prefix)) && exits_before(b, open, start, nested_for, may_run); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if left_early || !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; @@ -2930,23 +2932,63 @@ fn closure_params_head(head: &[u8]) -> bool { /// a `return` or a `?`, and a loop body (`loop_body`) by a `break` or a `continue` (a `return` or `?` /// there leaves the test, and the assertions with it). An exit inside a nested closure or async /// block leaves only that one, and a `break` or `continue` inside a nested loop leaves only that loop. -fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool) -> bool { - let nested = |at: usize, loops: bool| { - (open + 1..at).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).any(|inner| { - let stmt = (open + 1..inner).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); - let head = b[stmt..inner].trim_ascii(); - closure_params_head(head) - || async_block_keyword(b, stmt, inner).is_some() - || (loops - && [b"for".as_slice(), b"while", b"loop"] - .iter() - .any(|kw| head.starts_with(kw) && !head.get(kw.len()).copied().is_some_and(is_ident))) +/// A `return` whose operand holds `start` (`return app.run(c);`) runs the call first. With `definite`, +/// only an exit that always runs counts: a `return`, `break` or `continue` statement directly in the +/// block, not one in a nested block and not a `?`. +fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: bool) -> bool { + // The innermost block in `b[open..]` that encloses `at`. + let innermost = |at: usize| (open..at).rev().find(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).unwrap_or(open); + // Whether `b[from..to]` stays inside one expression: no `;` or `,` and no unmatched closing + // bracket outside nested brackets. + let one_expression = |from: usize, to: usize| { + let mut depth = 0usize; + b[from..to].iter().all(|&c| match c { + b'(' | b'[' | b'{' => { + depth += 1; + true + } + b')' | b']' | b'}' => depth.checked_sub(1).map(|d| depth = d).is_some(), + b';' | b',' => depth > 0, + _ => true, }) }; - let returns = words(b, b"return", open + 1, start).into_iter().any(|at| !nested(at, false)); - let tries = (open + 2..start).any(|i| b[i] == b'?' && (is_ident(b[i - 1]) || matches!(b[i - 1], b')' | b']')) && !nested(i, false)); - let loops = - loop_body && [b"break".as_slice(), b"continue"].iter().any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true))); + // An expression-bodied closure (`|| return`, `|x| x?`) whose body holds `at`. The pipe at `p` + // ends the parameter list, so the `||` of `skip || return` is read as a whole. + let in_expression_closure = |at: usize| { + let stmt = (open + 1..at).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); + (stmt..at).any(|p| b[p] == b'|' && b[p + 1] != b'|' && closure_params_head(b[stmt..=p].trim_ascii()) && one_expression(p + 1, at)) + }; + let nested = |at: usize, loops: bool| { + (!loops && in_expression_closure(at)) + || (open + 1..at).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).any(|inner| { + let stmt = (open + 1..inner).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); + let head = b[stmt..inner].trim_ascii(); + closure_params_head(head) + || async_block_keyword(b, stmt, inner).is_some() + || (loops + && [b"for".as_slice(), b"while", b"loop"] + .iter() + .any(|kw| head.starts_with(kw) && !head.get(kw.len()).copied().is_some_and(is_ident))) + }) + }; + // A statement that starts at `at` directly in the block, and ends before `start`. + let always = |at: usize| { + innermost(at) == open + && b[open + 1..at].trim_ascii_end().last().is_none_or(|c| matches!(c, b';' | b'{' | b'}')) + && matching(b, open).is_some_and(|close| statement_end(&b[..close], at) < start) + }; + let returns = + words(b, b"return", open + 1, start).into_iter().any(|at| !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); + let tries = !definite + && (open + 2..start).any(|i| { + b[i] == b'?' + && (open + 1..i).rev().find(|&p| !b[p].is_ascii_whitespace()).is_some_and(|p| is_ident(b[p]) || matches!(b[p], b')' | b']')) + && !nested(i, false) + }); + let loops = loop_body + && [b"break".as_slice(), b"continue"] + .iter() + .any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true) && (!definite || always(at)))); if loop_body { loops } else { returns || tries } } @@ -10949,6 +10991,53 @@ mod tests { [], "a return in a nested closure with a return type does not leave the async block" ); + assert_eq!( + census("let mut input = c; let mut reset = || { return; input = fallback(); }; reset(); app.run(input); assert!(menu(c).is_some());"), + [], + "a write after a return statement in a called closure never runs" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { if skip { return; } input = fallback(); }; reset(); app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a write after a conditional return in a called closure may run" + ); + assert_eq!( + census("block_on(async { let _f = || return; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a nested expression-bodied closure does not leave the async block" + ); + assert_eq!( + census("block_on(async { return app.run(c); }); assert!(menu(c).is_some());"), + [], + "the operand of a return runs before the return" + ); + assert_eq!( + census("block_on(async { let _ = (return, app.run(c)); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a call after a bare return in a tuple is not its operand" + ); + assert_eq!( + census("block_on(async { let _ = skip || return; app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return after a logical or is not in a closure" + ); + assert_eq!( + census("block_on(async { let _ = (|| 1, return); app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return after a closure in an earlier tuple element is not in that closure" + ); + assert_eq!( + census("block_on(async { prepare() /* why */ ?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? after a comment can leave a polled async block" + ); + assert_eq!( + census("block_on(async { prepare() ?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? after whitespace can leave a polled async block" + ); assert_eq!( census("let mut input = c; block_on(async move { input = fallback(); render(input, offset); }); assert!(menu(c).is_some());"), [(2, "census")], From 0613c48c50874c71b6b1b86d4cd214689703d0b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 05:07:36 -0800 Subject: [PATCH 046/103] xtask: test-lint census exits read match alternatives and skip stringify! A single pipe now ends a closure's parameter list only when an opening pipe stands in a closure position, so the `|` of a match arm such as `0 | 1 => return` no longer hides that return from the census rule. A closure that a match arm yields (`_ => |_: ()| return`) still keeps its return to itself. A `?` inside the arguments of `stringify!` is not evaluated and no longer counts as an exit from the enclosing async block. --- xtask/src/test_lint.rs | 48 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 7 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 1cc0760571..c372e4c971 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2919,13 +2919,16 @@ fn closure_params_head(head: &[u8]) -> bool { Some(p) if head[p + 1..].trim_ascii_start().starts_with(b"->") => &head[..=p], _ => head, }; - let Some(rest) = head.strip_suffix(b"||") else { - return head.ends_with(b"|"); - }; - let rest = rest.trim_ascii_end(); - rest.is_empty() - || matches!(rest.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) - || [b"move".as_slice(), b"async"].iter().any(|kw| rest.strip_suffix(*kw).is_some_and(|h| !h.last().copied().is_some_and(is_ident))) + // A single closing pipe needs its opening pipe in a closure position: `0 | 1` in a match arm and + // `a | b` are not parameter lists. + let rest = + head.strip_suffix(b"||").or_else(|| head.strip_suffix(b"|").and_then(|params| params.iter().rposition(|&c| c == b'|').map(|o| ¶ms[..o]))); + rest.map(<[u8]>::trim_ascii_end).is_some_and(|rest| { + rest.is_empty() + || matches!(rest.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) + || rest.ends_with(b"=>") + || [b"move".as_slice(), b"async"].iter().any(|kw| rest.strip_suffix(*kw).is_some_and(|h| !h.last().copied().is_some_and(is_ident))) + }) } /// Whether the block opening at `open` can be left before `start`: a closure body or async block by @@ -2979,9 +2982,19 @@ fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: }; let returns = words(b, b"return", open + 1, start).into_iter().any(|at| !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); + // The arguments of `stringify!` are not evaluated. + let unevaluated: Vec<(usize, usize)> = calls_at(b, open + 1, start) + .iter() + .filter(|(_, name, _)| name == "stringify!") + .filter_map(|(p, name, _)| { + let o = skip_ws(b, p + name.len()); + matching(b, o).map(|c| (o, c)) + }) + .collect(); let tries = !definite && (open + 2..start).any(|i| { b[i] == b'?' + && !unevaluated.iter().any(|&(o, c)| o < i && i < c) && (open + 1..i).rev().find(|&p| !b[p].is_ascii_whitespace()).is_some_and(|p| is_ident(b[p]) || matches!(b[p], b')' | b']')) && !nested(i, false) }); @@ -11102,6 +11115,27 @@ mod tests { ); } + #[test] + fn census_exits_count_match_alternatives_and_skip_stringify() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("block_on(async { match mode { 0 | 1 => return, _ => {} } app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return in a match arm with alternatives can leave a polled async block" + ); + assert_eq!( + census("block_on(async { let _f = match mode { _ => |_: ()| return }; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a closure that a match arm yields leaves only that closure" + ); + assert_eq!( + census("block_on(async { let _ = stringify!(prepare() ?); app.run(c); }); assert!(menu(c).is_some());"), + [], + "a ? inside stringify! is not evaluated" + ); + } + #[test] fn census_keeps_guards_around_nested_arguments() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); From 6ec484819a0ed892ef051e2937a784072ca4dd53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:08:23 -0800 Subject: [PATCH 047/103] xtask: test-lint census guards apply only to the operand they control - An `&&` left of an `||` alternative belongs to the `||`'s left operand, so `false && ready || { reset(); true }` now counts the reset. A group that holds the alternative (`false && (a || b)`) is still guarded by the outer `&&`. - A `?` after a block expression (`{ prepare() }?`) can leave a polled async block. A block that is the body of an expression closure (`|| { ... }?`) leaves only that closure. - `return`, `break` and `continue` inside `stringify!` are not evaluated, and a call inside `stringify!` does not feed the entry. --- xtask/src/test_lint.rs | 93 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 86 insertions(+), 7 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index c372e4c971..e4c8ecde36 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2353,13 +2353,27 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let numeric = numeric && operands > 0; s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None") }; + // The arguments of `stringify!` are not evaluated, so a call there does not run. + let unevaluated: Vec<(usize, usize)> = calls_at(b, from, to) + .iter() + .filter(|(_, name, _)| name == "stringify!") + .filter_map(|(p, name, _)| { + let o = skip_ws(b, p + name.len()); + matching(b, o).map(|c| (o, c)) + }) + .collect(); (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { let mut start = name_end; while start > from && is_ident(b[start - 1]) { start -= 1; } let name = String::from_utf8_lossy(&b[start..name_end]); - if start == name_end || LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() || !runs_with_assertion(b, from, to, start) { + if start == name_end + || LOOKUPS.contains(&name.as_ref()) + || b[start].is_ascii_digit() + || unevaluated.iter().any(|&(o, c)| o < start && start < c) + || !runs_with_assertion(b, from, to, start) + { return false; } let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; @@ -2655,6 +2669,9 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac .collect(); let mut closure = None; let mut sibling = false; + // Set after an `||` that may run the call: every `&&` further left belongs to its left operand + // (`false && ready || reset()`), so it does not guard the call, until an enclosing group opens. + let mut alternative = false; for i in (stmt + 1..start).rev() { if let Some(&(pipe, _)) = params.iter().find(|&&(pipe, end)| pipe <= i && i <= end) { // A closure that encloses the call at its own level, not a sibling element. @@ -2665,7 +2682,10 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } match b[i] { b')' | b']' | b'}' => depth += 1, - b'(' | b'[' | b'{' if depth == 0 => sibling = false, + b'(' | b'[' | b'{' if depth == 0 => { + sibling = false; + alternative = false; + } b'(' | b'[' | b'{' => depth -= 1, _ => {} } @@ -2683,6 +2703,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } if b[i] == b'&' && b[i - 1] == b'&' + && !alternative && ((!may_run && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) && !asserted_conjunction(b, from, to, i - 1)) @@ -2701,6 +2722,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac { // A literal `true` always skips the right side; any other operand may let it run. if may_run && !literal_operand(b, stmt, i - 1, b"true") { + alternative = true; continue; } return false; @@ -2980,8 +3002,6 @@ fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: && b[open + 1..at].trim_ascii_end().last().is_none_or(|c| matches!(c, b';' | b'{' | b'}')) && matching(b, open).is_some_and(|close| statement_end(&b[..close], at) < start) }; - let returns = - words(b, b"return", open + 1, start).into_iter().any(|at| !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); // The arguments of `stringify!` are not evaluated. let unevaluated: Vec<(usize, usize)> = calls_at(b, open + 1, start) .iter() @@ -2991,17 +3011,32 @@ fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: matching(b, o).map(|c| (o, c)) }) .collect(); + let evaluated = |at: usize| !unevaluated.iter().any(|&(o, c)| o < at && at < c); + let returns = words(b, b"return", open + 1, start) + .into_iter() + .any(|at| evaluated(at) && !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); + // A `?` follows an operand: a name, a call or index, or a block expression (`{ prepare() }?`). let tries = !definite && (open + 2..start).any(|i| { b[i] == b'?' - && !unevaluated.iter().any(|&(o, c)| o < i && i < c) - && (open + 1..i).rev().find(|&p| !b[p].is_ascii_whitespace()).is_some_and(|p| is_ident(b[p]) || matches!(b[p], b')' | b']')) + && evaluated(i) + && (open + 1..i).rev().find(|&p| !b[p].is_ascii_whitespace()).is_some_and(|p| { + is_ident(b[p]) + || matches!(b[p], b')' | b']') + // A block operand that is the body of an expression closure + // (`|| { … }?`) leaves only that closure. + || (b[p] == b'}' + && (open + 1..p) + .rev() + .find(|&o| b[o] == b'{' && matching(b, o) == Some(p)) + .is_some_and(|o| !in_expression_closure(o))) + }) && !nested(i, false) }); let loops = loop_body && [b"break".as_slice(), b"continue"] .iter() - .any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true) && (!definite || always(at)))); + .any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| evaluated(at) && !nested(at, true) && (!definite || always(at)))); if loop_body { loops } else { returns || tries } } @@ -11134,6 +11169,50 @@ mod tests { [], "a ? inside stringify! is not evaluated" ); + assert_eq!( + census("block_on(async { let _ = stringify!(return); app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return inside stringify! is not evaluated" + ); + assert_eq!( + census("for _ in [1] { let _ = stringify!(continue); app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue inside stringify! does not skip the call in a nested for body" + ); + assert_eq!( + census("block_on(async { return; let _ = stringify!(x); app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return outside stringify! still leaves the block" + ); + assert_eq!( + census("block_on(async { { prepare() }?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? after a block expression can leave a polled async block" + ); + assert_eq!( + census("block_on(async { let _f = || { Some(Some(())) }?; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a ? after the block body of an expression closure leaves only that closure" + ); + assert_eq!( + census("let _ = stringify!(app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "a call inside stringify! does not run, so it does not feed the entry" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; false && ready || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a literal false left of && guards only its own operand, not the || alternative" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; false && (ready || { reset(); true }); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a literal false left of && still guards a group that holds the || alternative" + ); } #[test] From cb837fa47a56db82dc93fd834fce399e1ef0b66e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:08:20 -0800 Subject: [PATCH 048/103] xtask: test-lint census skips stringified helpers and reads struct closure params An asserting helper inside `stringify!` is not evaluated, so it no longer counts as a check that runs for each entry. Closure parameter lists may now hold struct patterns (`|Row { c }|`), so a parameter that shadows the entry is seen. A path segment in a pattern (`entry::Row { .. }`) does not bind a name. --- xtask/src/test_lint.rs | 108 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 99 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e4c8ecde36..3b12d7c30e 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2052,10 +2052,16 @@ fn census(v: &View, helpers: &HashSet) -> Vec { // Failure messages run only after an assertion has failed, so a check there does not count. let unmessaged = v.body_without_messages(); let helpers_in = |from: usize, to: usize| -> Vec { - calls(&unmessaged, from - v.t.open, to - v.t.open) + let (f, t) = (from - v.t.open, to - v.t.open); + let unevaluated = stringify_args(&unmessaged, f, t); + calls_at(&unmessaged, f, t) .into_iter() - .filter(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) - .map(|(n, _)| n) + .filter(|(at, n, method)| { + !(n.ends_with('!') && is_assert_macro(n)) + && is_helper_call(n, *method, helpers) + && !unevaluated.iter().any(|&(o, c)| o < *at && *at < c) + }) + .map(|(_, n, _)| n) .collect() }; let weak_in = |from: usize, to: usize, var: &str| { @@ -2129,7 +2135,9 @@ fn pattern_names(pattern: &str) -> impl Iterator + '_ { // Inside braces, `name:` labels a field; outside them it starts a type (`let x: u32`). let in_braces = b[..at].iter().filter(|&&c| c == b'{').count() > b[..at].iter().filter(|&&c| c == b'}').count(); let next = end + b[end..].iter().take_while(|c| c.is_ascii_whitespace()).count(); - !in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':') + // A path segment (`entry::Row { .. }`, `Kind::empty`) names a module or an item. + let path = b[next..].starts_with(b"::") || pattern[..at].trim_end().ends_with("::"); + !path && (!in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':')) }) .map(move |(at, end)| &pattern[at..end]) .filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')) @@ -2180,7 +2188,7 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { } // Each parameter binds the names before its type. let params = String::from_utf8_lossy(&b[at + 1..end]).into_owned(); - let names: Vec = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::>()).collect(); + let names: Vec = closure_param_patterns(¶ms).into_iter().flat_map(|p| pattern_names(p).collect::>()).collect(); shadows.extend(names.into_iter().map(|n| (n, at + 1, until))); } // The scopes of nested loop patterns and closure parameters, where an assignment to the name @@ -2544,6 +2552,23 @@ fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { runs_with_assertion_within(b, from, to, start, &[], false) } +/// Whether `at` lies in the arguments of a `stringify!` in `b[from..to]`, which are not evaluated. +fn in_stringify(b: &[u8], from: usize, to: usize, at: usize) -> bool { + stringify_args(b, from, to).iter().any(|&(open, close)| open < at && at < close) +} + +/// The brackets around the arguments of each `stringify!` in `b[from..to]`. +fn stringify_args(b: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { + calls_at(b, from, to) + .into_iter() + .filter(|(_, name, _)| name == "stringify!") + .filter_map(|(p, name, _)| { + let open = skip_ws(b, p + name.len()); + matching(b, open).map(|close| (open, close)) + }) + .collect() +} + /// Checks whether `start` runs whenever assertions pass, or may run at all when `may_run` is true. /// `active` holds positions being checked so recursive closure calls terminate. fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize], may_run: bool) -> bool { @@ -2552,7 +2577,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } let mut active = active.to_vec(); active.push(start); - if in_uncalled_closure(b, from, to, start, &active, may_run) { + if in_stringify(b, from, to, start) || in_uncalled_closure(b, from, to, start, &active, may_run) { return false; } // Check enclosing blocks independently of the call's statement: an earlier semicolon inside @@ -2812,10 +2837,54 @@ fn parenthesized_closure_binding_head<'a>(b: &[u8], stmt: usize, start: usize, m /// The `|` that closes the closure parameter list opened by the `|` at `pipe`, before `to`, when the /// text between them can be a parameter list. Parameters may carry types (`|c: Command|`, -/// `|p: &[u8; 4]|`, `|f: fn() -> bool|`), but not a block, a string, a method call or an assignment. +/// `|p: &[u8; 4]|`, `|f: fn() -> bool|`) and struct patterns (`|Row { c, .. }|`), but not a block, +/// a string, a method call or an assignment. fn closure_params_end(b: &[u8], pipe: usize, to: usize) -> Option { - let end = (pipe + 1..to).find(|&i| b[i] == b'|')?; - (!b[pipe + 1..end].iter().any(|c| matches!(c, b'{' | b'}' | b'"' | b'.' | b'='))).then_some(end) + let mut i = pipe + 1; + loop { + match b[..to].get(i)? { + b'|' => break Some(i), + b'"' | b'.' | b'=' | b'}' => break None, + b'{' => { + // A struct pattern follows its path (`Row {`); its braces hold names, labels and `..`. + let named = b[pipe + 1..i].trim_ascii_end().last().copied().is_some_and(is_ident); + let close = matching(b, i).filter(|&c| c < to && named)?; + if b[i + 1..close].iter().any(|c| matches!(c, b'"' | b'=' | b';' | b'{' | b'}')) { + break None; + } + i = close + 1; + } + _ => i += 1, + } + } +} + +/// The patterns of a closure parameter list `params` without their types: the text of each +/// top-level parameter before its `:` (`c` in `c: Command`, `Row { c: other }` in `Row { c: other }: Row`). +fn closure_param_patterns(params: &str) -> Vec<&str> { + let b = params.as_bytes(); + let (mut out, mut depth, mut start, mut typed) = (vec![], 0usize, 0, false); + for (i, &c) in b.iter().enumerate() { + match c { + b'(' | b'[' | b'{' | b'<' => depth += 1, + b')' | b']' | b'}' | b'>' => depth = depth.saturating_sub(1), + b':' if depth == 0 && !typed && b.get(i + 1) != Some(&b':') && (i == 0 || b[i - 1] != b':') => { + out.push(¶ms[start..i]); + typed = true; + } + b',' if depth == 0 => { + if !typed { + out.push(¶ms[start..i]); + } + (start, typed) = (i + 1, false); + } + _ => {} + } + } + if !typed { + out.push(¶ms[start..]); + } + out } /// The head before a closure's parameters with a trailing `move` and `async` removed, and whether @@ -11199,6 +11268,27 @@ mod tests { [(2, "census")], "a call inside stringify! does not run, so it does not feed the entry" ); + assert_eq!( + census("let _ = stringify!(verify_entry(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an asserting helper inside stringify! does not run" + ); + assert_eq!(census("verify_entry(c); assert!(menu(c).is_some());"), [], "an asserting helper that runs checks each entry"); + assert_eq!( + census("let run = |Row { c }| { render(c, offset); }; run(fallback()); assert!(menu(c).is_some());"), + [(2, "census")], + "a struct pattern in closure parameters shadows the entry" + ); + assert_eq!( + census("let run = |Row { c: other }| { render(c, other); }; run(fallback()); assert!(menu(c).is_some());"), + [], + "a field label in a closure's struct pattern binds the name after it, not the entry" + ); + assert_eq!( + census("let run = |c::Row { offset }| { render(c, offset); }; run(fallback()); assert!(menu(c).is_some());"), + [], + "a path segment in a closure's struct pattern does not bind the name" + ); assert_eq!( census( "let mut input = c; let mut reset = || { input = fallback(); }; false && ready || { reset(); true }; app.run(input); assert!(menu(c).is_some());" From 2b05ddfa102de0dbcb5b8d1b0153a9a5cd214046 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 08:09:36 -0800 Subject: [PATCH 049/103] Properties: an unfinished Objects on Path Rotate value stays with the groups it was typed for The Rotate field of the Objects on Path Options section kept a typed but unentered value when the selection changed. When the newly selected group had the same Rotate, the field went on showing the old text, and the next Enter applied it to the new group: typing 3+ with one group selected, selecting another group at 0 degrees, then typing 1 and Enter gave the second group 4 degrees. The field now passes NumberField::edit_target the document, its File > Revert count and the selected groups in id order. When any of these changes, the field drops the unfinished value and shows the new groups' Rotate. The same groups selected in another order keep the value. --- .../src/panels/properties/object_sections.rs | 19 +++- crates/ui-egui/src/panels/properties/tests.rs | 101 ++++++++++++++++++ 2 files changed, 119 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/object_sections.rs b/crates/ui-egui/src/panels/properties/object_sections.rs index 844305a187..fb00a9a102 100644 --- a/crates/ui-egui/src/panels/properties/object_sections.rs +++ b/crates/ui-egui/src/panels/properties/object_sections.rs @@ -104,10 +104,25 @@ pub(super) fn selected_objects_on_path(app: &VectorcraftApp) -> Option)>; + +/// The [`EditTarget`] of the groups `oop` in the active document. +fn edit_target(app: &VectorcraftApp, oop: &ObjectsOnPathSelection) -> EditTarget { + let st = app.session.active()?; + let mut ids = oop.ids.clone(); + ids.sort_unstable(); + Some((st.uid, st.reverts, ids)) +} + /// The Objects on Path Options of the selected Objects on Path groups: Pivot, the point of each /// object that attaches to the path, and Rotate, the angle each object tilts by from upright on the /// path. A change goes to every selected group in one undo step (`object.objectsOnPath.options`). -/// Where the groups differ, no Pivot square is chosen and Rotate is blank. Detach takes the object +/// Where the groups differ, no Pivot square is chosen and Rotate is blank. A Rotate value typed and +/// not yet entered is dropped when its [`EditTarget`] changes. Detach takes the object /// chosen with its Select/Move widget off the path (`object.objectsOnPath.detach`), and is dimmed /// until one is chosen. pub(super) fn objects_on_path_section(app: &mut VectorcraftApp, ui: &mut Ui, oop: &ObjectsOnPathSelection) { @@ -117,6 +132,7 @@ pub(super) fn objects_on_path_section(app: &mut VectorcraftApp, ui: &mut Ui, oop app.status(e); } }; + let target = edit_target(app, oop); super::section(tl!("Objects on Path Options")).show(ui, |ui, _| { Field::new(tl!("Pivot")).show(ui, |ui, _| { // Mixed while the groups' pivots differ: no square is chosen. @@ -132,6 +148,7 @@ pub(super) fn objects_on_path_section(app: &mut VectorcraftApp, ui: &mut Ui, oop let presets: Vec> = transform::ANGLE_PRESETS.iter().map(|v| Entry::new(NumberPick::Number(*v), format!("{v}°"))).collect(); let out = NumberField::new(tl!("Rotate"), Bind::given(oop.rotate)) + .edit_target(&target) .unit_kind(UnitKind::Degrees) .presets(&presets) .range(-360.0..=f64::INFINITY) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index dea62a6dfa..0cbbca6bc3 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1823,6 +1823,107 @@ fn objects_on_path_options_set_pivot_and_rotate_in_one_undo_step() { assert_eq!(undo_depth(&panel.app()), depth + 1, "one undo step for both groups"); } +/// Clicks Rotate, selects its text and types `3+`, leaving the value unfinished. +fn unfinished_rotate(panel: &mut Panel) { + use craft::ui::contract::Role; + panel.click_role("Rotate", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("3+"); +} + +/// Types `1` into the focused field and presses Enter. +fn finish_with_one(panel: &mut Panel) { + panel.type_text("1"); + panel.key(Key::Enter, Modifiers::NONE); +} + +/// A Rotate value typed for one Objects on Path group and not yet entered stays with that group: +/// with the selection unchanged, `3+` then `1` and Enter gives 4°. After another group with the +/// same Rotate is selected, the field shows that group's value and `1` and Enter gives it 1°. The +/// same groups selected in another order keep the value. +#[test] +fn an_unfinished_rotate_value_does_not_reach_another_group() { + use craft::ui::contract::Role; + let mut app = new_app(); + let a = objects_on_path(&mut app, 150.0, 0.0); + let b = objects_on_path(&mut app, 250.0, 0.0); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut panel = Panel::new(app, objects_on_path_options); + let rotates = |panel: &Panel| { + let app = panel.app(); + (pivot_rotate(&app, &a).1, pivot_rotate(&app, &b).1) + }; + unfinished_rotate(&mut panel); + panel.frame(); + finish_with_one(&mut panel); + assert_eq!(rotates(&panel), (4.0, 0.0), "an unchanged target keeps the typed value"); + panel.app().run("object.objectsOnPath.options", json!({"ids": [a], "rotate": 0})).unwrap(); + panel.frame(); + + unfinished_rotate(&mut panel); + panel.app().run("select.set", json!({"ids": [b]})).unwrap(); + panel.frame(); + assert_ne!(panel.value_role("Rotate", Role::SPIN_BUTTON).as_deref(), Some("3+"), "the field drops the value typed for a"); + finish_with_one(&mut panel); + assert_eq!(rotates(&panel), (0.0, 1.0), "b takes 1°, not 3+1"); + + // The same groups selected in another order keep the value typed so far. + panel.app().run("object.objectsOnPath.options", json!({"ids": [b], "rotate": 0})).unwrap(); + panel.app().run("select.set", json!({"ids": [a, b]})).unwrap(); + panel.frame(); + unfinished_rotate(&mut panel); + panel.app().run("select.set", json!({"ids": [b, a]})).unwrap(); + panel.frame(); + finish_with_one(&mut panel); + assert_eq!(rotates(&panel), (4.0, 4.0), "the same groups in another order keep the typed value"); +} + +/// A Rotate value typed and not yet entered is dropped when another document becomes active, even +/// where its group has the same id and Rotate. +#[test] +fn an_unfinished_rotate_value_is_dropped_by_another_document() { + let mut app = new_app(); + let first = objects_on_path(&mut app, 150.0, 0.0); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let second = objects_on_path(&mut app, 150.0, 0.0); + assert_eq!(first, second, "both documents' groups have the same id"); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut panel = Panel::new(app, objects_on_path_options); + let rotate = |panel: &mut Panel, index: u64| { + panel.app().run("document.activate", json!({"index": index})).unwrap(); + pivot_rotate(&panel.app(), &first).1 + }; + + unfinished_rotate(&mut panel); + panel.app().run("document.activate", json!({"index": 1})).unwrap(); + panel.frame(); + finish_with_one(&mut panel); + assert_eq!((rotate(&mut panel, 0), rotate(&mut panel, 1)), (0.0, 1.0), "the other document takes 1°"); +} + +/// A Rotate value typed and not yet entered is dropped when File › Revert replaces the document's +/// content, even where the restored group, selected again, has the same id and Rotate. +#[test] +fn an_unfinished_rotate_value_is_dropped_by_file_revert() { + let mut app = new_app(); + let group = objects_on_path(&mut app, 150.0, 0.0); + let dir = vectorcraft_testkit::TempDir::new("objects-on-path-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Objects on Path.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the group as saved. + rect(&mut app, 300.0, 20.0, 20.0, 20.0); + app.run("select.set", json!({"ids": [group]})).unwrap(); + let mut panel = Panel::new(app, objects_on_path_options); + unfinished_rotate(&mut panel); + + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({"ids": [group]})).unwrap(); + panel.frame(); + finish_with_one(&mut panel); + assert_eq!(pivot_rotate(&panel.app(), &group).1, 1.0, "Revert drops the unfinished value"); +} + /// The objects of the Objects on Path group `id`, in their order along the path. fn on_path(app: &VectorcraftApp, id: &Value) -> Vec { let d = &app.session.active().unwrap().doc; From 99c8335dcdb16deed81548028c81feb9f732d083 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:34:07 -0800 Subject: [PATCH 050/103] Properties: an unfinished Word Gap or Line Gap stays with the type it was typed for The Dynamic Text Word Gap and Line Gap fields kept a typed but unfinished value when the selection changed. When the newly selected area type had the same gap, the field went on showing the old text, and the next Enter applied it there: typing 3+ in Word Gap for one frame, selecting another frame at 100%, then typing 1 and Enter set it to 4%. Both fields now pass NumberField::edit_target a key made of the active document, its File > Revert count and the area type frames that type.dynamicText changes, including frames inside selected groups. When the key changes, the field drops the unfinished value and shows the new frames' gap. Selecting other objects next to the same frames keeps it. --- .../src/panels/properties/dynamic_text.rs | 31 +++- crates/ui-egui/src/panels/properties/tests.rs | 150 ++++++++++++++++++ 2 files changed, 174 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/dynamic_text.rs b/crates/ui-egui/src/panels/properties/dynamic_text.rs index 29c7a37b17..f3deb0bbe1 100644 --- a/crates/ui-egui/src/panels/properties/dynamic_text.rs +++ b/crates/ui-egui/src/panels/properties/dynamic_text.rs @@ -10,7 +10,7 @@ use craft::ui::form::Field; use craft::ui::text::{NumberField, StepArrows}; use egui::Ui; use serde_json::{Value, json}; -use vectorcraft_doc::{AreaOptions, NodeKind, TextKind}; +use vectorcraft_doc::{AreaOptions, NodeId, NodeKind, TextKind}; use crate::VectorcraftApp; @@ -25,12 +25,24 @@ pub(crate) struct Shown { pub(crate) enabled: bool, } -/// Dynamic Text of the selected area type (and area type in selected groups); `None` when the -/// selection holds no area type, or holds other type too (the command refuses it). +/// [`shown_with_target`] without the edit target. +#[cfg(test)] pub(crate) fn shown(app: &VectorcraftApp) -> Option { + shown_with_target(app).map(|(s, _)| s) +} + +/// What the Word Gap and Line Gap fields edit, as their edit target: the document, how many times File › Revert +/// replaced its content, and the area type frames `type.dynamicText` changes, sorted by id. A field drops an +/// unfinished value when this changes, even where the newly selected frames have the same gap. +type EditTarget = (u64, u64, Vec); + +/// Dynamic Text of the selected area type (and area type in selected groups), and the [`EditTarget`] of those +/// frames; `None` when the selection holds no area type, or holds other type too (the command refuses it). +fn shown_with_target(app: &VectorcraftApp) -> Option<(Shown, EditTarget)> { let st = app.session.active()?; let threaded = |id| st.doc.text_threads.iter().any(|t| t.len() > 1 && t.contains(&id)); let mut frames = vec![]; + let mut ids = vec![]; let mut other = false; for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { n.walk(&mut |c| { @@ -38,18 +50,22 @@ pub(crate) fn shown(app: &VectorcraftApp) -> Option { if matches!(t.kind, TextKind::Area { .. }) { let (word, line) = t.area.block_gaps(); frames.push((t.dynamic_text, word, line, threaded(c.id))); + ids.push(c.id); } else { other = true; } }); } let &(on, word, line, _) = frames.first().filter(|_| !other)?; - Some(Shown { + ids.sort_unstable_by_key(|id| id.0); + ids.dedup(); + let shown = Shown { on: frames.iter().all(|f| f.0 == on).then_some(on), word_gap: frames.iter().all(|f| f.1 == word).then_some(word), line_gap: frames.iter().all(|f| f.2 == line).then_some(line), enabled: frames.iter().all(|f| !f.3), - }) + }; + Some((shown, (st.uid, st.reverts, ids))) } fn run(app: &mut VectorcraftApp, p: Value) { @@ -61,7 +77,7 @@ fn run(app: &mut VectorcraftApp, p: Value) { /// The checkbox, and the gap rows while every selected frame has Block on. Nothing shows without /// area type. Returns whether anything was drawn. pub(crate) fn rows(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { - let Some(s) = shown(app) else { return false }; + let Some((s, target)) = shown_with_target(app) else { return false }; let on = s.on.map_or(Mixed::Mixed, Mixed::Same); let out = Checkbox::new(Bind::given(on)).label(tl!("Dynamic Text")).enabled(s.enabled).show(ui); if let Some(&on) = out.events.committed() { @@ -78,6 +94,7 @@ pub(crate) fn rows(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { .range(lo..=hi) .step(10.0) .step_arrows(StepArrows::Leading) + .edit_target(&target) .show(ui); if let Some(Some(v)) = out.edit.events.committed() { run(app, json!({ "wordGap": v.clamp(lo, hi) })); @@ -86,7 +103,7 @@ pub(crate) fn rows(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let (lo, hi) = AreaOptions::LINE_GAP; let lengths = crate::canvas::general_lengths(app); Field::new(tl!("Line Gap")).show(ui, |ui, _| { - let out = NumberField::length(tl!("Line Gap"), Bind::given(s.line_gap), lengths).range(lo..=hi).show(ui); + let out = NumberField::length(tl!("Line Gap"), Bind::given(s.line_gap), lengths).range(lo..=hi).edit_target(&target).show(ui); if let Some(Some(v)) = out.edit.events.committed() { run(app, json!({ "lineGap": v.clamp(lo, hi) })); } diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index dea62a6dfa..cdc8951e22 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1959,6 +1959,156 @@ fn dynamic_text_rows_follow_the_selected_area_type() { assert_eq!(dynamic_text::shown(&panel.app()).map(|s| (s.on, s.enabled)), Some((Some(false), false))); } +/// Two area type frames at `x` 10 and 200 with Dynamic Text on, Word Gap 100% and Line Gap 2 pt, in a new document → +/// their ids. +fn dynamic_text_frames(app: &mut VectorcraftApp) -> (u64, u64) { + app.run("file.new", json!({"width": 500, "height": 400})).unwrap(); + let mut make = |x: f64| { + let id = app.run("text.create", json!({"x": x, "y": 10, "text": "Panel\ntext", "area": {"width": 100, "height": 120}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("type.dynamicText", json!({"ids": [id], "on": true, "lineGap": 2})).unwrap(); + id + }; + (make(10.0), make(200.0)) +} + +/// The Word Gap and Line Gap of area type `id` in the active document. +fn block_gaps(app: &VectorcraftApp, id: u64) -> (f64, f64) { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.area.block_gaps(), + _ => panic!("object {id} is not type"), + } +} + +/// Selects all of the field `name`'s value and types `3+`, leaving it unfinished. +fn type_unfinished(panel: &mut Panel, name: &str) { + use craft::ui::contract::Role; + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("3+"); +} + +/// A Word Gap or Line Gap typed for one frame and not yet entered is dropped when another frame with the same gap is +/// selected, so it does not reach that frame. With the selection unchanged, the value typed so far is kept. +#[test] +fn dynamic_text_gaps_drop_an_unfinished_value_when_the_selection_changes() { + use craft::ui::contract::Role; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (a, b) = dynamic_text_frames(&mut app); + let mut panel = Panel::new(app, type_sections); + for (name, gap) in [("Word Gap", 0), ("Line Gap", 1)] { + let at = |panel: &Panel, id| { + let gaps = block_gaps(&panel.app(), id); + [gaps.0, gaps.1][gap] + }; + let before = (at(&panel, a), at(&panel, b)); + panel.app().run("select.set", json!({"ids": [a]})).unwrap(); + panel.frame(); + type_unfinished(&mut panel, name); + panel.app().run("select.set", json!({"ids": [b]})).unwrap(); + panel.frame(); + assert_ne!(panel.value_role(name, Role::SPIN_BUTTON).as_deref(), Some("3+"), "{name} drops the value typed for a"); + panel.type_text("1"); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!((at(&panel, a), at(&panel, b)), (before.0, 1.0), "{name}: a keeps its gap, b takes 1, not 3+1"); + + // With the selection unchanged, 3+ then 1 gives 4. + type_unfinished(&mut panel, name); + panel.frame(); + panel.type_text("1"); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(at(&panel, b), 4.0, "{name}: an unchanged selection keeps the typed value"); + panel.app().run("type.dynamicText", json!({"ids": [b], "wordGap": 100, "lineGap": 2})).unwrap(); + } +} + +/// The gap fields' unfinished value follows the area type frames Dynamic Text changes, not the selected objects: a +/// rectangle added to the selection keeps it, and a frame moved into a selected group drops it. +#[test] +fn dynamic_text_gaps_keep_an_unfinished_value_while_the_frames_stay_the_same() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (a, b) = dynamic_text_frames(&mut app); + let square = app.run("shape.rectangle", json!({"x": 10, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut panel = Panel::new(app, type_sections); + type_unfinished(&mut panel, "Word Gap"); + panel.app().run("select.set", json!({"ids": [a, square]})).unwrap(); + panel.frame(); + panel.type_text("1"); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(block_gaps(&panel.app(), a).0, 4.0, "the same frame keeps the typed value: 3+1"); + + // b and a group holding a, selected; a third frame moved into the group while a value is typed. + let c = { + let mut app = panel.app(); + app.run("type.dynamicText", json!({"ids": [a], "wordGap": 100})).unwrap(); + let c = app.run("text.create", json!({"x": 10, "y": 150, "text": "Panel\ntext", "area": {"width": 100, "height": 120}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("type.dynamicText", json!({"ids": [c], "on": true, "lineGap": 2})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [b, group]})).unwrap(); + c + }; + panel.frame(); + type_unfinished(&mut panel, "Word Gap"); + let selected = panel.app().session.active().unwrap().selection.objects.clone(); + let group = selected[1].0; + panel.app().run("layer.move", json!({"id": c, "target": group, "place": "inside"})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().selection.objects, selected, "b and the group stay selected"); + panel.frame(); + panel.type_text("1"); + panel.key(Key::Enter, Modifiers::NONE); + let gaps = [a, b, c].map(|id| block_gaps(&panel.app(), id).0); + assert_eq!(gaps, [1.0; 3], "all three frames take 1%, not 3+1"); +} + +/// A Word Gap typed in one document and not yet entered is dropped when another document whose frame has the same id +/// and the same gap becomes active, and when File › Revert restores the frame. +#[test] +fn dynamic_text_gaps_drop_an_unfinished_value_in_another_document_or_after_revert() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (a, _) = dynamic_text_frames(&mut app); + let (other, _) = dynamic_text_frames(&mut app); + assert_eq!(other, a, "both documents' first frames have the same id"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut panel = Panel::new(app, type_sections); + type_unfinished(&mut panel, "Word Gap"); + panel.app().run("document.activate", json!({"index": 1})).unwrap(); + panel.app().run("select.set", json!({"ids": [a]})).unwrap(); + panel.frame(); + panel.type_text("1"); + panel.key(Key::Enter, Modifiers::NONE); + let word_gap = |panel: &mut Panel, index: u64| { + panel.app().run("document.activate", json!({"index": index})).unwrap(); + block_gaps(&panel.app(), a).0 + }; + assert_eq!((word_gap(&mut panel, 0), word_gap(&mut panel, 1)), (100.0, 1.0), "the other document's frame takes 1%, not 3+1"); + + // The second document, saved, then changed so that Revert has something to undo. + let dir = vectorcraft_testkit::TempDir::new("dynamic-text-revert"); + { + let mut app = panel.app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("type.dynamicText", json!({"ids": [a], "wordGap": 100})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Dynamic Text.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 300, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + } + panel.frame(); + type_unfinished(&mut panel, "Word Gap"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({"ids": [a]})).unwrap(); + panel.frame(); + panel.type_text("1"); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(block_gaps(&panel.app(), a).0, 1.0, "Revert drops the unfinished value"); +} + /// A document with a graph of `kind` and three series, selected → the graph's id. fn graph_doc(app: &mut VectorcraftApp, kind: &str, x: f64) -> u64 { if app.session.active().is_none() { From 5aadf6c61645dd58dbb1f9581307c4acc0b586f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 08:54:44 -0800 Subject: [PATCH 051/103] Shapes: stars stay live with an editable point count A star drawn with the Star tool, shape.star or addon.shapes.star was a plain path, so its point count could not change after it was drawn. - LiveShape::Star keeps the outer and inner radii, the point count (2 to 1000, clamped when read from a file) and Live Corners' radii and kinds. Its corners keep the radius they shared through a new count. - object.setLiveShape takes `points` (2 to 1000) and `ratio` (inner radius over outer radius, above 0 and up to 1), one undo step each and none when nothing changes. A new layout drops the star's selected anchors and segments; `points` with `radius` or `kind` is an error. - The side widget shows on a live star and sets 3 to 20 points. - Star Properties in the Transform panel and the Properties panel's Transform section have a Points field with a 3 to 20 slider and a Ratio field. - Shape Tools' configure keeps a whole star live. Fixes #4339 --- crates/doc/src/corners.rs | 15 ++- crates/doc/src/node/live_shape.rs | 98 ++++++++++++--- crates/doc/src/node/tests.rs | 28 +++++ crates/engine/src/cmd/addons/shapes.rs | 2 +- crates/engine/src/cmd/addons/shapes/tests.rs | 24 ++++ crates/engine/src/cmd/create.rs | 13 +- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 44 ++++++- crates/engine/src/tests/css.rs | 8 +- crates/engine/src/tests/livecorners.rs | 73 +++++++++-- crates/eps/src/ai_editing/writer/symbols.rs | 4 +- crates/svg/src/css.rs | 7 +- crates/tools/src/addons/box3d.rs | 47 +++++++ crates/tools/src/sidewidget.rs | 116 +++++++++++++++--- crates/ui-egui/src/dialogs/corners.rs | 2 +- .../src/panels/tests_css_properties.rs | 4 +- crates/ui-egui/src/panels/transform/shape.rs | 30 ++++- crates/ui-egui/src/panels/transform/tests.rs | 29 +++++ crates/ui-egui/src/tests/taskbar.rs | 2 +- crates/ui-egui/src/toolbar/tests.rs | 9 +- docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 22 files changed, 487 insertions(+), 77 deletions(-) diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 24228604a6..b22e08b3ff 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -36,14 +36,14 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { let was_relative = live.radii_relative(); let base = match live { LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)), - LiveShape::Polygon { .. } => live.polygon_outline(), + LiveShape::Polygon { .. } | LiveShape::Star { .. } => live.polygon_outline(), LiveShape::Path { base, .. } => base.clone(), LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; let corners = path_corners(&base); let radii: &mut [f64] = match live { LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii, LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; @@ -62,6 +62,7 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { match live { LiveShape::Rectangle { radii_relative: rel, .. } | LiveShape::Polygon { radii_relative: rel, .. } + | LiveShape::Star { radii_relative: rel, .. } | LiveShape::Path { radii_relative: rel, .. } => { *rel = relative; } @@ -99,7 +100,7 @@ impl<'a> LiveCorners<'a> { let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = l.folded() else { return None }; (Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec(), radii_relative) } - Some(l @ LiveShape::Polygon { radii, kinds, radii_relative, .. }) => { + Some(l @ (LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. })) => { (Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative) } Some(LiveShape::Path { base, radii, kinds, radii_relative }) => { @@ -258,6 +259,14 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne edit(&outline, relative, radii, kinds, corners, radius, kind); trim_vec_radii(radii, kinds); } + LiveShape::Star { r1, r2, points, xf, radii, kinds, .. } => { + let outline = shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf); + let n = 2 * *points as usize; + radii.resize(n, 0.0); + kinds.resize(n, CornerKind::Round); + edit(&outline, relative, radii, kinds, corners, radius, kind); + trim_vec_radii(radii, kinds); + } LiveShape::Path { base, radii, kinds, .. } => { let n = base.anchor_count(); radii.resize(n, 0.0); diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 0a17301331..5ad2caeb48 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -46,11 +46,32 @@ pub enum LiveShape { #[serde(default, skip_serializing_if = "is_false")] radii_relative: bool, }, + /// A star drawn with the Star tool or `shape.star`: its point count and radii stay editable. + Star { + /// Outer radius: centre to each tip. + r1: f64, + /// Inner radius: centre to each point between two tips. + r2: f64, + /// 2–1000, as [`LiveShape::set_points`] gives it; a file's count is clamped when read. + #[serde(deserialize_with = "de_points")] + points: u32, + /// Maps the star (centred on the origin, first tip straight up) into the document. + xf: Affine, + /// Corner radii in document units, by vertex from the first tip clockwise, tips and inner + /// points alternating (none: sharp). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + radii: Vec, + /// Corner kinds, in the same order (none: round). + #[serde(default, skip_serializing_if = "all_round")] + kinds: Vec, + #[serde(default, skip_serializing_if = "is_false")] + radii_relative: bool, + }, Line { a: Point, b: Point, }, - /// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut + /// Any other path whose corners Live Corners cut (a pen path, a star saved as a path): it keeps its uncut /// outline so the corners stay editable. Without a cut corner it is a plain path again. Path { /// The path with its corners uncut, in the document. @@ -74,9 +95,10 @@ fn is_false(b: &bool) -> bool { impl LiveShape { pub fn radii_relative(&self) -> bool { match self { - LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => { - *radii_relative - } + LiveShape::Rectangle { radii_relative, .. } + | LiveShape::Polygon { radii_relative, .. } + | LiveShape::Star { radii_relative, .. } + | LiveShape::Path { radii_relative, .. } => *radii_relative, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false, } } @@ -86,6 +108,7 @@ impl LiveShape { LiveShape::Rectangle { .. } => "Rectangle", LiveShape::Ellipse { .. } => "Ellipse", LiveShape::Polygon { .. } => "Polygon", + LiveShape::Star { .. } => "Star", LiveShape::Line { .. } => "Line", LiveShape::Path { .. } => "Path", } @@ -100,7 +123,7 @@ impl LiveShape { shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf) } LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf), - LiveShape::Polygon { radii, kinds, radii_relative, .. } => { + LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. } => { let outline = self.polygon_outline(); let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative); cut_corners(&outline, &radii, kinds).0 @@ -112,10 +135,12 @@ impl LiveShape { } } } - /// A polygon's outline with its corners uncut, in the document (empty for other shapes). + /// A polygon's or star's outline with its corners uncut, in the document (empty for other + /// shapes). pub fn polygon_outline(&self) -> PathData { match self { LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf), + LiveShape::Star { r1, r2, points, xf, .. } => shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf), _ => PathData::default(), } } @@ -124,16 +149,36 @@ impl LiveShape { pub fn set_sides(&mut self, n: u64) { let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return }; *sides = n.clamp(3, 1000) as u32; - fn spread(v: &mut Vec, n: usize) { - match v.first().copied() { - Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], - Some(_) => v.resize(n, T::default()), - None => {} - } - } spread(radii, *sides as usize); spread(kinds, *sides as usize); } + /// A star's point count. None for other shapes. + pub fn star_points(&self) -> Option { + let LiveShape::Star { points, .. } = self else { return None }; + Some(*points) + } + /// Give a star `n` points (2–1000). Its corners keep the radius and kind they shared; else the + /// corners past the old last one are sharp. + pub fn set_points(&mut self, n: u64) { + let LiveShape::Star { points, radii, kinds, .. } = self else { return }; + *points = n.clamp(2, 1000) as u32; + spread(radii, 2 * *points as usize); + spread(kinds, 2 * *points as usize); + } + /// A star's ratio: its inner radius over its outer radius (0 when the outer radius is 0). None + /// for other shapes. + pub fn star_ratio(&self) -> Option { + let LiveShape::Star { r1, r2, .. } = self else { return None }; + Some(if *r1 > 0.0 { *r2 / *r1 } else { 0.0 }) + } + /// Give a star the ratio `ratio` (0 to 1, see [`LiveShape::star_ratio`]), keeping its outer + /// radius. Nothing changes for other shapes or a ratio outside 0 to 1. + pub fn set_star_ratio(&mut self, ratio: f64) { + let LiveShape::Star { r1, r2, .. } = self else { return }; + if ratio.is_finite() && (0.0..=1.0).contains(&ratio) { + *r2 = *r1 * ratio; + } + } /// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of /// `xf` (exact while its sides are equal). None for other shapes. pub fn polygon_radius(&self) -> Option { @@ -151,7 +196,9 @@ impl LiveShape { /// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for /// other shapes. pub fn shape_angle(&self) -> Option { - let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None }; + let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. }) = self else { + return None; + }; // No −0° or 360° from rounding: a shape drawn level reads 0°. let a = (-self.angle_deg()).rem_euclid(360.0); Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) @@ -168,7 +215,7 @@ impl LiveShape { let angle = angle.rem_euclid(360.0); let (xf, local) = match self { LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)), - LiveShape::Polygon { xf, .. } => (xf, Point::ZERO), + LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => (xf, Point::ZERO), LiveShape::Line { .. } | LiveShape::Path { .. } => return, }; let center = *xf * local; @@ -274,7 +321,7 @@ impl LiveShape { *xf = a * *xf; false } - LiveShape::Polygon { xf, radii, radii_relative, .. } => { + LiveShape::Polygon { xf, radii, radii_relative, .. } | LiveShape::Star { xf, radii, radii_relative, .. } => { *xf = a * *xf; scale_radii(radii, a, *radii_relative) } @@ -326,7 +373,7 @@ impl LiveShape { let relative = self.radii_relative(); let radii: &mut [f64] = match self { LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } | LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false, }; if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 { @@ -338,7 +385,7 @@ impl LiveShape { /// Rotation angle of the live shape in degrees, clockwise on the page (y points down). pub fn angle_deg(&self) -> f64 { match self { - LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => { + LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => { let c = xf.as_coeffs(); c[1].atan2(c[0]).to_degrees() } @@ -358,6 +405,21 @@ fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { u32::deserialize(d).map(|n| n.clamp(3, 1000)) } +/// A star's point count read from a file, clamped as the commands clamp it (see [`de_sides`]). +fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(2, 1000)) +} + +/// Give a corner list `n` entries: one value all its corners shared fills it; otherwise entries +/// past its end are the default (sharp, round) and entries past `n` go. An empty list stays empty. +fn spread(v: &mut Vec, n: usize) { + match v.first().copied() { + Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], + Some(_) => v.resize(n, T::default()), + None => {} + } +} + /// Whether `a` only moves (no rotation, scale, shear or reflection). pub(super) fn moves_only(a: Affine) -> bool { let [a0, a1, a2, a3, _, _] = a.as_coeffs(); diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 480e201e2d..add639ed4d 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -158,6 +158,34 @@ fn a_polygon_from_a_file_has_3_to_1000_sides() { assert_eq!(huge.polygon_outline().anchor_count(), 1000); } +/// A live star saves and reads back as it was, and one read from a file has 2 to 1000 points. +#[test] +fn a_star_round_trips_and_its_file_count_is_clamped() { + let star = LiveShape::Star { + r1: 40.0, + r2: 20.0, + points: 7, + xf: Affine::translate((10.0, 20.0)), + radii: vec![2.0; 14], + kinds: vec![], + radii_relative: false, + }; + let text = serde_json::to_string(&star).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), star); + assert_eq!(star.label(), "Star"); + let read = |points: u64| { + let json = serde_json::json!({"shape": "star", "r1": 10.0, "r2": 5.0, "points": points, "xf": [1, 0, 0, 1, 0, 0]}); + serde_json::from_value::(json).unwrap().star_points().unwrap() + }; + assert_eq!([0, 2, 5, 1000, 4_000_000_000].map(read), [2, 2, 5, 1000, 1000]); + // Points and ratio change; the outer radius stays. + let mut s = star.clone(); + s.set_points(9); + s.set_star_ratio(0.25); + assert!(matches!(&s, LiveShape::Star { r1, r2, points: 9, radii, .. } if *r1 == 40.0 && *r2 == 10.0 && *radii == vec![2.0; 18])); + assert_eq!(s.polygon_outline().anchor_count(), 18); +} + #[test] fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { let close = |a: f64, b: f64| (a - b).abs() < 1e-9; diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs index 7fc935546e..43e8948118 100644 --- a/crates/engine/src/cmd/addons/shapes.rs +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -298,7 +298,7 @@ fn star(s: &mut Session, p: &Value) -> Result { pie, arc_mode, }; - insert_custom(s, "Star", None, cs) + insert_custom(s, "Star", cs.to_live_shape(), cs) } fn spiral(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs index bc5f1359e2..4f813263ef 100644 --- a/crates/engine/src/cmd/addons/shapes/tests.rs +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -144,6 +144,30 @@ fn shape_of(s: &Session, id: NodeId) -> CustomShape { CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()).unwrap() } +#[test] +fn configuring_a_live_star_keeps_its_live_shape() { + let mut s = new_session(); + for cmd in ["shape.star", "addon.shapes.star"] { + let id = id_of(&mut s, cmd, json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(live), .. } if matches!(live.as_ref(), LiveShape::Star { points: 5, .. }))); + assert!(matches!(CustomShape::read(n), Some(CustomShape::Polygon { sides: 5, spoke_ratio: Some(_), .. }))); + + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 7})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. })); + assert_eq!(path, &live.to_path()); + + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "spokeRatio": 0.4})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. })); + assert!((live.star_ratio().unwrap() - 0.4).abs() < 1e-9); + assert_eq!(path, &live.to_path()); + } +} + /// Runs `cmd` with `p`, which must fail with `msg` and leave the document and its history as they /// were. fn refused(s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str) { diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 083cfa65d9..934151589b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}: a live star whose points and ratio object.setLiveShape changes", has_doc, star ), @@ -655,14 +655,11 @@ fn star(s: &mut Session, p: &Value) -> Result { let r2 = f64_or(p, "radius2", r1 / 2.0).abs(); let n = count_or(p, "points", 5, "shape.star")?.clamp(2, 1000) as u32; let rot = f64_or(p, "rotation", 0.0); - let turn = vectorcraft_geom::rotate_deg(rot); // A quarter or whole turn (a Constrain Angle of 90°, say) turns the upright star exactly. - let path = if rot != 0.0 && turn.as_coeffs()[..4].iter().all(|c| c.fract() == 0.0) { - shapes::star(Point::ZERO, r1, r2, n, 0.0).transformed(Affine::translate(c.to_vec2()) * turn) - } else { - shapes::star(c, r1, r2, n, rot) - }; - add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot)) + let xf = Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + // The star stays live: its point count and ratio can change later (`object.setLiveShape`). + let live = LiveShape::Star { r1, r2, points: n, xf, radii: vec![], kinds: vec![], radii_relative: false }; + add_art_turned(s, "Star", path_kind(live.to_path(), Some(live)), constrained_turn(s, rot)) } fn line(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index bea69d1698..022820f0b5 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -314,7 +314,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the drawn anchor count drops its selected anchors and segments), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b8bd5ff8c6..b60f19cf06 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -103,7 +103,7 @@ fn corners_param(p: &Value) -> Result>> { /// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live /// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are. fn takes_rounding(live: Option<&LiveShape>) -> bool { - matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. })) + matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. } | LiveShape::Path { .. })) } /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about @@ -175,7 +175,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii", "strokes", "patterns"], "object.setLiveShape", )?; - check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; + check_numbers(p, &["radius", "sides", "points", "ratio"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { None => None, @@ -240,6 +240,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } else { number("sides", |n| n.fract() == 0.0 && (3.0..=1000.0).contains(&n), "a whole number from 3 to 1000")?.map(|n| n as u64) }; + // A star's Star Properties: its point count (a whole number from 2 to 1000, as `shape.star` + // takes it) and its ratio (inner radius over outer radius, above 0 and up to 1). Both are + // checked on replay too: no recording predates them. + let points = number("points", |n| n.fract() == 0.0 && (2.0..=1000.0).contains(&n), "a whole number from 2 to 1000")?.map(|n| n as u64); + let ratio = number("ratio", |r| r > 0.0 && r <= 1.0, "a ratio above 0 and up to 1")?; + // A new point count lays a star's corners out again, so the corners a radius or kind would set + // can't be told from the anchors selected before it. + if points.is_some() && (radius.is_some() || kind.is_some()) { + return Err(bad("object.setLiveShape", "`points` can't be set with `radius` or `kind`: set the corners in a call of their own")); + } // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?); let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true); @@ -292,6 +302,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } else { ids }; + // A ratio is the inner radius over the outer one: a star whose outer radius is 0 has none to set. + if ratio.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).and_then(|n| n.live_shape()), Some(LiveShape::Star { r1, .. }) if *r1 <= 0.0)) + { + return Err(bad("object.setLiveShape", "a star whose outer radius is 0 has no ratio to set")); + } // The lines that Line Length or Line Angle changes, as they become. A line that would reach // past the document's coordinate limit is an error before anything changes. let mut lines = std::collections::BTreeMap::new(); @@ -321,6 +336,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { { return false; } + Some(l @ LiveShape::Star { points: now, .. }) + if !(points.is_none_or(|n| n.clamp(2, 1000) == u64::from(*now)) + && ratio.is_none_or(|r| l.star_ratio().is_some_and(|k| (k - r).abs() < 1e-12))) => + { + return false; + } Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => { return false; } @@ -386,6 +407,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } edited = true; } + if let l @ LiveShape::Star { .. } = &mut new + && (points.is_some() || ratio.is_some()) + { + if let Some(n) = points { + l.set_points(n); + } + if let Some(r) = ratio { + l.set_star_ratio(r); + } + edited = true; + } if let Some(a) = rectangle_angle && let l @ LiveShape::Rectangle { .. } = &mut new { @@ -439,6 +471,14 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { *live = Some(Box::new(new.clone())); *path = new.to_path(); } + // A new point count, or a ratio that changes how many anchors the rounded star draws, lays + // its anchors out again: anchors and segments selected on the old layout would name + // others, or none. + if old.star_points() != new.star_points() || (old.star_points().is_some() && old.to_path().anchor_count() != new.to_path().anchor_count()) + { + sel.anchors.remove(id); + sel.segments.remove(id); + } } for id in &ids { let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; diff --git a/crates/engine/src/tests/css.rs b/crates/engine/src/tests/css.rs index 982bf51d24..3d86e558b6 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -173,12 +173,12 @@ fn export_writes_the_sheet_and_rasterized_art() { // Without a path: the CSS as data, the pictures as base64. let r = run(&mut s, "css.export", json!({"scope": "all", "rasterize": true})); let data = r["data"].as_str().unwrap(); - assert!(data.contains(".rectangle {") && data.contains(".path {\n") && data.contains("background-image: url(path.png);"), "{data}"); + assert!(data.contains(".rectangle {") && data.contains(".star {\n") && data.contains("background-image: url(star.png);"), "{data}"); assert!(data.ends_with("}\n")); assert_eq!(r["rules"], json!(2)); let images = r["images"].as_array().unwrap(); assert_eq!(images.len(), 1, "only the star is rasterized"); - assert_eq!(images[0]["name"], json!("path.png")); + assert_eq!(images[0]["name"], json!("star.png")); let png = vectorcraft_format::base64_decode(images[0]["dataBase64"].as_str().unwrap()).unwrap(); assert!(png.starts_with(b"\x89PNG")); // The selection alone (the star, selected last). @@ -263,9 +263,9 @@ fn export_to_a_path_puts_the_pictures_next_to_the_sheet() { let path = dir.join("site.css"); let r = run(&mut s, "css.export", json!({"path": path.to_string_lossy(), "rasterize": true})); let written = std::fs::read_to_string(&path).unwrap(); - assert!(written.contains("url(path.png)"), "{written}"); + assert!(written.contains("url(star.png)"), "{written}"); assert_eq!(r["bytes"], json!(written.len())); - let png = dir.join("path.png"); + let png = dir.join("star.png"); assert_eq!(r["images"], json!([png.to_string_lossy()])); assert!(std::fs::read(&png).unwrap().starts_with(b"\x89PNG")); std::fs::remove_dir_all(&dir).ok(); diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 7f46a8edcd..529fe0faf1 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -334,7 +334,7 @@ fn corners_of_a_non_square_rectangle_are_alike_circles() { assert_spans(&s, id, [8.0; 4]); } -/// A selected five-pointed star at (200, 200) of radii 60 and 30: a plain path. +/// A selected five-pointed live star at (200, 200) of radii 60 and 30. fn star(s: &mut Session) -> NodeId { NodeId(s.execute("shape.star", &json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap()) } @@ -357,8 +357,8 @@ fn radii(s: &Session, id: NodeId) -> [f64; N] { std::array::from_fn(|k| c.radius(k)) } -/// #511: a star (a plain path) rounds all ten corners as one step, keeps them editable (a new -/// radius cuts the outline again rather than the cut path), and is the plain star again at 0. +/// #511: a live star rounds all ten corners as one step, keeps them editable (a new radius cuts +/// the outline again rather than the cut path), and is the sharp star again at 0. #[test] fn a_star_rounds_its_corners_and_keeps_them_live() { let (mut s, _) = session(); @@ -370,17 +370,75 @@ fn a_star_rounds_its_corners_and_keeps_them_live() { assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); let (path, live) = node_path(&s, id); assert_eq!(path.anchor_count(), 20); - assert!(matches!(&live, Some(LiveShape::Path { base, .. }) if *base == sharp), "{live:?}"); + assert!(matches!(&live, Some(l @ LiveShape::Star { points: 5, .. }) if l.polygon_outline() == sharp), "{live:?}"); assert_eq!(style(&s, id), (Some(4.0), Some(CornerKind::Round), 10)); - assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Path"); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Star"); run(&mut s, json!({"radius": 6, "kind": "chamfer"})); assert_eq!((node_path(&s, id).0.anchor_count(), style(&s, id)), (20, (Some(6.0), Some(CornerKind::Chamfer), 10))); run(&mut s, json!({"radius": 0, "kind": "round"})); - assert_eq!(node_path(&s, id), (sharp, None)); + let (path, live) = node_path(&s, id); + assert_eq!(path, sharp); + assert!(matches!(&live, Some(LiveShape::Star { radii, kinds, .. }) if radii.is_empty() && kinds.is_empty()), "{live:?}"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(style(&s, id).0, Some(6.0)); } +/// #4339: a live star takes a new point count and ratio from `object.setLiveShape` in one undo +/// step each, keeps the corner radius its corners shared, and records nothing when the values +/// are the ones it has. A count or ratio out of range is an error that changes nothing. +#[test] +fn a_live_star_takes_a_new_point_count_and_ratio() { + let (mut s, _) = session(); + let id = star(&mut s); + assert_eq!(node_path(&s, id).0.anchor_count(), 10); + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, json!({"points": 8})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let (path, live) = node_path(&s, id); + assert_eq!(path.anchor_count(), 16); + assert_eq!(live.as_ref().and_then(LiveShape::star_points), Some(8)); + // The same count again: no undo step. + run(&mut s, json!({"points": 8})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + run(&mut s, json!({"ratio": 0.25})); + let (_, live) = node_path(&s, id); + assert!(matches!(live, Some(LiveShape::Star { r1, r2, .. }) if r1 == 60.0 && (r2 - 15.0).abs() < 1e-9)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 2); + // The shared corner radius spreads to the new corners. + run(&mut s, json!({"radius": 3})); + run(&mut s, json!({"points": 6})); + assert_eq!(style(&s, id), (Some(3.0), Some(CornerKind::Round), 12)); + for bad in [ + json!({"points": 1}), + json!({"points": 1001}), + json!({"points": 5.5}), + json!({"ratio": 1.5}), + json!({"ratio": -0.1}), + json!({"ratio": 0}), + json!({"points": 7, "radius": 2}), + ] { + let before = node_path(&s, id); + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + assert_eq!(node_path(&s, id), before, "{bad}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let (path, live) = node_path(&s, id); + assert_eq!(path.anchor_count(), 10); + assert_eq!(live.as_ref().and_then(LiveShape::star_points), Some(5)); + // Anchors selected on the old layout are dropped with a new point count. + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 8]], "mode": "set"})).unwrap(); + run(&mut s, json!({"id": id.0, "points": 3})); + assert_eq!(selected_anchors(&s, id), None); + // A star whose outer radius is 0 has no ratio to set. + let flat = NodeId(s.execute("shape.star", &json!({"cx": 50, "cy": 50, "radius1": 0, "radius2": 10})).unwrap()["id"].as_u64().unwrap()); + let before = node_path(&s, flat); + assert!(s.execute("object.setLiveShape", &json!({"id": flat.0, "ratio": 0.5})).is_err()); + assert_eq!(node_path(&s, flat), before); +} + /// Each corner stops at its own limit: its cut reaches halfway along its shorter side, so a /// star's neighbouring corners meet without overlapping. #[test] @@ -389,7 +447,8 @@ fn star_corners_stop_at_their_own_limit() { let id = star(&mut s); run(&mut s, json!({"radius": 1000})); let (path, live) = node_path(&s, id); - let Some(LiveShape::Path { base, .. }) = live else { panic!("live corners") }; + let Some(l @ LiveShape::Star { .. }) = live else { panic!("live corners") }; + let base = l.polygon_outline(); // Every cut ends at the middle of a side: each side's two cuts meet there. let sp = &base.subpaths[0]; for (i, a) in sp.anchors.iter().enumerate() { diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index a616d748d1..4a56421f69 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -48,7 +48,9 @@ pub(in crate::ai_editing) const SYMBOL_COUNT: &str = "symbols past 4,096 are lef pub(super) fn redrawn(n: &Node) -> bool { let rounded = |l: &vectorcraft_doc::LiveShape| match l { vectorcraft_doc::LiveShape::Rectangle { radii, .. } => radii.iter().any(|r| *r > 0.0), - vectorcraft_doc::LiveShape::Polygon { radii, .. } | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0), + vectorcraft_doc::LiveShape::Polygon { radii, .. } + | vectorcraft_doc::LiveShape::Star { radii, .. } + | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0), vectorcraft_doc::LiveShape::Ellipse { .. } | vectorcraft_doc::LiveShape::Line { .. } => false, }; match &n.kind { diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index d37715f9b9..fca1b86de3 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -805,7 +805,12 @@ fn corners(path: &PathData, live: Option<&LiveShape>) -> Option { (sweep < 1e-6 || (sweep - 360.0).abs() < 1e-6).then_some(Corners::Ellipse) } Some( - LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Line { .. } | LiveShape::Path { .. }, + LiveShape::Rectangle { .. } + | LiveShape::Ellipse { .. } + | LiveShape::Polygon { .. } + | LiveShape::Star { .. } + | LiveShape::Line { .. } + | LiveShape::Path { .. }, ) => None, None => is_upright_rectangle(path).then_some(Corners::Square), } diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index e4f4b272c5..70d49e870e 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -191,6 +191,33 @@ impl CustomShape { radii_relative: *radii_relative, }) } + CustomShape::Polygon { + radius, + sides, + xf, + radii, + kinds, + radii_relative, + spoke_ratio: Some(ratio), + rounded, + randomized, + pie, + arc_mode, + } if (0.01..=1.0).contains(ratio) && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole && { + let span = (pie.1 - pie.0).rem_euclid(360.0); + span < 1e-9 || 360.0 - span < 1e-9 + } => + { + Some(LiveShape::Star { + r1: *radius, + r2: (*radius * ratio.clamp(0.01, 1.0)).max(0.01), + points: *sides, + xf: *xf, + radii: radii.clone(), + kinds: kinds.clone(), + radii_relative: *radii_relative, + }) + } _ => None, } } @@ -294,6 +321,26 @@ impl CustomShape { }; Some(CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode }) } + LiveShape::Star { r1, r2, points, xf, radii, kinds, radii_relative } => { + let (rounded, randomized, pie, arc_mode) = match stored { + Some(CustomShape::Polygon { rounded, randomized, pie, arc_mode, .. }) => (rounded, randomized, pie, arc_mode), + _ => (0.0, 0.0, (0.0, 360.0), EllipseMode::Whole), + }; + let spoke_ratio = Some(if r1 > 0.0 { r2 / r1 } else { 0.0 }); + Some(CustomShape::Polygon { + radius: r1, + sides: points, + xf, + radii, + kinds, + radii_relative, + spoke_ratio, + rounded, + randomized, + pie, + arc_mode, + }) + } LiveShape::Line { .. } | LiveShape::Path { .. } => stored, } } diff --git a/crates/tools/src/sidewidget.rs b/crates/tools/src/sidewidget.rs index 361430dcf5..82668516c7 100644 --- a/crates/tools/src/sidewidget.rs +++ b/crates/tools/src/sidewidget.rs @@ -6,6 +6,10 @@ //! `object.setLiveShape`'s `sides` in one undo step, and none when the count ends where it began. //! The Selection tool and the shape tools that show the box hit the widget, and the canvas draws it //! from the same geometry. +//! +//! A live star shows the same widget +//! (): +//! its drag sends `points`, from 3 to 20, with the same rule for a count past either end. use serde_json::json; use vectorcraft_doc::{Document, LiveShape, NodeId, NodeKind, OrientedBox, Selection}; @@ -27,35 +31,45 @@ pub const STEP_PX: f64 = 12.0; pub const MIN_SIDES: u32 = 3; /// The most sides a drag gives. pub const MAX_SIDES: u32 = 11; +/// The fewest points a drag gives a star. +pub const MIN_POINTS: u32 = 3; +/// The most points a drag gives a star. +pub const MAX_POINTS: u32 = 20; -/// The side widget of a selection that is exactly one editable live polygon. +/// The side widget of a selection that is exactly one editable live polygon or star. #[derive(Clone, Copy, Debug, PartialEq)] pub struct SideWidget { pub id: NodeId, /// Center in document coordinates. pub at: Point, - /// The polygon's side count. + /// The polygon's side count, or the star's point count. pub sides: u32, + /// The shape is a star: the drag sets its points (3 to 20) instead of a polygon's sides. + pub star: bool, } impl SideWidget { /// The widget beside `bx`, the selection's bounding box, at `zoom` (screen px per document - /// point). None unless the selection is one whole editable live polygon, with no anchors or - /// segments of it selected. + /// point). None unless the selection is one whole editable live polygon or star, with no + /// anchors or segments of it selected. pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option { let [id] = selection.objects[..] else { return None }; if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !zoom.is_finite() || zoom <= 0.0 { return None; } let NodeKind::Path { live, .. } = &doc.node(id)?.kind else { return None }; - let Some(LiveShape::Polygon { sides, .. }) = live.as_deref() else { return None }; + let (sides, star) = match live.as_deref() { + Some(LiveShape::Polygon { sides, .. }) => (*sides, false), + Some(LiveShape::Star { points, .. }) => (*points, true), + _ => return None, + }; // After the kind: on a locked artboard it measures the art of the layer object holding `id`. if !doc.is_editable(id) { return None; } let r = bx.rect; let at = bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y); - (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides }) + (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides, star }) } /// The widget the tool can drag (its bounding box and the shape widgets showing). @@ -82,15 +96,35 @@ pub fn over_widget(cx: &ToolContext, p: Point) -> bool { /// The side count a drag of `steps` (down positive) gives a polygon of `from` sides: within 3 to 11, /// and `from` itself while a polygon of more than 11 sides has not been dragged up. pub fn sides_after(from: u32, steps: i64) -> u32 { - let (min, max) = (i64::from(MIN_SIDES), i64::from(MAX_SIDES)); - let to = if from <= MAX_SIDES { - i64::from(from).saturating_add(steps) - } else if steps >= 0 { - return from; + count_after(from, steps, MIN_SIDES, MAX_SIDES) +} + +/// The point count a drag of `steps` (down positive) gives a star of `from` points: within 3 to 20, +/// and `from` itself while a star of more than 20 points has not been dragged up, or a star of +/// fewer than 3 has not been dragged down. +pub fn points_after(from: u32, steps: i64) -> u32 { + count_after(from, steps, MIN_POINTS, MAX_POINTS) +} + +/// A count a drag of `steps` gives from `from`, within `min` to `max`. A count past `max` stays +/// until the drag goes up a step, which gives `max`; one below `min` stays until it goes down a +/// step, which gives `min`. +fn count_after(from: u32, steps: i64, min: u32, max: u32) -> u32 { + let (lo, hi) = (i64::from(min), i64::from(max)); + let to = if from > max { + if steps >= 0 { + return from; + } + (hi + 1).saturating_add(steps) + } else if from < min { + if steps <= 0 { + return from; + } + (lo - 1).saturating_add(steps) } else { - (max + 1).saturating_add(steps) + i64::from(from).saturating_add(steps) }; - to.clamp(min, max) as u32 + to.clamp(lo, hi) as u32 } /// Dragging the side widget. @@ -139,7 +173,7 @@ impl SideDrag { return vec![]; } // The cast saturates: an infinite count of steps becomes i64::MAX or i64::MIN. - let sides = sides_after(self.widget.sides, steps as i64); + let sides = if self.widget.star { points_after(self.widget.sides, steps as i64) } else { sides_after(self.widget.sides, steps as i64) }; if sides == self.sides { return vec![]; } @@ -149,7 +183,8 @@ impl SideDrag { out.push(Action::Begin("Live Shape".into())); } self.sides = sides; - out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, "sides": sides }))); + let key = if self.widget.star { "points" } else { "sides" }; + out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, key: sides }))); out } @@ -172,7 +207,8 @@ impl SideDrag { if !self.moved || !cx.measurement_labels { return vec![]; } - vec![Overlay::Measure { p: self.at, text: format!("Sides: {}", self.sides) }] + let label = if self.widget.star { "Points" } else { "Sides" }; + vec![Overlay::Measure { p: self.at, text: format!("{label}: {}", self.sides) }] } } @@ -188,7 +224,17 @@ mod tests { /// A document holding a live polygon of `sides` sides and radius 100 placed by `xf`, and a /// selection of it. fn polygon_doc(sides: u32, xf: Affine) -> (Document, NodeId, Selection) { - let live = LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + shape_doc(LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }) + } + + /// A document holding a live star of `points` points, radii 100 and 50, placed by `xf`, and a + /// selection of it. + fn star_doc(points: u32, xf: Affine) -> (Document, NodeId, Selection) { + shape_doc(LiveShape::Star { r1: 100.0, r2: 50.0, points, xf, radii: vec![], kinds: vec![], radii_relative: false }) + } + + /// A document holding the live shape `live`, and a selection of it. + fn shape_doc(live: LiveShape) -> (Document, NodeId, Selection) { let mut d = Document::new(800.0, 800.0); let l = d.layers[0].id; let id = d.alloc_id(); @@ -226,6 +272,42 @@ mod tests { assert_eq!(sides_after(1000, -100), 3); } + #[test] + fn a_star_s_counts_stay_within_three_and_twenty() { + assert_eq!(points_after(5, 1), 6); + assert_eq!(points_after(5, 100), 20); + assert_eq!(points_after(5, -100), 3); + assert_eq!(points_after(20, i64::MAX), 20); + // Over 20: unchanged until the drag goes up, which gives 20. + assert_eq!(points_after(40, 3), 40); + assert_eq!(points_after(40, -1), 20); + // Under 3 (a two-point star): unchanged until the drag goes down, which gives 3. + assert_eq!(points_after(2, 0), 2); + assert_eq!(points_after(2, -4), 2); + assert_eq!(points_after(2, 1), 3); + assert_eq!(points_after(2, 2), 4); + assert_eq!(points_after(2, i64::MIN), 2); + } + + /// A live star shows the widget, and dragging it down a step gives the star a point, in one + /// undo step, with the count beside the pointer. + #[test] + fn dragging_a_star_s_widget_down_adds_a_point() { + let (d, id, s) = star_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).expect("a widget on a live star"); + assert_eq!((w.id, w.sides, w.star), (id, 5, true)); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + let to = w.at + vectorcraft_geom::Vec2::new(0.0, STEP_PX + 1.0); + let out = t.pointer(&c, &ev(PointerKind::Drag, to)); + assert_eq!(out[0], Action::Begin("Live Shape".into())); + assert!(matches!(&out[1], Action::Preview(cmd, v) if cmd == "object.setLiveShape" && *v == json!({ "id": id.0, "points": 6 })), "{out:?}"); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Points: 6"))); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, to)), vec![Action::Commit]); + } + #[test] fn the_longest_drags_stay_within_three_and_eleven() { assert_eq!(sides_after(5, i64::MAX), 11); diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 29b5962d3e..f3a6bc366a 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -311,7 +311,7 @@ mod tests { set(&app, "radius", json!(5)); confirm(&mut app); let n = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().clone(); - assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(&**l, LiveShape::Star { radii, .. } if !radii.is_empty()))); assert_eq!(crate::panels::corner_radius(&app, &n), Some(5.0)); } diff --git a/crates/ui-egui/src/panels/tests_css_properties.rs b/crates/ui-egui/src/panels/tests_css_properties.rs index af606593c0..3c4e17cfba 100644 --- a/crates/ui-egui/src/panels/tests_css_properties.rs +++ b/crates/ui-egui/src/panels/tests_css_properties.rs @@ -75,13 +75,13 @@ fn copy_and_export_go_through_the_ui_commands() { app.run("shape.star", json!({"cx": 100, "cy": 50, "radius1": 30, "radius2": 15})).unwrap(); let r = app.run("css.exportFile", json!({"path": "/tmp/site/site.css", "scope": "all", "rasterize": true})).unwrap(); assert_eq!(r["rules"], json!(2)); - let png = std::path::Path::new("/tmp/site").join("path.png").to_string_lossy().into_owned(); + let png = std::path::Path::new("/tmp/site").join("star.png").to_string_lossy().into_owned(); assert_eq!(r["images"], json!([png])); let log = log.borrow(); let names: Vec<&str> = log.iter().map(|(p, _)| p.as_str()).collect(); assert_eq!(names, ["/tmp/site/site.css", png.as_str()]); let css = String::from_utf8(log[0].1.clone()).unwrap(); - assert!(css.contains(".rectangle {") && css.contains("background-image: url(path.png);"), "{css}"); + assert!(css.contains(".rectangle {") && css.contains("background-image: url(star.png);"), "{css}"); assert!(log[1].1.starts_with(b"\x89PNG")); } diff --git a/crates/ui-egui/src/panels/transform/shape.rs b/crates/ui-egui/src/panels/transform/shape.rs index 8530a90390..d493cdee9c 100644 --- a/crates/ui-egui/src/panels/transform/shape.rs +++ b/crates/ui-egui/src/panels/transform/shape.rs @@ -1,5 +1,5 @@ -//! The Transform panel's live-shape rows: the Rectangle, Polygon, Ellipse and Line Properties, also shown by the -//! Properties panel and the Contextual Task Bar. +//! The Transform panel's live-shape rows: the Rectangle, Polygon, Star, Ellipse and Line Properties, also shown by +//! the Properties panel and the Contextual Task Bar. use std::ops::RangeInclusive; @@ -28,6 +28,8 @@ enum Quantity { Degrees, /// A length in the document's general unit. Length, + /// A fraction from 0.001 to 1, three decimals. + Ratio, } /// The side counts Polygon Properties' Sides slider spans; the field beside it takes 3 to 1000. @@ -44,6 +46,7 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l corner_radius_row(app, ui, n); }), LiveShape::Polygon { .. } => under_heading(ui, headed.then(|| tl!("Polygon Properties:")), |ui| polygon_rows(app, ui, n, live)), + LiveShape::Star { .. } => under_heading(ui, headed.then(|| tl!("Star Properties:")), |ui| star_rows(app, ui, live)), LiveShape::Ellipse { pie, .. } => under_heading(ui, Some(tl!("Ellipse Properties:")), |ui| { angle_row(app, ui, live, "ellipseAngle"); pie_rows(app, ui, *pie); @@ -79,6 +82,7 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value: let field = match quantity { Quantity::Length => NumberField::length(label, bind, general_lengths(app)), Quantity::Degrees => NumberField::new(label, bind).unit("°").commit_decimals(1), + Quantity::Ratio => NumberField::new(label, bind).range(0.001..=1.0).step(0.001).commit_decimals(3), }; edit = Some(field.show(ui).edit); }); @@ -197,12 +201,17 @@ fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShap /// one undo step; Escape during the drag puts the count back. A click on the rail or an arrow key sets the count in /// one undo step. A count above 20 puts the thumb at the rail's right end, and screen readers read the real count. fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32) { - let label = tl!("Sides"); + count_row(app, ui, tl!("Sides"), "sides", sides, 3.0); +} + +/// A count row (Polygon Properties' Sides, Star Properties' Points) whose edits set `key`: a field that takes `min` +/// to 1000 and a slider over [`SIDES_SLIDER`], as [`sides_row`] describes. +fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'static str, sides: u32, min: f64) { let count = f64::from(sides); let (mut typed, mut slid) = (None, None); Field::new(label).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - typed = Some(NumberField::new(label, Bind::given(Some(count))).range(3.0..=1000.0).fixed_decimals(0).id_salt("field").show(ui).edit); + typed = Some(NumberField::new(label, Bind::given(Some(count))).range(min..=1000.0).fixed_decimals(0).id_salt("field").show(ui).edit); let (lo, hi) = (*SIDES_SLIDER.start(), *SIDES_SLIDER.end()); slid = Some( Slider::new(Bind::given(count.clamp(lo, hi)), SIDES_SLIDER) @@ -218,17 +227,26 @@ fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32) { if let Some(edit) = typed { apply_edits(app, &edit, EditPath::Scope, |app, v, _| { if let Some(v) = v { - set_live_shape(app, json!({ "sides": *v as u64 })); + set_live_shape(app, json!({ key: *v as u64 })); } }); } if let Some(edit) = slid { apply_edits(app, &edit, EditPath::Preview, |app, v, phase| { - crate::panels::live_run(app, "Live Shape Properties", "object.setLiveShape", json!({ "sides": v.round() as u64 }), phase); + crate::panels::live_run(app, "Live Shape Properties", "object.setLiveShape", json!({ key: v.round() as u64 }), phase); }); } } +/// A live star's Star Properties: its point count (a field that takes 2 to 1000 and a slider over 3 to 20) and its +/// ratio (inner radius over outer radius, 0.001 to 1). Its corners stay with Live Corners and Direct Selection, as any +/// path's do. +fn star_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) { + let Some(points) = live.star_points() else { return }; + count_row(app, ui, tl!("Points"), "points", points, 2.0); + number_row(app, ui, tl!("Ratio"), live.star_ratio(), Quantity::Ratio, |r| json!({ "ratio": r })); +} + /// The polygon's Corner type select, blank while `kind` is `None` (the corners differ), one number cell wide as the /// number fields of its column are. fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, kind: Option) { diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index fa4b550289..0ce3c2e78a 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -1133,6 +1133,35 @@ fn polygon_app(sides: u32) -> VectorcraftApp { app } +/// The selected live star's point count and ratio. +fn star_points(app: &VectorcraftApp) -> (u32, f64) { + let l = first_selected(app).unwrap().live_shape().cloned(); + match l { + Some(l @ LiveShape::Star { points, .. }) => (points, l.star_ratio().unwrap()), + k => panic!("{k:?}"), + } +} + +/// Star Properties' Points field sets a live star's point count past the slider's 20, and its Ratio field sets the +/// inner radius against the outer one, each in one undo step. +#[test] +fn star_points_and_ratio_fields_edit_a_live_star() { + use craft::ui::contract::Role; + let mut app = new_app(); + app.run("shape.star", json!({"cx": 150, "cy": 150, "radius1": 50, "radius2": 25, "points": 5})).unwrap(); + let mut p = Panel::new(app, show); + assert_eq!(p.value_role("Points", Role::SLIDER).as_deref(), Some("5")); + let depth = undo_depth(&p.app()); + p.type_into("Points", "12"); + assert_eq!(star_points(&p.app()).0, 12); + assert_eq!(undo_depth(&p.app()), depth + 1); + p.type_into("Ratio", "0.3"); + let (points, ratio) = star_points(&p.app()); + assert_eq!(points, 12); + assert!((ratio - 0.3).abs() < 1e-9, "{ratio}"); + assert_eq!(undo_depth(&p.app()), depth + 2); +} + fn undo_depth(app: &VectorcraftApp) -> usize { app.session.doc().unwrap().history.undo.len() } diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 1995432740..85ebc411b1 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -546,7 +546,7 @@ fn selection_kinds_offer_their_actions() { let s = id(app.run("shape.star", json!({"cx": 300, "cy": 150, "radius1": 40})).unwrap()); select(app, &[s]); app.run("object.setLiveShape", json!({"radius": 4})).unwrap(); - assert!(matches!(live(app, s), vectorcraft_doc::LiveShape::Path { .. })); + assert!(matches!(live(app, s), vectorcraft_doc::LiveShape::Star { radii, .. } if !radii.is_empty())); }, &["lock"], &["shapeProperties"], diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 06d6651315..6bea16b5e5 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -259,10 +259,13 @@ fn polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs() { app.select_tool(tool); } let view = app.view_info(); + // Each round starts clear of the last shape, whose center point and side widget (a live + // star's too) take a press. + let (dx, dy) = [(0.0, 0.0), (150.0, 150.0), (0.0, 180.0)][round]; for (kind, x, y) in [ - (vectorcraft_tools::PointerKind::Down, 50.0, 50.0), - (vectorcraft_tools::PointerKind::Drag, 90.0, 90.0), - (vectorcraft_tools::PointerKind::Up, 90.0, 90.0), + (vectorcraft_tools::PointerKind::Down, 50.0 + dx, 50.0 + dy), + (vectorcraft_tools::PointerKind::Drag, 90.0 + dx, 90.0 + dy), + (vectorcraft_tools::PointerKind::Up, 90.0 + dx, 90.0 + dy), ] { app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, x, y), view).unwrap(); } diff --git a/docs/mcp.md b/docs/mcp.md index 30ac0bfb82..eb9f0c2de6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10000,7 +10000,11 @@ The same command sets the rest of a live shape's properties, as the Properties a polygon (Polygon Properties): `sides` (3–1000), `polygonAngle` (degrees counterclockwise, its first vertex straight up at 0), `polygonRadius` (pt, centre to vertex), `sideLength` (pt, which sets the radius) and `makeSidesEqual: true`, which drops an uneven scale or shear (its sides then differ) and keeps its centre, angle and mean radius; a radius or -length that isn't a number above 0 is an error. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees +length that isn't a number above 0 is an error. A star drawn with the Star tool or `shape.star` stays live (Star +Properties): `points` (a whole number from 2 to 1000; its corners keep the radius and kind they shared) and `ratio` +(its inner radius over its outer radius, above 0 and up to 1; the outer radius stays); any other count or ratio is an error, and a +count or ratio the star already has adds no undo step. A change to the point count or drawn anchor count drops the star's selected anchors and segments; +`points` with `radius` or `kind` in one call is an error, and so is a `ratio` for a star whose outer radius is 0. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. `constrainPie: true` with one of `pieStart` and `pieEnd` (the panels' Constrain Pie Angle link) moves the other angle by as much, so each selected ellipse keeps its own span, counterclockwise from its start to its end; a whole ellipse diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 594d6de35b..adc14865cb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1656,6 +1656,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_without_live_corners_adds_no_undo_step`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). + - **Live stars:** a star drawn with the Star tool or `shape.star` stays a live shape (#4339), so its point count and ratio stay editable after it is drawn, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-stars.html) describes. A selected live star shows the side widget; its drag sets the point count from 3 to 20, and a star of more than 20 points keeps its count until the drag goes up. Star Properties in the Transform panel and the Properties panel's Transform section have a Points field (2 to 1000) with a slider over 3 to 20, and a Ratio field (inner radius over outer radius, 0.001 to 1). The command accepts a ratio above 0 and up to 1. Both send `object.setLiveShape {points, ratio}`, one undo step each, and a value the star already has adds none. Live Corners round a live star's corners and keep them through a new point count. The widget's range below 3 points, the field's lower limit of 2 and the Ratio field are VectorCraft's own (tests `a_live_star_takes_a_new_point_count_and_ratio`, `dragging_a_star_s_widget_down_adds_a_point`, `star_points_and_ratio_fields_edit_a_live_star`). - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}` and its release adds one undo step; Escape during the drag puts the count back and adds no undo step. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). From 0ee50df549d1c7327320f21029b34bf062632d38 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:14:04 -0800 Subject: [PATCH 052/103] Scripts: a print batch sent after a spool failure clears that failure A script's print batch that the desktop's worker sends without a failure now clears the spool failures reported before it was submitted, instead of keeping them in the status bar. A failure reported after the batch was submitted stays, and so do the status bar's other hover notes, such as a startup script's error. While the later batch prints, the earlier failure stays in the hover notes. Each failure is tracked by its own count, so a repeated failure with the same text is not cleared by a batch submitted before it. --- crates/ui-egui/src/io/save.rs | 1 + crates/ui-egui/src/print.rs | 70 +++++++++++++++++++++--- crates/ui-egui/src/script_runs.rs | 14 ++++- crates/ui-egui/src/state.rs | 10 ++++ crates/ui-egui/src/tests/script_print.rs | 32 ++++++++++- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 7 files changed, 118 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 1c82a3a7d7..1990d57e06 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -960,6 +960,7 @@ pub(crate) fn notes_of(r: &Value) -> Vec { /// hover ([`crate::state::UiState::status_notes`]). Without notes nothing is kept. pub(crate) fn show_with_notes(app: &mut VectorcraftApp, status: String, notes: Vec) { app.status(status); + app.ui.script_print_failure_notes.clear(); app.ui.status_notes = (!notes.is_empty()).then(|| (app.ui.status.clone(), notes)); } diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 5276329c86..9046170b98 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -353,7 +353,10 @@ const NO_SCRIPT_PRINTING: &str = "Printing from scripts is not available here: t const SCRIPT_PRINT_FAILED: &str = "Printing from a script failed"; /// Sends the jobs a script prepared, which the person approved, each to its printer. Every printer -/// must still be one the service lists, by its exact name, or no job is sent. → `{sent}`, or +/// must still be one the service lists, by its exact name, or no job is sent. When the desktop's +/// worker sends them all, the status bar drops the failures of batches that failed before these +/// were submitted and keeps its other hover notes; it shows a failure reported since then, or else +/// the last job's note. → `{sent}`, or /// `{background: true}` while the desktop's worker sends them. pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec) -> Result { let service = app.services.print.as_mut().filter(|s| s.scripts_may_print()).ok_or(NO_SCRIPT_PRINTING)?; @@ -363,6 +366,7 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec= 64 { + let (_, index) = failures.remove(0); + if kept.get(index).is_some_and(|n| n.starts_with(SCRIPT_PRINT_FAILED)) { + kept.remove(index); + } + for (_, i) in &mut failures { + if *i > index { + *i -= 1; + } + } + } + for (_, i) in &mut failures { + *i += 1; + } kept.insert(0, failure.clone()); + failures.push((app.ui.script_print_failures, 0)); io::show_with_notes(app, failure, kept); + app.ui.script_print_failure_notes = failures; })?; - let failed = app.ui.status_notes.clone().filter(|(_, notes)| notes.iter().any(|n| n.starts_with(SCRIPT_PRINT_FAILED))); - if let Some((status, kept)) = failed { - io::show_with_notes(app, status, kept); - } else if !app.ui.status.starts_with(SCRIPT_PRINT_FAILED) { - app.status(notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default()); + let noted = app.ui.status_notes.as_ref().is_some_and(|(_, notes)| notes.iter().any(|n| n.starts_with(SCRIPT_PRINT_FAILED))); + if !noted { + app.ui.script_print_failure_notes.clear(); + if !app.ui.status.starts_with(SCRIPT_PRINT_FAILED) { + app.status(notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default()); + } + return Ok(json!({ "sent": count })); } + let mut kept = app.ui.status_notes.take().map(|(_, notes)| notes).unwrap_or_default(); + let mut failures = std::mem::take(&mut app.ui.script_print_failure_notes); + let mut stale: Vec = failures.iter().filter(|(id, _)| *id <= failed_before).map(|(_, i)| *i).collect(); + failures.retain(|(id, _)| *id > failed_before); + stale.sort_unstable(); + for index in stale.into_iter().rev() { + if !kept.get(index).is_some_and(|n| n.starts_with(SCRIPT_PRINT_FAILED)) { + continue; + } + kept.remove(index); + for (_, i) in &mut failures { + if *i > index { + *i -= 1; + } + } + } + if let Some(failure) = kept.iter().find(|n| n.starts_with(SCRIPT_PRINT_FAILED)).cloned() { + io::show_with_notes(app, failure, kept); + } else { + let note = notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default().to_string(); + if !note.is_empty() && !kept.is_empty() { + kept.insert(0, note.clone()); + } + match kept.first().cloned() { + Some(first) => io::show_with_notes(app, first, kept), + None => app.status(note), + } + } + app.ui.script_print_failure_notes = failures; Ok(json!({ "sent": count })) }, ); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index eedac25ef3..d4c44e6847 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -196,13 +196,23 @@ fn end_round(app: &mut VectorcraftApp) { return; } let mut notes = std::mem::take(&mut app.ui.startup_notes); + let mut failures = Vec::new(); match app.ui.status_notes.take() { - Some((status, more)) if status == app.ui.status && more == notes => {} - Some((status, more)) if status == app.ui.status && !more.is_empty() => notes.extend(more), + Some((status, more)) if status == app.ui.status && more == notes => { + failures = std::mem::take(&mut app.ui.script_print_failure_notes); + } + Some((status, more)) if status == app.ui.status && !more.is_empty() => { + failures = std::mem::take(&mut app.ui.script_print_failure_notes); + for (_, i) in &mut failures { + *i += notes.len(); + } + notes.extend(more); + } _ if app.ui.status.is_empty() || notes.contains(&app.ui.status) => {} _ => notes.push(app.ui.status.clone()), } show_notes(app, notes); + app.ui.script_print_failure_notes = failures; } /// Shows the first of `notes` in the status bar, and keeps them all for its hover, which lists diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 19ef45dbbc..72482cb435 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -724,6 +724,14 @@ pub struct UiState { /// later can tell whether the line it started with is still the latest one. Not saved. #[serde(skip)] pub status_sets: u64, + /// How many batches of a script's print jobs the desktop's worker has failed to send, so that a + /// batch sent later can tell a failure from before it was submitted from one since. Not saved. + #[serde(skip)] + pub script_print_failures: u64, + /// The status bar's hover-note indexes for those failures, each with its count in + /// `script_print_failures`, while those notes are kept. Not saved. + #[serde(skip)] + pub script_print_failure_notes: Vec<(u64, usize)>, /// The Replace Font request behind the status bar's warning ([`ReplaceFontWarning`]). Not saved. #[serde(skip)] pub replace_font_warning: Option, @@ -1532,6 +1540,8 @@ impl Default for UiState { touch_drawing_tool: None, status: String::new(), status_sets: 0, + script_print_failures: 0, + script_print_failure_notes: Vec::new(), replace_font_warning: None, last_find: None, find_action: None, diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 327592a654..06ef8a02fd 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -356,7 +356,8 @@ fn a_sent_batch_does_not_hide_an_earlier_spool_failure() { assert!(app.ui.status.contains("The printer Office is offline"), "{}", app.ui.status); } -/// A spool failure stays visible after the next batch is approved and sent. +/// A spool failure stays visible while the next batch is approved and printing, and that batch +/// clears it once the worker sends it without a new failure. #[test] fn a_batch_submitted_after_a_spool_failure_does_not_hide_it() { let mut app = worker_print_app("The printer Lab is offline"); @@ -373,9 +374,34 @@ fn a_batch_submitted_after_a_spool_failure_does_not_hide_it() { assert!(!asking(&app)); assert!(!app.background.jobs.is_empty(), "the next batch was submitted"); assert_eq!(app.ui.status, "Printing from a script…"); + assert_eq!(app.ui.status_notes, Some((failure.clone(), vec![failure.clone()])), "the failure stays while the batch prints"); crate::background::wait_all(&mut app); - assert_eq!(app.ui.status, failure); - assert_eq!(app.ui.status_notes, Some((failure.clone(), vec![failure]))); + assert!(!app.ui.status.contains("offline"), "{}", app.ui.status); + assert!(!app.ui.status.is_empty()); + assert_eq!(app.ui.status_notes, None); +} + +/// A batch that is sent clears only the failures reported before it was submitted: the same +/// failure reported again since then stays in the status bar and its hover notes. +#[test] +fn a_repeated_spool_failure_keeps_its_own_hover_note() { + let mut app = worker_print_app("The printer Lab is offline"); + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 10.0, "Print"); + crate::background::wait_all(&mut app); + crate::io::show_with_notes(&mut app, "Another operation finished".into(), vec!["Another operation finished".into()]); + crate::print::send_script_prints(&mut app, Vec::new()).unwrap(); + let earlier_batch = std::mem::take(&mut app.background); + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 20.0, "Print"); + crate::background::wait_all(&mut app); + app.background = earlier_batch; + crate::background::wait_all(&mut app); + let failure = app.ui.status.clone(); + assert!(failure.contains("The printer Lab is offline"), "{failure}"); + let notes = &app.ui.status_notes.as_ref().unwrap().1; + assert!(notes.contains(&failure), "{notes:?}"); + assert_eq!(app.ui.script_print_failure_notes.len(), 1); } /// A spool failure keeps the startup scripts' errors in the status bar's hover notes. diff --git a/docs/mcp.md b/docs/mcp.md index 3e8da28cc7..3370f30236 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4914,7 +4914,8 @@ next one starts at the frame after, and a later run that cannot start, the chose status bar. A queued run also waits while the jobs the previous run prepared for a printer wait for Print or Cancel. Each queued run lists the printers listed when the runs were queued; the runs with reason `launch` list no printers, so they cannot print to a printer. A job that fails to spool is reported in the status bar even when a -later run or a later job's note took it. +later run or a later job's note took it. A batch submitted after the failure was reported clears it once the +worker sends that batch; a failure reported after that batch was submitted stays. Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from the prompt shown on quitting, between two runs, drops the runs not yet started, and the status bar says so. While that prompt is open, the next run does not start. Under `--automation-read-root` it reads the folder only when the folder lies inside a read root. With the preference on, `ui.runScript` and `ui.runInstalledScript` still return `script.run`'s reply, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2876fe81b0..22b1a7b092 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1130,7 +1130,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. + - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`); a batch submitted after a spool failure was reported clears it once the worker sends the batch, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. From 7e918324dbb9c7e1ce4829c38848fb047a4cb5df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:25:04 -0800 Subject: [PATCH 053/103] Shapes: a file's polygon side or star point count is kept to 1000 A shape's stored add-on settings read their side or point count from the file with no upper bound, and a live star or polygon made from them took that count as it was, so a document could ask for billions of points. The count is now clamped to 2-1000 when it is read, as the Polygon and Star tools clamp it, the live polygon and star made from it are kept to 3-1000 sides and 2-1000 points, and shapes::star keeps to 1000 points. --- crates/geom/src/shapes.rs | 10 ++++-- crates/tools/src/addons/box3d.rs | 55 ++++++++++++++++++++++++++++++-- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 3a3cc606c5..8550807893 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -455,9 +455,9 @@ pub fn polygon_configured(center: Point, radius: f64, sides: u32, rotation_deg: contour_with_rounding(&pts, rounded) } -/// Star with `points` tips (≥ 2), outer radius `r1`, inner radius `r2`, first tip up. +/// Star with `points` tips (2–1000), outer radius `r1`, inner radius `r2`, first tip up. pub fn star(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64) -> PathData { - let n = points.max(2) * 2; + let n = points.clamp(2, 1000) * 2; let rot = rotation_deg.to_radians(); let pts: Vec = (0..n) .map(|i| { @@ -1485,6 +1485,12 @@ mod tests { assert!((d[0] - 10.0).abs() < 1e-9 && (d[1] - 5.0).abs() < 1e-9); } + #[test] + fn star_keeps_to_a_thousand_points() { + assert_eq!(star(Point::ZERO, 10.0, 5.0, 5000, 0.0).anchor_count(), 2000); + assert_eq!(star(Point::ZERO, 10.0, 5.0, 1, 0.0).anchor_count(), 4); + } + #[test] fn straight_star_five_points() { let r2 = straight_star_inner_radius(100.0, 5); diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index 70d49e870e..4bac9e4fdd 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -35,6 +35,11 @@ fn default_pie() -> (f64, f64) { (0.0, 360.0) } +/// A polygon's sides or a star's points read from a file, clamped as the tools clamp them. +fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(2, 1000)) +} + /// Parse an [`EllipseMode`] from a command or tool option string (`"slice"`/`"pie"`, `"arc"`/`"open"`, /// `"chord"`, `"whole"`/`"full"`/`"closed"`). pub fn parse_arc_mode(s: &str) -> Option { @@ -86,6 +91,9 @@ pub enum CustomShape { }, Polygon { radius: f64, + /// Sides, or a star's points: 2–1000, as the Polygon and Star tools give them; a file's + /// count is clamped when read. + #[serde(deserialize_with = "de_sides")] sides: u32, xf: Affine, #[serde(default)] @@ -184,7 +192,7 @@ impl CustomShape { { Some(LiveShape::Polygon { radius: *radius, - sides: *sides, + sides: (*sides).clamp(3, 1000), xf: *xf, radii: radii.clone(), kinds: kinds.clone(), @@ -211,7 +219,7 @@ impl CustomShape { Some(LiveShape::Star { r1: *radius, r2: (*radius * ratio.clamp(0.01, 1.0)).max(0.01), - points: *sides, + points: (*sides).clamp(2, 1000), xf: *xf, radii: radii.clone(), kinds: kinds.clone(), @@ -806,3 +814,46 @@ impl Tool for Box3dTool { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn read_back(spoke_ratio: Option, sides: u64) -> CustomShape { + let shape = CustomShape::Polygon { + radius: 10.0, + sides: 5, + xf: Affine::IDENTITY, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio, + rounded: 0.0, + randomized: 0.0, + pie: (0.0, 360.0), + arc_mode: EllipseMode::Whole, + }; + let mut v = serde_json::to_value(&shape).unwrap_or_default(); + v["sides"] = json!(sides); + serde_json::from_value(v).unwrap_or_else(|e| panic!("{e}")) + } + + #[test] + fn a_file_point_count_is_clamped_as_the_tools_clamp_it() { + let star = read_back(Some(0.5), u64::from(u32::MAX)); + let CustomShape::Polygon { sides, .. } = &star else { panic!("a polygon") }; + assert_eq!(*sides, 1000); + let CustomShape::Polygon { sides, .. } = read_back(None, 0) else { panic!("a polygon") }; + assert_eq!(sides, 2); + let Some(LiveShape::Star { points, .. }) = star.to_live_shape() else { panic!("a live star") }; + assert_eq!(points, 1000); + assert_eq!(star.to_path().anchor_count(), 2000); + let polygon = read_back(None, u64::from(u32::MAX)); + let Some(LiveShape::Polygon { sides, .. }) = polygon.to_live_shape() else { panic!("a live polygon") }; + assert_eq!(sides, 1000); + let Some(LiveShape::Polygon { sides, .. }) = read_back(None, 0).to_live_shape() else { panic!("a live polygon") }; + assert_eq!(sides, 3); + let Some(LiveShape::Star { points, .. }) = read_back(Some(0.5), 0).to_live_shape() else { panic!("a live star") }; + assert_eq!(points, 2); + } +} From c1db0d8bf071dbb1a9a0976a27adb4a8fad43ed6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:04:02 -0800 Subject: [PATCH 054/103] Scripts: queued print batches keep the other hover notes When two batches are sent after a spool failure that shared the status bar's hover notes with another error, such as a startup script's, the first batch cleared the failure and the second replaced the status line alone, so the status bar hid the remaining notes. The second batch now keeps those notes and replaces the first batch's note at their head instead of adding another. The repeated-failure test now keeps both identical failures in its fixture and checks that one copy stays after the batch is sent. --- crates/ui-egui/src/print.rs | 24 ++++++++++++++++++- crates/ui-egui/src/state.rs | 5 ++++ crates/ui-egui/src/tests/script_print.rs | 30 ++++++++++++++++++++++-- 3 files changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 9046170b98..8e7c4d5061 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -411,7 +411,28 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec { + if !note.is_empty() { + if kept.len() > 1 && kept.first() == app.ui.script_print_receipt.as_ref() { + kept.remove(0); + } + kept.insert(0, note.clone()); + app.ui.script_print_receipt = Some(note); + } + if let Some(first) = kept.first().cloned() { + io::show_with_notes(app, first, kept); + } + } + None => app.status(note), + } } return Ok(json!({ "sent": count })); } @@ -437,6 +458,7 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec io::show_with_notes(app, first, kept), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 72482cb435..3c48fc52a9 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -732,6 +732,10 @@ pub struct UiState { /// `script_print_failures`, while those notes are kept. Not saved. #[serde(skip)] pub script_print_failure_notes: Vec<(u64, usize)>, + /// The sent batch's note that heads the status bar's hover notes, so the next sent batch + /// replaces it instead of adding another. Not saved. + #[serde(skip)] + pub script_print_receipt: Option, /// The Replace Font request behind the status bar's warning ([`ReplaceFontWarning`]). Not saved. #[serde(skip)] pub replace_font_warning: Option, @@ -1542,6 +1546,7 @@ impl Default for UiState { status_sets: 0, script_print_failures: 0, script_print_failure_notes: Vec::new(), + script_print_receipt: None, replace_font_warning: None, last_find: None, find_action: None, diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 06ef8a02fd..9c0af57d41 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -389,7 +389,6 @@ fn a_repeated_spool_failure_keeps_its_own_hover_note() { run(&mut app, PRINT_TO_LAB); click_after_delay(&mut app, 10.0, "Print"); crate::background::wait_all(&mut app); - crate::io::show_with_notes(&mut app, "Another operation finished".into(), vec!["Another operation finished".into()]); crate::print::send_script_prints(&mut app, Vec::new()).unwrap(); let earlier_batch = std::mem::take(&mut app.background); run(&mut app, PRINT_TO_LAB); @@ -400,10 +399,37 @@ fn a_repeated_spool_failure_keeps_its_own_hover_note() { let failure = app.ui.status.clone(); assert!(failure.contains("The printer Lab is offline"), "{failure}"); let notes = &app.ui.status_notes.as_ref().unwrap().1; - assert!(notes.contains(&failure), "{notes:?}"); + assert_eq!(notes.iter().filter(|n| **n == failure).count(), 1, "{notes:?}"); assert_eq!(app.ui.script_print_failure_notes.len(), 1); } +/// Two batches sent after a spool failure keep the other hover notes the failure shared, such as a +/// startup script's error, once the first batch has cleared the failure. +#[test] +fn queued_sent_batches_keep_other_hover_notes() { + let mut app = worker_print_app("The printer Lab is offline"); + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 10.0, "Print"); + crate::background::wait_all(&mut app); + let failure = app.ui.status.clone(); + assert!(failure.contains("The printer Lab is offline"), "{failure}"); + let startup = "The startup script b.jsx failed".to_string(); + let tracked = app.ui.script_print_failure_notes.clone(); + crate::io::show_with_notes(&mut app, failure.clone(), vec![failure.clone(), startup.clone()]); + app.ui.script_print_failure_notes = tracked; + app.services.print = worker_print_app("").services.print; + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 20.0, "Print"); + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 30.0, "Print"); + assert_eq!(app.background.jobs.len(), 2, "both batches are queued"); + crate::background::wait_all(&mut app); + assert!(!app.ui.status.contains("offline"), "{}", app.ui.status); + let (status, notes) = app.ui.status_notes.as_ref().expect("the startup error stays in the hover notes"); + assert_eq!(status, &app.ui.status, "the hover notes match the displayed status"); + assert_eq!(notes, &vec!["Sent".to_string(), startup], "the second batch's note replaces the first's"); +} + /// A spool failure keeps the startup scripts' errors in the status bar's hover notes. #[test] fn a_spool_failure_does_not_hide_a_later_startup_script_failure() { From bed27c32918fb68a9fc629b76acf8ea6162068d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:20:33 -0800 Subject: [PATCH 055/103] xtask: test-lint follows scopes, quoted shell text and casts more exactly - all-unguarded: a count bound inside a block that has closed no longer guards a later `.all` on a local of the same name. - exit-status-only: a parenthesized operand is judged by its own `&&` and `||` operands, so `status.success() && (status.success() && x)` reads `x`. - no-assertion: an assertion in a closure that is never called counts for nothing: `let _ = async || { ... }`, `async move |x|`, and a closure or async block bound to a name the test never mentions again. - A `for` pattern shadows a passed helper only in the loop body, not in a block expression that is the loop's source. - A helper with a non-ASCII name counts when passed as a callback. - Workflow variables: a `;`, `&` or `|` inside quotes does not end the command that prints an assignment, only the pipeline that prints it has to write `$GITHUB_ENV`, and a `#` inside a word (`build#1`) does not start a comment in a run script or a workflow line. - fixture-only and constant-echo: a cast to a primitive type (`Kind::A as u8 + 1`) is not arithmetic on a user value, `>>` that closes a turbofish (`None::>`) is not a shift, and an element indexed twice (`rows[0][1]`) out of a user-value array is a user value. --- xtask/src/test_lint.rs | 342 ++++++++++++++++++++++++++++++++--------- 1 file changed, 270 insertions(+), 72 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 8aab64ef85..595fc978f0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1032,19 +1032,59 @@ fn workflow_scalar(line: &str) -> Option { Some(out) } -/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, on a line -/// that does not write to `$GITHUB_ENV`. +/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, in a +/// pipeline that does not write to `$GITHUB_ENV`. fn printed(line: &str, from: usize) -> bool { - // A line break ends the command unless a backslash continues it. - let head = &line[..from]; - let cut = head - .char_indices() - .rev() - .find(|&(i, c)| matches!(c, ';' | '&' | '|') || (c == '\n' && !head[..i].ends_with('\\'))) - .map_or(0, |(i, c)| i + c.len_utf8()); - let command = &head.as_bytes()[cut..]; + let separators = shell_separators(line); + // The command starts after the last separator before `from`; the pipeline runs between the + // list separators (`;`, `&&`, `||`, `&` and line breaks) around it. + let command_start = separators.iter().rev().find(|s| s.end <= from).map_or(0, |s| s.end); + let pipeline_start = separators.iter().rev().find(|s| s.end <= from && !s.pipe).map_or(0, |s| s.end); + let pipeline_end = separators.iter().find(|s| s.start >= from && !s.pipe).map_or(line.len(), |s| s.start); + let command = &line.as_bytes()[command_start..from]; let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); - prints && !line.contains("GITHUB_ENV") + prints && !line[pipeline_start..pipeline_end].contains("GITHUB_ENV") +} + +/// A shell control operator outside quotes: its byte range, and whether it is a pipe (`|`) rather +/// than a list separator. +struct ShellSeparator { + start: usize, + end: usize, + pipe: bool, +} + +/// The control operators of a shell script outside quotes, in order. A line break counts as a list +/// separator unless a backslash continues it. +fn shell_separators(script: &str) -> Vec { + let bytes = script.as_bytes(); + let (mut out, mut quote, mut escaped, mut i) = (vec![], None, false, 0); + while i < bytes.len() { + let c = bytes[i]; + if escaped { + escaped = false; + } else if c == b'\\' && quote != Some(b'\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + b'\'' | b'"' => quote = Some(c), + b'|' | b'&' if bytes.get(i + 1) == Some(&c) => { + out.push(ShellSeparator { start: i, end: i + 2, pipe: false }); + i += 1; + } + // `2>&1`, `&>` and `>|` are redirections. + b'&' | b'|' if i > 0 && matches!(bytes[i - 1], b'>' | b'<') => {} + b'&' if bytes.get(i + 1) == Some(&b'>') => {} + b'|' => out.push(ShellSeparator { start: i, end: i + 1, pipe: true }), + b';' | b'&' | b'\n' => out.push(ShellSeparator { start: i, end: i + 1, pipe: false }), + _ => {} + } + } + i += 1; + } + out } fn env_assignment_name(name: &str) -> bool { @@ -1069,7 +1109,8 @@ fn open_quote(line: &str, at: usize) -> Option { quote.map(|(_, i)| i) } -/// Removes comment text outside quotes from a workflow line. +/// Removes comment text outside quotes from a workflow line. A `#` starts a comment only at the +/// start of the line or after whitespace, as in YAML and the shell (`build#1` is one word). fn workflow_code(line: &str) -> &str { let (mut quote, mut escaped) = (None, false); for (at, c) in line.char_indices() { @@ -1082,7 +1123,7 @@ fn workflow_code(line: &str) -> &str { } else if quote.is_none() { match c { '\'' | '"' => quote = Some(c), - '#' => return &line[..at], + '#' if line[..at].chars().next_back().is_none_or(char::is_whitespace) => return &line[..at], _ => {} } } @@ -1091,9 +1132,11 @@ fn workflow_code(line: &str) -> &str { } /// Removes comment text outside quotes from a shell script that can hold several lines (a decoded -/// `run` value): each comment ends at its line break, and quotes stay open across line breaks. +/// `run` value): each comment ends at its line break, quotes stay open across line breaks, and a +/// `#` starts a comment only where a word starts (`build#1` is one word). fn shell_code(script: &str) -> String { let (mut out, mut quote, mut escaped, mut comment) = (String::with_capacity(script.len()), None, false, false); + let mut previous = None; for c in script.chars() { if comment { comment = c != '\n'; @@ -1106,13 +1149,14 @@ fn shell_code(script: &str) -> String { } else if quote.is_none() { match c { '\'' | '"' => quote = Some(c), - '#' => comment = true, + '#' => comment = previous.is_none_or(|p: char| p.is_whitespace() || matches!(p, ';' | '&' | '|' | '(' | ')')), _ => {} } } if !comment { out.push(c); } + previous = Some(c); } out } @@ -1371,6 +1415,30 @@ fn norm_words(b: &[u8]) -> String { String::from_utf8_lossy(&out).into_owned() } +/// [`norm`], with each cast to a primitive type (`Kind::A as u8`) written as an element of an array +/// literal (`[Kind::A][0]`): the names the operand reads still count, but the result, a primitive +/// value whatever the type of the operand, is not a [`user_value`]. +fn norm_values(b: &[u8]) -> String { + const PRIMITIVES: &[&[u8]] = + &[b"u8", b"u16", b"u32", b"u64", b"u128", b"usize", b"i8", b"i16", b"i32", b"i64", b"i128", b"isize", b"f32", b"f64", b"bool", b"char"]; + let mut text = norm_words(b).into_bytes(); + let mut from = 0; + while let Some(at) = text[from..].windows(4).position(|w| w == b" as ").map(|p| p + from) { + let start = receiver_start(&text, at); + let ty = at + 4; + let end = ty + text[ty..].iter().take_while(|&&c| is_ident(c)).count(); + if start < at && PRIMITIVES.contains(&&text[ty..end]) { + let element: Vec = [&b"["[..], &text[start..at], b"][0]"].concat(); + from = start + element.len(); + text.splice(start..end, element); + } else { + from = at + 1; + } + } + text.retain(|c| !c.is_ascii_whitespace()); + String::from_utf8_lossy(&text).into_owned() +} + /// Line starts, to turn byte offsets into 1-based lines. struct Lines(Vec); @@ -1901,8 +1969,8 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { /// `m` with each `fn` and `macro_rules!` declared inside a test's body replaced by spaces, from /// its keyword to its closing brace. A call to one stays, so it can still count as a helper call. -/// A closure or async block bound to `_` (`let _ = async { … };`) is dropped unrun, so its -/// statement is replaced too. +/// A closure or async block bound to `_` (`let _ = async { … };`, `let _ = async || { … };`), or to +/// a name the rest of the test never mentions, is never run, so its statement is replaced too. fn executed(m: &[u8], tests: &[TestFn]) -> Vec { let mut out = m.to_vec(); for t in tests { @@ -1916,15 +1984,13 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec { .into_iter() .filter(|&at| m[..at].trim_ascii_end().last().is_some_and(|c| matches!(c, b'{' | b';' | b'}'))); for at in statements { - let wild = skip_ws(m, at + 3); - let eq = skip_ws(m, wild + 1); - if m.get(wild) != Some(&b'_') - || m.get(wild + 1).copied().is_some_and(is_ident) - || m.get(eq) != Some(&b'=') - || m.get(eq + 1) == Some(&b'=') - { + let name = skip_ws(m, at + 3); + let name_end = name + m[name..t.close].iter().copied().take_while(|&c| is_ident(c)).count(); + let eq = skip_ws(m, name_end); + if name_end == name || m.get(eq) != Some(&b'=') || m.get(eq + 1) == Some(&b'=') { continue; } + let wild = &m[name..name_end] == b"_"; let mut value = skip_ws(m, eq + 1); let is_async = m[value..].starts_with(b"async") && !m.get(value + 5).copied().is_some_and(is_ident); if is_async { @@ -1934,13 +2000,14 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec { value = skip_ws(m, value + 4); } let end = statement_end(m, at); - // The block alone is the value; `async { … }.await` runs it. - let unrun = if is_async { - m.get(value) == Some(&b'{') && matching(m, value).is_some_and(|close| skip_ws(m, close + 1) == end) - } else { - m.get(value) == Some(&b'|') - }; - if unrun && end < t.close { + // A closure (`|…| …`, `async |…| …`, `async move |…| …`) runs only when called. The block + // alone is the value; `async { … }.await` runs it. + let closure = m.get(value) == Some(&b'|'); + let unrun = closure || (is_async && m.get(value) == Some(&b'{') && matching(m, value).is_some_and(|close| skip_ws(m, close + 1) == end)); + // A value bound to `_` is dropped; one bound to a name the rest of the test never + // mentions is never called or awaited. + let dropped = wild || words(m, &m[name..name_end], end, t.close).is_empty(); + if unrun && dropped && end < t.close { blank(&mut out, at, end + 1); } } @@ -2060,13 +2127,8 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { } statement_end(body, at) < pos && pos < block_close(body, at) }); - let loops = words(body, b"for", 0, pos).into_iter().any(|at| { - let Some((open, close)) = block_after(body, at + 3) else { return false }; - let Some(&in_at) = words(body, b"in", at + 3, open).first() else { return false }; - open < pos && pos < close && !words(body, name, at + 3, in_at).is_empty() - }); let name = String::from_utf8_lossy(name); - lets || loops || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() + lets || for_binding(body, &name, pos).is_some() || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() } /// Whether the `let` pattern in `body[start..end]` binds `name`: not in its type annotation @@ -2116,14 +2178,16 @@ fn enclosing_open(m: &[u8], at: usize) -> Option { /// where its value is kept: not in a statement of its own (`(body,);`), a `let _` or `let _name` /// binding, or a `drop` or `forget` call. fn passed_names(m: &[u8], open: usize, close: usize) -> Vec<(String, usize)> { + // Non-ASCII letters (`vérifier`) are part of a name; their UTF-8 bytes are all 0x80 or above. + let ident = |c: u8| is_ident(c) || c >= 0x80; let mut names = Vec::new(); let mut at = open + 1; while at < close { - if !is_ident(m[at]) || (at > 0 && (is_ident(m[at - 1]) || m[at - 1] == b'.')) { + if !ident(m[at]) || (at > 0 && (ident(m[at - 1]) || m[at - 1] == b'.')) { at += 1; continue; } - let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); + let end = at + m[at..close].iter().take_while(|&&c| ident(c)).count(); let before = m[..at].trim_ascii_end().last().copied(); let after = m.get(skip_ws(m, end)).copied(); if matches!(before, Some(b'(' | b'[' | b',')) && matches!(after, Some(b')' | b']' | b',')) && value_kept(m, open, at) { @@ -5063,6 +5127,8 @@ struct Binding { counts: bool, /// The local whose method the initializer calls (`xs` in `let n = xs.len()`). source: Option>, + /// Where the block that holds the `let` closes, after which the name no longer refers to it. + scope_end: usize, } /// Every `let` of a plain name in `body`, in order. @@ -5084,7 +5150,8 @@ fn bindings(body: &[u8]) -> Vec { let counts = SIZE_CHECKS.iter().any(|g| init.contains(g)); let ident = init.bytes().take_while(|&c| is_ident(c)).count(); let source = (ident > 0 && init[ident..].starts_with('.')).then(|| init.as_bytes()[..ident].to_vec()); - Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source }) + let scope_end = enclosing_block(body, at).and_then(|(open, _)| matching(body, open)).unwrap_or(body.len()); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source, scope_end }) }) .collect() } @@ -5099,7 +5166,7 @@ fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> if field_or_path(prefix) { return false; } - let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); + let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p && p < o.scope_end); reaching .is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end))) }) @@ -5171,37 +5238,45 @@ fn exit_status_only(v: &View) -> Option { strip_stream_configuration(&mut body); let reads = ["stdout", "stderr", "fs::read", "read_to_string", "from_slice", "from_str", "contains("].iter().any(|w| contains(&body, w.as_bytes())); - let status_only = |a: &MacroCall| { - a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { - let c = norm(&v.file.m[from..to]); - let c = unparenthesized(&c); - let mut start = 0; - top_level_at(c, "||").into_iter().chain([c.len()]).any(|end| { - if end < start { - return false; - } - let alternative = c.get(start..end); - start = end.saturating_add(2); - alternative.is_some_and(|alternative| { - let mut start = 0; - top_level_at(alternative, "&&").into_iter().chain([alternative.len()]).all(|end| { - if end < start { - return true; - } - let operand = alternative.get(start..end); - start = end.saturating_add(2); - operand.is_some_and(|operand| operand.contains(".success()") || operand.contains(".code()")) - }) - }) - }) - }) - }; + let status_only = |a: &MacroCall| a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| status_condition(&norm(&v.file.m[from..to]), 0)); if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { return None; } Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) } +/// Whether a (whitespace-free) condition can pass on an exit status alone: one of its `||` +/// alternatives is made only of `&&` operands that read `.success()` or `.code()`, with each +/// parenthesized operand judged the same way. Conditions nested more than 64 levels deep are not +/// judged. +fn status_condition(c: &str, depth: usize) -> bool { + if depth > 64 { + return false; + } + fn split<'a>(s: &'a str, op: &str) -> Vec<&'a str> { + let mut parts = vec![]; + let mut start = 0; + for at in top_level_at(s, op) { + if at >= start { + parts.push(&s[start..at]); + start = at + op.len(); + } + } + parts.push(&s[start..]); + parts + } + let c = unparenthesized(c); + split(c, "||").into_iter().any(|alternative| { + split(alternative, "&&").into_iter().all(|operand| { + if operand.starts_with('(') && matching(operand.as_bytes(), 0) == Some(operand.len() - 1) { + status_condition(operand, depth + 1) + } else { + operand.contains(".success()") || operand.contains(".code()") + } + }) + }) +} + /// Blanks the names of builder calls that set a process's streams (`.stdout(…)`, whatever the /// argument) in whitespace-free text. Reads of the output fields (`out.stdout`) stay. fn strip_stream_configuration(body: &mut [u8]) { @@ -6534,7 +6609,8 @@ fn fixture_operator_runs(op: &str, at: usize, pos: usize, local: &LocalAt) -> bo return false; } let width = if matches!(c, b'<' | b'>') { - if next != Some(c) || previous == Some(c) || b.get(at + 2) == Some(&b'=') { + // `>>` can also close two generic argument lists (`None::>`). + if next != Some(c) || previous == Some(c) || b.get(at + 2) == Some(&b'=') || (c == b'>' && generic_depth(&b[..at]) > 0) { return false; } 2 @@ -6569,6 +6645,27 @@ fn fixture_operator_runs(op: &str, at: usize, pos: usize, local: &LocalAt) -> bo holds_user_value(&op[from..end], pos, local) } +/// How many turbofish generic argument lists (`::<…>`, with the `<…>` nested in them) are still +/// open at the end of a whitespace-free operand. +fn generic_depth(op: &[u8]) -> usize { + let mut depth = 0usize; + let mut i = 0; + while i < op.len() { + if op[i..].starts_with(b"::<") { + depth += 1; + i += 3; + continue; + } + match op[i] { + b'<' if depth > 0 => depth += 1, + b'>' if depth > 0 => depth -= 1, + _ => {} + } + i += 1; + } + depth +} + /// Where the receiver of the method call whose `.` is at `dot` starts in a whitespace-free operand: /// back over names, paths, field and method accesses, bracketed groups, macro names and string /// literals. @@ -6661,9 +6758,17 @@ fn holds_user_value(expr: &str, pos: usize, local: &LocalAt) -> bool { let b = expr.as_bytes(); let Some(open) = b.iter().position(|c| matches!(c, b'(' | b'[' | b'{')) else { return user_value(expr, pos, local) }; let Some(close) = matching(b, open) else { return false }; - // An element indexed out of a local (`xs[0]`) is a user value when the local's value holds one. - if b[open] == b'[' && close + 1 == b.len() && plain_local(&expr[..open]) && b[0].is_ascii_lowercase() { - return holds_user_value(&expr[..open], pos, local); + // An element indexed out of a local (`xs[0]`, `rows[0][1]`) is a user value when the local's + // value holds one. + if b[open] == b'[' && plain_local(&expr[..open]) && b[0].is_ascii_lowercase() { + let mut end = close + 1; + while b.get(end) == Some(&b'[') { + let Some(next) = matching(b, end) else { return false }; + end = next + 1; + } + if end == b.len() { + return holds_user_value(&expr[..open], pos, local); + } } // Only a whole container exposes its elements, not the result of a method such as `len`. if close + 1 != b.len() || expr[..open].bytes().any(|c| !is_ident(c) && !matches!(c, b':' | b'!')) { @@ -6901,7 +7006,7 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u if stop > before || block_close(body, at) < before { continue; } - let rest = norm(&body[n1..stop]); + let rest = norm_values(&body[n1..stop]); let plain = n1 > n0 && (rest.is_empty() || rest.starts_with(':') || rest.starts_with('=')); if plain && &body[n0..n1] == name.as_bytes() { let init = rest.split_once('=').filter(|(ty, _)| ty.is_empty() || ty.starts_with(':')).map(|(_, init)| (init.to_owned(), at)); @@ -7012,7 +7117,7 @@ fn echoes(v: &View) -> Option { return None; } for &(from, to) in a.args.iter().take(n) { - let op = norm(&body[from - v.t.open..to - v.t.open]); + let op = norm_values(&body[from - v.t.open..to - v.t.open]); reads_local |= inert_at(&body, &op, from - v.t.open, 0)?.0; } } @@ -8957,12 +9062,17 @@ mod tests { "let _ = async move { assert_eq!(f(), 1); };", "let _ = || assert_eq!(f(), 1);", "let _ = move |x| assert_eq!(x, 1);", + "let _ = async || { assert_eq!(compute(), 1); };", + "let _ = async move |x| { assert_eq!(x, 1); };", + "let _future = async { assert_eq!(f(), 1); };", ] { let src = format!("#[test]\nfn t() {{\n {dropped}\n}}\n"); assert_eq!(hits(&src), [(2, "no-assertion")], "{dropped}"); } let kept = "#[test]\nfn t() {\n let check = || assert_eq!(f(), 1);\n check();\n}\n"; assert_eq!(hits(kept), [], "a named closure can be called"); + assert_eq!(hits(&kept.replace(" check();\n", "")), [(2, "no-assertion")], "a named closure that is never called"); + assert_eq!(hits(&kept.replace(" check();\n", " run(check);\n")), [], "a named closure passed on can be called"); let awaited = "#[test]\nfn t() {\n let _ = async { assert_eq!(f(), 1); }.await;\n}\n"; assert_eq!(hits(awaited), [], "an awaited block runs"); let conditional = "#[test]\nfn t() {\n if let _ = || () {\n assert_eq!(f(), 1);\n };\n}\n"; @@ -9044,6 +9154,14 @@ mod tests { } } + #[test] + fn process_status_checks_judge_parenthesized_operands_by_their_own_operands() { + let good = "#[test]\nfn t() {\n let status = Command::new(\"cp\").arg(src).arg(&destination).status().unwrap();\n assert!(status.success() && (status.success() && destination.exists()));\n}\n"; + assert_eq!(hits(good), []); + let alternative = good.replace("(status.success() && destination.exists())", "(status.success() || destination.exists())"); + assert_eq!(hits(&alternative), [(2, "exit-status-only")]); + } + #[test] fn process_status_checks_accept_every_comparison_assertion() { for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { @@ -9580,6 +9698,38 @@ mod tests { } } + #[test] + fn printed_assignments_are_found_past_quoted_separators() { + for line in [" printf '%s;' 'MY_SAMPLES=fixtures'", " echo 'a|b' \"MY_SAMPLES=fixtures\"", " echo \"a && b\" MY_SAMPLES=x"] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + assert_eq!(upper_words(" printf '%s;' 'MY_SAMPLES=fixtures' >> \"$GITHUB_ENV\"").collect::>(), ["MY_SAMPLES"]); + } + + #[test] + fn only_the_printing_pipeline_writes_the_environment_file() { + let script = "run: \"echo \\\"MY_SAMPLES=fixtures\\\"\\necho \\\"OTHER=x\\\" >> \\\"$GITHUB_ENV\\\"\""; + assert_eq!(upper_words(script).collect::>(), ["OTHER"]); + for line in [ + " echo \"MY_SAMPLES=fixtures\" | tee -a \"$GITHUB_ENV\"", + " echo \"MY_SAMPLES=fixtures\" 2>&1 >> \"$GITHUB_ENV\"", + " true; echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\"", + ] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + assert_eq!(upper_words(" echo \"MY_SAMPLES=fixtures\"; echo x >> \"$GITHUB_ENV\"").collect::>(), Vec::::new()); + } + + #[test] + fn a_hash_inside_a_word_does_not_start_a_comment() { + for line in ["run: \"echo build#1; export MY_SAMPLES=fixtures; cargo test\"", "run: echo build#1; export MY_SAMPLES=fixtures"] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + for line in ["run: \"echo build # MY_SAMPLES=fixtures\"", "run: echo build # MY_SAMPLES=fixtures", "run: \"true;# MY_SAMPLES=fixtures\""] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + } + #[test] fn quoted_assignment_command_arguments_set_workflow_variables() { for line in [ @@ -9845,6 +9995,14 @@ mod tests { assert_eq!(hits(inside), []); } + #[test] + fn counts_bound_in_a_closed_block_do_not_guard_all() { + let src = "#[test]\nfn t() {\n let xs = f();\n let n = 1;\n {\n let n = xs.len();\n use_it(n);\n }\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(10, "all-unguarded")]); + let same_block = src.replace(" {\n let n = xs.len();\n use_it(n);\n }\n", " let n = xs.len();\n"); + assert_eq!(hits(&same_block), []); + } + #[test] fn constants_with_several_values_are_unknown() { let src = "mod a { const START: usize = 0; }\nmod b {\nconst START: usize = 2;\nconst END: usize = 2;\n#[test]\nfn t() {\n let xs: Vec = (START..END).collect();\n assert!(xs.iter().all(|x| *x > 0));\n}\n}\n"; @@ -9859,6 +10017,10 @@ mod tests { assert_eq!(hits(src), []); let cleared = src.replace(" assert_eq!(n, 1);", " xs.clear();\n assert_eq!(n, 1);"); assert_eq!(hits(&cleared), [(7, "all-unguarded")]); + let field = src.replace(" assert_eq!(n, 1);", " assert_eq!(n, 1);\n (other.xs, _) = (vec![], 0);"); + assert_eq!(hits(&field), [], "a field with the same name is another collection"); + let replaced = src.replace(" assert_eq!(n, 1);", " assert_eq!(n, 1);\n (xs, _) = (vec![], 0);"); + assert_eq!(hits(&replaced), [(7, "all-unguarded")]); } #[test] @@ -11343,12 +11505,23 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", &looped, &ctx), [(8, "no-assertion")], "a loop pattern shadows the helper in the loop body"); let after_loop = src.replace(" keeping(body);", " for body in [|| {}] {\n let _ = body;\n }\n keeping(body);"); assert_eq!(hits_in("crates/x/src/tests.rs", &after_loop, &ctx), [], "the helper after the loop"); + let block_source = src.replace(" keeping(body);", " for body in { [noop as fn()] } {\n keeping(body);\n }"); + assert_eq!( + hits_in("crates/x/src/tests.rs", &block_source, &ctx), + [(8, "no-assertion")], + "a loop over a block expression shadows the helper in the loop body" + ); + let in_source = src.replace(" keeping(body);", " for body in { keeping(body); [noop as fn()] } {\n let _ = body;\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &in_source, &ctx), [], "a loop pattern does not reach the loop's source"); let unused = src.replace(" keeping(body);", " let _unused = (body,);"); assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "a tuple that is never called"); let dropped = src.replace(" keeping(body);", " (body,);"); assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a tuple in a statement of its own"); let table = src.replace(" keeping(body);", " let cases = [(\"case\", body)];\n run(&cases);"); assert_eq!(hits_in("crates/x/src/tests.rs", &table, &ctx), [], "a table of named cases"); + let accented = src.replace("body", "vérifier"); + let accented_ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), accented.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &accented, &accented_ctx), [], "a helper with a non-ASCII name"); let idle = src.replace("assert_eq!(f(), 1);", "f();"); let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); @@ -12572,6 +12745,31 @@ mod tests { assert_eq!(only("fixture-only", indexed), [], "an indexed element of a user-value array"); let primitive = indexed.replace("Amount(2), Amount(3)", "2, 3"); assert_eq!(only("fixture-only", &primitive), [(2, "fixture-only")], "an indexed element of a primitive array"); + let nested = "#[test]\nfn t() {\n let rows = [[Amount(2), Amount(3)]];\n assert_eq!(rows[0][0] + rows[0][1], Amount(5));\n}\n"; + assert_eq!(only("fixture-only", nested), [], "an element indexed twice out of a user-value array"); + let nested_primitive = nested.replace("Amount(2), Amount(3)", "2, 3"); + assert_eq!(only("fixture-only", &nested_primitive), [(2, "fixture-only")], "an element indexed twice out of a primitive array"); + } + + #[test] + fn casts_and_turbofish_types_are_not_operators_on_user_values() { + for expr in ["Kind::A as u8 + 1", "(Kind::A as u8) << 2", "None::>"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, EXPECTED);\n}}\n"); + assert_eq!(only("constant-echo", &src), [(2, "constant-echo")], "{expr}"); + } + for expr in ["Kind::A + 1", "Some::(Amount(2)) >> 1"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, EXPECTED);\n}}\n"); + assert_eq!(only("constant-echo", &src), [], "{expr} runs an operator on a user value"); + } + let cast_local = "#[test]\nfn t() {\n let k = Kind::A as u8;\n assert_eq!(k + 1, 2);\n}\n"; + assert_eq!(only("fixture-only", cast_local), [(2, "fixture-only")]); + for computed in [ + "#[test]\nfn t() {\n let got = compute();\n assert_eq!(got as u8, 2);\n}\n", + "#[test]\nfn t() {\n let got = compute() as u8;\n assert_eq!(got, 2);\n}\n", + ] { + assert_eq!(only("constant-echo", computed), [], "{computed}"); + assert_eq!(only("fixture-only", computed), [], "{computed}"); + } } #[test] From cb284a53c0ccf4f2954e9ca60fd2e0f2d2da0afc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:24:15 -0800 Subject: [PATCH 056/103] Shapes: saves for older versions write a live star as its path A save for format versions 1 to 3 wrote `live: {shape: "star"}`, which those versions' readers reject, so the file did not open there. These saves now drop the live star and keep the outline it draws as a plain path, in the layers, symbols, graph designs, patterns, opacity masks and brush definitions. The current version keeps the star live. --- crates/doc/src/document_ext.rs | 46 ++++++++++++++++++++++ crates/format/src/lib.rs | 4 ++ crates/format/tests/it/native_v3.rs | 59 ++++++++++++++++++++++++++++- crates/format/tests/prop_format.rs | 20 +++++++++- docs/mcp.md | 2 +- 5 files changed, 128 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c29e8464ea..fe2ffc0fd1 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -239,6 +239,52 @@ impl Document { round_json_paths(brushes, &round); } } + + /// Make every live star a plain path of the outline it draws, for a save that versions before + /// live stars read: in the art of the layers, symbols, graph designs, pattern swatches and the + /// pattern definition that pattern editing's Cancel puts back (opacity-mask art included), and + /// in the brush definitions. + pub fn live_stars_to_paths(&mut self) { + let is_star = |n: &Node| matches!(n.live_shape(), Some(LiveShape::Star { .. })); + let mut plain = |n: &mut Node| { + if let NodeKind::Path { live, .. } = &mut n.kind + && matches!(live.as_deref(), Some(LiveShape::Star { .. })) + { + *live = None; + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + edit_branches_where(root, &is_star, &mut plain); + } + if let Some(brushes) = self.unknown.get_mut("brushes") { + json_stars_to_paths(brushes); + } + } +} + +/// Take `live` off every serialized path object (`type: "path"`) in `v` whose live shape is a +/// star. +fn json_stars_to_paths(v: &mut serde_json::Value) { + use serde_json::Value; + match v { + Value::Object(o) => { + if o.get("type").and_then(Value::as_str) == Some("path") + && o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") + { + o.remove("live"); + } + o.values_mut().for_each(json_stars_to_paths); + } + Value::Array(a) => a.iter_mut().for_each(json_stars_to_paths), + _ => {} + } } /// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds, diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9975527f78..97a0ca706b 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -274,6 +274,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { d.halftone_radii_to_points(); d.store_legacy_twist_angles(); } + // Older apps don't know live stars: they get the outline a star draws as a plain path. + if version < VERSION { + d.live_stars_to_paths(); + } let v1 = if version == 1 { let mut v = serde_json::to_value(&d).map_err(encode_err)?; legacy::anchors_to_v1(&mut v); diff --git a/crates/format/tests/it/native_v3.rs b/crates/format/tests/it/native_v3.rs index afc3bea9d2..0305246868 100644 --- a/crates/format/tests/it/native_v3.rs +++ b/crates/format/tests/it/native_v3.rs @@ -19,6 +19,20 @@ fn json_of(bytes: &[u8]) -> Value { serde_json::from_slice(bytes).unwrap() } +/// `v` (a document's JSON) with every live star's `live` taken off its path. +fn without_live_stars(v: &mut Value) { + match v { + Value::Object(o) => { + if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") { + o.remove("live"); + } + o.values_mut().for_each(without_live_stars); + } + Value::Array(a) => a.iter_mut().for_each(without_live_stars), + _ => {} + } +} + fn gzip(bytes: &[u8]) -> Vec { let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); gz.write_all(bytes).unwrap(); @@ -274,7 +288,9 @@ fn version_1_files_load() { fn saves_down_to_older_versions() { let mut d = rich_doc(); d.color_profiles = ColorProfiles { rgb: None, cmyk: Some("Coated".into()) }; - let current = doc_json(&load(&save(&d, false)).unwrap()); + let mut current = doc_json(&load(&save(&d, false)).unwrap()); + // Older versions get live stars as plain paths. + without_live_stars(&mut current); for version in [1, 2] { let bytes = save_with(&d, &opts(version, false)).unwrap(); let v = json_of(&bytes); @@ -299,6 +315,47 @@ fn saves_down_to_older_versions() { assert!(matches!(save_with(&d, &opts(2, true)), Err(FormatError::CompressedTooOld(2)))); } +/// Versions before [`VERSION`] don't know live stars: a save for them writes the star's outline as +/// a plain path, which those versions read; the current version keeps the star live. +#[test] +fn older_versions_get_a_live_star_as_its_path() { + let mut d = Document::new(100.0, 100.0); + let star = vectorcraft_doc::LiveShape::Star { + r1: 40.0, + r2: 20.0, + points: 5, + xf: Affine::translate((50.0, 50.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }; + let id = d.alloc_id(); + let mut node = Node::path(id, star.to_path(), Default::default()); + if let NodeKind::Path { live, .. } = &mut node.kind { + *live = Some(Box::new(star.clone())); + } + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, node).unwrap(); + for version in 1..VERSION { + let bytes = save_with(&d, &opts(version, false)).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert!(!text.contains("\"star\""), "v{version} writes no live star"); + let back = load(&bytes).unwrap(); + let mut anchors = None; + back.walk(|n| { + if let NodeKind::Path { path, live, .. } = &n.kind { + assert!(live.is_none(), "v{version}"); + anchors = Some(path.anchor_count()); + } + }); + assert_eq!(anchors, Some(10), "v{version} keeps the star's outline"); + } + let back = load(&save(&d, false)).unwrap(); + let mut live = None; + back.walk(|n| live = live.clone().or(n.live_shape().cloned())); + assert_eq!(live, Some(star)); +} + #[test] fn preview_is_embedded_and_read_back() { let d = Document::new(10.0, 10.0); diff --git a/crates/format/tests/prop_format.rs b/crates/format/tests/prop_format.rs index faecc37a8c..26d91ccf97 100644 --- a/crates/format/tests/prop_format.rs +++ b/crates/format/tests/prop_format.rs @@ -11,6 +11,20 @@ use vectorcraft_testkit::fixtures; use vectorcraft_testkit::invariants::{check_document, check_native_roundtrip, check_native_roundtrip_exact, doc_json, json_approx_eq}; use vectorcraft_testkit::strategies::arb_ops; +/// `v` (a document's JSON) with every live star's `live` taken off its path. +fn without_live_stars(v: &mut Value) { + match v { + Value::Object(o) => { + if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") { + o.remove("live"); + } + o.values_mut().for_each(without_live_stars); + } + Value::Array(a) => a.iter_mut().for_each(without_live_stars), + _ => {} + } +} + fn rich_doc() -> Document { (*fixtures::rich_session().doc().unwrap().doc).clone() } @@ -117,9 +131,13 @@ proptest! { } let d = s.doc().unwrap().doc.clone(); let want = doc_json(&load(&save(&d, false)).unwrap()); + // Older versions get live stars as plain paths. + let mut older = want.clone(); + without_live_stars(&mut older); for o in [SaveOptions { compress: true, ..SaveOptions::default() }, SaveOptions { version: 2, ..SaveOptions::default() }, SaveOptions { version: 1, pretty: true, ..SaveOptions::default() }] { let back = load(&save_with(&d, &o).unwrap()).unwrap(); - prop_assert!(json_approx_eq(&doc_json(&back), &want, 1e-12), "{:?} differs", o); + let want = if o.version < vectorcraft_format::VERSION { &older } else { &want }; + prop_assert!(json_approx_eq(&doc_json(&back), want, 1e-12), "{:?} differs", o); } } diff --git a/docs/mcp.md b/docs/mcp.md index eb9f0c2de6..4e097315a4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -820,7 +820,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | | `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | -| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | +| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | From f7ec5d50ccd23b1fc727ecab30a14bff8719775d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:56:46 -0800 Subject: [PATCH 057/103] Selection: a click inside an unfilled shape starts a marquee again #9807 made the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path with no fill by a click inside it (#9175). That is now an option: Preferences > Selection & Anchor Display > Select Inside Unfilled Shapes (`selectInsideUnfilledShapes`), off by default. With it off, a click or drag inside an unfilled shape that hits nothing else there starts a marquee, as it did before #9807. With it on, the tools behave as #9807 made them. Object Selection by Path Only still turns the inside off either way. Tests that asserted the #9807 default now turn the preference on before expecting the inside to select the shape, and also check that it selects nothing by default: the MCP test (renamed to a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference), the outside-stroke reach test and the Direct Selection center point test. A new Selection tool test checks that a drag inside an unfilled rectangle makes a marquee and leaves it in place by default, and moves it with the preference on. --- crates/engine/src/cmd/prefscmds.rs | 1 + crates/engine/src/prefs.rs | 4 ++++ crates/engine/src/tests/strokereach.rs | 6 ++++- crates/engine/src/tooling.rs | 3 +++ crates/mcp/src/tests.rs | 16 ++++++++----- crates/tools/src/context.rs | 11 ++++++--- crates/tools/src/direct/tests.rs | 5 ++-- crates/tools/src/lib.rs | 1 + crates/tools/src/select/tests.rs | 24 +++++++++++++++++++ crates/ui-egui/src/canvas/outline.rs | 10 ++++---- .../ui-egui/src/prefs_dialog/descriptions.rs | 4 ++++ docs/mcp.md | 7 ++++-- docs/target-app-parity.md | 4 ++-- 13 files changed, 76 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 0ee0340542..2011a61729 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -174,6 +174,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ choice(&[("touching", "Touching"), ("enclosed", "Fully Enclosed"), ("directional", "Drag Direction")]) ), p!("objectSelectionByPathOnly", "Selection & Anchor Display", "Selection", "Object Selection by Path Only", bool), + p!("selectInsideUnfilledShapes", "Selection & Anchor Display", "Selection", "Select Inside Unfilled Shapes", bool), p!("snapToPointTolerance", "Selection & Anchor Display", "Selection", "Snap to Point", num(1.0, 8.0, "px")), p!("ctrlClickSelectsBehind", "Selection & Anchor Display", "Selection", "Command Click to Select Objects Behind", bool), p!("zoomToSelection", "Selection & Anchor Display", "Selection", "Zoom to Selection", bool), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index f5528f0471..e72a20c6c1 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -134,6 +134,9 @@ pub struct Prefs { /// Selection-tool marquee: touching (default), enclosed, or screen drag direction. pub marquee_selection: String, pub object_selection_by_path_only: bool, + /// Off (the default), a selection tool click inside a closed path with no fill starts a + /// marquee; on, it selects the path when no other object is hit there (#9175). + pub select_inside_unfilled_shapes: bool, pub snap_to_point_tolerance: f64, pub ctrl_click_selects_behind: bool, pub zoom_to_selection: bool, @@ -593,6 +596,7 @@ impl Default for Prefs { selection_tolerance: 3.0, marquee_selection: "touching".into(), object_selection_by_path_only: false, + select_inside_unfilled_shapes: false, snap_to_point_tolerance: 2.0, ctrl_click_selects_behind: true, zoom_to_selection: true, diff --git a/crates/engine/src/tests/strokereach.rs b/crates/engine/src/tests/strokereach.rs index a04388af89..87a9b64917 100644 --- a/crates/engine/src/tests/strokereach.rs +++ b/crates/engine/src/tests/strokereach.rs @@ -62,8 +62,12 @@ fn a_click_outside_an_outside_stroke_selects_it() { s.execute("stroke.set", &json!({"ids": [r.0], "align": "center"})).unwrap(); s.execute("select.none", &json!({})).unwrap(); assert!(click(&mut s, 84.0, 200.0).is_empty(), "a centred stroke doesn't reach"); - // With it off, a click inside the unfilled square selects it (#9175). + // With it off, a click inside the unfilled square selects nothing by default, and selects the + // square with Select Inside Unfilled Shapes on (#9175). s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(click(&mut s, 116.0, 200.0).is_empty(), "off by default"); + s.execute("prefs.set", &json!({"key": "selectInsideUnfilledShapes", "value": true})).unwrap(); assert_eq!(click(&mut s, 116.0, 200.0), [r]); } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 05dde4c156..12296ad8a1 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -21,6 +21,7 @@ pub(crate) struct HoverKey { last_tools: (Option<&'static str>, Option<&'static str>), ctrl_click_selects_behind: bool, object_selection_by_path_only: bool, + select_inside_unfilled_shapes: bool, type_selection_by_path_only: bool, selection_tolerance: f64, anchor_size: u32, @@ -364,6 +365,7 @@ impl Session { last_tools: (self.last_selection_tool, self.last_part_selection_tool), ctrl_click_selects_behind: p.ctrl_click_selects_behind, object_selection_by_path_only: p.object_selection_by_path_only, + select_inside_unfilled_shapes: p.select_inside_unfilled_shapes, type_selection_by_path_only: p.type_selection_by_path_only, selection_tolerance: p.selection_tolerance, anchor_size: p.anchor_size, @@ -649,6 +651,7 @@ impl Session { }, anchor_size: self.prefs.anchor_size, path_only: self.prefs.object_selection_by_path_only, + unfilled_interiors: self.prefs.select_inside_unfilled_shapes, type_path_only: self.prefs.type_selection_by_path_only, double_click_isolate: self.prefs.double_click_to_isolate, double_click_adds_anchor: self.prefs.double_click_adds_anchor_points, diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 231cbd5f9f..8895dd4383 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1955,10 +1955,11 @@ fn selection_preferences_apply_to_pointer_gestures() { assert_eq!(click(&mut s, 7, 250.0, json!({})), json!([front]), "the path does"); } -/// A Selection tool click inside a closed shape with no fill selects it (#9175), and with Object -/// Selection by Path Only on it selects nothing. +/// A Selection tool click inside a closed shape with no fill selects nothing by default; with +/// Select Inside Unfilled Shapes on it selects the shape (#9175), unless Object Selection by Path +/// Only is on too. #[test] -fn a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only() { +fn a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference() { let mut s = server(); let r = call( &mut s, @@ -1975,10 +1976,13 @@ fn a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only() { assert_eq!(r["isError"], false, "{r}"); serde_json::from_str::(&text_of(&r)).unwrap()["selection"].clone() }; - assert_eq!(click(&mut s, 2), json!([id])); - let r = call(&mut s, 4, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); + assert_eq!(click(&mut s, 2), json!([]), "off by default"); + let r = call(&mut s, 4, "run_command", json!({"command": "prefs.set", "params": {"key": "selectInsideUnfilledShapes", "value": true}})); assert_eq!(r["isError"], false, "{r}"); - assert_eq!(click(&mut s, 5), json!([]), "path only"); + assert_eq!(click(&mut s, 5), json!([id])); + let r = call(&mut s, 7, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); + assert_eq!(r["isError"], false, "{r}"); + assert_eq!(click(&mut s, 8), json!([]), "path only"); } #[test] diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 79e69f77f6..2ac3c90086 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -288,6 +288,10 @@ pub struct ToolContext<'a> { /// Selection & Anchor Display → Object Selection by Path Only: a click inside a filled path /// doesn't pick it, only one on its path does. pub path_only: bool, + /// Selection & Anchor Display → Select Inside Unfilled Shapes (off by default): a selection + /// tool click inside a closed path with no fill picks it where nothing else is hit, instead of + /// starting a marquee. + pub unfilled_interiors: bool, /// Type → Type Object Selection by Path Only: type is picked on its type path only (point /// type's baseline, area type's frame, type on a path's path), not anywhere in its bounds. pub type_path_only: bool, @@ -476,15 +480,16 @@ impl ToolContext<'_> { /// [`Self::hit_options`] for the selection tools (Selection, Direct Selection, Group /// Selection): a clipping path is also hit on its outline ([`HitOptions::clip_outlines`]), and - /// where nothing else is hit, an unfilled closed path is hit inside unless Object Selection by - /// Path Only is on ([`HitOptions::unfilled_interiors`]). + /// with Select Inside Unfilled Shapes on ([`Self::unfilled_interiors`]), an unfilled closed path + /// is hit inside where nothing else is hit, unless Object Selection by Path Only is on + /// ([`HitOptions::unfilled_interiors`]). /// Only for what a press or a hover selects: a double-click, loaded text or a guide's release /// acts on what is drawn and takes [`Self::hit_options`]. /// /// [`HitOptions::clip_outlines`]: vectorcraft_doc::hit::HitOptions::clip_outlines /// [`HitOptions::unfilled_interiors`]: vectorcraft_doc::hit::HitOptions::unfilled_interiors pub fn selection_hit_options(&self) -> vectorcraft_doc::hit::HitOptions { - vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..self.hit_options() } + vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: self.unfilled_interiors, ..self.hit_options() } } } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 3707d4ee88..aa7fb8cc30 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1869,9 +1869,10 @@ fn the_centre_point_selects_and_moves_the_object_whole() { assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 140.0)); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Marquee(_)))); - // Without it, a press inside the unfilled square selects it (#9175). + // Without it and with Select Inside Unfilled Shapes on, a press inside the unfilled square + // selects it (#9175). let mut t = DirectSelectionTool::new(false); - let c = cx(&d, &none, &p); + let c = ToolContext { unfilled_interiors: true, ..cx(&d, &none, &p) }; assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 5a32145ec0..aa8e511d0b 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -685,6 +685,7 @@ pub(crate) mod testutil { selection_tolerance: 3.0, anchor_size: 3, path_only: false, + unfilled_interiors: false, type_path_only: false, double_click_isolate: true, double_click_adds_anchor: false, diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 0ebda2c719..63f7e5c25f 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -3026,6 +3026,30 @@ fn a_press_on_the_centre_point_moves_an_unfilled_shape() { assert!(matches!(t.overlays(&c).first(), Some(Overlay::SelectionMarquee { .. })), "a marquee"); } +/// A drag inside an unselected unfilled shape, away from its path, makes a marquee and leaves the +/// shape where it is by default; with Select Inside Unfilled Shapes on, the press selects the shape +/// and the drag moves it (#9175). +#[test] +fn a_drag_inside_an_unfilled_shape_makes_a_marquee_unless_asked() { + let (d, id) = doc_with_live_rect(); + let none = Selection::default(); + let p = paint(); + let inside = Point::new(130.0, 130.0); + let c = cx(&d, &none, &p); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::Down, inside.x, inside.y)).is_empty(), "nothing is selected"); + let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0)); + assert!(a.is_empty(), "nothing moves: {a:?}"); + assert!(matches!(t.overlays(&c).first(), Some(Overlay::SelectionMarquee { .. })), "a marquee"); + let c = ToolContext { unfilled_interiors: true, ..cx(&d, &none, &p) }; + let mut t = SelectionTool::default(); + let a = t.pointer(&c, &ev(PointerKind::Down, inside.x, inside.y)); + assert_eq!(a, vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); + let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0)); + assert!(a.iter().any(|a| *a == Action::Begin("Move".into())), "the shape moves: {a:?}"); + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::SelectionMarquee { .. })), "no marquee"); +} + /// A Shift-press on a selected object's centre point moves the selection too, held to 45° steps, /// and a Shift-click there (no drag) takes the object out of the selection, as a Shift-press on /// the object itself does. diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 0d70e1a78a..11a80a1449 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -218,12 +218,14 @@ pub(super) fn hit_at(app: &VectorcraftApp, p: Point, zoom: f64) -> Option Option { + let unfilled_interiors = app.session.prefs.select_inside_unfilled_shapes; hit_with(app, p, zoom, |doc, p, opt| { - vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..opt }) + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors, ..opt }) }) } diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index 6441158d29..00b5bf8314 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -139,6 +139,10 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "Whether the Selection tool's box selects objects it touches or only those fully inside; Drag Direction selects those inside on a drag to the right. E reverses it mid-drag.", ), ("objectSelectionByPathOnly", "A click selects a filled object only on its path, not inside its fill."), + ( + "selectInsideUnfilledShapes", + "A click inside a closed shape with no fill selects the shape when nothing else is there, unless Object Selection by Path Only is on; off, it starts a selection box.", + ), ( "snapToPointTolerance", "How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead.", diff --git a/docs/mcp.md b/docs/mcp.md index d659e73c88..7f45b27ad7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10635,8 +10635,11 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture handle or segment for Direct Selection, the Anchor Point, Add and Delete Anchor Point and Scissors tools, and the Pen with Alt. A handle shorter than that leaves its anchor to be picked when pressed nearer the anchor. - `objectSelectionByPathOnly`: a click inside a filled path or compound path doesn't select it, one on its path does. - Off (the default), a selection tool click inside the closed subpaths of a path or compound path with no fill selects - it when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, +- `selectInsideUnfilledShapes` (off by default): off, a selection tool click or drag inside a closed path with no fill + that hits nothing else there (its stroke, other art, a selected object's center point) starts a marquee, as it does + on empty canvas. On, with `objectSelectionByPathOnly` off, a selection tool click + inside the closed subpaths of a path or compound path with no fill selects it when the click hits no other object + there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds), the topmost such path first, except in Outline view and on a layer whose Preview is off; guides and clipping paths are still picked by their path only (#9175). - `ctrlClickSelectsBehind` (on by default): after a first Selection tool click with `mods: {cmd: true}` (Command on diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f96e28264f..95fa3b975a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -709,9 +709,9 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss by default, with Object Selection by Path Only on or in Outline view, and with Select Inside Unfilled Shapes on and Path Only off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. -- **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. +- **Clicks inside unfilled shapes (#9175):** with Selection & Anchor Display › Select Inside Unfilled Shapes on (off by default; off, a click or drag there starts a marquee) and Object Selection by Path Only off, the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference` (MCP), and `a_drag_inside_an_unfilled_shape_makes_a_marquee_unless_asked` (Selection tool). Scores and estimates unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. From 82fc8b1e5df455667d35cd6eb9657d48abaf714c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:02:52 -0800 Subject: [PATCH 058/103] Selection: Select Behind rechecks when Select Inside Unfilled Shapes changes The Selection tool keeps the answer of its last Select Behind hit test for the same point. The key it is stored under did not include whether unfilled interiors are hit, so after the preference was turned on or off, a Cmd/Ctrl-click at the same point could use the old answer. The key now includes it. --- crates/tools/src/select.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 1d7bd558e0..fe23341fb6 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -538,6 +538,7 @@ struct BehindKey { scope: Option, outline: bool, path_only: bool, + unfilled_interiors: bool, type_path_only: bool, skip_guides: bool, handles_multiple: bool, @@ -556,6 +557,7 @@ impl BehindKey { scope: cx.isolation, outline: opt.outline, path_only: opt.path_only, + unfilled_interiors: opt.unfilled_interiors, type_path_only: opt.type_path_only, skip_guides: opt.skip_guides, handles_multiple: cx.handles_multiple, From d632bd0761c5d60408d0203ac6e9506f4aac795d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:18:38 -0800 Subject: [PATCH 059/103] xtask: test-lint reads redirects, grouped calls, casts and dropped futures exactly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A workflow line sets a variable only when `$GITHUB_ENV` is the target of an unquoted `>`, `>>` or `>|` redirect or of a file-writing command (`tee`, `Out-File`, `Add-Content`); a printed word `GITHUB_ENV` does not count. - `split_args` tracks generic argument lists per delimiter depth, so a shift inside a const argument (`N::<{1 << 2}>`) no longer hides the next comma. - `norm_values` finds `as` at a word boundary, so `(Kind::A) as u8` is a primitive value. - A grouped argument (`reset((xs))`) passes a mutable reference on, and `(xs).len()` still only reads it. - An async closure whose futures are only made and dropped (`run();`, `let _future = run();`) runs no assertion. - A numeric index guards an `.all` assertion only until code before that assertion may shrink the indexed local. - A pinned snapshot compares its selector locals from the initializer as written, so `i` in `r.items(i as usize)` is checked for changes. - A saved count guards only when its collection is known; grouping parentheses (`(xs.len())`) still name it. - A `for` loop over `if … { … } else { … }` or `match` finds its body after the iterator's own blocks. --- xtask/src/test_lint.rs | 256 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 232 insertions(+), 24 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 595fc978f0..2b79b11660 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1043,7 +1043,24 @@ fn printed(line: &str, from: usize) -> bool { let pipeline_end = separators.iter().find(|s| s.start >= from && !s.pipe).map_or(line.len(), |s| s.start); let command = &line.as_bytes()[command_start..from]; let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); - prints && !line[pipeline_start..pipeline_end].contains("GITHUB_ENV") + prints && !writes_env_file(&line[pipeline_start..pipeline_end]) +} + +/// Whether a pipeline writes to `$GITHUB_ENV`: the file is the target of a `>` or `>>` redirect or +/// an argument of a command that writes files (`tee`, PowerShell's `Out-File`), not a word that an +/// `echo` prints. +fn writes_env_file(pipeline: &str) -> bool { + const WRITERS: [&str; 5] = ["tee", "tee-object", "out-file", "add-content", "set-content"]; + pipeline.match_indices("GITHUB_ENV").any(|(at, _)| { + let before = &pipeline[..at]; + let before = before.strip_suffix("env:").unwrap_or(before).trim_end_matches(['$', '{', '"', '\'']).trim_end(); + // A redirect (`>`, `>>`, `>|`) outside quotes; a quoted `">$GITHUB_ENV"` is printed text. + let operator = before.strip_suffix('|').unwrap_or(before); + let redirect = operator.ends_with('>') && open_quote(pipeline, operator.len() - 1).is_none(); + let command = before.rsplit('|').next().unwrap_or(before); + let program = command.split_whitespace().next().unwrap_or_default().to_ascii_lowercase(); + redirect || WRITERS.contains(&program.as_str()) + }) } /// A shell control operator outside quotes: its byte range, and whether it is a pipe (`|`) rather @@ -1363,14 +1380,19 @@ fn matching(m: &[u8], open: usize) -> Option { /// The ranges of the top-level comma-separated parts of `m[from..to]`. fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { let (mut out, mut depth, mut start) = (vec![], 0i32, from); - let mut angles = 0usize; + // The delimiter depth at which each open generic argument list started: a `<` or `>` inside a + // const argument's braces (`N::<{1 << 2}>`) is an operator there, not an angle bracket. + let mut angles: Vec = vec![]; for (j, &ch) in m.iter().enumerate().take(to).skip(from) { + let in_angle = angles.last() == Some(&depth); match ch { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth -= 1, - b'<' if angles > 0 || opens_angle(&m[from..j]) => angles += 1, - b'>' if angles > 0 => angles -= 1, - b',' if depth == 0 && angles == 0 => { + b'<' if in_angle || opens_angle(&m[from..j]) => angles.push(depth), + b'>' if in_angle => { + angles.pop(); + } + b',' if depth == 0 && angles.is_empty() => { out.push((start, j)); start = j + 1; } @@ -1423,16 +1445,23 @@ fn norm_values(b: &[u8]) -> String { &[b"u8", b"u16", b"u32", b"u64", b"u128", b"usize", b"i8", b"i16", b"i32", b"i64", b"i128", b"isize", b"f32", b"f64", b"bool", b"char"]; let mut text = norm_words(b).into_bytes(); let mut from = 0; - while let Some(at) = text[from..].windows(4).position(|w| w == b" as ").map(|p| p + from) { + // `as` as a whole word: after a space, or right after a closing delimiter (`(Kind::A)as u8`, + // since [`norm_words`] keeps a space only between two identifier characters). + let cast_at = |text: &[u8], from: usize| { + (from..text.len().saturating_sub(2)) + .find(|&p| text[p..].starts_with(b"as ") && p > 0 && (text[p - 1] == b' ' || matches!(text[p - 1], b')' | b']' | b'}'))) + }; + while let Some(word) = cast_at(&text, from) { + let at = if text[word - 1] == b' ' { word - 1 } else { word }; let start = receiver_start(&text, at); - let ty = at + 4; + let ty = word + 3; let end = ty + text[ty..].iter().take_while(|&&c| is_ident(c)).count(); if start < at && PRIMITIVES.contains(&&text[ty..end]) { let element: Vec = [&b"["[..], &text[start..at], b"][0]"].concat(); from = start + element.len(); text.splice(start..end, element); } else { - from = at + 1; + from = word + 1; } } text.retain(|c| !c.is_ascii_whitespace()); @@ -2006,7 +2035,11 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec { let unrun = closure || (is_async && m.get(value) == Some(&b'{') && matching(m, value).is_some_and(|close| skip_ws(m, close + 1) == end)); // A value bound to `_` is dropped; one bound to a name the rest of the test never // mentions is never called or awaited. - let dropped = wild || words(m, &m[name..name_end], end, t.close).is_empty(); + // Calling an async closure only makes a future, so one whose futures are all dropped + // never runs either. + let dropped = wild + || words(m, &m[name..name_end], end, t.close).is_empty() + || (is_async && closure && futures_dropped(m, &m[name..name_end], end, t.close)); if unrun && dropped && end < t.close { blank(&mut out, at, end + 1); } @@ -2015,6 +2048,29 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec { out } +/// Whether every mention of the async closure `name` in `m[from..to]` calls it and drops the +/// future: a statement `name();`, `let _ = name();`, or a `let` of a name the rest never mentions. +fn futures_dropped(m: &[u8], name: &[u8], from: usize, to: usize) -> bool { + words(m, name, from, to).into_iter().all(|p| { + let open = skip_ws(m, p + name.len()); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { return false }; + let semi = skip_ws(m, close + 1); + if m.get(semi) != Some(&b';') { + return false; + } + let before = m[..p].trim_ascii_end(); + if before.last().is_some_and(|c| matches!(c, b'{' | b';' | b'}')) { + return true; + } + let Some(lhs) = before.strip_suffix(b"=").map(<[u8]>::trim_ascii_end) else { return false }; + let n = lhs.iter().rev().take_while(|&&c| is_ident(c)).count(); + let (head, bound) = lhs.split_at(lhs.len() - n); + let head = head.trim_ascii_end(); + let is_let = head.strip_suffix(b"let").is_some_and(|h| !h.last().copied().is_some_and(is_ident)); + n > 0 && is_let && (bound == b"_" || words(m, bound, semi + 1, to).is_empty()) + }) +} + /// `(line, rule)` of each exemption comment that names a rule and a reason. /// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are /// masked. @@ -2389,12 +2445,13 @@ fn all_unguarded(v: &View) -> Vec { }) }); let sizes = Sizes { file: &v.file.m, consts: OnceCell::new(), src: v.file.src, open: v.t.open, cond: RefCell::default() }; - if checked || first_item_guard(&body, &sizes) { + if checked { return vec![]; } v.asserts .iter() .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) + .filter(|a| !first_item_guard(&body, &sizes, a.at - v.t.open)) .filter(|a| { let at = a.at - v.t.open; !direct.iter().any(|(name, to)| *to >= at || !may_shrink(&body[..at], name.as_bytes(), *to)) @@ -3832,9 +3889,11 @@ fn strip_all_predicates(body: &mut [u8]) { } /// Whether test code accesses an item in a way that fails on an empty collection: a first item, or -/// an index written as a number. -fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { +/// an index written as a number, which guards the assertion at `until` in `body`. +fn first_item_guard(body: &[u8], sizes: &Sizes, until: usize) -> bool { let compact = norm(body); + // Where each byte of `compact` sits in `body`. + let spots: Vec = body.iter().enumerate().filter(|(_, c)| !c.is_ascii_whitespace()).map(|(i, _)| i).collect(); let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; let indexed = compact.match_indices('[').any(|(at, _)| { let digits = compact[at + 1..].bytes().take_while(u8::is_ascii_digit).count(); @@ -3860,7 +3919,13 @@ fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { } let calls = &compact[end + 1..chain]; let all_over_item = [".iter()", ".into_iter()"].iter().any(|m| calls.starts_with(m)) && calls.ends_with('.'); - !all_over_item && array_literal_len(&compact[..=end], sizes).is_none_or(|n| n == 0) + // The access shows items only until code before the assertion at `until` may shrink or + // replace the local it indexes (`let _item = xs[1]; xs.clear();`). That is checked on the + // masked text, where `let xs` and `&mut xs` keep their spaces. + let receiver = &b[receiver_start(b, at)..at]; + let after_access = spots.get(chain).copied().unwrap_or(body.len()); + let shrunk = std::str::from_utf8(receiver).is_ok_and(plain_local) && may_shrink(&body[..until.max(after_access)], receiver, after_access); + !all_over_item && !shrunk && array_literal_len(&compact[..=end], sizes).is_none_or(|n| n == 0) }); indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) } @@ -3966,15 +4031,32 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { // or a local it passes as a selector (`r.items(active)`) from the binding on. let read = !plain_local(r) && plain_local(pinned) - && init(pinned, a.at).is_some_and(|(text, at)| { + && init(pinned, a.at).is_some_and(|(_, at)| { let bound = statement_end(body, at); let root = root_local(r); let root_from = let_init(body, root, at).map_or(0, |(_, pos)| statement_end(body, pos)); - keeping_base(&text, true) == r + // The initializer as written, compared in the receiver's whitespace-free form; + // its selectors are read where words stay apart (`i as usize` names `i`). + let eq = body[at..bound.min(body.len())].iter().position(|&c| c == b'=').map_or(bound, |p| at + p + 1); + let raw = &body[eq..bound.min(body.len())]; + let raw = &raw[..raw.iter().rposition(|&c| c != b';' && !c.is_ascii_whitespace()).map_or(0, |p| p + 1)]; + let worded = norm_words(raw); + let mut kept = 0; + let base_words: String = worded + .chars() + .take_while(|c| { + let more = kept < r.len(); + if more && *c != ' ' { + kept += c.len_utf8(); + } + more + }) + .collect(); + keeping_base(&norm(raw), true) == r && sizes.receiver_literals(r).is_some_and(|want| sizes.literals(let_value(body, at, bound), bound).starts_with(&want)) && !touched_after(&body[..a.at], pinned, bound, pinned) && !touched_after(body, root, bound, r) - && selector_locals(r).into_iter().all(|s| s == root || !selector_touched(body, s, bound)) + && selector_locals(&base_words).into_iter().all(|s| s == root || !selector_touched(body, s, bound)) && !gives_alias(&body[..at], root, root_from) }); // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its @@ -4964,10 +5046,12 @@ fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool }; // A local that already holds a `&mut` reborrows it when passed to a function or method // (`std::mem::take(xs)`), which can change it; a macro such as `assert_eq!` only reads it. + // Grouping parentheses are skipped: `reset((xs))` passes `xs`, and `(xs).len()` reads it. + let outer_before = body[..start].trim_ascii_end(); let passed = mut_ref - && (before.ends_with(b"(") || before.ends_with(b",")) - && matches!(after.first(), Some(b')' | b',')) - && enclosing_open(body, p).is_some_and(|open| { + && (outer_before.ends_with(b"(") || outer_before.ends_with(b",")) + && matches!(body.get(end), Some(b')' | b',')) + && enclosing_open(body, start).is_some_and(|open| { body[open] == b'(' && body[..open].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'>')) }); assigned || borrowed || called || passed @@ -5148,8 +5232,12 @@ fn bindings(body: &[u8]) -> Vec { let stmt = norm(&body[end..stop]); let init = stmt.split_once('=').map_or("", |(_, init)| init); let counts = SIZE_CHECKS.iter().any(|g| init.contains(g)); - let ident = init.bytes().take_while(|&c| is_ident(c)).count(); - let source = (ident > 0 && init[ident..].starts_with('.')).then(|| init.as_bytes()[..ident].to_vec()); + // Grouping parentheses are skipped: `(xs.len())` and `((xs).len())` read `xs`. + let grouped = init.trim_start_matches('('); + let ident = grouped.bytes().take_while(|&c| is_ident(c)).count(); + let opened = init.len() - grouped.len(); + let closed = grouped[ident..].bytes().take_while(|&c| c == b')').count(); + let source = (ident > 0 && closed <= opened && grouped[ident + closed..].starts_with('.')).then(|| grouped.as_bytes()[..ident].to_vec()); let scope_end = enclosing_block(body, at).and_then(|(open, _)| matching(body, open)).unwrap_or(body.len()); Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source, scope_end }) }) @@ -5168,7 +5256,11 @@ fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> } let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p && p < o.scope_end); reaching - .is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end))) + // A count whose collection is unknown (`let n = { let n = xs.len(); xs.clear(); n };`) + // cannot be shown to still hold. + .is_some_and(|r| { + r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_some_and(|s| !may_shrink(body, s, r.end)) + }) }) }) } @@ -6853,8 +6945,7 @@ fn for_binding(body: &[u8], name: &str, before: usize) -> Option { // A block expression as the iterator (`for n in { … } { … }`) comes before the loop body. let iter = skip_ws(body, kw + 2); let iter = if body.get(iter) == Some(&b'{') { matching(body, iter).map_or(iter, |close| close + 1) } else { iter }; - let Some((open, close)) = block_after(body, iter) else { return false }; - open < before && before < close && pattern_binds(body, name.as_bytes(), at + 3, kw) + loop_body(body, iter).is_some_and(|(open, close)| open < before && before < close && pattern_binds(body, name.as_bytes(), at + 3, kw)) }) } @@ -7058,6 +7149,24 @@ fn bracket_depth(b: &[u8]) -> isize { .sum() } +/// The braces of a `for` loop's body, given where its iterator expression starts. Blocks that belong +/// to that expression (`if … { … } else { … }`, `match … { … }`, `unsafe { … }`) come first. +fn loop_body(body: &[u8], iter: usize) -> Option<(usize, usize)> { + const OPENERS: [&[u8]; 6] = [b"if", b"else", b"match", b"unsafe", b"async", b"loop"]; + let mut from = iter; + loop { + let (open, close) = block_after(body, from)?; + let part = &body[from..open]; + // Only a keyword outside the expression's own delimiters (not the `if` inside a closure + // passed to `filter(…)`) opens a block that belongs to the iterator. + let opens = OPENERS.iter().any(|k| words(part, k, 0, part.len()).into_iter().any(|at| bracket_depth(&part[..at]) == 0)); + if !opens { + return Some((open, close)); + } + from = close + 1; + } +} + /// The braces of the block that follows an expression starting at `from`: the first `{` outside /// parentheses and brackets, and its match. fn block_after(body: &[u8], from: usize) -> Option<(usize, usize)> { @@ -9706,6 +9815,105 @@ mod tests { assert_eq!(upper_words(" printf '%s;' 'MY_SAMPLES=fixtures' >> \"$GITHUB_ENV\"").collect::>(), ["MY_SAMPLES"]); } + #[test] + fn only_a_redirect_or_tee_to_the_environment_file_writes_it() { + for line in [" echo \"MY_SAMPLES=fixtures\" \"GITHUB_ENV\"", " echo MY_SAMPLES=x GITHUB_ENV", " echo MY_SAMPLES=x | grep GITHUB_ENV"] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + for line in [" echo MY_SAMPLES=x >>\"${GITHUB_ENV}\"", " echo MY_SAMPLES=x | tee \"$GITHUB_ENV\""] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + } + + #[test] + fn split_args_counts_shifts_inside_const_arguments_apart() { + let m = b"N::<{1<<2}>, b"; + assert_eq!(split_args(m, 0, m.len()), [(0, 11), (12, 14)]); + let m = b"f::(x), (y < z, w)"; + assert_eq!(split_args(m, 0, m.len()), [(0, 12), (13, 24)]); + } + + #[test] + fn a_cast_of_a_parenthesized_operand_is_a_primitive_value() { + assert_eq!(norm_values(b"(Kind::A) as u8 + 1"), "[(Kind::A)][0]+1"); + assert_eq!(norm_values(b"x.f() as u8"), "[x.f()][0]"); + assert_eq!(norm_values(b"alias"), "alias"); + } + + #[test] + fn a_grouped_argument_passes_the_mutable_reference_on() { + let body = "let xs = &mut v; reset((xs));"; + assert!(may_shrink(body.as_bytes(), b"xs", body.find(';').unwrap_or(0) + 1)); + let read = "let xs = &mut v; let n = (xs).len();"; + assert!(!may_shrink(read.as_bytes(), b"xs", read.find(';').unwrap_or(0) + 1)); + } + + #[test] + fn a_future_made_and_dropped_runs_no_assertion() { + let made = "#[test]\nfn t() {\n let run = async || { assert_eq!(f(), 1); };\n let _future = run();\n}\n"; + assert_eq!(hits(made), [(2, "no-assertion")], "a future bound to a name never used"); + assert_eq!(hits(&made.replace("let _future = run();", "let _ = run();")), [(2, "no-assertion")], "a future bound to `_`"); + assert_eq!(hits(&made.replace("let _future = run();", "run();")), [(2, "no-assertion")], "a future made as a statement"); + assert_eq!(hits(&made.replace("let _future = run();", "run().await;")), [], "an awaited future"); + assert_eq!(hits(&made.replace("let _future = run();", "block_on(run());")), [], "a future passed on"); + assert_eq!(hits(&made.replace("let _future = run();", "let future = run();\n block_on(future);")), [], "a bound future passed on"); + } + + #[test] + fn a_length_saved_from_a_block_is_not_a_known_count() { + let src = "#[test]\nfn t() {\n let xs = f();\n let len = { let n = xs.len(); xs.clear(); n }; assert_eq!(len, 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(5, "all-unguarded")]); + } + + #[test] + fn an_indexed_item_guards_only_until_the_collection_shrinks() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n let _item = xs[1];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let cleared = src.replace(" assert!(xs", " xs.clear();\n assert!(xs"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")]); + let after = src.replace("> 0));\n", "> 0));\n xs.clear();\n"); + assert_eq!(hits(&after), [], "a collection cleared after the assertion the access guards"); + let lent = "#[test]\nfn t() {\n let xs = &mut items();\n let _item = xs[1];\n std::mem::take(xs);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(lent), [(6, "all-unguarded")], "a mutable reference passed on after the access"); + } + + #[test] + fn a_grouped_saved_length_still_names_its_collection() { + let src = + "#[test]\nfn t() {\n let xs = f();\n let len = (xs.len());\n assert_eq!(len, 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + assert_eq!(hits(&src.replace("(xs.len())", "((xs).len())")), []); + } + + #[test] + fn quoted_redirects_and_nested_keywords_are_not_what_they_look_like() { + assert_eq!(upper_words(" echo MY_SAMPLES=x \">$GITHUB_ENV\"").collect::>(), Vec::::new()); + assert_eq!(upper_words(" echo MY_SAMPLES=x >| \"$GITHUB_ENV\"").collect::>(), ["MY_SAMPLES"]); + let body = b"for n in results().filter(|n| if ready() { *n > 0 } else { false }) { use_it(n) }"; + let before = body.windows(6).position(|w| w == b"use_it").unwrap_or(0); + assert_eq!(for_binding(body, "n", before), Some(0)); + } + + #[test] + fn a_cast_selector_changed_after_the_snapshot() { + let local = "#[test]\nfn t() {\n let mut i = 1;\n let got: Vec = r.items(i as usize).iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1]);\n assert!(r.items(i as usize).iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(local), [], "an unchanged cast selector"); + let changed = local.replace(" assert!(r.items", " i = 0;\n assert!(r.items"); + assert_eq!(hits(&changed), [(7, "all-unguarded")], "a cast selector changed after the snapshot"); + let grouped = local.replace("i as usize", "(i) as usize"); + assert_eq!(hits(&grouped), [], "an unchanged grouped cast selector"); + assert_eq!(hits(&grouped.replace(" assert!(r.items", " i = 0;\n assert!(r.items")), [(7, "all-unguarded")]); + } + + #[test] + fn a_loop_body_follows_the_branches_of_an_if_iterator() { + let body = b"for n in if flag() { a } else { b } { use_it(n) }"; + let before = body.windows(6).position(|w| w == b"use_it").unwrap_or(0); + assert_eq!(for_binding(body, "n", before), Some(0)); + let inner = body.windows(3).position(|w| w == b"{ a").unwrap_or(0) + 2; + assert_eq!(for_binding(body, "n", inner), None); + } + #[test] fn only_the_printing_pipeline_writes_the_environment_file() { let script = "run: \"echo \\\"MY_SAMPLES=fixtures\\\"\\necho \\\"OTHER=x\\\" >> \\\"$GITHUB_ENV\\\"\""; From 3072440389a45f8b89f52d28b5ab896696ddc5bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:20:39 -0800 Subject: [PATCH 060/103] Tests: census reads more closure, guard and macro forms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A block behind `if false` or `while false` never runs, so a closure call inside it does not replace a binding that held the entry. - A parenthesized literal (`(false) && …`) decides `&&` and `||` like the bare literal; `(ready && true)` stays a compound operand. - Closure parameters accept nested struct patterns (`|Outer { row: Row { c } }|`). - A closure parameter's shadow lasts through an explicit return type to the end of the body, and brackets in the return type are skipped. - An uncalled closure with a return type (`|| -> () { … }`) is recognized, and a later block is not taken for its body. - Whitespace or a masked comment may separate a macro name from its `!` (`stringify /* note */ !(…)`) and `.` from `await`. - A raw identifier `r#return`, `r#break` or `r#continue` is not an exit. --- xtask/src/test_lint.rs | 255 ++++++++++++++++++++++++++++++++--------- 1 file changed, 204 insertions(+), 51 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 7e480e234e..fd340d78ea 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1296,9 +1296,11 @@ fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(usize, String, bool)> { continue; } let end = i + m[i..to].iter().take_while(|&&c| is_ident(c)).count(); - let bang = m.get(end) == Some(&b'!'); - let after = skip_ws(m, end + usize::from(bang)); - let after = if bang { after } else { skip_turbofish(m, after) }; + // Whitespace, a masked comment included, may separate a macro's name from its `!` + // (`stringify /* note */ !(…)`); `!=` is an operator. + let bang_at = skip_ws(m, end); + let bang = m.get(bang_at) == Some(&b'!') && m.get(bang_at + 1) != Some(&b'='); + let after = if bang { skip_ws(m, bang_at + 1) } else { skip_turbofish(m, skip_ws(m, end)) }; if matches!(m.get(after), Some(b'(' | b'[' | b'{')) && (bang || m[after] == b'(') { let name = String::from_utf8_lossy(&m[i..end]).into_owned(); let method = i > 0 && m[i - 1] == b'.'; @@ -2186,7 +2188,7 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { continue; } let Some(end) = closure_params_end(b, at, to) else { continue }; - let mut until = skip_ws(b, end + 1); + let mut until = closure_body_start(b, end, to); if b.get(until) == Some(&b'{') { until = matching(b, until).unwrap_or(to).min(to); } else { @@ -2370,14 +2372,8 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None") }; // The arguments of `stringify!` are not evaluated, so a call there does not run. - let unevaluated: Vec<(usize, usize)> = calls_at(b, from, to) - .iter() - .filter(|(_, name, _)| name == "stringify!") - .filter_map(|(p, name, _)| { - let o = skip_ws(b, p + name.len()); - matching(b, o).map(|c| (o, c)) - }) - .collect(); + let unevaluated: Vec<(usize, usize)> = + calls_at(b, from, to).iter().filter(|(_, name, _)| name == "stringify!").filter_map(|&(p, _, _)| macro_args(b, p)).collect(); (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { let mut start = name_end; while start > from && is_ident(b[start - 1]) { @@ -2603,14 +2599,16 @@ fn in_stringify(b: &[u8], from: usize, to: usize, at: usize) -> bool { /// The brackets around the arguments of each `stringify!` in `b[from..to]`. fn stringify_args(b: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { - calls_at(b, from, to) - .into_iter() - .filter(|(_, name, _)| name == "stringify!") - .filter_map(|(p, name, _)| { - let open = skip_ws(b, p + name.len()); - matching(b, open).map(|close| (open, close)) - }) - .collect() + calls_at(b, from, to).into_iter().filter(|(_, name, _)| name == "stringify!").filter_map(|(p, _, _)| macro_args(b, p)).collect() +} + +/// The brackets around the arguments of the macro whose name starts at `name` (`stringify!(…)`, +/// also with whitespace before or after the `!`). +fn macro_args(b: &[u8], name: usize) -> Option<(usize, usize)> { + let end = name + b[name..].iter().take_while(|&&c| is_ident(c)).count(); + let bang = skip_ws(b, end); + let open = (b.get(bang) == Some(&b'!')).then(|| skip_ws(b, bang + 1))?; + matching(b, open).map(|close| (open, close)) } /// Checks whether `start` runs whenever assertions pass, or may run at all when `may_run` is true. @@ -2681,6 +2679,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac return false; } } else if left_early + // A block behind a literal `false` guard (`if false { reset(); }`) never runs. + || (may_run && never_runs_guard(prefix)) || (!may_run && !prefix.ends_with(b"|") && !nested_for @@ -2915,7 +2915,7 @@ fn closure_params_end(b: &[u8], pipe: usize, to: usize) -> Option { // A struct pattern follows its path (`Row {`); its braces hold names, labels and `..`. let named = b[pipe + 1..i].trim_ascii_end().last().copied().is_some_and(is_ident); let close = matching(b, i).filter(|&c| c < to && named)?; - if b[i + 1..close].iter().any(|c| matches!(c, b'"' | b'=' | b';' | b'{' | b'}')) { + if !struct_pattern_braces(b, i, close) { break None; } i = close + 1; @@ -2925,6 +2925,41 @@ fn closure_params_end(b: &[u8], pipe: usize, to: usize) -> Option { } } +/// Where the body of the closure whose parameter list closes with the `|` at `end` starts. An +/// explicit return type comes before a block body (`|c: Command| -> Result<(), Error> { … }`). +fn closure_body_start(b: &[u8], end: usize, to: usize) -> usize { + let body = skip_ws(b, end + 1); + if !b[body..to.max(body)].starts_with(b"->") { + return body; + } + // Brackets in the return type (`-> [u8; { 1 }]`) hold no body. + let mut i = body + 2; + while i < to && b[i] != b'{' { + i = if matches!(b[i], b'(' | b'[') { matching(b, i).map_or(to, |close| close + 1) } else { i + 1 }; + } + i.min(to) +} + +/// Whether the braces of the struct pattern opening at `open` and closing at `close` hold only names, +/// labels, `..` and nested struct patterns (`Outer { row: Row { c } }`). +fn struct_pattern_braces(b: &[u8], open: usize, close: usize) -> bool { + let mut i = open + 1; + while i < close { + match b[i] { + b'"' | b'=' | b';' | b'}' => return false, + b'{' => { + let named = b[open + 1..i].trim_ascii_end().last().copied().is_some_and(is_ident); + match matching(b, i).filter(|&c| c < close && named) { + Some(c) if struct_pattern_braces(b, i, c) => i = c + 1, + _ => return false, + } + } + _ => i += 1, + } + } + true +} + /// The patterns of a closure parameter list `params` without their types: the text of each /// top-level parameter before its `:` (`c` in `c: Command`, `Row { c: other }` in `Row { c: other }: Row`). fn closure_param_patterns(params: &str) -> Vec<&str> { @@ -3032,7 +3067,7 @@ fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[ (open + 1..at).any(|k| { matches!(b[k], b'(' | b'[' | b'{') && matching(b, k).is_some_and(|close| at < close) - && b[open + 1..k].trim_ascii_end().strip_suffix(b"!").is_some_and(|h| { + && b[open + 1..k].trim_ascii_end().strip_suffix(b"!").map(<[u8]>::trim_ascii_end).is_some_and(|h| { let name = &h[h.iter().rposition(|&c| !is_ident(c)).map_or(0, |i| i + 1)..]; matches!(name, b"stringify" | b"concat_idents" | b"macro_rules") }) @@ -3107,7 +3142,7 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as } let Some(close) = matching(b, open) else { return false }; let next = skip_ws(b, close + 1); - let awaited = b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); + let awaited = awaits_at(b, next); // The future is the whole argument of `block_on` itself, not of a name that ends with it // (`discard_block_on`), and not part of a longer expression that may never poll it. // Grouping parentheses around the future (`block_on((run()))`) are skipped. @@ -3267,18 +3302,14 @@ fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: && matching(b, open).is_some_and(|close| statement_end(&b[..close], at) < start) }; // The arguments of `stringify!` are not evaluated. - let unevaluated: Vec<(usize, usize)> = calls_at(b, open + 1, start) - .iter() - .filter(|(_, name, _)| name == "stringify!") - .filter_map(|(p, name, _)| { - let o = skip_ws(b, p + name.len()); - matching(b, o).map(|c| (o, c)) - }) - .collect(); + let unevaluated: Vec<(usize, usize)> = + calls_at(b, open + 1, start).iter().filter(|(_, name, _)| name == "stringify!").filter_map(|&(p, _, _)| macro_args(b, p)).collect(); let evaluated = |at: usize| !unevaluated.iter().any(|&(o, c)| o < at && at < c); + // A raw identifier (`r#return`) names a binding, not the keyword. + let keyword = |at: usize| !b[..at].ends_with(b"r#"); let returns = words(b, b"return", open + 1, start) .into_iter() - .any(|at| evaluated(at) && !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); + .any(|at| keyword(at) && evaluated(at) && !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); // A `?` follows an operand: a name, a call or index, or a block expression (`{ prepare() }?`). let tries = !definite && (open + 2..start).any(|i| { @@ -3299,9 +3330,9 @@ fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: }); // Without `definite`, [`skips_rest_of_iteration`] reads a `continue`. let loops = loop_body - && [b"break".as_slice(), b"continue"][..if definite { 2 } else { 1 }] - .iter() - .any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| evaluated(at) && !nested(at, true) && (!definite || always(at)))); + && [b"break".as_slice(), b"continue"][..if definite { 2 } else { 1 }].iter().any(|kw| { + words(b, kw, open + 1, start).into_iter().any(|at| keyword(at) && evaluated(at) && !nested(at, true) && (!definite || always(at))) + }); if loop_body { loops } else { returns || tries } } @@ -3319,19 +3350,45 @@ fn declared_in(b: &[u8], body: usize, start: usize, name: &str) -> bool { /// literal `lit` (`false && …`, `true || …`), which decides the operator without its right side. fn literal_operand(b: &[u8], stmt: usize, op: usize, lit: &[u8]) -> bool { let left = b[stmt..op].trim_ascii_end(); - let Some(rest) = left.strip_suffix(lit) else { return false }; - if rest.last().copied().is_some_and(is_ident) { - return false; + // Parentheses around the literal group it (`(false) && …`); `(ready && true)` stays compound. + let grouped = || { + left.len() + .checked_sub(1) + .filter(|&close| left[close] == b')') + .and_then(|close| (0..close).rev().find(|&o| left[o] == b'(' && matching(left, o) == Some(close))) + .filter(|&open| ungrouped(&left[open..]) == lit) + .map(|open| &left[..open]) + }; + left.strip_suffix(lit).or_else(grouped).filter(|rest| !rest.last().copied().is_some_and(is_ident)).is_some_and(|rest| { + let rest = rest.trim_ascii_end(); + match rest.last() { + None | Some(b'(' | b'{' | b',' | b';') => true, + Some(b'=') => !matches!(rest.get(rest.len().wrapping_sub(2)), Some(b'=' | b'!' | b'<' | b'>')), + // `a && true || …` has `a && true` as its left operand, while `a && false && …` is still false. + Some(b'&') => lit == b"false" && rest.ends_with(b"&&"), + Some(b'|') => rest.ends_with(b"||"), + _ => false, + } + }) +} + +/// Whether `prefix`, the text of a statement before a block's `{`, is `if false`, `else if false` or +/// `while false`, also with parentheses around the literal: the block never runs. +fn never_runs_guard(prefix: &[u8]) -> bool { + fn keyword<'a>(text: &'a [u8], kw: &[u8]) -> Option<&'a [u8]> { + text.strip_prefix(kw).filter(|rest| !rest.first().copied().is_some_and(is_ident)) } - let rest = rest.trim_ascii_end(); - match rest.last() { - None | Some(b'(' | b'{' | b',' | b';') => true, - Some(b'=') => !matches!(rest.get(rest.len().wrapping_sub(2)), Some(b'=' | b'!' | b'<' | b'>')), - // `a && true || …` has `a && true` as its left operand, while `a && false && …` is still false. - Some(b'&') => lit == b"false" && rest.ends_with(b"&&"), - Some(b'|') => rest.ends_with(b"||"), - _ => false, + let prefix = keyword(prefix, b"else").map_or(prefix, <[u8]>::trim_ascii_start); + keyword(prefix, b"if").or_else(|| keyword(prefix, b"while")).is_some_and(|cond| ungrouped(cond) == b"false") +} + +/// `text` without the balanced parentheses that wrap all of it (`((false))` gives `false`). +fn ungrouped(mut text: &[u8]) -> &[u8] { + text = text.trim_ascii(); + while text.first() == Some(&b'(') && matching(text, 0) == Some(text.len() - 1) { + text = text[1..text.len() - 1].trim_ascii(); } + text } /// Whether `head`, the text before a closure's parameters, ends with a call to `drop`, which @@ -3369,7 +3426,16 @@ fn polled_in_place(b: &[u8], from: usize, kw: usize, open: usize) -> bool { before = from + b[from..before - 1].trim_ascii_end().len(); } let next = skip_ws(b, close + 1); - (b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident)) || passed_to_block_on(b, start, close + 1) + awaits_at(b, next) || passed_to_block_on(b, start, close + 1) +} + +/// Whether `.await` starts at `at`, with optional whitespace or a masked comment between the `.` +/// and the keyword (`. /* poll */ await`), and not `.awaited`. +fn awaits_at(b: &[u8], at: usize) -> bool { + b.get(at) == Some(&b'.') && { + let kw = skip_ws(b, at + 1); + b[kw..].starts_with(b"await") && !b.get(kw + 5).copied().is_some_and(is_ident) + } } /// Where the body of the innermost move closure around `start` that captures `name` ends: neither @@ -3379,7 +3445,7 @@ fn move_closure_copy_end(b: &[u8], from: usize, to: usize, start: usize, name: & words(b, b"move", from, start).into_iter().rev().find_map(|at| { let pipe = Some(skip_ws(b, at + 4)).filter(|&pipe| b.get(pipe) == Some(&b'|'))?; let end = (pipe + 1..to).find(|&i| b[i] == b'|')?; - let body = skip_ws(b, end + 1); + let body = closure_body_start(b, end, to); let mut until = body; if b.get(body) == Some(&b'{') { until = matching(b, body).unwrap_or(to).min(to); @@ -3413,7 +3479,16 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & b'(' | b'[' if depth > 0 => depth -= 1, b'{' if depth > 0 => depth -= 1, b'{' => { - let Some(params) = b[from..i].trim_ascii_end().strip_suffix(b"|") else { continue }; + // A return type may follow the parameters (`|| -> () { … }`), but not a statement + // after an earlier closure (`|| -> () {}; {`). + let head = b[from..i].trim_ascii_end(); + let head = match head.iter().rposition(|&c| c == b'|') { + Some(p) if head[p + 1..].trim_ascii_start().starts_with(b"->") && !head[p + 1..].iter().any(|c| matches!(c, b'{' | b'}')) => { + &head[..=p] + } + _ => head, + }; + let Some(params) = head.strip_suffix(b"|") else { continue }; let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); @@ -5684,8 +5759,12 @@ fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { .iter() .filter(|(_, name, _)| name == "stringify!" || name == "sleep" || LOG_MACROS.contains(&name.as_str())) .filter_map(|(p, name, _)| { - let o = skip_ws(m, p + name.len()); - matching(m, o).map(|c| (o, c)) + if name.ends_with('!') { + macro_args(m, *p) + } else { + let o = skip_ws(m, p + name.len()); + matching(m, o).map(|c| (o, c)) + } }) .collect(); let before = |p: usize| m[..p].trim_ascii_end(); @@ -11600,6 +11679,40 @@ mod tests { ); } + #[test] + fn census_skips_writes_behind_literal_guards() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; if false { reset(); } app.run(input); assert!(menu(c).is_some());" + ), + [], + "a block behind if false never runs the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; if ready { reset(); } app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a block behind an unknown guard may run the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; (false) && { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [], + "a parenthesized literal false left of && never runs the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; (ready && true) || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a parenthesized compound operand is not the literal true" + ); + } + #[test] fn census_exits_count_match_alternatives_and_skip_stringify() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); @@ -11670,6 +11783,46 @@ mod tests { [], "a path segment in a closure's struct pattern does not bind the name" ); + assert_eq!( + census("let run = |Outer { row: Row { c } }| { render(c, offset); }; run(fallback()); assert!(menu(c).is_some());"), + [(2, "census")], + "a nested struct pattern in closure parameters shadows the entry" + ); + assert_eq!( + census("let run = |c: Command| -> Result<(), Error> { render(c, offset); Ok(()) }; run(fallback()); assert!(menu(c).is_some());"), + [(2, "census")], + "a closure parameter shadows the entry through an explicit return type" + ); + assert_eq!( + census("let _ = stringify /* note */ !(verify_entry(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "whitespace between stringify and its ! still leaves the arguments unevaluated" + ); + assert_eq!( + census("block_on(async { let r#return = 0; consume(r#return); app.run(c); }); assert!(menu(c).is_some());"), + [], + "a raw identifier r#return is not an exit" + ); + assert_eq!( + census("(async { app.run(c); }). /* poll */ await; assert!(menu(c).is_some());"), + [], + "an await after a masked comment polls the block" + ); + assert_eq!( + census("block_on(async { let _saved = || -> () { prepare(); app.run(c); }; }); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled closure with a return type does not run its body" + ); + assert_eq!( + census("let _saved = || -> () {}; { app.run(c); } assert!(menu(c).is_some());"), + [], + "a block after an uncalled closure with a return type is not its body" + ); + assert_eq!( + census("let run = |c: Command| -> [u8; { 1 }] { render(c, offset); [0] }; run(fallback()); assert!(menu(c).is_some());"), + [(2, "census")], + "a brace inside a closure's return type does not end the parameter's shadow" + ); assert_eq!( census( "let mut input = c; let mut reset = || { input = fallback(); }; false && ready || { reset(); true }; app.run(input); assert!(menu(c).is_some());" From 578410b14a516a28c3a38aec1908db0523c3bea3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:26:57 -0800 Subject: [PATCH 061/103] Scripts: a batch that clears a print failure replaces the earlier receipt When a print batch cleared an earlier spool failure, its receipt was added to the hover notes without removing the receipt of the batch sent before the failure, so the notes held two receipts. The cleared-failure path now drops the earlier receipt first, as the path without a failure does. The docs say the failure clears once the worker sends every job of the later batch without a failure. --- crates/ui-egui/src/print.rs | 9 ++++-- crates/ui-egui/src/tests/script_print.rs | 37 ++++++++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 8e7c4d5061..fde8322118 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -457,8 +457,13 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec io::show_with_notes(app, first, kept), diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 9c0af57d41..8d3e4c68bf 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -430,6 +430,43 @@ fn queued_sent_batches_keep_other_hover_notes() { assert_eq!(notes, &vec!["Sent".to_string(), startup], "the second batch's note replaces the first's"); } +/// A batch that clears a spool failure replaces the note of the batch sent before the failure, +/// so the hover notes hold one receipt. +#[test] +fn a_batch_that_clears_a_failure_replaces_the_earlier_receipt() { + let mut app = worker_print_app("The printer Lab is offline"); + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 10.0, "Print"); + crate::background::wait_all(&mut app); + let failure = app.ui.status.clone(); + let startup = "The startup script b.jsx failed".to_string(); + let tracked = app.ui.script_print_failure_notes.clone(); + crate::io::show_with_notes(&mut app, failure.clone(), vec![failure, startup.clone()]); + app.ui.script_print_failure_notes = tracked; + app.services.print = worker_print_app("").services.print; + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 20.0, "Print"); + app.services.print = worker_print_app("The printer Lab is offline").services.print; + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 30.0, "Print"); + assert_eq!(app.background.jobs.len(), 2, "both batches are queued"); + crate::background::wait_all(&mut app); + assert!(app.ui.status.contains("The printer Lab is offline"), "{}", app.ui.status); + let (_, notes) = app.ui.status_notes.as_mut().expect("the failure keeps the other hover notes"); + assert_eq!(notes.get(1..), Some(&["Sent".to_string(), startup.clone()][..]), "{notes:?}"); + let earlier = "Sent to Lab earlier".to_string(); + notes[1] = earlier.clone(); + app.ui.script_print_receipt = Some(earlier); + app.services.print = worker_print_app("").services.print; + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 40.0, "Print"); + crate::background::wait_all(&mut app); + assert!(!app.ui.status.contains("offline"), "{}", app.ui.status); + let (status, notes) = app.ui.status_notes.as_ref().expect("the startup error stays in the hover notes"); + assert_eq!(status, &app.ui.status); + assert_eq!(notes, &vec!["Sent".to_string(), startup], "one receipt, from the last batch"); +} + /// A spool failure keeps the startup scripts' errors in the status bar's hover notes. #[test] fn a_spool_failure_does_not_hide_a_later_startup_script_failure() { diff --git a/docs/mcp.md b/docs/mcp.md index 3370f30236..82fbe76647 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4915,7 +4915,7 @@ status bar. A queued run also waits while the jobs the previous run prepared for Each queued run lists the printers listed when the runs were queued; the runs with reason `launch` list no printers, so they cannot print to a printer. A job that fails to spool is reported in the status bar even when a later run or a later job's note took it. A batch submitted after the failure was reported clears it once the -worker sends that batch; a failure reported after that batch was submitted stays. +worker sends every job of that batch without a failure; a failure reported after that batch was submitted stays. Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from the prompt shown on quitting, between two runs, drops the runs not yet started, and the status bar says so. While that prompt is open, the next run does not start. Under `--automation-read-root` it reads the folder only when the folder lies inside a read root. With the preference on, `ui.runScript` and `ui.runInstalledScript` still return `script.run`'s reply, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 22b1a7b092..e22f8c8936 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1130,7 +1130,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`); a batch submitted after a spool failure was reported clears it once the worker sends the batch, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. + - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`); a batch submitted after a spool failure was reported clears it once the worker sends every job of the batch without a failure, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. From 78eba16ad636129936405ef63cb60bb676d1992c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:45:43 -0800 Subject: [PATCH 062/103] Printing: a bare ::1 server is not the local CUPS scheduler CUPS (cupsSetServer) reads the digits after the last colon of an unbracketed server name as its port, so `::1` names host `:` on port 1. scheduler_is_local took any unbracketed name with several colons as a host without a port and matched `::1` as loopback, so `::1` with IPP_PORT=8631 used the local PPD folder for a queue on another scheduler. It now splits such a name at its last colon when the last group starts with a digit, as CUPS does. The IPv6 loopback is local only as `[::1]`, which docs/mcp.md now names. --- apps/vectorcraft/src/printing.rs | 12 ++++++++++-- docs/mcp.md | 4 ++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 9c7fdb1076..ba5b6a3a18 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -332,7 +332,7 @@ mod system { } } /// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain - /// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. + /// `sockets`, or `localhost`, `127.0.0.1` or `[::1]` with no port or port 631, each with an optional `/version=` suffix. /// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder /// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket. #[cfg(not(windows))] @@ -347,6 +347,10 @@ mod system { rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':'))) } else if server.matches(':').count() == 1 { server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port))) + } else if let Some((host, port)) = server.rsplit_once(':').filter(|(_, port)| port.starts_with(|c: char| c.is_ascii_digit())) { + // CUPS (`cupsSetServer`) reads the digits after the last `:` of an unbracketed name as its port, so `::1` is + // host `:` on port 1. + (host, Some(port)) } else { (server, None) }; @@ -741,7 +745,6 @@ mod client_conf_tests { Some("LocalHost:631"), Some("localhost:631"), Some("127.0.0.1:631"), - Some("::1"), Some("[::1]:631"), Some("[::1]"), Some("localhost/version=1.1"), @@ -755,6 +758,7 @@ mod client_conf_tests { "192.0.2.7", "[2001:db8::1]:631", "2001:db8::1", + "::1", "localhost.example.com", "print.example.com:631/version=1.1", "localhost:8631", @@ -777,6 +781,10 @@ mod client_conf_tests { assert!(!scheduler_is_local(Some(&server_with_ipp_port(named, Some(8631))), &own, real), "{named}"); assert!(scheduler_is_local(Some(&server_with_ipp_port(named, Some(631))), &own, real), "{named}"); } + // CUPS reads an unbracketed `::1` as host `:` on port 1, so it is not the local scheduler on any `IPP_PORT`. + for port in [None, Some(631), Some(8631)] { + assert!(!scheduler_is_local(Some(&server_with_ipp_port("::1", port)), &own, real), "::1 with {port:?}"); + } assert!(scheduler_is_local(Some(&server_with_ipp_port("localhost:631", Some(8631))), &own, real), "a port in the server name wins"); assert!(scheduler_is_local(Some(&server_with_ipp_port("/run/cups/cups.sock", Some(8631))), &own, real)); } diff --git a/docs/mcp.md b/docs/mcp.md index 7671533e12..acebe75c46 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13721,7 +13721,7 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than CUPS's own domain socket, a socket a `Listen` line of `/etc/cups/cupsd.conf` names (or a link to either), -`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), or when no scheduler is named, CUPS has no domain +`localhost`, `127.0.0.1` or `[::1]` (each with no port or port 631), or when no scheduler is named, CUPS has no domain socket and `IPP_PORT` sets a port other than 631, lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is @@ -13735,7 +13735,7 @@ A scheduler named without a port is on the port in `IPP_PORT` when it is set. Th rule above: a loopback name without a port counts as local only when `IPP_PORT` is unset or 631. With `localhost` and `IPP_PORT=8631`, the printer sizes come from that server instead of the local PPD folder. An IPv6 address named as the server without brackets (`fd00::cafe`) is asked in brackets (`ipp://[fd00::cafe]/printers/`); -as in CUPS, a last group that starts with a digit (`2001:db8::1`) is read as the port, so such an address needs brackets. +as in CUPS, a last group that starts with a digit (`2001:db8::1`) is read as the port, so such an address needs brackets. A bare `::1` is host `:` on port 1, not the local scheduler. Scoped addresses encode the zone separator as `%25`, as in `ipp://[fe80::abcd%25eth0]/printers/`. After a `printer` change, read `media` again once the new printer's sizes have loaded. Until then, the dialog keeps the previous printer's paper list. A printer paper the new printer lists by the same name and size stays chosen under From f53f074518bb988a891927cb2d850cc0c41417f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:45:53 -0800 Subject: [PATCH 063/103] Selection: describe the Outline and hit-target exceptions for unfilled shapes The Select Inside Unfilled Shapes description now names Outline view as an exception, and says that with the preference off a click starts a selection box only when it hits nothing else. The #9175 progress line says the same: a marquee starts only when the press misses the shape's stroke, other art and the shape's visible center point. --- crates/ui-egui/src/prefs_dialog/descriptions.rs | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index 00b5bf8314..dec9066151 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -141,7 +141,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("objectSelectionByPathOnly", "A click selects a filled object only on its path, not inside its fill."), ( "selectInsideUnfilledShapes", - "A click inside a closed shape with no fill selects the shape when nothing else is there, unless Object Selection by Path Only is on; off, it starts a selection box.", + "A click inside a closed shape with no fill selects the shape when nothing else is there, unless Object Selection by Path Only is on or the view is Outline; off, a click that hits nothing else starts a selection box.", ), ( "snapToPointTolerance", diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 95fa3b975a..309fea10ee 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -711,7 +711,7 @@ since 2026-10-01. **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss by default, with Object Selection by Path Only on or in Outline view, and with Select Inside Unfilled Shapes on and Path Only off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. -- **Clicks inside unfilled shapes (#9175):** with Selection & Anchor Display › Select Inside Unfilled Shapes on (off by default; off, a click or drag there starts a marquee) and Object Selection by Path Only off, the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference` (MCP), and `a_drag_inside_an_unfilled_shape_makes_a_marquee_unless_asked` (Selection tool). Scores and estimates unchanged. +- **Clicks inside unfilled shapes (#9175):** with Selection & Anchor Display › Select Inside Unfilled Shapes on (off by default; off, a click or drag there starts a marquee when it hits nothing else there: not the shape's stroke, other art or the shape's visible center point) and Object Selection by Path Only off, the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference` (MCP), and `a_drag_inside_an_unfilled_shape_makes_a_marquee_unless_asked` (Selection tool). Scores and estimates unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. From bb4e3308afe43804938eefd6cfe25c4c7e098f22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:57:39 -0800 Subject: [PATCH 064/103] File formats: DWG drawings open and place through the DXF reader File > Open, File > Place and document.dxfInfo read DWG drawings. The craft-libs craft-dwg bridge converts the drawing to DXF bytes and the existing DXF reader reads them, so a DWG takes the DXF Import Options (layout, ratio or fit, lineweights, centering, merged layers) and comes in with the same layers, blocks and units as the DXF it converts to. What the conversion skips is listed in the warnings. - vectorcraft-cad: dwg module. On desktop the conversion runs in a copy of the program started with --dwg-worker (vectorcraft and vectorcraft-cli call serve_if_asked and use_own_worker), so a damaged file ends that copy, not the app. Inputs over 512 MiB, or a DXF rendition over 1 GiB, are refused. The last conversion (up to 128 MiB of DXF), or its error, is kept, so the dialog's layout list, each layout preview and the open read the file once. R1.x and R2.x drawings are refused with a hint to save as DXF. - Engine: a read-only dwg format (detected by content or by .dwg), in the open and place extension lists, not associated with the app by packaging. DWG leaves the unsupported list; exporting to it says to export DXF instead, Export As keeps it greyed out, and Save over the drawing is refused. - UI: the DXF Import Options dialog opens for .dwg files on Open, Place and a Shift-click with the place cursor. - NOTICE and licenses/acadrust-0.6.6/: acadrust 0.6.6 (MPL-2.0, unmodified) and its third-party notices. - Docs: docs/mcp.md, docs/file-format-parity.md, docs/roadmap.md and the progress line in docs/target-app-parity.md. Tests build DWG files from DXF drawings with craft-dwg's writer: a DWG comes in as its DXF does (layers, bounds, strokes, units, blocks), with the DXF options, through Place, and in dxfInfo; a truncated DWG is an error; saving or exporting a DWG writes nothing. Fixes #3450 --- Cargo.lock | 62 +++ Cargo.toml | 2 + NOTICE | 6 + apps/vectorcraft-cli/src/main.rs | 6 + apps/vectorcraft/src/main.rs | 7 + crates/cad/Cargo.toml | 3 +- crates/cad/src/dwg.rs | 140 +++++++ crates/cad/src/import.rs | 35 +- crates/cad/src/import/tests_dwg.rs | 80 ++++ crates/cad/src/lib.rs | 4 + crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/fileio.rs | 5 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/dxf.rs | 33 +- crates/engine/src/cmd/fileio/dxfimport.rs | 6 +- crates/engine/src/cmd/fileio/formats.rs | 13 +- crates/engine/src/cmd/fileio/load.rs | 12 +- .../engine/src/cmd/fileio/tests_dwgimport.rs | 111 ++++++ crates/engine/src/cmd/fileio/tests_dxf.rs | 9 +- .../engine/src/cmd/fileio/tests_dxfimport.rs | 2 +- crates/engine/src/cmd/place.rs | 6 +- crates/engine/src/lib.rs | 3 + crates/ui-egui/src/dialogs/dxf_import.rs | 23 +- crates/ui-egui/src/dialogs/export_as.rs | 4 +- crates/ui-egui/src/place.rs | 6 +- docs/file-format-parity.md | 4 +- docs/mcp.md | 15 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 1 + licenses/acadrust-0.6.6/LICENSE | 375 ++++++++++++++++++ .../acadrust-0.6.6/THIRD_PARTY_NOTICES.md | 40 ++ 31 files changed, 953 insertions(+), 66 deletions(-) create mode 100644 crates/cad/src/dwg.rs create mode 100644 crates/cad/src/import/tests_dwg.rs create mode 100644 crates/engine/src/cmd/fileio/tests_dwgimport.rs create mode 100644 licenses/acadrust-0.6.6/LICENSE create mode 100644 licenses/acadrust-0.6.6/THIRD_PARTY_NOTICES.md diff --git a/Cargo.lock b/Cargo.lock index 75c87011b4..4527ceb03a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,30 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "acadrust" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8923c99ea1f151cb7fc17ce2fc14f8b1e330fa22611e535602d985c0cc3c89a2" +dependencies = [ + "anyhow", + "bitflags 2.13.2", + "byteorder", + "encoding_rs", + "flate2", + "foldhash 0.2.0", + "indexmap", + "itoa", + "memmap2", + "nom 7.1.3", + "oem_cp", + "once_cell", + "rayon", + "ryu", + "thiserror 2.0.21", + "web-time", +] + [[package]] name = "accesskit" version = "0.25.2" @@ -1510,6 +1534,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-dwg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +dependencies = [ + "acadrust", + "log", +] + [[package]] name = "craft-dxf" version = "0.1.0" @@ -5864,6 +5897,15 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oem_cp" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7959d3349f484aec36462f98226983578bf7d33f9b034c32967489c7000e1f" +dependencies = [ + "phf 0.11.3", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -6036,6 +6078,15 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared 0.11.3", +] + [[package]] name = "phf" version = "0.13.1" @@ -6103,6 +6154,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.13.1" @@ -8618,6 +8678,7 @@ dependencies = [ name = "vectorcraft-cad" version = "0.25.1" dependencies = [ + "craft-dwg", "craft-dxf", "craft-image-codecs", "craft-plotter", @@ -8726,6 +8787,7 @@ dependencies = [ "craft-codepage", "craft-doc", "craft-docpath", + "craft-dwg", "craft-font-catalog", "craft-font-store", "craft-image-codecs", diff --git a/Cargo.toml b/Cargo.toml index 7dab0c8895..45590bd3b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,6 +34,8 @@ craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ec # DXF tags, reader and writer (craft-libs#778, #926, #927). craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } diff --git a/NOTICE b/NOTICE index 4d7c813796..4790c330bc 100644 --- a/NOTICE +++ b/NOTICE @@ -35,6 +35,12 @@ based in part on the work of the Independent JPEG Group. WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is under the Apache License 2.0 with the LLVM exception. +DWG drawings are read by the acadrust crate 0.6.6 (https://crates.io/crates/acadrust/0.6.6), through +craft-dwg from https://github.com/storytold/craft-libs. acadrust is used unmodified under the Mozilla +Public License 2.0; its source is available at that address. Its license text and its third-party +notices (code adapted from ACadSharp, Copyright (c) 2021 Albert Domenech, MIT License) are in +licenses/acadrust-0.6.6/. + The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 51d2aec7b6..b4a65c7ba0 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -209,6 +209,12 @@ fn help() -> Result<(), String> { } fn main() -> ExitCode { + // A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits. + if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() { + std::process::exit(code); + } + // DWG drawings open through that copy, so a damaged file can't end this process. + vectorcraft_engine::dwg::use_own_worker(); // Before the first render: the cores the process may run on. #[cfg(windows)] windows_cores::install(); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 4b1c77e0f1..2455cd191c 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -573,10 +573,17 @@ fn finish_pending_update(nightly: bool) { } fn main() -> std::process::ExitCode { + // A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits, + // before the launch profile, the logger or any window. + if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() { + std::process::exit(code); + } // The launch profile first: a nightly build self-isolates or uses the Launcher's profile here, // before the update helper, the logger, fonts or any saved state, and `--version` is answered // here too. let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS }; + // DWG drawings open through that copy, so a damaged file can't end this process. + vectorcraft_engine::dwg::use_own_worker(); let nightly = launch_profile::current().is_nightly(); #[cfg(windows)] finish_pending_update(nightly); diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 1cbf8dc431..55f3ab8278 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -3,13 +3,14 @@ name = "vectorcraft-cad" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer" +description = "VectorCraft CAD interchange: DXF export through craft-dxf, DXF and DWG import, and an HP-GL/2 plot file reader and writer" [lints] workspace = true [dependencies] craft-dxf = { workspace = true } +craft-dwg = { workspace = true } craft-plotter = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs new file mode 100644 index 0000000000..65ed42af6a --- /dev/null +++ b/crates/cad/src/dwg.rs @@ -0,0 +1,140 @@ +//! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result. +//! +//! The conversion runs in a child process once the program has called [`use_own_worker`] (and +//! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort +//! ends that process, not VectorCraft. Without a worker the conversion is refused, unless +//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there. + +use std::hash::BuildHasher; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; + +pub use craft_dwg::{WORKER_ARG, allow_in_process, serve_if_asked, use_own_worker}; + +/// The largest DXF rendition kept for the next read of the same drawing (128 MiB). +const MAX_KEPT: usize = 128 << 20; + +/// Is `bytes` a DWG drawing (an `AC10nn` version code first)? +pub fn is_dwg(bytes: &[u8]) -> bool { + craft_dwg::is_dwg(bytes) +} + +/// A DWG drawing as DXF bytes, and what the conversion left out. +#[derive(Debug, PartialEq)] +pub(crate) struct Converted { + pub dxf: Vec, + pub notes: Vec, +} + +type Outcome = Result, String>; + +/// The outcome of the last drawing converted, by a hash of its bytes and its length. Open reads a +/// drawing's layouts, draws a preview of each in its dialog and then opens it, and each of those +/// reads the same file; a file the conversion refused (or whose worker stopped) is refused again +/// without another conversion. +#[derive(Default)] +struct Kept { + hasher: std::collections::hash_map::RandomState, + last: Option<((u64, usize), Outcome)>, +} + +impl Kept { + fn key(&self, bytes: &[u8]) -> (u64, usize) { + (self.hasher.hash_one(bytes), bytes.len()) + } + + fn get(&self, key: (u64, usize)) -> Option { + self.last.as_ref().filter(|(k, _)| *k == key).map(|(_, outcome)| outcome.clone()) + } + + fn keep(&mut self, key: (u64, usize), outcome: &Outcome) { + if outcome.as_ref().is_ok_and(|c| c.dxf.len() > MAX_KEPT) { + self.last = None; + } else { + self.last = Some((key, outcome.clone())); + } + } +} + +/// The conversion of `bytes` that `kept` holds, else `convert`'s, which `kept` then holds. The +/// lock is not held while `convert` runs, so another drawing can be converted at the same time. +fn through(kept: &Mutex, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result) -> Outcome { + let key = { + let kept = kept.lock().unwrap_or_else(PoisonError::into_inner); + let key = kept.key(bytes); + if let Some(outcome) = kept.get(key) { + return outcome; + } + key + }; + let outcome = convert(bytes).map(Arc::new); + kept.lock().unwrap_or_else(PoisonError::into_inner).keep(key, &outcome); + outcome +} + +static KEPT: LazyLock> = LazyLock::new(Mutex::default); + +/// `bytes` (a DWG drawing) as DXF, within craft-dwg's default limits (512 MiB of DWG, 1 GiB of DXF). +pub(crate) fn to_dxf(bytes: &[u8]) -> Outcome { + through(&KEPT, bytes, convert) +} + +fn convert(bytes: &[u8]) -> Result { + let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?; + Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() }) +} + +/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one. +fn worded(message: &str) -> String { + message + .replace("accepted by this bridge", "VectorCraft opens") + .replace("types this bridge can't preserve", "types VectorCraft can't read") + .replace("; saving over the original file would lose them", "") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn counting<'a>(calls: &'a std::cell::Cell, dxf: &'a [u8]) -> impl FnOnce(&[u8]) -> Result + 'a { + move |_| { + calls.set(calls.get() + 1); + Ok(Converted { dxf: dxf.to_vec(), notes: vec![] }) + } + } + + #[test] + fn the_same_drawing_is_converted_once_and_another_drawing_again() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let a = through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + let again = through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap(); + assert_eq!(calls.get(), 1); + assert_eq!(again.dxf, a.dxf); + through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 2); + // The first drawing is no longer held. + through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 3); + } + + #[test] + fn a_refused_file_is_refused_again_without_converting_and_an_oversized_rendition_is_not_kept() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + assert_eq!(through(&kept, b"AC1015 bad", |_| Err("DWG: no".to_string())).unwrap_err(), "DWG: no"); + let again = through(&kept, b"AC1015 bad", counting(&calls, b"0\nEOF\n")); + assert_eq!((again.unwrap_err().as_str(), calls.get()), ("DWG: no", 0)); + let big = vec![b' '; MAX_KEPT + 1]; + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + assert_eq!(calls.get(), 2, "a rendition over MAX_KEPT is converted again"); + } + + #[test] + fn messages_name_what_vectorcraft_does() { + let m = worded("DWG: the file is 9.9 MB, larger than the 1.0 MB accepted by this bridge"); + assert_eq!(m, "DWG: the file is 9.9 MB, larger than the 1.0 MB VectorCraft opens"); + let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them"); + assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)"); + } +} diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 9216c57c29..7c6dc0a516 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -1,4 +1,5 @@ -//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. +//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. A DWG drawing comes +//! in the same way, converted to DXF first ([`crate::dwg`]). //! //! The drawing's model space (or a paper layout) comes in at a ratio (1 unit of the art = N //! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred @@ -102,11 +103,24 @@ pub fn is_dxf(bytes: &[u8]) -> bool { false } -/// The tags of a DXF file and where it is damaged (DWG files are refused). -fn tags(bytes: &[u8]) -> Result<(Vec, Option), String> { - if bytes.starts_with(b"AC10") || bytes.starts_with(b"AC1.") { - return Err("this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that".into()); +/// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read +/// left out: where the file is damaged, and what the DWG conversion couldn't read. +fn tags(bytes: &[u8]) -> Result<(Vec, Vec), String> { + if crate::dwg::is_dwg(bytes) { + let converted = crate::dwg::to_dxf(bytes)?; + let (tags, mut notes) = dxf_tags(&converted.dxf)?; + notes.extend(converted.notes.iter().cloned()); + return Ok((tags, notes)); } + // R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number. + if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) { + return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into()); + } + dxf_tags(bytes) +} + +/// The tags of a DXF file and where it is damaged. +fn dxf_tags(bytes: &[u8]) -> Result<(Vec, Vec), String> { let (tags, damaged) = craft_dxf::parse_recovering(bytes).map_err(|e| match e { craft_dxf::DxfError::TooLarge { .. } => "the drawing is too large to open".to_string(), _ if bytes.starts_with(reader::BINARY_SENTINEL) => "this binary DXF file is damaged or cut short".to_string(), @@ -115,7 +129,7 @@ fn tags(bytes: &[u8]) -> Result<(Vec, Option), String> { if tags.is_empty() { return Err("not a DXF drawing".into()); } - Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")))) + Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")).into_iter().collect())) } /// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it. @@ -182,7 +196,7 @@ pub fn info(bytes: &[u8]) -> Result { }) } -/// Import a DXF drawing with `o`. +/// Import a DXF or DWG drawing with `o`. pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { let (w, h) = o.fit_to; if !(w > 0.0 && h > 0.0 && w.max(h) <= build::MAX_EXTENT) { @@ -193,7 +207,7 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { { return Err(format!("scale must be a number from {} to {}, not {s}", SCALE_RANGE.start(), SCALE_RANGE.end())); } - let (tags, damaged) = tags(bytes)?; + let (tags, notes) = tags(bytes)?; let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags)); if d.sections == 0 { return Err("not a DXF drawing".into()); @@ -214,10 +228,13 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { }; let (mut document, mut warnings) = build::Build::new(&d, o).run(layout, natural, ratio)?; document.units = if o.fit { unit } else { o.unit.unwrap_or(unit) }; - warnings.extend(damaged); + warnings.extend(notes); document.limit_depth_noting(&mut warnings); Ok(Imported { document, warnings }) } #[cfg(test)] mod tests; +// craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on aarch64. +#[cfg(all(test, not(target_arch = "wasm32"), not(all(target_os = "freebsd", target_arch = "aarch64"))))] +mod tests_dwg; diff --git a/crates/cad/src/import/tests_dwg.rs b/crates/cad/src/import/tests_dwg.rs new file mode 100644 index 0000000000..72f4157221 --- /dev/null +++ b/crates/cad/src/import/tests_dwg.rs @@ -0,0 +1,80 @@ +//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF +//! does; damaged files are errors. + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, Unit}; +use vectorcraft_geom::{Rect, shapes}; + +use super::*; +use crate::{DxfOptions, DxfVersion}; + +/// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse. +fn dxf() -> Vec { + let mut d = Document::new(200.0, 100.0); + let layer = d.add_layer(Some("Walls")); + let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0); + let rect = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), stroke(Color::rgb(1.0, 0.0, 0.0))); + let oval = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), stroke(Color::rgb(0.0, 0.0, 1.0))); + for n in [rect, oval] { + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() }; + crate::export(&d, &o).unwrap().bytes +} + +fn dwg() -> Vec { + crate::dwg::allow_in_process(); + craft_dwg::dxf_to_dwg_as(&dxf(), "AC1018").unwrap() +} + +/// Each layer holding art, with each object's bounds (to 0.01 pt) and stroke color. +fn art(doc: &Document) -> Vec<(Option, Vec<([i64; 4], Option<[u8; 4]>)>)> { + let r = |v: f64| (v * 100.0).round() as i64; + doc.layers + .iter() + .filter_map(|layer| { + let objects: Vec<_> = layer + .children()? + .iter() + .map(|n| { + let b = n.geometric_bounds().unwrap(); + let stroke = match n.appearance.stroke().map(|s| &s.paint) { + Some(Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), + _ => None, + }; + ([r(b.x0), r(b.y0), r(b.x1), r(b.y1)], stroke) + }) + .collect(); + (!objects.is_empty()).then(|| (layer.name.clone(), objects)) + }) + .collect() +} + +#[test] +fn a_dwg_drawing_comes_in_as_its_dxf_does() { + let (dxf, dwg) = (dxf(), dwg()); + assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf)); + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; + let want = art(&import(&dxf, &o).unwrap().document); + assert_eq!(want.len(), 1, "{want:?}"); + assert_eq!(want[0].0.as_deref(), Some("Walls")); + assert_eq!(want[0].1.len(), 2, "{want:?}"); + assert_eq!(art(&import(&dwg, &o).unwrap().document), want); + let i = info(&dwg).unwrap(); + assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model"))); + assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}"); +} + +#[test] +fn a_damaged_dwg_is_an_error_that_names_dwg() { + let mut cut = dwg(); + cut.truncate(cut.len() / 3); + let e = import(&cut, &ImportOptions::default()).unwrap_err(); + assert!(e.contains("DWG"), "{e}"); + assert!(info(&cut).is_err()); + // An R1.x or R2.x drawing is refused without reading it. + for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] { + let e = import(old, &ImportOptions::default()).unwrap_err(); + assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}"); + } +} diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index b54d9022bf..c272376668 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -14,15 +14,18 @@ //! clipping) is approximated or left out, and each such loss comes back as a warning. //! //! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`]. +//! It reads a DWG drawing too, converted to DXF by [`dwg`]. //! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`]. //! //! - `aci`: the 256-colour index palette and the nearest index of a colour. //! - The ASCII file around those entities is written by `craft_dxf::drawing`. //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. +//! - `dwg`: DWG drawings converted to DXF by craft-dwg, in a child process on desktop builds. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. mod aci; +pub mod dwg; #[cfg(test)] mod expansion_test; pub mod hpgl; @@ -33,6 +36,7 @@ use vectorcraft_doc::{Document, Unit}; use vectorcraft_geom::Rect; pub use aci::{aci_rgb, nearest_aci}; +pub use dwg::is_dwg; pub use import::{DxfInfo, ImportOptions, Imported, import, info, is_dxf}; /// How deep symbols, blocks and brush art may nest in one another (deeper art is left out). diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fe4f7d10e..2487dcd01d 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -114,6 +114,8 @@ apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] } zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] } [dev-dependencies] +# DWG files for the `.dwg` open and place tests, written from DXF by craft-dwg. +craft-dwg = { workspace = true } # JPEG XL files for the `.jxl` open and place tests. zune-jpegxl = { workspace = true } zune-core = { workspace = true } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 52871e23fa..fd81791573 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -74,7 +74,7 @@ use serde_json::{Value, json}; pub(crate) use action_batch::action_step; pub use action_batch::batch_overwrites_one_file; -pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; +pub use dxf::{UNSUPPORTED, Unsupported, unsupported, write_hint}; pub use encode::{ ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds, note_texts, @@ -248,6 +248,9 @@ mod tests_eps; #[cfg(test)] mod tests_dxfimport; +// craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on aarch64. +#[cfg(all(test, not(target_arch = "wasm32"), not(all(target_os = "freebsd", target_arch = "aarch64"))))] +mod tests_dwgimport; #[cfg(test)] mod tests_hpgl; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index bddd245b71..66ee66a5a0 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as PageMaker, with what to use instead)}", always, formats ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8004234c07..c92d9b8ad0 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -1,6 +1,7 @@ //! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As //! → DXF Options): the options parsed from the params, one drawing per artboard with Use -//! Artboards, and the formats that can't be written (DWG, PageMaker) with what to use instead. +//! Artboards, and the formats that can't be written (DWG, which opens, and PageMaker) with what to +//! use instead. use std::sync::Arc; @@ -99,20 +100,12 @@ pub struct Unsupported { } /// Formats people ask for that VectorCraft doesn't read or write. Append-only. -pub const UNSUPPORTED: &[Unsupported] = &[ - Unsupported { - id: "dwg", - label: "DWG", - extensions: &["dwg"], - hint: "DWG is not available (no openly licensed writer exists): export DXF instead, which CAD apps open", - }, - Unsupported { - id: "pmd", - label: "PageMaker", - extensions: &["pmd"], - hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here", - }, -]; +pub const UNSUPPORTED: &[Unsupported] = &[Unsupported { + id: "pmd", + label: "PageMaker", + extensions: &["pmd"], + hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here", +}]; /// The unsupported format an id or extension (any case, leading dot allowed) names. pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> { @@ -120,6 +113,16 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> { UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str())) } +/// Formats VectorCraft opens but doesn't write, with what to export instead. +const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")]; + +/// What to write instead of the format an id or extension (any case, leading dot allowed) names, +/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG). +pub fn write_hint(id_or_ext: &str) -> Option<&'static str> { + let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase(); + unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(id, _)| *id == k).map(|(_, hint)| *hint)) +} + impl Unsupported { pub fn to_json(&self) -> Value { json!({ "id": self.id, "label": self.label, "extensions": self.extensions, "hint": self.hint }) diff --git a/crates/engine/src/cmd/fileio/dxfimport.rs b/crates/engine/src/cmd/fileio/dxfimport.rs index eef7aca4cd..2d16034c09 100644 --- a/crates/engine/src/cmd/fileio/dxfimport.rs +++ b/crates/engine/src/cmd/fileio/dxfimport.rs @@ -1,4 +1,4 @@ -//! Opening and placing DXF drawings: the `dxf` options `document.open` and `file.place` read +//! Opening and placing DXF and DWG drawings: the `dxf` options `document.open` and `file.place` read //! (layout, scale or fit, lineweights, centring, merged layers) and `document.dxfInfo` (layouts, //! layers, units) for the DXF Import Options dialog. @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "DXF Info", [], None, - "{path} or {name?, dataBase64} what a DXF drawing holds → {version (2018, R12…), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}; a DWG answers an error saying to save it as DXF", + "{path} or {name?, dataBase64} what a DXF or DWG drawing holds → {version (2018, R12…; a DWG's is that of the DXF it converts to), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}", always, dxf_info )] @@ -70,7 +70,7 @@ pub(super) fn options(cmd: &str, p: Option<&Value>) -> Result { }) } -/// Import a DXF drawing → the document and import notes. +/// Import a DXF or DWG drawing → the document and import notes. pub(super) fn import(bytes: &[u8], o: &ImportOptions) -> Result<(Document, Vec)> { let r = vectorcraft_cad::import(bytes, o).map_err(err)?; Ok((r.document, r.warnings)) diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 4fee998d8e..f8da5b941c 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -561,6 +561,9 @@ pub const FORMATS: &[Format] = &[ // Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size // composite, the layers combined, or the preview with a note. Exports don't write them. reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true), + // DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF + // reader with the DXF import options. Exports don't write them. + reader("dwg", "DWG", &["dwg"], "image/vnd.dwg", false), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -622,6 +625,7 @@ pub const OPEN_EXTS: &[&str] = &[ "cdt", "cmx", "pcraft", + "dwg", ]; /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to @@ -629,11 +633,11 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. -/// The packaging declares no type for HP-GL plot files, PICT pictures or layered raster `.pcraft` -/// documents either. +/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft` +/// documents or DWG drawings either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -724,6 +728,7 @@ pub const PLACE_EXTS: &[&str] = &[ "cdt", "cmx", "pcraft", + "dwg", "txt", "rtf", "docx", @@ -1087,6 +1092,8 @@ pub fn writable_format(format_param: Option<&str>, path: Option<&str>) -> std::r Ok(f) } else if TEMPLATE_FORMATS.contains(&f.id) { Err(format!("{} files are written by file.saveAsTemplate", f.label)) + } else if let Some(hint) = super::dxf::write_hint(f.id) { + Err(hint.to_string()) } else { Err(format!("{} files can be opened but not written (see document.formats)", f.label)) } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 53cac16bee..f152132c69 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -47,12 +47,12 @@ impl Loaded { /// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or /// what an importer plug-in reads, as the reference app opens such files (#5820). A native /// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the - /// units of its root's size, pixels when it gives none), a DXF drawing (the unit it was read - /// in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows + /// units of its root's size, pixels when it gives none), a DXF or DWG drawing (the unit it was + /// read in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows /// change, not its art. pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self { let records_units = - self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf"); + self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf" | "dwg"); if !records_units { self.doc.units = crate::units::pref_unit(&prefs.units_general); } @@ -125,6 +125,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if vectorcraft_cad::is_dxf(bytes) { return format("dxf"); } + if vectorcraft_cad::is_dwg(bytes) { + return format("dwg"); + } if let Some(kind) = vectorcraft_metafile::sniff(bytes) { return format(kind.id()); } @@ -560,7 +563,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } read } - "dxf" => { + // A DWG drawing is read as the DXF craft-dwg converts it to. + "dxf" | "dwg" => { let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?; (doc, warnings, false) } diff --git a/crates/engine/src/cmd/fileio/tests_dwgimport.rs b/crates/engine/src/cmd/fileio/tests_dwgimport.rs new file mode 100644 index 0000000000..5eb5c95a69 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_dwgimport.rs @@ -0,0 +1,111 @@ +//! DWG through the commands: `document.open`, `document.dxfInfo` and File → Place read a DWG +//! drawing as the DXF it converts to, with the DXF options; DWG is in the format table as read +//! only, and saving or exporting one says to write DXF. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; + +use super::tests_dxfimport::plan; +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// The DXF test drawing as a DWG 2004 file, written by craft-dwg. +fn plan_dwg() -> Vec { + vectorcraft_cad::dwg::allow_in_process(); + craft_dwg::dxf_to_dwg_as(&plan(), "AC1018").unwrap() +} + +fn open(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> crate::Result { + let mut p = json!({"name": name, "dataBase64": b64(bytes)}); + if let (Some(p), Value::Object(e)) = (p.as_object_mut(), extra) { + p.extend(e); + } + s.execute("document.open", &p) +} + +fn layer_names(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().filter_map(|l| l.name.clone()).collect() +} + +fn leaves(s: &Session) -> Vec { + let mut out = vec![]; + s.doc().unwrap().doc.walk(|n| { + if n.children().is_none() { + out.push(n.clone()); + } + }); + out +} + +#[test] +fn document_open_reads_a_dwg_drawing_as_its_dxf() { + let mut s = Session::new(); + open(&mut s, "plan.dxf", &plan(), json!({})).unwrap(); + let (want_layers, want_board, want_leaves) = (layer_names(&s), s.doc().unwrap().doc.artboards[0].rect, leaves(&s).len()); + let r = open(&mut s, "plan.dwg", &plan_dwg(), json!({})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("dwg"), Some("plan.dwg"))); + assert_eq!(layer_names(&s), want_layers); + let st = s.doc().unwrap(); + let board = st.doc.artboards[0].rect; + assert!((board.width() - want_board.width()).abs() < 1e-6 && (board.height() - want_board.height()).abs() < 1e-6, "{board:?}"); + assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters); + assert_eq!(leaves(&s).len(), want_leaves); + assert_eq!(leaves(&s).iter().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).count(), 2, "the block's two inserts"); + // The DXF options apply. + open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"fit": true, "mergeLayers": true}})).unwrap(); + assert_eq!(layer_names(&s), ["Layer 1"]); + assert!(open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"layout": "Sheet 9"}})).is_err()); +} + +#[test] +fn a_dwg_opened_is_never_written_back_as_dwg() { + let dir = std::env::temp_dir().join(format!("vc-dwg-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("plan.dwg"); + let dwg = plan_dwg(); + std::fs::write(&path, &dwg).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap(); + let e = s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("not DWG"), "{e}"); + let e = s.execute("document.export", &json!({"format": "dwg"})).unwrap_err().to_string(); + assert!(e.contains("export DXF instead"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), dwg, "the drawing is unchanged"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn dxf_info_and_place_read_a_dwg() { + let mut s = Session::new(); + let dxf = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&plan())})).unwrap(); + let dwg = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&plan_dwg())})).unwrap(); + for k in ["units", "layouts", "unit", "scale"] { + assert_eq!(dwg[k], dxf[k], "{k}"); + } + let layers: Vec<&str> = dwg["layers"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(layers.contains(&"Walls") && layers.contains(&"Notes"), "{layers:?}"); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("file.place", &json!({"name": "plan.dwg", "dataBase64": b64(&plan_dwg()), "dxf": {"fit": true}})).unwrap(); + assert_eq!(r["format"], "dwg"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + assert!((b.width() - 600.0).abs() < 1.0 && (b.center().y - 200.0).abs() < 0.5, "fitted to the artboard: {b:?}"); +} + +#[test] +fn dwg_is_read_only_and_detected_by_content() { + let f = format("dwg").unwrap(); + assert!(f.read && !f.write); + assert!(OPEN_EXTS.contains(&"dwg") && PLACE_EXTS.contains(&"dwg") && UNASSOCIATED_EXTS.contains(&"dwg")); + assert_eq!(detect("drawing.bin", &plan_dwg()).map(|f| f.id), Some("dwg"), "the content tells"); + let mut s = Session::new(); + let r = s.execute("document.formats", &json!({})).unwrap(); + assert!(r["readable"].as_array().unwrap().contains(&json!("dwg"))); + assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg"))); + assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg")); +} diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index b5129d1910..7a04d93ddc 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -1,5 +1,5 @@ //! DXF export through the commands: options, artboards, selection, images, and the formats that -//! can't be written (DWG, PageMaker). +//! can't be written (DWG, which opens, and PageMaker). use serde_json::{Value, json}; @@ -293,7 +293,7 @@ fn formats_list_dxf_and_what_can_not_be_written() { } assert!(r["writable"].as_array().unwrap().contains(&json!("dxf"))); let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap()).collect(); - assert_eq!(unsupported, ["dwg", "pmd"]); + assert_eq!(unsupported, ["pmd"]); } #[test] @@ -301,7 +301,7 @@ fn dwg_and_pagemaker_say_what_to_use_instead() { let mut s = two_boards(); for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] { let e = s.execute("document.export", &p).unwrap_err().to_string(); - assert!(e.contains("DWG is not available") && e.contains("DXF"), "{p}: {e}"); + assert!(e.contains("DWG files open but can't be written") && e.contains("export DXF instead"), "{p}: {e}"); } // PICT opens; it isn't written. let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string(); @@ -315,7 +315,8 @@ fn dwg_and_pagemaker_say_what_to_use_instead() { .execute("document.open", &json!({"name": "site.dwg", "dataBase64": vectorcraft_format::base64_encode(b"AC1032\0\0")})) .unwrap_err() .to_string(); - assert!(e.contains("DWG is not available"), "{e}"); + // A DWG that can't be converted says so (DWG drawings open: see tests_dwgimport). + assert!(e.contains("DWG"), "{e}"); let e = s .execute("document.open", &json!({"name": "brochure.PMD", "dataBase64": vectorcraft_format::base64_encode(b"PageMaker")})) .unwrap_err() diff --git a/crates/engine/src/cmd/fileio/tests_dxfimport.rs b/crates/engine/src/cmd/fileio/tests_dxfimport.rs index d3dcdcb86c..524913dcb7 100644 --- a/crates/engine/src/cmd/fileio/tests_dxfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_dxfimport.rs @@ -14,7 +14,7 @@ fn b64(bytes: &[u8]) -> String { /// A millimetre drawing: a 200 × 100 rectangle on layer Walls, a circle on layer Notes, a block /// "Mark" (a short line) inserted twice, and a paper layout holding a line. -fn plan() -> Vec { +pub(super) fn plan() -> Vec { let pairs: &[(i32, &str)] = &[ (0, "SECTION"), (2, "HEADER"), diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 949b470263..7329d2f02d 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -357,9 +357,9 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o let (natural, warnings) = (s.frame, s.warnings.clone()); return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None }); } - let anchored = format.id == "dxf" && (opts.dxf.fit || !opts.dxf.center); + let anchored = matches!(format.id, "dxf" | "dwg") && (opts.dxf.fit || !opts.dxf.center); let (mut doc, warnings) = { - // Of the open options, only a DXF drawing's apply (the colour mode stays the file's). + // Of the open options, only a DXF or DWG drawing's apply (the colour mode stays the file's). let o = fileio::LoadOptions { dxf: opts.dxf, ..Default::default() }; let mut l = fileio::load_with(src.name, &src.bytes, &o)?; // An Affinity file whose native document couldn't be read is only its preview: it @@ -380,7 +380,7 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o let board = doc.artboards.first().map(|a| a.rect).filter(|_| anchored); let layers = std::mem::take(&mut doc.layers); let symbols = doc.symbol_boxes(); - let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") { + let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "dwg" | "hpgl") { // An SVG with `crop: "crop"` asked for is framed and clipped by its viewBox (its artboard), // as a PDF by its page: art drawn on a shared canvas keeps its place and scale (#788). By // default, as Illustrator places one, it is its art's bounds. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 16e1e7f5a5..30bba3b4e8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,6 +45,9 @@ pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use cmd::{EyedropperOptions, PathfinderOptions}; pub use journal::Journal; pub use tooling::{UiRequest, ViewInfo}; +/// DWG drawings are converted in a child process: a program calls `dwg::serve_if_asked` first in +/// `main` and `dwg::use_own_worker` at startup. +pub use vectorcraft_cad::dwg; pub use vectorcraft_doc as doc; pub use vectorcraft_doc::cancel; pub use vectorcraft_pathops::{SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, simplify_level_tolerance}; diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 59d5dddca0..a493f3474b 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -1,4 +1,4 @@ -//! DXF Import Options: opening or placing a DXF drawing asks which layout to import (model space +//! DXF Import Options: opening or placing a DXF or DWG drawing asks which layout to import (model space //! or a paper layout, previewed), its scale (fitted to the artboard, or 1 unit of the art = N //! drawing units: by default the drawing at 1:1 in its own unit), whether lineweights scale with //! it, whether it is centred, and whether its layers merge into one. @@ -320,10 +320,15 @@ impl HoldsOk for DxfImportDialog { } } +/// Is `ext` the extension of a drawing this dialog opens (DXF, or DWG converted to DXF)? +pub(crate) fn is_drawing_ext(ext: &str) -> bool { + matches!(ext, "dxf" | "dwg") +} + /// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they -/// are a DXF drawing; false when they aren't (or can't be read: the loader then says why). +/// are a DXF or DWG drawing; false when they aren't (or can't be read: the loader then says why). pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, place: Option<&Value>) -> bool { - if fileio::detect(name, bytes).is_none_or(|f| f.id != "dxf") { + if fileio::detect(name, bytes).is_none_or(|f| !is_drawing_ext(f.id)) { return false; } let Ok(info) = vectorcraft_cad::info(bytes) else { return false }; @@ -347,23 +352,23 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option bool { let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension); - if p.get("dxf").is_some() || named.as_deref() != Some("dxf") { + if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_drawing_ext) { return false; } - let Some((name, bytes, path)) = place_source(app, p, |ext| ext == "dxf") else { return false }; + let Some((name, bytes, path)) = place_source(app, p, is_drawing_ext) else { return false }; offer(app, &name, &bytes, path, Some(p)) } /// The `dxf` options a drawing `file.place` params `p` name is placed with when Show Import Options /// is off: the choices confirmed last (fit, lineweights, centring, layers), the drawing at 1:1 in -/// its own unit. `None` when `p` names no `.dxf` drawing or already gives `dxf` options. +/// its own unit. `None` when `p` names no `.dxf` or `.dwg` drawing or already gives `dxf` options. pub fn last_options(app: &VectorcraftApp, p: &Value) -> Option { let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension); - if p.get("dxf").is_some() || named.as_deref() != Some("dxf") { + if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_drawing_ext) { return None; } Some(remembered(app)) diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 949382c23e..e98d212976 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -29,7 +29,7 @@ pub(super) const KIND: &str = "exportAs"; /// The built-in formats Export As writes (the native format and `.ai` are Save As's). static BUILT_IN: LazyLock> = LazyLock::new(|| fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect()); -/// Formats listed after them that can't be written (`fileio::unsupported` ids), greyed out. +/// Formats listed after them that can't be written (`fileio::write_hint` ids), greyed out. const UNAVAILABLE: [(&str, &str); 1] = [("dwg", "DWG (use DXF)")]; /// The formats Export As writes: the built-in ones, then those of the installed exporter plug-ins. @@ -46,7 +46,7 @@ fn from_plugin(f: &Format) -> bool { fn unavailable(fields: &DialogFields) -> Option<(&'static str, &'static str)> { let id = fields.text("format")?; let (_, label) = UNAVAILABLE.iter().find(|u| u.0 == id)?; - Some((label, fileio::unsupported(id)?.hint)) + Some((label, fileio::write_hint(id)?)) } /// The chosen format (PNG when the field names none Export As writes). diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 3ee2b402dc..46fe91a1dc 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -726,7 +726,7 @@ fn set_aside_import_options(p: &mut Value) { let ext = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension).unwrap_or_default(); let keys: &[&str] = match ext.as_str() { "pdf" | "ai" | "ait" => &["page", "crop"], - "dxf" => &["dxf"], + "dxf" | "dwg" => &["dxf"], "psd" | "pdd" | "psb" => &["layers", "hiddenLayers", "importSlices"], _ if crate::dialogs::text_import::is_text(p) => &["text"], _ => &[], @@ -758,7 +758,7 @@ fn source_index(p: &Value) -> Option { usize::try_from(p.get(vectorcraft_tools::place::SOURCE_INDEX)?.as_u64()?).ok() } -/// The params of a cursor click (`rect` at the file's queued size) on a PDF or DXF file, whose +/// The params of a cursor click (`rect` at the file's queued size) on a PDF, DXF or DWG file, whose /// import options may change its size (another page, another scale): placed as its options place /// it at the click (`at`, the center of the box the click gave), as File › Place of that one file /// places it, instead of fitted into the box of the first page or the default scale. The cursor @@ -769,7 +769,7 @@ fn clicked_at_full_size(app: &VectorcraftApp, p: &Value) -> Value { return p; } let Some(name) = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::file_name) else { return p }; - if !matches!(fileio::extension(&name).as_str(), "pdf" | "ai" | "ait" | "dxf") { + if !matches!(fileio::extension(&name).as_str(), "pdf" | "ai" | "ait" | "dxf" | "dwg") { return p; } let r: Vec = p.get("rect").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index b6de624c20..31f0da4316 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -61,7 +61,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 36 | missing: FreeHand, DWG | +| Formats opened or placed | ~30 | 37 | missing: FreeHand | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 20 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -373,7 +373,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | -| DWG | open, export | no | no | no open spec; DXF instead | +| DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | no (export DXF instead) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer); not in the web build | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | | PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | diff --git a/docs/mcp.md b/docs/mcp.md index d659e73c88..39b5384cd0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12403,9 +12403,9 @@ blending, opacity masks, raster effects, clipping) comes back in `warnings`. In no linked file, and `warnings` carries "an image couldn't be decoded and is missing from the picture" once for all such images. -DWG can't be written (no openly licensed writer exists): `document.formats` lists it under `unsupported` with that -hint, and exporting to it answers with the hint to export DXF. PICT files open and place (see PICT import) but can't -be written. +DWG drawings open and place (see DXF import) but can't be written: `document.formats` lists `dwg` as readable and +not writable, and exporting to it answers with the hint to export DXF. PICT files open and place (see PICT +import) but can't be written. ```json {"name":"run_command","arguments":{"command":"document.exportDxf","params":{"path":"/tmp/plan.dxf","version":"2013","unit":"mm","scale":10,"preserve":"editability"}}} @@ -12429,7 +12429,14 @@ hatches filled, pattern hatches as their boundaries), text and multiline text po (one per look when their art takes colour "by block"), anonymous blocks such as dimensions groups. Indexed colours (7 is black on paper), true colour, lineweights (`scaleLineweights` scales them with the art), linetypes and transparency resolve through layers and blocks. What is left out (viewports, images, meshes, unknown entities) is -listed in `warnings`. ASCII and binary DXF files are read; DWG files answer an error saying to save them as DXF. +listed in `warnings`. ASCII and binary DXF files are read. + +DWG drawings (by content or the `.dwg` extension) open, place and answer `document.dxfInfo` the same way, with the +same `dxf` options: craft-dwg converts the drawing to DXF (acadrust 0.6.6, MPL-2.0) and the DXF reader reads that. +In the desktop app and `vectorcraft-cli` the conversion runs in a copy of the program started with `--dwg-worker`, so +a damaged file stops that copy, not the app; it gives up after 30 minutes. Files over 512 MiB, or whose DXF would +pass 1 GiB, are refused. What the conversion skips (objects of types it can't read) is listed in `warnings`. R1.x and +R2.x drawings (`MC0.`, `AC1.` and `AC2.` headers) and the web build answer an error saying to save the drawing as DXF. ```json {"name":"run_command","arguments":{"command":"document.dxfInfo","params":{"path":"/tmp/plan.dxf"}}} diff --git a/docs/roadmap.md b/docs/roadmap.md index efbb51831b..2ebf5da5d3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -198,7 +198,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors the topmost, newest objects keep their Smart Guides targets (#8531) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). DWG drawings open and place through the DXF reader (estimates unchanged). Left: DWG export (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders done (#1880); vertical type in progress (Type › Type Orientation, #5027) | 45–60 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f96e28264f..f630eb16f3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2559,6 +2559,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). + - DWG drawings open and place, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker` on desktop, and the DXF reader reads it with the DXF Import Options. DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - `.cmx` exchange files with 32-bit coordinates open and place: `craft-cdr` reads their color, pen, line type, dash and outline tables and each page's instructions, and the importer maps pages, layers (a layer that holds nothing is left out), groups and curves, with uniform fills and outlines, as it maps a `.cdr` drawing's. Text, images, rectangles, ellipses, clipping paths, other fills, arrowheads and lenses are named in the warnings, and big-endian files and files with 16-bit coordinates are refused with a message (`craft-cdr` `storytold/craft-libs@9b28b56bc7` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`, `crates/engine/tests/import_fuzz.rs`). diff --git a/licenses/acadrust-0.6.6/LICENSE b/licenses/acadrust-0.6.6/LICENSE new file mode 100644 index 0000000000..7321068a3e --- /dev/null +++ b/licenses/acadrust-0.6.6/LICENSE @@ -0,0 +1,375 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under the name "LEGAL", and included in all Covered Software +distributed in Source Code Form. Except to the extent prohibited by +statute or regulation, such description must be sufficiently detailed +for a recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + diff --git a/licenses/acadrust-0.6.6/THIRD_PARTY_NOTICES.md b/licenses/acadrust-0.6.6/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000000..35fd822bbd --- /dev/null +++ b/licenses/acadrust-0.6.6/THIRD_PARTY_NOTICES.md @@ -0,0 +1,40 @@ +# Third-Party Notices + +## ACadSharp + +The DWG reader and writer include code ported and adapted from ACadSharp. The repository +history's initial DWG support commit identifies the source classes explicitly, including +`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and +`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`. + +Copyright (c) 2021 Albert Domenech + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## DWG Format References + +DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG +specification and reverse engineering, including comparison with drawings produced by CAD +applications. LibreDWG is used as a secondary cross-check for selected field names and +layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's +`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not +translated routines. The repository history and source review found no LibreDWG routines +ported into the implementation. The source comments identify the specific cross-checks. From e3415d38889b1469534e1ee16b72f8d72c9873e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 06:50:59 -0800 Subject: [PATCH 065/103] Variables: an unfinished Data Set name stays with its document and data set The Data Set box renamed the current data set while the name was still being typed: the panel ran dataset.rename for every value the field reported, not only a committed one. Typing a name and then switching to another document left the first document's data set renamed, without Enter. The box now renames only when the name is committed (Enter or leaving the box). Its edit target is the document's uid, how many times File > Revert replaced its content, and the current data set's name, so a name typed and not yet committed is dropped when another document, a reverted one or a data set with another name becomes current. --- crates/ui-egui/src/panels/variables.rs | 117 +++++++++++++++++++++++-- 1 file changed, 112 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 30a840d7b9..5214799496 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -433,9 +433,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let states = row_states(st); let sort = st.variables_sort; let doc_uid = st.uid; + let reverts = st.reverts; let (mut acts, mut pressed) = (Vec::new(), None); Stack::new().fill().footer(|ui, _| pressed = footer(ui, &states)).show(ui, |ui, _| { - data_set_bar(ui, &rows.sets, &mut acts); + data_set_bar(ui, &rows.sets, (doc_uid, reverts), &mut acts); variable_table(ui, &rows.vars, sort, &states, doc_uid, &mut acts); Text::new(tl!("Data Sets")).role(TypeRole::Heading).show(ui); data_set_list(ui, &rows.sets, &mut acts); @@ -463,9 +464,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// The current data set across the top: its name in a box that renames it, the list that chooses -/// another, and the arrows that step through them. -fn data_set_bar(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec<Act>) { +/// The current data set across the top: its name in a box that renames it when the typed name is +/// committed (Enter or leaving the box), the list that chooses another, and the arrows that step +/// through them. `doc` is the document's uid and how many times +/// File › Revert replaced its content: with the current data set's name, it is the box's edit +/// target, so a name typed and not yet committed is dropped when another document, a reverted one +/// or another data set becomes current, even one with the same name. +fn data_set_bar(ui: &mut Ui, sets: &[SetRow], doc: (u64, u64), acts: &mut Vec<Act>) { let current = sets.iter().find(|s| s.active).map(|s| s.name.as_str()); Row::new().show(ui, |ui, _| { Field::new(tl!("Data Set")).show(ui, |ui, _| { @@ -477,9 +482,10 @@ fn data_set_bar(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec<Act>) { }), ) .enabled(current.is_some()) + .edit_target((doc, current)) .show(ui) .events - .landed() + .committed() .cloned(); if let (Some(from), Some(to)) = (current, typed) { acts.push(Act::Rename(from.to_owned(), to)); @@ -1211,6 +1217,107 @@ mod tests { assert_eq!(undo_steps(&app), before + 1); } + /// A document whose one data set, "Spring", is current. + fn add_spring(app: &mut VectorcraftApp) { + let t = app.run("text.create", json!({"x": 10, "y": 40, "text": "Alice"})).unwrap()["id"].as_u64().unwrap(); + app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap(); + app.run("variable.bind", json!({"variable": "Name", "ids": [t]})).unwrap(); + app.run("dataset.capture", json!({})).unwrap(); + app.run("dataset.rename", json!({"name": "Data Set 1", "newName": "Spring"})).unwrap(); + } + + /// Clicks the Data Set box and types `text` over its name without pressing Enter. + fn start_typing(panel: &mut crate::tests::panel_harness::Panel, text: &str) { + panel.click_role(tl!("Data Set"), craft::ui::contract::Role::TEXT_INPUT); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + } + + /// A name typed into the Data Set box renames nothing until it is committed, and it is dropped + /// when another document becomes current, even when that document's current data set has the + /// same name: Enter there renames neither document's data set. + #[test] + fn an_unfinished_data_set_name_does_not_rename_another_documents_data_set() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + for _ in 0..2 { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + add_spring(&mut app); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + let steps = undo_steps(&app); + let mut panel = Panel::new(app, show); + let names = |panel: &Panel| -> Vec<Vec<String>> { + panel.app().session.documents().iter().map(|st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect()).collect() + }; + start_typing(&mut panel, "Summer"); + assert_eq!(names(&panel), [["Spring"], ["Spring"]], "typing renames nothing before Enter"); + assert_eq!(undo_steps(&panel.app()), steps, "typing adds no undo step"); + panel.app().run("document.activate", json!({"index": 1})).unwrap(); + panel.frame(); + panel.frame(); + let field = craft::ui::contract::Role::TEXT_INPUT; + assert!(panel.focused_nth(field, 0), "the box keeps the focus through the switch"); + assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "the box shows the other document's name"); + assert_eq!(names(&panel), [["Spring"], ["Spring"]], "switching documents renames nothing"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(names(&panel), [["Spring"], ["Spring"]], "Enter in the other document renames neither data set"); + } + + /// A name typed into the Data Set box and not yet committed is dropped by File › Revert, which + /// restores a data set of the same name: Enter afterwards does not rename the restored one. + #[test] + fn an_unfinished_data_set_name_does_not_rename_the_data_set_file_revert_restores() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + add_spring(&mut app); + let dir = vectorcraft_testkit::TempDir::new("variables-revert"); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + // An unsaved edit, so the revert has changes to throw away. + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + let mut panel = Panel::new(app, show); + start_typing(&mut panel, "Summer"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + assert_eq!(set_names(&mut panel.app()), ["Spring"], "the revert restores the data set"); + let steps = undo_steps(&panel.app()); + panel.frame(); + panel.frame(); + let field = craft::ui::contract::Role::TEXT_INPUT; + assert!(panel.focused_nth(field, 0), "the box keeps the focus through the revert"); + assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "the box shows the restored name"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(set_names(&mut panel.app()), ["Spring"], "the restored data set keeps its name"); + assert_eq!(undo_steps(&panel.app()), steps, "no rename runs"); + } + + /// A name typed into the Data Set box and not yet committed is dropped when another data set of + /// the same document becomes current: Enter afterwards renames neither data set. With the same + /// data set current, Enter renames it. + #[test] + fn an_unfinished_data_set_name_does_not_rename_the_next_data_set() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + add_spring(&mut app); + app.run("dataset.capture", json!({"name": "Autumn"})).unwrap(); + app.run("dataset.select", json!({"name": "Spring"})).unwrap(); + let mut panel = Panel::new(app, show); + start_typing(&mut panel, "Summer"); + panel.app().run("dataset.next", json!({})).unwrap(); + panel.frame(); + panel.frame(); + let field = craft::ui::contract::Role::TEXT_INPUT; + assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the box shows the next data set's name"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(set_names(&mut panel.app()), ["Spring", "Autumn"], "Enter renames neither data set"); + start_typing(&mut panel, "Winter"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(set_names(&mut panel.app()), ["Spring", "Winter"], "Enter renames the data set the name was typed for"); + } + /// A press on a column header sorts the list by that column, and a second press on it reverses /// the order, as `variable.list` reports it; sorting is not an edit. #[test] From 4c7aa2471c4b94dafce4c083831672d41b8ec94d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 08:46:41 -0800 Subject: [PATCH 066/103] Variables: a name being composed in the Data Set box stays with its data set A name being composed with an input method in the Data Set box carried over when another data set became current: a changed name clears the typed text but not the composition, so the input method's commit landed in the next data set's name and Enter renamed it. The current data set's name in the box's edit target drops the composition too, and a new test shows it. The box's doc comment now says that a data set replacing the current one under the same name in the same document still takes the unfinished name, since data sets have no id. New tests cover leaving the box with Tab (one undo step) and Escape (renames nothing). --- crates/ui-egui/src/panels/variables.rs | 61 ++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 5214799496..51d219feaf 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -466,10 +466,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// The current data set across the top: its name in a box that renames it when the typed name is /// committed (Enter or leaving the box), the list that chooses another, and the arrows that step -/// through them. `doc` is the document's uid and how many times -/// File › Revert replaced its content: with the current data set's name, it is the box's edit -/// target, so a name typed and not yet committed is dropped when another document, a reverted one -/// or another data set becomes current, even one with the same name. +/// through them. `doc` is the document's uid and how many times File › Revert replaced its +/// content. With the current data set's name, it is the box's edit target, so a name typed or +/// being composed and not yet committed is dropped when another document, a reverted one or a data +/// set with another name becomes current. Data sets have no identity besides their names, so a +/// data set that replaces the current one under the same name in the same document takes the +/// unfinished name. fn data_set_bar(ui: &mut Ui, sets: &[SetRow], doc: (u64, u64), acts: &mut Vec<Act>) { let current = sets.iter().find(|s| s.active).map(|s| s.name.as_str()); Row::new().show(ui, |ui, _| { @@ -1318,6 +1320,57 @@ mod tests { assert_eq!(set_names(&mut panel.app()), ["Spring", "Winter"], "Enter renames the data set the name was typed for"); } + /// A name being composed with an input method in the Data Set box is dropped when another data + /// set becomes current: the composition's commit and Enter rename neither data set. + #[test] + fn a_composed_data_set_name_does_not_rename_the_next_data_set() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + add_spring(&mut app); + app.run("dataset.capture", json!({"name": "Autumn"})).unwrap(); + app.run("dataset.select", json!({"name": "Spring"})).unwrap(); + let mut panel = Panel::new(app, show); + panel.click_role(tl!("Data Set"), craft::ui::contract::Role::TEXT_INPUT); + let preedit = |text: &str| egui::Event::Ime(egui::ImeEvent::Preedit { text: text.into(), active_range_chars: Some(0..text.chars().count()) }); + let field = craft::ui::contract::Role::TEXT_INPUT; + panel.frame_with(vec![preedit("Sum")]); + assert!(panel.value_role(tl!("Data Set"), field).is_some_and(|name| name.contains("Sum")), "the box shows the composition"); + panel.app().run("dataset.next", json!({})).unwrap(); + panel.frame(); + panel.frame(); + assert!(panel.focused_nth(field, 0), "the box keeps the focus through the switch"); + assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the box shows the next data set's name"); + panel.frame_with(vec![egui::Event::Ime(egui::ImeEvent::Commit("Summer".into()))]); + assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the commit does not reach the box"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(set_names(&mut panel.app()), ["Spring", "Autumn"], "the composition renames neither data set"); + } + + /// Leaving the Data Set box with Tab commits the typed name as one undo step, and Escape puts + /// the current name back without renaming anything. + #[test] + fn leaving_the_data_set_box_renames_once_and_escape_renames_nothing() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + add_spring(&mut app); + let steps = undo_steps(&app); + let mut panel = Panel::new(app, show); + let field = craft::ui::contract::Role::TEXT_INPUT; + start_typing(&mut panel, "Summer"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "Escape puts the name back"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(set_names(&mut panel.app()), ["Spring"], "Escape renames nothing"); + assert_eq!(undo_steps(&panel.app()), steps, "Escape adds no undo step"); + start_typing(&mut panel, "Summer"); + assert_eq!(set_names(&mut panel.app()), ["Spring"], "typing renames nothing"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(set_names(&mut panel.app()), ["Summer"], "Tab commits the typed name"); + assert_eq!(undo_steps(&panel.app()), steps + 1, "the rename is one undo step"); + } + /// A press on a column header sorts the list by that column, and a second press on it reverses /// the order, as `variable.list` reports it; sorting is not an edit. #[test] From a7a97bcc5b4c6b041d91948e411fee1a400c2c80 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 12:17:46 -0800 Subject: [PATCH 067/103] Effects: a zoomed-in drag filters raster effects once and moves the raster Once an object with raster effects covers more than the pixel budget on screen, its raster is cropped to the view. While dragging, such content was rendered within the drag budget and no raster was kept, so every frame of the drag painted the content and ran the whole effect chain again: about 0.5 s a frame with Texturizer at 6400%. A drag now keeps that raster when every effect only looks nearby. The raster covers the view with a margin around it, within the drag budget (at full resolution when the frame's crop fits it), and records the part whose pixels the effects decided with all they look at. Later frames of the drag move it with the object, as the whole-raster move already does, while what the frame shows of the content, with the sampling footprint of a lower-resolution raster, lies inside that part. A move or pan past it filters again. Still frames are unchanged: a drag's raster never draws outside a drag, and the frame after the drag renders as before. Part of #2558. Builds on the approach of #2779 by 00xJS. --- crates/render/src/frame.rs | 5 +- crates/render/src/fx/pixels.rs | 154 +++++++++++++++++++++++------ crates/render/src/fx/raster.rs | 5 + crates/render/src/fx/tests.rs | 108 +++++++++++++++++++- crates/ui-egui/src/canvas/tests.rs | 9 +- 5 files changed, 245 insertions(+), 36 deletions(-) diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 90a35458cc..49e252d206 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -157,8 +157,9 @@ pub struct FrameStats { /// their object moved, or made over such rasters ([`RenderOptions::interacting`]), and those it /// drew at a drag's lower resolution ([`Self::previewed`]). pub moved: usize, - /// The filtered contents, shadows and glows the frame drew at a drag's lower resolution - /// ([`RenderOptions::dragging`]). [`Self::moved`] counts them too. + /// The filtered contents, shadows and glows the frame filtered at a drag's lower resolution + /// ([`RenderOptions::dragging`]). [`Self::moved`] counts them too, and counts alone a raster a + /// drag's earlier frame kept that this frame draws again. pub previewed: usize, /// What the frame drew in a way that depends on the frame's size: effect rasters and filter /// layers cropped to it or made at a lower resolution, blending groups drawn as layers past its diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index ceead2a01e..f9d9877a24 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -33,6 +33,33 @@ pub(crate) fn paint_names(doc: &Document) -> u64 { h.finish() } +/// Whether a raster of content filtered by `chain` can move with its object +/// ([`Renderer::move_pixel_content`]): not under De-Interlace, nor under a Rasterize first in the +/// chain. +fn movable(chain: &[&RasterFx]) -> bool { + !chain.iter().any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. }))) && !matches!(chain.first(), Some(RasterFx::Rasterize(_))) +} + +/// The device pixels a frame onto `screen` shows of content reaching `full`, against the device +/// position `at` of the content's anchor. Each side where `screen` cuts the content includes one +/// device pixel for placement rounding and, for raster scale `k` below 1, `ceil(1 / k)` more for +/// bilinear sampling, up to the content's edges. Uncut sides stay at the content's edges. +fn shown(full: Rect, screen: Rect, at: vectorcraft_geom::Point, k: f64) -> Rect { + let s = full.intersect(screen); + let margin = if k < 1.0 { 1.0 + (1.0 / k).ceil() } else { 1.0 }; + let cut = |c: bool| if c { margin } else { 0.0 }; + Rect::new(s.x0 - cut(screen.x0 > full.x0), s.y0 - cut(screen.y0 > full.y0), s.x1 + cut(screen.x1 < full.x1), s.y1 + cut(screen.y1 < full.y1)) + .intersect(full) + - at.to_vec2() +} + +/// Whether `outer` holds all of `inner`, to a millionth of a pixel: the edges of moved content, +/// against its anchor, can differ by rounding. +fn holds(outer: Rect, inner: Rect) -> bool { + let e = 1e-6; + outer.x0 <= inner.x0 + e && outer.y0 <= inner.y0 + e && outer.x1 + e >= inner.x1 && outer.y1 + e >= inner.y1 +} + impl Renderer { /// Paint `content` through the content-changing effects of `rfx` (Gaussian Blur, Feather, the /// Photoshop-style filters and Rasterize) in stack order on its pixels: rendered offscreen over @@ -51,7 +78,9 @@ impl Renderer { /// a drag and for content without a [`Kept`] image, the view with [`pan_margin`] around it. A /// lower-resolution one is kept resampled to the view's pixels ([`Self::resampled`]). /// While dragging, content without such a raster to draw renders within [`DRAG_PIXEL_BUDGET`] - /// pixels and is not cached. + /// pixels and is not cached, except content cropped to the view whose raster can move: its + /// raster covers the view with [`pan_margin`] around it, and the drag's later frames move it with + /// the object while what they show of it lies within ([`PixelEntry::valid`]). pub(super) fn pixel_content( &mut self, ctx: &mut RenderContext, @@ -101,11 +130,23 @@ impl Renderer { let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink)); // Made again at this zoom and rotation (after a pan), a raster cropped to the view covers a // margin around the view too, so that later pans within the margin draw it. - let again = key.and_then(|key| self.pixel_fx.get(&key)).is_some_and(|e| e.linear == linear) + let again = key.and_then(|key| self.pixel_fx.get(&key)).is_some_and(|e| e.linear == linear && e.valid.is_none()) && content.kept.is_none_or(|k| k.shared) && !f.opts.dragging; - let room = match margin { - Some(m) if !fits && again => { + // A drag's raster of content cropped to the view covers a margin around the view too, of + // twice the view's area with the reach around it, and is kept: the drag's later frames move + // it with the object while what they show of it lies within. + let drag_margin = margin + .filter(|_| f.opts.dragging && f.opts.interacting && !fits && key.is_some() && content.kept.is_none() && movable(&chain)) + .map(|m| { + let (w, h) = (screen.width(), screen.height()); + pan_margin((w, h), m, 2.0 * (w + 2.0 * m) * (h + 2.0 * m), f64::from(crate::MAX_RASTER_SIDE)) + }) + .filter(|e| *e > 0.0); + let drag_keep = drag_margin.is_some(); + let room = match (margin, drag_margin) { + (_, Some(e)) => screen.inflate(e, e), + (Some(m), None) if !fits && again => { let e = pan_margin((screen.width(), screen.height()), m, PIXEL_BUDGET, f64::from(crate::MAX_RASTER_SIDE)); screen.inflate(e, e) } @@ -121,6 +162,17 @@ impl Renderer { let side = f64::from(crate::MAX_RASTER_SIDE); let k = (PIXEL_BUDGET / (rw * rh)).sqrt().min(side / rw).min(side / rh).min(1.0); let (w, h) = ((rw * k).ceil().clamp(1.0, side), (rh * k).ceil().clamp(1.0, side)); + // The scale of a drag's kept raster: 1 when the frame's region fits the drag's budget at full + // resolution, else the scale at which the view, its margin and the reach around them fit + // it, the same for each frame of the drag whatever part of the object the frame shows. + let keep_k = drag_keep.then(|| { + if rw * rh <= DRAG_PIXEL_BUDGET { + return 1.0; + } + let around = room.inflate(margin.unwrap_or(0.0), margin.unwrap_or(0.0)); + let (aw, ah) = (around.width().ceil() + 1.0, around.height().ceil() + 1.0); + (DRAG_PIXEL_BUDGET / (aw * ah)).sqrt().min(side / aw).min(side / ah).min(1.0) + }); // The cached raster: of the whole content at full size at this zoom, else of this view (and // the margin around it). let whole = fits && k >= 1.0; @@ -146,18 +198,27 @@ impl Renderer { let interacting = f.opts.interacting; let in_place = |e: &PixelEntry| match e.view { None => whole, - Some(v) => !whole && v.serves(f.view, screen), + Some(v) => !whole && (e.valid.is_some() || v.serves(f.view, screen)), }; + // A raster a drag kept draws during a drag, while what the frame shows of the content lies + // where its pixels are right ([`PixelEntry::valid`]). let exact = |e: &PixelEntry| { - e.linear == linear && in_place(e) && e.node.is(content.node) && Some(&e.inputs) == inputs.as_ref() && (interacting || !e.moved) + e.linear == linear + && in_place(e) + && e.valid.is_none_or(|v| f.opts.dragging && holds(v, shown(full, screen, f.view * e.anchor, e.k))) + && e.node.is(content.node) + && Some(&e.inputs) == inputs.as_ref() + && (interacting || !e.moved) }; + // During a drag, what the frame shows of the content, against the content's anchor. + let crop = keep_k.map(|d| (d, shown(full, screen, f.view * content.reach.origin(), d))); if interacting - && whole + && (whole || crop.is_some()) && let Some(key) = key && let Some(inputs) = &inputs && !self.pixel_fx.get(&key).is_some_and(exact) { - self.move_pixel_content(f, content, key, &chain, channels, inputs, paint); + self.move_pixel_content(f, content, key, &chain, channels, inputs, crop, paint); } if let Some(e) = key.and_then(|key| self.pixel_fx.get_mut(&key)).filter(|e| exact(e)) { e.stamp = stamp; @@ -171,15 +232,20 @@ impl Renderer { draw_scaled(ctx, image, at, k); return; } - // During a drag, content without a raster to draw renders within the drag's budget and keeps - // no raster (#2558). - let (k, w, h, key) = match drag_scale(f.opts.dragging, (rw, rh), k) { - Some(d) => { + // During a drag, content without a raster to draw renders within the drag's budget (#2558). + // Its raster is kept, marked moved, only when it is cropped to the view and can move. + let (k, w, h, key) = match (keep_k, drag_scale(f.opts.dragging, (rw, rh), k)) { + (Some(d), _) => { + self.stats.moved += 1; + self.stats.previewed += usize::from(d < 1.0); + (d, (rw * d).ceil().clamp(1.0, side), (rh * d).ceil().clamp(1.0, side), key) + } + (None, Some(d)) => { self.stats.moved += 1; self.stats.previewed += 1; (d, (rw * d).ceil().clamp(1.0, side), (rh * d).ceil().clamp(1.0, side), None) } - None => (k, w, h, key), + (None, None) => (k, w, h, key), }; let (wu, hu) = (w as u16, h as u16); let view = Affine::scale(k) * Affine::translate((-x0, -y0)) * f.view; @@ -237,12 +303,12 @@ impl Renderer { let failed = crate::paint::decode_failures() - decoded; let image_left_out = self.image_left_out.unwrap_or(false) || crate::pattern::images_left_out() > pattern_images_left_out; self.image_left_out = outer_image_left_out.map(|outer| outer || image_left_out); - // Content drawn over moved rasters makes a moved raster. - let moved = self.stats.moved > before; - // What the raster is made from, for its object once it moves (`move_pixel_content`): a - // cropped or coarser raster never moves. + // Content drawn over moved rasters makes a moved raster, as does a drag. + let moved = drag_keep || self.stats.moved > before; + // What the raster is made from, for its object once it moves (`move_pixel_content`): of + // the rasters cropped to the view or made coarser, only a drag's moves. let made = key.map(|_| Made { - pixels: if whole { pm.data_as_u8_slice().to_vec() } else { Vec::new() }, + pixels: if whole || drag_keep { pm.data_as_u8_slice().to_vec() } else { Vec::new() }, fx: chain.iter().map(|fx| (*fx).clone()).collect(), size: content.reach.size(), channels: Some(channels), @@ -297,7 +363,7 @@ impl Renderer { // A raster kept for this view alone at a lower resolution than the view's is resampled to the // view's pixels once: each frame that draws it then copies it pixel for pixel, where sampling // it again across the whole view cost several times as much as a plain fill. - let view_raster = key.is_some() && in_view.is_some() && k < 1.0 && content.kept.is_none_or(|k| k.shared); + let view_raster = key.is_some() && in_view.is_some() && k < 1.0 && content.kept.is_none_or(|k| k.shared) && !drag_keep; let (image, x0, y0, k) = match view_raster.then(|| self.resampled(f, image.clone(), (x0, y0), k, screen)).flatten() { Some((image, x, y)) => (image, x, y, 1.0), None => (image, x0, y0, k), @@ -311,8 +377,24 @@ impl Renderer { let rel = (x0 - p.x, y0 - p.y); let owner = content.owner.cloned().or_else(|| self.fx_owner.clone().filter(|o| std::ptr::eq(&**o, content.node))); let node = Drawn::of(content.node, owner.as_ref()); - let entry = - PixelEntry { node, linear, anchor, rel, k, image: image.clone(), view: in_view, made, inputs, moved, failed, image_left_out, stamp }; + // The effects saw all they look at for the pixels of the view and its margin. + let valid = drag_keep.then(|| full.intersect(room) - p.to_vec2()); + let entry = PixelEntry { + node, + linear, + anchor, + rel, + k, + image: image.clone(), + view: in_view, + valid, + made, + inputs, + moved, + failed, + image_left_out, + stamp, + }; self.pixel_fx.insert(key, entry); self.trim_fx_rasters(FX_RASTER_BUDGET); } @@ -362,7 +444,13 @@ impl Renderer { /// (and the same Feather outline against its anchor), and whose pixels are the pixels of /// `content` drawn into a raster placed as that one was against its anchor. The raster is kept /// as `content`'s, marked moved, and is drawn at the nearest whole pixel. Content under - /// De-Interlace, or under a Rasterize first in the chain, takes none. + /// De-Interlace, or under a Rasterize first in the chain, takes none ([`movable`]). + /// + /// With `crop` (a drag's frame of content cropped to the view: the scale its raster is made at, + /// and the device pixels the frame shows of the content against its anchor), the raster is + /// instead one a drag's earlier frame kept at that scale or at full resolution + /// ([`PixelEntry::valid`]), whose pixels the effects decided with all they look at over the + /// part the frame shows. #[allow(clippy::too_many_arguments)] fn move_pixel_content( &mut self, @@ -372,10 +460,10 @@ impl Renderer { chain: &[&RasterFx], channels: Channels, inputs: &Inputs, + crop: Option<(f64, Rect)>, paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame), ) { - if chain.iter().any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. }))) || matches!(chain.first(), Some(RasterFx::Rasterize(_))) - { + if !movable(chain) { return; } let (linear, stamp, anchor) = (linear_key(f.view), self.stamp, content.reach.origin()); @@ -384,23 +472,29 @@ impl Renderer { (k.1, k.2) == (key.1, key.2) && e.stamp < stamp && e.linear == linear - && e.k >= 1.0 - && e.view.is_none() + && match crop { + None => e.k >= 1.0 && e.view.is_none(), + Some((scale, need)) => { + (e.k.to_bits() == scale.to_bits() || e.k == 1.0) && e.view.is_some() && e.valid.is_some_and(|v| holds(v, need)) + } + } && e.node.id() == content.node.id && e.inputs == *inputs && e.made.fits(chain, content.reach.size(), Some(channels), outline.as_ref()) }; - let Some((old, rel, w, h)) = self.pixel_fx.iter().find(|(k, e)| fits(k, e)).map(|(k, e)| (*k, e.rel, e.image.width(), e.image.height())) + let Some((old, rel, k, w, h)) = + self.pixel_fx.iter().find(|(k, e)| fits(k, e)).map(|(k, e)| (*k, e.rel, e.k, e.image.width(), e.image.height())) else { return; }; // The content drawn where the old content lies in its raster. let p = f.view * anchor; - let view = Affine::translate((-(p.x + rel.0), -(p.y + rel.1))) * f.view; + let view = Affine::scale(k) * Affine::translate((-(p.x + rel.0), -(p.y + rel.1))) * f.view; let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h))); - let frame = Frame { mt: false, view, visible, ..*f }; + let px = f.px / k; + let frame = Frame { mt: false, view, visible, px, ..*f }; let mut off = f.offscreen_context(w, h); - if hard_edged(chain, f.px) { + if hard_edged(chain, px) { off.set_aliasing_threshold(crate::AntiAlias::None.threshold()); } self.inside_layer(|r| paint(r, &mut off, &frame)); diff --git a/crates/render/src/fx/raster.rs b/crates/render/src/fx/raster.rs index efbab00da4..02bf918089 100644 --- a/crates/render/src/fx/raster.rs +++ b/crates/render/src/fx/raster.rs @@ -95,6 +95,11 @@ pub(crate) struct PixelEntry { /// made for: it draws only there, so dragging other art over the object keeps it (a wide blur, /// or any blur zoomed in, reaches past the pixel budget). pub(super) view: Option<ViewCrop>, + /// For a raster a drag's frame kept of content cropped to the view, the device pixels (against + /// the anchor's view position) whose pixels the effects decided with all they look at: the + /// drag's later frames move the raster with its object while what they show of it lies within + /// ([`Renderer::move_pixel_content`]). `None` for other rasters. + pub(super) valid: Option<Rect>, pub(super) made: Made, /// What the content read when the raster was made, with the channels the effects ran on and, /// under De-Interlace, the raster resolution. diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index f843ce01f7..1c58a7da96 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1718,7 +1718,7 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() { let dragged = r.render(&d, 1600, 1000, view, &drag).pixels; assert_eq!(r.stats.previewed, 2, "the shadow and the filtered content"); assert_eq!(r.stats.moved, 2, "counted as moved: the frame after the drag renders them again"); - assert!(r.pixel_fx.is_empty() && r.shadows.values().all(|e| e.stamp < r.stamp), "no raster kept"); + assert!(r.pixel_fx.values().all(|e| e.moved) && r.shadows.values().all(|e| e.stamp < r.stamp), "only rasters marked moved kept"); assert!(dragged != fresh, "at the drag's lower resolution"); let after = r.render(&d, 1600, 1000, view, &still).pixels; assert_eq!((r.stats.previewed, r.stats.moved), (0, 0)); @@ -1742,6 +1742,112 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() { assert!(after == threaded().render(&scaled, 1600, 1000, view, &still).pixels, "the frame after the drag"); } +/// At 6400% a Texturized 200 × 150 pt rectangle covers 12800 × 9600 px, past the pixel budget, +/// so its raster is cropped to the view. A drag filters it once, and the drag's later frames +/// move that raster with the object until the object leaves the raster's slack, also when the +/// view shows an edge of the object, and until a pan shows what the raster does not cover. +#[test] +fn a_zoomed_drag_moves_the_cropped_raster_with_its_object() { + let base = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("texture.texturizer", json!({}))]); + let id = base.layers[0].children().unwrap()[0].id; + let still = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let drag = RenderOptions { interacting: true, dragging: true, ..still.clone() }; + // The rectangle moved by (`dx`, `dy`) device pixels. + let moved = |dx: f64, dy: f64| { + let mut d = base.clone(); + d.node_mut(id).unwrap().transform(Affine::translate((dx / 64.0, dy / 64.0)), false); + d + }; + // A still frame, then eight drag frames: the filters each ran. + let drag_through = |r: &mut Renderer, view: Affine| { + let _ = r.render(&base, 1600, 1000, view, &still); + (1..=8).fold(0, |n, i| { + let _ = r.render(&moved(20.0 * f64::from(i), 13.0 * f64::from(i)), 1600, 1000, view, &drag); + n + r.stats.previewed + }) + }; + // Centered on (290, 175), the view shows the rectangle's right edge. + let edge = Affine::translate((800.0, 500.0)) * Affine::scale(64.0) * Affine::translate((-290.0, -175.0)); + assert_eq!(drag_through(&mut Renderer::new(), edge), 1, "with the object's edge in view"); + let view = Affine::translate((800.0, 500.0)) * Affine::scale(64.0) * Affine::translate((-200.0, -175.0)); + let mut panned = Renderer::new(); + assert_eq!(drag_through(&mut panned, view), 1, "the first drag frame filters the content, and the next seven move its raster"); + // The raster covers between 250 and 300 px around the view as it was when the drag began, and + // the rectangle moved 160 px to the right of where it was. + let held = moved(160.0, 104.0); + let _ = panned.render(&held, 1600, 1000, view, &drag); + assert_eq!(panned.stats.previewed, 0, "where the drag's last frame left it"); + for dx in [40.0, 10.5] { + let _ = panned.render(&held, 1600, 1000, Affine::translate((dx, 0.0)) * view, &drag); + assert_eq!(panned.stats.previewed, 0, "a pan within the raster's margin draws the kept raster ({dx} px)"); + } + let _ = panned.render(&held, 1600, 1000, Affine::translate((200.0, 0.0)) * view, &drag); + assert_eq!(panned.stats.previewed, 1, "a pan that shows what the moved raster does not cover filters the content again"); + let live = RenderOptions { dragging: false, ..drag.clone() }; + let pixels = panned.render(&held, 1600, 1000, view, &live).pixels; + assert!(pixels == Renderer::new().render(&held, 1600, 1000, view, &live).pixels, "an interaction without a drag"); + let mut r = Renderer::new(); + assert_eq!(drag_through(&mut r, view), 1); + let last = moved(1000.0, 0.0); + let _ = r.render(&last, 1600, 1000, view, &drag); + assert_eq!(r.stats.previewed, 1, "a move past the raster's slack filters the content again"); + let after = r.render(&last, 1600, 1000, view, &still).pixels; + let mut fresh = Renderer::new(); + assert!(after == fresh.render(&last, 1600, 1000, view, &still).pixels, "the frame after the drag"); + let kept = r.pixel_fx.values().find(|e| e.node.is(last.node(id).unwrap()) && e.valid.is_none()).unwrap(); + let fresh = fresh.pixel_fx.values().next().unwrap(); + assert_eq!( + (kept.image.width(), kept.image.height()), + (fresh.image.width(), fresh.image.height()), + "the first still frame keeps the same crop as a fresh renderer" + ); + + // Only a narrow strip at the rectangle's right edge lies in view, so its crop fits the drag budget. + let strip = Affine::translate((300.0, 500.0)) * Affine::scale(64.0) * Affine::translate((-300.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&moved(20.0, 13.0), 1600, 1000, strip, &drag); + assert_eq!(r.stats.previewed, 0, "the narrow crop keeps full resolution"); + assert_eq!(r.pixel_fx.values().filter(|e| e.valid.is_some()).count(), 1, "the drag keeps one cropped raster"); + assert!(r.pixel_fx.values().any(|e| e.valid.is_some() && e.k == 1.0), "the kept raster uses scale 1"); + let image = r.pixel_fx.values().find(|e| e.valid.is_some()).unwrap().image.clone(); + for i in 2..=4 { + let _ = r.render(&moved(20.0 * f64::from(i), 13.0 * f64::from(i)), 1600, 1000, strip, &drag); + assert_eq!(r.stats.previewed, 0, "a later frame within the slack keeps full resolution"); + assert_eq!(r.pixel_fx.values().filter(|e| e.valid.is_some()).count(), 1, "the drag keeps one cropped raster"); + let kept = r.pixel_fx.values().find(|e| e.valid.is_some()).unwrap(); + assert!(std::sync::Arc::ptr_eq(&image, &kept.image), "a later frame within the slack draws the kept raster"); + } + // The crop grows past the drag budget while the visible content stays within the 255 px slack. + let _ = r.render(&moved(120.0, 13.0), 1600, 1000, strip, &drag); + assert_eq!(r.stats.previewed, 0, "crossing the drag budget draws the full-resolution raster"); + let kept = r.pixel_fx.values().find(|e| e.valid.is_some()).unwrap(); + assert!(std::sync::Arc::ptr_eq(&image, &kept.image), "crossing the drag budget draws the kept raster"); +} + +#[test] +fn a_zoomed_drag_keeps_the_sampling_footprint_inside_the_valid_crop() { + let base = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("texture.texturizer", json!({}))]); + let id = base.layers[0].children().unwrap()[0].id; + let drag = RenderOptions { interacting: true, dragging: true, background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((800.0, 500.0)) * Affine::scale(64.0) * Affine::translate((-200.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&base, 1600, 1000, view, &drag); + let kept = r.pixel_fx.values().find(|e| e.valid.is_some()).unwrap(); + assert!(kept.k < 1.0, "the drag raster uses a lower resolution"); + let valid = kept.valid.unwrap(); + let at = view * kept.anchor; + let footprint = 1.0 + (1.0 / kept.k).ceil(); + let gap = (1.0 + footprint) / 2.0; + let dx = -at.x - valid.x0 - gap; + let left = -(at.x + dx); + assert!(left - 1.0 > valid.x0, "the visible edge and placement rounding stay inside the valid crop"); + assert!(left - footprint < valid.x0, "the sampling footprint reaches past the valid crop"); + let mut moved = base.clone(); + moved.node_mut(id).unwrap().transform(Affine::translate((dx / 64.0, 0.0)), false); + let _ = r.render(&moved, 1600, 1000, view, &drag); + assert_eq!(r.stats.previewed, 1, "the sampling footprint outside the valid crop filters the content again"); +} + #[test] fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() { let doc = doc_with( diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index df0d8fc387..02bf0a0a52 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2084,8 +2084,9 @@ fn dragging_with_raster_effects() { } /// A tool's drag on the canvas renders with `dragging` (#2558). At 3200% a rectangle with -/// Texturizer covers more than the raster budget, so no raster is kept for it, and each frame -/// of a Selection tool drag draws its filtered content at the drag's lower resolution. The +/// Texturizer covers more than the raster budget, so its raster is cropped to the view: the first +/// frame of a Selection tool drag filters its content at the drag's lower resolution, and the +/// next moves that raster with the rectangle. The /// frame after the drag draws what a fresh renderer draws. A dialog's preview, an interaction /// without a drag, renders without `dragging` and draws the same. #[test] @@ -2137,7 +2138,9 @@ fn a_drag_at_a_lower_resolution(fits_frame: bool) { for step in [1.0, 2.0] { let drawn = run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]).expect("each frame of the drag renders"); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}"); - assert_eq!(app.canvas.renderer.stats.previewed, 1, "the filtered content, step {step}"); + // Cropped to the view, the first frame's raster moves with the rectangle on the second. + let filtered = usize::from(fits_frame || step == 1.0); + assert_eq!(app.canvas.renderer.stats.previewed, filtered, "the filtered content, step {step}"); if fits_frame { assert_eq!(app.canvas.renderer.stats.view_sized, 0, "only the drag budget reduced the raster"); assert!(app.canvas.whole_frames, "a whole drag preview cannot accept a full-resolution patch"); From 5273f4547bee20a4b24068e29268614cc7b06401 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 12:29:22 -0800 Subject: [PATCH 068/103] Tests: DWG test modules use #[cfg(test)] so clippy treats them as tests The modules were behind cfg(all(test, ...)), which clippy's allow-unwrap-in-tests does not read as test code. The platform condition moves into each file as an inner attribute. --- crates/cad/src/import.rs | 3 +-- crates/cad/src/import/tests_dwg.rs | 11 ++++++++--- crates/engine/src/cmd/fileio.rs | 3 +-- crates/engine/src/cmd/fileio/tests_dwgimport.rs | 4 +++- 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 7c6dc0a516..5a5582efe1 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -235,6 +235,5 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> { #[cfg(test)] mod tests; -// craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on aarch64. -#[cfg(all(test, not(target_arch = "wasm32"), not(all(target_os = "freebsd", target_arch = "aarch64"))))] +#[cfg(test)] mod tests_dwg; diff --git a/crates/cad/src/import/tests_dwg.rs b/crates/cad/src/import/tests_dwg.rs index 72f4157221..00ff6aa7da 100644 --- a/crates/cad/src/import/tests_dwg.rs +++ b/crates/cad/src/import/tests_dwg.rs @@ -1,5 +1,7 @@ //! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF -//! does; damaged files are errors. +//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD +//! on aarch64. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, Unit}; @@ -27,8 +29,11 @@ fn dwg() -> Vec<u8> { craft_dwg::dxf_to_dwg_as(&dxf(), "AC1018").unwrap() } -/// Each layer holding art, with each object's bounds (to 0.01 pt) and stroke color. -fn art(doc: &Document) -> Vec<(Option<String>, Vec<([i64; 4], Option<[u8; 4]>)>)> { +/// A layer's name, and each of its objects' bounds (to 0.01 pt) and stroke color. +type LayerArt = (Option<String>, Vec<([i64; 4], Option<[u8; 4]>)>); + +/// Each layer holding art. +fn art(doc: &Document) -> Vec<LayerArt> { let r = |v: f64| (v * 100.0).round() as i64; doc.layers .iter() diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index fd81791573..9d89de2c3c 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -248,8 +248,7 @@ mod tests_eps; #[cfg(test)] mod tests_dxfimport; -// craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on aarch64. -#[cfg(all(test, not(target_arch = "wasm32"), not(all(target_os = "freebsd", target_arch = "aarch64"))))] +#[cfg(test)] mod tests_dwgimport; #[cfg(test)] mod tests_hpgl; diff --git a/crates/engine/src/cmd/fileio/tests_dwgimport.rs b/crates/engine/src/cmd/fileio/tests_dwgimport.rs index 5eb5c95a69..d4aa2ad348 100644 --- a/crates/engine/src/cmd/fileio/tests_dwgimport.rs +++ b/crates/engine/src/cmd/fileio/tests_dwgimport.rs @@ -1,6 +1,8 @@ //! DWG through the commands: `document.open`, `document.dxfInfo` and File → Place read a DWG //! drawing as the DXF it converts to, with the DXF options; DWG is in the format table as read -//! only, and saving or exporting one says to write DXF. +//! only, and exporting one says to write DXF. craft-dwg reads and writes DWG everywhere but wasm32 +//! and FreeBSD on aarch64. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeKind}; From bebaebdbe44b416f175b0085075f761c74a2f5c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 07:39:18 -0800 Subject: [PATCH 069/103] Type: an unfinished Font Size value stays with the text it was typed for The Font Size field of the Control bar and the Contextual Task Bar kept a value typed and not yet committed when other text with the same size was selected, and the next Enter applied it there: 3+ typed for one text object, then 1 and Enter with another selected, gave the second one 4 pt. The field now passes an edit target to NumberField::edit_target: the document, its File > Revert count, its Undo and Redo restore count (after which a node id can name another object), and the text text.setStyle changes (format_target): the range or story the Type tool has selected, the whole edited text at a caret, else the selected stories. When it changes, the field drops the unfinished value. The range is clamped to the text, so Select All over characters that are already selected keeps the value, and a range over the whole text counts as a caret, which also changes the whole text. While Real-time Drawing off leaves typing unapplied, the range is the Type tool's own offsets clamped to the length the text has with that typing, so a range reaching into it is another range than the applied text it starts in, and keeping the typing keeps the value. In a threaded frame, where keeping the typing can reflow text from the other frames, the offsets are not clamped. SymbolPart derives Hash so the target can hold it. --- crates/doc/src/selection.rs | 2 +- crates/ui-egui/src/panels/character.rs | 68 ++++- crates/ui-egui/src/panels/character/tests.rs | 270 +++++++++++++++++++ 3 files changed, 336 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 02c4391921..ead201ffab 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -78,7 +78,7 @@ pub struct Selection { } /// See [`Selection::symbol_part`]. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct SymbolPart { /// The symbol instance. pub instance: NodeId, diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 677eec516a..b158a9175b 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -316,7 +316,7 @@ fn run_format_after_typing(app: &mut VectorcraftApp, mut p: Value, editing: Opti app.run("text.setRangeStyle", p) } -#[derive(PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Hash)] pub(crate) enum FormatTarget { Objects(Vec<NodeId>, Option<SymbolPart>), Story(Vec<NodeId>), @@ -1318,9 +1318,66 @@ fn snap_to_glyph(app: &mut VectorcraftApp, ui: &mut Ui) { }); } +/// What the bars' Font Size field edits, as its edit target: the document, how many times File › +/// Revert and Undo or Redo replaced its content (after which a node id can name another object), +/// and the text `text.setStyle` changes ([`format_target`]): the range or story the Type tool has +/// selected, all of the edited text at a caret, else the selected stories. The field drops a value +/// typed and not yet committed when this changes, even where the new text has the same size. +fn size_target(app: &VectorcraftApp) -> Option<(u64, u64, u64, FormatTarget)> { + let st = app.session.active()?; + // The range [`text_editing`] clamps to the stored text, or, while Real-time Drawing off leaves + // typing unapplied, the Type tool's own offsets, which can reach into that typing, clamped to + // the length the text has with it ([`pending_text_len`]). A caret changes the whole text + // wherever it is ([`range_style`]); a range over the whole text keys as a caret does. + let o = app.session.tool_options(); + let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize); + let editing = text_editing(app).map(|(id, a, b)| { + let unapplied_typing = o.get("typing").and_then(Value::as_bool) == Some(true) + && st.interaction.as_ref().is_some_and(|it| it.label == "Typing" && it.preview.is_some() && std::sync::Arc::ptr_eq(&it.doc, &st.doc)); + let (a, b, len) = if unapplied_typing { + let (a, b) = (offset("start"), offset("end")); + pending_text_len(st, id).map_or((a, b, None), |len| (a.min(len), b.min(len), Some(len))) + } else { + let len = st.doc.node(id).and_then(|node| match &node.kind { + NodeKind::Text(t) => Some(vectorcraft_text::edit::runs_len(&t.runs)), + _ => None, + }); + (a, b, len) + }; + if b > a && !(a == 0 && len.is_some_and(|len| b >= len)) { (id, a, b) } else { (id, 0, 0) } + }); + Some((st.uid, st.reverts, st.history_restores, format_target(app, editing))) +} + +/// The byte length text `id` will have once the typing that Real-time Drawing off leaves unapplied +/// is applied: the stored text with the `text.editRange` preview's range replaced by its runs. +/// `None` for a frame of a threaded story, whose text can reflow from other frames, when the +/// preview is not an edit of `id`, or when its range does not fit the stored text. +fn pending_text_len(st: &DocState, id: NodeId) -> Option<usize> { + if st.doc.story_of(id).len() > 1 { + return None; + } + let (cmd, params) = st.interaction.as_ref()?.preview.as_ref()?; + if cmd != "text.editRange" || params.get("id")?.as_u64()? != id.0 { + return None; + } + let NodeKind::Text(text) = &st.doc.node(id)?.kind else { return None }; + let stored_len = vectorcraft_text::edit::runs_len(&text.runs); + let start = usize::try_from(params.get("start")?.as_u64()?).ok()?; + let end = usize::try_from(params.get("end")?.as_u64()?).ok()?; + if end > stored_len { + return None; + } + let removed_len = end.checked_sub(start)?; + let inserted_len = params.get("runs")?.as_array()?.iter().try_fold(0usize, |len, run| len.checked_add(run.get("text")?.as_str()?.len()))?; + stored_len.checked_sub(removed_len)?.checked_add(inserted_len) +} + /// The Font Size field of the bars, named `name`: typed, stepped, scrubbed or picked from the -/// presets, in the type unit, blank where the selected text's sizes differ. +/// presets, in the type unit, blank where the selected text's sizes differ. A value typed and not +/// yet committed stays with the text it was typed for ([`size_target`]). fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) { + let target = size_target(app); let unit = type_unit(app); let scale = unit_scale(unit); let units = Env::of(ui).units(); @@ -1332,7 +1389,12 @@ fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) { }) .collect(); let mut size = shared_effective(app, |s| s.size).map(|v| v * scale); - let out = NumberField::new(name, Bind::bound(&mut size)).unit_kind(unit.kind).range(0.1 * scale..=1296.0 * scale).presets(&presets).show(ui); + let out = NumberField::new(name, Bind::bound(&mut size)) + .unit_kind(unit.kind) + .range(0.1 * scale..=1296.0 * scale) + .presets(&presets) + .edit_target(&target) + .show(ui); apply_edits(app, &out.edit, EditPath::Scope, |app, value, _| { if let Some(v) = value { style(app, json!({"size": v / scale})); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index d1f6be332e..473f834734 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -1482,3 +1482,273 @@ fn panels_work_out_the_selected_stories_once_per_frame() { STORIES_UNKEPT.set(false); assert!(reads > 1, "the fields read the list {reads} times"); } + +/// A drawing of controls over the app. +type Draw = fn(&mut VectorcraftApp, &mut egui::Ui); + +/// The Control bar's and the Contextual Task Bar's type controls, each drawn alone. +const BARS: [(&str, Draw); 2] = [ + ("Control bar", |app, ui| { + control_bar(app, ui); + }), + ("Contextual Task Bar", task_bar), +]; + +/// Types `3+` into the bar's Font Size field without committing it. +fn unfinished_size(p: &mut crate::tests::panel_harness::Panel) { + p.focus(tl!("Font Size")); + p.key(egui::Key::A, egui::Modifiers::COMMAND); + p.type_text("3+"); +} + +/// Draws a frame, then types `1` and Enter into the Font Size field. +fn finish_size(p: &mut crate::tests::panel_harness::Panel) { + p.frame(); + p.type_text("1"); + p.key(egui::Key::Enter, egui::Modifiers::NONE); +} + +/// Each run of the text `id` with its size. +fn run_sizes(app: &VectorcraftApp, id: u64) -> Vec<(String, f64)> { + block_text(app, NodeId(id)).runs.iter().map(|r| (r.text.clone(), r.style.size)).collect() +} + +/// A document with two text objects at 12 pt: `Ab` and `Cd`. +fn two_texts() -> (VectorcraftApp, u64, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.create", json!({"x": 20, "y": 140, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + (app, a, b) +} + +/// The bars' Font Size field keeps a value typed and not yet committed while the text it was typed +/// for stays selected, and drops it when other text with the same size is selected. +#[test] +fn an_unfinished_font_size_does_not_reach_other_selected_text() { + use crate::tests::panel_harness::Panel; + for (bar, draw) in BARS { + let (mut app, a, b) = two_texts(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, draw); + unfinished_size(&mut p); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), a), [("Ab".to_string(), 4.0)], "{bar}: an unchanged selection keeps 3+"); + p.app().run("text.setStyle", json!({"ids": [a], "size": 12})).unwrap(); + + unfinished_size(&mut p); + p.app().run("select.set", json!({"ids": [b]})).unwrap(); + finish_size(&mut p); + let app = p.app(); + assert_eq!( + (run_sizes(&app, a), run_sizes(&app, b)), + (vec![("Ab".to_string(), 12.0)], vec![("Cd".to_string(), 1.0)]), + "{bar}: b takes 1 pt, not 3+1" + ); + } +} + +/// While the Type tool edits text, the field's value belongs to the selected characters: another +/// range in the same text drops it. At a caret it belongs to the whole text, so moving the caret +/// keeps it. +#[test] +fn an_unfinished_font_size_does_not_reach_another_text_range() { + use crate::tests::panel_harness::Panel; + for (bar, draw) in BARS { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 1, "caret": 1})); + let mut p = Panel::new(app, draw); + unfinished_size(&mut p); + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 3, "caret": 3})); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: a caret moved in the same text keeps 3+"); + p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap(); + + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 2})); + p.frame(); + unfinished_size(&mut p); + p.app().run("select.all", json!({})).unwrap(); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: Select All after a caret keeps 3+"); + p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap(); + + // Select All over text whose characters are all selected selects the same characters. + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 4})); + p.frame(); + unfinished_size(&mut p); + p.app().run("select.all", json!({})).unwrap(); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: Select All over the same characters keeps 3+"); + p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap(); + + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 2})); + p.frame(); + unfinished_size(&mut p); + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 4})); + finish_size(&mut p); + let want = vec![("Ab".to_string(), 12.0), ("cd".to_string(), 1.0)]; + assert_eq!(run_sizes(&p.app(), id), want, "{bar}: the second range takes 1 pt, not 3+1"); + } +} + +/// Another document whose text has the same id and size drops the value. +#[test] +fn an_unfinished_font_size_does_not_reach_another_document() { + use crate::tests::panel_harness::Panel; + let (mut app, a, _) = two_texts(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let other = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(other, a, "both documents' texts have the same id"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().run("document.activate", json!({"index": 1})).unwrap(); + finish_size(&mut p); + let second = run_sizes(&p.app(), a); + p.app().run("document.activate", json!({"index": 0})).unwrap(); + let first = run_sizes(&p.app(), a); + assert_eq!((first, second), (vec![("Ab".to_string(), 12.0)], vec![("Ab".to_string(), 1.0)]), "the other document takes 1 pt"); +} + +/// File › Revert drops the value, though the restored text has the same id and size. +#[test] +fn an_unfinished_font_size_is_dropped_by_file_revert() { + use crate::tests::panel_harness::Panel; + let (mut app, a, _) = two_texts(); + let dir = vectorcraft_testkit::TempDir::new("font-size-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Type.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the text as saved. + app.run("shape.rectangle", json!({"x": 100, "y": 200, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.app().run("select.set", json!({"ids": [a]})).unwrap(); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), a), [("Ab".to_string(), 1.0)], "Revert drops the unfinished value"); +} + +/// Undo drops the value, though the text it takes away and the text made and selected after it +/// have the same id and size. +#[test] +fn an_unfinished_font_size_is_dropped_by_undo() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().run("edit.undo", json!({})).unwrap(); + let b = p.app().run("text.create", json!({"x": 20, "y": 40, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(b, a, "the new text has the undone text's id"); + p.app().run("select.set", json!({"ids": [b]})).unwrap(); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), b), [("Cd".to_string(), 1.0)], "Undo drops the unfinished value"); +} + +/// With Real-time Drawing off, a Type tool range that reaches into typing not applied yet is +/// another range than the applied text it starts in. +#[test] +fn an_unfinished_font_size_does_not_reach_a_range_with_unapplied_typing() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 2, "end": 2})); + let mut app = crate::testing::windowed(app); + let ctx = app.ui_ctx.clone().unwrap(); + // The keymap builds in the first pass. + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + assert_eq!(run_sizes(&app, id), [("Ab".to_string(), 12.0)], "the typing is not applied yet"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 2})); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().session.set_tool_option("select", &json!({"start": 0, "end": 4})); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("AbCd".to_string(), 1.0)], "the longer range takes 1 pt, not 3+1"); +} + +/// With Real-time Drawing off, deleting a paragraph break pulls text from the next frame when +/// typing is applied. A different range drops the unfinished size before that reflow. +#[test] +fn an_unfinished_font_size_does_not_reach_a_range_in_threaded_text_with_unapplied_typing() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let area = json!({"x": 10, "y": 10, "text": "a\nb", "size": 12, "area": {"width": 150, "height": 20}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(story_frame(&app, a).plain_text(), "a\n"); + assert_eq!(story_frame(&app, b).plain_text(), "b"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 2, "end": 2})); + let mut app = crate::testing::windowed(app); + let ctx = app.ui_ctx.clone().unwrap(); + // The first frame builds the keymap. + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + let backspace = |pressed| egui::Event::Key { + key: egui::Key::Backspace, + physical_key: Some(egui::Key::Backspace), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![backspace(true), backspace(false)]); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + assert_eq!(story_frame(&app, a).plain_text(), "a\n", "the deletion is not applied yet"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 1})); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().session.set_tool_option("select", &json!({"start": 0, "end": 2})); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), a), [("ab".to_string(), 1.0)], "the longer range takes 1 pt, not 3+1"); + assert_eq!(story_frame(&p.app(), b).plain_text(), "", "the following text flows into the first frame"); +} + +#[test] +fn an_unfinished_font_size_stays_when_typing_is_kept() { + use crate::tests::panel_harness::Panel; + for real_time_drawing in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time_drawing})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 2, "end": 2})); + let mut app = crate::testing::windowed(app); + let ctx = app.ui_ctx.clone().unwrap(); + // The keymap builds in the first pass. + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]); + assert_eq!(app.session.tool_options()["typing"], json!(true), "realTimeDrawing={real_time_drawing}"); + let stored_text = if real_time_drawing { "AbCd" } else { "Ab" }; + assert_eq!(run_sizes(&app, id), [(stored_text.to_string(), 12.0)], "typing before keeping, realTimeDrawing={real_time_drawing}"); + app.run("select.all", json!({})).unwrap(); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().keep_typing().unwrap(); + assert_ne!(p.app().session.tool_options()["typing"], json!(true), "realTimeDrawing={real_time_drawing}"); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("AbCd".to_string(), 4.0)], "the kept typing keeps 3+, realTimeDrawing={real_time_drawing}"); + } +} From 47aa74994386492e7b7aa9d3d0dbd93d1b591896 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 08:53:35 -0800 Subject: [PATCH 070/103] Symbols: the panel and Control bar find the selected instances' symbols once per revision The Symbols panel listed the symbols the selected instances link to by looking up every selected instance, cloning its symbol name, sorting and deduplicating the list on every frame it was drawn. The Control bar's Replace menu looked up every selected object on every frame to find the symbol they share. With 1,024 instances selected, ten idle frames of the panel alone made 10,240 lookups by id, and the Control bar made as many again. SymbolInstances, the walk of the selection kept per (document uid, revision), now also keeps the linked symbol names and the shared symbol, each found on its first read. The Control bar walks the selection for its instances only when instances alone are selected, so a selected group is not walked for it. --- crates/ui-egui/src/caches.rs | 7 ++ crates/ui-egui/src/panels/symbols.rs | 66 ++++++++---- crates/ui-egui/src/panels/symbols/tests.rs | 116 +++++++++++++++++++++ 3 files changed, 169 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6dcec22bff..8c13fca6a1 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -305,6 +305,13 @@ pub struct SymbolInstances { /// One of them has a scale, rotation or shear that Reset Transformation would change; measured /// on the first read. pub transformed: Option<bool>, + /// The names of the symbols they are instances of, each once and sorted; found on the first + /// read. + pub names: Option<Vec<String>>, + /// The symbol the selected objects share when every one is a symbol instance, blank when they + /// are instances of different symbols, and `None` inside when nothing is selected or one is not + /// an instance; found on the first read. + pub shared: Option<Option<String>>, } /// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision). diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index c9179cfa06..c9147ef357 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -323,12 +323,9 @@ fn instance_flags(app: &VectorcraftApp) -> InstanceFlags { } } -/// The names of the symbols the selected instances are instances of, each once. -fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> { - let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return vec![] }; - let Some(found) = selected_instances(app) else { return vec![] }; - let mut names: Vec<String> = found - .ids +/// The names of the symbols the instances `ids` of `doc` are instances of, each once and sorted. +fn symbol_names(doc: &Document, ids: &[NodeId]) -> Vec<String> { + let mut names: Vec<String> = ids .iter() .filter_map(|id| match doc.node(*id).map(|n| &n.kind) { Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.clone()), @@ -340,6 +337,15 @@ fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> { names } +/// The names of the symbols the selected instances are instances of, each once, looked up once per +/// (document uid, revision) ([`SymbolInstances::names`]). +fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> { + let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return vec![] }; + let Some(found) = selected_instances(app) else { return vec![] }; + let ids = &found.ids; + found.names.get_or_insert_with(|| symbol_names(&doc, ids)).clone() +} + /// Collect the IDs of selected instances of symbol `name` (including inside groups). fn selected_symbol_instances(app: &VectorcraftApp, name: &str) -> Vec<u64> { let mut ids = vec![]; @@ -431,19 +437,40 @@ fn transformed_instances_selected(app: &mut VectorcraftApp) -> bool { *found.transformed.get_or_insert_with(|| transformed(&doc, ids)) } -/// The symbols of the selected objects when every one is a symbol instance; `None` otherwise. -fn selected_instance_symbols(app: &VectorcraftApp) -> Option<Vec<String>> { +/// The symbol the selected objects of `st` share when every one is a symbol instance, blank when +/// they are instances of different symbols; `None` when nothing is selected or one is not an +/// instance. +fn shared_symbol(st: &DocState) -> Option<String> { + let mut shared: Option<&str> = None; + for id in &st.selection.objects { + let Some(NodeKind::SymbolInstance { symbol, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return None }; + if shared.is_some_and(|s| s != symbol) { + shared = Some(""); + } else if shared.is_none() { + shared = Some(symbol); + } + } + shared.map(str::to_string) +} + +/// [`shared_symbol`] of the active document, kept in [`SymbolInstances::shared`] once per +/// (document uid, revision). While that version's selection has not been walked for its instances, +/// the walk runs only when instances alone are selected, so a selected group is not walked for the +/// Control bar. +fn selected_shared_symbol(app: &mut VectorcraftApp) -> Option<String> { let st = app.session.active()?; - let symbols: Option<Vec<String>> = st - .selection - .objects - .iter() - .map(|id| match st.doc.node(*id).map(|n| &n.kind) { - Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.clone()), - _ => None, - }) - .collect(); - symbols.filter(|s| !s.is_empty()) + let walked = match &app.canvas.symbol_instances { + Some((key, found)) if *key == (st.uid, st.revision) => match &found.shared { + Some(shared) => return shared.clone(), + None => true, + }, + _ => false, + }; + let shared = shared_symbol(st); + if walked || shared.is_some() { + selected_instances(app)?.shared = Some(shared.clone()); + } + shared } /// The Control bar's Replace menu while symbol instances alone are selected: the document's @@ -456,10 +483,9 @@ fn selected_instance_symbols(app: &VectorcraftApp) -> Option<Vec<String>> { /// by its rank before the Transform link. Returns whether it drew them (symbol instances alone are /// selected). pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { - let Some(symbols) = selected_instance_symbols(app) else { return false }; + let Some(shared) = selected_shared_symbol(app) else { return false }; let Some(st) = app.session.active() else { return false }; let entries: Vec<Entry<String>> = st.doc.symbols.iter().map(|s| Entry::new(s.name.clone(), s.name.clone())).collect(); - let shared = symbols.first().filter(|first| symbols.iter().all(|s| s == *first)).cloned().unwrap_or_default(); // Reset: Reset Transformation, enabled while an instance's scale, rotation or shear differs // from its symbol's. let transformed = transformed_instances_selected(app); diff --git a/crates/ui-egui/src/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index 23bd444373..c9e2d68972 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -1173,6 +1173,122 @@ fn properties_and_symbols_panels_walk_the_selection_once_per_revision() { assert_eq!(scans(), before + 1); } +/// The names of the symbols the selected instances are instances of, each once, found by walking +/// every selected subtree on each call: what the cached list must match. +fn walked_names(app: &VectorcraftApp) -> Vec<String> { + let Some(st) = app.session.active() else { return vec![] }; + let mut names = vec![]; + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { + names.push(symbol.clone()); + } + }); + } + names.sort(); + names.dedup(); + names +} + +thread_local! { + /// [`panel_and_bar_lookups`] of this thread. + static PANEL_AND_BAR_LOOKUPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +/// The lookups by id that [`panel_and_bar`] has made on this thread, without those of the menus +/// the harness's frames rebuild. +fn panel_and_bar_lookups() -> u64 { + PANEL_AND_BAR_LOOKUPS.with(std::cell::Cell::get) +} + +/// The Symbols panel and the symbol instances' controls of the Control bar. +fn panel_and_bar(app: &mut VectorcraftApp, ui: &mut Ui) { + let before = vectorcraft_doc::path_lookups(); + show(app, ui); + control_bar(app, ui); + PANEL_AND_BAR_LOOKUPS.with(|n| n.set(n.get() + vectorcraft_doc::path_lookups() - before)); +} + +/// The Symbols panel finds the names of the selected instances' symbols, and the Control bar the +/// symbol they share, once per document revision: over idle frames with 1,024 instances selected, +/// their draws look up at most one node per instance in all, and both follow a rename, Undo and a +/// new selection. +#[test] +fn linked_symbol_names_are_found_once_per_revision() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + for (x, name) in [(10, "S"), (60, "T")] { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("symbol.new", json!({"name": name})).unwrap(); + } + // Two instances, doubled nine times. + for _ in 0..9 { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + let instances = app.session.active().map_or(0, |st| st.selection.objects.len()) as u64; + assert_eq!(instances, 1024); + let mut p = harness(app, panel_and_bar); + assert_eq!(linked_symbols(&mut p.app()), ["S", "T"]); + let before = panel_and_bar_lookups(); + for _ in 0..10 { + p.frame(); + } + let lookups = panel_and_bar_lookups() - before; + assert!(lookups <= instances, "10 idle frames looked up {lookups} nodes for {instances} selected instances"); + let check = |p: &mut Panel, want: &[&str], shared: Option<&str>, what: &str| { + p.frame(); + let mut app = p.app(); + assert_eq!(linked_symbols(&mut app), want, "{what}"); + assert_eq!(walked_names(&app), want, "{what}: a walk of the selection agrees"); + assert_eq!(selected_shared_symbol(&mut app).as_deref(), shared, "{what}: the Control bar's symbol"); + assert_eq!(app.session.active().and_then(shared_symbol).as_deref(), shared, "{what}: a walk of the selection agrees"); + }; + check(&mut p, &["S", "T"], Some(""), "two symbols' instances"); + p.app().run("symbol.options", json!({"name": "S", "newName": "R"})).unwrap(); + check(&mut p, &["R", "T"], Some(""), "after a rename"); + p.app().run("edit.undo", json!({})).unwrap(); + check(&mut p, &["S", "T"], Some(""), "after Undo"); + let t = instance_of(&p.app(), "T").expect("a T instance"); + p.app().run("select.set", json!({"ids": [t.0]})).unwrap(); + check(&mut p, &["T"], Some("T"), "one T instance selected"); + p.app().run("symbol.options", json!({"name": "T", "newName": "U"})).unwrap(); + check(&mut p, &["U"], Some("U"), "the selected instance's symbol renamed"); + let group = p.app().run("object.group", json!({})).unwrap()["id"].clone(); + p.app().run("select.set", json!({"ids": [group]})).unwrap(); + check(&mut p, &["U"], None, "the instance in a selected group"); + p.app().run("select.none", json!({})).unwrap(); + check(&mut p, &[], None, "nothing selected"); +} + +/// The Control bar's symbol does not walk a selected group for its instances while no reader has +/// walked that document version, as a group never shows the symbol controls; instances alone +/// selected are walked once, and a version already walked keeps its answer. +#[test] +fn the_control_bar_walks_only_a_selection_of_instances() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + let inst = app.run("symbol.new", json!({"name": "S"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + let before = scans(); + for _ in 0..3 { + assert_eq!(selected_shared_symbol(&mut app), None, "a selected group"); + } + assert_eq!(scans(), before, "a selected group is not walked"); + assert!(has_instances_selected(&mut app), "the panel's readers walk the group"); + assert_eq!(selected_shared_symbol(&mut app), None, "a walked group"); + assert_eq!(scans(), before + 1, "one walk for the group"); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + for _ in 0..3 { + assert_eq!(selected_shared_symbol(&mut app).as_deref(), Some("S"), "a selected instance"); + } + assert_eq!(scans(), before + 2, "one walk for the instance"); +} + /// The picture the panel's tile shows of an imported symbol frames the symbol's whole art. #[test] fn an_imported_symbols_thumbnail_frames_its_whole_art() { From 8c1ab0dbf739404f393eb3bd9e2f590257f45047 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 13:06:43 -0800 Subject: [PATCH 071/103] Tests: the Control bar keeps its answer for a walked group Once a reader has walked the selection of a document version, the Control bar stores its answer for a selected group too. The test now reads the Control bar's symbol three times for a walked group and checks that the reads look up at most one node. --- crates/ui-egui/src/panels/symbols/tests.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index c9e2d68972..bd9bd7f3e1 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -1280,7 +1280,12 @@ fn the_control_bar_walks_only_a_selection_of_instances() { } assert_eq!(scans(), before, "a selected group is not walked"); assert!(has_instances_selected(&mut app), "the panel's readers walk the group"); - assert_eq!(selected_shared_symbol(&mut app), None, "a walked group"); + let lookups = vectorcraft_doc::path_lookups(); + for _ in 0..3 { + assert_eq!(selected_shared_symbol(&mut app), None, "a walked group"); + } + let lookups = vectorcraft_doc::path_lookups() - lookups; + assert!(lookups <= 1, "3 reads of a walked group's symbol looked up {lookups} nodes"); assert_eq!(scans(), before + 1, "one walk for the group"); app.run("select.set", json!({"ids": [inst]})).unwrap(); for _ in 0..3 { From 094f60b2fb6a29bc420fff27f03ac146a7babbff Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 20:36:08 -0800 Subject: [PATCH 072/103] Tests: DWG opens through the DXF Import Options dialog and the CLI worker - The DXF Import Options dialog test opens a DWG, confirms it at 1:1 in model space and places it. - `vectorcraft-cli info` reads a DWG as the DXF it was written from, and five damaged copies (cut short, overwritten, bytes flipped) end in an error that names DWG or open with warnings, with the process exiting normally. - The engine's DWG and DXF test modules are listed in order. --- Cargo.lock | 2 ++ apps/vectorcraft-cli/Cargo.toml | 2 ++ apps/vectorcraft-cli/tests/it/fileio.rs | 37 ++++++++++++++++++++++++ crates/engine/src/cmd/fileio.rs | 4 +-- crates/ui-egui/Cargo.toml | 2 ++ crates/ui-egui/src/dialogs/dxf_import.rs | 19 ++++++++++++ 6 files changed, 64 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 227bcc9a37..b6bdcc0afe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8699,6 +8699,7 @@ dependencies = [ name = "vectorcraft-cli" version = "0.25.1" dependencies = [ + "craft-dwg", "log", "objc2-core-foundation", "objc2-core-text", @@ -9235,6 +9236,7 @@ dependencies = [ "bytemuck", "chrono", "craft", + "craft-dwg", "craft-image-codecs", "egui", "egui_extras", diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 25cffe599e..f3115d0779 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -47,6 +47,8 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" [dev-dependencies] tempfile = "3" vectorcraft-testkit = { workspace = true } +# DWG files for the `info` test, written from DXF by craft-dwg. +craft-dwg = { workspace = true } serde_json = { workspace = true } # The files of other crates that this crate compiles or its tests read, for CI's test selection. diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 9593d2630e..0c2ee7aaef 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -378,3 +378,40 @@ fn convert_and_run_write_ait_templates() { assert!(!one.status.success()); assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr)); } + +/// A DWG drawing opens through a worker copy of the program, so a damaged one ends in an error from +/// `info`, never in a crash. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on +/// aarch64. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() { + let dxf = tmp("plan.dxf"); + make(&dxf, 120, 80); + craft_dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&std::fs::read(&dxf).unwrap(), "AC1018").unwrap(); + let good = tmp("plan.dwg"); + std::fs::write(&good, &dwg).unwrap(); + // The DWG comes in as the DXF it was written from. + let (v, from) = (info(&good), info(&dxf)); + assert!(v["kinds"]["Path"].as_u64().is_some_and(|n| n > 0), "{v}"); + assert_eq!((&v["kinds"], &v["artboards"][0]["rect"]), (&from["kinds"], &from["artboards"][0]["rect"]), "{v}\n{from}"); + + let n = dwg.len(); + let mut damaged = vec![dwg[..n / 3].to_vec(), dwg[..2 * n / 3].to_vec(), dwg[..16].to_vec()]; + let mut overwritten = dwg.clone(); + overwritten[n / 2..(n / 2 + 64).min(n)].fill(0xFF); + damaged.push(overwritten); + let mut flipped = dwg.clone(); + flipped.iter_mut().skip(32).step_by(97).for_each(|b| *b ^= 0xA5); + damaged.push(flipped); + for (i, bytes) in damaged.iter().enumerate() { + let path = tmp(&format!("damaged-{i}.dwg")); + std::fs::write(&path, bytes).unwrap(); + let out = Command::new(crate::bin()).args(["info", &path]).output().unwrap(); + // A process ended by a signal has no exit code. + assert!(out.status.code().is_some(), "damaged file {i}: {:?}", out.status); + if !out.status.success() { + assert!(String::from_utf8_lossy(&out.stderr).contains("DWG"), "damaged file {i}: {}", String::from_utf8_lossy(&out.stderr)); + } + } +} diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 9d89de2c3c..1a24bf623b 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -246,11 +246,11 @@ mod tests_svgimport; #[cfg(test)] mod tests_eps; -#[cfg(test)] -mod tests_dxfimport; #[cfg(test)] mod tests_dwgimport; #[cfg(test)] +mod tests_dxfimport; +#[cfg(test)] mod tests_hpgl; #[cfg(test)] mod tests_metafile; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 49fad8d56f..ac7b1fe1a6 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -95,6 +95,8 @@ web-time = "1" rustix = { workspace = true, features = ["std", "process"] } [dev-dependencies] +# DWG files for the DXF Import Options tests, written from DXF by craft-dwg. +craft-dwg = { workspace = true } # `Fixture` and the stories sit behind craft-ui's `testing` feature. craft = { workspace = true, features = ["ui-testing"] } egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index a493f3474b..0a35c97b32 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -616,6 +616,25 @@ mod tests { assert_eq!(w, 100.0, "1 pt = 1 unit"); } + /// craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on aarch64. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_opens_and_places_through_the_dialog() { + vectorcraft_engine::dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap(); + let mut app = host::app(); + io::open_bytes(&mut app, "plan.dwg", &dwg, None).unwrap(); + let f = host::fields(&app, KIND); + assert_eq!((&f["mode"], &f["layout"], &f["unit"]), (&json!("open"), &json!("Model"), &json!("Millimeters"))); + host::confirm(&mut app, KIND).unwrap(); + assert!(!host::is_open(&app, KIND)); + let w = app.session.doc().unwrap().doc.artboards[0].rect.width(); + assert!((w - 100.0 * Unit::Millimeters.points()).abs() < 1e-6, "the model space line at 1:1: {w}"); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + crate::place::run(&mut app, &json!({"name": "plan.dwg", "dataBase64": vectorcraft_format::base64_encode(&dwg)})).unwrap(); + assert_eq!(host::fields(&app, KIND)["mode"], "place"); + } + #[test] fn placing_a_drawing_asks_then_places_one_group() { let mut app = host::app(); From 5c630500b3026532d039df8fafa15dde00b7c945 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 21:28:54 -0800 Subject: [PATCH 073/103] File formats: DWG converts off the UI thread, and a thumbnail's worker stops in time Opening or placing a DWG drawing from the desktop UI converted it on the UI thread before DXF Import Options opened, so the window stopped responding until a large drawing was converted. File > Open, Open Recent, the Home screen, a drop and Place now convert it on a job of their own; the status bar says "Converting <name>..." and the dialog opens once the conversion is done. A drawing that can't be converted is reported and does not go on the recent files. Commands run at once (MCP, scripts) still convert before they return. `thumbnail` exits after 20 seconds, but a DWG worker it started kept running after that. The CLI now starts the worker with `--dwg-worker-seconds 20`, and a worker started that way exits with code 1 once its time is up. The CLI `info` test requires the drawing cut to a third and the one cut to its header to be refused. The File formats row and the DWG entry in docs/target-app-parity.md name the remaining limits: the web build and R1.x and R2.x drawings return an error that says to save as DXF. --- apps/vectorcraft-cli/src/main.rs | 2 + apps/vectorcraft-cli/tests/it/fileio.rs | 24 ++++++ crates/cad/src/dwg.rs | 38 +++++++- crates/ui-egui/src/dialogs/dxf_import.rs | 105 ++++++++++++++++++++++- crates/ui-egui/src/io/open.rs | 6 +- crates/ui-egui/src/opening.rs | 68 +++++++++++++++ crates/ui-egui/src/place.rs | 9 ++ docs/target-app-parity.md | 4 +- 8 files changed, 251 insertions(+), 5 deletions(-) diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b4a65c7ba0..dd36a5e573 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -622,6 +622,8 @@ fn thumbnail(args: &[String]) -> Result<(), String> { } } let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?; + // A DWG worker ends by then too, so the exit below leaves no conversion running. + vectorcraft_engine::dwg::use_own_worker_for(THUMBNAIL_TIME); // The process ends when the time is up, wherever the work is: OUT is written whole or not at all. std::thread::spawn(|| { std::thread::sleep(THUMBNAIL_TIME); diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 0c2ee7aaef..95922dc497 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -410,8 +410,32 @@ fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() { let out = Command::new(crate::bin()).args(["info", &path]).output().unwrap(); // A process ended by a signal has no exit code. assert!(out.status.code().is_some(), "damaged file {i}: {:?}", out.status); + // The file cut to a third and the one cut to its header can't be read; the reader may + // recover the others. + if i == 0 || i == 2 { + assert!(!out.status.success(), "damaged file {i} is refused: {}", String::from_utf8_lossy(&out.stdout)); + } if !out.status.success() { assert!(String::from_utf8_lossy(&out.stderr).contains("DWG"), "damaged file {i}: {}", String::from_utf8_lossy(&out.stderr)); } } } + +/// A DWG worker started with a time limit (as `thumbnail` starts one) exits with code 1 once the +/// time is up, even while it still waits for its drawing, so `thumbnail`'s exit leaves no +/// conversion running. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() { + let mut worker = Command::new(crate::bin()) + .args(["--dwg-worker", "--dwg-worker-seconds", "1"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + // Its input stays open, so the worker never gets the whole request. + let input = worker.stdin.take(); + let status = worker.wait().unwrap(); + drop(input); + assert_eq!(status.code(), Some(1), "{status:?}"); +} diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index 65ed42af6a..b5d135ef58 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -8,7 +8,43 @@ use std::hash::BuildHasher; use std::sync::{Arc, LazyLock, Mutex, PoisonError}; -pub use craft_dwg::{WORKER_ARG, allow_in_process, serve_if_asked, use_own_worker}; +pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; + +/// The worker argument after [`WORKER_ARG`] that gives the most seconds the worker runs +/// ([`use_own_worker_for`]). +const WORKER_SECONDS_ARG: &str = "--dwg-worker-seconds"; + +/// Serve one conversion and return the exit code if this process was started as a worker. A +/// worker started by [`use_own_worker_for`] exits with code 1 once its time is up, wherever the +/// conversion is. +pub fn serve_if_asked() -> Option<i32> { + let mut args = std::env::args_os().skip(1); + if args.next()? != WORKER_ARG { + return None; + } + if args.next().is_some_and(|a| a == WORKER_SECONDS_ARG) + && let Some(seconds) = args.next().and_then(|s| s.to_str()?.parse::<u64>().ok()) + { + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(seconds)); + std::process::exit(1); + }); + } + craft_dwg::serve_if_asked() +} + +/// [`use_own_worker`], each worker exiting once `limit` (in whole seconds, at least 1) is up, so a +/// program that ends after `limit` leaves no conversion running. If this program's path can't be +/// found, the worker setting does not change. Web builds have no worker. +pub fn use_own_worker_for(limit: std::time::Duration) { + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + if let Ok(program) = std::env::current_exe() { + let seconds = limit.as_secs().max(1).to_string(); + craft_dwg::worker::use_worker(program, vec![WORKER_ARG.into(), WORKER_SECONDS_ARG.into(), seconds.into()]); + } + #[cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))] + let _ = limit; +} /// The largest DXF rendition kept for the next read of the same drawing (128 MiB). const MAX_KEPT: usize = 128 << 20; diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 0a35c97b32..491aaddeea 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -332,6 +332,54 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St return false; } let Ok(info) = vectorcraft_cad::info(bytes) else { return false }; + show(app, name, bytes, path, place, &info) +} + +/// [`offer`] for a file the user opens or places where files are read off the UI thread: a DWG +/// drawing is converted on a job of its own ([`crate::opening::convert_drawing`]) and its dialog +/// opens once that is done ([`converted`]) → true; false when `bytes` aren't a DWG drawing. +pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, place: Option<&Value>) -> bool { + if !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| f.id != "dwg") { + return false; + } + crate::opening::convert_drawing(app, name, bytes.to_vec(), path, place.cloned()); + true +} + +/// [`offer_place`] for a file the user places where files are read off the UI thread: a DWG +/// drawing is converted first ([`convert_in_background`]) → true; false when `p` names no DWG +/// drawing. +pub fn convert_place_in_background(app: &mut VectorcraftApp, p: &Value) -> bool { + let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension); + if p.get("dxf").is_some() || named.as_deref() != Some("dwg") { + return false; + } + let Some((name, bytes, path)) = place_source(app, p, |ext| ext == "dwg") else { return false }; + convert_in_background(app, &name, &bytes, path, Some(p)) +} + +/// A DWG drawing converted off the UI thread ([`convert_in_background`]): its dialog opens, to +/// place it with the `file.place` params `place`, or else to open it (it then goes on the recent +/// files); a drawing that can't be read is reported. +pub(crate) fn converted(app: &mut VectorcraftApp, name: &str, conversion: crate::opening::Conversion, path: Option<String>, place: Option<&Value>) { + let (bytes, info) = conversion; + match info { + Ok(info) => { + let opens = place.is_none(); + if show(app, name, &bytes, path.clone(), place, &info) + && opens + && let Some(path) = &path + { + io::note_recent(app, path); + } + } + Err(e) if place.is_some() => app.status(e), + Err(e) => io::report_open_error(app, &fileio::file_name(name), &e), + } +} + +/// Open the dialog for `bytes`, the drawing `info` describes (see [`offer`]). +fn show(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, place: Option<&Value>, info: &vectorcraft_cad::DxfInfo) -> bool { let mut choices = DxfChoices { layout: info.layouts.first().cloned().unwrap_or_else(|| "Model".into()), unit: info.unit, @@ -348,7 +396,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St } let file = DialogFile::new(bytes.to_vec()); let source = Source { place: place.map(|p| other_place_params(p, &["dxf"])), name: name.to_string(), path, file: file.clone() }; - let dialog = DxfImportDialog::new(place.is_some(), file, &info, choices); + let dialog = DxfImportDialog::new(place.is_some(), file, info, choices); open_held(app, dialog, move |app, choices| confirm(app, &source, choices)).is_some() } @@ -635,6 +683,61 @@ mod tests { assert_eq!(host::fields(&app, KIND)["mode"], "place"); } + /// Where files the user opens and places are read off the UI thread, a DWG drawing is converted + /// on a job: its dialog opens once the conversion is done, not while File › Open or Place runs. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_is_converted_off_the_ui_thread_before_its_dialog_opens() { + fn converted(app: &mut VectorcraftApp) { + for c in &mut app.opening.converting { + let (tx, done) = std::sync::mpsc::channel(); + if let Ok(r) = c.done.recv() { + let _ = tx.send(r); + } + c.done = done; + } + crate::opening::poll(app); + } + vectorcraft_engine::dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap(); + let dir = crate::tests_folder::Folder::new("dxf-import-dwg-background"); + let (plan, bad) = (dir.join("plan.dwg"), dir.join("bad.dwg")); + std::fs::write(&plan, &dwg).unwrap(); + std::fs::write(&bad, &dwg[..dwg.len() / 3]).unwrap(); + let (plan, bad) = (plan.to_string_lossy().into_owned(), bad.to_string_lossy().into_owned()); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + crate::io::open_file(&mut app, &plan, true).unwrap(); + assert!(!host::is_open(&app, KIND), "the dialog waits for the conversion"); + assert_eq!(app.opening.converting.len(), 1); + assert!(crate::opening::long_operation_busy(&app)); + assert_eq!(app.ui.status, "Converting plan.dwg…"); + // Asked for again while it is converted, it is converted once. + crate::io::open_file(&mut app, &plan, true).unwrap(); + assert_eq!(app.opening.converting.len(), 1); + converted(&mut app); + assert!(app.opening.converting.is_empty() && app.ui.status.is_empty(), "{}", app.ui.status); + assert_eq!(host::fields(&app, KIND)["mode"], "open"); + assert_eq!(app.ui.recent_files.first(), Some(&plan)); + host::confirm(&mut app, KIND).unwrap(); + let w = app.session.doc().unwrap().doc.artboards[0].rect.width(); + assert!((w - 100.0 * Unit::Millimeters.points()).abs() < 1e-6, "the model space line at 1:1: {w}"); + // Placed by the user, it is converted first too. + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + assert!(!host::is_open(&app, KIND)); + converted(&mut app); + assert_eq!(host::fields(&app, KIND)["mode"], "place"); + host::cancel(&app, KIND); + // A drawing that can't be converted is reported, and doesn't go on the recent files. + crate::io::open_file(&mut app, &bad, true).unwrap(); + converted(&mut app); + assert!(!host::is_open(&app, KIND)); + assert!(app.ui.status.starts_with("Couldn't open bad.dwg"), "{}", app.ui.status); + assert_ne!(app.ui.recent_files.first(), Some(&bad)); + }); + } + #[test] fn placing_a_drawing_asks_then_places_one_group() { let mut app = host::app(); diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 7223cc92fb..53fb450c93 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -641,7 +641,7 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va if let Some(r) = try_activate_open_document(app, path, canonical.as_deref())? { return Ok(r); } - if app.opening.pending.iter().any(|p| same(&p.path)) { + if app.opening.pending.iter().any(|p| same(&p.path)) || app.opening.converting.iter().any(|c| c.path.as_deref().is_some_and(|p| same(p))) { return Ok(Value::Null); } // A shortcut set is read by Import Shortcut Set, up to its reader's cap. @@ -672,6 +672,10 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va check_import_size(path, false)?; let bytes = read(app, path)?; if background && opens_as(path).is_none() { + // A DWG drawing is converted off the UI thread too, before its import options open. + if crate::dialogs::dxf_import::convert_in_background(app, path, &bytes, Some(path.to_string()), None) { + return Ok(Value::Null); + } // A PDF with several pages or a password, a DXF drawing, or a PSD file with several layers // or with slices asks first, as at once. if crate::dialogs::import_pdf::offer(app, path, &bytes, Some(path.to_string()), None) diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 541b033cff..9ec98750e7 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -35,10 +35,32 @@ pub struct Pending { pub(crate) started: f64, } +/// What converting a DWG drawing hands back: its bytes, and its layouts and units or why it can't +/// be read. +pub(crate) type Conversion = (Vec<u8>, Result<vectorcraft_cad::DxfInfo, String>); + +/// A DWG drawing being converted to DXF off the UI thread before its import options open +/// ([`convert_drawing`]). +pub struct Converting { + /// What the status bar shows ("Converting Plan.dwg"). + pub label: String, + /// Where it is, when it was read from a file. + pub path: Option<String>, + /// Its name (or path). + name: String, + /// The `file.place` params when it is being placed, else `None` (it opens). + place: Option<Value>, + pub(crate) done: Receiver<Conversion>, + /// The automation roots in force where the open or place started. + scope: ScopeHandle, +} + /// The files being read. #[derive(Default)] pub struct Opening { pub pending: Vec<Pending>, + /// DWG drawings being converted before their import options open. + pub converting: Vec<Converting>, /// Open documents asked for again while the active one couldn't change: their tabs come to /// the front once it can ([`may_switch`]), each in the file access scope it was asked in. pub activate: Vec<(String, ScopeHandle)>, @@ -50,6 +72,7 @@ pub struct Opening { pub fn long_operation_busy(app: &VectorcraftApp) -> bool { app.background.jobs.iter().any(|j| !j.label.is_empty() && !j.cancelled()) || !app.opening.pending.is_empty() + || !app.opening.converting.is_empty() || !app.plugin_runs.running.is_empty() || !app.placing.pending.is_empty() || !app.trace_runs.running.is_empty() @@ -136,6 +159,30 @@ pub(crate) fn finish_answered(app: &mut VectorcraftApp, path: &str, file: ReadFi track(app, path, done, scope, CancelToken::new()) } +/// Convert `bytes`, the DWG drawing `name` (at `path`, if read from a file), to DXF and read its +/// layouts and units on a job of its own. Its DXF Import Options open once that is done +/// ([`poll`], [`crate::dialogs::dxf_import::converted`]), to place it with the `file.place` params +/// `place`, or else to open it. +pub(crate) fn convert_drawing(app: &mut VectorcraftApp, name: &str, bytes: Vec<u8>, path: Option<String>, place: Option<Value>) { + let (tx, done) = channel(); + // The automation roots in force here are in force there. + let scope = ScopeHandle::capture(); + let run = scope.clone(); + app.jobs().spawn( + "vectorcraft-dwg", + Box::new(move || { + let info = run + .run(|| vectorcraft_engine::guard::catch_panic(|| vectorcraft_cad::info(&bytes))) + .unwrap_or_else(|msg| Err(format!("internal error: {msg} (please report this bug)"))); + // The app may have quit meanwhile: nothing to hand it to. + let _ = tx.send((bytes, info)); + }), + ); + let label = format!("Converting {}", fileio::file_name(name)); + app.status(format!("{label}…")); + app.opening.converting.push(Converting { label, path, name: name.to_string(), place, done, scope }); +} + /// Lists the file being read for `path` and tells the status bar → `{background: true, status}`. fn track(app: &mut VectorcraftApp, path: &str, done: Receiver<Result<ReadFile, String>>, scope: ScopeHandle, token: CancelToken) -> Value { let label = format!("Opening {}", fileio::file_name(path)); @@ -178,6 +225,27 @@ pub fn poll(app: &mut VectorcraftApp) { // Closed meanwhile, it opens again; a failure is reported to the user there. let _ = scope.run(|| crate::io::open_reporting(app, &path)); } + // A DWG drawing that has been converted asks for its import options. + let mut i = 0; + while let Some(c) = app.opening.converting.get(i) { + let r = match c.done.try_recv() { + Ok(r) => r, + Err(TryRecvError::Empty) => { + i += 1; + continue; + } + Err(TryRecvError::Disconnected) => (Vec::new(), Err("the drawing stopped being converted (please report this bug)".to_string())), + }; + let c = app.opening.converting.remove(i); + // The status bar no longer says it is converting. + if app.ui.status == format!("{}…", c.label) { + app.ui.status.clear(); + } + c.scope.run(|| crate::dialogs::dxf_import::converted(app, &c.name, r, c.path, c.place.as_ref())); + if !may_switch(app) { + return; + } + } let mut i = 0; while let Some(p) = app.opening.pending.get(i) { let r = match p.done.try_recv() { diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 46fe91a1dc..b4d501fcd0 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -302,6 +302,15 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu if offered { return Ok(Value::Null); } + // A DWG drawing the user places is converted off the UI thread before its import options open. + if builtin + && ask + && matches!(read, Read::ForUser { .. }) + && crate::placing::available(app) + && crate::dialogs::dxf_import::convert_place_in_background(app, &p) + { + return Ok(Value::Null); + } // A DXF drawing asks for its import options. if builtin && ask && crate::dialogs::dxf_import::offer_place(app, &p) { return Ok(json!({ "dialog": crate::dialogs::dxf_import::KIND })); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3fbcb5f33d..307bf8f42f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -367,7 +367,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | | Layers, artboards, document setup | 5 | 82% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: managing artboards from the canvas (artboard locking and colors, #2532 and #2403, Layers row menus and blend spine row menus are done; guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated; Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), the editing copy that Include Editing Data for Other Apps writes in a saved `.ai` (VectorCraft reopens the embedded VectorCraft document instead when it is current and readable, unless `document.open` chooses pages or sets `linkPages: true` or `editingData: false`) without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (images with a Warp effect keep it editable when they qualify), and with live objects other than grouped column, stacked column, line and area graphs, envelopes, blends, symbols with their instances (except instances the writer writes as their art, with a warning; symbols' 9-slice guides and export types are left out, and a dynamic symbol instance that otherwise qualifies stays live with its parts' fill, stroke, opacity and blend changes, which other apps leave out; the writer keeps them for VectorCraft only when the instance's changes fit in 1 MiB, and fill and stroke changes to type, held as outlines, are not reproduced, and when the copy leaves out an earlier part, such as an empty path, a change applies to a different part or to none) and gradient meshes (except meshes with a Lab point, more than 128 rows or columns, folded meshes, meshes the reader would open otherwise, meshes in pattern tiles or in art cut to a clipping object, and meshes on a large canvas) the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object); see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; aligned type lies as far from its path as the file lays it out (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`); the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), the editing copy that Include Editing Data for Other Apps writes in a saved `.ai` (VectorCraft reopens the embedded VectorCraft document instead when it is current and readable, unless `document.open` chooses pages or sets `linkPages: true` or `editingData: false`) without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (images with a Warp effect keep it editable when they qualify), and with live objects other than grouped column, stacked column, line and area graphs, envelopes, blends, symbols with their instances (except instances the writer writes as their art, with a warning; symbols' 9-slice guides and export types are left out, and a dynamic symbol instance that otherwise qualifies stays live with its parts' fill, stroke, opacity and blend changes, which other apps leave out; the writer keeps them for VectorCraft only when the instance's changes fit in 1 MiB, and fill and stroke changes to type, held as outlines, are not reproduced, and when the copy leaves out an earlier part, such as an empty path, a change applies to a different part or to none) and gradient meshes (except meshes with a Lab point, more than 128 rows or columns, folded meshes, meshes the reader would open otherwise, meshes in pattern tiles or in art cut to a clipping object, and meshes on a large canvas) the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand import, DWG import in the web build and of R1.x and R2.x drawings (both say to save the drawing as DXF), shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object); see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; aligned type lies as far from its path as the file lays it out (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`); the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); View › Snapping groups five existing toggles and Pixel Snapping Options… (G13), retaining top-level commands and shortcuts; Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | | Export for Screens, Asset Export, slices, Save for Web | 3 | 87% | TIFF choices and settings are implemented; anti-aliasing ghost borders are fixed (#983) | 2–4 | estimated; depth not measured | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | @@ -2561,7 +2561,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - - DWG drawings open and place, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker` on desktop, and the DXF reader reads it with the DXF Import Options. DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). + - DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build and R1.x and R2.x drawings return an error that says to save the drawing as DXF. DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - `.cmx` exchange files with 32-bit coordinates open and place: `craft-cdr` reads their color, pen, line type, dash and outline tables and each page's instructions, and the importer maps pages, layers (a layer that holds nothing is left out), groups and curves, with uniform fills and outlines, as it maps a `.cdr` drawing's. Text, images, rectangles, ellipses, clipping paths, other fills, arrowheads and lenses are named in the warnings, and big-endian files and files with 16-bit coordinates are refused with a message (`craft-cdr` `storytold/craft-libs@9b28b56bc7` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`, `crates/engine/tests/import_fuzz.rs`). From c3cbe1983ca2fbf3b95b400ca80225de0fc89581 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 3 Dec 2026 23:31:45 -0800 Subject: [PATCH 074/103] File formats: pass the path check to is_some_and directly Clippy 1.100 denies the closure around `same` in the converting-file check of `open.rs` as `redundant_closure`, which stopped the clippy step of `cargo xtask ci`. The check now passes `&same`; behavior is unchanged. --- crates/ui-egui/src/io/open.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 53fb450c93..f22c0b9609 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -641,7 +641,7 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va if let Some(r) = try_activate_open_document(app, path, canonical.as_deref())? { return Ok(r); } - if app.opening.pending.iter().any(|p| same(&p.path)) || app.opening.converting.iter().any(|c| c.path.as_deref().is_some_and(|p| same(p))) { + if app.opening.pending.iter().any(|p| same(&p.path)) || app.opening.converting.iter().any(|c| c.path.as_deref().is_some_and(&same)) { return Ok(Value::Null); } // A shortcut set is read by Import Shortcut Set, up to its reader's cap. From 1302127d9acea066306f8164447bdb1d559c1443 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 00:51:42 -0800 Subject: [PATCH 075/103] xtask: test-lint reads fields of tuple literals A field read on a plain tuple literal, such as `pair.0` after `let pair = (Input { n: 5 },);`, now resolves to the element, so a conversion of a user value read from it is no longer reported as fixture-only. Parentheses without a top-level comma group the value inside them, so `(Pair(5)).0` still resolves to `5`. Primitive tuple elements stay inert. The merge of main also kept the `!path_tail` guard on capitalized calls that this branch had removed; qualified constructors such as `model::Input(5)` again count as fixture construction, with main's turbofish-aware path check kept. --- xtask/src/test_lint.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index b19962dfbd..047625145e 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -6679,7 +6679,7 @@ fn inert(op: &str, pos: usize, local: &LocalAt) -> Option<(bool, bool)> { let path = without_turbofish(&op[path_start..end]); ["Box::new", "String::from", "Vec::new"].iter().any(|p| path.ends_with(p)) }) - || (!path_tail && screaming_or_camel(name)); + || screaming_or_camel(name); if !builder { return None; } @@ -6895,7 +6895,7 @@ fn last_field(expr: &str) -> Option<(&str, &str)> { (n > 0 && expr.as_bytes()[dot] == b'.' && dot > 0 && expr.as_bytes()[dot - 1] != b'.').then(|| (&expr[..dot], &expr[dot + 1..])) } -/// The expression a struct literal or tuple constructor gives `field` when `base` (a local, a field +/// The expression a struct literal, tuple constructor or tuple literal gives `field` when `base` (a local, a field /// read or the literal itself) is one: `5` for `input.n` after `let input = Input { n: 5 };`. /// Local aliases resolve at their own binding positions. The expression comes with the position /// where its names are resolved. @@ -6906,12 +6906,18 @@ fn field_value(base: &str, field: &str, pos: usize, local: &LocalAt) -> Option<( } else if plain_local(base) && base.as_bytes()[0].is_ascii_lowercase() { let (_, init, at) = local(base, pos)?; return field_value(&init, field, at, local); + } else if base.starts_with('(') && matching(base.as_bytes(), 0) == Some(base.len() - 1) && top_level_at(&base[1..base.len() - 1], ",").is_empty() + { + // Without a top-level comma the parentheses only group the value inside them: `(Pair(5))`. + (base[1..base.len() - 1].to_owned(), pos) } else { (base.to_owned(), pos) }; let v = value.as_bytes(); let open = v.iter().take_while(|&&c| is_ident(c) || c == b':').count(); - if open == 0 || !matches!(v.get(open), Some(b'{' | b'(')) || matching(v, open) != Some(v.len() - 1) { + // A tuple literal (`(Input { n: 5 },)`) has no name before its `(`. + let tuple_literal = open == 0 && v.first() == Some(&b'('); + if (open == 0 && !tuple_literal) || !matches!(v.get(open), Some(b'{' | b'(')) || matching(v, open) != Some(v.len() - 1) { return None; } let args = split_args(v, open + 1, v.len() - 1); @@ -12952,6 +12958,8 @@ mod tests { "#[test]\nfn t() {\n let shown = Kind::A.to_string();\n assert_eq!(shown, \"a\");\n}\n", "#[test]\nfn t() {\n let c: u8 = 5.into();\n assert_eq!(c, 5);\n}\n", "#[test]\nfn t() {\n let pair = Pair(5, Kind::A);\n assert_eq!(pair.1.to_string(), \"a\");\n}\n", + "#[test]\nfn t() {\n let pair = (Input { n: 5 },);\n assert_eq!(pair.0.clone().n, 6);\n}\n", + "#[test]\nfn t() {\n let pair = (5, Kind::A);\n assert_eq!(pair.1.to_string(), \"a\");\n}\n", ] { assert_eq!(only("fixture-only", src), [], "{src}"); } @@ -12960,6 +12968,8 @@ mod tests { "#[test]\nfn t() {\n let xs = vec![Input { n: 5 }];\n assert_eq!(xs.len(), 1);\n}\n", "#[test]\nfn t() {\n let input = Input { n: 5 };\n assert_eq!(input.n.to_string(), \"5\");\n}\n", "#[test]\nfn t() {\n let pair = Pair(5, Kind::A);\n assert_eq!(pair.0.to_string(), \"5\");\n}\n", + "#[test]\nfn t() {\n let pair = (5, Kind::A);\n assert_eq!(pair.0.to_string(), \"5\");\n}\n", + "#[test]\nfn t() {\n let pair = (Pair(5));\n assert_eq!(pair.0.to_string(), \"5\");\n}\n", ] { assert_eq!(only("fixture-only", src), [(2, "fixture-only")], "{src}"); } From 7844ed33796d7949f9c90b96236b59fef893daa5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 00:59:23 -0800 Subject: [PATCH 076/103] Docs: split the unfilled-interior selection sentence The Selection fill eligibility entry now lists the cases where a hidden-only or true-None interior misses in one sentence, and the case where Select Inside Unfilled Shapes picks it in a second. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 309fea10ee..b90b091c14 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -709,7 +709,7 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss by default, with Object Selection by Path Only on or in Outline view, and with Select Inside Unfilled Shapes on and Path Only off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss by default, with Object Selection by Path Only on, and in Outline view. With Select Inside Unfilled Shapes on, Path Only off and not in Outline view, such an interior is picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Clicks inside unfilled shapes (#9175):** with Selection & Anchor Display › Select Inside Unfilled Shapes on (off by default; off, a click or drag there starts a marquee when it hits nothing else there: not the shape's stroke, other art or the shape's visible center point) and Object Selection by Path Only off, the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference` (MCP), and `a_drag_inside_an_unfilled_shape_makes_a_marquee_unless_asked` (Selection tool). Scores and estimates unchanged. From b3f5c2263324bc0e502fcc270e44abd1d5968537 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 01:01:51 -0800 Subject: [PATCH 077/103] Shapes: a live star keeps a small ratio and its corners through edits A live star whose ratio is below 0.01, which object.setLiveShape takes, lost its inner radius and its live shape when addon.shapes.configure changed another value: the stored ratio was clamped to 0.01 when the star was drawn and no longer counted as live. Any ratio from 0 to 1 now draws and stays live as it is. A corner list shorter than the star's or polygon's corners counted as one shared radius, so a new point or side count gave the missing corners the first corner's radius. The missing corners now stay sharp. A ratio that changes which corners a rounded star cuts is now an error with radius or kind in the same call, as points is, since the corners selected before it no longer name the same corners. The anchor selection is dropped by the same check. --- crates/doc/src/node/live_shape.rs | 21 ++++++++++----- crates/doc/src/node/tests.rs | 16 ++++++++++++ crates/engine/src/cmd/addons/shapes/tests.rs | 14 ++++++++++ crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 27 ++++++++++++++++---- crates/engine/src/tests/livecorners.rs | 27 ++++++++++++++++++++ crates/tools/src/addons/box3d.rs | 7 ++--- docs/mcp.md | 4 +-- docs/target-app-parity.md | 2 +- 9 files changed, 101 insertions(+), 19 deletions(-) diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 5ad2caeb48..f1419d9e95 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -148,9 +148,10 @@ impl LiveShape { /// the corners past the old last one are sharp. pub fn set_sides(&mut self, n: u64) { let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return }; + let old = *sides as usize; *sides = n.clamp(3, 1000) as u32; - spread(radii, *sides as usize); - spread(kinds, *sides as usize); + spread(radii, old, *sides as usize); + spread(kinds, old, *sides as usize); } /// A star's point count. None for other shapes. pub fn star_points(&self) -> Option<u32> { @@ -161,9 +162,10 @@ impl LiveShape { /// corners past the old last one are sharp. pub fn set_points(&mut self, n: u64) { let LiveShape::Star { points, radii, kinds, .. } = self else { return }; + let old = 2 * *points as usize; *points = n.clamp(2, 1000) as u32; - spread(radii, 2 * *points as usize); - spread(kinds, 2 * *points as usize); + spread(radii, old, 2 * *points as usize); + spread(kinds, old, 2 * *points as usize); } /// A star's ratio: its inner radius over its outer radius (0 when the outer radius is 0). None /// for other shapes. @@ -410,9 +412,14 @@ fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> { u32::deserialize(d).map(|n| n.clamp(2, 1000)) } -/// Give a corner list `n` entries: one value all its corners shared fills it; otherwise entries -/// past its end are the default (sharp, round) and entries past `n` go. An empty list stays empty. -fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, n: usize) { +/// Give a corner list for `old` corners `n` entries: one value all `old` corners shared fills it; +/// otherwise entries past its end are the default (sharp, round) and entries past `n` go. A list +/// shorter than `old` holds the default for its missing corners, so it is shared only when that +/// default is. An empty list stays empty. +fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, old: usize, n: usize) { + if !v.is_empty() && v.len() < old { + v.resize(old, T::default()); + } match v.first().copied() { Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], Some(_) => v.resize(n, T::default()), diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index add639ed4d..555a4f349d 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -186,6 +186,22 @@ fn a_star_round_trips_and_its_file_count_is_clamped() { assert_eq!(s.polygon_outline().anchor_count(), 18); } +/// A corner list shorter than the corners holds sharp corners past its end, so a new point or +/// side count does not give those corners the first corner's radius. +#[test] +fn a_short_corner_list_keeps_its_missing_corners_sharp() { + let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false }; + star.set_points(6); + let mut want = vec![0.0; 12]; + want[0] = 2.0; + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want), "{star:?}"); + let mut polygon = LiveShape::Polygon { radius: 40.0, sides: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false }; + polygon.set_sides(6); + let mut want = vec![0.0; 6]; + want[0] = 2.0; + assert!(matches!(&polygon, LiveShape::Polygon { radii, .. } if *radii == want), "{polygon:?}"); +} + #[test] fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { let close = |a: f64, b: f64| (a - b).abs() < 1e-9; diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs index 4f813263ef..9839c1ed26 100644 --- a/crates/engine/src/cmd/addons/shapes/tests.rs +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -168,6 +168,20 @@ fn configuring_a_live_star_keeps_its_live_shape() { } } +/// A live star with a ratio below 0.01, which `object.setLiveShape` accepts, keeps its inner +/// radius and stays live when it is configured without a ratio. +#[test] +fn configuring_a_live_star_keeps_a_small_ratio() { + let mut s = new_session(); + let id = id_of(&mut s, "shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 60.0, "radius2": 30.0, "points": 5})); + s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": 0.0001})).unwrap(); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 6})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { r1, r2, points: 6, .. } if *r1 == 60.0 && (r2 - 0.006).abs() < 1e-9), "{live:?}"); + assert_eq!(path, &live.to_path()); +} + /// Runs `cmd` with `p`, which must fail with `msg` and leave the document and its history as they /// were. fn refused(s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str) { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 022820f0b5..08207497fc 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -314,7 +314,7 @@ pub fn specs() -> Vec<CommandSpec> { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the drawn anchor count drops its selected anchors and segments), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b60f19cf06..79a26dd73f 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -130,6 +130,16 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live (changed && new != *l).then_some(new) } +/// Whether a star's anchors are laid out differently after an edit: a new point count, or a ratio +/// that changes which corners a rounded star cuts (each drawn anchor's source corner). +fn star_relaid(old: &LiveShape, new: &LiveShape) -> bool { + fn layout(l: &LiveShape) -> Option<Vec<Vec<usize>>> { + let path = l.to_path(); + LiveCorners::new(&path, Some(l)).map(|c| c.sources().to_vec()) + } + old.star_points().is_some() && (old.star_points() != new.star_points() || layout(old) != layout(new)) +} + /// The transform that takes live shape `old` to `new` where they differ only in place, angle and /// size (a new Rectangle, Ellipse or Polygon Angle, Polygon Radius, Side Length, Make Sides Equal, /// Line Length or Line Angle): what moves, turns and scales the rest of the object (a linked @@ -443,6 +453,14 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> { reshaped.insert(*id, ((**old).clone(), new)); } } + // A ratio that changes which corners a rounded star cuts lays its anchors out again, as a new + // point count does, so the corners a radius or kind would set can't be told apart. + if ratio.is_some() && (radius.is_some() || kind.is_some()) && reshaped.values().any(|(old, new)| star_relaid(old, new)) { + return Err(bad( + "object.setLiveShape", + "this `ratio` changes the star's anchors, so it can't be set with `radius` or `kind`: set the corners in a call of their own", + )); + } // A shape that moves, turns or scales takes the rest of the object along as a transform does: // Scale Strokes & Effects and Transform Patterns come from `strokes` and `patterns` or the // preferences, and are noted in the journal so a replay does the same. Corner radii in the rest @@ -471,11 +489,10 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> { *live = Some(Box::new(new.clone())); *path = new.to_path(); } - // A new point count, or a ratio that changes how many anchors the rounded star draws, lays - // its anchors out again: anchors and segments selected on the old layout would name - // others, or none. - if old.star_points() != new.star_points() || (old.star_points().is_some() && old.to_path().anchor_count() != new.to_path().anchor_count()) - { + // A new point count, or a ratio that changes which corners the rounded star cuts, lays its + // anchors out again: anchors and segments selected on the old layout would name others, + // or none. + if star_relaid(old, new) { sel.anchors.remove(id); sel.segments.remove(id); } diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 529fe0faf1..2a50f2a1bf 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -439,6 +439,33 @@ fn a_live_star_takes_a_new_point_count_and_ratio() { assert_eq!(node_path(&s, flat), before); } +/// A ratio that changes how many anchors a rounded star draws can't come with a radius: the +/// corners selected before it would no longer name the same corners. A ratio alone still drops +/// the stale anchor selection. +#[test] +fn a_ratio_that_relays_a_rounded_star_is_not_set_with_a_radius() { + let (mut s, _) = session(); + // At this ratio the inner points lie on the lines between the outer ones. + let flat = 36f64.to_radians().cos(); + let id = star(&mut s); + run(&mut s, json!({"id": id.0, "radius": 4})); + let rounded = node_path(&s, id).0.anchor_count(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let before = (node_path(&s, id), selected_anchors(&s, id)); + let err = s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": flat, "radius": 6})).unwrap_err(); + assert!(err.to_string().contains("`ratio`"), "{err}"); + assert_eq!((node_path(&s, id), selected_anchors(&s, id)), before); + // The same ratio alone lays the anchors out again and drops the selection. + run(&mut s, json!({"id": id.0, "ratio": flat})); + assert_ne!(node_path(&s, id).0.anchor_count(), rounded); + assert_eq!(selected_anchors(&s, id), None); + // A ratio that keeps the anchors still goes with a radius. + let other = star(&mut s); + run(&mut s, json!({"id": other.0, "radius": 4})); + run(&mut s, json!({"id": other.0, "ratio": 0.4, "radius": 5})); + assert_eq!(style(&s, other).0, Some(5.0)); +} + /// Each corner stops at its own limit: its cut reaches halfway along its shorter side, so a /// star's neighbouring corners meet without overlapping. #[test] diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index 4bac9e4fdd..4ff528e583 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -152,7 +152,8 @@ impl CustomShape { CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode } => { let raw = match spoke_ratio { Some(ratio) => { - let r2 = (*radius * ratio.clamp(0.01, 1.0)).max(0.01); + // Any ratio a live star takes (0 to 1) draws as it is. + let r2 = *radius * if ratio.is_finite() { ratio.clamp(0.0, 1.0) } else { 0.01 }; shapes::star_configured(Point::ZERO, *radius, r2, *sides, 0.0, *rounded, *randomized) } None => shapes::polygon_configured(Point::ZERO, *radius, *sides, 0.0, *rounded, *randomized), @@ -211,14 +212,14 @@ impl CustomShape { randomized, pie, arc_mode, - } if (0.01..=1.0).contains(ratio) && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole && { + } if (0.0..=1.0).contains(ratio) && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole && { let span = (pie.1 - pie.0).rem_euclid(360.0); span < 1e-9 || 360.0 - span < 1e-9 } => { Some(LiveShape::Star { r1: *radius, - r2: (*radius * ratio.clamp(0.01, 1.0)).max(0.01), + r2: *radius * ratio, points: (*sides).clamp(2, 1000), xf: *xf, radii: radii.clone(), diff --git a/docs/mcp.md b/docs/mcp.md index 4e097315a4..b198d6b293 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10003,8 +10003,8 @@ which drops an uneven scale or shear (its sides then differ) and keeps its centr length that isn't a number above 0 is an error. A star drawn with the Star tool or `shape.star` stays live (Star Properties): `points` (a whole number from 2 to 1000; its corners keep the radius and kind they shared) and `ratio` (its inner radius over its outer radius, above 0 and up to 1; the outer radius stays); any other count or ratio is an error, and a -count or ratio the star already has adds no undo step. A change to the point count or drawn anchor count drops the star's selected anchors and segments; -`points` with `radius` or `kind` in one call is an error, and so is a `ratio` for a star whose outer radius is 0. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees +count or ratio the star already has adds no undo step. A change to the point count, or a ratio that changes which corners a rounded star cuts, drops the star's selected anchors and segments; +`points` with `radius` or `kind` in one call is an error, as is such a `ratio` with `radius` or `kind`, and so is a `ratio` for a star whose outer radius is 0. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. `constrainPie: true` with one of `pieStart` and `pieEnd` (the panels' Constrain Pie Angle link) moves the other angle by as much, so each selected ellipse keeps its own span, counterclockwise from its start to its end; a whole ellipse diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index adc14865cb..d9c84d8d18 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1656,7 +1656,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_without_live_corners_adds_no_undo_step`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - - **Live stars:** a star drawn with the Star tool or `shape.star` stays a live shape (#4339), so its point count and ratio stay editable after it is drawn, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-stars.html) describes. A selected live star shows the side widget; its drag sets the point count from 3 to 20, and a star of more than 20 points keeps its count until the drag goes up. Star Properties in the Transform panel and the Properties panel's Transform section have a Points field (2 to 1000) with a slider over 3 to 20, and a Ratio field (inner radius over outer radius, 0.001 to 1). The command accepts a ratio above 0 and up to 1. Both send `object.setLiveShape {points, ratio}`, one undo step each, and a value the star already has adds none. Live Corners round a live star's corners and keep them through a new point count. The widget's range below 3 points, the field's lower limit of 2 and the Ratio field are VectorCraft's own (tests `a_live_star_takes_a_new_point_count_and_ratio`, `dragging_a_star_s_widget_down_adds_a_point`, `star_points_and_ratio_fields_edit_a_live_star`). + - **Live stars:** a star drawn with the Star tool or `shape.star` stays a live shape (#4339), so its point count and ratio stay editable after it is drawn, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-stars.html) describes. A selected live star shows the side widget; its drag sets the point count from 3 to 20, and a star of more than 20 points keeps its count until the drag goes up. Star Properties in the Transform panel and the Properties panel's Transform section have a Points field (2 to 1000) with a slider over 3 to 20, and a Ratio field (inner radius over outer radius, 0.001 to 1). The command accepts a ratio above 0 and up to 1. Both send `object.setLiveShape {points, ratio}`, one undo step each, and a value the star already has adds none. Live Corners round a live star's corners and keep them through a new point count. The help page covers the widget and the editable point count; the widget's drag range of 3 to 20, the Points field's range of 2 to 1000 and the Ratio field are VectorCraft's own (tests `a_live_star_takes_a_new_point_count_and_ratio`, `dragging_a_star_s_widget_down_adds_a_point`, `star_points_and_ratio_fields_edit_a_live_star`). - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}` and its release adds one undo step; Escape during the drag puts the count back and adds no undo step. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). From 21408d593d6bd39e7e3b6459778d665d3c340507 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 01:21:22 -0800 Subject: [PATCH 078/103] File formats: a converted DWG keeps its document, wakes the window and stays converted Three faults in reading DWG off the UI thread: - A DWG placed while it was converted went into whichever document was active when the conversion ended. The conversion now records the document it was placed in, which becomes the active one again before the DXF Import Options open; when that document was closed or reverted meanwhile, nothing is placed and the status bar says why, as for other files read for Place. - The idle window did not come back to look for a finished conversion, so its dialog waited for other input. The window now polls while a drawing is converted, as it does while a file is read. - The conversion cache kept only the last drawing, and none over 128 MiB of DXF, so the dialog of an earlier or large drawing converted it again on the UI thread for its previews and its OK. Each dialog now holds its drawing's conversion (`vectorcraft_cad::dwg::hold`) while it is open, and the cache finds held conversions. --- crates/cad/src/dwg.rs | 66 +++++++++- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs/dxf_import.rs | 150 ++++++++++++++++++++--- crates/ui-egui/src/opening.rs | 44 ++++++- 4 files changed, 233 insertions(+), 28 deletions(-) diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index b5d135ef58..bd64dd1149 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -6,7 +6,7 @@ //! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there. use std::hash::BuildHasher; -use std::sync::{Arc, LazyLock, Mutex, PoisonError}; +use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak}; pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; @@ -63,14 +63,16 @@ pub(crate) struct Converted { type Outcome = Result<Arc<Converted>, String>; -/// The outcome of the last drawing converted, by a hash of its bytes and its length. Open reads a -/// drawing's layouts, draws a preview of each in its dialog and then opens it, and each of those -/// reads the same file; a file the conversion refused (or whose worker stopped) is refused again -/// without another conversion. +/// The outcome of the last drawing converted, by a hash of its bytes and its length, and the +/// conversions a [`Held`] keeps. Open reads a drawing's layouts, draws a preview of each in its +/// dialog and then opens it, and each of those reads the same file; a file the conversion refused +/// (or whose worker stopped) is refused again without another conversion. #[derive(Default)] struct Kept { hasher: std::collections::hash_map::RandomState, last: Option<((u64, usize), Outcome)>, + /// The conversions handed out by [`hold`], while a [`Held`] for each exists. + held: Vec<((u64, usize), Weak<Converted>)>, } impl Kept { @@ -79,7 +81,15 @@ impl Kept { } fn get(&self, key: (u64, usize)) -> Option<Outcome> { - self.last.as_ref().filter(|(k, _)| *k == key).map(|(_, outcome)| outcome.clone()) + if let Some((_, outcome)) = self.last.as_ref().filter(|(k, _)| *k == key) { + return Some(outcome.clone()); + } + self.held.iter().filter(|(k, _)| *k == key).find_map(|(_, c)| c.upgrade()).map(Ok) + } + + fn hold(&mut self, key: (u64, usize), converted: &Arc<Converted>) { + self.held.retain(|(_, c)| c.strong_count() > 0); + self.held.push((key, Arc::downgrade(converted))); } fn keep(&mut self, key: (u64, usize), outcome: &Outcome) { @@ -107,6 +117,15 @@ fn through(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Resu outcome } +/// [`through`], and the conversion stays where `kept` finds it while the [`Held`] lasts. +fn hold_in(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Result<Held, String> { + let converted = through(kept, bytes, convert)?; + let mut kept = kept.lock().unwrap_or_else(PoisonError::into_inner); + let key = kept.key(bytes); + kept.hold(key, &converted); + Ok(Held { _converted: converted }) +} + static KEPT: LazyLock<Mutex<Kept>> = LazyLock::new(Mutex::default); /// `bytes` (a DWG drawing) as DXF, within craft-dwg's default limits (512 MiB of DWG, 1 GiB of DXF). @@ -114,6 +133,20 @@ pub(crate) fn to_dxf(bytes: &[u8]) -> Outcome { through(&KEPT, bytes, convert) } +/// A DWG drawing's conversion, kept for every read of the same bytes ([`crate::info`], +/// [`crate::import`]) while this value exists, whatever other drawings are converted meanwhile and +/// however large its DXF is. +#[derive(Debug, Clone)] +pub struct Held { + _converted: Arc<Converted>, +} + +/// Convert `bytes` (a DWG drawing), or take the conversion already kept, and keep it while the +/// returned [`Held`] exists → the conversion's error when it fails. +pub fn hold(bytes: &[u8]) -> Result<Held, String> { + hold_in(&KEPT, bytes, convert) +} + fn convert(bytes: &[u8]) -> Result<Converted, String> { let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?; Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() }) @@ -166,6 +199,27 @@ mod tests { assert_eq!(calls.get(), 2, "a rendition over MAX_KEPT is converted again"); } + #[test] + fn a_held_drawing_is_not_converted_again_until_its_hold_is_dropped() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let big = vec![b' '; MAX_KEPT + 1]; + let one = hold_in(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + let large = hold_in(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 3); + // Another drawing converted since, and a rendition over MAX_KEPT, are still found. + through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap(); + assert_eq!(through(&kept, b"AC1015 big", counting(&calls, b"other")).unwrap().dxf.len(), big.len()); + assert_eq!(calls.get(), 3); + drop((one, large)); + through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + assert_eq!(calls.get(), 5, "a dropped hold no longer keeps its conversion"); + let refused = hold_in(&kept, b"AC1015 bad", |_| Err("DWG: no".to_string())); + assert_eq!(refused.unwrap_err(), "DWG: no"); + } + #[test] fn messages_name_what_vectorcraft_does() { let m = worded("DWG: the file is 9.9 MB, larger than the 1.0 MB accepted by this bridge"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0448534fda..416cc2c6d2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -614,6 +614,7 @@ impl VectorcraftApp { crate::addons::select::link_status::refresh(self, now); if !self.background.jobs.is_empty() || !self.opening.pending.is_empty() + || !self.opening.converting.is_empty() || plugin_runs::any_pending(self) || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 491aaddeea..31b1bc3b8d 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -77,6 +77,9 @@ struct Source { name: String, path: Option<String>, file: Arc<DialogFile>, + /// A DWG drawing's conversion, kept while the dialog is open so that its previews and its OK + /// read the drawing without converting it again. + _held: Option<vectorcraft_cad::dwg::Held>, } /// The DXF Import Options dialog: the layout preview and what the drawing declares on the left, the @@ -332,7 +335,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St return false; } let Ok(info) = vectorcraft_cad::info(bytes) else { return false }; - show(app, name, bytes, path, place, &info) + show(app, name, bytes, path, place, &info, None) } /// [`offer`] for a file the user opens or places where files are read off the UI thread: a DWG @@ -364,9 +367,9 @@ pub fn convert_place_in_background(app: &mut VectorcraftApp, p: &Value) -> bool pub(crate) fn converted(app: &mut VectorcraftApp, name: &str, conversion: crate::opening::Conversion, path: Option<String>, place: Option<&Value>) { let (bytes, info) = conversion; match info { - Ok(info) => { + Ok((info, held)) => { let opens = place.is_none(); - if show(app, name, &bytes, path.clone(), place, &info) + if show(app, name, &bytes, path.clone(), place, &info, Some(held)) && opens && let Some(path) = &path { @@ -378,8 +381,17 @@ pub(crate) fn converted(app: &mut VectorcraftApp, name: &str, conversion: crate: } } -/// Open the dialog for `bytes`, the drawing `info` describes (see [`offer`]). -fn show(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, place: Option<&Value>, info: &vectorcraft_cad::DxfInfo) -> bool { +/// Open the dialog for `bytes`, the drawing `info` describes (see [`offer`]), keeping `held`, its +/// DWG conversion, while it is open. +fn show( + app: &mut VectorcraftApp, + name: &str, + bytes: &[u8], + path: Option<String>, + place: Option<&Value>, + info: &vectorcraft_cad::DxfInfo, + held: Option<vectorcraft_cad::dwg::Held>, +) -> bool { let mut choices = DxfChoices { layout: info.layouts.first().cloned().unwrap_or_else(|| "Model".into()), unit: info.unit, @@ -395,7 +407,7 @@ fn show(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String> } } let file = DialogFile::new(bytes.to_vec()); - let source = Source { place: place.map(|p| other_place_params(p, &["dxf"])), name: name.to_string(), path, file: file.clone() }; + let source = Source { place: place.map(|p| other_place_params(p, &["dxf"])), name: name.to_string(), path, file: file.clone(), _held: held }; let dialog = DxfImportDialog::new(place.is_some(), file, info, choices); open_held(app, dialog, move |app, choices| confirm(app, &source, choices)).is_some() } @@ -688,16 +700,7 @@ mod tests { #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn a_dwg_drawing_is_converted_off_the_ui_thread_before_its_dialog_opens() { - fn converted(app: &mut VectorcraftApp) { - for c in &mut app.opening.converting { - let (tx, done) = std::sync::mpsc::channel(); - if let Ok(r) = c.done.recv() { - let _ = tx.send(r); - } - c.done = done; - } - crate::opening::poll(app); - } + let converted = finish_conversions; vectorcraft_engine::dwg::allow_in_process(); let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap(); let dir = crate::tests_folder::Folder::new("dxf-import-dwg-background"); @@ -738,6 +741,121 @@ mod tests { }); } + /// Waits for the DWG conversions under way to finish, then lets [`crate::opening::poll`] hand + /// them on. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + fn finish_conversions(app: &mut VectorcraftApp) { + for c in &mut app.opening.converting { + let (tx, done) = std::sync::mpsc::channel(); + if let Ok(r) = c.done.recv() { + let _ = tx.send(r); + } + c.done = done; + } + crate::opening::poll(app); + } + + /// `plan.dwg`, the [`drawing`] as a DWG file in a folder of `test`'s own → its path. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + fn dwg_file(test: &str) -> (crate::tests_folder::Folder, String) { + let dwg = craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap(); + let dir = crate::tests_folder::Folder::new(test); + let plan = dir.join("plan.dwg"); + std::fs::write(&plan, &dwg).unwrap(); + let plan = plan.to_string_lossy().into_owned(); + (dir, plan) + } + + /// While a DWG drawing is converted the idle window keeps coming back to look, so its dialog + /// opens when the conversion is done without other input. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn the_idle_window_opens_the_dialog_when_the_conversion_is_done() { + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64) -> std::time::Duration { + app.now_override = Some(time); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + time: Some(time), + ..Default::default() + }; + let out = crate::testing::app_frame(app, ctx, raw); + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) + } + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-idle"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + let ctx = app.ui_ctx.clone().expect("the test app has a window"); + frame(&mut app, &ctx, 0.0); + crate::io::open_file(&mut app, &plan, true).unwrap(); + // The conversion's result is held back, so the drawing is still being converted in the frames below. + let (tx, done) = std::sync::mpsc::channel(); + let result = std::mem::replace(&mut app.opening.converting[0].done, done).recv().unwrap(); + frame(&mut app, &ctx, 1.0); + let wait = frame(&mut app, &ctx, 2.0); + assert!(wait <= std::time::Duration::from_millis(100), "{wait:?}: {:?}", ctx.repaint_causes()); + tx.send(result).unwrap(); + frame(&mut app, &ctx, 2.0 + wait.as_secs_f64()); + assert!(host::is_open(&app, KIND), "the dialog opens in the next frame"); + }); + } + + /// A DWG drawing placed while it is converted goes in the document it was placed in, which + /// becomes the active one again; it is not placed when that document was closed or reverted + /// meanwhile, and the status bar says why. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_placed_while_converted_goes_in_its_own_document() { + fn undo_steps(app: &VectorcraftApp, uid: u64) -> usize { + app.session.documents().iter().find(|st| st.uid == uid).map_or(0, |st| st.history.undo.len()) + } + fn placed(app: &mut VectorcraftApp) { + while !app.placing.pending.is_empty() { + crate::placing::wait(app); + crate::placing::poll(app); + } + } + vectorcraft_engine::dwg::allow_in_process(); + let (dir, plan) = dwg_file("dxf-import-dwg-place-doc"); + let saved = dir.join("saved.vectorcraft").to_string_lossy().into_owned(); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let first = app.session.doc().unwrap().uid; + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let other = app.session.doc().unwrap().uid; + let (before, other_before) = (undo_steps(&app, first), undo_steps(&app, other)); + finish_conversions(&mut app); + assert_eq!(app.session.doc().unwrap().uid, first, "the document it was placed in is active again"); + assert_eq!(host::fields(&app, KIND)["mode"], "place"); + host::confirm(&mut app, KIND).unwrap(); + placed(&mut app); + assert_eq!((undo_steps(&app, first), undo_steps(&app, other)), (before + 1, other_before)); + // Closed meanwhile. + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + app.session.execute("file.close", &json!({})).unwrap(); + let other_before = undo_steps(&app, other); + finish_conversions(&mut app); + assert!(!host::is_open(&app, KIND)); + assert_eq!(app.ui.status, "Couldn't place plan.dwg: the document it was placed in was closed"); + assert_eq!(undo_steps(&app, other), other_before); + // Reverted meanwhile. + app.run("file.saveAs", json!({ "path": saved })).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = undo_steps(&app, other); + finish_conversions(&mut app); + assert!(!host::is_open(&app, KIND)); + assert_eq!(app.ui.status, "Couldn't place plan.dwg: the document it was placed in was reverted"); + assert_eq!(undo_steps(&app, other), reverted); + }); + } + #[test] fn placing_a_drawing_asks_then_places_one_group() { let mut app = host::app(); diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 9ec98750e7..c41f57814b 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -35,9 +35,9 @@ pub struct Pending { pub(crate) started: f64, } -/// What converting a DWG drawing hands back: its bytes, and its layouts and units or why it can't -/// be read. -pub(crate) type Conversion = (Vec<u8>, Result<vectorcraft_cad::DxfInfo, String>); +/// What converting a DWG drawing hands back: its bytes, and its layouts and units with the +/// conversion kept for its dialog's reads, or why it can't be read. +pub(crate) type Conversion = (Vec<u8>, Result<(vectorcraft_cad::DxfInfo, vectorcraft_cad::dwg::Held), String>); /// A DWG drawing being converted to DXF off the UI thread before its import options open /// ([`convert_drawing`]). @@ -50,6 +50,9 @@ pub struct Converting { name: String, /// The `file.place` params when it is being placed, else `None` (it opens). place: Option<Value>, + /// The document it is placed in ([`vectorcraft_engine::DocState::uid`]) and that document's + /// [`vectorcraft_engine::DocState::reverts`] when the conversion started, when it is placed. + placed_in: Option<(u64, u64)>, pub(crate) done: Receiver<Conversion>, /// The automation roots in force where the open or place started. scope: ScopeHandle, @@ -162,8 +165,12 @@ pub(crate) fn finish_answered(app: &mut VectorcraftApp, path: &str, file: ReadFi /// Convert `bytes`, the DWG drawing `name` (at `path`, if read from a file), to DXF and read its /// layouts and units on a job of its own. Its DXF Import Options open once that is done /// ([`poll`], [`crate::dialogs::dxf_import::converted`]), to place it with the `file.place` params -/// `place`, or else to open it. +/// `place` in the document active now, or else to open it. pub(crate) fn convert_drawing(app: &mut VectorcraftApp, name: &str, bytes: Vec<u8>, path: Option<String>, place: Option<Value>) { + let placed_in = match place { + Some(_) => app.session.doc().ok().map(|st| (st.uid, st.reverts)), + None => None, + }; let (tx, done) = channel(); // The automation roots in force here are in force there. let scope = ScopeHandle::capture(); @@ -172,7 +179,13 @@ pub(crate) fn convert_drawing(app: &mut VectorcraftApp, name: &str, bytes: Vec<u "vectorcraft-dwg", Box::new(move || { let info = run - .run(|| vectorcraft_engine::guard::catch_panic(|| vectorcraft_cad::info(&bytes))) + .run(|| { + vectorcraft_engine::guard::catch_panic(|| { + // Held first, so that reading its layouts reuses the one conversion. + let held = vectorcraft_cad::dwg::hold(&bytes)?; + Ok((vectorcraft_cad::info(&bytes)?, held)) + }) + }) .unwrap_or_else(|msg| Err(format!("internal error: {msg} (please report this bug)"))); // The app may have quit meanwhile: nothing to hand it to. let _ = tx.send((bytes, info)); @@ -180,7 +193,7 @@ pub(crate) fn convert_drawing(app: &mut VectorcraftApp, name: &str, bytes: Vec<u ); let label = format!("Converting {}", fileio::file_name(name)); app.status(format!("{label}…")); - app.opening.converting.push(Converting { label, path, name: name.to_string(), place, done, scope }); + app.opening.converting.push(Converting { label, path, name: name.to_string(), place, placed_in, done, scope }); } /// Lists the file being read for `path` and tells the status bar → `{background: true, status}`. @@ -241,6 +254,25 @@ pub fn poll(app: &mut VectorcraftApp) { if app.ui.status == format!("{}…", c.label) { app.ui.status.clear(); } + // A drawing being placed is placed in the document it was placed in, which becomes the + // active one again, as [`crate::placing`] places files read off the UI thread; it is not + // placed when that document was closed or reverted meanwhile. + if let Some((doc, reverts)) = c.placed_in { + let name = fileio::file_name(&c.name); + match app.session.documents().iter().position(|st| st.uid == doc) { + None => { + app.status(format!("Couldn't place {name}: the document it was placed in was closed")); + continue; + } + Some(d) if app.session.documents()[d].reverts != reverts => { + app.status(format!("Couldn't place {name}: the document it was placed in was reverted")); + continue; + } + Some(d) => { + app.session.set_active(d); + } + } + } c.scope.run(|| crate::dialogs::dxf_import::converted(app, &c.name, r, c.path, c.place.as_ref())); if !may_switch(app) { return; From afc4de9b0704cbc0e4c45d0f4379c7043114e50b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 01:41:07 -0800 Subject: [PATCH 079/103] Render: a full-frame render hands its pixels over without a fill and a copy Renderer::render, render_node, render_pattern_swatch and the image of Effect > Rasterize copied the rendered pixmap into a new Vec<u8>. They now take the pixmap's buffer and cast it to bytes in place (group::into_bytes); a buffer the cast cannot take is still copied. The target pixmap with nothing under it is allocated zeroed (group::blank_pixmap) instead of being filled pixel by pixel. At 2880x1800 that removes one 20.7 MB fill and one 20.7 MB copy from every whole-frame render. The pixels are the same bytes. Part of #1172 --- Cargo.lock | 1 + crates/render/Cargo.toml | 2 + crates/render/src/fx/pixels.rs | 8 +- crates/render/src/group.rs | 27 ++++- crates/render/src/pattern.rs | 2 +- crates/render/src/renderer.rs | 4 +- crates/render/src/tests.rs | 1 + crates/render/src/tests/framebuffer.rs | 136 +++++++++++++++++++++++++ 8 files changed, 175 insertions(+), 6 deletions(-) create mode 100644 crates/render/src/tests/framebuffer.rs diff --git a/Cargo.lock b/Cargo.lock index be4b734a08..7fe1eaf302 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9005,6 +9005,7 @@ dependencies = [ name = "vectorcraft-render" version = "0.25.1" dependencies = [ + "bytemuck", "craft-gif", "craft-image-codecs", "craft-psd", diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 9a4c095650..eb47f2a218 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -18,6 +18,8 @@ vectorcraft-brush = { workspace = true } vello_cpu = { workspace = true } # Filter types (Gaussian blur, drop shadow) are not re-exported by vello_cpu 0.2. vello_common = { version = "0.2", default-features = false } +# Hands a rendered pixmap's buffer over as bytes (`group::into_bytes`). +bytemuck = { version = "1", features = ["extern_crate_alloc"] } image = { workspace = true } craft-gif = { workspace = true } craft-image-codecs = { workspace = true } diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index ceead2a01e..673082bfb5 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -570,9 +570,13 @@ impl Renderer { let mut off = frame.offscreen_context(w, h); self.inside_layer(|s| paint(s, &mut off, &frame)); off.flush(); - let mut pm = vello_cpu::Pixmap::new(w, h); + let mut pm = crate::group::blank_pixmap(w, h); off.render(&mut pm, &mut self.resources); - let mut pixels = pm.data_as_u8_slice().to_vec(); + #[cfg(test)] + let rendered = pm.data().as_ptr() as usize; + let mut pixels = crate::group::into_bytes(pm); + #[cfg(test)] + crate::group::RASTERIZE_BUFFERS.with(|b| b.set((rendered, pixels.as_ptr() as usize))); r.finish(&mut pixels); Some((pixels, usize::from(w), usize::from(h))) } diff --git a/crates/render/src/group.rs b/crates/render/src/group.rs index 12490eb308..82f774631c 100644 --- a/crates/render/src/group.rs +++ b/crates/render/src/group.rs @@ -209,13 +209,17 @@ impl Renderer { pub(crate) fn finish(&mut self, ctx: &mut RenderContext, settings: vello_cpu::RasterizerSettings) -> Pixmap { ctx.flush(); let Some(below) = self.picture.take() else { - let mut pm = Pixmap::new(ctx.width(), ctx.height()); + let mut pm = blank_pixmap(ctx.width(), ctx.height()); ctx.render_with(&mut pm, &mut self.resources, settings); + #[cfg(test)] + FINISHED.with(|p| p.set(pm.data().as_ptr() as usize)); return pm; }; let mut pm = Arc::unwrap_or_clone(below); let over = vello_cpu::RasterizerSettings { composite_mode: vello_cpu::CompositeMode::SrcOver, ..settings }; ctx.render_with(&mut pm, &mut self.resources, over); + #[cfg(test)] + FINISHED.with(|p| p.set(pm.data().as_ptr() as usize)); pm } @@ -345,10 +349,31 @@ pub(crate) fn draw_pixmap(ctx: &mut RenderContext, pm: Arc<Pixmap>, at: (f64, f6 ctx.set_transform(Affine::IDENTITY); } +/// A transparent `w`×`h` pixmap in zeroed memory, which the allocator can hand out without +/// writing every byte as [`Pixmap::new`] does. +pub(crate) fn blank_pixmap(w: u16, h: u16) -> Pixmap { + Pixmap::from_parts(bytemuck::zeroed_vec(usize::from(w) * usize::from(h)), w, h) +} + +/// `pm`'s premultiplied RGBA pixels as bytes, in the buffer `pm` held. +pub(crate) fn into_bytes(pm: Pixmap) -> Vec<u8> { + bytes_of(pm.take()) +} + +/// `pixels` as bytes: the same allocation when `T` is aligned like a byte, else a copy. +pub(crate) fn bytes_of<T: bytemuck::Pod>(pixels: Vec<T>) -> Vec<u8> { + bytemuck::allocation::try_cast_vec(pixels).unwrap_or_else(|(_, v)| bytemuck::cast_slice(&v).to_vec()) +} + #[cfg(test)] thread_local! { /// The pixels [`draw_pixmap`] has drawn on this thread. pub(crate) static PIXELS_DRAWN: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; + /// The address of the pixel buffer [`Renderer::finish`] last returned on this thread. + pub(crate) static FINISHED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + /// The addresses of the pixmap the last Effect › Rasterize image on this thread was rendered + /// into and of the bytes it was returned in. + pub(crate) static RASTERIZE_BUFFERS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; } /// The offscreen pixels that groups drawn offscreen may keep alive at once, in frames: deeper diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 5f4b5d71df..9e44f5c655 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -339,7 +339,7 @@ pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option<Re let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side)); let px = size.clamp(1, 1024) as u16; let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, (px, px), Ink::Display, false))?; - Some(Rendered { width: px as u32, height: px as u32, pixels: pm.data_as_u8_slice().to_vec() }) + Some(Rendered { width: px as u32, height: px as u32, pixels: crate::group::into_bytes(pm) }) } impl Renderer { diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index fdf7847412..9eb6082e37 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -377,7 +377,7 @@ impl Renderer { self.contexts.remove(0); } let Some(pm) = pm else { return Vec::new() }; - let mut pixels = pm.data_as_u8_slice().to_vec(); + let mut pixels = group::into_bytes(pm); if let Some(bg) = opts.background { over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg))); } @@ -504,7 +504,7 @@ impl Renderer { let pm = self.finish(&mut ctx, self.raster); self.end_frame(); self.raster = raster; - pm.data_as_u8_slice().to_vec() + group::into_bytes(pm) } /// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 9ee678965c..133e2356aa 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -18,6 +18,7 @@ mod container; mod curvedstrokeedges; mod dither; pub(super) mod fontchange; +mod framebuffer; mod freeform; mod fxzoom; mod isolation; diff --git a/crates/render/src/tests/framebuffer.rs b/crates/render/src/tests/framebuffer.rs new file mode 100644 index 0000000000..5931449617 --- /dev/null +++ b/crates/render/src/tests/framebuffer.rs @@ -0,0 +1,136 @@ +//! The pixels a render returns are the buffer it rendered into, handed over without a copy: a +//! page, a node, a pattern swatch and the image of Effect › Rasterize. + +use std::cell::Cell; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::pattern::pattern_paint; +use vectorcraft_doc::{Appearance, Effect, Node, PatternDef}; +use vectorcraft_geom::shapes; + +use crate::group::{FINISHED, RASTERIZE_BUFFERS, blank_pixmap, bytes_of, into_bytes}; +use crate::*; + +/// A red square over 10..30 pt with the effects `fx` (id, params). +fn red_square(fx: &[(&str, serde_json::Value)]) -> Document { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + n.appearance.effects = fx.iter().map(|(id, params)| Effect { id: (*id).into(), params: params.clone(), visible: true }).collect(); + d.insert(Some(l), 0, n).unwrap(); + d +} + +fn finished() -> usize { + FINISHED.with(Cell::get) +} + +/// A pixmap with the red square drawn into it, over transparency. +fn drawn(w: u16, h: u16) -> Pixmap { + let mut ctx = crate::threads::single_threaded_context(w, h); + ctx.set_paint(peniko::Color::from_rgba8(255, 0, 0, 255)); + ctx.fill_rect(&Rect::new(10.0, 10.0, 30.0, 30.0)); + ctx.flush(); + let mut pm = Pixmap::new(w, h); + ctx.render(&mut pm, &mut Resources::new()); + pm +} + +#[test] +fn a_pixmap_is_handed_over_in_its_own_buffer_with_the_same_bytes() { + let pm = drawn(40, 30); + let (bytes, at) = (pm.data_as_u8_slice().to_vec(), pm.data().as_ptr() as usize); + let out = into_bytes(pm); + assert_eq!(out.as_ptr() as usize, at, "the buffer is handed over, not copied"); + assert!(out == bytes, "the same bytes"); + assert_eq!(&out[(20 * 40 + 20) * 4..][..4], &[255, 0, 0, 255]); +} + +#[test] +fn pixels_aligned_wider_than_a_byte_are_copied_with_the_same_bytes() { + let words: Vec<u32> = (0..1000u32).map(|i| i.wrapping_mul(0x9e37_79b9)).collect(); + let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_ne_bytes()).collect(); + let out = bytes_of(words); + assert!(out == bytes, "a buffer the cast cannot take is copied byte for byte"); + assert!(bytes_of(Vec::<u32>::new()).is_empty()); + assert!(bytes_of(Vec::<vello_cpu::color::PremulRgba8>::new()).is_empty()); +} + +#[test] +fn a_blank_pixmap_is_transparent_and_renders_as_a_new_one_does() { + for (w, h) in [(1, 1), (40, 30), (257, 3)] { + let blank = blank_pixmap(w, h); + assert_eq!((blank.width(), blank.height()), (w, h)); + assert!(blank.data_as_u8_slice() == Pixmap::new(w, h).data_as_u8_slice()); + } + let mut ctx = crate::threads::single_threaded_context(40, 30); + ctx.set_paint(peniko::Color::from_rgba8(0, 0, 255, 128)); + ctx.fill_rect(&Rect::new(5.0, 5.0, 25.0, 15.0)); + ctx.flush(); + let mut on_blank = blank_pixmap(40, 30); + ctx.render(&mut on_blank, &mut Resources::new()); + assert!(on_blank.data_as_u8_slice() == drawn_with(&ctx).data_as_u8_slice()); +} + +/// What `ctx` renders into a new pixmap of its size. +fn drawn_with(ctx: &RenderContext) -> Pixmap { + let mut pm = Pixmap::new(ctx.width(), ctx.height()); + ctx.render(&mut pm, &mut Resources::new()); + pm +} + +#[test] +fn a_page_render_returns_the_buffer_it_rendered_into() { + let d = red_square(&[]); + let mut r = Renderer::new(); + for background in [None, Some([255, 255, 255, 255])] { + let opts = RenderOptions { background, ..Default::default() }; + let out = r.render(&d, 64, 48, Affine::IDENTITY, &opts); + assert_eq!(out.pixels.len(), 64 * 48 * 4); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "background {background:?}: the page's pixels are returned without a copy"); + } +} + +#[test] +fn a_node_render_returns_the_buffer_it_rendered_into() { + let d = red_square(&[]); + let n = d.layers[0].children().unwrap()[0].clone(); + let out = Renderer::new().render_node(&d, &n, 40, 40, Affine::IDENTITY).unwrap(); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "the node's pixels are returned without a copy"); + assert_eq!(&out.pixels[(20 * 40 + 20) * 4..][..4], &[255, 0, 0, 255]); +} + +#[test] +fn a_pattern_swatch_returns_the_buffer_it_rendered_into() { + let mut d = Document::new(100.0, 100.0); + let red = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + let mut def = PatternDef::new("Checks", vec![Arc::new(red)]); + def.tile = Rect::new(0.0, 0.0, 20.0, 20.0); + d.patterns.push(def); + let l = d.layers[0].id; + let filled = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::basic(pattern_paint("Checks"), Paint::None, 0.0)); + d.insert(Some(l), 0, filled).unwrap(); + let out = render_pattern_swatch(&d, "Checks", 20).unwrap(); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "the swatch's pixels are returned without a copy"); +} + +#[test] +fn the_rasterize_effect_keeps_the_buffer_it_rendered_its_image_into() { + RASTERIZE_BUFFERS.with(|b| b.set((0, 0))); + let d = red_square(&[("rasterize", json!({}))]); + let opts = RenderOptions { background: None, artboards: false, ..Default::default() }; + Renderer::new().render(&d, 100, 100, Affine::scale(2.0), &opts); + let (rendered, bytes) = RASTERIZE_BUFFERS.with(Cell::get); + assert_ne!(rendered, 0, "the effect made its image"); + assert_eq!(bytes, rendered, "the image's pixels are taken from its pixmap without a copy"); +} From 5f345e4a398bc5243d981ede48eb40e5cc206604 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 02:01:41 -0800 Subject: [PATCH 080/103] 3D: a canceled drag clears the fallback warning its preview showed Canceling a 3D and Materials drag, or dragging back to where it began, rolled the preview back but left its rendered fallback warning in the status bar, describing settings the document no longer had. The rollback now clears that warning while the status line still holds it and shows the restored selection's own warning instead. A warning shown before the drag began, or a newer status message, is kept. docs/three-d.md now scopes the painter's algorithm note to shaded vector faces; a Rendered image is drawn with a depth buffer. --- crates/ui-egui/src/panels/tests_three_d.rs | 58 ++++++++++++++++++++++ crates/ui-egui/src/panels/three_d.rs | 22 +++++++- docs/three-d.md | 5 +- 3 files changed, 81 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index f0a8626eb2..145c210b72 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1704,6 +1704,64 @@ fn a_live_edit_without_a_warning_clears_the_earlier_one() { assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); } +/// A drag whose preview falls back to shaded faces and is then canceled, or dragged back to where it +/// began, clears the fallback warning, since the restored settings render; a newer status line stays. +#[test] +fn a_canceled_drag_clears_the_fallback_warning_its_preview_showed() { + let fresh = || { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 500, "height": 500})).unwrap(); + let render = json!({"mode": "rendered", "quality": "low", "resolution": 300}); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"depth": 50, "render": render}})).unwrap(); + app.ui.status.clear(); + app + }; + let too_large = vectorcraft_effects::rendered::TOO_LARGE; + for back in [false, true] { + let mut app = fresh(); + let before = begin(&mut app, GESTURE); + update(&mut app, GESTURE, &[("depth", json!(2000.0))]); + assert_eq!(app.ui.status, too_large); + if back { + update(&mut app, GESTURE, &[("depth", json!(50.0))]); + } else { + pass(&mut app, &before, EditEvent::cancel(GESTURE, CancelReason::Escape, None)); + } + assert_eq!(effect(&app).1["depth"], 50.0); + assert_eq!(app.ui.status, "", "dragged back: {back}"); + } + let mut app = fresh(); + let before = begin(&mut app, GESTURE); + update(&mut app, GESTURE, &[("depth", json!(2000.0))]); + app.status("Something else"); + pass(&mut app, &before, EditEvent::cancel(GESTURE, CancelReason::Escape, None)); + assert_eq!(app.ui.status, "Something else"); + + // A warning an earlier edit of other objects showed stays when a drag that showed none is canceled. + let mut app = fresh(); + let square = app.session.active().unwrap().selection.objects[0].0; + let a = app.run("shape.rectangle", json!({"x": 600, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 750, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run( + "paint.setFill", + json!({"gradient": {"kind": "linear", "stops": [ + {"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"} + ]}}), + ) + .unwrap(); + set_type(&mut app, "extrude").unwrap(); + super::set_render(&mut app, "rendered", Some("low")); + app.ui.status.clear(); + send(&mut app, Map::from_iter([("depth".into(), json!(40))]), Live::Released); + assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); + app.run("select.set", json!({"ids": [square]})).unwrap(); + let before = begin(&mut app, GESTURE); + update(&mut app, GESTURE, &[("depth", json!(60.0))]); + pass(&mut app, &before, EditEvent::cancel(GESTURE, CancelReason::Escape, None)); + assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY); +} + /// Raster Settings OK shows why a rendered image falls back to shaded faces at a higher resolution. #[test] fn raster_settings_rendered_warning_reaches_the_status_bar() { diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index 56847a4639..fe8e629be2 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -67,6 +67,8 @@ pub(crate) struct Model { graphic: usize, /// The settings as they were when the gesture began. before: Value, + /// [`crate::state::UiState::status_sets`] when the gesture began: a live warning shown after it is the gesture's own. + began_sets: u64, } /// The selection's 3D effect: the appearance item whose effects hold it (`None`: the object's @@ -159,10 +161,25 @@ fn rollback(app: &mut VectorcraftApp) { m.before = Value::Null; if previewed { app.session.cancel_interaction().ok(); - app.sync_views(); + restored(app); } } +/// After a preview was rolled back: clears the warning the gesture's preview put in the status bar +/// while the status line still holds it, shows the restored selection's own rendered warning, and +/// redraws. A warning shown before the gesture began is kept. +fn restored(app: &mut VectorcraftApp) { + if let Some((cmd, sets, text)) = app.ui.live_warning.take() { + if sets <= app.three_d.began_sets { + app.ui.live_warning = Some((cmd, sets, text)); + } else if app.ui.status_sets == sets && app.ui.status == text { + app.ui.status.clear(); + show_rendered_warning(app); + } + } + app.sync_views(); +} + /// What a change goes to, taken when it starts (before any preview): the selected objects' ids, /// and each selected object with a 3D effect, the effect, and whether its list of lights matches /// the first one's (a light list edited in the panel replaces only those). @@ -282,6 +299,7 @@ pub(crate) fn apply(app: &mut VectorcraftApp, params: &[Param], input: &DialogFi // A gesture still running (its selection changed under it) ends with what it previewed. finish(app); app.three_d.gesture = Some(*id); + app.three_d.began_sets = app.ui.status_sets; app.three_d.before = settings(input); app.three_d.plan = Some(plan(app)); } @@ -292,7 +310,7 @@ pub(crate) fn apply(app: &mut VectorcraftApp, params: &[Param], input: &DialogFi // gesture goes on. app.three_d.pending.clear(); app.session.cancel_interaction().ok(); - app.sync_views(); + restored(app); } else { let changed = returned(app, changed); send(app, changed, Live::Dragging); diff --git a/docs/three-d.md b/docs/three-d.md index 9a97fc6258..d45a826edc 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -798,8 +798,9 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. Inflate's puffed front and back only ([Graphics](#graphics)). - The bevel shapes and their names are our own. Custom bevels come from VectorCraft's own bevels file ([Custom bevels](#custom-bevels)) and are cut into straight lines. -- Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn - back to front, with a flat cap or flat back turned toward the viewer drawn after all of them. Concave solids +- Shaded vector faces are drawn with a painter's algorithm. This covers Rendered too when it falls back to shaded + faces; a Rendered image is drawn with a depth buffer. Faces of a closed solid turned away are left out, and the + rest are drawn back to front, with a flat cap or flat back turned toward the viewer drawn after all of them. Concave solids seen at steep angles can overlap wrongly; open (hollow) solids show both sides. Twisted walls and bevels are drawn in pieces about as long as a wall slice is wide (fewer near the limit of 32,768 facets). The piece drawn on top can still lie a few points behind another nearby piece. From 57efe8105ec080f26e70fb71244586abd184ff93 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 01:54:15 -0800 Subject: [PATCH 081/103] Curvature comb: the line through the tips breaks where a straight segment turns back A straight segment cleared the direction the comb carries from segment to segment, so a curve that ended heading one way and a line that went back the other way, or a line followed by a curve that turned back on it, kept one line through the tips across the cusp. A straight segment now carries its chord's direction, and the comb starts a new line wherever the next direction heads back against the last one. The test for turning back now ignores a dot product that rounds a little below zero at a right angle, at interior anchors and at the closed-path seam alike. --- crates/geom/src/curvature.rs | 74 ++++++++++++++++++++++++++++++++++-- docs/mcp.md | 3 +- 2 files changed, 72 insertions(+), 5 deletions(-) diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index ac6f721b85..c95e9edf45 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -236,6 +236,16 @@ pub struct CombTooth { /// The most teeth a curvature comb draws in all. pub const MAX_COMB_TEETH: usize = 20_000; +/// Does the direction `next` head back against the direction `previous`? A right angle +/// whose dot product rounds a little below zero does not count. +fn turns_back(previous: Vec2, next: Vec2) -> bool { + let unit = |v: Vec2| { + let v = v / v.x.abs().max(v.y.abs()); + v / v.hypot() + }; + unit(previous).dot(unit(next)) < -1e-9 +} + /// The curvature comb of `sp`: `samples` teeth on each segment (at least 2), evenly spaced in `t` /// from 0 to 1, each `scale` times the signed curvature long ([`CombTooth`]). A straight segment /// gives teeth of no length, its ends included. A point of a curved segment where it has no @@ -243,6 +253,8 @@ pub const MAX_COMB_TEETH: usize = 20_000; /// with no length, a segment whose points are not finite, or a `scale` that is not finite. When /// `samples` teeth on every segment would pass `max_teeth`, every segment gets 2 teeth, and when /// that would still pass it, only every k-th segment gets teeth, spread along the whole subpath. +/// The line through the tips starts again wherever the path turns back on itself, at a straight +/// segment as at a curve. pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize) -> Vec<CombTooth> { let n = sp.segment_count(); if n == 0 || !scale.is_finite() || max_teeth < 2 { @@ -279,8 +291,10 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize if line { // A line stored with its handles on its anchors has no speed at its ends, but a // direction and no curvature all along. + // A line that turns back on the segment before it is a cusp at their anchor. let at = c.eval(t); - previous_direction = None; + start |= previous_direction.is_some_and(|previous| turns_back(previous, chord)); + previous_direction = Some(chord); if !at.is_finite() { start = true; continue; @@ -298,7 +312,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize } let k = v.cross(a) / (speed * speed * speed); let direction = v / speed; - start |= previous_direction.is_some_and(|previous| previous.dot(direction) < 0.0); + start |= previous_direction.is_some_and(|previous| turns_back(previous, direction)); previous_direction = Some(direction); let normal = Vec2::new(-direction.y, direction.x); let at = c.eval(t); @@ -333,8 +347,13 @@ pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { if !(last.segment + 1..n).chain(0..first.segment).all(no_length) { return false; } - match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) { - (Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0, + match ((0..n).rev().find(|&i| !no_length(i)), (0..n).find(|&i| !no_length(i))) { + (Some(into), Some(out)) => { + let (a, b) = (sp.segment(into), sp.segment(out)); + let a = if sp.segment_is_line(into) { a.p3 - a.p0 } else { end_direction(a) }; + let b = if sp.segment_is_line(out) { b.p3 - b.p0 } else { start_direction(b) }; + !turns_back(a, b) + } _ => false, } } @@ -415,6 +434,22 @@ mod tests { assert!(!comb_closes(&sp, &teeth), "an open subpath does not close"); } + /// A curve that ends heading down, a straight segment back up from its end, and a curve that + /// starts heading down again: both anchors are cusps, so the line through the tips starts again + /// at each of them. + #[test] + fn the_comb_breaks_where_a_straight_segment_turns_back() { + let a0 = Anchor { h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_out: Point::new(100.0, -50.0), ..Anchor::corner(Point::new(100.0, -100.0)) }; + let a3 = Anchor { h_in: Point::new(200.0, -50.0), ..Anchor::corner(Point::new(200.0, -100.0)) }; + let sp = SubPath::new(vec![a0, a1, a2, a3], false); + assert!(sp.segment_is_line(1)); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 9); + assert_eq!(teeth.iter().map(|t| t.start).collect::<Vec<_>>(), [true, false, false, true, false, false, true, false, false]); + } + /// A closed comb closes at its first anchor when the curve goes on smoothly there, even with a /// cusp elsewhere, and stays open when the first anchor is the cusp. #[test] @@ -436,6 +471,37 @@ mod tests { assert!(comb_closes(sp, &curvature_comb(sp, 5, 1000.0, MAX_COMB_TEETH))); } + /// A straight segment uses its chord at the seam even when a tiny handle points the other way. + #[test] + fn the_comb_stays_open_where_a_straight_segment_turns_back_at_the_seam() { + let a0 = Anchor { h_in: Point::new(-1e-12, 0.0), h_out: Point::new(50.0, 0.0), ..Anchor::corner(Point::ORIGIN) }; + let a1 = Anchor { h_in: Point::new(100.0, 50.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let mut sp = SubPath::new(vec![a0, a1], true); + for line in [1, 0] { + assert!(sp.segment_is_line(line)); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + assert!(teeth[0].at.distance(teeth[5].at) < 1e-9, "the teeth meet at the seam"); + assert!(!comb_closes(&sp, &teeth), "the chord reverses direction at the seam: {line}"); + sp.reverse(); + sp.anchors.rotate_right(1); + } + } + + /// Large finite line directions still break the comb at a reversal inside the path and at its seam. + #[test] + fn the_comb_breaks_where_large_straight_segments_turn_back() { + let sp = SubPath::polyline(&[Point::ORIGIN, Point::new(1e155, 0.0), Point::ORIGIN], false); + let teeth = curvature_comb(&sp, 2, 1.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::<Vec<_>>(), [true, false, true, false]); + let closed = SubPath::polyline(&[Point::ORIGIN, Point::new(1e155, 0.0)], true); + let teeth = curvature_comb(&closed, 2, 1.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4); + assert!(!comb_closes(&closed, &teeth), "the closing chord reverses direction at the first anchor"); + } + /// A segment with no length and a handle drawn back onto its anchor do not panic and give no /// tooth where the curve has no direction; a scale that is not finite gives no comb. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 85e35043df..4f22af5274 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9639,7 +9639,8 @@ origin), when `t` is not from 0 to 1, when `id` is a guide, and when the path, s `view.curvatureComb` (View › Show Curvature Comb, or Hide Curvature Comb while it is on) turns on the curvature comb of the selected paths, and of each path in a selected compound path, while edges show. Each segment gets 16 evenly spaced teeth along the normal, on the outer side of the bend, each as long as the curvature at that point, and a line -joins the teeth's tips, in the path's layer color. A straight segment has teeth of no length, and a point of a curve +joins the teeth's tips, in the path's layer color. The line starts again where the path turns back on itself at a +cusp, a straight segment included. A straight segment has teeth of no length, and a point of a curve where it has no direction (a handle on its anchor) has no tooth. The length is VectorCraft's own value: a bend with a radius of 100 screen points draws 20-point teeth at any zoom. The comb draws about 20,000 teeth at most, shared among the selected paths by their number of segments: a larger selection gets 2 teeth per segment, then teeth on every k-th From 176ce701b6a095922010536f55dcc50ec6d099ec Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 02:11:10 -0800 Subject: [PATCH 082/103] =?UTF-8?q?Panels:=20File=20=E2=80=BA=20Revert,=20?= =?UTF-8?q?Undo=20and=20Redo=20drop=20an=20unfinished=20selection=20field?= =?UTF-8?q?=20value?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The edit target of the selection fields (`selection_target`) named the document, the selected objects and the symbol part. File › Revert and Undo or Redo replace the document's content, after which the same node id can name another object, and the target did not change: a value typed and not yet committed into Opacity (Transparency panel, Control bar, Properties) or into Image Trace's Divider and settings sliders stayed, and Enter applied it to the reverted or restored document when the same id was selected again. The target now also holds the document's revert and history restore counts. It lists the selected objects in id order, so the same objects selected in another order keep the value. The Opacity target of the Transparency panel and the Control bar names the first selected object with the active Appearance row, whose stack holds that row. --- crates/ui-egui/src/chrome/tests.rs | 30 ++++++ crates/ui-egui/src/panels.rs | 26 ++++-- .../ui-egui/src/panels/image_trace/tests.rs | 54 +++++++++++ crates/ui-egui/src/panels/properties/tests.rs | 28 ++++++ crates/ui-egui/src/panels/transparency.rs | 93 +++++++++++++++++++ 5 files changed, 221 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index fb3032d235..aeafbc9936 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -3194,6 +3194,36 @@ fn the_control_bar_opacity_drops_an_unfinished_value_when_the_selection_changes( assert_eq!((opacity(&bar, &a), opacity(&bar, &b)), (0.5, 0.01), "the typing gives the other object 1%, not 20+1"); } +/// File › Revert drops an unfinished Opacity expression in the Control bar, though the reverted document has the same +/// object, with the same opacity, selected again before the next frame. +#[test] +fn the_control_bar_opacity_drops_an_unfinished_value_on_file_revert() { + use egui::{Key, Modifiers}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 20, "y": 50, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("transparency.set", json!({"ids": [a], "opacity": 50})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("control-bar-opacity-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Opacity.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the rectangle as saved. + app.run("shape.rectangle", json!({"x": 200, "y": 50, "width": 40, "height": 40})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar); + bar.room(egui::vec2(2400.0, 300.0)).frame(); + bar.click_role("Opacity:", Role::SPIN_BUTTON); + bar.key(Key::A, Modifiers::COMMAND); + bar.type_text("20+"); + bar.app().run("file.revert", json!({"confirmed": true})).unwrap(); + bar.app().run("select.set", json!({"ids": [a]})).unwrap(); + bar.type_text("1"); + bar.key(Key::Enter, Modifiers::NONE); + let opacity = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a.as_u64().unwrap())).unwrap().opacity; + assert_eq!(opacity, 0.01, "Revert drops the unfinished value: 1%, not 20+1"); +} + /// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard /// controls while it has room, and the Distribute buttons for two or more selected artboards with /// Align to Artboard and three or more with Align to Selection. A diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index dcdae93c30..ca610d9067 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -767,27 +767,33 @@ pub(crate) fn current_transparency(app: &VectorcraftApp) -> Option<(f32, BlendMo Some(picked.unwrap_or((n.opacity, n.blend))) } -/// The objects a selection field edits, as a field's edit target: the document, the selected objects (or the -/// object targeted in the Layers panel) and the selected symbol part. A field with an unfinished value drops it when -/// these change. -pub(crate) type SelectionTarget = (Option<u64>, Vec<NodeId>, Option<(NodeId, Vec<u32>)>); +/// The objects a selection field edits, as a field's edit target: the document with how many times File › Revert and +/// Undo or Redo replaced its content (after which a node id can name another object), the selected objects (or the +/// object targeted in the Layers panel) in id order, and the selected symbol part. A field with an unfinished value +/// drops it when these change, and keeps it when the same objects are selected in another order. +pub(crate) type SelectionTarget = (Option<(u64, u64, u64)>, Vec<NodeId>, Option<(NodeId, Vec<u32>)>); /// The [`SelectionTarget`] of the active document. pub(crate) fn selection_target(app: &VectorcraftApp) -> SelectionTarget { let Some(st) = app.session.active() else { return (None, vec![], None) }; let part = st.selection.symbol_part.as_ref().map(|p| (p.instance, p.path.clone())); - (Some(st.uid), st.selection.subjects().to_vec(), part) + let mut subjects = st.selection.subjects().to_vec(); + subjects.sort_unstable(); + (Some((st.uid, st.reverts, st.history_restores)), subjects, part) } /// What the Transparency panel's and the Control bar's Opacity fields edit, as their edit target: the -/// [`SelectionTarget`], the masked object while its mask is edited, the Appearance panel's active item and the picked -/// gradient mesh points (see [`current_transparency`]). -pub(crate) type TransparencyTarget = (SelectionTarget, Option<NodeId>, Option<usize>, Option<Vec<(NodeId, Vec<usize>)>>); +/// [`SelectionTarget`], the masked object while its mask is edited, the Appearance panel's active item with the first +/// selected object, whose stack holds it, and the picked gradient mesh points (see [`current_transparency`]). +pub(crate) type TransparencyTarget = (SelectionTarget, Option<NodeId>, Option<(NodeId, usize)>, Option<Vec<(NodeId, Vec<usize>)>>); /// The [`TransparencyTarget`] of the active document. pub(crate) fn transparency_target(app: &VectorcraftApp) -> TransparencyTarget { - let masked = app.session.active().and_then(|st| st.doc.mask_edit.as_ref()).map(|m| m.object); - (selection_target(app), masked, app.session.appearance_item(), app.session.mesh_points_picked()) + let st = app.session.active(); + let masked = st.and_then(|st| st.doc.mask_edit.as_ref()).map(|m| m.object); + let first = st.and_then(|st| st.selection.subjects().first().copied()); + let item = app.session.appearance_item().zip(first).map(|(index, object)| (object, index)); + (selection_target(app), masked, item, app.session.mesh_points_picked()) } /// Is the active proxy "?" (the selected objects' paints differ)? diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index c97e3e1c27..c01b51b2e4 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -657,6 +657,60 @@ fn an_unfinished_divider_value_is_dropped_when_another_object_is_selected() { assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "A keeps its divider"); } +/// Saves the traced object of `app` to a file in `dir`, makes an unsaved change for File › Revert to undo, and selects +/// the traced object again. +fn saved_trace(app: &mut VectorcraftApp, dir: &vectorcraft_testkit::TempDir) -> NodeId { + let id = first_selected(app).unwrap().id; + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Trace.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 60, "y": 60, "width": 10, "height": 10})).unwrap(); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + id +} + +/// File › Revert drops a value typed into the Divider and not finished, though the reverted document has the same +/// Image Trace object, with the same divider, selected again before the next frame: Enter afterwards leaves the +/// divider as saved. +#[test] +fn an_unfinished_divider_value_is_dropped_by_file_revert() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + app.run("imageTrace.setView", json!({"view": "split", "split": 0.4})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("trace-divider-revert"); + let id = saved_trace(&mut app, &dir); + let mut panel = panel_over(app); + panel.frame(); + type_unfinished(&mut panel, "Divider", "8"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({"ids": [id.0]})).unwrap(); + let steps = undo(&panel.app()); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "the divider stays as saved"); + assert_eq!(undo(&panel.app()), steps, "no undo step"); +} + +/// File › Revert drops a value typed into a settings slider and not finished, though the reverted document has the +/// same Image Trace object, with the same settings, selected again before the next frame: Enter afterwards leaves +/// the setting as saved. +#[test] +fn an_unfinished_slider_value_is_dropped_by_file_revert() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + let dir = vectorcraft_testkit::TempDir::new("trace-slider-revert"); + let id = saved_trace(&mut app, &dir); + let mut panel = panel_over(app); + panel.frame(); + let threshold = param(&panel.app(), "threshold"); + type_unfinished(&mut panel, "Threshold", "3"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({"ids": [id.0]})).unwrap(); + let steps = undo(&panel.app()); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(param(&panel.app(), "threshold"), threshold, "the threshold stays as saved"); + assert_eq!(undo(&panel.app()), steps, "nothing was traced"); +} + /// Properties shows the Divider slider of the selected Image Trace object in the Split view only, /// with its name and value for screen readers. #[test] diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index cf45300b76..090cac0b4d 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1027,6 +1027,34 @@ fn unfinished_opacity_does_not_reach_the_next_selected_object() { assert_eq!((opacity(&panel, &a), opacity(&panel, &b)), (0.5, 0.01), "the typing gives the new object 1%, not 20+1"); } +/// File › Revert drops an unfinished Opacity expression, though the reverted document has the same object, with the +/// same opacity, selected again before the next frame. +#[test] +fn unfinished_opacity_is_dropped_by_file_revert() { + use craft::ui::contract::Role; + let mut app = new_app(); + let a = rect(&mut app, 20.0, 20.0, 40.0, 40.0); + app.run("transparency.set", json!({"ids": [a], "opacity": 50})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("properties-opacity-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Opacity.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the rectangle as saved. + rect(&mut app, 200.0, 20.0, 40.0, 40.0); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(400.0, 2400.0)).frame(); + panel.click_role("Opacity", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("20+"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({"ids": [a]})).unwrap(); + panel.type_text("1"); + panel.key(Key::Enter, Modifiers::NONE); + let opacity = panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a.as_u64().unwrap())).unwrap().opacity; + assert_eq!(opacity, 0.01, "Revert drops the unfinished value: 1%, not 20+1"); +} + fn undo_depth(app: &VectorcraftApp) -> usize { app.session.doc().unwrap().history.undo.len() } diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 565f56da75..05f1c4b940 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -686,6 +686,99 @@ mod tests { assert_eq!(shown(&panel).as_deref(), Some("100%"), "the field shows the other part's value"); } + /// Types `20+` into the panel's Opacity field without committing it. + fn unfinished_opacity(panel: &mut Panel) { + use egui::{Key, Modifiers}; + panel.click_role("Opacity", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("20+"); + } + + /// Types `1` and Enter into the panel's focused Opacity field. + fn finish_opacity(panel: &mut Panel) { + panel.type_text("1"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + } + + /// The opacity of object `id` in the active document. + fn opacity_of(panel: &Panel, id: &Value) -> f32 { + panel.app().session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().opacity + } + + /// File › Revert drops an unfinished Opacity expression, though the reverted document has the same object, + /// with the same opacity, selected again before the next frame. + #[test] + fn unfinished_opacity_is_dropped_by_file_revert() { + let mut app = new_app(); + let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}))["id"].clone(); + run_cmd(&mut app, "transparency.set", json!({"ids": [a], "opacity": 50})); + let dir = vectorcraft_testkit::TempDir::new("opacity-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Opacity.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the rectangle as saved. + run_cmd(&mut app, "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30})); + run_cmd(&mut app, "select.set", json!({"ids": [a]})); + let mut panel = Panel::new(app, show); + unfinished_opacity(&mut panel); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + run_cmd(&mut panel.app(), "select.set", json!({"ids": [a]})); + finish_opacity(&mut panel); + assert_eq!(opacity_of(&panel, &a), 0.01, "Revert drops the unfinished value: 1%, not 20+1"); + } + + /// Undo drops an unfinished Opacity expression, though the object it takes away and the object made and selected + /// after it have the same id and opacity. + #[test] + fn unfinished_opacity_is_dropped_by_undo() { + let mut app = new_app(); + let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}))["id"].clone(); + run_cmd(&mut app, "select.set", json!({"ids": [a]})); + let mut panel = Panel::new(app, show); + unfinished_opacity(&mut panel); + run_cmd(&mut panel.app(), "edit.undo", json!({})); + let b = run_cmd(&mut panel.app(), "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].clone(); + assert_eq!(b, a, "the new rectangle has the undone rectangle's id"); + run_cmd(&mut panel.app(), "select.set", json!({"ids": [b]})); + finish_opacity(&mut panel); + assert_eq!(opacity_of(&panel, &b), 0.01, "Undo drops the unfinished value: 1%, not 20+1"); + } + + /// The same objects selected in another order keep an unfinished Opacity expression. + #[test] + fn unfinished_opacity_stays_when_the_same_objects_are_selected_in_another_order() { + let mut app = new_app(); + let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}))["id"].clone(); + let b = run_cmd(&mut app, "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].clone(); + run_cmd(&mut app, "select.set", json!({"ids": [a, b]})); + let mut panel = Panel::new(app, show); + unfinished_opacity(&mut panel); + run_cmd(&mut panel.app(), "select.set", json!({"ids": [b, a]})); + panel.frame(); + finish_opacity(&mut panel); + assert_eq!((opacity_of(&panel, &a), opacity_of(&panel, &b)), (0.21, 0.21), "both objects take 20+1"); + } + + /// An active Appearance row is a row of the first selected object's stack: the same objects selected in another + /// order, with the same row index active again, drop an unfinished Opacity expression typed for the first one's row. + #[test] + fn unfinished_row_opacity_is_dropped_when_another_object_comes_first() { + let mut app = new_app(); + let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}))["id"].clone(); + let b = run_cmd(&mut app, "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].clone(); + run_cmd(&mut app, "select.set", json!({"ids": [a, b]})); + run_cmd(&mut app, "appearance.setActiveItem", json!({"index": 0})); + let mut panel = Panel::new(app, show); + unfinished_opacity(&mut panel); + run_cmd(&mut panel.app(), "select.set", json!({"ids": [b, a]})); + run_cmd(&mut panel.app(), "appearance.setActiveItem", json!({"index": 0})); + finish_opacity(&mut panel); + let row = |panel: &Panel, id: &Value| { + panel.app().session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().appearance.items[0].opacity() + }; + assert_eq!(row(&panel, &b), 0.01, "the first object's row takes 1%, not 20+1"); + } + /// Each knockout state and the state a click on the box moves it to. #[test] fn knockout_states_and_page_group_items() { From f0bf8ec9c472bdd576bf0fc3d4483fc730e73154 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 02:29:15 -0800 Subject: [PATCH 083/103] Docs: limit the unfilled-interior picking sentence to ordinary clicks The selection fill eligibility entry now says that its "nothing else there" rule covers ordinary picking and points to the #9175 entry for Select Behind. The #9175 entry no longer says Select Behind lists unfilled paths after painted ones: it steps through them with the other objects under the pointer, as `object_behind` does through `leaves_at`. --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b90b091c14..abeaa8150e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -709,9 +709,9 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss by default, with Object Selection by Path Only on, and in Outline view. With Select Inside Unfilled Shapes on, Path Only off and not in Outline view, such an interior is picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss by default, with Object Selection by Path Only on, and in Outline view. With Select Inside Unfilled Shapes on, Path Only off and not in Outline view, in ordinary picking (not Select Behind) such an interior is picked only when the click hits nothing else there; the #9175 bullet below covers Select Behind. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. -- **Clicks inside unfilled shapes (#9175):** with Selection & Anchor Display › Select Inside Unfilled Shapes on (off by default; off, a click or drag there starts a marquee when it hits nothing else there: not the shape's stroke, other art or the shape's visible center point) and Object Selection by Path Only off, the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference` (MCP), and `a_drag_inside_an_unfilled_shape_makes_a_marquee_unless_asked` (Selection tool). Scores and estimates unchanged. +- **Clicks inside unfilled shapes (#9175):** with Selection & Anchor Display › Select Inside Unfilled Shapes on (off by default; off, a click or drag there starts a marquee when it hits nothing else there: not the shape's stroke, other art or the shape's visible center point) and Object Selection by Path Only off, the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind steps through them with the other objects under the pointer. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_only_with_the_preference` (MCP), and `a_drag_inside_an_unfilled_shape_makes_a_marquee_unless_asked` (Selection tool). Scores and estimates unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. From 1b4f26e7634cef0b92d7629ea0bc72b9fde3fdb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 02:32:10 -0800 Subject: [PATCH 084/103] Docs: the Color Picker returns the color given only when its model is unchanged too OK returns a new object of the color given only when both the color and its model are unchanged; a model-only change is a new pick. The progress line, docs/mcp.md and the script.run params text now say so. --- crates/engine/src/cmd/scripts.rs | 2 +- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 5f58050758..c07265d173 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), 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); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, unless a run of that engine takes it first with update(), which runs the handler during that run with no report or undo step of its own, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), 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); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with both the color and its model unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, unless a run of that engine takes it first with update(), which runs the handler during that run with no report or undo step of its own, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; 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.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 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, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), 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], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), 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, fileCalls, fileExecutes}, 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), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, 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, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/docs/mcp.md b/docs/mcp.md index 731a0d2373..92f398ab6a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4392,7 +4392,7 @@ https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. when the run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so the color's `typename` can differ from the picker's model and from the color given. An answer taken from `answers` keeps the color model it was given. The picker opens on the color as -given, whatever Only Web Colors was left at in another picker. OK with the color unchanged and Cancel return a new object of the color the +given, whatever Only Web Colors was left at in another picker. OK with both the color and its model unchanged, and Cancel, return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting end the run as they do at the other dialogs, and close the picker. They also end a screen color sample (`ui.sampleScreenColor` with `picker`, or the picker's eyedropper) that the picker started, and drop a sampled color diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e76a305371..f2ad6db7c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1134,7 +1134,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel, and OK with both the color and its model unchanged, return a new object based on the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. From d5be27f55af585c1529db39d14a55ff1f20f4e15 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 02:38:51 -0800 Subject: [PATCH 085/103] Curvature comb: a seam segment whose anchors coincide uses its handle direction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit comb_closes took a straight segment's chord as its direction at the seam. When the segment's anchors sit on one point and its handle is too short to count, that chord has no length, the reversal test compared against a zero vector, and the comb closed across a seam where the path turns back. The seam check now uses the chord only when it has a length, as curvature_comb does, and falls back to the handle direction otherwise. The View › Show Curvature Comb params help and the ROADMAP line now say that the line through the tips starts again at a cusp, a straight segment included; ui_catalog.rs is regenerated. --- ROADMAP.md | 2 +- crates/geom/src/curvature.rs | 21 +++++++++++++++++++-- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8b29a40471..2611bd4965 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,7 +124,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log -- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged. +- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged. - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index c95e9edf45..74c4737c9f 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -350,8 +350,10 @@ pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { match ((0..n).rev().find(|&i| !no_length(i)), (0..n).find(|&i| !no_length(i))) { (Some(into), Some(out)) => { let (a, b) = (sp.segment(into), sp.segment(out)); - let a = if sp.segment_is_line(into) { a.p3 - a.p0 } else { end_direction(a) }; - let b = if sp.segment_is_line(out) { b.p3 - b.p0 } else { start_direction(b) }; + // A straight segment's chord, as `curvature_comb` uses it, when the chord has a length. + let chord = |i: usize, c: CubicBez| Some(c.p3 - c.p0).filter(|v| sp.segment_is_line(i) && v.hypot() > 0.0); + let a = chord(into, a).unwrap_or_else(|| end_direction(a)); + let b = chord(out, b).unwrap_or_else(|| start_direction(b)); !turns_back(a, b) } _ => false, @@ -488,6 +490,21 @@ mod tests { } } + /// A segment whose anchors sit on one point and whose handle is too short to count still has + /// a direction at the seam, so a reversal there keeps the comb open. + #[test] + fn the_comb_stays_open_at_a_seam_segment_with_coincident_anchors() { + let a0 = Anchor::corner(Point::ORIGIN); + let a1 = Anchor::corner(Point::new(100.0, 0.0)); + let a2 = Anchor { h_out: Point::new(1e-12, 0.0), ..Anchor::corner(Point::ORIGIN) }; + let sp = SubPath::new(vec![a0, a1, a2], true); + assert!(sp.segment_is_line(2)); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + let (first, last) = (teeth.first().map(|t| t.at), teeth.last().map(|t| t.at)); + assert!(first.zip(last).is_some_and(|(f, l)| f.distance(l) < 1e-9), "the teeth meet at the seam: {teeth:?}"); + assert!(!comb_closes(&sp, &teeth), "the closing segment heads back against the first one"); + } + /// Large finite line directions still break the comb at a reversal inside the path and at its seam. #[test] fn the_comb_breaks_where_large_straight_segments_turn_back() { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 618c9d7529..429db2126c 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -265,7 +265,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.curvatureComb", "Show Curvature Comb", "", - "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color that starts again where the path turns back on itself at a cusp, a straight segment included; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", ), ( "type.hiddenCharacters", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 6f955c6dba..87302382bc 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -266,7 +266,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.curvatureComb", "Show Curvature Comb", "", - "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color that starts again where the path turns back on itself at a cusp, a straight segment included; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", ), ( "type.hiddenCharacters", From 90b6a7640b83dd83b1b2d3d5d08f5b4aefcc674e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 02:54:11 -0800 Subject: [PATCH 086/103] Scripts: palette events keep drags, drafts and frames as the person left them Follow-up to the review of #9147 (script palettes): - A waiting click or change that can no longer run (its control was disabled, hidden or removed by an earlier handler) is dropped before the open edit is settled, so it no longer commits or cancels a drag in the active document with no handler run. - A palette title or other getter that hides or closes the palette while the palette is being described no longer sends that description to the host: the host keeps the controls the palette had when it was hidden. - A typed text that matches the field's stored text is still given to the script, before a click, a close or on focus loss, when another change of that field waits, so the handler reads the typed text and not the waiting change. - After a palette event's run fails to begin, the app does not retry and ask for a frame on every pass. It tries again after the next input in the window, another palette event, or a change to the documents' edit state, the active document or the recovery settings. - The print test now checks that the click's handler ran after the print jobs were canceled, and the list test only fails when the earlier item's text changed. --- crates/engine/src/script/palettes.rs | 37 +++++- crates/engine/src/tests/script_palettes.rs | 26 +++++ crates/js/src/scriptui.rs | 6 + crates/js/src/scriptui_tests.rs | 45 ++++++-- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/dialogs/script_window.rs | 46 ++++++-- crates/ui-egui/src/script_palettes.rs | 71 ++++++++++-- crates/ui-egui/src/state.rs | 7 ++ crates/ui-egui/src/tests/script_palettes.rs | 122 ++++++++++++++++++++ crates/ui-egui/src/tests/script_print.rs | 9 ++ docs/mcp.md | 4 +- 11 files changed, 337 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index a63a712918..7d3c2eaf9e 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -236,6 +236,17 @@ impl Palettes { None } + /// Drops the events at the front of the line that [`Palettes::next`] would drop, so that the + /// line is empty or starts with an event that can still run. + fn drop_stale(&mut self) { + while let Some(q) = self.waiting.front() { + if self.resolved(q.clone()).is_some() { + break; + } + self.waiting.pop_front(); + } + } + /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other /// engines' palettes keep their places in line. Events whose file access scopes do not cover /// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest @@ -252,7 +263,13 @@ impl Palettes { /// The taken event `q` given to its control in its palette, and that palette, or `None` when it /// is dropped ([`Palettes::next`]). - fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> { + fn checked(&self, q: Queued) -> Option<(ScriptPalette, Queued)> { + let (p, q) = self.resolved(q)?; + Some((p.clone(), q)) + } + + /// [`Palettes::checked`] without the copy of the palette. + fn resolved(&self, mut q: Queued) -> Option<(&ScriptPalette, Queued)> { let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?; if let Some(c) = control_of(&mut q.event) { *c = p.dialog.index_of(q.element?)?; @@ -271,7 +288,7 @@ impl Palettes { } else { q.event = scriptui::check_event(&p.dialog, q.event).ok()?; } - Some((p.clone(), q)) + Some((p, q)) } /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` @@ -414,6 +431,12 @@ impl Session { self.script_palettes.waiting.len() } + /// The number of the last palette event put in line, which an event added, or merged into a + /// waiting one, changes. + pub fn script_palette_last_ticket(&self) -> u64 { + self.script_palettes.last_ticket + } + /// The changes that wait for a run, as (palette id, the id of the control they change). pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> { self.script_palettes @@ -456,7 +479,12 @@ impl Session { /// run is going or no event waits; otherwise the run's name, or the error that ended it before /// it began. An open edit that cannot be settled gives its error, and the events keep waiting. pub fn script_palette_start(&mut self) -> Option<Result<String>> { - if self.script_running() || self.script_palettes.waiting.is_empty() { + if self.script_running() { + return None; + } + // Events that can no longer run do not settle the open edit. + self.script_palettes.drop_stale(); + if self.script_palettes.waiting.is_empty() { return None; } // An event waits while a drag or an undo group is open, which a run cannot start in. @@ -507,6 +535,9 @@ impl Session { let want = self.script_palettes.last_ticket; let mut mine = None; loop { + if !self.script_running() { + self.script_palettes.drop_stale(); + } if !self.script_running() && !self.script_palettes.waiting.is_empty() && let Err(e) = self.settle_for_script() diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index cf873ec324..6908ef08ea 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -563,6 +563,32 @@ fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { assert_eq!(s.script_palette_events_waiting(), 0); } +#[test] +fn a_line_of_clicks_that_can_no_longer_run_does_not_settle_the_open_edit() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \ + var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \ + go.onClick = function () { vc.log('go'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the first click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"])); + // Settling would fail here, so a start that tries to settle gives an error. + SETTLE_FAILS.with(|f| f.set(true)); + let started = s.script_palette_start(); + SETTLE_FAILS.with(|f| f.set(false)); + assert!(started.is_none(), "the stale click does not settle the open edit: {:?}", started.map(|r| r.map_err(|e| e.to_string()))); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 8864fc1911..ba8e7f69f3 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1802,7 +1802,13 @@ fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if !slot(i, win, SHOWN)?.truthy() { return Ok(()); } + let hides = number_slot(i, win, HIDES)?; let (desc, ..) = describe(i, win)?; + // A getter that hid or closed the palette leaves the host the controls it had then. + let same = matches!(slot(i, win, PALETTE_ID)?, Value::Number(now) if now == id); + if !same || !slot(i, win, SHOWN)?.truthy() || number_slot(i, win, HIDES)? != hides { + return Ok(()); + } let f = host_fn(i, "paletteUpdate")?; i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; Ok(()) diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 11bde4ca26..7468e82cfd 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1250,6 +1250,22 @@ fn a_hidden_palette_is_not_described_after_the_run() { assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls"); } +#[test] +fn a_palette_a_title_getter_hides_is_not_described_after_the_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); var hiding = false; \ + Object.defineProperty(p, 'text', {get: function () { if (hiding) { hiding = false; p.hide(); return 'New'; } return 'T'; }});", + ) + .unwrap(); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count(); + let before = updates(&calls); + r.run("hiding = true;").unwrap(); + r.refresh_script_ui().expect("the refresh reads the title"); + assert_eq!(r.run("[hiding, p.visible].join()").unwrap(), JsValue::String("false,false".into()), "the getter ran and hid the palette"); + assert_eq!(updates(&calls), before, "the host keeps the controls the palette had when it was hidden"); +} + #[test] fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); @@ -1339,19 +1355,24 @@ fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_th #[test] fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() { - let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); // The second read of the second item's text, which compares it with the items the person saw, - // changes the first item's text, which that comparison already took. - r.run( - "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ - l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ - Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \ - p.show();", - ) - .unwrap(); - let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); - assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); - assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); + // changes the first item's text, which that comparison already took. It also puts back a plain + // `b` in place of its getter, so that only the first item's change can end the choice: without + // that change, the same choice reaches `onChange`. + for (mutate, error, got) in [(true, "a palette's list changed before the person's choice was taken", ""), (false, "none", "a")] { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); + r.run(&format!( + "var mutate = {mutate}; var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; var second = l.items[1]; \ + Object.defineProperty(second, 'text', {{configurable: true, get: function () {{ if (reads >= 0 && ++reads == 2) {{ \ + if (mutate) {{ l.items[0].text = 'z'; }} Object.defineProperty(second, 'text', {{value: 'b', writable: true, configurable: true}}); }} \ + return 'b'; }}}}); p.show();" + )) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(error.into()), "mutate: {mutate}"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String(got.into()), "mutate: {mutate}"); + } } #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0448534fda..5cc27ca4d9 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -831,6 +831,8 @@ impl VectorcraftApp { toast::post(&ctx, &WindowKey::main(), Toast::new(t.message).tone(tone(t.level)).timeout(Some(t.seconds as f32))); } menus::native::sync(self, &ctx); + // A palette event whose start failed tries again after this pass's input. + crate::script_palettes::clear_failed_start(self, &ctx); // A palette event that waited for an undo group this pass ended starts its run next frame. if crate::script_palettes::can_start(self) { ctx.request_repaint(); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 48401c4b57..825e87abdb 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -218,6 +218,18 @@ pub(crate) fn keep_fields(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String> /// as the script in `w` would check it first; when one is refused, every field keeps its text, /// `events` stays as it was and the error is returned. pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String>, events: &mut Vec<UiEvent>) -> Result<(), String> { + commit_texts_over(w, drafts, events, &[]) +} + +/// [`commit_texts`] for fields whose earlier changes still wait to be delivered: a draft of a field +/// whose id is in `queued` is given even when it matches the field's text, since the script reads the +/// waiting change's text first. +pub(crate) fn commit_texts_over( + w: &ScriptUiDialog, + drafts: &mut BTreeMap<u64, String>, + events: &mut Vec<UiEvent>, + queued: &[u64], +) -> Result<(), String> { let mut given = Vec::new(); let mut changes = Vec::new(); for (i, n) in w.nodes.iter().enumerate() { @@ -230,7 +242,7 @@ pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String continue; } if let Some(text) = drafts.get(&n.id) { - if *text != n.text { + if *text != n.text || queued.contains(&n.id) { changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?); } given.push(n.id); @@ -336,7 +348,7 @@ impl StackDialog for ScriptWindow { let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open)); // The body can run twice in a pass (measure, then paint), so it only reports what the // person did; the dialog applies the last run's report after the container. - let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting)); + let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting, &[])); let pass = shown.inner.unwrap_or_default(); if pass.layer.is_some() { self.layer = pass.layer; @@ -416,7 +428,7 @@ pub(crate) fn heading(w: &ScriptUiDialog) -> String { /// Draws the visible controls of the ScriptUI window `w` at the places the engine laid them out, /// with the text typed in its edit fields (`drafts`); none can be used unless `usable`. -pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, String>, usable: bool) -> Pass { +pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, String>, usable: bool, queued: &[u64]) -> Pass { let (width, height) = w.size(); let size = egui::vec2(width.max(1.0), height.max(1.0)); let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() }; @@ -432,7 +444,13 @@ pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, S continue; } let parent = containers.get(n.parent).copied().flatten(); - let place = Place { origin, enabled: usable && n.enabled, default: w.default_element == Some(i), parent }; + let place = Place { + origin, + enabled: usable && n.enabled, + default: w.default_element == Some(i), + parent, + queued_text: queued.contains(&n.id), + }; let shown = control(ui, drafts, &place, (i, n, prompt_of(w, i))); if let Some(slot) = containers.get_mut(i) { *slot = shown.container; @@ -453,6 +471,7 @@ struct Place { enabled: bool, default: bool, parent: Option<egui::Id>, + queued_text: bool, } /// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus, @@ -531,7 +550,7 @@ fn control(ui: &mut Ui, drafts: &BTreeMap<u64, String>, place: &Place, (i, n, pr shown.event = Some(UiEvent::Click(i)); } } - UiKind::EditText => shown = edit(ui, rect, drafts, enabled, (i, n, prompt)), + UiKind::EditText => shown = edit(ui, rect, drafts, enabled, place.queued_text, (i, n, prompt)), UiKind::DropDownList => { let entries: Vec<Entry<Option<usize>>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect(); let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show_at(ui, rect); @@ -634,9 +653,15 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { /// accepts, so that a text that is too long can still be typed, refused and shortened. pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES; +/// The change an edit field `n` at index `i` gives when its text `text` is committed: none for a +/// read-only field, or for the field's own text unless a change of the field waits (`queued`). +pub(crate) fn text_change(i: usize, n: &UiNode, text: String, queued: bool) -> Option<UiEvent> { + (!n.readonly && (text != n.text || queued)).then_some(UiEvent::Change(i, UiValue::Text(text))) +} + /// An edit field: its text is kept in the dialog while it is typed and given to the script when /// the field loses the focus, or at Enter in a one-line field. -fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { +fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: bool, queued: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone()); let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text)) .limit(DRAFT_CHARS) @@ -648,13 +673,14 @@ fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: } let out = field.show_at(ui, rect); let focused = out.response.has_focus(); - let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone())); + let queued = queued && (drafts.contains_key(&n.id) || out.events.value().is_some()); + let mut draft = (out.events.value().is_some() || text != n.text || queued).then(|| Some(text.clone())); let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus(); - if committed && text != n.text && !n.readonly { - return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None, draft: Some(None) }; + if committed && let Some(event) = text_change(i, n, text.clone(), queued) { + return Shown { event: Some(event), typing: true, container: None, draft: Some(None) }; } // A text the script refused stays in the field until the person changes it. - if !focused && text == n.text { + if !focused && text == n.text && !queued { draft = Some(None); } Shown { event: None, typing: focused || committed, container: None, draft } diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index eed7529753..33862e7af2 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -55,12 +55,21 @@ pub(crate) struct PaletteWindow { /// field shows it until no change of that field waits, even while the palette's field holds the /// same text, since a run before the change may set the field to another one. pending: BTreeMap<u64, String>, + queued_texts: Vec<u64>, open: bool, } impl PaletteWindow { fn new(palette: ScriptPalette) -> Self { - PaletteWindow { palette, drafts: BTreeMap::new(), draft_scopes: BTreeMap::new(), given: Vec::new(), pending: BTreeMap::new(), open: true } + PaletteWindow { + palette, + drafts: BTreeMap::new(), + draft_scopes: BTreeMap::new(), + given: Vec::new(), + pending: BTreeMap::new(), + queued_texts: Vec::new(), + open: true, + } } /// The palette as the session has it now. A typed text whose field the palette no longer has is @@ -68,6 +77,7 @@ impl PaletteWindow { /// [`vectorcraft_engine::Session::script_palette_changes_waiting`]). fn sync(&mut self, palette: ScriptPalette, waiting: &[(u64, u64)]) { self.palette = palette; + self.queued_texts = waiting.iter().filter(|(id, _)| *id == self.palette.id).map(|(_, field)| *field).collect(); script_window::keep_fields(&self.palette.dialog, &mut self.drafts); let (nodes, palette, given) = (&self.palette.dialog.nodes, self.palette.id, !self.given.is_empty()); self.pending.retain(|id, _| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id)); @@ -76,7 +86,7 @@ impl PaletteWindow { /// Draws the palette's controls in `ui` and takes what the person did, as its body does. #[cfg(test)] pub(crate) fn paint(&mut self, ui: &mut Ui) { - let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true); + let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true, &self.queued_texts); self.take_pass(pass.drafts.into_iter().collect(), pass.events); } @@ -105,8 +115,12 @@ impl PaletteWindow { /// the focus. #[cfg(test)] pub(crate) fn commit_text(&mut self, i: usize, text: &str) { - if let Some(n) = self.palette.dialog.nodes.get(i) { - self.take_pass(vec![(n.id, None)], vec![UiEvent::Change(i, UiValue::Text(text.to_string()))]); + let committed = shown_dialog(&self.palette.dialog, &self.pending) + .nodes + .get(i) + .map(|n| (n.id, script_window::text_change(i, n, text.to_string(), self.queued_texts.contains(&n.id)))); + if let Some((id, event)) = committed { + self.take_pass(vec![(id, None)], event.into_iter().collect()); } } @@ -219,7 +233,7 @@ impl StackDialog for PaletteWindow { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> { let heading = script_window::heading(&self.palette.dialog); - let PaletteWindow { palette, drafts, pending, open, .. } = self; + let PaletteWindow { palette, drafts, pending, queued_texts, open, .. } = self; let dialog = shown_dialog(&palette.dialog, pending); let drafts_now = &*drafts; // The body can run twice in a pass (measure, then paint), so the last run's report is @@ -228,7 +242,7 @@ impl StackDialog for PaletteWindow { .modeless() .initial_focus(Initial::Keep) .opened(Bind::bound(open)) - .show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true)); + .show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true, queued_texts)); let pass = shown.inner.unwrap_or_default(); let mut events = pass.events; // The close box gives the script the close; the palette stays open until the script closes @@ -316,7 +330,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => true, }); let before = at_pass.clone(); - let (batch, refused) = drafted(app, &p.dialog, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes); + let (batch, refused) = drafted(app, p, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes); // A refused text keeps every later click and close out of line too. change_refused |= refused; // A text the click or close took leaves its field unless a later one was typed there. @@ -358,13 +372,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { /// events with their scopes, and whether a text was refused. fn drafted( app: &mut VectorcraftApp, - w: &ScriptUiDialog, + p: &ScriptPalette, drafts: &mut BTreeMap<u64, String>, events: &mut Vec<UiEvent>, scope: &ScopeHandle, pass_scope: &ScopeHandle, draft_scopes: &BTreeMap<u64, ScopeHandle>, ) -> (Vec<(ScopeHandle, UiEvent)>, bool) { + let w = &p.dialog; let mut refused = false; if let Some(e) = script_window::keep_refused(w, drafts, events) { app.status(e); @@ -375,7 +390,10 @@ fn drafted( if events.iter().any(closing) { changes.extend(events.iter().filter(|e| !closing(e)).cloned()); let existing = changes.len(); - match script_window::commit_texts(w, drafts, &mut changes) { + // A draft that matches its field's text still goes in line when a change of that field + // waits, so the click reads the draft and not the waiting change. + let queued: Vec<u64> = app.session.script_palette_changes_waiting().into_iter().filter(|(id, _)| *id == p.id).map(|(_, e)| e).collect(); + match script_window::commit_texts_over(w, drafts, &mut changes, &queued) { Ok(()) => { drop(changes.drain(..existing)); } @@ -465,10 +483,38 @@ pub(crate) fn with_palette<R>(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut } /// Whether a waiting palette event's run can start now ([`vectorcraft_engine::Session::script_palette_can_start`]): -/// it also waits while the last run's print jobs wait to be approved or canceled, and asks for no -/// frame meanwhile. +/// it also waits while the last run's print jobs wait to be approved or canceled, and after a start +/// that failed until the person's next input or a change of the edit state ([`clear_failed_start`]), +/// and asks for no frame meanwhile. pub(crate) fn can_start(app: &VectorcraftApp) -> bool { - app.session.script_palette_can_start() && !crate::script_runs::waiting_for_print(app) + app.ui.palette_start_failed.is_none_or(|at| at != edit_state(app)) + && app.session.script_palette_can_start() + && !crate::script_runs::waiting_for_print(app) +} + +/// What a failed start may depend on: the documents, whether each has changes, an open drag or +/// undo group, the active one, and the palette events in line. +fn edit_state(app: &VectorcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + for d in app.session.documents() { + (d.uid, d.is_dirty(), d.interaction.is_some(), d.undo_group.is_some()).hash(&mut h); + } + app.session.active().map(|d| d.uid).hash(&mut h); + app.session.script_copy_first.hash(&mut h); + app.session.prefs.recovery_off_for_complex.hash(&mut h); + app.session.prefs.recovery_folder.hash(&mut h); + app.session.script_palette_events_waiting().hash(&mut h); + app.session.script_palette_last_ticket().hash(&mut h); + h.finish() +} + +/// Lets a waiting palette event whose start failed try again once the frame carries input, which +/// may have changed the edit that kept it from starting. +pub(crate) fn clear_failed_start(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.ui.palette_start_failed.is_some() && ctx.input(|i| !i.events.is_empty()) { + app.ui.palette_start_failed = None; + } } /// Starts the run of the oldest waiting palette event when no run is going. → whether one started. @@ -485,6 +531,7 @@ pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { None => false, Some(Ok(_)) => true, Some(Err(e)) => { + app.ui.palette_start_failed = Some(edit_state(app)); app.status(e.to_string()); false } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8ff9aaf3ad..fecb678aee 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -724,6 +724,12 @@ pub struct UiState { #[serde(skip)] pub touch_drawing_tool: Option<String>, pub status: String, + /// The edit state in which the last start of a waiting palette event's run failed + /// ([`crate::script_palettes::start_next`]). The event then waits for the person's next input, + /// or for that state to change, before it starts again, and asks for no frame meanwhile. Not + /// saved. + #[serde(skip)] + pub palette_start_failed: Option<u64>, /// How many times [`crate::VectorcraftApp::status`] has set `status`, so that work finishing /// later can tell whether the line it started with is still the latest one. Not saved. #[serde(skip)] @@ -1535,6 +1541,7 @@ impl Default for UiState { group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(), touch_drawing_tool: None, status: String::new(), + palette_start_failed: None, status_sets: 0, replace_font_warning: None, last_find: None, diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index ef816ce39e..7efb272535 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -260,6 +260,66 @@ fn a_click_or_close_narrows_the_scope_of_the_draft_it_commits() { } } +#[test] +fn a_click_reads_a_typed_text_that_matches_the_field_while_another_change_of_it_waits() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();", + ); + app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap(); + // The person types the field's text back and clicks before the change to `b` is delivered. + with_palette(&app, id, |w| w.type_text(1, "a")).unwrap(); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + let mut logs = Vec::new(); + for _ in 0..10 { + script_runs::poll(&mut app); + if !app.session.script_running() && app.session.script_palette_events_waiting() == 0 { + break; + } + run_to_end(&mut app); + logs.extend(app.session.script_report().unwrap()["log"].as_array().cloned().unwrap_or_default()); + } + run_to_end(&mut app); + if let Some(report) = app.session.script_report() { + logs.extend(report["log"].as_array().cloned().unwrap_or_default()); + } + assert!(logs.contains(&json!("clicked a")), "the click reads the text the person typed: {logs:?}"); + assert!(!logs.contains(&json!("clicked b")), "{logs:?}"); +} + +#[test] +fn focus_loss_commits_a_restored_text_while_another_change_of_the_field_waits() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();", + ); + app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap(); + follow(&mut app); + with_palette(&app, id, |w| w.type_text(1, "a")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + crate::testing::part_frame(&mut app, &ctx, egui::RawInput::default(), |app, ui| { + with_palette(app, id, |w| w.paint(ui)); + }); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten().as_deref(), Some("a")); + with_palette(&app, id, |w| w.commit_text(1, "a")).unwrap(); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 1, "focus loss merges the restored text into the waiting change"); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 2, "the click follows the restored text"); + for _ in 0..2 { + assert!(script_palettes::start_next(&mut app)); + run_to_end(&mut app); + } + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked a"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_text_typed_in_two_scopes_goes_to_the_script_in_what_both_allow() { use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; @@ -791,6 +851,68 @@ fn a_click_whose_run_cannot_begin_after_a_stopped_run_shows_its_own_error() { assert!(app.ui.status.contains("recovery copy"), "{}", app.ui.status); } +#[test] +fn a_click_whose_run_cannot_begin_asks_for_no_frame_until_the_next_input() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine two\nvar p = new Window('palette'); p.add('button', undefined, 'A').onClick = function () { vc.log('a'); }; \ + p.add('button', undefined, 'B').onClick = function () { vc.log('b'); }; p.show();", + ); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.session.script_copy_first = true; + give(&app, id, UiEvent::Click(1)); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + assert!(!script_palettes::start_next(&mut app)); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the second click still waits"); + assert!(!script_palettes::can_start(&app), "the failed start does not retry, nor ask for a frame, on every pass"); + // An event given without the window, as automation gives one, changes what the start depends on. + app.session.script_palette_event(id, UiEvent::Click(1)).unwrap(); + assert!(script_palettes::can_start(&app), "a change of the edit state lets the start try again"); + assert!(!script_palettes::start_next(&mut app)); + assert!(!script_palettes::can_start(&app)); + let ctx = app.ui_ctx.clone().unwrap(); + let input = egui::RawInput { events: vec![egui::Event::PointerGone], ..Default::default() }; + crate::testing::part_frame(&mut app, &ctx, input, |app, ui| script_palettes::clear_failed_start(app, ui.ctx())); + assert!(script_palettes::can_start(&app), "the person's next input lets the click try again"); + app.session.script_copy_first = false; + assert!(script_palettes::start_next(&mut app)); +} + +#[test] +fn a_failed_palette_start_retries_after_recovery_settings_change_without_input() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine retries\nvar p = new Window('palette'); \ + for (var i = 0; i < 3; i++) { p.add('button', undefined, 'Go ' + i).onClick = function () { vc.log('clicked'); }; } p.show();", + ); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.session.script_copy_first = true; + for i in 1..=3 { + give(&app, id, UiEvent::Click(i)); + } + follow(&mut app); + assert!(!script_palettes::start_next(&mut app)); + assert_eq!(app.session.script_palette_events_waiting(), 2); + assert!(!script_palettes::can_start(&app)); + assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "the failed start asks for no frames"); + app.session.execute("prefs.set", &json!({"key": "recoveryOffForComplex", "value": true})).unwrap(); + assert!(script_palettes::can_start(&app), "automation can change the recovery condition without window input"); + assert!(!script_palettes::start_next(&mut app), "the missing recovery store still prevents a start"); + assert_eq!(app.session.script_palette_events_waiting(), 1); + assert!(!script_palettes::can_start(&app)); + assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "a repeated failure still asks for no frames"); + app.session.script_copy_first = false; + assert!(script_palettes::can_start(&app), "disabling the recovery prerequisite permits another attempt"); + assert!(script_palettes::start_next(&mut app)); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index a8d5c7c030..d633c3633d 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -277,6 +277,15 @@ fn a_palette_click_waits_for_the_answer_to_the_last_runs_print_jobs() { cancel(&mut app, PRINT_KIND); script_runs::poll(&mut app); assert_eq!(app.session.script_palette_events_waiting(), 0, "the click's run starts once the jobs are answered"); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + script_runs::poll(&mut app); + } + assert!(!app.session.script_running(), "the click's run ends"); + let report = app.session.script_report().expect("the click's run reports"); + assert_eq!(report["log"], serde_json::json!(["clicked"]), "the click's handler ran: {report}"); } /// Cancel, from anyone, drops the jobs and keeps the run's changes. diff --git a/docs/mcp.md b/docs/mcp.md index e99e34fe86..66b472c21f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4635,7 +4635,9 @@ visible, controls: [{index, kind, name, text, enabled, visible, value?, items?, waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gives a shown palette a `click`, a `change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in -`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events in order and returns the report of +`ui.inspect`'s `scriptReport`. When a waiting event's run cannot begin in the app, the status bar shows the error, +and the events still in line wait until the next input in the window, another `script.palette.event`, or a change +to a document's unsaved state, drag or undo group, or to the active document. With nobody to ask, it runs the waiting events in order and returns the report of the run that handled this one, or its error, even when it took the place of an earlier waiting event; an event dropped without a run is an error. An event whose run cannot begin ends it with that error, or with this event's result when this one has run, and the events after it keep waiting. When an open edit cannot be finished before From cc13d6abee65d7f049135b27fe2660b25e11a3a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 02:55:02 -0800 Subject: [PATCH 087/103] xtask: test-lint closes thirteen scanner gaps in workflow and test reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Workflow environment scan: - A quoted `NAME=value` counts as an assignment only after a command that sets variables (`export`, `declare`, `env`, `/usr/bin/env` and similar) or in a pipeline that writes `$GITHUB_ENV`, not as an argument such as `cargo test -- "NAME=x"`. - Bash `|&` is one pipe, so `echo "NAME=x" |& tee -a "$GITHUB_ENV"` writes the environment file. - A `#` after an escaped space (`a\ #b`) stays in its word and does not start a comment. Test reads: - `split_args` does not close generic arguments at a `->` arrow. - Binding names and nested `fn` names read non-ASCII letters (`_vérifier`), so an uncalled closure or nested function is excluded. - A grouped size receiver (`(xs).len()`) is checked for later shrinking. - An indexed item that is the direct `.all()` receiver (`rows[1].all(..)`) does not guard that assertion; an earlier access still shows the collection has items. - Selector locals before a bitwise `|` are tracked; closure parameters are excluded by their parameter list and scope, and the scan no longer slices inside a non-ASCII character. - A count whose initializer shrinks its source after the size read (`xs.len() + { xs.clear(); 0 }`) guards nothing. - `&&status.success()` is a double borrow, not a conjunction. - Generic tuple constructors (`Pair::<Input>(..)`) resolve their fields. - A braced const argument in a loop iterator's turbofish is not taken as the loop body. --- xtask/src/test_lint.rs | 265 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 237 insertions(+), 28 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 047625145e..8e7f78d016 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -973,7 +973,9 @@ fn upper_words(text: &str) -> impl Iterator<Item = String> + '_ { // an assignment, not one inside a value (`m="NAME=x"`). let boundary = match open_quote(line, from) { None => word_start(from), - Some(q) => q + 1 == from && word_start(q), + // A quoted word is an assignment only for a command that sets variables or in a + // pipeline that writes `$GITHUB_ENV`, not as an argument (`cargo test -- "N=x"`). + Some(q) => q + 1 == from && word_start(q) && quoted_setter(line, q), }; (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>']) && !printed(line, from)).then(|| name.to_owned()) }); @@ -1046,6 +1048,20 @@ fn printed(line: &str, from: usize) -> bool { prints && !writes_env_file(&line[pipeline_start..pipeline_end]) } +/// Whether the quoted word at `from` is an argument of a command that sets shell variables +/// (`export`, `declare`, `env` and similar) in its shell command, or sits in a pipeline that writes to `$GITHUB_ENV`. +fn quoted_setter(line: &str, from: usize) -> bool { + const SETTERS: [&str; 6] = ["export", "declare", "typeset", "readonly", "local", "env"]; + let separators = shell_separators(line); + let command_start = separators.iter().rev().find(|s| s.end <= from).map_or(0, |s| s.end); + let pipeline_start = separators.iter().rev().find(|s| s.end <= from && !s.pipe).map_or(0, |s| s.end); + let pipeline_end = separators.iter().find(|s| s.start >= from && !s.pipe).map_or(line.len(), |s| s.start); + // The setter can follow a YAML key or a shell keyword (`run: export`, `then export`). + // A path-qualified program (`/usr/bin/env`) is named by its last segment. + line[command_start..from].split_whitespace().any(|w| SETTERS.contains(&w.rsplit('/').next().unwrap_or(w))) + || writes_env_file(&line[pipeline_start..pipeline_end]) +} + /// Whether a pipeline writes to `$GITHUB_ENV`: the file is the target of a `>` or `>>` redirect or /// an argument of a command that writes files (`tee`, PowerShell's `Out-File`), not a word that an /// `echo` prints. @@ -1057,7 +1073,8 @@ fn writes_env_file(pipeline: &str) -> bool { // A redirect (`>`, `>>`, `>|`) outside quotes; a quoted `">$GITHUB_ENV"` is printed text. let operator = before.strip_suffix('|').unwrap_or(before); let redirect = operator.ends_with('>') && open_quote(pipeline, operator.len() - 1).is_none(); - let command = before.rsplit('|').next().unwrap_or(before); + // The `&` of a `|&` pipe belongs to the operator, not to the command after it. + let command = before.rsplit('|').next().unwrap_or(before).trim_start_matches('&'); let program = command.split_whitespace().next().unwrap_or_default().to_ascii_lowercase(); redirect || WRITERS.contains(&program.as_str()) }) @@ -1094,6 +1111,11 @@ fn shell_separators(script: &str) -> Vec<ShellSeparator> { // `2>&1`, `&>` and `>|` are redirections. b'&' | b'|' if i > 0 && matches!(bytes[i - 1], b'>' | b'<') => {} b'&' if bytes.get(i + 1) == Some(&b'>') => {} + // Bash's `|&` pipes standard error with standard output: one pipe. + b'|' if bytes.get(i + 1) == Some(&b'&') => { + out.push(ShellSeparator { start: i, end: i + 2, pipe: true }); + i += 1; + } b'|' => out.push(ShellSeparator { start: i, end: i + 1, pipe: true }), b';' | b'&' | b'\n' => out.push(ShellSeparator { start: i, end: i + 1, pipe: false }), _ => {} @@ -1153,8 +1175,11 @@ fn workflow_code(line: &str) -> &str { /// `#` starts a comment only where a word starts (`build#1` is one word). fn shell_code(script: &str) -> String { let (mut out, mut quote, mut escaped, mut comment) = (String::with_capacity(script.len()), None, false, false); - let mut previous = None; + // Whether the previous character ended a word: an unescaped space or control operator, or the + // start of the script. An escaped space (`a\ #b`) keeps the `#` inside the word. + let mut word_ended = true; for c in script.chars() { + let literal = escaped && !comment; if comment { comment = c != '\n'; } else if escaped { @@ -1166,14 +1191,14 @@ fn shell_code(script: &str) -> String { } else if quote.is_none() { match c { '\'' | '"' => quote = Some(c), - '#' => comment = previous.is_none_or(|p: char| p.is_whitespace() || matches!(p, ';' | '&' | '|' | '(' | ')')), + '#' => comment = word_ended, _ => {} } } if !comment { out.push(c); } - previous = Some(c); + word_ended = !literal && (c.is_whitespace() || matches!(c, ';' | '&' | '|' | '(' | ')')); } out } @@ -1332,6 +1357,23 @@ fn skip_ws(b: &[u8], mut i: usize) -> usize { i } +/// The text of `b` from `at`, at most 1 KiB of it, up to the first byte that does not decode as +/// UTF-8. +fn utf8_from(b: &[u8], at: usize) -> &str { + let rest = &b[at.min(b.len())..(at + 1024).min(b.len())]; + std::str::from_utf8(rest).unwrap_or_else(|e| std::str::from_utf8(&rest[..e.valid_up_to()]).unwrap_or_default()) +} + +/// Where the name that starts at `at` (after any whitespace, Unicode whitespace included) starts +/// and ends: letters, digits and `_`, non-ASCII ones included (`vérifier`). +fn name_at(b: &[u8], at: usize) -> (usize, usize) { + let s = utf8_from(b, at); + let start = at + s.len() - s.trim_start().len(); + let s = utf8_from(b, start); + let len = s.find(|c: char| !(c.is_alphanumeric() || c == '_')).unwrap_or(s.len()); + (start, start + len) +} + /// Every start of `word` in `b[from..to]` with no identifier character on either side. fn words(b: &[u8], word: &[u8], from: usize, to: usize) -> Vec<usize> { let mut out = vec![]; @@ -1389,7 +1431,8 @@ fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth -= 1, b'<' if in_angle || opens_angle(&m[from..j]) => angles.push(depth), - b'>' if in_angle => { + // The `>` of a return-type arrow (`fn() -> u8`) does not close the list. + b'>' if in_angle && (j == 0 || m[j - 1] != b'-') => { angles.pop(); } b',' if depth == 0 && angles.is_empty() => { @@ -2013,8 +2056,9 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec<u8> { .into_iter() .filter(|&at| m[..at].trim_ascii_end().last().is_some_and(|c| matches!(c, b'{' | b';' | b'}'))); for at in statements { - let name = skip_ws(m, at + 3); - let name_end = name + m[name..t.close].iter().copied().take_while(|&c| is_ident(c)).count(); + // Non-ASCII letters (`_vérifier`) are part of the name, and Unicode whitespace is not. + let (name, name_end) = name_at(m, at + 3); + let name_end = name_end.min(t.close); let eq = skip_ws(m, name_end); if name_end == name || m.get(eq) != Some(&b'=') || m.get(eq + 1) == Some(&b'=') { continue; @@ -2423,14 +2467,20 @@ fn all_unguarded(v: &View) -> Vec<Hit> { let text = norm(&body[from..to]); let other = SIZE_CHECKS.iter().any(|g| { text.match_indices(g).any(|(i, _)| { - let head = &text[..i]; - let start = head.bytes().rposition(|c| !is_ident(c)).map_or(0, |p| p + 1); + // A grouped receiver (`(xs).len()`) names the local inside its parentheses. + let closes = text[..i].len() - text[..i].trim_end_matches(')').len(); + let head = &text[..i - closes]; + let ident = head.bytes().rposition(|c| !is_ident(c)).map_or(0, |p| p + 1); + let grouped = closes > 0 && ident >= closes && head[..ident].ends_with(&"(".repeat(closes)); + let (head, closes) = if grouped || closes == 0 { (head, closes) } else { (&text[..i], 0) }; + let start = if grouped { ident } else { head.bytes().rposition(|c| !is_ident(c)).map_or(0, |p| p + 1) }; let receiver = &head[start..]; - let plain = plain_local(receiver) && !head[..start].ends_with(['.', ':']); + let outer = if grouped { start - closes } else { start }; + let plain = plain_local(receiver) && !head[..outer].ends_with(['.', ':']); // An operand that may shrink the local after reading its size // (`{ let n = xs.len(); xs.clear(); n }`) guards nothing; a change before the // read (`{ xs = fetch(); xs.len() }`) is measured by it. - let read = format!("{receiver}{g}"); + let read = format!("{receiver}{}{g}", ")".repeat(closes)); let kept = words(&body, receiver.as_bytes(), from, to) .into_iter() .filter(|&p| norm(&body[p..to]).starts_with(&read)) @@ -3918,7 +3968,11 @@ fn first_item_guard(body: &[u8], sizes: &Sizes, until: usize) -> bool { }; } let calls = &compact[end + 1..chain]; - let all_over_item = [".iter()", ".into_iter()"].iter().any(|m| calls.starts_with(m)) && calls.ends_with('.'); + // The item itself can also be the `.all` receiver (`rows[1].all(…)` over a range): then it + // does not guard the assertion it is in, though an earlier one still shows `rows` has items. + let in_assertion = spots.get(at).is_some_and(|&p| p >= until); + let all_over_item = + (calls == "." && in_assertion) || ([".iter()", ".into_iter()"].iter().any(|m| calls.starts_with(m)) && calls.ends_with('.')); // The access shows items only until code before the assertion at `until` may shrink or // replace the local it indexes (`let _item = xs[1]; xs.clear();`). That is checked on the // masked text, where `let xs` and `&mut xs` keep their spaces. @@ -4194,20 +4248,43 @@ fn selector_touched(body: &[u8], name: &str, from: usize) -> bool { fn selector_locals(expr: &str) -> Vec<&str> { let b = expr.as_bytes(); let mut out = vec![]; - let mut at = b.iter().take_while(|&&c| is_ident(c)).count(); + // Closure parameter lists (`|j|`, `|a, b|`): a `|` where an operand starts opens one, and the + // next `|` closes it. A `|` after an operand is bitwise or (`i | 0`). + let mut params: Vec<(usize, usize)> = vec![]; + let mut i = 0; + while i < b.len() { + // Bytes, not `&str` slices: `i` can sit inside a non-ASCII character (`café`). + let before = b[..i].trim_ascii_end(); + let opens = matches!(before.last(), None | Some(b'(' | b',' | b'=' | b'{' | b'[' | b';')) || before.ends_with(b"move"); + if let Some(close) = (b[i] == b'|' && opens).then(|| expr[i + 1..].find('|')).flatten() { + params.push((i, i + 1 + close)); + i += close + 2; + } else { + i += 1; + } + } + // Non-ASCII letters (`café`) are part of a name; their UTF-8 bytes are 0x80 or above. + let ident = |c: u8| is_ident(c) || c >= 0x80; + let mut at = b.iter().take_while(|&&c| ident(c)).count(); while at < b.len() { - if !is_ident(b[at]) { + if !ident(b[at]) { at += 1; continue; } let start = at; - while at < b.len() && is_ident(b[at]) { + while at < b.len() && ident(b[at]) { at += 1; } let word = &expr[start..at]; let before = expr[..start].trim_end(); let after = expr[at..].trim_start(); - let named = field_or_path(before.as_bytes()) || before.ends_with([':', '|']) || after.starts_with(['(', '!', ':', '|']); + // A closure parameter, in its list or after it in the closure's body; an argument before + // the closure (`r.items(i, |i| i > 0)`) is still the outer local. + let param = params.iter().any(|&(open, close)| { + (open < start && start < close) + || (start > close && expr[open + 1..close].split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|p| p == word)) + }); + let named = param || field_or_path(before.as_bytes()) || before.ends_with(':') || after.starts_with(['(', '!', ':']); if plain_local(word) && !named && !matches!(word, "true" | "false" | "as" | "mut") && !out.contains(&word) { out.push(word); } @@ -5213,6 +5290,9 @@ struct Binding { source: Option<Vec<u8>>, /// Where the block that holds the `let` closes, after which the name no longer refers to it. scope_end: usize, + /// Where the initializer first names its source: code after that can change the source after + /// its size is read (`let n = xs.len() + { xs.clear(); 0 };`). + init: usize, } /// Every `let` of a plain name in `body`, in order. @@ -5239,7 +5319,12 @@ fn bindings(body: &[u8]) -> Vec<Binding> { let closed = grouped[ident..].bytes().take_while(|&c| c == b')').count(); let source = (ident > 0 && closed <= opened && grouped[ident + closed..].starts_with('.')).then(|| grouped.as_bytes()[..ident].to_vec()); let scope_end = enclosing_block(body, at).and_then(|(open, _)| matching(body, open)).unwrap_or(body.len()); - Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source, scope_end }) + // Mutations are checked from just after the read of the source itself, so a view taken + // for that read (`xs.as_mut_slice().len()`) does not count, but later code in the + // initializer does. + let eq = end + body[end..stop].iter().position(|&c| c == b'=').map_or(stop - end, |p| p + 1); + let init = source.as_ref().and_then(|s| words(body, s, eq, stop).first().map(|p| p + s.len())).unwrap_or(stop); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source, scope_end, init }) }) .collect() } @@ -5259,7 +5344,7 @@ fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> // A count whose collection is unknown (`let n = { let n = xs.len(); xs.clear(); n };`) // cannot be shown to still hold. .is_some_and(|r| { - r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_some_and(|s| !may_shrink(body, s, r.end)) + r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_some_and(|s| !may_shrink(body, s, r.init)) }) }) }) @@ -5349,7 +5434,9 @@ fn status_condition(c: &str, depth: usize) -> bool { let mut parts = vec![]; let mut start = 0; for at in top_level_at(s, op) { - if at >= start { + // An operator needs a left operand: `&&status` at an operand's start is a double borrow. + let left = s.as_bytes()[start.min(at)..at].last().is_some_and(|c| !b"&|!=<>(,+-*/%^".contains(c)); + if at >= start && left { parts.push(&s[start..at]); start = at + op.len(); } @@ -5992,9 +6079,10 @@ fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { /// the parameter list, the return type and the body. `None` for a `fn` pointer type (`fn(u8)`) or a /// declaration without a body. fn fn_item_span(m: &[u8], kw: usize, to: usize) -> Option<(usize, usize)> { - let name = skip_ws(m, kw + 2); - let name_end = name + m[name..to].iter().take_while(|&&c| is_ident(c)).count(); - if name_end == name { + // Non-ASCII letters (`vérifier`) are part of the name. + let (name, name_end) = name_at(m, kw + 2); + let name_end = name_end.min(to); + if name_end <= name { return None; } let mut i = skip_ws(m, name_end); @@ -6914,7 +7002,11 @@ fn field_value(base: &str, field: &str, pos: usize, local: &LocalAt) -> Option<( (base.to_owned(), pos) }; let v = value.as_bytes(); - let open = v.iter().take_while(|&&c| is_ident(c) || c == b':').count(); + let mut open = v.iter().take_while(|&&c| is_ident(c) || c == b':').count(); + // A generic constructor's turbofish (`Pair::<Input>(…)`) comes before its fields. + if v.get(open) == Some(&b'<') && value[..open].ends_with("::") { + open = skip_turbofish(v, open - 2); + } // A tuple literal (`(Input { n: 5 },)`) has no name before its `(`. let tuple_literal = open == 0 && v.first() == Some(&b'('); if (open == 0 && !tuple_literal) || !matches!(v.get(open), Some(b'{' | b'(')) || matching(v, open) != Some(v.len() - 1) { @@ -7201,17 +7293,23 @@ fn loop_body(body: &[u8], iter: usize) -> Option<(usize, usize)> { } /// The braces of the block that follows an expression starting at `from`: the first `{` outside -/// parentheses and brackets, and its match. +/// parentheses, brackets and turbofish arguments (`results::<{ 1 + 1 }>()`), and its match. fn block_after(body: &[u8], from: usize) -> Option<(usize, usize)> { - let mut depth = 0usize; - for (i, &c) in body.iter().enumerate().skip(from) { - match c { + let (mut depth, mut i) = (0usize, from); + while i < body.len() { + let after = skip_turbofish(body, i); + if after > i { + i = after; + continue; + } + match body[i] { b'(' | b'[' => depth += 1, b')' | b']' => depth = depth.saturating_sub(1), b'{' if depth == 0 => return matching(body, i).map(|close| (i, close)), b';' | b'}' if depth == 0 => return None, _ => {} } + i += 1; } None } @@ -13129,4 +13227,115 @@ mod tests { ); assert_eq!(only("fixture-only", &user_alias), [], "the aliased field holds a user type"); } + + #[test] + fn only_a_setter_or_an_environment_file_write_makes_a_quoted_assignment() { + for line in ["run: cargo test -- \"MY_SAMPLES=fixtures\"", " cargo run 'MY_SAMPLES=fixtures'"] { + assert_eq!(upper_words(line).collect::<Vec<_>>(), Vec::<String>::new(), "{line}"); + } + for line in ["run: export \"MY_SAMPLES=fixtures\"", "run: /usr/bin/env \"MY_SAMPLES=fixtures\" cargo test"] { + assert_eq!(upper_words(line).collect::<Vec<_>>(), ["MY_SAMPLES"], "{line}"); + } + } + + #[test] + fn a_pipe_of_both_streams_is_one_pipe() { + let line = " echo \"MY_SAMPLES=fixtures\" |& tee -a \"$GITHUB_ENV\""; + assert_eq!(upper_words(line).collect::<Vec<_>>(), ["MY_SAMPLES"]); + assert_eq!(upper_words(" echo \"MY_SAMPLES=fixtures\" & tee -a \"$GITHUB_ENV\"").collect::<Vec<_>>(), Vec::<String>::new()); + } + + #[test] + fn a_hash_after_an_escaped_space_stays_in_its_word() { + assert_eq!(upper_words("run: \"echo a\\\\ #b; export MY_SAMPLES=x\"").collect::<Vec<_>>(), ["MY_SAMPLES"]); + assert_eq!(upper_words("run: \"echo a #b; export MY_SAMPLES=x\"").collect::<Vec<_>>(), Vec::<String>::new()); + } + + #[test] + fn a_return_type_arrow_does_not_close_generic_arguments() { + let m = b"actual, f::<fn() -> u8, u16>()"; + assert_eq!(split_args(m, 0, m.len()), [(0, 6), (7, m.len())]); + } + + #[test] + fn an_uncalled_closure_with_a_non_ascii_name_runs_no_assertion() { + let src = "#[test]\nfn t() {\n let _vérifier = || assert_eq!(compute(), 1);\n}\n"; + assert_eq!(hits(src), [(2, "no-assertion")]); + assert_eq!(hits(&src.replace(";\n}", ";\n _vérifier();\n}")), [], "a called closure"); + } + + #[test] + fn a_grouped_size_receiver_is_checked_for_later_shrinking() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n assert_eq!((xs).len(), 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let cleared = src.replace(" assert!(xs", " xs.clear();\n assert!(xs"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")]); + } + + #[test] + fn an_indexed_item_that_is_the_all_receiver_guards_nothing() { + let src = "#[test]\nfn t() {\n let rows = f();\n assert!(rows[1].all(|n| n > 0));\n}\n"; + assert_eq!(hits(src), [(4, "all-unguarded")]); + let earlier = + "#[test]\nfn t() {\n let rows = f();\n let _ = rows[1].all(|n| n > 0);\n assert!(rows.iter().all(|r| r.end > 0));\n}\n"; + assert_eq!(hits(earlier), [], "an earlier access still shows the collection has items"); + } + + #[test] + fn selector_closures_hide_only_their_own_parameters() { + assert_eq!(selector_locals("r.items(café, |j| j > 0, i)"), ["i"], "a non-ASCII name before a closure"); + assert_eq!(selector_locals("r.items(i, |i| i > 0)"), ["i"]); + assert_eq!(selector_locals("r.items(|i| i > 0)"), Vec::<&str>::new()); + } + + #[test] + fn a_selector_local_before_a_bitwise_or_is_tracked() { + let local = "#[test]\nfn t() {\n let mut i = 1;\n let got: Vec<u32> = r.items(i | 0).iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1]);\n assert!(r.items(i | 0).iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(local), [], "an unchanged bitwise selector"); + let changed = local.replace(" assert!(r.items", " i = 0;\n assert!(r.items"); + assert_eq!(hits(&changed), [(7, "all-unguarded")], "a bitwise selector changed after the snapshot"); + } + + #[test] + fn a_count_whose_initializer_shrinks_its_collection_guards_nothing() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len() + { xs.clear(); 0 };\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(6, "all-unguarded")]); + assert_eq!(hits(&src.replace(" + { xs.clear(); 0 }", "")), [], "a plain count"); + assert_eq!(hits(&src.replace("xs.len() + { xs.clear(); 0 }", "xs.as_mut_slice().len()")), [], "a view taken for the read"); + } + + #[test] + fn a_double_borrow_of_a_status_is_not_a_conjunction() { + let src = "#[test]\nfn t() {\n let status = Command::new(\"cp\").arg(src).arg(&destination).status().unwrap();\n assert_eq!(&&status.success(), &&true);\n}\n"; + assert_eq!(hits(src), [(2, "exit-status-only")]); + let both = src.replace("assert_eq!(&&status.success(), &&true)", "assert!(status.success() && destination.exists())"); + assert_eq!(hits(&both), []); + } + + #[test] + fn a_nested_function_with_a_non_ascii_name_is_not_polling() { + let src = "fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < D {\n fn vérifier() { probe(); }\n thread::sleep(D);\n }\n}\n"; + assert_eq!(hits(src).iter().filter(|h| h.1 == "sleep").count(), 1); + let called = src.replace(" thread::sleep", " vérifier();\n thread::sleep"); + assert_eq!(hits(&called).iter().filter(|h| h.1 == "sleep").count(), 0, "a call to the function polls"); + } + + #[test] + fn a_generic_tuple_constructor_resolves_its_fields() { + let src = "#[test]\nfn t() {\n let pair = Pair::<Input>(Input { n: 5 });\n assert_eq!(pair.0.clone().n, 6);\n}\n"; + assert_eq!(only("fixture-only", src), []); + let primitive = "#[test]\nfn t() {\n let pair = Pair::<u8>(5);\n assert_eq!(pair.0.to_string(), \"5\");\n}\n"; + assert_eq!(only("fixture-only", primitive), [(2, "fixture-only")]); + } + + #[test] + fn a_braced_const_argument_is_not_a_loop_body() { + let body = b"for n in results::<{ 1 + 1 }>() { use_it(n) }"; + let before = body.windows(6).position(|w| w == b"use_it").unwrap_or(0); + assert_eq!(for_binding(body, "n", before), Some(0)); + let inner = body.windows(5).position(|w| w == b"1 + 1").unwrap_or(0); + assert_eq!(for_binding(body, "n", inner), None, "the binding is not in scope in the iterator"); + let src = "#[test]\nfn t() {\n let n = 0;\n for n in results::<{ 1 + 1 }>() {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", src), []); + } } From 5436a18547acbdd7e235ff48c8fc83dd35e5c53d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 03:50:30 -0800 Subject: [PATCH 088/103] File formats: a DWG placed while converted keeps Place's context, and the conversion can be canceled - A DWG placed while it is converted goes on the layer that was current when Place started and, with `replace`, in place of the object selected then, selected again unless it changed meanwhile. A layer the user made current since stays current, as for other files read for Place. - Place's checks run before the conversion starts, so a bad param or a selection Replace can't swap (several objects, part of a symbol instance) is reported at once and nothing is converted. - The open progress window shows a DWG drawing being converted. `file.cancelOpen` drops the conversion, so its dialog never opens, and `file.openInBackground` closes the window while it goes on in the status bar. Both commands' help text and `docs/mcp.md` say so. --- crates/mcp/src/ui_catalog.rs | 4 +- crates/ui-egui/src/dialogs/dxf_import.rs | 146 ++++++++++++++++++++--- crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 4 +- crates/ui-egui/src/opening.rs | 95 ++++++++++----- crates/ui-egui/src/placing.rs | 13 +- docs/mcp.md | 5 + 7 files changed, 215 insertions(+), 54 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 618c9d7529..891f1388c3 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1732,13 +1732,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.cancelOpen", "Cancel Opening", "", - "{} stop opening every file being read in the background (its progress window's Cancel): the files don't open → {cancelled: n}", + "{} stop opening every file being read in the background and every DWG drawing being converted (its progress window's Cancel): the files don't open and the drawings don't open or place → {cancelled: n}", ), ( "file.openInBackground", "Continue in Background", "", - "{} close the progress window of the files being opened; they go on being read, shown in the status bar → {hidden: n}", + "{} close the progress window of the files being opened and the DWG drawings being converted; they go on, shown in the status bar → {hidden: n}", ), ( "file.cancelPlace", diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 31b1bc3b8d..ce05994234 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -77,9 +77,17 @@ struct Source { name: String, path: Option<String>, file: Arc<DialogFile>, - /// A DWG drawing's conversion, kept while the dialog is open so that its previews and its OK - /// read the drawing without converting it again. - _held: Option<vectorcraft_cad::dwg::Held>, + /// What a DWG drawing converted off the UI thread brings. + converted: Option<Converted>, +} + +/// A DWG drawing converted off the UI thread ([`converted`]). +pub(crate) struct Converted { + /// Its conversion, kept while the dialog is open so that its previews and its OK read the + /// drawing without converting it again. + _held: vectorcraft_cad::dwg::Held, + /// Where it is placed, taken when Place started; `None` when it opens. + placement: Option<crate::opening::Placement>, } /// The DXF Import Options dialog: the layout preview and what the drawing declares on the left, the @@ -351,25 +359,47 @@ pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8], /// [`offer_place`] for a file the user places where files are read off the UI thread: a DWG /// drawing is converted first ([`convert_in_background`]) → true; false when `p` names no DWG -/// drawing. +/// drawing. Place's checks run first, as for other files read for Place: a bad param, or a +/// selection that `replace` can't swap, is reported in the status bar at once and nothing is +/// converted (true). pub fn convert_place_in_background(app: &mut VectorcraftApp, p: &Value) -> bool { let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension); if p.get("dxf").is_some() || named.as_deref() != Some("dwg") { return false; } let Some((name, bytes, path)) = place_source(app, p, |ext| ext == "dwg") else { return false }; + if !vectorcraft_cad::is_dwg(&bytes) { + return false; + } + if p.get("replace").and_then(Value::as_bool) == Some(true) { + // The edit the tool computes on another thread comes first: the object Replace swaps is the + // one selected after it. + let r = app.session.finish_tool_edit(); + crate::canvas::apply_requests(app, r); + } + if let Err(e) = app.session.prepare_place(p) { + app.status(e.to_string()); + return true; + } convert_in_background(app, &name, &bytes, path, Some(p)) } /// A DWG drawing converted off the UI thread ([`convert_in_background`]): its dialog opens, to -/// place it with the `file.place` params `place`, or else to open it (it then goes on the recent -/// files); a drawing that can't be read is reported. -pub(crate) fn converted(app: &mut VectorcraftApp, name: &str, conversion: crate::opening::Conversion, path: Option<String>, place: Option<&Value>) { +/// place it with the `file.place` params `place` where `placement` says, or else to open it (it +/// then goes on the recent files); a drawing that can't be read is reported. +pub(crate) fn converted( + app: &mut VectorcraftApp, + name: &str, + conversion: crate::opening::Conversion, + path: Option<String>, + place: Option<&Value>, + placement: Option<crate::opening::Placement>, +) { let (bytes, info) = conversion; match info { Ok((info, held)) => { let opens = place.is_none(); - if show(app, name, &bytes, path.clone(), place, &info, Some(held)) + if show(app, name, &bytes, path.clone(), place, &info, Some(Converted { _held: held, placement })) && opens && let Some(path) = &path { @@ -381,8 +411,8 @@ pub(crate) fn converted(app: &mut VectorcraftApp, name: &str, conversion: crate: } } -/// Open the dialog for `bytes`, the drawing `info` describes (see [`offer`]), keeping `held`, its -/// DWG conversion, while it is open. +/// Open the dialog for `bytes`, the drawing `info` describes (see [`offer`]), with what its +/// conversion off the UI thread brings, if it was converted there. fn show( app: &mut VectorcraftApp, name: &str, @@ -390,7 +420,7 @@ fn show( path: Option<String>, place: Option<&Value>, info: &vectorcraft_cad::DxfInfo, - held: Option<vectorcraft_cad::dwg::Held>, + converted: Option<Converted>, ) -> bool { let mut choices = DxfChoices { layout: info.layouts.first().cloned().unwrap_or_else(|| "Model".into()), @@ -407,7 +437,7 @@ fn show( } } let file = DialogFile::new(bytes.to_vec()); - let source = Source { place: place.map(|p| other_place_params(p, &["dxf"])), name: name.to_string(), path, file: file.clone(), _held: held }; + let source = Source { place: place.map(|p| other_place_params(p, &["dxf"])), name: name.to_string(), path, file: file.clone(), converted }; let dialog = DxfImportDialog::new(place.is_some(), file, info, choices); open_held(app, dialog, move |app, choices| confirm(app, &source, choices)).is_some() } @@ -465,7 +495,32 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R Some(place) => { let mut p = with_file(place, source.path.as_deref(), &source.name, &source.file); p["dxf"] = dxf; - crate::place::run_for_user(app, &p).map(|_| ()) + let placement = source.converted.as_ref().and_then(|c| c.placement.as_ref()); + // Where new art goes now is taken before Replace selects the object it swaps again. + let current = placement.and_then(|_| crate::placing::Insertion::of(app)); + // A drawing converted off the UI thread replaces the object selected when Place + // started, selected again, unless it changed meanwhile. + if let Some((old, node)) = placement.and_then(|pl| pl.replaced.as_ref()) { + let st = app.session.doc().map_err(|e| e.to_string())?; + if st.doc.node(*old) != Some(node) { + return Err("replace: the object to replace was changed or deleted".into()); + } + if st.selection.objects != [*old] || st.selection.symbol_part.is_some() { + app.session.execute("select.set", &json!({ "ids": [old.0] })).map_err(|e| e.to_string())?; + } + } + // It goes where new art went when Place started, and what the user changed since is + // kept, as for other files read for Place. + let restore = placement.and_then(|pl| pl.insertion.clone()).map(|insertion| { + let insertion = insertion.or_now(current.as_ref(), app, false); + insertion.clone().set(app); + insertion + }); + let r = crate::place::run_for_user(app, &p).map(|_| ()); + if let (Some(current), Some(insertion)) = (current, restore) { + current.restore_changed(&insertion, app); + } + r } None => io::open_document(app, &source.name, &source.file.bytes, source.path.clone(), &json!({ "dxf": dxf })).map(|_| ()), } @@ -801,9 +856,42 @@ mod tests { }); } + /// The progress window shows a DWG drawing being converted: Cancel drops it, so its dialog + /// never opens, and Continue in Background leaves it converting in the status bar only. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_conversion_can_be_cancelled_or_continued_in_the_background() { + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-cancel"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + assert!(!crate::menus::enabled(&app, "file.cancelOpen")); + crate::io::open_file(&mut app, &plan, true).unwrap(); + let (tx, done) = std::sync::mpsc::channel(); + let result = std::mem::replace(&mut app.opening.converting[0].done, done).recv().unwrap(); + assert!(crate::menus::enabled(&app, "file.cancelOpen") && crate::menus::enabled(&app, "file.openInBackground")); + assert!(crate::opening::shown(&app).is_some_and(|s| s.title.contains("plan.dwg"))); + assert_eq!(app.run("file.cancelOpen", json!({})).unwrap()["cancelled"], 1); + assert!(app.opening.converting.is_empty() && app.ui.status.is_empty(), "{}", app.ui.status); + assert!(!crate::menus::enabled(&app, "file.cancelOpen")); + assert!(tx.send(result).is_err(), "nothing waits for the result"); + crate::opening::poll(&mut app); + assert!(!host::is_open(&app, KIND)); + // Continue in Background. + crate::io::open_file(&mut app, &plan, true).unwrap(); + assert_eq!(app.run("file.openInBackground", json!({})).unwrap()["hidden"], 1); + assert!(crate::opening::shown(&app).is_none() && !crate::menus::enabled(&app, "file.openInBackground")); + assert_eq!(app.ui.status, "Converting plan.dwg…"); + finish_conversions(&mut app); + assert!(host::is_open(&app, KIND)); + }); + } + /// A DWG drawing placed while it is converted goes in the document it was placed in, which - /// becomes the active one again; it is not placed when that document was closed or reverted - /// meanwhile, and the status bar says why. + /// becomes the active one again, on the layer that was current when Place started and, with + /// `replace`, in place of the object selected then; it is not placed when that document was + /// closed or reverted meanwhile, and the status bar says why. #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn a_dwg_drawing_placed_while_converted_goes_in_its_own_document() { @@ -825,7 +913,11 @@ mod tests { app.services.write = Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); let first = app.session.doc().unwrap().uid; + let bottom = app.session.doc().unwrap().active_layer; + let ink = vectorcraft_doc::NodeId(app.run("layer.new", json!({})).unwrap()["id"].as_u64().unwrap()); crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + // The user makes another layer current, then another document. + app.session.doc_mut().unwrap().active_layer = bottom; app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); let other = app.session.doc().unwrap().uid; let (before, other_before) = (undo_steps(&app, first), undo_steps(&app, other)); @@ -835,6 +927,30 @@ mod tests { host::confirm(&mut app, KIND).unwrap(); placed(&mut app); assert_eq!((undo_steps(&app, first), undo_steps(&app, other)), (before + 1, other_before)); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.parent_of(st.selection.objects[0]), Some(ink), "on the layer current when Place started"); + assert_eq!(st.active_layer, bottom, "the layer the user made current stays current"); + // Replace: the object selected when Place started is replaced, not the one selected since. + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + app.session.doc().unwrap().selection.objects[0] + }; + let replaced = rect(&mut app, 10.0); + crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); + // Meanwhile the user draws on another layer, which stays current. + app.session.doc_mut().unwrap().active_layer = Some(ink); + let selected_since = rect(&mut app, 50.0); + finish_conversions(&mut app); + host::confirm(&mut app, KIND).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert!(st.doc.node(replaced).is_none() && st.doc.node(selected_since).is_some(), "{}", app.ui.status); + assert_eq!(st.active_layer, Some(ink), "the layer the user made current stays current"); + // A selection Replace can't swap is refused at once, and nothing is converted. + app.run("select.all", json!({})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap(); + assert!(app.opening.converting.is_empty()); + assert!(app.ui.status.contains("select the one object to replace"), "{}", app.ui.status); // Closed meanwhile. crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); app.session.execute("file.close", &json!({})).unwrap(); diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 6ae7c66be0..63683cca2f 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -346,7 +346,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "file.reveal" => app.services.reveal.is_some() && app.session.active().is_some_and(|d| d.path.is_some()), "file.cancelExport" | "file.exportInBackground" => app.background.running(crate::background::Kind::Export), "file.cancelSave" | "file.saveInBackground" => app.background.running(crate::background::Kind::Save), - "file.cancelOpen" => !app.opening.pending.is_empty(), + "file.cancelOpen" => crate::opening::can_cancel(app), "file.openInBackground" => crate::opening::any_shown(app), "file.cancelPlace" => crate::placing::can_cancel(app), crate::dialogs::failed_plugins::COMMAND => vectorcraft_engine::cmd::plugin::failed_load_count(&app.session) > 0, diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 6f955c6dba..7d053a9a3f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1733,13 +1733,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.cancelOpen", "Cancel Opening", "", - "{} stop opening every file being read in the background (its progress window's Cancel): the files don't open → {cancelled: n}", + "{} stop opening every file being read in the background and every DWG drawing being converted (its progress window's Cancel): the files don't open and the drawings don't open or place → {cancelled: n}", ), ( "file.openInBackground", "Continue in Background", "", - "{} close the progress window of the files being opened; they go on being read, shown in the status bar → {hidden: n}", + "{} close the progress window of the files being opened and the DWG drawings being converted; they go on, shown in the status bar → {hidden: n}", ), ( "file.cancelPlace", diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index c41f57814b..34639ec9eb 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -50,12 +50,27 @@ pub struct Converting { name: String, /// The `file.place` params when it is being placed, else `None` (it opens). place: Option<Value>, - /// The document it is placed in ([`vectorcraft_engine::DocState::uid`]) and that document's - /// [`vectorcraft_engine::DocState::reverts`] when the conversion started, when it is placed. - placed_in: Option<(u64, u64)>, + /// Where it is placed, when it is placed. + placed_in: Option<Placement>, pub(crate) done: Receiver<Conversion>, /// The automation roots in force where the open or place started. scope: ScopeHandle, + /// Continue in Background: the progress window no longer shows it. + hidden: bool, + /// [`crate::export_progress::now`] when the conversion started. + started: f64, +} + +/// Where a DWG drawing placed while it is converted goes, taken when Place started. +pub(crate) struct Placement { + /// The document ([`vectorcraft_engine::DocState::uid`]) and its + /// [`vectorcraft_engine::DocState::reverts`]. + doc: u64, + reverts: u64, + /// Where new art went in it. + pub(crate) insertion: Option<crate::placing::Insertion>, + /// With `replace`, the object selected to be replaced, as it was. + pub(crate) replaced: Option<(vectorcraft_doc::NodeId, vectorcraft_doc::Node)>, } /// The files being read. @@ -165,10 +180,20 @@ pub(crate) fn finish_answered(app: &mut VectorcraftApp, path: &str, file: ReadFi /// Convert `bytes`, the DWG drawing `name` (at `path`, if read from a file), to DXF and read its /// layouts and units on a job of its own. Its DXF Import Options open once that is done /// ([`poll`], [`crate::dialogs::dxf_import::converted`]), to place it with the `file.place` params -/// `place` in the document active now, or else to open it. +/// `place` in the document active now, where new art goes now and, with `replace`, in place of the +/// object selected now, or else to open it. pub(crate) fn convert_drawing(app: &mut VectorcraftApp, name: &str, bytes: Vec<u8>, path: Option<String>, place: Option<Value>) { + let replace = place.as_ref().is_some_and(|p| p.get("replace").and_then(Value::as_bool) == Some(true)); let placed_in = match place { - Some(_) => app.session.doc().ok().map(|st| (st.uid, st.reverts)), + Some(_) => app.session.doc().ok().map(|st| Placement { + doc: st.uid, + reverts: st.reverts, + insertion: crate::placing::Insertion::of(app), + replaced: match &st.selection.objects[..] { + [id] if replace => st.doc.node(*id).map(|n| (*id, n.clone())), + _ => None, + }, + }), None => None, }; let (tx, done) = channel(); @@ -193,7 +218,8 @@ pub(crate) fn convert_drawing(app: &mut VectorcraftApp, name: &str, bytes: Vec<u ); let label = format!("Converting {}", fileio::file_name(name)); app.status(format!("{label}…")); - app.opening.converting.push(Converting { label, path, name: name.to_string(), place, placed_in, done, scope }); + let started = crate::export_progress::now(app); + app.opening.converting.push(Converting { label, path, name: name.to_string(), place, placed_in, done, scope, hidden: false, started }); } /// Lists the file being read for `path` and tells the status bar → `{background: true, status}`. @@ -257,14 +283,14 @@ pub fn poll(app: &mut VectorcraftApp) { // A drawing being placed is placed in the document it was placed in, which becomes the // active one again, as [`crate::placing`] places files read off the UI thread; it is not // placed when that document was closed or reverted meanwhile. - if let Some((doc, reverts)) = c.placed_in { + if let Some(placement) = &c.placed_in { let name = fileio::file_name(&c.name); - match app.session.documents().iter().position(|st| st.uid == doc) { + match app.session.documents().iter().position(|st| st.uid == placement.doc) { None => { app.status(format!("Couldn't place {name}: the document it was placed in was closed")); continue; } - Some(d) if app.session.documents()[d].reverts != reverts => { + Some(d) if app.session.documents()[d].reverts != placement.reverts => { app.status(format!("Couldn't place {name}: the document it was placed in was reverted")); continue; } @@ -273,7 +299,7 @@ pub fn poll(app: &mut VectorcraftApp) { } } } - c.scope.run(|| crate::dialogs::dxf_import::converted(app, &c.name, r, c.path, c.place.as_ref())); + c.scope.run(|| crate::dialogs::dxf_import::converted(app, &c.name, r, c.path, c.place.as_ref(), c.placed_in)); if !may_switch(app) { return; } @@ -301,49 +327,62 @@ pub fn poll(app: &mut VectorcraftApp) { } } -/// The progress window's Cancel: the files being read don't open. An importer plug-in stops -/// between two slices of its budget; a built-in reader finishes reading and the result is dropped -/// → `{cancelled: n}`. +/// The progress window's Cancel: the files being read don't open, and the DWG drawings being +/// converted don't open or place. An importer plug-in stops between two slices of its budget; a +/// built-in reader or a conversion finishes and the result is dropped → `{cancelled: n}`. pub fn cancel_all(app: &mut VectorcraftApp) -> Value { let cancelled = std::mem::take(&mut app.opening.pending); + let converting = std::mem::take(&mut app.opening.converting); for p in &cancelled { p.token.cancel(); - // The status bar no longer says it is opening. - if app.ui.status == format!("{}…", p.label) { + } + // The status bar no longer says it is opening or converting. + for label in cancelled.iter().map(|p| &p.label).chain(converting.iter().map(|c| &c.label)) { + if app.ui.status == format!("{label}…") { app.ui.status.clear(); } } - json!({ "cancelled": cancelled.len() }) + json!({ "cancelled": cancelled.len() + converting.len() }) } -/// The progress window's Continue in Background: the files go on being read, shown in the status -/// bar only → `{hidden: n}`. +/// Can a file being read, or a DWG drawing being converted, be cancelled? +pub fn can_cancel(app: &VectorcraftApp) -> bool { + !app.opening.pending.is_empty() || !app.opening.converting.is_empty() +} + +/// The progress window's Continue in Background: the files go on being read, and the drawings +/// converted, shown in the status bar only → `{hidden: n}`. pub fn hide_all(app: &mut VectorcraftApp) -> Value { let mut n = 0; - for p in app.opening.pending.iter_mut().filter(|p| !p.hidden) { - p.hidden = true; - n += 1; + for hidden in app.opening.pending.iter_mut().map(|p| &mut p.hidden).chain(app.opening.converting.iter_mut().map(|c| &mut c.hidden)) { + if !*hidden { + *hidden = true; + n += 1; + } } json!({ "hidden": n }) } -/// Is a file being read that the progress window shows? +/// Is a file being read, or a DWG drawing being converted, that the progress window shows? pub fn any_shown(app: &VectorcraftApp) -> bool { - app.opening.pending.iter().any(|p| !p.hidden) + app.opening.pending.iter().any(|p| !p.hidden) || app.opening.converting.iter().any(|c| !c.hidden) } -/// The progress window's entry for the first file being read it shows. +/// The progress window's entry for the first file being read, or drawing being converted, it +/// shows. pub(crate) fn shown(app: &VectorcraftApp) -> Option<Shown> { - let waiting: Vec<&Pending> = app.opening.pending.iter().filter(|p| !p.hidden).collect(); - let first = *waiting.first()?; + let pending = app.opening.pending.iter().filter(|p| !p.hidden).map(|p| (&p.label, p.started)); + let converting = app.opening.converting.iter().filter(|c| !c.hidden).map(|c| (&c.label, c.started)); + let waiting: Vec<(&String, f64)> = pending.chain(converting).collect(); + let &(label, started) = waiting.first()?; let more = waiting.len() - 1; Some(Shown { - title: format!("{}…", crate::i18n::msg(&first.label)), + title: format!("{}…", crate::i18n::msg(label)), step: tl!("Reading the file…").to_string(), fraction: None, counts: None, queued: (more > 0).then(|| crate::i18n::tn(more as u64, "{n} more file waiting", "{n} more files waiting").to_string()), - started: first.started, + started, cancel: "file.cancelOpen", hide: Some("file.openInBackground"), }) diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 9d972c06a5..b170091261 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -61,9 +61,10 @@ struct Paste { /// Where new art goes in the active document: the current layer, the isolated group or object, and /// the drawing mode with the object Draw Inside draws into. A paste and a placed file read off the -/// UI thread keep the one from when they were given. +/// UI thread keep the one from when they were given, and so does a DWG drawing placed while it is +/// converted ([`crate::opening::convert_drawing`]). #[derive(Clone, PartialEq)] -struct Insertion { +pub(crate) struct Insertion { layer: Option<vectorcraft_doc::NodeId>, isolation: Option<vectorcraft_doc::NodeId>, draw_mode: vectorcraft_engine::DrawMode, @@ -72,13 +73,13 @@ struct Insertion { impl Insertion { /// Where new art goes in `app`'s active document now. - fn of(app: &VectorcraftApp) -> Option<Self> { + pub(crate) fn of(app: &VectorcraftApp) -> Option<Self> { let st = app.session.doc().ok()?; Some(Self { layer: st.active_layer, isolation: st.isolation, draw_mode: app.session.draw_mode, draw_inside: app.session.draw_inside }) } /// Make it where new art goes in `app`'s active document → where new art went before. - fn set(self, app: &mut VectorcraftApp) -> Option<Self> { + pub(crate) fn set(self, app: &mut VectorcraftApp) -> Option<Self> { let st = app.session.doc_mut().ok()?; let (layer, isolation) = (std::mem::replace(&mut st.active_layer, self.layer), std::mem::replace(&mut st.isolation, self.isolation)); let draw_mode = std::mem::replace(&mut app.session.draw_mode, self.draw_mode); @@ -104,7 +105,7 @@ impl Insertion { /// `self` when new art can still go there ([`Self::usable`]), else `now`: where new art went /// before the paste or the place selected anything again. - fn or_now(self, now: Option<&Self>, app: &VectorcraftApp, draws_inside: bool) -> Self { + pub(crate) fn or_now(self, now: Option<&Self>, app: &VectorcraftApp, draws_inside: bool) -> Self { match now { Some(now) if !self.usable(app, draws_inside) => now.clone(), _ => self, @@ -114,7 +115,7 @@ impl Insertion { /// Put back each part of `self` (where new art went before [`Self::set`] set `started`) that /// differs from `started`, what the user changed meanwhile; a part the paste or the place /// itself changed stays as it left it. - fn restore_changed(self, started: &Self, app: &mut VectorcraftApp) { + pub(crate) fn restore_changed(self, started: &Self, app: &mut VectorcraftApp) { if let Ok(st) = app.session.doc_mut() { if self.layer != started.layer { st.active_layer = self.layer; diff --git a/docs/mcp.md b/docs/mcp.md index 6c9a50e773..af13970bc4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12590,6 +12590,11 @@ In the desktop app and `vectorcraft-cli` the conversion runs in a copy of the pr a damaged file stops that copy, not the app; it gives up after 30 minutes. Files over 512 MiB, or whose DXF would pass 1 GiB, are refused. What the conversion skips (objects of types it can't read) is listed in `warnings`. R1.x and R2.x drawings (`MC0.`, `AC1.` and `AC2.` headers) and the web build answer an error saying to save the drawing as DXF. +When the user opens or places a DWG drawing in the desktop app, it is converted off the UI thread: the status bar and, +after 0.4 s, the open progress window show it (`file.cancelOpen` drops it, `file.openInBackground` closes the window), +and its DXF Import Options open once it is converted. A drawing being placed goes in the document, on the layer and +(with `replace`) in place of the object that were current when Place started; it is not placed when that document +was closed or reverted meanwhile, or when the object to replace was changed or deleted. ```json {"name":"run_command","arguments":{"command":"document.dxfInfo","params":{"path":"/tmp/plan.dxf"}}} From d4670a94cf92f5ae6fc8fee3580598d8a406e8c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 04:20:45 -0800 Subject: [PATCH 089/103] File formats: a DWG being placed can still be opened, and a worker ends by its deadline - File > Open of a DWG drawing that is being converted for Place no longer does nothing: only conversions started for opening count as that file already being opened. - A DWG worker gets an absolute deadline (`--dwg-worker-until`, in milliseconds since the UNIX epoch) instead of a time limit counted from its own start. `thumbnail` sets it when its own timer starts, so a worker started late no longer outlives the thumbnail process. A worker whose deadline has passed exits with code 1 at once. --- apps/vectorcraft-cli/tests/it/fileio.rs | 32 +++++++++++++----------- crates/cad/src/dwg.rs | 29 +++++++++++++-------- crates/ui-egui/src/dialogs/dxf_import.rs | 17 +++++++++++++ crates/ui-egui/src/io/open.rs | 2 +- crates/ui-egui/src/opening.rs | 7 ++++++ 5 files changed, 61 insertions(+), 26 deletions(-) diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 95922dc497..2842559bfc 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -421,21 +421,25 @@ fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() { } } -/// A DWG worker started with a time limit (as `thumbnail` starts one) exits with code 1 once the -/// time is up, even while it still waits for its drawing, so `thumbnail`'s exit leaves no -/// conversion running. +/// A DWG worker started with a deadline (as `thumbnail` starts one) exits with code 1 once the +/// deadline passes, even while it still waits for its drawing, and at once when it has already +/// passed, so `thumbnail`'s exit leaves no conversion running. #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() { - let mut worker = Command::new(crate::bin()) - .args(["--dwg-worker", "--dwg-worker-seconds", "1"]) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::null()) - .spawn() - .unwrap(); - // Its input stays open, so the worker never gets the whole request. - let input = worker.stdin.take(); - let status = worker.wait().unwrap(); - drop(input); - assert_eq!(status.code(), Some(1), "{status:?}"); + let now = std::time::SystemTime::now(); + for until in [now + std::time::Duration::from_secs(1), now - std::time::Duration::from_secs(1)] { + let millis = until.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis().to_string(); + let mut worker = Command::new(crate::bin()) + .args(["--dwg-worker", "--dwg-worker-until", &millis]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + // Its input stays open, so the worker never gets the whole request. + let input = worker.stdin.take(); + let status = worker.wait().unwrap(); + drop(input); + assert_eq!(status.code(), Some(1), "{status:?}"); + } } diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index bd64dd1149..d72f77c83e 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -10,9 +10,9 @@ use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak}; pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; -/// The worker argument after [`WORKER_ARG`] that gives the most seconds the worker runs +/// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch /// ([`use_own_worker_for`]). -const WORKER_SECONDS_ARG: &str = "--dwg-worker-seconds"; +const WORKER_UNTIL_ARG: &str = "--dwg-worker-until"; /// Serve one conversion and return the exit code if this process was started as a worker. A /// worker started by [`use_own_worker_for`] exits with code 1 once its time is up, wherever the @@ -22,25 +22,32 @@ pub fn serve_if_asked() -> Option<i32> { if args.next()? != WORKER_ARG { return None; } - if args.next().is_some_and(|a| a == WORKER_SECONDS_ARG) - && let Some(seconds) = args.next().and_then(|s| s.to_str()?.parse::<u64>().ok()) + if args.next().is_some_and(|a| a == WORKER_UNTIL_ARG) + && let Some(millis) = args.next().and_then(|s| s.to_str()?.parse::<u64>().ok()) + && let Some(until) = std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_millis(millis)) { + if until <= std::time::SystemTime::now() { + return Some(1); + } std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_secs(seconds)); + std::thread::sleep(until.duration_since(std::time::SystemTime::now()).unwrap_or_default()); std::process::exit(1); }); } craft_dwg::serve_if_asked() } -/// [`use_own_worker`], each worker exiting once `limit` (in whole seconds, at least 1) is up, so a -/// program that ends after `limit` leaves no conversion running. If this program's path can't be -/// found, the worker setting does not change. Web builds have no worker. +/// [`use_own_worker`], each worker exiting once `limit` from this call is up (a deadline passed to it +/// in milliseconds since the UNIX epoch), however late it starts, so a program that ends after +/// `limit` leaves no conversion running. If this program's path can't be found, or the deadline +/// can't be written, the worker setting does not change. Web builds have no worker. pub fn use_own_worker_for(limit: std::time::Duration) { #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] - if let Ok(program) = std::env::current_exe() { - let seconds = limit.as_secs().max(1).to_string(); - craft_dwg::worker::use_worker(program, vec![WORKER_ARG.into(), WORKER_SECONDS_ARG.into(), seconds.into()]); + if let Ok(program) = std::env::current_exe() + && let Some(until) = std::time::SystemTime::now().checked_add(limit).and_then(|until| until.duration_since(std::time::UNIX_EPOCH).ok()) + && let Ok(millis) = u64::try_from(until.as_millis()) + { + craft_dwg::worker::use_worker(program, vec![WORKER_ARG.into(), WORKER_UNTIL_ARG.into(), millis.to_string().into()]); } #[cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))] let _ = limit; diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index ce05994234..fed98a8064 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -888,6 +888,23 @@ mod tests { }); } + /// File › Open of a DWG drawing being converted for Place converts it for opening too. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_being_placed_can_also_be_opened() { + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-place-open"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + crate::io::open_file(&mut app, &plan, true).unwrap(); + assert_eq!(app.opening.converting.len(), 2); + finish_conversions(&mut app); + }); + } + /// A DWG drawing placed while it is converted goes in the document it was placed in, which /// becomes the active one again, on the layer that was current when Place started and, with /// `replace`, in place of the object selected then; it is not placed when that document was diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index f22c0b9609..dce5bac6e5 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -641,7 +641,7 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va if let Some(r) = try_activate_open_document(app, path, canonical.as_deref())? { return Ok(r); } - if app.opening.pending.iter().any(|p| same(&p.path)) || app.opening.converting.iter().any(|c| c.path.as_deref().is_some_and(&same)) { + if app.opening.pending.iter().any(|p| same(&p.path)) || app.opening.converting.iter().any(|c| c.opens() && c.path.as_deref().is_some_and(&same)) { return Ok(Value::Null); } // A shortcut set is read by Import Shortcut Set, up to its reader's cap. diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 34639ec9eb..214b0e56f2 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -61,6 +61,13 @@ pub struct Converting { started: f64, } +impl Converting { + /// Is this drawing being converted for opening? + pub(crate) fn opens(&self) -> bool { + self.place.is_none() + } +} + /// Where a DWG drawing placed while it is converted goes, taken when Place started. pub(crate) struct Placement { /// The document ([`vectorcraft_engine::DocState::uid`]) and its From 826c92f7b6fa3080773d8533afed9f4f54bcc833 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 04:44:48 -0800 Subject: [PATCH 090/103] File formats: a placed DWG keeps its conversion until its read is done A DWG drawing placed through its import options was read off the UI thread after the dialog had closed and dropped the drawing's conversion, so a drawing whose DXF is over 128 MiB, or whose cache entry another conversion had replaced, was converted again for that read. The dialog's OK now hands the conversion to the place read it starts (`placing::Placing::keep_next`), which keeps it until the file is placed, canceled or dropped. --- crates/ui-egui/src/dialogs/dxf_import.rs | 36 +++++++++++++++++++++--- crates/ui-egui/src/placing.rs | 16 +++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index fed98a8064..91d8a8cd5a 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -83,9 +83,10 @@ struct Source { /// A DWG drawing converted off the UI thread ([`converted`]). pub(crate) struct Converted { - /// Its conversion, kept while the dialog is open so that its previews and its OK read the - /// drawing without converting it again. - _held: vectorcraft_cad::dwg::Held, + /// Its conversion, kept while the dialog is open, and for a place until the place's read is + /// done ([`crate::placing::Placing::keep_next`]), so that its previews, its OK and that read + /// read the drawing without converting it again. + held: vectorcraft_cad::dwg::Held, /// Where it is placed, taken when Place started; `None` when it opens. placement: Option<crate::opening::Placement>, } @@ -399,7 +400,7 @@ pub(crate) fn converted( match info { Ok((info, held)) => { let opens = place.is_none(); - if show(app, name, &bytes, path.clone(), place, &info, Some(Converted { _held: held, placement })) + if show(app, name, &bytes, path.clone(), place, &info, Some(Converted { held, placement })) && opens && let Some(path) = &path { @@ -516,7 +517,11 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R insertion.clone().set(app); insertion }); + if let Some(converted) = &source.converted { + app.placing.keep_next = Some(Box::new(converted.held.clone())); + } let r = crate::place::run_for_user(app, &p).map(|_| ()); + app.placing.keep_next = None; if let (Some(current), Some(insertion)) = (current, restore) { current.restore_changed(&insertion, app); } @@ -905,6 +910,29 @@ mod tests { }); } + /// A DWG drawing converted off the UI thread and placed keeps its conversion until the place + /// read off the UI thread is done. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_conversion_is_kept_for_the_pending_read() { + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-pending-hold"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + finish_conversions(&mut app); + host::confirm(&mut app, KIND).unwrap(); + assert!(app.placing.pending.first().is_some_and(crate::placing::Pending::holds_conversion)); + assert!(app.placing.keep_next.is_none()); + while !app.placing.pending.is_empty() { + crate::placing::wait(&mut app); + crate::placing::poll(&mut app); + } + }); + } + /// A DWG drawing placed while it is converted goes in the document it was placed in, which /// becomes the active one again, on the layer that was current when Place started and, with /// `replace`, in place of the object selected then; it is not placed when that document was diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index b170091261..a1eeb20879 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -182,12 +182,26 @@ pub struct Pending { pub hidden: bool, /// [`crate::export_progress::now`] when the read started. pub(crate) started: f64, + /// What stays alive until this entry is removed ([`Placing::keep_next`]). + _keep: Option<Box<dyn std::any::Any + Send>>, +} + +#[cfg(test)] +impl Pending { + /// Does this entry keep a DWG drawing's conversion? + pub(crate) fn holds_conversion(&self) -> bool { + self._keep.as_ref().is_some_and(|keep| keep.is::<vectorcraft_cad::dwg::Held>()) + } } /// The files being read for Place, in the order they were started. #[derive(Default)] pub struct Placing { pub pending: Vec<Pending>, + /// What the next read started ([`spawn_labeled`]) keeps alive until it is placed, canceled or + /// dropped: the conversion of a DWG drawing placed through its import options, which the read + /// then finds without converting the drawing again. + pub(crate) keep_next: Option<Box<dyn std::any::Any + Send>>, /// A deferred paste awaiting its own Swatch Conflict dialog. swatch_paste: Option<PendingSwatch>, /// Set by unit tests whose app reads the files the user places off the UI thread. @@ -417,6 +431,7 @@ fn spawn_labeled( let jobs = app.jobs(); app.placing.lane.push(&*jobs, "vectorcraft-place", job); let started = crate::export_progress::now(app); + let keep = app.placing.keep_next.take(); app.placing.pending.push(Pending { name, label: label.clone(), @@ -430,6 +445,7 @@ fn spawn_labeled( token, hidden: false, started, + _keep: keep, }); let status = format!("{label}…"); app.status(status.clone()); From 2c7f37723ccd62a67dad5ff8a88d7f3c455334a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 05:01:40 -0800 Subject: [PATCH 091/103] File formats: a converted DWG's OK checks the document it is placed in The DXF Import Options of a DWG drawing converted for Place checked its document only before opening. When that document was closed, reverted or no longer active by the time of OK (a script or the control channel can switch documents while the dialog is open), OK placed the drawing in whatever document was active. OK now refuses with the reason, changes nothing and keeps the dialog open; the choices are remembered only when OK goes ahead. --- crates/ui-egui/src/dialogs/dxf_import.rs | 38 ++++++++++++++++++++++-- crates/ui-egui/src/opening.rs | 32 ++++++++++++-------- 2 files changed, 55 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 91d8a8cd5a..a01076a838 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -491,12 +491,16 @@ fn options(c: &DxfChoices) -> Value { /// OK: open or place the drawing with the choices; an error keeps the dialog open. fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> Result<(), String> { let dxf = options(choices); - app.ui.dxf_import = Value::Object(REMEMBERED.iter().map(|k| (k.to_string(), dxf[*k].clone())).collect()); + let remembered = Value::Object(REMEMBERED.iter().map(|k| (k.to_string(), dxf[*k].clone())).collect()); match &source.place { Some(place) => { + let placement = source.converted.as_ref().and_then(|c| c.placement.as_ref()); + if let Some(placement) = placement { + placement.check(app)?; + } + app.ui.dxf_import = remembered; let mut p = with_file(place, source.path.as_deref(), &source.name, &source.file); p["dxf"] = dxf; - let placement = source.converted.as_ref().and_then(|c| c.placement.as_ref()); // Where new art goes now is taken before Replace selects the object it swaps again. let current = placement.and_then(|_| crate::placing::Insertion::of(app)); // A drawing converted off the UI thread replaces the object selected when Place @@ -527,7 +531,10 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R } r } - None => io::open_document(app, &source.name, &source.file.bytes, source.path.clone(), &json!({ "dxf": dxf })).map(|_| ()), + None => { + app.ui.dxf_import = remembered; + io::open_document(app, &source.name, &source.file.bytes, source.path.clone(), &json!({ "dxf": dxf })).map(|_| ()) + } } } @@ -1017,6 +1024,31 @@ mod tests { }); } + /// Switching documents while the import dialog is open leaves both documents unchanged. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn a_dwg_drawing_cannot_be_placed_after_switching_documents_in_its_dialog() { + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-place-dialog-switch"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let first = app.session.doc().unwrap().uid; + let before = app.session.doc().unwrap().history.undo.len(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + finish_conversions(&mut app); + assert!(host::is_open(&app, KIND)); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let other_before = app.session.doc().unwrap().history.undo.len(); + let error = host::confirm(&mut app, KIND).unwrap_err(); + assert!(error.contains("not the active document"), "{error}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), other_before); + let first = app.session.documents().iter().find(|st| st.uid == first).unwrap(); + assert_eq!(first.history.undo.len(), before); + }); + } + #[test] fn placing_a_drawing_asks_then_places_one_group() { let mut app = host::app(); diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 214b0e56f2..5c08b2e2fe 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -80,6 +80,20 @@ pub(crate) struct Placement { pub(crate) replaced: Option<(vectorcraft_doc::NodeId, vectorcraft_doc::Node)>, } +impl Placement { + /// Is the document it was placed in still open, unreverted and active? + pub(crate) fn check(&self, app: &VectorcraftApp) -> Result<(), String> { + let st = app.session.documents().iter().find(|st| st.uid == self.doc).ok_or("the document it was placed in was closed")?; + if st.reverts != self.reverts { + return Err("the document it was placed in was reverted".into()); + } + if !app.session.doc().is_ok_and(|st| st.uid == self.doc) { + return Err("the document it was placed in is not the active document".into()); + } + Ok(()) + } +} + /// The files being read. #[derive(Default)] pub struct Opening { @@ -292,18 +306,12 @@ pub fn poll(app: &mut VectorcraftApp) { // placed when that document was closed or reverted meanwhile. if let Some(placement) = &c.placed_in { let name = fileio::file_name(&c.name); - match app.session.documents().iter().position(|st| st.uid == placement.doc) { - None => { - app.status(format!("Couldn't place {name}: the document it was placed in was closed")); - continue; - } - Some(d) if app.session.documents()[d].reverts != placement.reverts => { - app.status(format!("Couldn't place {name}: the document it was placed in was reverted")); - continue; - } - Some(d) => { - app.session.set_active(d); - } + if let Some(d) = app.session.documents().iter().position(|st| st.uid == placement.doc && st.reverts == placement.reverts) { + app.session.set_active(d); + } + if let Err(e) = placement.check(app) { + app.status(format!("Couldn't place {name}: {e}")); + continue; } } c.scope.run(|| crate::dialogs::dxf_import::converted(app, &c.name, r, c.path, c.place.as_ref(), c.placed_in)); From 177d0c670088f93099692c95fab0a3194724f3e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 05:56:09 -0800 Subject: [PATCH 092/103] Shapes: a whole star stays live whatever its pie angles hold A whole star draws every point, so its pie angles no longer stop it from being stored as a live star. Angles configured on any whole shape are stored with it, so a later arc mode change uses them. A corner list longer than the old corner count drops its entries past the last corner before it is spread, so the corners a new point or side count adds are sharp and keep the default kind. --- crates/doc/src/node/live_shape.rs | 4 +- crates/doc/src/node/tests.rs | 27 ++++++++++++ crates/engine/src/cmd/addons/shapes/tests.rs | 24 ++++++++++ crates/tools/src/addons/box3d.rs | 46 +++++++++++--------- 4 files changed, 80 insertions(+), 21 deletions(-) diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index f1419d9e95..33b3f10868 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -415,8 +415,10 @@ fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> { /// Give a corner list for `old` corners `n` entries: one value all `old` corners shared fills it; /// otherwise entries past its end are the default (sharp, round) and entries past `n` go. A list /// shorter than `old` holds the default for its missing corners, so it is shared only when that -/// default is. An empty list stays empty. +/// default is; entries of a longer list past `old` name no corner and go first. An empty list +/// stays empty. fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, old: usize, n: usize) { + v.truncate(old); if !v.is_empty() && v.len() < old { v.resize(old, T::default()); } diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 555a4f349d..2ecdda06bd 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -202,6 +202,33 @@ fn a_short_corner_list_keeps_its_missing_corners_sharp() { assert!(matches!(&polygon, LiveShape::Polygon { radii, .. } if *radii == want), "{polygon:?}"); } +/// A corner list longer than the corners drops its entries past the old last corner, so the +/// corners a new point count adds are sharp and keep the default kind. +#[test] +fn a_long_corner_list_drops_its_entries_past_the_corners() { + let mut radii = vec![0.0; 12]; + radii[0] = 2.0; + radii[10] = 7.0; + radii[11] = 7.0; + let mut kinds = vec![CornerKind::Round; 12]; + kinds[0] = CornerKind::Chamfer; + kinds[10] = CornerKind::Chamfer; + kinds[11] = CornerKind::Chamfer; + let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii, kinds, radii_relative: false }; + star.set_points(6); + let mut want_radii = vec![0.0; 12]; + want_radii[0] = 2.0; + let mut want_kinds = vec![CornerKind::Round; 12]; + want_kinds[0] = CornerKind::Chamfer; + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want_radii), "{star:?}"); + assert!(matches!(&star, LiveShape::Star { kinds, .. } if *kinds == want_kinds), "{star:?}"); + // A complete list that all corners share still fills the new corners. + let mut star = + LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![3.0; 10], kinds: vec![], radii_relative: false }; + star.set_points(6); + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == vec![3.0; 12]), "{star:?}"); +} + #[test] fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { let close = |a: f64, b: f64| (a - b).abs() < 1e-9; diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs index 9839c1ed26..274678dd62 100644 --- a/crates/engine/src/cmd/addons/shapes/tests.rs +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -182,6 +182,30 @@ fn configuring_a_live_star_keeps_a_small_ratio() { assert_eq!(path, &live.to_path()); } +/// Angles configured on a whole shape stay live and are kept for a later arc mode. +#[test] +fn angles_configured_on_a_whole_shape_are_kept_for_a_later_arc_mode() { + let mut s = new_session(); + let shapes = [ + ("shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})), + ("shape.polygon", json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5})), + ("shape.rectangle", json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 50.0})), + ("shape.ellipse", json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})), + ]; + for (cmd, p) in shapes { + let id = id_of(&mut s, cmd, p); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "startAngle": 0.0, "endAngle": 90.0})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(_), .. }), "{cmd} stays live"); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "arcMode": "pie"})).unwrap(); + let pie = match CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()) { + Some(CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. }) => pie, + other => panic!("{cmd}: {other:?}"), + }; + assert_eq!(pie, (0.0, 90.0), "{cmd}"); + } +} + /// Runs `cmd` with `p`, which must fail with `msg` and leave the document and its history as they /// were. fn refused(s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str) { diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index 4ff528e583..7ac8a008b0 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -201,22 +201,8 @@ impl CustomShape { }) } CustomShape::Polygon { - radius, - sides, - xf, - radii, - kinds, - radii_relative, - spoke_ratio: Some(ratio), - rounded, - randomized, - pie, - arc_mode, - } if (0.0..=1.0).contains(ratio) && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole && { - let span = (pie.1 - pie.0).rem_euclid(360.0); - span < 1e-9 || 360.0 - span < 1e-9 - } => - { + radius, sides, xf, radii, kinds, radii_relative, spoke_ratio: Some(ratio), rounded, randomized, arc_mode, .. + } if (0.0..=1.0).contains(ratio) && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole => { Some(LiveShape::Star { r1: *radius, r2: *radius * ratio, @@ -233,7 +219,13 @@ impl CustomShape { /// Whether this shape uses extended add-on parameters beyond what `LiveShape` stores on its own. pub fn needs_extra_storage(&self) -> bool { - self.to_live_shape().is_none() + // A whole shape's `LiveShape` keeps no angles, so angles set for a later arc mode are + // stored with it. + let angles = match self { + CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. } => *pie != (0.0, 360.0), + _ => false, + }; + self.to_live_shape().is_none() || angles } /// Write this shape's regenerated path, `LiveShape` (if standard) and `vc-shape-tools` attribute @@ -315,9 +307,14 @@ impl CustomShape { LiveShape::Ellipse { w, h, pie, xf } => { let span = (pie.1 - pie.0).rem_euclid(360.0); let default_mode = if span < 1e-9 || 360.0 - span < 1e-9 { EllipseMode::Whole } else { EllipseMode::Slice }; - let arc_mode = match stored { - Some(CustomShape::Ellipse { arc_mode, .. }) if default_mode != EllipseMode::Slice => arc_mode, - _ => default_mode, + let (pie, arc_mode) = match stored { + // A whole ellipse's `LiveShape` draws the full turn; its stored angles wait + // for another arc mode. + Some(CustomShape::Ellipse { arc_mode: EllipseMode::Whole, pie: angles, .. }) if default_mode != EllipseMode::Slice => { + (angles, EllipseMode::Whole) + } + Some(CustomShape::Ellipse { arc_mode, .. }) if default_mode != EllipseMode::Slice => (pie, arc_mode), + _ => (pie, default_mode), }; Some(CustomShape::Ellipse { w, h, pie, arc_mode, xf }) } @@ -857,4 +854,13 @@ mod tests { let Some(LiveShape::Star { points, .. }) = read_back(Some(0.5), 0).to_live_shape() else { panic!("a live star") }; assert_eq!(points, 2); } + + /// A whole star draws every point whatever its pie angles hold, so it stays live. + #[test] + fn a_whole_star_with_other_pie_angles_is_live() { + let mut star = read_back(Some(0.5), 5); + let CustomShape::Polygon { pie, .. } = &mut star else { panic!("a polygon") }; + *pie = (0.0, 90.0); + assert!(matches!(star.to_live_shape(), Some(LiveShape::Star { points: 5, .. })), "{star:?}"); + } } From 1b59dcb3ac0ccc75591d566070365248f0368167 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Fri, 4 Dec 2026 09:11:23 -0500 Subject: [PATCH 093/103] docs: specify the FreeBSD release requirement --- README.md | 2 ++ docs/releasing.md | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3280824dc8..df83d9e9dd 100644 --- a/README.md +++ b/README.md @@ -316,6 +316,8 @@ RISC-V (riscv64) packages are `vectorcraft-<ver>-linux-riscv64.deb`, ### FreeBSD +Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds. + | Build | File | |---|---| | x86_64 | `vectorcraft-<ver>-freebsd-x86_64.tar.gz` | diff --git a/docs/releasing.md b/docs/releasing.md index 3a4969acca..0d661caf5a 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -61,7 +61,7 @@ the host Flatpak interface, and read-only access to the shared version choices. | Linux riscv64 | `vectorcraft-<v>-linux-riscv64.tar.gz` (cross-compiled, glibc >= 2.39; CLI smoke-tested under QEMU) | `ubuntu-24.04` | | Linux AppImage updates | `vectorcraft-<v>-linux-{x86_64,aarch64}.AppImage.zsync` | with the AppImages | | Flatpak x86_64, aarch64 | `vectorcraft-<v>-linux-{x86_64,aarch64}.flatpak` | `ubuntu-24.04`, `ubuntu-24.04-arm` (repackages the Linux tarball) | -| FreeBSD 14 x86_64 | `vectorcraft-<v>-freebsd-x86_64.tar.gz` | a FreeBSD 14.3 VM on `ubuntu-latest` | +| FreeBSD 15.1+ x86_64 | `vectorcraft-<v>-freebsd-x86_64.tar.gz` | a FreeBSD 15.1 VM on `ubuntu-latest` | | Web | `vectorcraft-web-<v>.zip`, a static site (see [`packaging/web/README.md`](../packaging/web/README.md)) | `ubuntu-latest` | `vectorcraft --version` and `vectorcraft-cli --version` print the version from `Cargo.toml`. @@ -221,8 +221,8 @@ keeps the runtime and sandbox permissions of the two manifests identical. ### FreeBSD -GitHub has no FreeBSD runners, so the job builds in a FreeBSD 14.3 VM on `ubuntu-latest` (the same -image as `.github/workflows/freebsd.yml`). `packaging/freebsd/package.sh` writes a +The shared release workflow builds in a FreeBSD 15.1 VM on `ubuntu-latest`. +Prebuilt archives target FreeBSD 15.1 or newer, not FreeBSD 14.x. `packaging/freebsd/package.sh` writes a `/usr/local`-style tree; users install it with `tar -xzf vectorcraft-*-freebsd-x86_64.tar.gz --strip-components 1 -C /usr/local`. From 31f86b52b5b20294eccf91a2f9896504931f3054 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 06:37:21 -0800 Subject: [PATCH 094/103] xtask: test-lint follows redirects, closure uses and saved counts exactly Workflow environment scan: - A command whose standard output is redirected (`echo "N=x" >/dev/null |& tee -a "$GITHUB_ENV"`) does not set the variable; the same pipeline without the redirect still does. - `env` reads assignments only before its child command, so `env printf '%s' "N=x"` passes the word to `printf`. - A line break after `|` or `|&` continues the pipeline. - A line continuation inside a name (`MY_\` and `SAMPLES=x` on the next line) is removed before names are read; single-quoted text is kept as it is. Test reads: - Closure names are read past the 1 KiB decode window and with combining marks. - A unary `-` or `!` stays inside a cast's operand (`-Kind::A as i8`). - A closure called only from a closure that never runs is not run; statements are judged last first against the code kept so far. - An async closure's future passed to `drop` or `std::mem::drop` is not polled. - `fallback(xs).len()` is a size check of the call's result, not of `xs`; `(xs).len() == 2` keeps its exact bound. - An index shows `k + 1` items (`xs[0]` does not guard `xs.windows(2)`), and an index after the assertion counts only while nothing in between changes the collection. - Turbofish arguments neither end a selector closure nor count as selector locals. - A count through `by_ref()` consumes its source. - A saved count (`let n = xs.len()`) guards only `xs`, with its compared bound. - `(status.success() && dest.exists()) == true` is not status-only. - Brackets inside const arguments are skipped when tracking open generic lists, so a shift after them stays visible. - Every grouping layer around a constructor is unwrapped before a field is read. - A raw identifier (`r#loop`) does not open an iterator block. --- xtask/src/test_lint.rs | 515 +++++++++++++++++++++++++++++++++++------ 1 file changed, 442 insertions(+), 73 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index d533a2dafe..21fc9a33a1 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1286,22 +1286,106 @@ fn workflow_scalar(line: &str) -> Option<String> { } /// Whether the text at `from` is an argument of an `echo` or `printf` command, and that command's -/// pipeline does not write to `$GITHUB_ENV` ([`writes_env_file`]). +/// output does not reach a `$GITHUB_ENV` writer ([`env_file_receives`]). fn printed(line: &str, from: usize) -> bool { let (start, end) = shell_command(line, from); - command_word(&line[start..from]).is_some_and(|w| matches!(w, "echo" | "printf")) && !writes_env_file(&line[start..end]) + command_word(&line[start..from]).is_some_and(|w| matches!(w, "echo" | "printf")) && !env_file_receives(&line[start..end], from - start) } /// Whether the shell command that holds the word at `word` reads it as an assignment: an `export`, -/// `env`, `declare`, `local`, `readonly` or `typeset` command, or a pipeline that writes to -/// `$GITHUB_ENV` ([`writes_env_file`]). The setter has to be the command itself, not one of its -/// arguments (`cargo test -- env "N=x"`). A path-qualified program (`/usr/bin/env`) is named by its -/// last segment. +/// `env`, `declare`, `local`, `readonly` or `typeset` command, or a pipeline whose `$GITHUB_ENV` +/// writer receives the word's output ([`env_file_receives`]). The setter has to be the command +/// itself, not one of its arguments (`cargo test -- env "N=x"`). A path-qualified program +/// (`/usr/bin/env`) is named by its last segment. `env` reads assignments only up to its child +/// command (`env printf '%s' "N=x"` passes the word to `printf`). fn assigned_by_command(line: &str, word: usize) -> bool { let (start, end) = shell_command(line, word); - command_word(&line[start..word]) - .is_some_and(|w| ["export", "env", "declare", "local", "readonly", "typeset"].contains(&w.rsplit('/').next().unwrap_or(w))) - || writes_env_file(&line[start..end]) + let text = &line[start..word]; + let setter = command_word(text).is_some_and(|w| { + let name = w.rsplit('/').next().unwrap_or(w); + // `w` is a slice of `text`, so this is where it ends there. + let after = w.as_ptr() as usize - text.as_ptr() as usize + w.len(); + ["export", "env", "declare", "local", "readonly", "typeset"].contains(&name) && (name != "env" || env_operands(&text[after..])) + }); + setter || env_file_receives(&line[start..end], word - start) +} + +/// Whether every word of `text`, the arguments of an `env` command before a word, is an option or an +/// assignment, so `env` has not reached its child command yet. `-u` and `-C` take the next word. +fn env_operands(text: &str) -> bool { + let mut words = shell_words(text).into_iter(); + while let Some(w) = words.next() { + let bare = w.trim_matches(['"', '\'']); + if matches!(bare, "-u" | "--unset" | "-C" | "--chdir") { + words.next(); + } else if !(bare.starts_with('-') || shell_assignment(bare)) { + return false; + } + } + true +} + +/// Whether `command` writes `$GITHUB_ENV` ([`writes_env_file`]) and the pipeline command that holds +/// offset `word` sends its output there: it is the writer itself, or it leaves its standard output +/// on the pipe. A redirection of standard output (`echo "N=x" > /dev/null |& tee -a +/// "$GITHUB_ENV"`) sends it elsewhere; with `|&`, Bash joins standard error to the pipe after the +/// command's own redirections. +fn env_file_receives(command: &str, word: usize) -> bool { + if !writes_env_file(command) { + return false; + } + let pipes: Vec<usize> = shell_separators(command).into_iter().filter(|s| s.pipe).map(|s| s.end).collect(); + let start = pipes.iter().copied().rfind(|&e| e <= word).unwrap_or(0); + let end = pipes.iter().copied().find(|&e| e > word).map_or(command.len(), |e| e - if command[..e].ends_with("|&") { 2 } else { 1 }); + let element = &command[start..end]; + writes_env_file(element) || !redirects_stdout(element) +} + +/// Whether a pipeline command redirects its own standard output (`> file`, `1>> file`, `&> file`, +/// `>&2`), outside quotes and outside the `( … )` and `{ … }` groups it holds. +fn redirects_stdout(element: &str) -> bool { + let b = element.as_bytes(); + let (mut quote, mut escaped, mut depth) = (None, false, 0usize); + for (i, &c) in b.iter().enumerate() { + if escaped { + escaped = false; + continue; + } + if c == b'\\' && quote != Some(b'\'') { + escaped = true; + continue; + } + if let Some(q) = quote { + if q == c { + quote = None; + } + continue; + } + match c { + b'\'' | b'"' => quote = Some(c), + b'(' | b'{' => depth += 1, + b')' | b'}' => depth = depth.saturating_sub(1), + b'>' if depth == 0 && (i == 0 || !matches!(b[i - 1], b'>' | b'<')) => { + // A descriptor number counts only when it is a whole word (`2>`, not `a2>`). + let digits = b[..i].iter().rev().take_while(|d| d.is_ascii_digit()).count(); + let from = i - digits; + let fd = if from == 0 || b[from - 1].is_ascii_whitespace() { &element[from..i] } else { "" }; + if fd.is_empty() || fd == "1" { + return true; + } + } + _ => {} + } + } + false +} + +/// Whether a line break after `before` continues a pipeline: the text before it ends with `|` or +/// `|&` outside quotes, not with `||`. +fn ends_with_pipe(before: &[u8]) -> bool { + let t = before.trim_ascii_end(); + let t = t.strip_suffix(b"&").filter(|t| t.ends_with(b"|")).unwrap_or(t); + t.ends_with(b"|") && !t.ends_with(b"||") && !t.ends_with(b"\\|") } /// A shell control operator outside quotes: where it ends, and whether it is a pipe (`|`) rather @@ -1312,7 +1396,7 @@ struct ShellSeparator { } /// The control operators of a shell script outside quotes, in order. A line break counts as a list -/// separator unless a backslash continues it. +/// separator unless a backslash continues it or it follows a pipe. fn shell_separators(script: &str) -> Vec<ShellSeparator> { let bytes = script.as_bytes(); let (mut out, mut quote, mut escaped, mut i) = (vec![], None, false, 0); @@ -1340,6 +1424,8 @@ fn shell_separators(script: &str) -> Vec<ShellSeparator> { i += 1; } b'|' => out.push(ShellSeparator { end: i + 1, pipe: true }), + // A line break after a pipe continues the pipeline. + b'\n' if ends_with_pipe(&bytes[..i]) => {} b';' | b'&' | b'\n' => out.push(ShellSeparator { end: i + 1, pipe: false }), _ => {} } @@ -1353,8 +1439,9 @@ fn shell_separators(script: &str) -> Vec<ShellSeparator> { /// `;`, `&`, `|` or line break before `at` outside quotes. Its pipeline ends at the next `;`, `&`, /// `||` or line break outside quotes, since `|` and Bash's `|&` pass its output on. A command /// inside a `{ … }` or `( … )` group runs on to the group's redirection -/// (`{ echo A=1; } >> "$GITHUB_ENV"`). A backslash before a line break continues the command, and -/// `&` in a redirection (`>&2`) does not end it. +/// (`{ echo A=1; } >> "$GITHUB_ENV"`). A backslash before a line break continues the command, so +/// does a pipe before one (`echo A=1 |` and `tee` on the next line), and `&` in a redirection +/// (`>&2`) does not end it. fn shell_command(line: &str, at: usize) -> (usize, usize) { let b = line.as_bytes(); let (mut quote, mut escaped) = (None, false); @@ -1386,8 +1473,9 @@ fn shell_command(line: &str, at: usize) -> (usize, usize) { let redirect = c == b'&' && (i.checked_sub(1).is_some_and(|p| matches!(b[p], b'>' | b'<')) || b.get(i + 1) == Some(&b'>')); // The `&` of a `|&` pipe belongs to the pipe. let pipe = c == b'&' && i.checked_sub(1).is_some_and(|p| b[p] == b'|') && i.checked_sub(2).is_none_or(|p| b[p] != b'|'); - let separator = - (matches!(c, b';' | b'&' | b'\n') && !redirect && !(pipe && i >= at)) || (c == b'|' && (i < at || b.get(i + 1) == Some(&b'|'))); + let continued = c == b'\n' && ends_with_pipe(&b[..i]); + let separator = (matches!(c, b';' | b'&' | b'\n') && !redirect && !(pipe && i >= at) && !continued) + || (c == b'|' && (i < at || b.get(i + 1) == Some(&b'|'))); if !separator { continue; } @@ -1447,12 +1535,16 @@ fn workflow_code(line: &str) -> &str { /// Removes comment text outside quotes from a shell script that can hold several lines (a decoded /// `run` value): each comment ends at its line break, quotes stay open across line breaks, and a -/// `#` starts a comment only where a word starts (`one#two` and `a\ #b` are one word). +/// `#` starts a comment only where a word starts (`one#two` and `a\ #b` are one word). A line +/// continuation outside single quotes is removed, so `MY_\` and `SAMPLES=x` on the next line give +/// `MY_SAMPLES=x`. fn shell_code(script: &str) -> String { let (mut out, mut quote, mut escaped, mut comment) = (String::with_capacity(script.len()), None, false, false); // Whether the previous character ended a word: an unescaped space or control operator, or the // start of the script. let mut word_ended = true; + // An escaping backslash not yet written: it is dropped when a line break follows it. + let mut backslash = false; for c in script.chars() { let literal = escaped && !comment; let mut escape_start = false; @@ -1472,8 +1564,15 @@ fn shell_code(script: &str) -> String { _ => {} } } - if !comment { - out.push(c); + if escape_start { + backslash = true; + } else if !comment { + if std::mem::take(&mut backslash) && !(literal && c == '\n') { + out.push('\\'); + } + if !(literal && c == '\n') { + out.push(c); + } } // A backslash and the line break after it (a line continuation) are removed and leave the // word state as it was; an escaped space or other character is part of the word. @@ -1481,6 +1580,9 @@ fn shell_code(script: &str) -> String { word_ended = !literal && (c.is_whitespace() || matches!(c, ';' | '&' | '|' | '(' | ')' | '<' | '>')); } } + if backslash { + out.push('\\'); + } out } @@ -1646,8 +1748,10 @@ fn utf8_from(b: &[u8], at: usize) -> &str { } /// Where the name that starts at `at` (after any whitespace, Unicode whitespace included) starts -/// and ends: letters, digits and `_`, non-ASCII ones included (`vérifier`). The whitespace can be -/// longer than one [`utf8_from`] window, as where a long comment has been masked. +/// and ends: letters, digits and `_`, and every other non-ASCII character that is not whitespace +/// (`vérifier`, a combining accent), since masked code holds non-ASCII text only in names. The +/// whitespace and the name can each be longer than one [`utf8_from`] window, as where a long +/// comment has been masked. fn name_at(b: &[u8], at: usize) -> (usize, usize) { let mut start = at; loop { @@ -1658,9 +1762,16 @@ fn name_at(b: &[u8], at: usize) -> (usize, usize) { } start += blank; } - let s = utf8_from(b, start); - let len = s.find(|c: char| !(c.is_alphanumeric() || c == '_')).unwrap_or(s.len()); - (start, start + len) + let mut end = start; + loop { + let s = utf8_from(b, end); + let len = s.find(|c: char| !(c.is_alphanumeric() || c == '_' || (!c.is_ascii() && !c.is_whitespace()))).unwrap_or(s.len()); + end += len; + if len == 0 || len < s.len() { + break; + } + } + (start, end) } /// Every start of `word` in `b[from..to]` with no identifier character on either side. @@ -1785,7 +1896,16 @@ fn norm_values(b: &[u8]) -> String { }; while let Some(word) = cast_at(&text, from) { let at = if text[word - 1] == b' ' { word - 1 } else { word }; - let start = receiver_start(&text, at); + let mut start = receiver_start(&text, at); + // A unary `-` or `!` binds tighter than `as`, so it is part of the operand (`-Kind::A as i8` + // runs `Neg` on `Kind::A`); one after an operand is a binary operator (`a - b as i8`). + while start > 0 + && start < at + && matches!(text[start - 1], b'-' | b'!') + && !text[..start - 1].last().is_some_and(|&p| is_ident(p) || p >= 0x80 || matches!(p, b')' | b']' | b'}' | b'"' | b'\'')) + { + start -= 1; + } let ty = word + 3; let end = ty + text[ty..].iter().take_while(|&&c| is_ident(c)).count(); if start < at && PRIMITIVES.contains(&&text[ty..end]) { @@ -2354,11 +2474,14 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec<u8> { blank(&mut out, at, close + 1); } } - // Only a `let` statement, not the pattern of an `if let` or `while let`. - let statements = words(m, b"let", t.open, t.close) + // Only a `let` statement, not the pattern of an `if let` or `while let`. Statements are + // judged last first, and mentions are looked up in the code kept so far, so a call made + // only inside a closure that never runs (`let _ = || run();`) does not keep `run`. + let statements: Vec<usize> = words(m, b"let", t.open, t.close) .into_iter() - .filter(|&at| m[..at].trim_ascii_end().last().is_some_and(|c| matches!(c, b'{' | b';' | b'}'))); - for at in statements { + .filter(|&at| m[..at].trim_ascii_end().last().is_some_and(|c| matches!(c, b'{' | b';' | b'}'))) + .collect(); + for at in statements.into_iter().rev() { // Non-ASCII letters (`_vérifier`) are part of the name, and Unicode whitespace is not. let (name, name_end) = name_at(m, at + 3); let name_end = name_end.min(t.close); @@ -2399,8 +2522,8 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec<u8> { // Calling an async closure only makes a future, so one whose futures are all dropped // never runs either. let dropped = wild - || words(m, &m[name..name_end], end, t.close).is_empty() - || (is_async && closure && futures_dropped(m, &m[name..name_end], end, t.close)); + || words(&out, &m[name..name_end], end, t.close).is_empty() + || (is_async && closure && futures_dropped(&out, &m[name..name_end], end, t.close)); if unrun && dropped && end < t.close { blank(&mut out, at, end + 1); } @@ -2410,16 +2533,25 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec<u8> { } /// Whether every mention of the async closure `name` in `m[from..to]` calls it and drops the -/// future: a statement `name();`, `let _ = name();`, or a `let` of a name the rest never mentions. +/// future: a statement `name();`, `let _ = name();`, `drop(name());` (`std::mem::drop` included), +/// or a `let` of a name the rest never mentions. fn futures_dropped(m: &[u8], name: &[u8], from: usize, to: usize) -> bool { words(m, name, from, to).into_iter().all(|p| { let open = skip_ws(m, p + name.len()); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { return false }; + let before = m[..p].trim_ascii_end(); + // `drop` takes the future and drops it unpolled; a wrapper such as `block_on` may run it. + if let Some(callee) = before.strip_suffix(b"(").map(<[u8]>::trim_ascii_end) + && let Some(path) = callee.strip_suffix(b"drop") + && !path.last().is_some_and(|&c| is_ident(c) || c == b'.') + { + let after = skip_ws(m, close + 1); + return m.get(after) == Some(&b')') && m.get(skip_ws(m, after + 1)) == Some(&b';'); + } let semi = skip_ws(m, close + 1); if m.get(semi) != Some(&b';') { return false; } - let before = m[..p].trim_ascii_end(); if before.last().is_some_and(|c| matches!(c, b'{' | b';' | b'}')) { return true; } @@ -2801,7 +2933,17 @@ fn all_unguarded(v: &View) -> Vec<Hit> { let closes = source.len() - source.trim_end_matches(')').len(); let inner = &source[..source.len() - closes]; let ident = inner.bytes().rposition(|c| !is_ident(c)).map_or(0, |p| p + 1); - let grouped = closes > 0 && ident >= closes && inner[..ident].ends_with(&"(".repeat(closes)); + // The parentheses of a call (`fallback(xs)`, `vec!(xs)`) hold an argument, not a + // grouped receiver; a `!` without a name before it negates (`!(xs).is_empty()`). + let called = |s: &[u8]| match s.last() { + Some(&c) if is_ident(c) || c >= 0x80 || matches!(c, b')' | b']') => true, + Some(b'!') => s.len() >= 2 && (is_ident(s[s.len() - 2]) || s[s.len() - 2] >= 0x80), + _ => false, + }; + let grouped = closes > 0 + && ident >= closes + && inner[..ident].ends_with(&"(".repeat(closes)) + && !called(&inner.as_bytes()[..ident - closes]); let (source, closes) = if grouped || closes == 0 { (inner, closes) } else { (source, 0) }; let start = if grouped { ident } else { source.bytes().rposition(|c| !is_ident(c)).map_or(0, |p| p + 1) }; let receiver = &source[start..]; @@ -2816,13 +2958,21 @@ fn all_unguarded(v: &View) -> Vec<Hit> { .filter(|&p| norm(&body[p..to]).starts_with(&read)) .find(|&p| !may_shrink(&body[..to], receiver.as_bytes(), p + receiver.len())); if let (true, Some(read_at)) = (plain, kept) { - let count = compared_count(a, &body, v.t.open, (&text[..start], &text[i + g.len()..]), &read); + // The comparison reads the whole grouped expression (`(xs).len() == 2`). + let whole = format!("{}{g}", &head[outer..]); + let count = compared_count(a, &body, v.t.open, (&text[..outer], &text[i + g.len()..]), &whole, false); direct.push((receiver.to_owned(), to, read_at, count)); } !plain }) }); - other || reads_counted_local(&body, &locals, from, to) + // A saved count (`let n = xs.len(); assert_eq!(n, 2);`) guards `xs` like a direct check. + for (source, name, p) in counted_locals(&body, &locals, from, to) { + let around = (norm(&body[from..p]), norm(&body[p + name.len()..to])); + let count = compared_count(a, &body, v.t.open, (&around.0, &around.1), &name, true); + direct.push((source, to, p, count)); + } + other }) }); let sizes = Sizes { file: &v.file.m, consts: OnceCell::new(), src: v.file.src, open: v.t.open, cond: RefCell::default() }; @@ -2868,8 +3018,9 @@ fn all_unguarded(v: &View) -> Vec<Hit> { // check inside it, or after it, while nothing between the read and the `.all(…)` changes // its item count at all (`xs.push(1)` included). let guards = |root: Option<&str>, need: usize, call: usize| { - // An item read by a numeric index or a first-item unwrap shows that its own local has one. - if root.is_some_and(|r| item_roots.iter().any(|n| n == r)) { + // An item read by a numeric index or a first-item unwrap shows that its own local has + // that many items (`xs[1]` shows two, enough for `.windows(2)`). + if root.is_some_and(|r| item_roots.iter().any(|(n, items)| n == r && *items >= need)) { return true; } direct.iter().any(|(name, to, read_at, count)| { @@ -2972,10 +3123,10 @@ fn chain_root(text: &str) -> Option<&str> { /// The count that the size check `read` (`xs.len()`) is compared with in a guard operand of `a`, /// given the operand's text `around` the read: the other operand of an equality assertion whose /// operand is the read alone, or the name or number right of `==`, `>=` or `>` (left of `==`, `<=` -/// or `<`). Only `.len()` and `.count()` give a count. The flag is true for a strict bound (`>`, +/// or `<`). Only `.len()` and `.count()` give a count, or a `saved` local that holds one. The flag is true for a strict bound (`>`, /// `<`), where the collection holds at least one item more than the count. -fn compared_count(a: &MacroCall, body: &[u8], open: usize, around: (&str, &str), read: &str) -> Option<(String, bool)> { - if !(read.ends_with(".len()") || read.ends_with(".count()")) { +fn compared_count(a: &MacroCall, body: &[u8], open: usize, around: (&str, &str), read: &str, saved: bool) -> Option<(String, bool)> { + if !(saved || read.ends_with(".len()") || read.ends_with(".count()")) { return None; } let (before, after) = around; @@ -4418,15 +4569,15 @@ fn strip_all_predicates(body: &mut [u8]) { /// Where test code accesses an item in a way that fails on an empty collection: a first item, or an /// index written as a number, for the assertion at `until` in `body`. The flag is true for an access /// whose collection is not a plain local (`rows()[0]`), which counts for every collection; the list -/// names the plain locals that such accesses read (`expected` of `expected[1]`), each of which then -/// has an item. -fn first_item_guard(body: &[u8], sizes: &Sizes, until: usize) -> (bool, Vec<String>) { +/// names the plain locals that such accesses read (`expected` of `expected[1]`), each with the +/// number of items the access shows it has (`expected[1]` shows two). +fn first_item_guard(body: &[u8], sizes: &Sizes, until: usize) -> (bool, Vec<(String, usize)>) { let compact = norm(body); // Where each byte of `compact` sits in `body`. let spots: Vec<usize> = body.iter().enumerate().filter(|(_, c)| !c.is_ascii_whitespace()).map(|(i, _)| i).collect(); let (mut any, mut roots) = (false, vec![]); - let mut add = |head: &str| match chain_root(head) { - Some(root) => roots.push(root.to_owned()), + let mut add = |head: &str, items: usize| match chain_root(head) { + Some(root) => roots.push((root.to_owned(), items)), None => any = true, }; let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; @@ -4472,11 +4623,26 @@ fn first_item_guard(body: &[u8], sizes: &Sizes, until: usize) -> (bool, Vec<Stri // masked text, where `let xs` and `&mut xs` keep their spaces. let receiver = &b[receiver_start(b, at)..at]; let after_access = spots.get(chain).copied().unwrap_or(body.len()); - let shrunk = std::str::from_utf8(receiver).is_ok_and(plain_local) && may_shrink(&body[..until.max(after_access)], receiver, after_access); - !all_over_item && !shrunk && array_literal_len(&compact[..=end], sizes).is_none_or(|n| n == 0) + let local = std::str::from_utf8(receiver).is_ok_and(plain_local); + let shrunk = local && may_shrink(&body[..until.max(after_access)], receiver, after_access); + // An access after the assertion shows items only while nothing between them changes the + // count (`assert!(xs.iter().all(…)); xs.push(1); let _ = xs[0];`). + let access = spots.get(at).copied().unwrap_or(body.len()); + let changed = local && access > until && may_change(&body[..access], receiver, until, false); + !all_over_item && !shrunk && !changed && array_literal_len(&compact[..=end], sizes).is_none_or(|n| n == 0) }); - for (at, _) in indexed.chain(unwrapped.iter().flat_map(|g| compact.match_indices(g))) { - add(&compact[..at]); + for (at, matched) in indexed.chain(unwrapped.iter().flat_map(|g| compact.match_indices(g))) { + // `xs[k]` shows `k + 1` items; a first-item unwrap shows one. + let items = if matched == "[" { + compact[at + 1..] + .bytes() + .take_while(u8::is_ascii_digit) + .fold(0usize, |n, d| n.saturating_mul(10).saturating_add(usize::from(d - b'0'))) + .saturating_add(1) + } else { + 1 + }; + add(&compact[..at], items); } (any || panicking_first_binding(body), roots) } @@ -4741,7 +4907,7 @@ fn selector_touched(body: &[u8], name: &str, from: usize) -> bool { /// The plain locals an expression passes as call arguments or indexes after its root /// (`active` in `r.items(active)`, `i` in `rows[i]`): not method or field names, path segments, -/// called names, closure parameters or `true` and `false`. +/// called names, closure parameters, turbofish arguments or `true` and `false`. fn selector_locals(expr: &str) -> Vec<&str> { let b = expr.as_bytes(); let mut out = vec![]; @@ -4758,8 +4924,15 @@ fn selector_locals(expr: &str) -> Vec<&str> { let close = i + 1 + close; let mut depth = 0usize; let mut body_end = b.len(); - for (k, &c) in b.iter().enumerate().skip(close + 1) { - match c { + let mut k = close + 1; + while k < b.len() { + // A comma between turbofish arguments (`pick::<u8, u16>(i)`) does not end the body. + let past = skip_turbofish(b, k); + if past > k { + k = past; + continue; + } + match b[k] { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' if depth == 0 => { body_end = k; @@ -4772,6 +4945,7 @@ fn selector_locals(expr: &str) -> Vec<&str> { } _ => {} } + k += 1; } params.push((i, close, body_end)); i = close + 1; @@ -4781,6 +4955,12 @@ fn selector_locals(expr: &str) -> Vec<&str> { } let mut at = b.iter().take_while(|&&c| name_byte(c)).count(); while at < b.len() { + // Turbofish arguments (`pick::<u8, u16>`) name types, not locals. + let past = skip_turbofish(b, at); + if past > at { + at = past; + continue; + } if !name_byte(b[at]) { at += 1; continue; @@ -5861,6 +6041,7 @@ fn bindings(body: &[u8]) -> Vec<Binding> { let stop = statement_end(body, end); let stmt = norm(&body[end..stop]); let init = stmt.split_once('=').map_or("", |(_, init)| init); + let init_text = init; let counts = SIZE_CHECKS.iter().any(|g| init.contains(g)); // Grouping parentheses are skipped: `(xs.len())` and `((xs).len())` read `xs`. let grouped = init.trim_start_matches('('); @@ -5907,31 +6088,40 @@ fn bindings(body: &[u8]) -> Vec<Binding> { .iter() .any(|d| m == d.as_bytes()) }); - let counts = counts && !drains; + // A count through `by_ref()` (`xs.by_ref().count()`) consumes the source iterator; a + // length read through it (`xs.by_ref().len()`) does not. + let init_text = init_text.trim_end_matches(';'); + let consumes = first_method.is_some_and(|m| m == b"by_ref") && !(init_text.ends_with(".len()") || init_text.ends_with(".is_empty()")); + let counts = counts && !drains && !consumes; Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source, scope_end, init }) }) .collect() } -/// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that +/// The reads in `body[from..to]` (an assertion operand) of a local whose binding reaching that /// point checks a size and was not assigned since, of a collection that no later code may shrink -/// or replace. -fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool { - all.iter().filter(|b| b.counts && b.name != b"_").any(|b| { - words(body, &b.name, from, to).into_iter().any(|p| { +/// or replace: the collection's name, the local's name and where it is read. The count guards only +/// that collection, not every `.all(…)` of the test. +fn counted_locals(body: &[u8], all: &[Binding], from: usize, to: usize) -> Vec<(String, String, usize)> { + let mut out = vec![]; + for b in all.iter().filter(|b| b.counts && b.name != b"_") { + for p in words(body, &b.name, from, to) { let prefix = body[..p].trim_ascii_end(); if field_or_path(prefix) { - return false; + continue; } let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p && p < o.scope_end); - reaching - // A count whose collection is unknown (`let n = { let n = xs.len(); xs.clear(); n };`) - // cannot be shown to still hold. - .is_some_and(|r| { - r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_some_and(|s| !may_shrink(body, s, r.init)) - }) - }) - }) + // A count whose collection is unknown (`let n = { let n = xs.len(); xs.clear(); n };`) + // cannot be shown to still hold. + let source = reaching + .filter(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end)) + .and_then(|r| r.source.as_ref().filter(|s| !may_shrink(body, s, r.init)).map(|s| String::from_utf8_lossy(s).into_owned())); + if let Some(source) = source { + out.push((source, String::from_utf8_lossy(&b.name).into_owned(), p)); + } + } + } + out } /// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. @@ -6028,14 +6218,27 @@ fn status_condition(c: &str, depth: usize) -> bool { parts.push(&s[start..]); parts } + // A name, a path or a literal (`expected`, `true`, `Some(0)`, `-1`), which reads no other result. + fn plain(s: &str) -> bool { + let s = s.trim_start_matches(['&', '-']); + let s = s.strip_prefix("Some(").and_then(|r| r.strip_suffix(')')).unwrap_or(s).trim_start_matches(['&', '-']); + !s.is_empty() && s.bytes().all(|c| is_ident(c) || c >= 0x80 || c == b':') + } let c = unparenthesized(c); split(c, "||").into_iter().any(|alternative| { split(alternative, "&&").into_iter().all(|operand| { if operand.starts_with('(') && matching(operand.as_bytes(), 0) == Some(operand.len() - 1) { - status_condition(operand, depth + 1) - } else { - operand.contains(".success()") || operand.contains(".code()") + return status_condition(operand, depth + 1); } + // A comparison is a status check when one side is and the other is plain or a status + // too: `status.code() == Some(0)`, but not `(status.success() && dest.exists()) == true`. + let compared = top_level_at(operand, "==").into_iter().chain(top_level_at(operand, "!=")).min(); + if let Some(at) = compared { + let (left, right) = (&operand[..at], &operand[at + 2..]); + let status = |s: &str| !plain(s) && status_condition(s, depth + 1); + return (status(left) && (plain(right) || status(right))) || (plain(left) && status(right)); + } + operand.contains(".success()") || operand.contains(".code()") }) }) } @@ -7448,8 +7651,15 @@ fn generic_depth(op: &[u8]) -> usize { continue; } match op[i] { + // A bracketed group inside the arguments, a const block included (`N::<{ 1 << 2 }>`), + // is skipped whole, as [`angle_end`] skips it; one still open at the end holds the + // operand. + b'(' | b'[' | b'{' if depth > 0 => match matching(op, i) { + Some(close) => i = close, + None => return depth, + }, b'<' if depth > 0 => depth += 1, - b'>' if depth > 0 => depth -= 1, + b'>' if depth > 0 && op[i - 1] != b'-' => depth -= 1, _ => {} } i += 1; @@ -7593,8 +7803,9 @@ fn field_value(base: &str, field: &str, pos: usize, local: &LocalAt) -> Option<( return field_value(&init, field, at, local); } else if base.starts_with('(') && matching(base.as_bytes(), 0) == Some(base.len() - 1) && top_level_at(&base[1..base.len() - 1], ",").is_empty() { - // Without a top-level comma the parentheses only group the value inside them: `(Pair(5))`. - (base[1..base.len() - 1].to_owned(), pos) + // Without a top-level comma the parentheses only group the value inside them: `(Pair(5))`, + // and each further layer is unwrapped the same way (`((Pair(5)))`). + return field_value(&base[1..base.len() - 1], field, pos, local); } else { (base.to_owned(), pos) }; @@ -7885,7 +8096,10 @@ fn loop_body(body: &[u8], iter: usize) -> Option<(usize, usize)> { let part = &body[from..open]; // Only a keyword outside the expression's own delimiters (not the `if` inside a closure // passed to `filter(…)`) opens a block that belongs to the iterator. - let opens = OPENERS.iter().any(|k| words(part, k, 0, part.len()).into_iter().any(|at| bracket_depth(&part[..at]) == 0)); + // A raw identifier (`r#loop()`) is a name, not the keyword. + let opens = OPENERS + .iter() + .any(|k| words(part, k, 0, part.len()).into_iter().any(|at| bracket_depth(&part[..at]) == 0 && !part[..at].ends_with(b"r#"))); if !opens { return Some((open, close)); } @@ -14272,4 +14486,159 @@ mod tests { let before = body.windows(6).position(|w| w == b"use_it").unwrap_or(0); assert_eq!(for_binding(body, "n", before), Some(0)); } + + #[test] + fn a_redirected_command_does_not_reach_the_environment_file_writer() { + let none = Vec::<String>::new(); + let redirected = " echo \"MY_SAMPLES=fixtures\" >/dev/null |& tee -a \"$GITHUB_ENV\""; + assert_eq!(upper_words(redirected).collect::<Vec<_>>(), none); + assert_eq!(upper_words(&redirected.replace('"', "")).collect::<Vec<_>>(), none, "an unquoted assignment"); + assert_eq!(upper_words(&redirected.replace(">/dev/null ", "")).collect::<Vec<_>>(), ["MY_SAMPLES"]); + assert_eq!(upper_words(&redirected.replace(">/dev/null", "2>/dev/null")).collect::<Vec<_>>(), ["MY_SAMPLES"], "standard error only"); + } + + #[test] + fn env_reads_assignments_only_before_its_child_command() { + let child = "run: /usr/bin/env printf '%s\\n' \"MY_SAMPLES=fixtures\""; + assert_eq!(upper_words(child).collect::<Vec<_>>(), Vec::<String>::new()); + let options = "run: env -u HOME \"MY_SAMPLES=fixtures\" cargo test"; + assert_eq!(upper_words(options).collect::<Vec<_>>(), ["MY_SAMPLES"]); + } + + #[test] + fn a_pipe_at_the_end_of_a_line_continues_the_pipeline() { + let block = "run: |\n echo \"MY_SAMPLES=fixtures\" |&\n tee -a \"$GITHUB_ENV\"\n"; + assert_eq!(upper_words(block).collect::<Vec<_>>(), ["MY_SAMPLES"]); + assert_eq!(upper_words(&block.replace("|&", "|")).collect::<Vec<_>>(), ["MY_SAMPLES"], "a plain pipe"); + assert_eq!(upper_words(&block.replace(" |&", "")).collect::<Vec<_>>(), Vec::<String>::new(), "two separate commands"); + } + + #[test] + fn a_line_continuation_inside_a_name_is_removed() { + assert_eq!(upper_words("run: \"export MY_\\\\\\nSAMPLES=x\"").collect::<Vec<_>>(), ["MY_SAMPLES"]); + assert_eq!(shell_code("export MY_\\\nSAMPLES=x"), "export MY_SAMPLES=x"); + assert_eq!(shell_code("echo 'MY_\\\nSAMPLES=x'"), "echo 'MY_\\\nSAMPLES=x'", "inside single quotes"); + assert_eq!(shell_code("echo a\\ b"), "echo a\\ b", "an escaped space"); + } + + #[test] + fn a_closure_name_is_read_whole() { + let src = "#[test]\nfn t() {\n let NAME = || assert_eq!(compute(), 1);\n}\n"; + for name in [format!("_{}", "e".repeat(1100)), "_e\u{301}".to_owned()] { + let unused = src.replace("NAME", &name); + assert_eq!(hits(&unused), [(2, "no-assertion")], "{}", name.len()); + assert_eq!(hits(&unused.replace(";\n}", &format!(";\n {name}();\n}}"))), [], "a called closure"); + } + } + + #[test] + fn a_unary_operator_belongs_to_the_cast_operand() { + assert_eq!(norm_values(b"-Kind::A as i8"), "[-Kind::A][0]"); + assert_eq!(norm_values(b"!Flag::On as u8"), "[!Flag::On][0]"); + assert_eq!(norm_values(b"-(Kind::A as i8)"), "-([Kind::A][0])"); + assert_eq!(norm_values(b"a - Kind::A as i8"), "a-[Kind::A][0]"); + } + + #[test] + fn a_call_inside_a_discarded_closure_does_not_run_a_closure() { + let src = "#[test]\nfn t() {\n let run = || assert_eq!(compute(), 1);\n let _ = || run();\n}\n"; + assert_eq!(hits(src), [(2, "no-assertion")]); + assert_eq!(hits(&src.replace("let _ = || run();", "run();")), [], "a call from the test"); + assert_eq!(hits(&src.replace("let _ = || run();", "let _ = wrap(|| run());")), [], "a closure passed on"); + } + + #[test] + fn a_future_passed_to_drop_runs_no_assertion() { + let made = "#[test]\nfn t() {\n let run = async || { assert_eq!(f(), 1); };\n std::mem::drop(run());\n}\n"; + assert_eq!(hits(made), [(2, "no-assertion")]); + assert_eq!(hits(&made.replace("std::mem::drop", "drop")), [(2, "no-assertion")]); + assert_eq!(hits(&made.replace("std::mem::drop", "block_on")), [], "a wrapper that can run it"); + assert_eq!(hits(&made.replace("std::mem::drop", "x.drop")), [], "a method named drop"); + } + + #[test] + fn a_size_check_of_a_call_result_is_not_a_check_of_its_argument() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n assert_eq!(fallback(xs).len(), 1);\n xs.clear();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), hits(&src.replace("fallback(xs)", "fallback()")), "read like a call without the local"); + let negated = + "#[test]\nfn t() {\n let mut xs = f();\n assert!(!(xs).is_empty());\n xs.clear();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(negated), [(6, "all-unguarded")], "a negated grouped receiver"); + } + + #[test] + fn a_grouped_length_check_keeps_its_bound() { + let src = "#[test]\nfn t() {\n let xs = f();\n assert_eq!((xs).len(), 2);\n assert!(xs.windows(2).all(|w| w[0] < w[1]));\n}\n"; + assert_eq!(hits(src), []); + assert_eq!(hits(&src.replace("len(), 2", "len(), 1")), [(5, "all-unguarded")], "one item gives no window"); + } + + #[test] + fn an_index_shows_only_as_many_items_as_it_reads() { + let src = "#[test]\nfn t() {\n let xs = f();\n let _ = xs[0];\n assert!(xs.windows(2).all(|w| w[0] < w[1]));\n}\n"; + assert_eq!(hits(src), [(5, "all-unguarded")]); + assert_eq!(hits(&src.replace("xs[0]", "xs[1]")), [], "a second item"); + } + + #[test] + fn a_later_index_after_growth_guards_nothing() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n assert!(xs.iter().all(|v| *v > 0));\n xs.push(1);\n let _ = xs[0];\n}\n"; + assert_eq!(hits(src), [(4, "all-unguarded")]); + assert_eq!(hits(&src.replace(" xs.push(1);\n", "")), [], "an unchanged collection"); + } + + #[test] + fn a_turbofish_comma_does_not_end_a_selector_closure() { + assert_eq!(selector_locals("r.items(|i| pick::<u8, u16>(i))"), Vec::<&str>::new()); + assert_eq!(selector_locals("r.items(|i| pick::<u8, u16>(i), j)"), ["j"]); + } + + #[test] + fn a_count_through_by_ref_consumes_its_source() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.by_ref().count();\n assert_eq!(n, 1);\n assert!(xs.all(|x| x > 0));\n}\n"; + assert_eq!(hits(src), [(6, "all-unguarded")]); + assert_eq!(hits(&src.replace("by_ref().count()", "by_ref().len()")), [], "a length read"); + } + + #[test] + fn a_saved_count_guards_only_its_own_collection() { + let src = "#[test]\nfn t() {\n let xs = f();\n let ys = g();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(ys.iter().all(|y| *y > 0));\n}\n"; + assert_eq!(hits(src), [(7, "all-unguarded")]); + assert_eq!(hits(&src.replace("ys.iter()", "xs.iter()")), [], "the counted collection"); + let windows = src.replace("ys.iter().all(|y| *y > 0)", "xs.windows(2).all(|w| w[0] < w[1])"); + assert_eq!(hits(&windows), [(7, "all-unguarded")], "one item gives no window"); + assert_eq!(hits(&windows.replace("(n, 1)", "(n, 2)")), [], "two items"); + } + + #[test] + fn a_compound_check_compared_with_true_is_not_status_only() { + let src = "#[test]\nfn t() {\n let status = Command::new(\"cp\").arg(src).arg(&destination).status().unwrap();\n assert!((status.success() && destination.exists()) == true);\n}\n"; + assert_eq!(hits(src), []); + let alternative = src.replace("status.success() && destination", "status.success() || destination"); + assert_eq!(hits(&alternative), [(2, "exit-status-only")]); + assert_eq!(hits(&src.replace("(status.success() && destination.exists())", "status.success()")), [(2, "exit-status-only")]); + } + + #[test] + fn a_shift_inside_a_const_argument_leaves_no_generic_list_open() { + assert_eq!(generic_depth(b"N::<{1<<2}>::VALUE"), 0); + assert_eq!(generic_depth(b"None::<Vec<Amount>"), 1); + } + + #[test] + fn every_grouping_layer_is_unwrapped_before_a_field() { + let src = "#[test]\nfn t() {\n let pair = ((Pair(Input { n: 5 })));\n assert_eq!(pair.0.clone().n, 6);\n}\n"; + assert_eq!(only("fixture-only", src), []); + let primitive = "#[test]\nfn t() {\n let pair = ((Pair(5)));\n assert_eq!(pair.0.to_string(), \"5\");\n}\n"; + assert_eq!(only("fixture-only", primitive), [(2, "fixture-only")]); + } + + #[test] + fn a_raw_identifier_is_not_a_block_keyword() { + let body = b"for n in r#loop() { use_it(n) }"; + let before = body.windows(6).position(|w| w == b"use_it").unwrap_or(0); + assert_eq!(for_binding(body, "n", before), Some(0)); + let src = "#[test]\nfn t() {\n let n = 0;\n for n in r#loop() {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", src), []); + } } From 69eae94826499e7c9034e4d6f5f71e3804b3a2e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 06:44:59 -0800 Subject: [PATCH 095/103] Shapes: a star's stored settings read back with up to 2000 corners A star with a radius on each corner stores its corner list in its shape settings entry. A 1000-point star's entry is longer than the 4,096-byte read limit, so it was dropped on read and the star lost its pie angles and arc mode on the next edit. The limit is now 128 KiB, which holds the longest entry a 1000-point star can write. --- crates/tools/src/addons/box3d.rs | 50 ++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index 7ac8a008b0..0fbc4c5522 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -24,8 +24,9 @@ pub const ID: &str = "box3d"; /// The `vc-` prefix marks it as internal so SVG export omits it from `data-*` attributes. pub const KEY: &str = "vc-shape-tools"; -/// Maximum stored JSON length read back from a file. -const MAX_STORED: usize = 4096; +/// Maximum stored JSON length read back from a file: room for a 1000-point star's 2000 corner +/// radii and kinds. +const MAX_STORED: usize = 128 * 1024; fn whole_mode() -> EllipseMode { EllipseMode::Whole @@ -863,4 +864,49 @@ mod tests { *pie = (0.0, 90.0); assert!(matches!(star.to_live_shape(), Some(LiveShape::Star { points: 5, .. })), "{star:?}"); } + + /// A 1000-point star with a radius on each of its 2000 corners, written and read back. + fn round_trip(arc_mode: EllipseMode) -> CustomShape { + let mut star = read_back(Some(0.5), 1000); + let CustomShape::Polygon { radii, kinds, pie, arc_mode: mode, .. } = &mut star else { panic!("a polygon") }; + *radii = vec![12.0; 2000]; + *kinds = vec![CornerKind::Round; 2000]; + *pie = (0.0, 90.0); + *mode = arc_mode; + let mut node = Node::path(vectorcraft_doc::NodeId(1), PathData::default(), vectorcraft_doc::Appearance::default_art()); + star.write_to_node(&mut node); + CustomShape::read(&node).unwrap_or_else(|| panic!("a shape")) + } + + /// A live star's stored entry holds a long corner list, and its pie angles still read back. + #[test] + fn a_live_star_with_many_corners_keeps_its_pie_angles() { + let back = round_trip(EllipseMode::Whole); + let CustomShape::Polygon { pie, radii, kinds, .. } = &back else { panic!("a polygon") }; + assert_eq!(*pie, (0.0, 90.0)); + assert_eq!(radii.len(), 2000); + assert_eq!(kinds.len(), 2000); + } + + /// A sliced star has no `LiveShape`, so its stored entry holds every corner and still reads back. + #[test] + fn a_sliced_star_with_many_corners_reads_back() { + let back = round_trip(EllipseMode::Slice); + let CustomShape::Polygon { pie, radii, arc_mode, .. } = &back else { panic!("a polygon") }; + assert_eq!(*pie, (0.0, 90.0)); + assert_eq!(*arc_mode, EllipseMode::Slice); + assert_eq!(radii.len(), 2000); + } + + /// The longest corner values a 1000-point star can hold still fit in the stored entry. + #[test] + fn the_longest_star_entry_fits_the_read_limit() { + let mut star = read_back(Some(0.5), 1000); + let CustomShape::Polygon { radius, radii, kinds, .. } = &mut star else { panic!("a polygon") }; + *radius = -f64::MAX; + *radii = vec![-1.2345678901234567e-300; 2000]; + *kinds = vec![CornerKind::InvertedRound; 2000]; + let len = serde_json::to_string(&star).map(|s| s.len()).unwrap_or(usize::MAX); + assert!(len <= MAX_STORED, "{len}"); + } } From 3451c7a0a87b7618a732e37ffe20923d0d74fb1a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 06:51:26 -0800 Subject: [PATCH 096/103] xtask: test-lint takes a saved bound only from a saved length A local saved from `xs.len()` or `xs.iter().count()` gives the number compared with it as the item count. One saved from an item or a flag (`xs.first().copied().unwrap_or(0)`) shows at least one item, whatever it is compared with. --- xtask/src/test_lint.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 21fc9a33a1..af6177eba9 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2967,9 +2967,9 @@ fn all_unguarded(v: &View) -> Vec<Hit> { }) }); // A saved count (`let n = xs.len(); assert_eq!(n, 2);`) guards `xs` like a direct check. - for (source, name, p) in counted_locals(&body, &locals, from, to) { + for (source, name, p, exact) in counted_locals(&body, &locals, from, to) { let around = (norm(&body[from..p]), norm(&body[p + name.len()..to])); - let count = compared_count(a, &body, v.t.open, (&around.0, &around.1), &name, true); + let count = compared_count(a, &body, v.t.open, (&around.0, &around.1), &name, exact); direct.push((source, to, p, count)); } other @@ -6016,6 +6016,9 @@ struct Binding { name: Vec<u8>, end: usize, counts: bool, + /// Whether the value is the count itself (`xs.len()`, `xs.iter().count()`), so a comparison + /// with it gives a number of items, rather than an item or a flag (`xs.first()`). + exact: bool, /// The local whose method the initializer calls (`xs` in `let n = xs.len()`). source: Option<Vec<u8>>, /// Where the block that holds the `let` closes, after which the name no longer refers to it. @@ -6093,16 +6096,18 @@ fn bindings(body: &[u8]) -> Vec<Binding> { let init_text = init_text.trim_end_matches(';'); let consumes = first_method.is_some_and(|m| m == b"by_ref") && !(init_text.ends_with(".len()") || init_text.ends_with(".is_empty()")); let counts = counts && !drains && !consumes; - Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source, scope_end, init }) + let exact = init_text.ends_with(".len()") || init_text.ends_with(".count()"); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts, exact, source, scope_end, init }) }) .collect() } /// The reads in `body[from..to]` (an assertion operand) of a local whose binding reaching that /// point checks a size and was not assigned since, of a collection that no later code may shrink -/// or replace: the collection's name, the local's name and where it is read. The count guards only -/// that collection, not every `.all(…)` of the test. -fn counted_locals(body: &[u8], all: &[Binding], from: usize, to: usize) -> Vec<(String, String, usize)> { +/// or replace: the collection's name, the local's name, where it is read, and whether the local +/// holds the count itself ([`Binding::exact`]). The count guards only that collection, not every +/// `.all(…)` of the test. +fn counted_locals(body: &[u8], all: &[Binding], from: usize, to: usize) -> Vec<(String, String, usize, bool)> { let mut out = vec![]; for b in all.iter().filter(|b| b.counts && b.name != b"_") { for p in words(body, &b.name, from, to) { @@ -6115,9 +6120,9 @@ fn counted_locals(body: &[u8], all: &[Binding], from: usize, to: usize) -> Vec<( // cannot be shown to still hold. let source = reaching .filter(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end)) - .and_then(|r| r.source.as_ref().filter(|s| !may_shrink(body, s, r.init)).map(|s| String::from_utf8_lossy(s).into_owned())); - if let Some(source) = source { - out.push((source, String::from_utf8_lossy(&b.name).into_owned(), p)); + .and_then(|r| r.source.as_ref().filter(|s| !may_shrink(body, s, r.init)).map(|s| (String::from_utf8_lossy(s).into_owned(), r.exact))); + if let Some((source, exact)) = source { + out.push((source, String::from_utf8_lossy(&b.name).into_owned(), p, exact)); } } } @@ -14608,6 +14613,8 @@ mod tests { let windows = src.replace("ys.iter().all(|y| *y > 0)", "xs.windows(2).all(|w| w[0] < w[1])"); assert_eq!(hits(&windows), [(7, "all-unguarded")], "one item gives no window"); assert_eq!(hits(&windows.replace("(n, 1)", "(n, 2)")), [], "two items"); + let item = windows.replace("xs.len()", "xs.first().copied().unwrap_or(0)").replace("(n, 1)", "(n, 2)"); + assert_eq!(hits(&item), [(7, "all-unguarded")], "an item compared with 2 is not a count of 2"); } #[test] From d363ecc800e9591e25b8b760b1efa2c1a8c21708 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 07:01:29 -0800 Subject: [PATCH 097/103] Tests: the timed-out DWG worker writes no answer The time-limit test checked only the worker's exit code, which the test-lint exit-status-only rule rejects. It now also reads the worker's output and checks that nothing was written before it exited. --- apps/vectorcraft-cli/tests/it/fileio.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 2842559bfc..fee790b65b 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -433,13 +433,15 @@ fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() { let mut worker = Command::new(crate::bin()) .args(["--dwg-worker", "--dwg-worker-until", &millis]) .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) .spawn() .unwrap(); // Its input stays open, so the worker never gets the whole request. let input = worker.stdin.take(); - let status = worker.wait().unwrap(); + let out = worker.wait_with_output().unwrap(); drop(input); - assert_eq!(status.code(), Some(1), "{status:?}"); + assert_eq!(out.status.code(), Some(1), "{:?}", out.status); + // It stops without answering, so no partial drawing reaches the caller. + assert!(out.stdout.is_empty(), "{} bytes written", out.stdout.len()); } } From cc7c7675a7065044a707e0a5ad4144bf55933dd5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 07:23:53 -0800 Subject: [PATCH 098/103] File formats: a failed DWG conversion is tried again after 10 seconds A failed conversion was returned for the same bytes until another drawing replaced it, so a worker stopped by its deadline, by a lack of memory or by a failed start kept failing after the cause was gone. The failure is now kept for 10 seconds from when the conversion returned, which still covers the reads of one Open, and the next read converts the drawing again. A conversion that worked is kept as before. --- Cargo.lock | 1 + crates/cad/Cargo.toml | 1 + crates/cad/src/dwg.rs | 61 ++++++++++++++++++++++++++++++++++++------- 3 files changed, 53 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index edef276a56..7e0e10db6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8719,6 +8719,7 @@ dependencies = [ "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", "vectorcraft-text", + "web-time", ] [[package]] diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 55f3ab8278..c09eb31879 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -22,6 +22,7 @@ vectorcraft-text = { workspace = true } kurbo = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } +web-time = "1" [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index d72f77c83e..b6e4b545c4 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -7,6 +7,9 @@ use std::hash::BuildHasher; use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak}; +use std::time::Duration; + +use web_time::Instant; pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; @@ -73,11 +76,13 @@ type Outcome = Result<Arc<Converted>, String>; /// The outcome of the last drawing converted, by a hash of its bytes and its length, and the /// conversions a [`Held`] keeps. Open reads a drawing's layouts, draws a preview of each in its /// dialog and then opens it, and each of those reads the same file; a file the conversion refused -/// (or whose worker stopped) is refused again without another conversion. +/// (or whose worker stopped) is refused again without another conversion for [`FAILURE_KEPT`], +/// after which the next read converts it again. #[derive(Default)] struct Kept { hasher: std::collections::hash_map::RandomState, - last: Option<((u64, usize), Outcome)>, + /// The last outcome, by key, and when it was kept. + last: Option<((u64, usize), Outcome, Instant)>, /// The conversions handed out by [`hold`], while a [`Held`] for each exists. held: Vec<((u64, usize), Weak<Converted>)>, } @@ -87,8 +92,9 @@ impl Kept { (self.hasher.hash_one(bytes), bytes.len()) } - fn get(&self, key: (u64, usize)) -> Option<Outcome> { - if let Some((_, outcome)) = self.last.as_ref().filter(|(k, _)| *k == key) { + fn get(&self, key: (u64, usize), now: Instant) -> Option<Outcome> { + let fresh = |outcome: &Outcome, at: &Instant| outcome.is_ok() || now.saturating_duration_since(*at) < FAILURE_KEPT; + if let Some((_, outcome, _)) = self.last.as_ref().filter(|(k, outcome, at)| *k == key && fresh(outcome, at)) { return Some(outcome.clone()); } self.held.iter().filter(|(k, _)| *k == key).find_map(|(_, c)| c.upgrade()).map(Ok) @@ -99,28 +105,37 @@ impl Kept { self.held.push((key, Arc::downgrade(converted))); } - fn keep(&mut self, key: (u64, usize), outcome: &Outcome) { + fn keep(&mut self, key: (u64, usize), outcome: &Outcome, now: Instant) { if outcome.as_ref().is_ok_and(|c| c.dxf.len() > MAX_KEPT) { self.last = None; } else { - self.last = Some((key, outcome.clone())); + self.last = Some((key, outcome.clone(), now)); } } } +/// How long a failed conversion is returned again for the same bytes. A worker can fail for a +/// passing cause (memory, its deadline, a failed start), so a later read converts the drawing again. +const FAILURE_KEPT: Duration = Duration::from_secs(10); + /// The conversion of `bytes` that `kept` holds, else `convert`'s, which `kept` then holds. The /// lock is not held while `convert` runs, so another drawing can be converted at the same time. fn through(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Outcome { + through_at(kept, bytes, &Instant::now, convert) +} + +/// [`through`] with the time read from `now`; an outcome is kept from when `convert` returned. +fn through_at(kept: &Mutex<Kept>, bytes: &[u8], now: &dyn Fn() -> Instant, convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Outcome { let key = { let kept = kept.lock().unwrap_or_else(PoisonError::into_inner); let key = kept.key(bytes); - if let Some(outcome) = kept.get(key) { + if let Some(outcome) = kept.get(key, now()) { return outcome; } key }; let outcome = convert(bytes).map(Arc::new); - kept.lock().unwrap_or_else(PoisonError::into_inner).keep(key, &outcome); + kept.lock().unwrap_or_else(PoisonError::into_inner).keep(key, &outcome, now()); outcome } @@ -197,8 +212,10 @@ mod tests { fn a_refused_file_is_refused_again_without_converting_and_an_oversized_rendition_is_not_kept() { let kept = Mutex::new(Kept::default()); let calls = std::cell::Cell::new(0); - assert_eq!(through(&kept, b"AC1015 bad", |_| Err("DWG: no".to_string())).unwrap_err(), "DWG: no"); - let again = through(&kept, b"AC1015 bad", counting(&calls, b"0\nEOF\n")); + let start = Instant::now(); + let at_start = move || start; + assert_eq!(through_at(&kept, b"AC1015 bad", &at_start, |_| Err("DWG: no".to_string())).unwrap_err(), "DWG: no"); + let again = through_at(&kept, b"AC1015 bad", &at_start, counting(&calls, b"0\nEOF\n")); assert_eq!((again.unwrap_err().as_str(), calls.get()), ("DWG: no", 0)); let big = vec![b' '; MAX_KEPT + 1]; through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); @@ -206,6 +223,30 @@ mod tests { assert_eq!(calls.get(), 2, "a rendition over MAX_KEPT is converted again"); } + #[test] + fn a_failed_conversion_is_tried_again_once_its_time_is_up() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let clock = std::cell::Cell::new(Instant::now()); + let now = || clock.get(); + // The worker fails after running for longer than FAILURE_KEPT: the failure is kept from then. + let slow_failure = |_: &[u8]| { + clock.set(clock.get() + FAILURE_KEPT * 2); + Err("DWG: stopped".to_string()) + }; + assert!(through_at(&kept, b"AC1015 bad", &now, slow_failure).is_err()); + clock.set(clock.get() + FAILURE_KEPT / 2); + let within = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n")); + assert_eq!((within.unwrap_err().as_str(), calls.get()), ("DWG: stopped", 0)); + clock.set(clock.get() + FAILURE_KEPT / 2); + let later = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n")); + assert_eq!((later.unwrap().dxf.as_slice(), calls.get()), (b"0\nEOF\n".as_slice(), 1)); + // A conversion that worked is kept whatever the time. + clock.set(clock.get() + FAILURE_KEPT * 100); + through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"other")).unwrap(); + assert_eq!(calls.get(), 1); + } + #[test] fn a_held_drawing_is_not_converted_again_until_its_hold_is_dropped() { let kept = Mutex::new(Kept::default()); From 005b9ac384d554bf9af45f93a7095427653ee843 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 07:24:22 -0800 Subject: [PATCH 099/103] Scripts: a palette's edit field gives its text when its text part loses the focus The edit field read the focus of the field's outer response, which never holds the keyboard focus: the focus sits on the field's text part. A click elsewhere or Tab out of a palette's or dialog's edit field then did not give the typed text to the script. The field now reads the text part's focus loss (`text_lost_focus`). The focus-loss test drives the focus with Tab through egui instead of calling the commit helper, and fails without the fix. The retry docs in the script.palette.event help, docs/mcp.md and the progress-doc entry name the recoveryFolder and recoveryOffForComplex preferences, the two recovery preferences whose change starts the waiting events again. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/ui-egui/src/dialogs/script_window.rs | 3 ++- crates/ui-egui/src/tests/script_palettes.rs | 23 +++++++++++++++++---- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 5 files changed, 24 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index ee2f3fcc5d..f822107cf7 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; when a waiting event's run cannot begin in the app, the status bar shows the error and the events in line wait until the next input in the window, another script.palette.event, or a change to a document's unsaved state, drag or undo group, to the active document, or to the recoveryFolder or recoveryOffForComplex preference; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", always, palette_event ), diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 825e87abdb..3c52fae8a3 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -675,7 +675,8 @@ fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: let focused = out.response.has_focus(); let queued = queued && (drafts.contains_key(&n.id) || out.events.value().is_some()); let mut draft = (out.events.value().is_some() || text != n.text || queued).then(|| Some(text.clone())); - let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus(); + // The focus is on the field's text part, so the text part's focus loss is the one that counts. + let committed = out.submitted || out.events.committed().is_some() || out.text_lost_focus; if committed && let Some(event) = text_change(i, n, text.clone(), queued) { return Shown { event: Some(event), typing: true, container: None, draft: Some(None) }; } diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 7efb272535..e2ffd4626b 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -302,11 +302,26 @@ fn focus_loss_commits_a_restored_text_while_another_change_of_the_field_waits() follow(&mut app); with_palette(&app, id, |w| w.type_text(1, "a")).unwrap(); let ctx = app.ui_ctx.clone().unwrap(); - crate::testing::part_frame(&mut app, &ctx, egui::RawInput::default(), |app, ui| { - with_palette(app, id, |w| w.paint(ui)); - }); + let paint = |app: &mut VectorcraftApp, events: Vec<egui::Event>| { + let raw = egui::RawInput { events, ..Default::default() }; + crate::testing::part_frame(app, &ctx, raw, |app, ui| { + with_palette(app, id, |w| w.paint(ui)); + }); + }; + paint(&mut app, Vec::new()); + // Tab gives the edit field, the palette's first control, the keyboard focus. + let tab = |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + paint(&mut app, vec![tab(true), tab(false)]); + paint(&mut app, Vec::new()); + let focused = ctx.memory(|m| m.focused()).expect("the edit field has the keyboard focus"); + assert!(ctx.text_edit_focused()); assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten().as_deref(), Some("a")); - with_palette(&app, id, |w| w.commit_text(1, "a")).unwrap(); + // Tab moves the keyboard focus on to the Go button, and the pass after it gives the field's text to the script. + paint(&mut app, vec![tab(true), tab(false)]); + paint(&mut app, Vec::new()); + paint(&mut app, Vec::new()); + assert_ne!(ctx.memory(|m| m.focused()), Some(focused), "the edit field lost the keyboard focus"); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten(), None, "focus loss gives the typed text"); follow(&mut app); assert_eq!(app.session.script_palette_events_waiting(), 1, "focus loss merges the restored text into the waiting change"); give(&app, id, UiEvent::Click(2)); diff --git a/docs/mcp.md b/docs/mcp.md index 66b472c21f..fb025b3bed 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4637,7 +4637,7 @@ waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gi index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in `ui.inspect`'s `scriptReport`. When a waiting event's run cannot begin in the app, the status bar shows the error, and the events still in line wait until the next input in the window, another `script.palette.event`, or a change -to a document's unsaved state, drag or undo group, or to the active document. With nobody to ask, it runs the waiting events in order and returns the report of +to a document's unsaved state, drag or undo group, to the active document, or to the `recoveryFolder` or `recoveryOffForComplex` preference. With nobody to ask, it runs the waiting events in order and returns the report of the run that handled this one, or its error, even when it took the place of an earlier waiting event; an event dropped without a run is an error. An event whose run cannot begin ends it with that error, or with this event's result when this one has run, and the events after it keep waiting. When an open edit cannot be finished before diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 05db1eb6a6..388808da90 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1186,7 +1186,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. When a waiting event's run cannot begin in the app, the status bar shows the error, and the events in line wait until the next input in the window, another palette event, or a change to a document's unsaved state, drag or undo group, to the active document, or to the `recoveryFolder` or `recoveryOffForComplex` preference. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). From f838285622dd286b3a6f3221f7944a7b7a96926e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 07:32:43 -0800 Subject: [PATCH 100/103] Selection: anchor points draw at 4 pt under the Selection tool again Under the Selection tool, Group Selection and the other tools that do not edit anchors, the selected paths' anchor squares draw at 4 pt at the default Size, one point smaller than under Direct Selection, the Pen and the other anchor-editing tools, which keep 5 pt. Each Size step still adds or removes one point under every tool. Tool overlays follow the active tool the same way. Part of #10720. --- crates/ui-egui/src/canvas/overlays.rs | 2 +- crates/ui-egui/src/canvas/selection.rs | 17 ++++++++----- crates/ui-egui/src/canvas/selection/tests.rs | 25 ++++++++++++++++++-- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 56ecf1b24c..ef40ffefe4 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -32,7 +32,7 @@ const BADGE_OFFSET: Vec2 = Vec2::new(14.0, 14.0); /// on the canvas of `space`. The extras lie under the tool's own marks. pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, overlays: &[Overlay], extra: &[Overlay]) { let rect = space.view.rect; - let options = super::selection::path_options(&app.session.prefs); + let options = super::selection::path_options(&app.session.prefs, app.session.tool_id()); let quiet = tool_adapter::in_gesture(app, ui.ctx()) || tool_adapter::view_tool_held(app); let lists = [extra, overlays]; // Only the overlays that are controls get a child `Ui`: a list of 10,000 path marks makes none. diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index c2d53fcf97..861eda0790 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -30,8 +30,11 @@ use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). -/// The anchor square's side at Selection & Anchor Display › Size 3, the default, in points. +/// The anchor square's side at Selection & Anchor Display › Size 3, the default, in points, under a tool that edits +/// anchors ([`vectorcraft_tools::catalog::edits_anchors`]). const ANCHOR_AT_DEFAULT_SIZE: f32 = 5.0; +/// How many points smaller the anchor squares are under a tool that does not edit anchors, such as the Selection tool. +const SELECTING_ANCHOR_SHRINK: f32 = 1.0; /// The default of Selection & Anchor Display › Size. const DEFAULT_SIZE: u32 = 3; /// How many points bigger than the other selected anchors the key anchor's square is drawn. @@ -129,12 +132,14 @@ pub(super) fn outline_revision(paths: &[BezPath], key: Option<&BezPath>, extra: hasher.finish() } -/// The Path Options the anchors layer draws with: Selection & Anchor Display › Size (1–7, one point per step) and -/// Handles. One builder, so every overlay reads the preference the same way. +/// The Path Options the anchors layer draws with under `tool`: Selection & Anchor Display › Size (1–7, one point per +/// step) and Handles. Anchors are [`SELECTING_ANCHOR_SHRINK`] smaller under a tool that does not edit anchors. One +/// builder, so every overlay reads the preference the same way. #[allow(clippy::field_reassign_with_default)] // `PathOptionsSettings` is non-exhaustive: no struct literal outside its crate -pub(super) fn path_options(prefs: &Prefs) -> PathOptionsSettings { +pub(super) fn path_options(prefs: &Prefs, tool: &str) -> PathOptionsSettings { let mut options = PathOptionsSettings::default(); - options.anchor_size = Some(ANCHOR_AT_DEFAULT_SIZE + grow(prefs)); + let shrink = if vectorcraft_tools::catalog::edits_anchors(tool) { 0.0 } else { SELECTING_ANCHOR_SHRINK }; + options.anchor_size = Some(ANCHOR_AT_DEFAULT_SIZE - shrink + grow(prefs)); options.handles = match prefs.handle_style.as_str() { "hollow" => HandleStyle::Hollow, "large" => HandleStyle::Large, @@ -282,7 +287,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin shown: if curvature { AnchorsShown::Curvature } else { AnchorsShown::All }, handles: if prefs.show_handles_multiple_anchors { HandlesShown::Selected } else { HandlesShown::OneAnchor }, segment_mark: SegmentMark::Line, - options: path_options(prefs), + options: path_options(prefs, tool), }; if hidden(app) || too_big(app, st) || (curvature && tool_points) { return out; diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 42adf76890..65ca87aff3 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -119,10 +119,11 @@ fn no_stale_marks_after_a_change(tool: &str) { // The display preferences. app.session.active_mut().unwrap().selection.segments.clear(); + let at_default = marks(&app).options.anchor_size.unwrap(); app.session.prefs.anchor_size = 6; app.session.prefs.handle_style = "hollow".into(); let options = marks(&app).options; - assert_eq!((options.anchor_size, options.handles), (Some(8.0), HandleStyle::Hollow)); + assert_eq!((options.anchor_size, options.handles), (Some(at_default + 3.0), HandleStyle::Hollow), "Size 6 is three points up"); app.session.prefs.show_handles_multiple_anchors = false; assert_eq!(marks(&app).handles, HandlesShown::OneAnchor); app.session.prefs.show_handles_multiple_anchors = true; @@ -875,7 +876,8 @@ fn curvature_marks_existing_paths_as_circles_and_leaves_a_drafts_points_to_the_t #[test] fn anchor_size_scales_anchors_and_handles() { - let options = |size: u32, style: &str| path_options(&Prefs { anchor_size: size, handle_style: style.into(), ..Default::default() }); + let options = + |size: u32, style: &str| path_options(&Prefs { anchor_size: size, handle_style: style.into(), ..Default::default() }, "directSelection"); assert_eq!(options(3, "solid").anchor_size, Some(ANCHOR_AT_DEFAULT_SIZE)); let large = options(7, "large"); assert_eq!((large.anchor_size, large.handles), (Some(ANCHOR_AT_DEFAULT_SIZE + 4.0), HandleStyle::Large)); @@ -883,6 +885,25 @@ fn anchor_size_scales_anchors_and_handles() { assert_eq!(options(3, "solid").handles, HandleStyle::Solid); } +/// Anchors are a point smaller under the selection tools that move objects than under the tools that edit anchors, +/// at every Size. +#[test] +fn anchors_are_smaller_under_the_selection_tool_than_under_the_tools_that_edit_them() { + let (mut app, _) = scene(); + let mut size_under = |tool: &str| { + app.select_tool(tool); + assert!(!shown_paths(&marks(&app)).is_empty(), "{tool} shows the selection's anchors"); + marks(&app).options.anchor_size.unwrap() + }; + let (selection, group, direct, pen) = (size_under("selection"), size_under("groupSelection"), size_under("directSelection"), size_under("pen")); + assert_eq!(direct, ANCHOR_AT_DEFAULT_SIZE); + assert_eq!(pen, direct, "the Pen tool draws anchors as Direct Selection does"); + assert_eq!(selection, direct - SELECTING_ANCHOR_SHRINK); + assert_eq!(group, selection, "Group Selection moves objects as the Selection tool does"); + let largest = |tool: &str| path_options(&Prefs { anchor_size: 7, ..Default::default() }, tool).anchor_size.unwrap(); + assert_eq!(largest("directSelection") - largest("selection"), SELECTING_ANCHOR_SHRINK, "Size grows both alike"); +} + /// The revision is of the drawn outline: the same paths and colour give one value, other paths or another colour do not. #[test] fn the_outline_revision_follows_what_is_drawn() { From 843d7cb4970d1760ebc3e0af9bde624fc9c3bcca Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 07:49:41 -0800 Subject: [PATCH 101/103] Main: guard the tool-name check in tool_schemas_are_valid #10622 changed the tool-name assertion in crates/mcp/src/tests.rs, and test-lint's all-unguarded rule failed main's gate on it: the all() check had no emptiness check that the rule recognizes. The test now asserts that tools are defined and that each name is non-empty on its own, then checks the name's length and characters. --- crates/mcp/src/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 60b27bacbf..ceaff98fb5 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -229,10 +229,12 @@ fn initialize_negotiates_version() { #[test] fn tool_schemas_are_valid() { let tools = tool_definitions(); + assert!(!tools.is_empty(), "no tools defined"); let mut names = std::collections::HashSet::new(); for t in &tools { let name = t["name"].as_str().expect("name"); - assert!(!name.is_empty() && name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'), "{name}"); + assert!(!name.is_empty(), "empty tool name"); + assert!(name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'), "{name}"); assert!(names.insert(name), "duplicate tool {name}"); assert!(t["description"].as_str().is_some_and(|d| d.len() > 10), "{name} description"); let schema = &t["inputSchema"]; From e8693940feeeaa088a7bf1e8d43369698e419981 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 09:43:41 -0800 Subject: [PATCH 102/103] Docs: the roadmap's M4 row lists DWG import as done DWG drawings open and place through the DXF reader since #10802, but the M4 row in docs/roadmap.md still listed DWG under Left. The row now lists DWG import with its pull request, and Left keeps DWG export (use DXF). --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 7ebe434027..a86bbe6ebe 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -199,7 +199,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors the topmost, newest objects keep their Smart Guides targets (#8531) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | DWG import: DWG drawings open and place through the DXF reader (#10802; estimates unchanged); `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG export (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders done (#1880); vertical type in progress (Type › Type Orientation, #5027) | 45–60 | From a047d8297fffb28c024d15e91476c6eae5a1b09f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 09:47:07 -0800 Subject: [PATCH 103/103] CDR import: warn that PowerClip frames whose contents were left out open empty The reader opens a PowerClip frame whose clipped objects were all left out (bitmaps, text and other objects it doesn't read yet, or contents past the import limits) as a plain shape, and the warnings only said that objects were left out, so an empty frame had no explanation. Opening a drawing of version 4 or later now adds the line "CDR PowerClip frames whose contents were left out opened empty, as plain shapes" whenever the reader left objects out or stopped at a limit. Drawings of versions 1 to 3, which the reader opens without frames, don't get it. The reader's warnings don't say which frames lost their contents, so the line is shown for every such drawing. --- crates/engine/src/cmd/fileio/cdr.rs | 14 +++++++++- crates/engine/src/cmd/fileio/tests_cdr.rs | 31 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index c341f03e69..04aef3563a 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -29,6 +29,14 @@ const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under th const LENSES: &str = "CDR lenses and object transparency were not applied, and the objects they are on show opaque"; const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out"; const DAMAGED: &str = "damaged parts of the drawing were left out"; +/// Shown with [`UNSUPPORTED_OBJECTS`] or [`TOO_DEEP`]: `craft-cdr` opens a PowerClip frame whose +/// contents were all left out as a plain shape. Its warnings name neither the kinds of objects +/// left out nor the frames that lost their contents, so this line is shown whenever objects were +/// left out. Once `craft-cdr` reports which frames lost their contents, show it only for those. +const EMPTY_FRAMES: &str = "CDR PowerClip frames whose contents were left out opened empty, as plain shapes"; +/// The first version, in hundreds, whose PowerClip frames `craft-cdr` reads: earlier versions +/// store their objects' styles inline, and the reader opens none of them as frames. +const FRAMES_FROM: u16 = 400; const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; const CMX_UNSUPPORTED_OBJECTS: &str = @@ -103,7 +111,11 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> { } why => err(format!("this CDR drawing can't be read ({why})")), })?; - Ok(build(&d, note, PAGES_CUT)) + let (doc, mut warnings) = build(&d, note, PAGES_CUT); + if d.version >= FRAMES_FROM && d.warnings.iter().any(|w| matches!(w, Warning::UnsupportedObjects | Warning::TooDeep)) { + warnings.push(EMPTY_FRAMES.to_string()); + } + Ok((doc, warnings)) } /// Is `bytes` a `.cmx` file, of any byte order or coordinate size? diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 2645e86c76..2e4d82822b 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -89,6 +89,8 @@ fn versions_3_and_4_open_and_place_as_editable_art() { assert_eq!(r["format"], "cdr", "{version} {name}"); let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}"); + // The reader opens PowerClip frames from version 4 on. + assert_eq!(w.iter().any(|w| w.contains("PowerClip")), version >= 400, "{version}: {w:?}"); } let doc = &s.doc().unwrap().doc; assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}"); @@ -535,6 +537,35 @@ fn containers_open_as_clipping_groups() { assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. }))); } +/// A container whose clipped group holds only objects the reader leaves out (a bitmap here), or +/// whose group holds a container of that same group, opens as a plain shape, and the warnings +/// say that such frames opened empty. +#[test] +fn containers_whose_contents_were_left_out_are_named_in_the_warnings() { + let v = V(1100); + let rect = |w: f64, extra: Vec<(u32, Vec<u8>)>| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let open = |clipped: Vec<synth::Node>| { + let doc = list(b"doc ", vec![synth::clpt(vec![(5, clipped)])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]); + super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap() + }; + let frames = "PowerClip frames whose contents were left out opened empty"; + let (doc, warnings) = open(vec![synth::object(v, 5, &[(30, v.rect(10.0, 10.0, 0.0))], None)]); + let p = paths(&doc); + let [frame] = p.as_slice() else { panic!("{p:?}") }; + assert!(matches!(frame.kind, NodeKind::Path { clipping: false, .. }), "{:?}", frame.kind); + assert!(warnings.iter().any(|w| w.contains("text, bitmaps")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); + // The inner container names the group already being read, so it is left out at the limit. + let (_, warnings) = open(vec![rect(10.0, vec![synth::container(5)])]); + assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); +} + /// An object with a lens or transparency opens opaque, and the warnings say so. #[test] fn lenses_and_transparency_are_named_in_the_warnings() {