mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 19:04:25 +01:00
Merge pull request #6499 from dotCooCoo/feat/script-console
Scripts: Window › Script Console shows script output, errors and run reports
This commit is contained in:
49 files changed
+1627
-30
No files matched your search
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport",
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error)}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, fuelLeft, fuelUsed, hostCalls and the fields above",
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -45,6 +45,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
stop
|
||||
),
|
||||
cmd!(
|
||||
query "script.console",
|
||||
"Script Console",
|
||||
[],
|
||||
None,
|
||||
"{} the Script Console's lines, oldest first: each run's start, its $.write and $.writeln output, its vc.log entries, its uncaught error as name:line:column: message, its end and a report of its time, host calls and slowest commands; a session keeps at most 2048 lines and 1 MiB of text, dropping the oldest, a line at most 4096 bytes and a script's name in its lines at most 256 bytes, each cut with … (VectorCraft's own limits); line feeds, carriage returns and the two together break lines, other control characters show as their Unicode Control Pictures → {lines: [{run: the run's number in the session, name, kind: start|output|log|error|end|report, text}], droppedLines, truncatedLines} (an end line's text is ended: finished|error|fuel|hostLimit|limit|stopped|internal)",
|
||||
always,
|
||||
console_lines
|
||||
),
|
||||
cmd!(
|
||||
query "script.console.clear",
|
||||
"Clear Script Console",
|
||||
[],
|
||||
None,
|
||||
"{} empty the Script Console and set its dropped and cut counts to zero; a running script goes on writing, and scriptReport keeps the last run's console → {cleared: lines removed}",
|
||||
always,
|
||||
console_clear
|
||||
),
|
||||
cmd!(
|
||||
query "script.check",
|
||||
"Check Script",
|
||||
@@ -146,6 +164,14 @@ fn stop(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"stopped": s.script_request_stop()}))
|
||||
}
|
||||
|
||||
fn console_lines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(s.script_console().to_json())
|
||||
}
|
||||
|
||||
fn console_clear(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"cleared": s.clear_script_console()}))
|
||||
}
|
||||
|
||||
/// The folder a script is in, which its included files are read from.
|
||||
struct Folder {
|
||||
dir: std::path::PathBuf,
|
||||
|
||||
@@ -259,6 +259,10 @@ pub struct Session {
|
||||
pub(crate) script_stop: vectorcraft_js::Interrupt,
|
||||
/// The report of the run that ended last.
|
||||
pub(crate) script_report: Option<Value>,
|
||||
/// The Script Console's lines ([`script::console`]).
|
||||
pub(crate) script_console: script::console::Console,
|
||||
/// The runs started in this session, which numbers each run's console lines.
|
||||
pub(crate) script_runs: u64,
|
||||
/// `script.run` starts the job and returns, and the frontend advances it once per frame
|
||||
/// ([`Session::script_pump`]). Off, `script.run` advances it to its end.
|
||||
pub script_frames: bool,
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! The Script Console: what scripts write with `$.write` and `$.writeln`, what they log with
|
||||
//! `vc.log`, their uncaught errors, and a start, an end and a report line for each run.
|
||||
//!
|
||||
//! A session keeps its own console, and each run keeps one more for its report. Each holds at most
|
||||
//! [`MAX_CONSOLE_LINES`] lines and [`MAX_CONSOLE_BYTES`] of text, dropping its oldest lines first,
|
||||
//! and a line holds at most [`MAX_LINE_BYTES`], cut at a character boundary and ended with
|
||||
//! [`CUT_MARK`]. A script's name in its lines is cut the same way to [`MAX_NAME_BYTES`]. These are
|
||||
//! VectorCraft's own limits. A line break is a line feed, a carriage
|
||||
//! return or the two together. Other control characters show as their Unicode Control Pictures
|
||||
//! (U+2400 to U+2421), and the line and paragraph separators as U+2424.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The most lines a console keeps.
|
||||
pub const MAX_CONSOLE_LINES: usize = 2_048;
|
||||
/// The most bytes of text (UTF-8) a console keeps.
|
||||
pub const MAX_CONSOLE_BYTES: usize = 1 << 20;
|
||||
/// The most bytes (UTF-8) of one line, its cut mark included.
|
||||
pub const MAX_LINE_BYTES: usize = 4_096;
|
||||
/// The most bytes (UTF-8) of a script's name as console lines give it, its cut mark included.
|
||||
pub const MAX_NAME_BYTES: usize = 256;
|
||||
/// The end of a line that was cut.
|
||||
pub const CUT_MARK: char = '…';
|
||||
|
||||
/// How a run ended, as its end line gives it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Ending {
|
||||
/// The script ran to its end and its changes were kept.
|
||||
Finished,
|
||||
/// An uncaught error or a syntax error.
|
||||
Error,
|
||||
/// The instructions ran out (`maxFuel`).
|
||||
Fuel,
|
||||
/// A host limit: host calls, data passed to commands, growth, or a command's fault.
|
||||
HostLimit,
|
||||
/// Another limit of the interpreter: heap, call depth or a nested run that could not pause.
|
||||
Limit,
|
||||
/// `script.stop`, Stop or a cancel from the caller.
|
||||
Stopped,
|
||||
/// A fault inside VectorCraft.
|
||||
Internal,
|
||||
}
|
||||
|
||||
impl Ending {
|
||||
/// The id `script.console` gives.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Ending::Finished => "finished",
|
||||
Ending::Error => "error",
|
||||
Ending::Fuel => "fuel",
|
||||
Ending::HostLimit => "hostLimit",
|
||||
Ending::Limit => "limit",
|
||||
Ending::Stopped => "stopped",
|
||||
Ending::Internal => "internal",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A command among the slowest of a run: its id, how often it ran and how long it took.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Slow {
|
||||
pub id: String,
|
||||
pub calls: u64,
|
||||
pub total_ms: u64,
|
||||
pub max_ms: u64,
|
||||
}
|
||||
|
||||
/// What a console line holds.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
/// The run started.
|
||||
Start,
|
||||
/// A line of `$.write` and `$.writeln` output.
|
||||
Output(String),
|
||||
/// A `vc.log` entry: a string as it is, any other value as JSON.
|
||||
Log(String),
|
||||
/// The uncaught error that ended the run: `name:line:column: message`.
|
||||
Error(String),
|
||||
/// The run ended.
|
||||
End(Ending),
|
||||
/// The run's report: its time (when the platform has a clock), host calls and slowest commands.
|
||||
Report { ms: Option<u64>, host_calls: u64, slowest: Vec<Slow> },
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// The id of the line's kind that `script.console` gives.
|
||||
pub fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Entry::Start => "start",
|
||||
Entry::Output(_) => "output",
|
||||
Entry::Log(_) => "log",
|
||||
Entry::Error(_) => "error",
|
||||
Entry::End(_) => "end",
|
||||
Entry::Report { .. } => "report",
|
||||
}
|
||||
}
|
||||
|
||||
/// The line's text in English, as `script.console` and the run report give it.
|
||||
pub fn text(&self) -> String {
|
||||
match self {
|
||||
Entry::Start => "started".to_string(),
|
||||
Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.clone(),
|
||||
Entry::End(e) => format!("ended: {}", e.id()),
|
||||
Entry::Report { ms, host_calls, slowest } => {
|
||||
let time = ms.map_or_else(|| "time unavailable".to_string(), |ms| format!("{ms} ms"));
|
||||
let mut s = format!("{time}, {host_calls} host calls");
|
||||
if !slowest.is_empty() {
|
||||
let list: Vec<String> = slowest.iter().map(|c| format!("{} ×{} {} ms", c.id, c.calls, c.total_ms)).collect();
|
||||
s.push_str("; slowest: ");
|
||||
s.push_str(&list.join(", "));
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes the line counts toward [`MAX_CONSOLE_BYTES`].
|
||||
fn bytes(&self) -> usize {
|
||||
match self {
|
||||
Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.len(),
|
||||
Entry::Start | Entry::End(_) => 16,
|
||||
Entry::Report { slowest, .. } => 48 + slowest.iter().map(|c| c.id.len() + 24).sum::<usize>(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A console line: the run it belongs to, by its number in the session, and the script's name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ConsoleLine {
|
||||
pub run: u64,
|
||||
pub name: Arc<str>,
|
||||
pub entry: Entry,
|
||||
}
|
||||
|
||||
/// A bounded store of console lines.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Console {
|
||||
lines: VecDeque<ConsoleLine>,
|
||||
bytes: usize,
|
||||
dropped: u64,
|
||||
truncated: u64,
|
||||
/// The number of the first line kept: every line the console was given has its own number,
|
||||
/// counted from 0, which dropping and clearing do not change.
|
||||
first: u64,
|
||||
}
|
||||
|
||||
impl Console {
|
||||
/// The lines kept, oldest first.
|
||||
pub fn lines(&self) -> &VecDeque<ConsoleLine> {
|
||||
&self.lines
|
||||
}
|
||||
|
||||
/// The number of [`Console::lines`]' first line; each line after it has the next number.
|
||||
pub fn first_number(&self) -> u64 {
|
||||
self.first
|
||||
}
|
||||
|
||||
/// The lines dropped to make room since the console was last cleared.
|
||||
pub fn dropped_lines(&self) -> u64 {
|
||||
self.dropped
|
||||
}
|
||||
|
||||
/// The lines cut to [`MAX_LINE_BYTES`] since the console was last cleared.
|
||||
pub fn truncated_lines(&self) -> u64 {
|
||||
self.truncated
|
||||
}
|
||||
|
||||
/// Removes every line and sets the counts to zero.
|
||||
pub fn clear(&mut self) {
|
||||
*self = Self { first: self.first + self.lines.len() as u64, ..Self::default() };
|
||||
}
|
||||
|
||||
/// Adds a line, dropping the oldest ones past the limits. `cut`: the line's text was cut.
|
||||
pub(crate) fn push(&mut self, line: ConsoleLine, cut: bool) {
|
||||
if cut {
|
||||
self.truncated = self.truncated.saturating_add(1);
|
||||
}
|
||||
let bytes = line.entry.bytes();
|
||||
while !self.lines.is_empty() && (self.lines.len() >= MAX_CONSOLE_LINES || self.bytes + bytes > MAX_CONSOLE_BYTES) {
|
||||
if let Some(old) = self.lines.pop_front() {
|
||||
self.bytes -= old.entry.bytes();
|
||||
self.dropped = self.dropped.saturating_add(1);
|
||||
self.first += 1;
|
||||
}
|
||||
}
|
||||
self.bytes += bytes;
|
||||
self.lines.push_back(line);
|
||||
}
|
||||
|
||||
/// `{lines: [text…], droppedLines, truncatedLines}`, as a run report gives its console.
|
||||
pub(crate) fn report(&self) -> Value {
|
||||
let lines: Vec<String> = self.lines.iter().map(|l| l.entry.text()).collect();
|
||||
json!({"lines": lines, "droppedLines": self.dropped, "truncatedLines": self.truncated})
|
||||
}
|
||||
|
||||
/// `{lines: [{run, name, kind, text}…], droppedLines, truncatedLines}`, as `script.console`
|
||||
/// gives it.
|
||||
pub fn to_json(&self) -> Value {
|
||||
let lines: Vec<Value> =
|
||||
self.lines.iter().map(|l| json!({"run": l.run, "name": &*l.name, "kind": l.entry.kind(), "text": l.entry.text()})).collect();
|
||||
json!({"lines": lines, "droppedLines": self.dropped, "truncatedLines": self.truncated})
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as the console shows it: a control character as its Control Picture, a line or paragraph
|
||||
/// separator as U+2424, anything else as it is.
|
||||
fn shown(c: char) -> char {
|
||||
match c {
|
||||
'\u{0}'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
|
||||
'\u{7f}' => '\u{2421}',
|
||||
'\u{80}'..='\u{9f}' => '\u{fffd}',
|
||||
'\u{2028}' | '\u{2029}' => '\u{2424}',
|
||||
c => c,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `text` to `line` as the console shows it, up to [`MAX_LINE_BYTES`]. → `true` when part of
|
||||
/// it did not fit.
|
||||
fn append(line: &mut String, text: &str) -> bool {
|
||||
for c in text.chars().map(shown) {
|
||||
if line.len() + c.len_utf8() > MAX_LINE_BYTES {
|
||||
return true;
|
||||
}
|
||||
line.push(c);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A script's name as console lines give it: shown as a line shows its text, and cut to
|
||||
/// [`MAX_NAME_BYTES`] with [`CUT_MARK`].
|
||||
pub(crate) fn line_name(name: &str) -> Arc<str> {
|
||||
let mut out = String::new();
|
||||
for c in name.chars().map(shown) {
|
||||
if out.len() + c.len_utf8() > MAX_NAME_BYTES {
|
||||
mark_cut(&mut out, MAX_NAME_BYTES);
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
Arc::from(out)
|
||||
}
|
||||
|
||||
/// Ends a line that was cut with [`CUT_MARK`], within `limit` bytes.
|
||||
fn mark_cut(line: &mut String, limit: usize) {
|
||||
let mut at = line.len().min(limit - CUT_MARK.len_utf8());
|
||||
while !line.is_char_boundary(at) {
|
||||
at -= 1;
|
||||
}
|
||||
line.truncate(at);
|
||||
line.push(CUT_MARK);
|
||||
}
|
||||
|
||||
/// What `$.write` has written of the line it has not ended yet.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Pending {
|
||||
text: String,
|
||||
/// Part of the line did not fit; the rest is left out until the line ends.
|
||||
cut: bool,
|
||||
/// The last text written ended with a carriage return, so a line feed next ends no line.
|
||||
after_cr: bool,
|
||||
}
|
||||
|
||||
impl Pending {
|
||||
/// Writes `text`, calling `done` with each line it ends and whether that line was cut.
|
||||
pub(crate) fn write(&mut self, text: &str, mut done: impl FnMut(String, bool)) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut rest = text;
|
||||
if self.after_cr && rest.starts_with('\n') {
|
||||
rest = &rest[1..];
|
||||
}
|
||||
self.after_cr = false;
|
||||
while let Some(at) = rest.find(['\r', '\n']) {
|
||||
self.add(&rest[..at]);
|
||||
done(self.take_line(), self.cut);
|
||||
self.cut = false;
|
||||
let skip = if rest[at..].starts_with("\r\n") { 2 } else { 1 };
|
||||
if skip == 1 && rest[at..].starts_with('\r') && at + 1 == rest.len() {
|
||||
self.after_cr = true;
|
||||
}
|
||||
rest = &rest[at + skip..];
|
||||
}
|
||||
self.add(rest);
|
||||
}
|
||||
|
||||
/// Ends the current line, empty or not.
|
||||
pub(crate) fn end_line(&mut self, mut done: impl FnMut(String, bool)) {
|
||||
let cut = self.cut;
|
||||
done(self.take_line(), cut);
|
||||
self.cut = false;
|
||||
self.after_cr = false;
|
||||
}
|
||||
|
||||
/// Is part of a line waiting for its end?
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.text.is_empty() && !self.cut
|
||||
}
|
||||
|
||||
fn add(&mut self, text: &str) {
|
||||
if !self.cut && !text.is_empty() {
|
||||
self.cut = append(&mut self.text, text);
|
||||
}
|
||||
}
|
||||
|
||||
fn take_line(&mut self) -> String {
|
||||
if self.cut {
|
||||
mark_cut(&mut self.text, MAX_LINE_BYTES);
|
||||
}
|
||||
std::mem::take(&mut self.text)
|
||||
}
|
||||
}
|
||||
+235
-10
@@ -20,7 +20,15 @@
|
||||
//! The values here are VectorCraft's own limits: [`MAX_SOURCE_BYTES`], [`DEFAULT_FUEL`],
|
||||
//! [`MAX_FUEL`], [`SLICE_FUEL`], [`HEAP_BYTES`], [`MAX_HOST_CALLS`], [`GROWTH_OBJECTS`],
|
||||
//! [`GROWTH_BYTES`], [`MAX_CONTINUES`], [`MAX_LOG_LINES`], [`MAX_LOG_BYTES`], [`MAX_ARGS_BYTES`],
|
||||
//! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default.
|
||||
//! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default,
|
||||
//! and the console's ([`console`]).
|
||||
//!
|
||||
//! A run writes to the Script Console with `$.write` and `$.writeln`, and `vc.log` adds a line
|
||||
//! there too. The session's console gets a start line, the run's output, its uncaught error, an end
|
||||
//! line and a report line; the run's report holds its own output and error, its time, its host
|
||||
//! calls by kind and its slowest commands.
|
||||
|
||||
pub mod console;
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
@@ -72,7 +80,9 @@ const MAX_BRIDGE_BYTES: u64 = 4 << 30;
|
||||
/// The version `vc.api.version` gives.
|
||||
pub const API_VERSION: &str = "1.0";
|
||||
/// The features `vc.api.has` knows.
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args"];
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console"];
|
||||
/// The most commands a run's report lists in `slowestCommands`.
|
||||
pub const SLOWEST_COMMANDS: usize = 5;
|
||||
|
||||
/// What the step of a run's one undo step is called.
|
||||
pub const STEP_LABEL: &str = "Run Script";
|
||||
@@ -446,9 +456,92 @@ struct Host {
|
||||
log: RefCell<Vec<Value>>,
|
||||
log_bytes: Cell<usize>,
|
||||
written: RefCell<Vec<String>>,
|
||||
/// The run's number in its session, and the script's name, which its console lines carry.
|
||||
run: u64,
|
||||
name: Arc<str>,
|
||||
/// The run's own output and error, for its report.
|
||||
console: RefCell<console::Console>,
|
||||
/// The line `$.write` has not ended yet.
|
||||
pending: RefCell<console::Pending>,
|
||||
counts: Counts,
|
||||
/// Each command `vc.run` ran: its calls, its total time and its longest call, in nanoseconds.
|
||||
commands: RefCell<HashMap<&'static str, (u64, u128, u128)>>,
|
||||
/// The time the run's slices took, in nanoseconds.
|
||||
run_nanos: Cell<u128>,
|
||||
}
|
||||
|
||||
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
|
||||
#[derive(Default)]
|
||||
struct Counts {
|
||||
vc_run: Cell<u64>,
|
||||
document_reads: Cell<u64>,
|
||||
command_list_reads: Cell<u64>,
|
||||
vc_log: Cell<u64>,
|
||||
console_writes: Cell<u64>,
|
||||
}
|
||||
|
||||
impl Counts {
|
||||
fn json(&self) -> Value {
|
||||
json!({
|
||||
"vcRun": self.vc_run.get(),
|
||||
"documentReads": self.document_reads.get(),
|
||||
"commandListReads": self.command_list_reads.get(),
|
||||
"vcLog": self.vc_log.get(),
|
||||
"consoleWrites": self.console_writes.get(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn bump(c: &Cell<u64>) {
|
||||
c.set(c.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// Now, where the platform has a clock (not in a wasm build).
|
||||
fn clock() -> Option<std::time::Instant> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
Some(std::time::Instant::now())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Whole milliseconds, rounded down.
|
||||
fn millis(nanos: u128) -> u64 {
|
||||
u64::try_from(nanos / 1_000_000).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
/// The [`SLOWEST_COMMANDS`] commands of `times` that took longest in all, longest first and then by
|
||||
/// id.
|
||||
pub(crate) fn slowest(times: &HashMap<&'static str, (u64, u128, u128)>) -> Vec<console::Slow> {
|
||||
let mut all: Vec<(&&str, &(u64, u128, u128))> = times.iter().collect();
|
||||
all.sort_by(|a, b| b.1.1.cmp(&a.1.1).then_with(|| a.0.cmp(b.0)));
|
||||
all.into_iter()
|
||||
.take(SLOWEST_COMMANDS)
|
||||
.map(|(id, &(calls, total, max))| console::Slow { id: (*id).to_string(), calls, total_ms: millis(total), max_ms: millis(max) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// Adds a line to the run's console and, during a slice, to the session's.
|
||||
fn line(&self, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
|
||||
if let Ok(mut s) = self.session.try_borrow_mut() {
|
||||
s.script_console.push(line.clone(), cut);
|
||||
}
|
||||
self.console.borrow_mut().push(line, cut);
|
||||
}
|
||||
|
||||
/// `$.write` and `$.writeln`: `text`, then with `end` a line break.
|
||||
fn write(&self, text: &str, end: bool) {
|
||||
let mut pending = self.pending.borrow_mut();
|
||||
pending.write(text, |line, cut| self.line(console::Entry::Output(line), cut));
|
||||
if end {
|
||||
pending.end_line(|line, cut| self.line(console::Entry::Output(line), cut));
|
||||
}
|
||||
}
|
||||
fn over(&self, limit: &str) -> HostError {
|
||||
HostError::Abort(limit.to_string())
|
||||
}
|
||||
@@ -706,11 +799,20 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
};
|
||||
let bytes = args.iter().map(data_size).sum();
|
||||
host.charge_call(bytes)?;
|
||||
bump(&host.counts.vc_run);
|
||||
let session = host.session.clone();
|
||||
let started = clock();
|
||||
let r = {
|
||||
let mut s = session.borrow_mut();
|
||||
step(&mut s, host, &id, ¶ms)
|
||||
};
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
let mut times = host.commands.borrow_mut();
|
||||
let row = times.entry(spec.id).or_insert((0, 0, 0));
|
||||
*row = (row.0 + 1, row.1.saturating_add(nanos), row.2.max(nanos));
|
||||
}
|
||||
let (value, objects, added, save) = match r {
|
||||
Ok(done) => done,
|
||||
// A bug is not something a script can handle, and neither is a request to stop.
|
||||
@@ -778,10 +880,39 @@ fn vc_log(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError>
|
||||
return Err(HostError::Range(LOG_FULL.to_string()));
|
||||
}
|
||||
host.log_bytes.set(host.log_bytes.get() + bytes);
|
||||
host.log.borrow_mut().push(to_json(entry));
|
||||
let value = to_json(entry);
|
||||
let text = match &value {
|
||||
Value::String(s) => s.clone(),
|
||||
v => v.to_string(),
|
||||
};
|
||||
host.log.borrow_mut().push(value);
|
||||
each_line(&text, |line, cut| host.line(console::Entry::Log(line), cut));
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// Calls `done` with each console line of `text` and whether that line was cut, one at a time.
|
||||
fn each_line(text: &str, mut done: impl FnMut(String, bool)) {
|
||||
let mut pending = console::Pending::default();
|
||||
pending.write(text, &mut done);
|
||||
pending.end_line(done);
|
||||
}
|
||||
|
||||
/// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)`
|
||||
/// gives them, one after another, and `$.writeln(...values)` does the same and ends the line.
|
||||
fn dollar_object(host: &Rc<Host>) -> Vec<(String, HostItem)> {
|
||||
let writer = |end: bool| {
|
||||
let h = host.clone();
|
||||
HostItem::TextFunction(function(move |a| {
|
||||
let text: String = a.iter().map(|d| if let Data::String(s) = d { s.as_str() } else { "" }).collect();
|
||||
h.charge_call(text.len() as u64 + 2)?;
|
||||
bump(&h.counts.console_writes);
|
||||
h.write(&text, end);
|
||||
Ok(Data::Undefined)
|
||||
}))
|
||||
};
|
||||
vec![("write".into(), writer(false)), ("writeln".into(), writer(true))]
|
||||
}
|
||||
|
||||
fn function(f: impl Fn(Vec<Data>) -> std::result::Result<Data, HostError> + 'static) -> HostFunction {
|
||||
Rc::new(f)
|
||||
}
|
||||
@@ -795,6 +926,7 @@ fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> {
|
||||
let h = host.clone();
|
||||
function(move |_| {
|
||||
h.charge_call(64)?;
|
||||
bump(&h.counts.document_reads);
|
||||
vc_document(&h)
|
||||
})
|
||||
};
|
||||
@@ -804,6 +936,7 @@ fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> {
|
||||
let size = data_size(&list);
|
||||
function(move |_| {
|
||||
h.charge_call(size)?;
|
||||
bump(&h.counts.command_list_reads);
|
||||
Ok((*list).clone())
|
||||
})
|
||||
};
|
||||
@@ -811,6 +944,7 @@ fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> {
|
||||
let h = host.clone();
|
||||
function(move |a| {
|
||||
h.charge_call(data_size(a.first().unwrap_or(&Data::Undefined)))?;
|
||||
bump(&h.counts.vc_log);
|
||||
vc_log(&h, a)
|
||||
})
|
||||
};
|
||||
@@ -841,8 +975,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
|
||||
|
||||
/// `message`, with what to do about a failure that comes from a script written for another program.
|
||||
fn explained(kind: &RunErrorKind, message: &str, source: &str, line: u32) -> String {
|
||||
const HOST_OBJECTS: &[&str] =
|
||||
&["app", "$", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"];
|
||||
const HOST_OBJECTS: &[&str] = &["app", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"];
|
||||
let names_host_object =
|
||||
message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o)));
|
||||
let directive =
|
||||
@@ -873,6 +1006,19 @@ impl Session {
|
||||
self.script_report.as_ref()
|
||||
}
|
||||
|
||||
/// The Script Console: the lines of this session's runs, oldest first.
|
||||
pub fn script_console(&self) -> &console::Console {
|
||||
&self.script_console
|
||||
}
|
||||
|
||||
/// Empties the Script Console and sets its counts to zero. The last run's report, and the
|
||||
/// report of a running script, keep their lines. → the lines removed.
|
||||
pub fn clear_script_console(&mut self) -> usize {
|
||||
let n = self.script_console.lines().len();
|
||||
self.script_console.clear();
|
||||
n
|
||||
}
|
||||
|
||||
/// The error text of the last run when it failed: its name, place, message and kind, and the
|
||||
/// files it left written.
|
||||
pub fn script_failure_text(&self) -> Option<String> {
|
||||
@@ -962,6 +1108,7 @@ impl Session {
|
||||
let mut realm = Realm::with_options(options, limits);
|
||||
realm.share_interrupt(&self.script_stop);
|
||||
realm.set_data_limits(DataLimits::default());
|
||||
self.script_runs += 1;
|
||||
let host = Rc::new(Host {
|
||||
session: Rc::new(RefCell::new(Session::new())),
|
||||
pause: realm.pause_flag(),
|
||||
@@ -978,12 +1125,25 @@ impl Session {
|
||||
log: RefCell::new(Vec::new()),
|
||||
log_bytes: Cell::new(0),
|
||||
written: RefCell::new(Vec::new()),
|
||||
run: self.script_runs,
|
||||
name: console::line_name(&request.name),
|
||||
console: RefCell::default(),
|
||||
pending: RefCell::default(),
|
||||
counts: Counts::default(),
|
||||
commands: RefCell::default(),
|
||||
run_nanos: Cell::new(0),
|
||||
});
|
||||
let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0))
|
||||
.map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?;
|
||||
let started = realm.define_host_object("vc", vc_object(&host, args)).and_then(|()| realm.start(&request.source));
|
||||
let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start };
|
||||
self.script_console.push(line, false);
|
||||
let started = realm
|
||||
.define_host_object("vc", vc_object(&host, args))
|
||||
.and_then(|()| realm.define_host_object("$", dollar_object(&host)))
|
||||
.and_then(|()| realm.start(&request.source));
|
||||
if let Err(e) = started {
|
||||
let report = failure_report(&request.name, &e, &request.source, &host, 0);
|
||||
let mut report = failure_report(&request.name, &e, &request.source, &host, 0, 0);
|
||||
close_run(self, &host, &mut report, ending(&e.kind));
|
||||
let message = failure_text(&report);
|
||||
self.script_report = Some(report);
|
||||
return Err(EngineError::Other(message));
|
||||
@@ -1033,7 +1193,9 @@ impl Session {
|
||||
}
|
||||
|
||||
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
|
||||
let report = failure_report(&job.name, e, "", &job.host, job.realm.fuel_left());
|
||||
let fuel_left = job.realm.fuel_left();
|
||||
let mut report = failure_report(&job.name, e, "", &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
close_run(self, &job.host, &mut report, ending(&e.kind));
|
||||
drop(job);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
@@ -1106,7 +1268,7 @@ impl Session {
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
let host = &job.host;
|
||||
let report = json!({
|
||||
let mut report = json!({
|
||||
"ok": true,
|
||||
"name": job.name,
|
||||
"changed": changed_names,
|
||||
@@ -1115,6 +1277,7 @@ impl Session {
|
||||
"fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(),
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
self.script_report = Some(report.clone());
|
||||
Ok(report)
|
||||
}
|
||||
@@ -1147,7 +1310,7 @@ const LOG_FULL: &str = "vc.log: the log of this run is full";
|
||||
const NO_RECOVERY_COPY: &str = "a recovery copy could not be written, so the script was not run";
|
||||
|
||||
/// The report of a run that failed.
|
||||
fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left: u64) -> Value {
|
||||
fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left: u64, fuel_used: u64) -> Value {
|
||||
json!({
|
||||
"ok": false,
|
||||
"kind": kind_id(&e.kind),
|
||||
@@ -1158,9 +1321,67 @@ fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left
|
||||
"written": *host.written.borrow(),
|
||||
"log": *host.log.borrow(),
|
||||
"fuelLeft": fuel_left,
|
||||
"fuelUsed": fuel_used,
|
||||
"hostCalls": host.calls.get(),
|
||||
})
|
||||
}
|
||||
|
||||
/// How the run that failed with `kind` ended, as its console end line gives it.
|
||||
fn ending(kind: &RunErrorKind) -> console::Ending {
|
||||
match kind {
|
||||
RunErrorKind::Syntax | RunErrorKind::Thrown => console::Ending::Error,
|
||||
RunErrorKind::Limit(LimitKind::Fuel) => console::Ending::Fuel,
|
||||
RunErrorKind::Limit(LimitKind::Host) => console::Ending::HostLimit,
|
||||
RunErrorKind::Limit(LimitKind::Interrupted) => console::Ending::Stopped,
|
||||
RunErrorKind::Limit(_) => console::Ending::Limit,
|
||||
RunErrorKind::Internal => console::Ending::Internal,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a line of `host`'s run to the session's console and to the run's own.
|
||||
fn line_to(s: &mut Session, host: &Host, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry };
|
||||
s.script_console.push(line.clone(), cut);
|
||||
host.console.borrow_mut().push(line, cut);
|
||||
}
|
||||
|
||||
/// Ends the console lines of `host`'s run: the line `$.write` left unended, then for a failed run
|
||||
/// (`report["ok"]` false) its error as `name:line:column: message`, then an end line and a report
|
||||
/// line in the session's console. Adds the run's time, host calls by kind, slowest commands and
|
||||
/// console to `report`.
|
||||
fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::Ending) {
|
||||
let mut pending = std::mem::take(&mut *host.pending.borrow_mut());
|
||||
if !pending.is_empty() {
|
||||
let mut last = None;
|
||||
pending.end_line(|line, cut| last = Some((line, cut)));
|
||||
if let Some((line, cut)) = last {
|
||||
line_to(s, host, console::Entry::Output(line), cut);
|
||||
}
|
||||
}
|
||||
if report["ok"] == false {
|
||||
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
|
||||
let message = report["message"].as_str().unwrap_or_default();
|
||||
let text =
|
||||
if line > 0 { format!("{}:{line}:{column}: {message}", host.name) } else { format!("{}: location unavailable: {message}", host.name) };
|
||||
each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
}
|
||||
let timing = clock().is_some();
|
||||
let ms = millis(host.run_nanos.get());
|
||||
let slow = slowest(&host.commands.borrow());
|
||||
let slow_json: Vec<Value> = slow.iter().map(|c| json!({"id": c.id, "calls": c.calls, "totalMs": c.total_ms, "maxMs": c.max_ms})).collect();
|
||||
let line = |entry| console::ConsoleLine { run: host.run, name: host.name.clone(), entry };
|
||||
s.script_console.push(line(console::Entry::End(ending)), false);
|
||||
let summary = console::Entry::Report { ms: timing.then_some(ms), host_calls: host.calls.get(), slowest: slow };
|
||||
s.script_console.push(line(summary), false);
|
||||
if let Some(o) = report.as_object_mut() {
|
||||
o.insert("runTimeMs".into(), json!(if timing { ms } else { 0 }));
|
||||
o.insert("timingAvailable".into(), json!(timing));
|
||||
o.insert("hostCallCounts".into(), host.counts.json());
|
||||
o.insert("slowestCommands".into(), Value::Array(slow_json));
|
||||
o.insert("console".into(), host.console.borrow().report());
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a failed run's error.
|
||||
fn failure_text(report: &Value) -> String {
|
||||
let s = |k: &str| report[k].as_str().unwrap_or_default();
|
||||
@@ -1187,6 +1408,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
let scope = job.scope.clone();
|
||||
let realm = &mut job.realm;
|
||||
let started = clock();
|
||||
let r = scope.run(|| {
|
||||
guard::catch_panic(|| {
|
||||
#[cfg(test)]
|
||||
@@ -1196,6 +1418,9 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
realm.advance(SLICE_FUEL)
|
||||
})
|
||||
});
|
||||
if let Some(started) = started {
|
||||
job.host.run_nanos.set(job.host.run_nanos.get().saturating_add(started.elapsed().as_nanos()));
|
||||
}
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
s.script_in_run = false;
|
||||
job.world.swap(s);
|
||||
|
||||
@@ -135,6 +135,8 @@ impl Session {
|
||||
script_key: None,
|
||||
script_stop: vectorcraft_js::Interrupt::new(),
|
||||
script_report: None,
|
||||
script_console: Default::default(),
|
||||
script_runs: 0,
|
||||
script_frames: false,
|
||||
script_high_water: Default::default(),
|
||||
script_in_run: false,
|
||||
|
||||
@@ -150,6 +150,7 @@ mod repeat_edit;
|
||||
mod save;
|
||||
mod saveoptions;
|
||||
mod scalestrokes;
|
||||
mod script_console;
|
||||
mod script_run;
|
||||
mod scripts;
|
||||
mod select_ids_first;
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! The Script Console: `$.write` and `$.writeln`, `vc.log` lines, the bounded store of a session
|
||||
//! and of a run, errors with their place, the end and report lines, and the diagnostics a run's
|
||||
//! report holds.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::console::{CUT_MARK, MAX_CONSOLE_BYTES, MAX_CONSOLE_LINES, MAX_LINE_BYTES, MAX_NAME_BYTES};
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// The session console's `(run, kind, text)` lines.
|
||||
fn lines(s: &mut Session) -> Vec<(u64, String, String)> {
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
c["lines"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|l| (l["run"].as_u64().unwrap(), l["kind"].as_str().unwrap().to_string(), l["text"].as_str().unwrap().to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn texts(s: &mut Session, kind: &str) -> Vec<String> {
|
||||
lines(s).into_iter().filter(|(_, k, _)| k == kind).map(|(_, _, t)| t).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_and_writeln_join_their_values_and_break_lines() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "$.write('a', 1, null, undefined, 1/0); $.write('b\\r\\nc\\rd\\n'); $.writeln(); $.write('x\\r'); $.write('\\ny'); $.writeln([1, 2], {}); $.write('p\\r'); $.write(''); $.write('\\nq'); $.writeln(); $.write('\\0\\t\\u2028\\x7f')").unwrap();
|
||||
let want = ["a1nullundefinedInfinityb", "c", "d", "", "x", "y1,2[object Object]", "p", "q", "\u{2400}\u{2409}\u{2424}\u{2421}"];
|
||||
assert_eq!(texts(&mut s, "output"), want);
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["console"]["lines"], json!(want), "the run's own console holds the same output");
|
||||
assert_eq!(report["hostCallCounts"]["consoleWrites"], 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_endless_writeln_stays_within_the_line_limit_and_counts_what_it_dropped() {
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("script.run", &json!({"source": "while (1) $.writeln('x')", "name": "t.js", "maxFuel": 2_000_000})).unwrap_err();
|
||||
assert!(e.to_string().ends_with("(limit)"), "{e}");
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
let kept = c["lines"].as_array().unwrap().len();
|
||||
assert_eq!(kept, MAX_CONSOLE_LINES);
|
||||
let report = s.script_report().unwrap().clone();
|
||||
let writes = report["hostCallCounts"]["consoleWrites"].as_u64().unwrap();
|
||||
assert!(writes > MAX_CONSOLE_LINES as u64 * 2, "{writes} writes");
|
||||
// The session console holds a start line, the output, an error, an end and a report line.
|
||||
assert_eq!(c["droppedLines"].as_u64().unwrap(), writes + 4 - MAX_CONSOLE_LINES as u64);
|
||||
assert_eq!(report["console"]["lines"].as_array().unwrap().len(), MAX_CONSOLE_LINES);
|
||||
assert_eq!(report["console"]["droppedLines"].as_u64().unwrap(), writes + 1 - MAX_CONSOLE_LINES as u64);
|
||||
assert!(report["fuelUsed"].as_u64().unwrap() > 1_900_000);
|
||||
assert_eq!(report["hostCalls"].as_u64().unwrap(), writes);
|
||||
let tail = lines(&mut s);
|
||||
let ends: Vec<&str> = tail.iter().rev().take(3).map(|(_, k, t)| if k == "error" { "error" } else { t.as_str() }).collect();
|
||||
assert_eq!(ends[1], "ended: fuel");
|
||||
assert_eq!(ends[2], "error", "{tail:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_lines_stay_within_the_byte_limit() {
|
||||
let mut s = Session::new();
|
||||
let source = "var l = new Array(4000).join('y'); for (var i = 0; i < 400; i++) $.writeln(l)";
|
||||
run(&mut s, source).unwrap();
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
let bytes: usize = c["lines"].as_array().unwrap().iter().map(|l| l["text"].as_str().unwrap().len()).sum();
|
||||
assert!(bytes <= MAX_CONSOLE_BYTES, "{bytes}");
|
||||
let kept = c["lines"].as_array().unwrap().len();
|
||||
assert!(kept < 400 && kept > 200, "{kept} lines");
|
||||
assert!(c["droppedLines"].as_u64().unwrap() > 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_line_is_cut_at_a_character_boundary_and_counted() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "$.writeln(new Array(5000).join('é')); $.write(new Array(3000).join('a')); $.write(new Array(3000).join('b')); $.writeln('c'); $.writeln('ok')")
|
||||
.unwrap();
|
||||
let out = texts(&mut s, "output");
|
||||
assert_eq!(out.len(), 3);
|
||||
for line in &out[..2] {
|
||||
assert!(line.len() <= MAX_LINE_BYTES && line.len() > MAX_LINE_BYTES - 8, "{}", line.len());
|
||||
assert!(line.ends_with(CUT_MARK));
|
||||
}
|
||||
assert!(!out[1].contains('c'), "the rest of a cut line is left out until it ends");
|
||||
assert_eq!(out[2], "ok");
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
assert_eq!(c["truncatedLines"], 2);
|
||||
assert_eq!(s.script_report().unwrap()["console"]["truncatedLines"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_script_name_is_cut_in_every_line_and_shows_its_control_characters() {
|
||||
let mut s = Session::new();
|
||||
let name = format!("a\nb{}", "é".repeat(100_000));
|
||||
s.execute("script.run", &json!({"source": "$.writeln('x'); $.writeln('y')", "name": name})).unwrap();
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
let names: Vec<&str> = c["lines"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names.len(), 5);
|
||||
for n in names {
|
||||
assert!(n.len() <= MAX_NAME_BYTES && n.len() > MAX_NAME_BYTES - 8, "{}", n.len());
|
||||
assert!(n.starts_with("a\u{240a}b") && n.ends_with(CUT_MARK), "{n}");
|
||||
}
|
||||
assert_eq!(s.script_report().unwrap()["name"].as_str().map(str::len), Some(name.len()), "the report keeps the name given");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_uncaught_error_shows_the_script_its_line_and_column() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "$.write('half');\n\n throw new Error('boom\\nsecond');").unwrap_err();
|
||||
let all = lines(&mut s);
|
||||
let kinds: Vec<&str> = all.iter().map(|(_, k, _)| k.as_str()).collect();
|
||||
assert_eq!(kinds, ["start", "output", "error", "error", "end", "report"]);
|
||||
assert_eq!(all[1].2, "half", "a line left unended still shows");
|
||||
assert_eq!(all[2].2, "t.js:3:3: Error: boom");
|
||||
assert_eq!(all[3].2, "second");
|
||||
assert_eq!(all[4].2, "ended: error");
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["console"]["lines"], json!(["half", "t.js:3:3: Error: boom", "second"]));
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "var = 1").unwrap_err();
|
||||
assert!(texts(&mut s, "error")[0].starts_with("t.js:1:"), "a syntax error has its place too");
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
run(&mut s, "while (true) {}").unwrap();
|
||||
s.script_abandon();
|
||||
assert_eq!(texts(&mut s, "error"), ["t.js: location unavailable: limit reached: Interrupted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_result_and_the_report_agree_and_count_each_kind_of_host_call() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let source = "vc.run('shape.rectangle', {x:0,y:0,width:5,height:5}); vc.run('shape.rectangle', {x:9,y:0,width:5,height:5}); \
|
||||
try { vc.run('no.such', {}); } catch (e) {} var d = vc.document; var c = vc.commands; vc.log({a: 1}); vc.log('two\\nlines'); $.writeln('w');";
|
||||
let r = run(&mut s, source).unwrap();
|
||||
assert_eq!(&r, s.script_report().unwrap());
|
||||
assert_eq!(r["hostCallCounts"], json!({"vcRun": 3, "documentReads": 1, "commandListReads": 1, "vcLog": 2, "consoleWrites": 1}));
|
||||
assert_eq!(r["timingAvailable"], true);
|
||||
assert!(r["runTimeMs"].is_u64());
|
||||
let slow = r["slowestCommands"].as_array().unwrap();
|
||||
assert_eq!(slow.len(), 1, "an unknown command is not timed: {slow:?}");
|
||||
assert_eq!((slow[0]["id"].as_str(), slow[0]["calls"].as_u64()), (Some("shape.rectangle"), Some(2)));
|
||||
assert!(slow[0]["maxMs"].as_u64() <= slow[0]["totalMs"].as_u64());
|
||||
assert_eq!(r["console"]["lines"], json!(["{\"a\":1}", "two", "lines", "w"]));
|
||||
assert_eq!(texts(&mut s, "log"), ["{\"a\":1}", "two", "lines"]);
|
||||
assert_eq!(texts(&mut s, "end"), ["ended: finished"]);
|
||||
assert!(texts(&mut s, "report")[0].contains("host calls; slowest: shape.rectangle ×2"), "{:?}", texts(&mut s, "report"));
|
||||
assert_eq!(r["log"], json!([{"a": 1}, "two\nlines"]), "the log keeps its values");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_run_reports_its_diagnostics_and_its_unended_line() {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
run(&mut s, "$.write('so far'); vc.log(1); while (true) {}").unwrap();
|
||||
assert!(s.script_pump().is_none());
|
||||
assert_eq!(texts(&mut s, "log"), ["1"], "a line shows while the run goes on");
|
||||
s.execute("script.stop", &json!({})).unwrap();
|
||||
assert!(s.script_pump().unwrap().is_err());
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["kind"], "stopped");
|
||||
for key in ["runTimeMs", "hostCallCounts", "slowestCommands", "console", "fuelUsed", "hostCalls", "timingAvailable"] {
|
||||
assert!(!report[key].is_null(), "{key}: {report}");
|
||||
}
|
||||
assert_eq!(report["hostCalls"], 2);
|
||||
assert_eq!(texts(&mut s, "output"), ["so far"]);
|
||||
assert_eq!(texts(&mut s, "end"), ["ended: stopped"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_are_numbered_a_busy_run_adds_nothing_and_clear_keeps_the_report() {
|
||||
let mut s = Session::new();
|
||||
for _ in 0..3 {
|
||||
run(&mut s, "for (var i = 0; i < 1000; i++) $.writeln(i)").unwrap();
|
||||
}
|
||||
let all = lines(&mut s);
|
||||
assert_eq!(all.len(), MAX_CONSOLE_LINES);
|
||||
assert_eq!(all.last().map(|l| l.0), Some(3));
|
||||
s.script_frames = true;
|
||||
run(&mut s, "$.writeln('four'); while (true) {}").unwrap();
|
||||
assert!(s.script_pump().is_none());
|
||||
let before = lines(&mut s);
|
||||
assert!(matches!(run(&mut s, "$.writeln('five')"), Err(EngineError::Busy)));
|
||||
assert_eq!(lines(&mut s), before, "a refused run adds no line");
|
||||
assert_eq!(s.execute("script.console.clear", &json!({})).unwrap()["cleared"], MAX_CONSOLE_LINES);
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
assert_eq!((c["lines"].as_array().map(Vec::len), c["droppedLines"].as_u64()), (Some(0), Some(0)));
|
||||
s.execute("script.stop", &json!({})).unwrap();
|
||||
assert!(s.script_pump().unwrap().is_err());
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["console"]["lines"][0], "four", "a clear leaves the running script's own console");
|
||||
assert_eq!(texts(&mut s, "end"), ["ended: stopped"], "the run goes on writing after a clear");
|
||||
assert_eq!(lines(&mut s)[0].0, 4);
|
||||
let mut other = Session::new();
|
||||
assert!(lines(&mut other).is_empty(), "each session has its own console");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_slowest_commands_are_the_longest_in_all_then_by_id() {
|
||||
let times = std::collections::HashMap::from([
|
||||
("a.one", (1, 5_000_000, 5_000_000)),
|
||||
("b.two", (3, 9_000_000, 4_000_000)),
|
||||
("c.three", (1, 5_000_000, 5_000_000)),
|
||||
("d", (1, 1, 1)),
|
||||
("e", (1, 2, 2)),
|
||||
("f", (1, 3, 3)),
|
||||
]);
|
||||
let slow = script::slowest(×);
|
||||
let ids: Vec<&str> = slow.iter().map(|c| c.id.as_str()).collect();
|
||||
assert_eq!(ids, ["b.two", "a.one", "c.three", "f", "e"]);
|
||||
assert_eq!((slow[0].calls, slow[0].total_ms, slow[0].max_ms), (3, 9, 4));
|
||||
}
|
||||
@@ -175,12 +175,14 @@ pub(crate) enum NativeKind {
|
||||
|
||||
/// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section
|
||||
/// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given.
|
||||
/// `Data` is a host function given [`crate::Data`]; with `text`, each argument arrives as the
|
||||
/// string `String(value)` gives.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Func {
|
||||
Closure { code: Rc<Code>, env: EnvId },
|
||||
Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str },
|
||||
Host { f: Rc<HostFn>, name: Rc<str> },
|
||||
Data { f: DataFn, name: Rc<str> },
|
||||
Data { f: DataFn, name: Rc<str>, text: bool },
|
||||
Bound { target: ObjId, this: Value, args: Rc<[Value]> },
|
||||
}
|
||||
|
||||
|
||||
+33
-7
@@ -68,6 +68,8 @@ pub enum HostItem {
|
||||
/// A read-only copy of a value.
|
||||
Value(Data),
|
||||
Function(HostFunction),
|
||||
/// A function whose arguments arrive as strings, each the string `String(value)` gives.
|
||||
TextFunction(HostFunction),
|
||||
/// A property whose value the function gives each time it is read.
|
||||
Getter(HostFunction),
|
||||
/// A frozen object with these members.
|
||||
@@ -275,15 +277,31 @@ impl Interp {
|
||||
Ok(Value::Object(id))
|
||||
}
|
||||
|
||||
/// Calls host function `f`: reads its arguments, runs it, and gives its result to the script.
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, args: &[Value]) -> JsResult<Value> {
|
||||
/// Calls host function `f`: reads its arguments (with `text`, each as the string `String(value)`
|
||||
/// gives), runs it, and gives its result to the script.
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, args: &[Value], text: bool) -> JsResult<Value> {
|
||||
let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() };
|
||||
let mut data = Vec::with_capacity(args.len());
|
||||
// A conversion can run the script's own `toString`, which may collect garbage.
|
||||
let mark = self.temp_roots.len();
|
||||
if text {
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
}
|
||||
let mut read = Ok(());
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX)));
|
||||
data.push(self.read_data(a, &mut reading)?);
|
||||
let d = if text { self.read_text(a, &mut reading) } else { self.read_data(a, &mut reading) };
|
||||
match d {
|
||||
Ok(d) => data.push(d),
|
||||
Err(e) => {
|
||||
read = Err(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
reading.path.pop();
|
||||
}
|
||||
self.temp_roots.truncate(mark);
|
||||
read?;
|
||||
match f(data) {
|
||||
Ok(d) => self.write_data(d, 0, false),
|
||||
Err(HostError::Abort(message)) => {
|
||||
@@ -296,6 +314,13 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as the string `String(v)` gives, within the limits of a crossing.
|
||||
fn read_text(&mut self, v: &Value, r: &mut Reading) -> JsResult<Data> {
|
||||
let s = self.to_str(v)?;
|
||||
self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?;
|
||||
Ok(Data::String(s.to_rust_string()))
|
||||
}
|
||||
|
||||
/// The exception for a host error, charged to the heap.
|
||||
fn throw_host(&mut self, t: ErrorType, message: &str) -> JsResult<Abrupt> {
|
||||
let bytes = string_bytes(message.encode_utf16().count());
|
||||
@@ -332,16 +357,17 @@ impl Interp {
|
||||
let full = format!("{path}.{name}");
|
||||
let prop = match item {
|
||||
HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE },
|
||||
HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full)), flags: ENUMERABLE },
|
||||
HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full)), set: None, flags: ENUMERABLE },
|
||||
HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, false)), flags: ENUMERABLE },
|
||||
HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, true)), flags: ENUMERABLE },
|
||||
HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, false)), set: None, flags: ENUMERABLE },
|
||||
HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE },
|
||||
};
|
||||
self.define(o, key(&name), prop)
|
||||
}
|
||||
|
||||
fn host_function(&mut self, f: HostFunction, name: &str) -> ObjId {
|
||||
fn host_function(&mut self, f: HostFunction, name: &str, text: bool) -> ObjId {
|
||||
let proto = self.intrinsics.function_proto;
|
||||
self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into() }), Some(proto)))
|
||||
self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), text }), Some(proto)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -223,6 +223,25 @@ fn a_getter_is_read_each_time() {
|
||||
assert_eq!(r.run("host.n + host.n").unwrap(), JsValue::Number(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_function_takes_each_argument_as_string_gives_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
let seen: Rc<RefCell<Vec<Data>>> = Rc::default();
|
||||
let log = seen.clone();
|
||||
let f: HostFunction = Rc::new(move |args| {
|
||||
log.borrow_mut().extend(args);
|
||||
Ok(Data::Undefined)
|
||||
});
|
||||
r.define_host_object("host", vec![("text".into(), HostItem::TextFunction(f))]).unwrap();
|
||||
r.run("host.text(1 / 0, NaN, undefined, null, 0.1, [1, [2]], {toString: function () { return 'own'; }}, function f() {}, '\\ud800x')").unwrap();
|
||||
let texts: Vec<String> = seen.borrow().iter().map(|d| if let Data::String(s) = d { s.clone() } else { format!("{d:?}") }).collect();
|
||||
assert_eq!(texts[..7], ["Infinity", "NaN", "undefined", "null", "0.1", "1,2", "own"]);
|
||||
assert!(texts[7].starts_with("function f()"), "{}", texts[7]);
|
||||
assert_eq!(texts[8], "\u{fffd}x", "a lone surrogate becomes U+FFFD");
|
||||
let e = r.run("host.text({toString: function () { throw new Error('no text'); }})").unwrap_err();
|
||||
assert!(e.message.contains("no text"), "{}", e.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_from_the_host_can_be_caught_and_an_abort_cannot() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
@@ -1846,10 +1846,10 @@ impl Interp {
|
||||
self.temp_roots.truncate(mark);
|
||||
return Ok(Prepared::Done(r?));
|
||||
}
|
||||
Func::Data { f, name } => {
|
||||
Func::Data { f, name, text } => {
|
||||
// The arguments are read before the function runs, and a result being built
|
||||
// keeps itself reachable.
|
||||
return Ok(Prepared::Done(self.call_data(&f, &name, &args)?));
|
||||
return Ok(Prepared::Done(self.call_data(&f, &name, &args, text)?));
|
||||
}
|
||||
Func::Host { f: host, .. } => {
|
||||
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
|
||||
|
||||
@@ -6488,3 +6488,18 @@ breakText Glyphs Глифи
|
||||
@msg side is left or right, not `{s}` side е left или right, а не `{s}`
|
||||
Edit Custom Dictionary Редактиране на потребителски речник
|
||||
Entry: Запис:
|
||||
# Script Console
|
||||
Script Console Конзола за скриптове
|
||||
Clear Script Console Изчистване на конзолата за скриптове
|
||||
Copy Script Console Копиране на конзолата за скриптове
|
||||
Copy All Копиране на всичко
|
||||
Copy Selected Копиране на избраното
|
||||
Finished Завършен
|
||||
Ended with an error Прекратен с грешка
|
||||
Out of fuel Достигнат лимит на инструкциите
|
||||
Ended at a host limit Прекратен при лимит на хоста
|
||||
Ended at a limit Прекратен при лимит
|
||||
Stopped Спрян
|
||||
Ended by an internal fault Прекратен поради вътрешна грешка
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} извиквания към хоста
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} по-ранни реда премахнати, {cut} реда съкратени
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6539,3 +6539,18 @@ shape Open Otvoren
|
||||
@msg side is left or right, not `{s}` side je left ili right, a ne `{s}`
|
||||
Edit Custom Dictionary Uredi prilagođeni rječnik
|
||||
Entry: Unos:
|
||||
# Script Console
|
||||
Script Console Konzola skripti
|
||||
Clear Script Console Očisti konzolu skripti
|
||||
Copy Script Console Kopiraj konzolu skripti
|
||||
Copy All Kopiraj sve
|
||||
Copy Selected Kopiraj odabrano
|
||||
Finished Završeno
|
||||
Ended with an error Završeno s greškom
|
||||
Out of fuel Dostignuto ograničenje instrukcija
|
||||
Ended at a host limit Završeno na ograničenju hosta
|
||||
Ended at a limit Završeno na ograničenju
|
||||
Stopped Zaustavljeno
|
||||
Ended by an internal fault Završeno zbog interne greške
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} poziva hosta
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} ranijih redova uklonjeno, {cut} redova skraćeno
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6741,3 +6741,19 @@ breakText Glyphs Glifs
|
||||
No Suggestions No hi ha suggeriments
|
||||
Edit Custom Dictionary Edita el diccionari personalitzat
|
||||
Entry: Entrada:
|
||||
# Script Console
|
||||
Script Console Consola d’scripts
|
||||
Clear Script Console Esborra la consola d’scripts
|
||||
Copy Script Console Copia la consola d’scripts
|
||||
Copy All Copia-ho tot
|
||||
Copy Selected Copia la selecció
|
||||
Finished Acabat
|
||||
Ended with an error Acabat amb un error
|
||||
Out of fuel Límit d’instruccions esgotat
|
||||
Ended at a host limit Acabat en un límit de l’amfitrió
|
||||
Ended at a limit Acabat en un límit
|
||||
Stopped Aturat
|
||||
Ended by an internal fault Acabat per un error intern
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} crides a l’amfitrió
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} línies anteriors descartades, {cut} línies tallades
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` han de ser números de línies que la consola conserva, `first` abans de `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6760,3 +6760,19 @@ breakText Glyphs Glyfy
|
||||
No Suggestions Žádné návrhy
|
||||
Edit Custom Dictionary Upravit vlastní slovník
|
||||
Entry: Položka:
|
||||
# Script Console
|
||||
Script Console Konzole skriptů
|
||||
Clear Script Console Vymazat konzoli skriptů
|
||||
Copy Script Console Kopírovat konzoli skriptů
|
||||
Copy All Kopírovat vše
|
||||
Copy Selected Kopírovat vybrané
|
||||
Finished Dokončeno
|
||||
Ended with an error Ukončeno s chybou
|
||||
Out of fuel Vyčerpán limit instrukcí
|
||||
Ended at a host limit Ukončeno na limitu hostitele
|
||||
Ended at a limit Ukončeno na limitu
|
||||
Stopped Zastaveno
|
||||
Ended by an internal fault Ukončeno vnitřní chybou
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} volání hostitele
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} starších řádků zahozeno, {cut} řádků zkráceno
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` a `last` musí být čísla řádků, které konzole uchovává, `first` před `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6502,3 +6502,18 @@ breakText Glyphs Glyffer
|
||||
@msg side is left or right, not `{s}` side er left eller right, ikke `{s}`
|
||||
Edit Custom Dictionary Redigér egen ordliste
|
||||
Entry: Opslag:
|
||||
# Script Console
|
||||
Script Console Scriptkonsol
|
||||
Clear Script Console Ryd scriptkonsollen
|
||||
Copy Script Console Kopiér scriptkonsollen
|
||||
Copy All Kopiér alt
|
||||
Copy Selected Kopiér markeret
|
||||
Finished Færdig
|
||||
Ended with an error Afsluttet med en fejl
|
||||
Out of fuel Instruktionsgrænsen er nået
|
||||
Ended at a host limit Afsluttet ved en værtsgrænse
|
||||
Ended at a limit Afsluttet ved en grænse
|
||||
Stopped Stoppet
|
||||
Ended by an internal fault Afsluttet af en intern fejl
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} værtskald
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} tidligere linjer fjernet, {cut} linjer afkortet
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6347,3 +6347,19 @@ breakText Glyphs Glyphen
|
||||
No Suggestions Keine Vorschläge
|
||||
Edit Custom Dictionary Benutzerwörterbuch bearbeiten
|
||||
Entry: Eintrag:
|
||||
# Script Console
|
||||
Script Console Skriptkonsole
|
||||
Clear Script Console Skriptkonsole leeren
|
||||
Copy Script Console Skriptkonsole kopieren
|
||||
Copy All Alles kopieren
|
||||
Copy Selected Auswahl kopieren
|
||||
Finished Beendet
|
||||
Ended with an error Mit einem Fehler beendet
|
||||
Out of fuel Anweisungslimit erreicht
|
||||
Ended at a host limit An einem Host-Limit beendet
|
||||
Ended at a limit An einem Limit beendet
|
||||
Stopped Gestoppt
|
||||
Ended by an internal fault Durch einen internen Fehler beendet
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} Host-Aufrufe
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} ältere Zeilen verworfen, {cut} Zeilen gekürzt
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` und `last` müssen Nummern von Zeilen sein, die die Konsole enthält, `first` vor `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6712,3 +6712,19 @@ breakText Glyphs Γλύφοι
|
||||
No Suggestions Καμία πρόταση
|
||||
Edit Custom Dictionary Επεξεργασία προσαρμοσμένου λεξικού
|
||||
Entry: Λήμμα:
|
||||
# Script Console
|
||||
Script Console Κονσόλα σεναρίων
|
||||
Clear Script Console Εκκαθάριση κονσόλας σεναρίων
|
||||
Copy Script Console Αντιγραφή κονσόλας σεναρίων
|
||||
Copy All Αντιγραφή όλων
|
||||
Copy Selected Αντιγραφή επιλεγμένων
|
||||
Finished Ολοκληρώθηκε
|
||||
Ended with an error Τερματίστηκε με σφάλμα
|
||||
Out of fuel Εξαντλήθηκε το όριο εντολών
|
||||
Ended at a host limit Τερματίστηκε σε όριο του κεντρικού συστήματος
|
||||
Ended at a limit Τερματίστηκε σε όριο
|
||||
Stopped Διακόπηκε
|
||||
Ended by an internal fault Τερματίστηκε λόγω εσωτερικού σφάλματος
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} κλήσεις προς το κεντρικό σύστημα
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} παλαιότερες γραμμές απορρίφθηκαν, {cut} γραμμές περικόπηκαν
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last Τα `first` και `last` πρέπει να είναι αριθμοί γραμμών που κρατά η κονσόλα, το `first` πριν από το `last`
|
||||
|
Can't render this file because it is too large.
|
@@ -6703,3 +6703,19 @@ breakText Glyphs Glifos
|
||||
No Suggestions No hay sugerencias
|
||||
Edit Custom Dictionary Editar diccionario personalizado
|
||||
Entry: Entrada:
|
||||
# Script Console
|
||||
Script Console Consola de scripts
|
||||
Clear Script Console Borrar consola de scripts
|
||||
Copy Script Console Copiar consola de scripts
|
||||
Copy All Copiar todo
|
||||
Copy Selected Copiar selección
|
||||
Finished Terminado
|
||||
Ended with an error Terminado con un error
|
||||
Out of fuel Límite de instrucciones agotado
|
||||
Ended at a host limit Terminado en un límite del host
|
||||
Ended at a limit Terminado en un límite
|
||||
Stopped Detenido
|
||||
Ended by an internal fault Terminado por un error interno
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} llamadas al host
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} líneas anteriores descartadas, {cut} líneas recortadas
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` y `last` deben ser números de líneas que la consola conserva, `first` antes que `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6795,3 +6795,19 @@ breakText Glyphs Merkit
|
||||
No Suggestions Ei ehdotuksia
|
||||
Edit Custom Dictionary Muokkaa omaa sanastoa
|
||||
Entry: Merkintä:
|
||||
# Script Console
|
||||
Script Console Komentosarjakonsoli
|
||||
Clear Script Console Tyhjennä komentosarjakonsoli
|
||||
Copy Script Console Kopioi komentosarjakonsoli
|
||||
Copy All Kopioi kaikki
|
||||
Copy Selected Kopioi valitut
|
||||
Finished Valmis
|
||||
Ended with an error Päättyi virheeseen
|
||||
Out of fuel Käskyraja täyttyi
|
||||
Ended at a host limit Päättyi isännän rajaan
|
||||
Ended at a limit Päättyi rajaan
|
||||
Stopped Pysäytetty
|
||||
Ended by an internal fault Päättyi sisäiseen virheeseen
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} isäntäkutsua
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} aiempaa riviä poistettu, {cut} riviä katkaistu
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` ja `last` on oltava konsolin säilyttämien rivien numeroita, `first` ennen arvoa `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6755,3 +6755,19 @@ breakText Glyphs Glyphes
|
||||
No Suggestions Aucune suggestion
|
||||
Edit Custom Dictionary Modifier le dictionnaire personnalisé
|
||||
Entry: Entrée :
|
||||
# Script Console
|
||||
Script Console Console de scripts
|
||||
Clear Script Console Effacer la console de scripts
|
||||
Copy Script Console Copier la console de scripts
|
||||
Copy All Tout copier
|
||||
Copy Selected Copier la sélection
|
||||
Finished Terminé
|
||||
Ended with an error Terminé avec une erreur
|
||||
Out of fuel Limite d’instructions atteinte
|
||||
Ended at a host limit Terminé à une limite de l’hôte
|
||||
Ended at a limit Terminé à une limite
|
||||
Stopped Arrêté
|
||||
Ended by an internal fault Terminé par une erreur interne
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} appels à l’hôte
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} lignes antérieures supprimées, {cut} lignes coupées
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` et `last` doivent être des numéros de lignes que la console contient, `first` avant `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -8201,3 +8201,19 @@ theme Appearance अपीयरेंस
|
||||
No Suggestions कोई सुझाव नहीं
|
||||
Edit Custom Dictionary कस्टम शब्दकोश संपादित करें
|
||||
Entry: प्रविष्टि:
|
||||
# Script Console
|
||||
Script Console स्क्रिप्ट कंसोल
|
||||
Clear Script Console स्क्रिप्ट कंसोल साफ़ करें
|
||||
Copy Script Console स्क्रिप्ट कंसोल कॉपी करें
|
||||
Copy All सब कॉपी करें
|
||||
Copy Selected चयनित कॉपी करें
|
||||
Finished पूरा हुआ
|
||||
Ended with an error त्रुटि के साथ समाप्त
|
||||
Out of fuel निर्देश सीमा समाप्त
|
||||
Ended at a host limit होस्ट सीमा पर समाप्त
|
||||
Ended at a limit सीमा पर समाप्त
|
||||
Stopped रोका गया
|
||||
Ended by an internal fault आंतरिक त्रुटि से समाप्त
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} होस्ट कॉल
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} पुरानी पंक्तियाँ हटाई गईं, {cut} पंक्तियाँ काटी गईं
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` और `last` कंसोल में रखी पंक्तियों की संख्याएँ होनी चाहिए, `first` पहले और `last` बाद में
|
||||
|
Can't render this file because it is too large.
|
@@ -6744,3 +6744,19 @@ breakText Glyphs Glifák
|
||||
No Suggestions Nincs javaslat
|
||||
Edit Custom Dictionary Egyéni szótár szerkesztése
|
||||
Entry: Bejegyzés:
|
||||
# Script Console
|
||||
Script Console Parancsfájlkonzol
|
||||
Clear Script Console Parancsfájlkonzol törlése
|
||||
Copy Script Console Parancsfájlkonzol másolása
|
||||
Copy All Összes másolása
|
||||
Copy Selected Kijelölés másolása
|
||||
Finished Befejeződött
|
||||
Ended with an error Hibával ért véget
|
||||
Out of fuel Elfogyott az utasításkeret
|
||||
Ended at a host limit Gazdakorlátnál ért véget
|
||||
Ended at a limit Korlátnál ért véget
|
||||
Stopped Leállítva
|
||||
Ended by an internal fault Belső hiba miatt ért véget
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} gazdahívás
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} korábbi sor elvetve, {cut} sor levágva
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last A `first` és a `last` a konzolban tárolt sorok számai legyenek, a `first` a `last` előtt
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6502,3 +6502,18 @@ breakText Glyphs Glif
|
||||
@msg side is left or right, not `{s}` side adalah left atau right, bukan `{s}`
|
||||
Edit Custom Dictionary Edit kamus kustom
|
||||
Entry: Entri:
|
||||
# Script Console
|
||||
Script Console Konsol Skrip
|
||||
Clear Script Console Bersihkan Konsol Skrip
|
||||
Copy Script Console Salin Konsol Skrip
|
||||
Copy All Salin Semua
|
||||
Copy Selected Salin yang Dipilih
|
||||
Finished Selesai
|
||||
Ended with an error Berakhir dengan galat
|
||||
Out of fuel Batas instruksi tercapai
|
||||
Ended at a host limit Berakhir pada batas host
|
||||
Ended at a limit Berakhir pada batas
|
||||
Stopped Dihentikan
|
||||
Ended by an internal fault Berakhir karena galat internal
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} panggilan host
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} baris lama dibuang, {cut} baris dipotong
|
||||
|
Can't render this file because it contains an unexpected character in line 2316 and column 5.
|
@@ -6381,3 +6381,19 @@ breakText Glyphs Glifi
|
||||
No Suggestions Nessun suggerimento
|
||||
Edit Custom Dictionary Modifica dizionario personalizzato
|
||||
Entry: Voce:
|
||||
# Script Console
|
||||
Script Console Console script
|
||||
Clear Script Console Cancella console script
|
||||
Copy Script Console Copia console script
|
||||
Copy All Copia tutto
|
||||
Copy Selected Copia selezione
|
||||
Finished Terminato
|
||||
Ended with an error Terminato con un errore
|
||||
Out of fuel Limite di istruzioni esaurito
|
||||
Ended at a host limit Terminato a un limite dell'host
|
||||
Ended at a limit Terminato a un limite
|
||||
Stopped Interrotto
|
||||
Ended by an internal fault Terminato per un errore interno
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} chiamate all'host
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} righe precedenti scartate, {cut} righe tagliate
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devono essere numeri di righe presenti nella console, `first` prima di `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6446,3 +6446,19 @@ breakText Glyphs 字形
|
||||
No Suggestions 候補なし
|
||||
Edit Custom Dictionary カスタム辞書を編集
|
||||
Entry: エントリ:
|
||||
# Script Console
|
||||
Script Console スクリプトコンソール
|
||||
Clear Script Console スクリプトコンソールを消去
|
||||
Copy Script Console スクリプトコンソールをコピー
|
||||
Copy All すべてコピー
|
||||
Copy Selected 選択範囲をコピー
|
||||
Finished 完了
|
||||
Ended with an error エラーで終了
|
||||
Out of fuel 命令数の上限に到達
|
||||
Ended at a host limit ホストの上限で終了
|
||||
Ended at a limit 上限で終了
|
||||
Stopped 停止
|
||||
Ended by an internal fault 内部エラーで終了
|
||||
{ms} ms, {calls} host calls {ms} ms、ホスト呼び出し {calls} 回
|
||||
{dropped} earlier lines dropped, {cut} lines cut 古い行 {dropped} 行を破棄、{cut} 行を切り詰め
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` と `last` には、コンソールが保持している行の番号を、`first` が `last` より前になるよう指定してください
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6821,3 +6821,19 @@ font-script Japanese იაპონური
|
||||
No Suggestions შემოთავაზებები არ არის
|
||||
Edit Custom Dictionary მომხმარებლის ლექსიკონის რედაქტირება
|
||||
Entry: ჩანაწერი:
|
||||
# Script Console
|
||||
Script Console სკრიპტების კონსოლი
|
||||
Clear Script Console სკრიპტების კონსოლის გასუფთავება
|
||||
Copy Script Console სკრიპტების კონსოლის კოპირება
|
||||
Copy All ყველაფრის კოპირება
|
||||
Copy Selected მონიშნულის კოპირება
|
||||
Finished დასრულდა
|
||||
Ended with an error დასრულდა შეცდომით
|
||||
Out of fuel ინსტრუქციების ლიმიტი ამოიწურა
|
||||
Ended at a host limit დასრულდა ჰოსტის ლიმიტზე
|
||||
Ended at a limit დასრულდა ლიმიტზე
|
||||
Stopped შეჩერდა
|
||||
Ended by an internal fault დასრულდა შიდა შეცდომის გამო
|
||||
{ms} ms, {calls} host calls {ms} ms, ჰოსტის {calls} გამოძახება
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} ძველი სტრიქონი წაიშალა, {cut} სტრიქონი შემოკლდა
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` და `last` უნდა იყოს კონსოლში შენახული სტრიქონების ნომრები და `first` უნდა იყოს `last`-ზე წინ
|
||||
|
Can't render this file because it is too large.
|
@@ -6342,3 +6342,19 @@ breakText Glyphs 글리프
|
||||
No Suggestions 제안 없음
|
||||
Edit Custom Dictionary 사용자 사전 편집
|
||||
Entry: 항목:
|
||||
# Script Console
|
||||
Script Console 스크립트 콘솔
|
||||
Clear Script Console 스크립트 콘솔 지우기
|
||||
Copy Script Console 스크립트 콘솔 복사
|
||||
Copy All 모두 복사
|
||||
Copy Selected 선택 항목 복사
|
||||
Finished 완료됨
|
||||
Ended with an error 오류로 종료됨
|
||||
Out of fuel 명령 한도에 도달함
|
||||
Ended at a host limit 호스트 한도에서 종료됨
|
||||
Ended at a limit 한도에서 종료됨
|
||||
Stopped 중지됨
|
||||
Ended by an internal fault 내부 오류로 종료됨
|
||||
{ms} ms, {calls} host calls {ms} ms, 호스트 호출 {calls}회
|
||||
{dropped} earlier lines dropped, {cut} lines cut 이전 줄 {dropped}개 삭제됨, 줄 {cut}개 잘림
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first`와 `last`는 콘솔에 있는 줄 번호여야 하며 `first`가 `last`보다 앞서야 합니다
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6553,3 +6553,18 @@ breakText Glyphs Glyphs
|
||||
@msg side is left or right, not `{s}` side is left of right, niet `{s}`
|
||||
Edit Custom Dictionary Aangepast woordenboek bewerken
|
||||
Entry: Item:
|
||||
# Script Console
|
||||
Script Console Scriptconsole
|
||||
Clear Script Console Scriptconsole wissen
|
||||
Copy Script Console Scriptconsole kopiëren
|
||||
Copy All Alles kopiëren
|
||||
Copy Selected Selectie kopiëren
|
||||
Finished Voltooid
|
||||
Ended with an error Beëindigd met een fout
|
||||
Out of fuel Instructielimiet bereikt
|
||||
Ended at a host limit Beëindigd bij een hostlimiet
|
||||
Ended at a limit Beëindigd bij een limiet
|
||||
Stopped Gestopt
|
||||
Ended by an internal fault Beëindigd door een interne fout
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} host-aanroepen
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} eerdere regels verwijderd, {cut} regels ingekort
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6616,3 +6616,19 @@ breakText Glyphs Glify
|
||||
No Suggestions Brak sugestii
|
||||
Edit Custom Dictionary Edytuj słownik użytkownika
|
||||
Entry: Wpis:
|
||||
# Script Console
|
||||
Script Console Konsola skryptów
|
||||
Clear Script Console Wyczyść konsolę skryptów
|
||||
Copy Script Console Kopiuj konsolę skryptów
|
||||
Copy All Kopiuj wszystko
|
||||
Copy Selected Kopiuj zaznaczenie
|
||||
Finished Zakończono
|
||||
Ended with an error Zakończono z błędem
|
||||
Out of fuel Wyczerpano limit instrukcji
|
||||
Ended at a host limit Zakończono na limicie hosta
|
||||
Ended at a limit Zakończono na limicie
|
||||
Stopped Zatrzymano
|
||||
Ended by an internal fault Zakończono z powodu błędu wewnętrznego
|
||||
{ms} ms, {calls} host calls {ms} ms, wywołania hosta: {calls}
|
||||
{dropped} earlier lines dropped, {cut} lines cut Odrzucone wcześniejsze wiersze: {dropped}, skrócone wiersze: {cut}
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` muszą być numerami wierszy przechowywanych w konsoli, `first` przed `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6833,3 +6833,19 @@ swatch Yellow Green Verde-amarelado
|
||||
No Suggestions Nenhuma Sugestão
|
||||
Edit Custom Dictionary Editar Dicionário Personalizado
|
||||
Entry: Entrada:
|
||||
# Script Console
|
||||
Script Console Console de scripts
|
||||
Clear Script Console Limpar console de scripts
|
||||
Copy Script Console Copiar console de scripts
|
||||
Copy All Copiar tudo
|
||||
Copy Selected Copiar seleção
|
||||
Finished Concluído
|
||||
Ended with an error Encerrado com um erro
|
||||
Out of fuel Limite de instruções esgotado
|
||||
Ended at a host limit Encerrado em um limite do host
|
||||
Ended at a limit Encerrado em um limite
|
||||
Stopped Interrompido
|
||||
Ended by an internal fault Encerrado por um erro interno
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} chamadas ao host
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} linhas anteriores descartadas, {cut} linhas cortadas
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devem ser números de linhas que o console mantém, `first` antes de `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -6849,3 +6849,19 @@ shape Open Открытый
|
||||
No Suggestions Нет вариантов
|
||||
Edit Custom Dictionary Редактировать пользовательский словарь
|
||||
Entry: Запись:
|
||||
# Script Console
|
||||
Script Console Консоль скриптов
|
||||
Clear Script Console Очистить консоль скриптов
|
||||
Copy Script Console Копировать консоль скриптов
|
||||
Copy All Копировать всё
|
||||
Copy Selected Копировать выделенное
|
||||
Finished Завершено
|
||||
Ended with an error Завершено с ошибкой
|
||||
Out of fuel Исчерпан лимит инструкций
|
||||
Ended at a host limit Завершено на лимите хоста
|
||||
Ended at a limit Завершено на лимите
|
||||
Stopped Остановлено
|
||||
Ended by an internal fault Завершено из-за внутренней ошибки
|
||||
{ms} ms, {calls} host calls {ms} мс, вызовов хоста: {calls}
|
||||
{dropped} earlier lines dropped, {cut} lines cut Отброшено прежних строк: {dropped}, обрезано строк: {cut}
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` и `last` должны быть номерами строк, которые хранит консоль, причём `first` не позже `last`
|
||||
|
Can't render this file because it is too large.
|
@@ -8245,3 +8245,19 @@ digits Hindi Hindi
|
||||
No Suggestions Inga förslag
|
||||
Edit Custom Dictionary Redigera egen ordlista
|
||||
Entry: Post:
|
||||
# Script Console
|
||||
Script Console Skriptkonsol
|
||||
Clear Script Console Rensa skriptkonsolen
|
||||
Copy Script Console Kopiera skriptkonsolen
|
||||
Copy All Kopiera allt
|
||||
Copy Selected Kopiera markerade
|
||||
Finished Klar
|
||||
Ended with an error Avslutades med ett fel
|
||||
Out of fuel Instruktionsgränsen nåddes
|
||||
Ended at a host limit Avslutades vid en värdgräns
|
||||
Ended at a limit Avslutades vid en gräns
|
||||
Stopped Stoppad
|
||||
Ended by an internal fault Avslutades av ett internt fel
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} värdanrop
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} tidigare rader borttagna, {cut} rader avkortade
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` och `last` måste vara nummer på rader som konsolen har kvar, `first` före `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 25.
|
@@ -6716,3 +6716,19 @@ breakText Glyphs Glifler
|
||||
No Suggestions Öneri Yok
|
||||
Edit Custom Dictionary Özel Sözlüğü Düzenle
|
||||
Entry: Giriş:
|
||||
# Script Console
|
||||
Script Console Betik Konsolu
|
||||
Clear Script Console Betik Konsolunu Temizle
|
||||
Copy Script Console Betik Konsolunu Kopyala
|
||||
Copy All Tümünü Kopyala
|
||||
Copy Selected Seçileni Kopyala
|
||||
Finished Bitti
|
||||
Ended with an error Bir hatayla sona erdi
|
||||
Out of fuel Komut sınırına ulaşıldı
|
||||
Ended at a host limit Bir ana bilgisayar sınırında sona erdi
|
||||
Ended at a limit Bir sınırda sona erdi
|
||||
Stopped Durduruldu
|
||||
Ended by an internal fault Bir iç hata nedeniyle sona erdi
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} ana bilgisayar çağrısı
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} eski satır atıldı, {cut} satır kesildi
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` ve `last`, konsolun tuttuğu satırların numaraları olmalı ve `first`, `last` değerinden önce gelmeli
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 25.
|
@@ -6361,3 +6361,19 @@ breakText Glyphs Гліфи
|
||||
No Suggestions Немає варіантів
|
||||
Edit Custom Dictionary Редагувати словник користувача
|
||||
Entry: Запис:
|
||||
# Script Console
|
||||
Script Console Консоль скриптів
|
||||
Clear Script Console Очистити консоль скриптів
|
||||
Copy Script Console Копіювати консоль скриптів
|
||||
Copy All Копіювати все
|
||||
Copy Selected Копіювати виділене
|
||||
Finished Завершено
|
||||
Ended with an error Завершено з помилкою
|
||||
Out of fuel Вичерпано ліміт інструкцій
|
||||
Ended at a host limit Завершено на ліміті хоста
|
||||
Ended at a limit Завершено на ліміті
|
||||
Stopped Зупинено
|
||||
Ended by an internal fault Завершено через внутрішню помилку
|
||||
{ms} ms, {calls} host calls {ms} мс, викликів хоста: {calls}
|
||||
{dropped} earlier lines dropped, {cut} lines cut Відкинуто попередніх рядків: {dropped}, обрізано рядків: {cut}
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` і `last` мають бути номерами рядків, які зберігає консоль, причому `first` не пізніше `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 182 and column 5.
|
@@ -6362,3 +6362,19 @@ breakText Glyphs Glyph
|
||||
No Suggestions Không có gợi ý
|
||||
Edit Custom Dictionary Chỉnh sửa từ điển tùy chỉnh
|
||||
Entry: Mục nhập:
|
||||
# Script Console
|
||||
Script Console Bảng điều khiển tập lệnh
|
||||
Clear Script Console Xóa bảng điều khiển tập lệnh
|
||||
Copy Script Console Sao chép bảng điều khiển tập lệnh
|
||||
Copy All Sao chép tất cả
|
||||
Copy Selected Sao chép mục đã chọn
|
||||
Finished Đã xong
|
||||
Ended with an error Kết thúc do lỗi
|
||||
Out of fuel Đã hết giới hạn lệnh
|
||||
Ended at a host limit Kết thúc ở giới hạn của máy chủ
|
||||
Ended at a limit Kết thúc ở giới hạn
|
||||
Stopped Đã dừng
|
||||
Ended by an internal fault Kết thúc do lỗi nội bộ
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} lệnh gọi máy chủ
|
||||
{dropped} earlier lines dropped, {cut} lines cut Đã bỏ {dropped} dòng cũ, đã cắt {cut} dòng
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` và `last` phải là số thứ tự của các dòng mà bảng điều khiển đang giữ, `first` đứng trước `last`
|
||||
|
Can't render this file because it contains an unexpected character in line 204 and column 5.
|
@@ -6598,3 +6598,19 @@ breakText Glyphs 字形
|
||||
@msg side is left or right, not `{s}` side 应为 left 或 right,而不是 `{s}`
|
||||
Edit Custom Dictionary 编辑自定义词典
|
||||
Entry: 条目:
|
||||
# Script Console
|
||||
Script Console 脚本控制台
|
||||
Clear Script Console 清除脚本控制台
|
||||
Copy Script Console 复制脚本控制台
|
||||
Copy All 全部复制
|
||||
Copy Selected 复制所选内容
|
||||
Finished 已完成
|
||||
Ended with an error 因错误结束
|
||||
Out of fuel 已用尽指令上限
|
||||
Ended at a host limit 在宿主限制处结束
|
||||
Ended at a limit 在限制处结束
|
||||
Stopped 已停止
|
||||
Ended by an internal fault 因内部错误结束
|
||||
{ms} ms, {calls} host calls {ms} 毫秒,宿主调用 {calls} 次
|
||||
{dropped} earlier lines dropped, {cut} lines cut 已丢弃 {dropped} 行较早内容,已截断 {cut} 行
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必须是控制台保留的行号,且 `first` 不能在 `last` 之后
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6396,3 +6396,19 @@ breakText Glyphs 字符
|
||||
@msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}`
|
||||
Edit Custom Dictionary 編輯自訂字典
|
||||
Entry: 項目:
|
||||
# Script Console
|
||||
Script Console 指令碼主控台
|
||||
Clear Script Console 清除指令碼主控台
|
||||
Copy Script Console 複製指令碼主控台
|
||||
Copy All 全部複製
|
||||
Copy Selected 複製所選內容
|
||||
Finished 已完成
|
||||
Ended with an error 因錯誤結束
|
||||
Out of fuel 已用盡指令上限
|
||||
Ended at a host limit 在主機限制處結束
|
||||
Ended at a limit 在限制處結束
|
||||
Stopped 已停止
|
||||
Ended by an internal fault 因內部錯誤結束
|
||||
{ms} ms, {calls} host calls {ms} 毫秒,主機呼叫 {calls} 次
|
||||
{dropped} earlier lines dropped, {cut} lines cut 已捨棄 {dropped} 行較早內容,已截斷 {cut} 行
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必須是主控台保留的行號,且 `first` 不能在 `last` 之後
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -771,6 +771,7 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
|
||||
}
|
||||
"ui.imageTracePresetDialog" => crate::dialogs::trace_presets::open(app, p),
|
||||
"ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p),
|
||||
"ui.copyScriptConsole" => crate::panels::script_console::copy(app, p),
|
||||
"window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p),
|
||||
"ui.libraryPanel" => crate::panels::library_panel::command(app, p),
|
||||
"ui.libraryPanel.locate" => crate::panels::library_panel::locate(app, p),
|
||||
|
||||
@@ -664,6 +664,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec<Item>)> {
|
||||
panel("Pathfinder", "pathfinder"),
|
||||
panel("Pattern Options", "patternOptions"),
|
||||
panel("Properties", "properties"),
|
||||
panel("Script Console", crate::panels::script_console::ID),
|
||||
panel("Separations Preview", "separations"),
|
||||
panel("Stroke", "stroke"),
|
||||
panel("SVG Interactivity", crate::panels::svg_interactivity::ID),
|
||||
|
||||
@@ -976,6 +976,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it",
|
||||
),
|
||||
(
|
||||
"ui.copyScriptConsole",
|
||||
"Copy Script Console",
|
||||
"",
|
||||
"{first?, last?: numbers of lines the Script Console holds, both or neither} copy those lines of the Script Console to the clipboard as the panel shows them, each with its run's number and script name; without them every line, after a line counting the lines it dropped and cut when it dropped or cut any, which n does not count (Script Console panel: Copy Selected, Copy All; script.console gives the lines) → {lines: n}",
|
||||
),
|
||||
(
|
||||
"window.graphicStyleLibrary",
|
||||
"Graphic Style Library",
|
||||
|
||||
@@ -37,6 +37,7 @@ pub mod paragraph;
|
||||
pub mod pathfinder;
|
||||
pub mod pattern_options;
|
||||
pub mod properties;
|
||||
pub mod script_console;
|
||||
pub mod separations;
|
||||
pub mod stroke;
|
||||
pub mod svg_interactivity;
|
||||
@@ -183,6 +184,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
|
||||
asset_export::ID => asset_export::show(app, ui),
|
||||
css_properties::ID => css_properties::show(app, ui),
|
||||
three_d::ID => three_d::show(app, ui),
|
||||
script_console::ID => script_console::show(app, ui),
|
||||
crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui),
|
||||
crate::addons::color::ID => crate::addons::color::show(app, ui),
|
||||
crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui),
|
||||
@@ -238,6 +240,7 @@ pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool
|
||||
asset_export::ID => asset_export::menu(app, ui),
|
||||
css_properties::ID => css_properties::menu(app, ui),
|
||||
variables::ID => variables::menu(app, ui),
|
||||
script_console::ID => script_console::menu(app, ui),
|
||||
"actions" => actions::menu(app, ui),
|
||||
id if library_panel::parse(id).is_some() => library_panel::menu(app, ui, id),
|
||||
_ => return false,
|
||||
@@ -675,6 +678,8 @@ mod tests_long_popups;
|
||||
#[cfg(test)]
|
||||
mod tests_maskview;
|
||||
#[cfg(test)]
|
||||
mod tests_script_console;
|
||||
#[cfg(test)]
|
||||
mod tests_stroke;
|
||||
#[cfg(test)]
|
||||
mod tests_strokedepth;
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Script Console panel (Window › Script Console): the lines of this session's script runs
|
||||
//! (`script.console`), each marked with its run's number and its script's name: a start, the
|
||||
//! script's `$.write` and `$.writeln` output and `vc.log` entries, its uncaught error, an end and a
|
||||
//! report of its time and host calls. The panel lays out only the rows in view. A click selects a
|
||||
//! line and Shift-click a range. Clear runs `script.console.clear`; Copy Selected and Copy All run
|
||||
//! `ui.copyScriptConsole`. Closing the panel only hides it: runs go on writing to the console.
|
||||
|
||||
use egui::{Sense, Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::script::console::{Console, ConsoleLine, Ending, Entry};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
pub const ID: &str = "scriptConsole";
|
||||
/// Panel state: the selected lines, by their numbers ([`Console::first_number`]), first and last.
|
||||
const SELECTION: &str = "script-console-selection";
|
||||
/// Panel state: how many rows the last frame laid out.
|
||||
pub(crate) const DRAWN: &str = "script-console-drawn";
|
||||
const ROW_HEIGHT: f32 = 16.0;
|
||||
|
||||
/// How a run ended, in the UI language.
|
||||
fn ending_label(e: Ending) -> &'static str {
|
||||
match e {
|
||||
Ending::Finished => tl!("Finished"),
|
||||
Ending::Error => tl!("Ended with an error"),
|
||||
Ending::Fuel => tl!("Out of fuel"),
|
||||
Ending::HostLimit => tl!("Ended at a host limit"),
|
||||
Ending::Limit => tl!("Ended at a limit"),
|
||||
Ending::Stopped => tl!("Stopped"),
|
||||
Ending::Internal => tl!("Ended by an internal fault"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A line as the panel shows it, in the UI language: its run's number, its script and its text.
|
||||
pub(crate) fn shown(line: &ConsoleLine) -> String {
|
||||
let text = match &line.entry {
|
||||
Entry::Start => "▶".to_string(),
|
||||
Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.clone(),
|
||||
Entry::End(e) => format!("■ {}", ending_label(*e)),
|
||||
Entry::Report { ms, host_calls, slowest } => {
|
||||
let ms = ms.map_or_else(|| "?".to_string(), |ms| ms.to_string());
|
||||
let mut s = crate::i18n::fmt(tl!("{ms} ms, {calls} host calls"), &[("ms", &ms), ("calls", &host_calls.to_string())]);
|
||||
for c in slowest {
|
||||
s.push_str(&format!("; {} ×{} {} ms", c.id, c.calls, c.total_ms));
|
||||
}
|
||||
s
|
||||
}
|
||||
};
|
||||
format!("#{} {}: {}", line.run, line.name, text)
|
||||
}
|
||||
|
||||
/// The notice of the lines the console dropped and cut, or `None` when it has done neither.
|
||||
fn notice(c: &Console) -> Option<String> {
|
||||
(c.dropped_lines() > 0 || c.truncated_lines() > 0).then(|| {
|
||||
crate::i18n::fmt(
|
||||
tl!("{dropped} earlier lines dropped, {cut} lines cut"),
|
||||
&[("dropped", &c.dropped_lines().to_string()), ("cut", &c.truncated_lines().to_string())],
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// `ui.copyScriptConsole {first?, last?}`: copy the console's lines numbered `first` to `last`
|
||||
/// (both kept lines; default every line, with the notice of dropped and cut lines first when the
|
||||
/// console dropped or cut any) to the clipboard, as the panel shows them → `{lines: n}`, where `n`
|
||||
/// does not count the notice.
|
||||
pub(crate) fn copy(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let c = app.session.script_console();
|
||||
let start = c.first_number();
|
||||
let end = start + c.lines().len() as u64;
|
||||
let (first, last) = (p.get("first"), p.get("last"));
|
||||
let mut text: Vec<String> = Vec::new();
|
||||
let (from, to) = if first.is_none() && last.is_none() {
|
||||
text.extend(notice(c));
|
||||
(start, end)
|
||||
} else {
|
||||
let held = |v: Option<&Value>| v.and_then(Value::as_u64).filter(|n| (start..end).contains(n));
|
||||
match (held(first), held(last)) {
|
||||
(Some(a), Some(b)) if a <= b => (a, b + 1),
|
||||
_ => return Err("`first` and `last` must be numbers of lines the console holds, first before last".to_string()),
|
||||
}
|
||||
};
|
||||
let picked = c.lines().iter().skip((from - start) as usize).take((to - from) as usize);
|
||||
let lines = picked.map(shown).collect::<Vec<_>>();
|
||||
let n = lines.len();
|
||||
text.extend(lines);
|
||||
app.clipboard_out = Some(text.join("\n"));
|
||||
Ok(json!({"lines": n}))
|
||||
}
|
||||
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let c = app.session.script_console();
|
||||
let start = c.first_number();
|
||||
let count = c.lines().len();
|
||||
let mut selection: Option<(u64, u64)> = super::pstate(ui.ctx(), SELECTION);
|
||||
// A selection whose lines were dropped or cleared is gone.
|
||||
if selection.is_some_and(|(a, b)| a < start || b >= start + count as u64) {
|
||||
selection = None;
|
||||
}
|
||||
if let Some(n) = notice(c) {
|
||||
crate::widgets::dim_label(ui, &n);
|
||||
}
|
||||
let mut clicked: Option<(u64, bool)> = None;
|
||||
let mut drawn = 0usize;
|
||||
let height = crate::widgets::panel_list_height(ui, 260.0, 0.0);
|
||||
crate::widgets::list_box(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 0.0;
|
||||
egui::ScrollArea::vertical().id_salt("script-console").max_height(height).stick_to_bottom(true).auto_shrink([false, true]).show_rows(
|
||||
ui,
|
||||
ROW_HEIGHT,
|
||||
count,
|
||||
|ui, range| {
|
||||
drawn = range.len();
|
||||
for (i, line) in c.lines().range(range.clone()).enumerate() {
|
||||
let number = start + (range.start + i) as u64;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click());
|
||||
if selection.is_some_and(|(a, b)| (a..=b).contains(&number)) {
|
||||
ui.painter().rect_filled(r, 0.0, t.row_selected);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 0.0, t.hover);
|
||||
}
|
||||
let color = match line.entry {
|
||||
Entry::Error(_) => t.error,
|
||||
Entry::Start | Entry::End(_) | Entry::Report { .. } => t.text_dim,
|
||||
Entry::Output(_) | Entry::Log(_) => t.text,
|
||||
};
|
||||
let text = shown(line);
|
||||
ui.painter().with_clip_rect(r).text(
|
||||
r.left_center() + vec2(4.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
&text,
|
||||
egui::FontId::monospace(11.5),
|
||||
color,
|
||||
);
|
||||
let resp = resp.on_hover_text(&text);
|
||||
if resp.clicked() {
|
||||
clicked = Some((number, ui.input(|i| i.modifiers.shift)));
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
super::set_pstate(ui.ctx(), DRAWN, drawn);
|
||||
if let Some((number, shift)) = clicked {
|
||||
selection = Some(match (selection, shift) {
|
||||
(Some((a, b)), true) => (a.min(number), b.max(number)),
|
||||
_ => (number, number),
|
||||
});
|
||||
}
|
||||
super::set_pstate(ui.ctx(), SELECTION, selection);
|
||||
crate::widgets::bottom_bar(ui, |ui| {
|
||||
if ui.add_enabled(count > 0, egui::Button::new(tl!("Clear"))).clicked() {
|
||||
run(app, "script.console.clear", json!({}));
|
||||
}
|
||||
if ui.add_enabled(selection.is_some(), egui::Button::new(tl!("Copy Selected"))).clicked()
|
||||
&& let Some((first, last)) = selection
|
||||
{
|
||||
run(app, "ui.copyScriptConsole", json!({"first": first, "last": last}));
|
||||
}
|
||||
if ui.add_enabled(count > 0, egui::Button::new(tl!("Copy All"))).clicked() {
|
||||
run(app, "ui.copyScriptConsole", json!({}));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The panel menu: Clear, Copy Selected and Copy All.
|
||||
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let count = app.session.script_console().lines().len();
|
||||
let selection: Option<(u64, u64)> = super::pstate(ui.ctx(), SELECTION);
|
||||
if crate::widgets::menu_item(ui, tl!("Clear"), count > 0, false) {
|
||||
run(app, "script.console.clear", json!({}));
|
||||
}
|
||||
if crate::widgets::menu_item(ui, tl!("Copy Selected"), selection.is_some(), false)
|
||||
&& let Some((first, last)) = selection
|
||||
{
|
||||
run(app, "ui.copyScriptConsole", json!({"first": first, "last": last}));
|
||||
}
|
||||
if crate::widgets::menu_item(ui, tl!("Copy All"), count > 0, false) {
|
||||
run(app, "ui.copyScriptConsole", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, id: &str, params: Value) {
|
||||
if let Err(e) = app.run(id, params) {
|
||||
app.ui.status = e;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! The Script Console panel drawn headless: a full console lays out only the rows in view, output
|
||||
//! goes on while the panel is hidden, Clear works during a run, and Copy Selected and Copy All
|
||||
//! through `ui.copyScriptConsole`.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::pstate;
|
||||
use super::script_console::{DRAWN, ID, show};
|
||||
use crate::tests_labels::painted_text;
|
||||
use crate::{Services, VectorcraftApp, script_runs};
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// Runs `source` to its end, a frame at a time, as the app does.
|
||||
fn run(app: &mut VectorcraftApp, source: &str) {
|
||||
app.session.script_frames = true;
|
||||
app.run("script.run", json!({"source": source, "name": "c.js"})).unwrap();
|
||||
for _ in 0..10_000 {
|
||||
if !app.session.script_running() {
|
||||
return;
|
||||
}
|
||||
script_runs::poll(app);
|
||||
}
|
||||
panic!("the script did not end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_console_lays_out_only_the_rows_in_view() {
|
||||
let mut app = app();
|
||||
run(&mut app, "for (var i = 0; i < 3000; i++) $.writeln('line ' + i)");
|
||||
assert_eq!(app.session.script_console().lines().len(), vectorcraft_engine::script::console::MAX_CONSOLE_LINES);
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut drawn = 0;
|
||||
for _ in 0..2 {
|
||||
ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
show(&mut app, ui);
|
||||
drawn = pstate::<usize>(ui.ctx(), DRAWN);
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
}
|
||||
assert!(drawn > 0 && drawn < 40, "{drawn} rows laid out");
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(text.contains("#1 c.js: line 2999"), "the newest line is in view: {text}");
|
||||
assert!(text.contains("lines dropped"), "the panel says lines were dropped: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_goes_on_while_the_panel_is_hidden_and_shows_when_it_opens() {
|
||||
let mut app = app();
|
||||
assert!(crate::state::rail_panel(ID).is_some());
|
||||
run(&mut app, "$.writeln('hidden'); vc.log({n: 1}); throw new Error('late')");
|
||||
app.run("window.panel", json!({"panel": ID})).unwrap();
|
||||
let text = painted_text(&mut app, show);
|
||||
for want in ["#1 c.js: ▶", "#1 c.js: hidden", "#1 c.js: {\"n\":1}", "#1 c.js: c.js:1:", "#1 c.js: ■ Ended with an error", "host calls"] {
|
||||
assert!(text.contains(want), "{want} in {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_works_during_a_run_and_the_run_goes_on_writing() {
|
||||
let mut app = app();
|
||||
app.session.script_frames = true;
|
||||
app.run("script.run", json!({"source": "$.writeln('before'); while (true) {}", "name": "c.js"})).unwrap();
|
||||
script_runs::poll(&mut app);
|
||||
assert!(app.session.script_running());
|
||||
assert_eq!(app.run("script.console.clear", json!({})).unwrap()["cleared"], 2);
|
||||
app.run("script.stop", json!({})).unwrap();
|
||||
script_runs::poll(&mut app);
|
||||
assert!(!app.session.script_running());
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(!text.contains("before") && text.contains("■ Stopped"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_all_and_copy_selected_put_the_lines_on_the_clipboard() {
|
||||
let mut app = app();
|
||||
run(&mut app, "$.writeln('one'); $.writeln('two'); $.writeln('three')");
|
||||
assert_eq!(app.run("ui.copyScriptConsole", json!({})).unwrap()["lines"], 6);
|
||||
let all = app.clipboard_out.take().unwrap();
|
||||
assert!(all.starts_with("#1 c.js: ▶\n#1 c.js: one\n#1 c.js: two\n"), "{all}");
|
||||
assert_eq!(app.run("ui.copyScriptConsole", json!({"first": 2, "last": 3})).unwrap()["lines"], 2);
|
||||
assert_eq!(app.clipboard_out.take().as_deref(), Some("#1 c.js: two\n#1 c.js: three"));
|
||||
for bad in [json!({"first": 3, "last": 2}), json!({"first": 1}), json!({"first": 0, "last": 99}), json!({"first": "1", "last": 2})] {
|
||||
assert!(app.run("ui.copyScriptConsole", bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
assert!(app.clipboard_out.is_none(), "a refused copy copies nothing");
|
||||
run(&mut app, "for (var i = 0; i < 2100; i++) $.writeln(i)");
|
||||
app.run("ui.copyScriptConsole", json!({})).unwrap();
|
||||
let all = app.clipboard_out.take().unwrap();
|
||||
assert!(all.lines().next().is_some_and(|l| l.contains("lines dropped")), "Copy All starts with the notice: {}", &all[..80]);
|
||||
}
|
||||
@@ -208,6 +208,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[
|
||||
(crate::panels::css_properties::ID, "CSS Properties", "globe"),
|
||||
(crate::panels::three_d::ID, "3D and Materials", "dc-cube"),
|
||||
(crate::panels::variables::ID, "Variables", "chart-column"),
|
||||
(crate::panels::script_console::ID, "Script Console", "message-circle"),
|
||||
(crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"),
|
||||
(crate::addons::color::ID, "Color Effects", "sun"),
|
||||
(crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"),
|
||||
|
||||
+3
-3
@@ -689,9 +689,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
|
||||
## G6 Automation and scripting
|
||||
|
||||
- **Missing:** the document object model for scripts, a script console, the Scripts folder and script
|
||||
directives (#1183 is open). File › Scripts › Other Script… and `script.run` run JavaScript files over the
|
||||
command registry. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and
|
||||
- **Missing:** the document object model for scripts, the Scripts folder and script directives (#1183 is
|
||||
open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, and
|
||||
Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and
|
||||
export, and full agent control over MCP are done.
|
||||
- **Estimate:** 4–8 h.
|
||||
- **Done (2026-10-16):** the MCP server hears the client during a long call: `notifications/cancelled` stops a queued or running export (PDF pages, flattening, baking, drawing, artboards) without writing anything or changing the document, `ping` and the list methods answer at once, any other request that would wait behind a call running for two seconds or more is refused as busy (`-32003`, naming the call), and `_meta.progressToken` gets page progress (#2165, #2171, #2172). Reading the document during an export is not served (refused as busy); estimate unchanged.
|
||||
|
||||
+39
-5
@@ -1549,7 +1549,7 @@ describes that menu item. Pass exactly one of `path` and `source`. A `path` must
|
||||
case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is
|
||||
not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and
|
||||
`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the
|
||||
app through one global object:
|
||||
app through the global object `vc`, and writes to the Script Console through `$`:
|
||||
|
||||
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
|
||||
catch. The documents and the session state the command changed, preferences included, go back, and any file it
|
||||
@@ -1558,7 +1558,9 @@ app through one global object:
|
||||
- `vc.document` is a snapshot of the active document, or `null` when none is open. A snapshot too large to cross
|
||||
throws a `RangeError`.
|
||||
- `vc.commands` lists the commands a script may run.
|
||||
- `vc.log(value)` adds a value to the report.
|
||||
- `vc.log(value)` adds a value to the report and a line to the Script Console.
|
||||
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
|
||||
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.
|
||||
- `vc.args` is the `args` object.
|
||||
- `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature.
|
||||
|
||||
@@ -1597,13 +1599,23 @@ VectorCraft sets these limits itself:
|
||||
| A value crossing to or from a command | 16 MiB and 1,048,576 entries |
|
||||
| `args` as JSON | 1 MiB |
|
||||
| Log | 10,000 entries and 4 MiB |
|
||||
| Script Console | 2,048 lines and 1 MiB of text; 4,096 bytes a line; 256 bytes of a script's name |
|
||||
| Growth before a person is asked | 100,000 objects and 512 MiB of new document data |
|
||||
|
||||
In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and
|
||||
`ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends
|
||||
with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls}`.
|
||||
In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`.
|
||||
`answers` takes only an empty object, since scripts have no prompts yet.
|
||||
with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls,
|
||||
runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console}`. In the app the reply is `{running: true,
|
||||
name}`, and the report appears later as `scriptReport` in `ui.inspect`. The report of a failed run has the same
|
||||
fields after `kind`, `message`, `line`, `column` and `fuelLeft`. `answers` takes only an empty object, since scripts
|
||||
have no prompts yet.
|
||||
|
||||
- `runTimeMs` is the time the script ran, its commands included. Waits between frames and for a person's answer are
|
||||
left out. `timingAvailable` is false on the web, where `runTimeMs` is 0.
|
||||
- `hostCallCounts` is `{vcRun, documentReads, commandListReads, vcLog, consoleWrites}`.
|
||||
- `slowestCommands` lists at most 5 commands as `{id, calls, totalMs, maxMs}`, the longest in all first, then by id.
|
||||
- `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as
|
||||
text.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}}
|
||||
@@ -1613,6 +1625,28 @@ In the app the reply is `{running: true, name}`, and the report appears later as
|
||||
vectorcraft-cli run --cmd script.run --params '{"path": "Tidy Layers.js", "args": {"margin": 12}}'
|
||||
```
|
||||
|
||||
Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and
|
||||
`$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message`, its end, and a report of
|
||||
its time, host calls and slowest commands. Each line shows the run's number and the script's name. Line feeds,
|
||||
carriage returns and the two together break lines, and other control characters show as their Unicode Control
|
||||
Pictures. The console keeps at most 2,048 lines and 1 MiB of text and drops the oldest lines past that. A line longer
|
||||
than 4,096 bytes, and a script's name longer than 256 bytes, is cut with `…`. When the console has dropped or cut any lines, a note at the top counts them. The panel lays out only the
|
||||
rows in view. Click a line to select it and Shift-click to extend the selection. Clear, Copy Selected and Copy All are
|
||||
at the bottom of the panel and in its menu. Output goes on while the panel is closed.
|
||||
|
||||
- `script.console {}` returns `{lines: [{run, name, kind, text}], droppedLines, truncatedLines}`. `run` is the
|
||||
run's number in the session, and `kind` is `start`, `output`, `log`, `error`, `end` or `report`. An end line's text
|
||||
is `ended:`, a space, and then `finished`, `error`, `fuel`, `hostLimit`, `limit`, `stopped` or `internal`.
|
||||
- `script.console.clear {}` empties the console, sets its counts to zero and returns `{cleared}`. A running script
|
||||
goes on writing, and `scriptReport` keeps the last run's console.
|
||||
- `ui.copyScriptConsole {first?, last?}` copies lines `first` to `last` to the clipboard as the panel shows them, or
|
||||
every line when both are left out. When the console has dropped or cut any lines, a copy of every line starts with a
|
||||
line that counts them. Pass both or neither. It returns `{lines}`, which does not count that line.
|
||||
|
||||
```sh
|
||||
vectorcraft-cli run --cmd script.run --params '{"source": "$.writeln(\"layers: \", 3);"}'
|
||||
```
|
||||
|
||||
## Transparency and opacity masks
|
||||
|
||||
Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage
|
||||
|
||||
+1
-1
@@ -160,7 +160,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 |
|
||||
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
|
||||
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369) | 6–10 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files; the script document model and console and batch work remain | 18–27 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 |
|
||||
| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 |
|
||||
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
|
||||
|
||||
@@ -726,6 +726,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
|
||||
- Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`.
|
||||
- MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172).
|
||||
- MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads).
|
||||
|
||||
Reference in new issue
Block a user