From 04c65a85af1e2722798331dfb5ba8244473b2039 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 08:30:51 -0800 Subject: [PATCH 1/4] Messages: app.toast shows a message over the window without stopping work `app.toast {message, level?, seconds?}` queues a short message that the desktop app shows at the window's bottom right. It closes after its time (4 seconds by default, 0.5 to 60) or when clicked. At most 5 show at once, the newest lowest; a message shows at most 6 lines with the whole text on hover, and a stack taller than the window scrolls. `level` (info, success, warning, error) sets the color of its edge. Scripts raise one with `vc.run`, MCP clients and plug-ins through the command, and an action records it as a step. The app's own code calls `Session::toast`. The command edits no document and adds no undo step; invalid values are errors. Part of #7523: the tick sound is not included. Docs: docs/mcp.md, the Automation evidence in docs/target-app-parity.md. --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/toast.rs | 248 ++++++++++++++ crates/engine/src/lib.rs | 2 + crates/engine/src/session/documents.rs | 1 + crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/toasts.rs | 308 ++++++++++++++++++ docs/mcp.md | 17 + docs/target-app-parity.md | 1 + 10 files changed, 585 insertions(+) create mode 100644 crates/engine/src/cmd/toast.rs create mode 100644 crates/ui-egui/src/toasts.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..692408f112 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -104,6 +104,7 @@ pub use textedit::effective_kerning; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; +pub mod toast; pub(crate) mod typecmd; mod typemenu; mod variablecmds; @@ -333,6 +334,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(compositefonts::specs()); v.extend(fontfiles::specs()); v.extend(help::specs()); + v.extend(toast::specs()); v.extend(threads::specs()); v.extend(textwrap::specs()); v.extend(graph::specs()); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 6a0caf4cd6..01e3e1a4e6 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -84,6 +84,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.shapes.star", "addon.type.releasePath", "addon.type.textTweaker", + "app.toast", "appearance.addEffect", "appearance.addFill", "appearance.addStroke", diff --git a/crates/engine/src/cmd/toast.rs b/crates/engine/src/cmd/toast.rs new file mode 100644 index 0000000000..c692ad702d --- /dev/null +++ b/crates/engine/src/cmd/toast.rs @@ -0,0 +1,248 @@ +//! `app.toast`: a short message shown over the window that does not stop work and goes away by +//! itself (a toast). Scripts (`vc.run`), actions (a recorded step), MCP clients and the app's own +//! code ([`Session::toast`]) raise one. The engine queues the messages and the desktop app takes +//! them each frame ([`Session::take_toasts`]) and shows them. + +use std::collections::VecDeque; + +use serde_json::{Value, json}; + +use super::{CommandSpec, Result, always, bad, cmd}; +use crate::Session; + +const ID: &str = "app.toast"; + +/// The most characters a message has. +pub const MAX_CHARS: usize = 500; + +/// How long a message shows when `seconds` is omitted, and the shortest and longest time it may +/// show. +pub const DEFAULT_SECONDS: f64 = 4.0; +pub const MIN_SECONDS: f64 = 0.5; +pub const MAX_SECONDS: f64 = 60.0; + +/// The most messages waiting for the app to take them: past it the oldest one goes. A session +/// without a window (MCP, the command line) never takes them. +pub const MAX_QUEUED: usize = 32; + +/// What kind of news a message is, which sets its color. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Level { + #[default] + Info, + Success, + Warning, + Error, +} + +impl Level { + pub const ALL: [Level; 4] = [Level::Info, Level::Success, Level::Warning, Level::Error]; + + /// Its `level` value. + pub fn param(self) -> &'static str { + match self { + Level::Info => "info", + Level::Success => "success", + Level::Warning => "warning", + Level::Error => "error", + } + } + + /// The level whose `level` value is `param`. + pub fn from_param(param: &str) -> Option { + Level::ALL.into_iter().find(|l| l.param() == param) + } +} + +/// A message to show. +#[derive(Clone, Debug, PartialEq)] +pub struct Toast { + pub message: String, + pub level: Level, + /// How long it shows, in seconds. + pub seconds: f64, +} + +impl Toast { + /// A message of `level` shown for [`DEFAULT_SECONDS`]. + pub fn new(message: impl Into, level: Level) -> Toast { + Toast { message: message.into(), level, seconds: DEFAULT_SECONDS } + } +} + +/// The messages waiting for the app to show them. +#[derive(Clone, Debug, Default)] +pub struct Queue(VecDeque); + +impl Session { + /// Queue `toast` for the app to show. With [`MAX_QUEUED`] waiting, the oldest one goes. + pub fn toast(&mut self, toast: Toast) { + while self.toasts.0.len() >= MAX_QUEUED { + self.toasts.0.pop_front(); + } + self.toasts.0.push_back(toast); + } + + /// Take the messages queued since the last call, oldest first. + pub fn take_toasts(&mut self) -> Vec { + self.toasts.0.drain(..).collect() + } +} + +pub fn specs() -> Vec { + vec![cmd!( + "app.toast", + "Show Message", + [], + None, + "{message: string (1 to 500 characters, not only spaces), level?: \"info\" | \"success\" | \"warning\" | \"error\" (default \"info\"), seconds?: number 0.5 to 60 (default 4)} show `message` over the window without stopping work: it goes away after `seconds` or when clicked; messages stack at the window's bottom right, the newest lowest, at most 5 at once; edits no document; an action records it as a step → {message, level, seconds}", + always, + run + )] +} + +fn run(s: &mut Session, p: &Value) -> Result { + let toast = parse(p)?; + let r = json!({"message": &toast.message, "level": toast.level.param(), "seconds": toast.seconds}); + s.toast(toast); + Ok(r) +} + +/// The message `p` asks for; an invalid value of any key is an error. +fn parse(p: &Value) -> Result { + let message = match p.get("message") { + Some(Value::String(m)) => m, + Some(_) => return Err(bad(ID, "`message` must be a string")), + None => return Err(bad(ID, "`message` is required")), + }; + if message.trim().is_empty() { + return Err(bad(ID, "`message` must have a character other than a space")); + } + let chars = message.chars().count(); + if chars > MAX_CHARS { + return Err(bad(ID, format!("`message` has {chars} characters; at most {MAX_CHARS} are allowed"))); + } + let level = match p.get("level") { + None => Level::default(), + Some(v) => v.as_str().and_then(Level::from_param).ok_or_else(|| { + let all: Vec<&str> = Level::ALL.iter().map(|l| l.param()).collect(); + bad(ID, format!("`level` must be one of {}", all.join(", "))) + })?, + }; + let seconds = match p.get("seconds") { + None => DEFAULT_SECONDS, + Some(v) => v + .as_f64() + .filter(|s| (MIN_SECONDS..=MAX_SECONDS).contains(s)) + .ok_or_else(|| bad(ID, format!("`seconds` must be a number from {MIN_SECONDS} to {MAX_SECONDS}")))?, + }; + Ok(Toast { message: message.clone(), level, seconds }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_message_is_queued_with_its_defaults() { + let mut s = Session::new(); + let r = s.execute(ID, &json!({"message": "Saved 3 files"})).unwrap(); + assert_eq!(r, json!({"message": "Saved 3 files", "level": "info", "seconds": 4.0})); + assert_eq!(s.take_toasts(), vec![Toast::new("Saved 3 files", Level::Info)]); + // Taken once. + assert_eq!(s.take_toasts(), vec![]); + } + + #[test] + fn level_and_seconds_are_kept() { + let mut s = Session::new(); + for level in Level::ALL { + s.execute(ID, &json!({"message": "m", "level": level.param(), "seconds": 0.5})).unwrap(); + } + s.execute(ID, &json!({"message": "long", "seconds": 60})).unwrap(); + let got: Vec<(Level, f64)> = s.take_toasts().iter().map(|t| (t.level, t.seconds)).collect(); + assert_eq!(got, vec![(Level::Info, 0.5), (Level::Success, 0.5), (Level::Warning, 0.5), (Level::Error, 0.5), (Level::Info, 60.0)]); + } + + #[test] + fn invalid_values_are_errors_and_queue_nothing() { + let mut s = Session::new(); + let long = "x".repeat(MAX_CHARS + 1); + for p in [ + json!({}), + json!({"message": 3}), + json!({"message": ""}), + json!({"message": " \n\t"}), + json!({"message": long}), + json!({"message": "m", "level": "loud"}), + json!({"message": "m", "level": 1}), + json!({"message": "m", "seconds": 0.4}), + json!({"message": "m", "seconds": 61}), + json!({"message": "m", "seconds": "4"}), + json!({"message": "m", "seconds": null}), + ] { + let e = s.execute(ID, &p).unwrap_err().to_string(); + assert!(e.contains(ID), "{p}: {e}"); + } + assert_eq!(s.take_toasts(), vec![]); + // The longest message is allowed, counted in characters, not bytes. + let most = "é".repeat(MAX_CHARS); + s.execute(ID, &json!({"message": most})).unwrap(); + assert_eq!(s.take_toasts().len(), 1); + } + + #[test] + fn the_oldest_waiting_message_goes_past_the_limit() { + let mut s = Session::new(); + for i in 0..MAX_QUEUED + 2 { + s.toast(Toast::new(format!("{i}"), Level::Info)); + } + let left: Vec = s.take_toasts().into_iter().map(|t| t.message).collect(); + assert_eq!(left.len(), MAX_QUEUED); + assert_eq!(left.first().map(String::as_str), Some("2")); + assert_eq!(left.last().map(String::as_str), Some("33")); + } + + #[test] + fn a_message_is_journaled_without_an_undo_step_or_a_document() { + let mut s = Session::new(); + // No document open. + s.execute(ID, &json!({"message": "no document"})).unwrap(); + assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "no document"}))); + s.execute("file.new", &json!({})).unwrap(); + let undo = s.active().unwrap().history.undo.len(); + let revision = s.active().unwrap().revision; + s.execute(ID, &json!({"message": "m", "level": "success"})).unwrap(); + assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "m", "level": "success"}))); + assert_eq!(s.active().unwrap().history.undo.len(), undo); + assert_eq!(s.active().unwrap().revision, revision); + } + + #[test] + fn a_script_raises_a_message_with_vc_run() { + let mut s = Session::new(); + let r = s + .execute( + "script.run", + &json!({"source": "vc.run('app.toast', {message: 'Done: ' + (1 + 1), level: 'success'});", "name": "t.js", "answers": []}), + ) + .unwrap(); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + assert_eq!(s.take_toasts(), vec![Toast::new("Done: 2", Level::Success)]); + } + + #[test] + fn a_command_batch_raises_its_messages_in_order() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute( + "command.batch", + &json!({"commands": [ + {"command": "app.toast", "params": {"message": "one"}}, + {"command": "app.toast", "params": {"message": "two", "level": "warning"}}, + ]}), + ) + .unwrap(); + assert_eq!(s.take_toasts(), vec![Toast::new("one", Level::Info), Toast::new("two", Level::Warning)]); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4f7532108d..424fc9f6e9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -356,6 +356,8 @@ pub struct Session { /// Set while [`Session::tool_typed_text`] passes keyboard input to the active tool /// ([`vectorcraft_tools::ToolContext::typed_from_keyboard`]). keyboard_text: bool, + /// The messages `app.toast` and [`Session::toast`] queued for the app to show; not saved. + pub(crate) toasts: cmd::toast::Queue, } impl Default for Session { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 4415566d13..cda550dfd1 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -148,6 +148,7 @@ impl Session { global_edit_options: Default::default(), select_similar: crate::cmd::SIMILAR[0].0, keyboard_text: false, + toasts: Default::default(), script_key: None, script_engines: crate::script::EnginesKey::new(), script_stop: vectorcraft_js::Interrupt::new(), diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..b0d5f80020 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -161,6 +161,7 @@ impl VectorcraftApp { plugin_runs: Default::default(), placing: Default::default(), trace_runs: Default::default(), + toasts: Default::default(), recovery: Default::default(), host_modifiers: Default::default(), forwarded: Vec::new(), @@ -629,6 +630,7 @@ impl VectorcraftApp { trace_runs::show(self, &ctx); opening::show(self, &ctx); palette::show(self, &ctx); + crate::toasts::show(self, &ctx); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); if self.custom_titlebar { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0b8ee67183..9f3bf69197 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -79,6 +79,7 @@ pub mod sysclip; pub mod theme; pub mod thumb_worker; pub mod titlebar; +pub mod toasts; pub mod toolbar; mod tools_float; pub mod touch; @@ -291,6 +292,8 @@ pub struct VectorcraftApp { pub placing: placing::Placing, /// Image Traces running off the UI thread ([`trace_runs`]). pub trace_runs: trace_runs::TraceRuns, + /// The messages shown over the window ([`toasts`]). + pub toasts: toasts::Shown, /// Data Recovery's timer and startup question ([`recovery`]). pub recovery: recovery::Timer, /// Modifiers the keyboard holds (from the host's input), given back after synthetic input. diff --git a/crates/ui-egui/src/toasts.rs b/crates/ui-egui/src/toasts.rs new file mode 100644 index 0000000000..0d47c4e3b4 --- /dev/null +++ b/crates/ui-egui/src/toasts.rs @@ -0,0 +1,308 @@ +//! Messages that `app.toast` and the app's own code ([`vectorcraft_engine::Session::toast`]) queue, +//! shown over the window without taking the keyboard or stopping work: a stack at the window's +//! bottom right, the newest lowest. Each one goes after its time or when clicked; past +//! [`MAX_SHOWN`] the oldest goes first. A message shows at most [`MAX_ROWS`] lines, and the whole +//! text on hover; a stack taller than the window scrolls. + +use std::time::Duration; + +use vectorcraft_engine::cmd::toast::{Level, Toast}; + +use crate::VectorcraftApp; +use crate::theme::Tokens; + +/// The most messages shown at once. +pub const MAX_SHOWN: usize = 5; + +/// The widest a message is, in points; longer text wraps. +const WIDTH: f32 = 320.0; + +/// The most lines a message shows; the rest shows on hover. +const MAX_ROWS: usize = 6; + +/// The gap between the stack and the window's right and bottom edges, in points. +const MARGIN: f32 = 16.0; + +/// A message shown. +#[derive(Clone, Debug)] +pub(crate) struct Entry { + pub(crate) toast: Toast, + /// When it goes, in [`crate::clock::now_secs`] seconds. + until: f64, + id: u64, + /// Where the last pass drew it. + pub(crate) rect: Option, +} + +/// The messages shown, oldest first. +#[derive(Debug, Default)] +pub struct Shown { + pub(crate) list: Vec, + next_id: u64, +} + +impl Shown { + /// Show `new` from `now` on, dropping the oldest past [`MAX_SHOWN`]. + fn add(&mut self, new: Vec, now: f64) { + for toast in new { + let until = now + toast.seconds; + self.list.push(Entry { toast, until, id: self.next_id, rect: None }); + self.next_id = self.next_id.wrapping_add(1); + } + let over = self.list.len().saturating_sub(MAX_SHOWN); + self.list.drain(..over); + } + + /// Drop the messages whose time is up at `now`; the seconds until the next one's is. + fn expire(&mut self, now: f64) -> Option { + self.list.retain(|e| e.until > now); + self.list.iter().map(|e| e.until - now).reduce(f64::min) + } +} + +/// The color of a message's edge. +fn color(t: &Tokens, level: Level) -> egui::Color32 { + match level { + Level::Info => t.text_dim, + Level::Success => t.axis_y, + Level::Warning => t.warning, + Level::Error => t.error, + } +} + +/// Take the messages queued since the last pass and draw the ones shown. +pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + show_at(app, ctx, crate::clock::now_secs()); +} + +/// [`show`] at `now`, in [`crate::clock::now_secs`] seconds. +pub(crate) fn show_at(app: &mut VectorcraftApp, ctx: &egui::Context, now: f64) { + // Messages whose time is up go before new ones count toward the limit. + app.toasts.expire(now); + let new = app.session.take_toasts(); + app.toasts.add(new, now); + let Some(left) = app.toasts.expire(now) else { + return; + }; + // Finite and positive: every message's time is 0.5 to 60 seconds. + ctx.request_repaint_after(Duration::from_secs_f64(left.clamp(0.0, 60.0))); + let t = Tokens::get(ctx); + let corner = egui::vec2(-MARGIN, -MARGIN); + let area = egui::Area::new(egui::Id::unique("toasts")).order(egui::Order::Foreground).anchor(egui::Align2::RIGHT_BOTTOM, corner); + // A stack taller than the window scrolls, kept at its newest message. + let height = (ctx.content_rect().height() - 2.0 * MARGIN).max(0.0); + let dismissed = area + .show(ctx, |ui| { + let scroll = egui::ScrollArea::vertical().max_height(height).stick_to_bottom(true); + scroll.show(ui, |ui| stack(ui, &mut app.toasts.list, &t)).inner + }) + .inner; + if let Some(id) = dismissed { + app.toasts.list.retain(|e| e.id != id); + ctx.request_repaint(); + } +} + +/// Draw `list`, oldest first; the id of the message clicked. +fn stack(ui: &mut egui::Ui, list: &mut [Entry], t: &Tokens) -> Option { + ui.set_max_width(WIDTH); + let mut clicked = None; + for e in list { + // Each message's widgets keep its id when the messages before it go, so a press and a + // release land on the same message. + let r = ui.push_id(e.id, |ui| message(ui, e, t)).inner; + if r.clicked() { + clicked = Some(e.id); + } + e.rect = Some(r.rect); + ui.add_space(6.0); + } + clicked +} + +/// Draw one message → its response to clicks. +fn message(ui: &mut egui::Ui, e: &Entry, t: &Tokens) -> egui::Response { + let frame = egui::Frame::new() + .fill(t.panel) + .stroke(egui::Stroke::new(1.0, color(t, e.toast.level))) + .corner_radius(t.radius) + .inner_margin(egui::Margin::symmetric(10, 8)) + .show(ui, |ui| { + ui.set_width(WIDTH - 20.0); + let format = egui::TextFormat::simple(egui::TextStyle::Body.resolve(ui.style()), t.text); + let mut job = egui::text::LayoutJob::single_section(e.toast.message.clone(), format); + job.wrap.max_width = WIDTH - 20.0; + job.wrap.max_rows = MAX_ROWS; + let galley = ui.painter().layout_job(job); + let elided = galley.elided; + ui.add(egui::Label::new(galley).selectable(false)); + elided + }); + let r = frame.response.interact(egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); + // A message cut short shows in full on hover. + if frame.inner { r.on_hover_text(&e.toast.message) } else { r } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_engine::Session; + + use super::*; + + fn app() -> (VectorcraftApp, egui::Context) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + (app, ctx) + } + + /// One pass at `now` with `events`; the text the pass drew. + fn pass(app: &mut VectorcraftApp, ctx: &egui::Context, now: f64, events: Vec) -> Vec { + pass_in(app, ctx, now, events, 700.0) + } + + /// [`pass`] in a window `height` points tall. + fn pass_in(app: &mut VectorcraftApp, ctx: &egui::Context, now: f64, events: Vec, height: f32) -> Vec { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, height)); + let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| show_at(app, ui.ctx(), now)); + output.textures_delta.clear(); + let mut texts = Vec::new(); + for clipped in &output.shapes { + if let egui::epaint::Shape::Text(text) = &clipped.shape { + texts.push(text.galley.text().to_string()); + } + } + texts + } + + fn messages(app: &VectorcraftApp) -> Vec<&str> { + app.toasts.list.iter().map(|e| e.toast.message.as_str()).collect() + } + + #[test] + fn a_message_shows_until_its_time_is_up() { + let (mut app, ctx) = app(); + app.run("app.toast", json!({"message": "Exported 4 files", "seconds": 2})).unwrap(); + // A new area measures itself in its first pass and draws from the next. + pass(&mut app, &ctx, 10.0, vec![]); + let texts = pass(&mut app, &ctx, 10.0, vec![]); + assert!(texts.iter().any(|t| t == "Exported 4 files"), "{texts:?}"); + let rect = app.toasts.list[0].rect.unwrap(); + assert!(rect.right() <= 1000.0 - MARGIN + 0.5 && rect.bottom() <= 700.0 - MARGIN + 0.5, "{rect:?}"); + assert!(pass(&mut app, &ctx, 11.9, vec![]).iter().any(|t| t == "Exported 4 files")); + assert!(!pass(&mut app, &ctx, 12.0, vec![]).iter().any(|t| t == "Exported 4 files")); + assert!(app.toasts.list.is_empty()); + } + + #[test] + fn newer_messages_show_below_older_ones_and_the_oldest_goes_past_the_limit() { + let (mut app, ctx) = app(); + for i in 0..MAX_SHOWN + 1 { + app.session.toast(Toast::new(format!("m{i}"), Level::Info)); + } + pass(&mut app, &ctx, 0.0, vec![]); + assert_eq!(messages(&app), vec!["m1", "m2", "m3", "m4", "m5"]); + let tops: Vec = app.toasts.list.iter().map(|e| e.rect.unwrap().top()).collect(); + assert!(tops.windows(2).all(|w| w[0] < w[1]), "{tops:?}"); + } + + #[test] + fn messages_whose_time_is_up_do_not_count_toward_the_limit() { + let (mut app, ctx) = app(); + app.session.toast(Toast { seconds: 60.0, ..Toast::new("long", Level::Info) }); + for i in 0..MAX_SHOWN - 1 { + app.session.toast(Toast { seconds: 0.5, ..Toast::new(format!("short{i}"), Level::Info) }); + } + pass(&mut app, &ctx, 0.0, vec![]); + app.session.toast(Toast::new("new", Level::Info)); + pass(&mut app, &ctx, 0.5, vec![]); + assert_eq!(messages(&app), vec!["long", "new"]); + } + + #[test] + fn a_click_dismisses_only_that_message() { + let (mut app, ctx) = app(); + app.session.toast(Toast::new("first", Level::Warning)); + app.session.toast(Toast::new("second", Level::Error)); + pass(&mut app, &ctx, 0.0, vec![]); + pass(&mut app, &ctx, 0.0, vec![]); + let at = app.toasts.list[0].rect.unwrap().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + pass(&mut app, &ctx, 0.1, vec![egui::Event::PointerMoved(at)]); + pass(&mut app, &ctx, 0.2, vec![press(true)]); + pass(&mut app, &ctx, 0.3, vec![press(false)]); + assert_eq!(messages(&app), vec!["second"]); + } + + #[test] + fn a_message_that_goes_between_press_and_release_closes_no_other() { + let (mut app, ctx) = app(); + for (message, seconds) in [("top", 60.0), ("pressed", 0.5), ("bottom", 60.0)] { + app.session.toast(Toast { seconds, ..Toast::new(message, Level::Info) }); + } + pass(&mut app, &ctx, 0.0, vec![]); + pass(&mut app, &ctx, 0.0, vec![]); + let at = app.toasts.list[1].rect.unwrap().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + pass(&mut app, &ctx, 0.1, vec![egui::Event::PointerMoved(at)]); + pass(&mut app, &ctx, 0.2, vec![press(true)]); + // "pressed" goes, and "top" moves down under the pointer. + pass(&mut app, &ctx, 0.6, vec![]); + pass(&mut app, &ctx, 0.7, vec![]); + pass(&mut app, &ctx, 0.8, vec![press(false)]); + assert_eq!(messages(&app), vec!["top", "bottom"]); + } + + #[test] + fn an_action_records_a_message_and_shows_it_again_when_played() { + use crate::panels::actions::{START_RECORDING, STOP_RECORDING, play}; + let (mut app, _) = app(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + app.run("app.toast", json!({"message": "Step done", "level": "success"})).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + // The recording is the set's last action. + let last = app.ui.action_sets[0].actions.len() - 1; + let steps = &app.ui.action_sets[0].actions[last].steps; + assert_eq!(steps, &vec![("app.toast".to_string(), json!({"message": "Step done", "level": "success"}))]); + app.session.take_toasts(); + let undo = app.session.active().unwrap().history.undo.len(); + play(&mut app, 0, last).unwrap(); + assert_eq!(app.session.take_toasts(), vec![Toast::new("Step done", Level::Success)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "a message adds no undo step"); + } + + #[test] + fn a_long_message_shows_its_first_lines_and_the_stack_stays_in_the_window() { + let (mut app, ctx) = app(); + app.run("app.toast", json!({"message": "line"})).unwrap(); + app.run("app.toast", json!({"message": "line\n".repeat(100)})).unwrap(); + pass(&mut app, &ctx, 0.0, vec![]); + pass(&mut app, &ctx, 0.0, vec![]); + let (short, long) = (app.toasts.list[0].rect.unwrap(), app.toasts.list[1].rect.unwrap()); + // 100 lines would make it about 100 times as tall as a message of one line. + assert!(long.height() > short.height() && long.height() < short.height() * MAX_ROWS as f32, "{short:?} {long:?}"); + app.toasts.list.remove(0); + // Five such messages in a short window: the newest shows whole at the bottom, and none + // reaches past the window's edges. + for _ in 0..MAX_SHOWN - 1 { + app.run("app.toast", json!({"message": "line\n".repeat(100)})).unwrap(); + } + let height = 300.0; + pass_in(&mut app, &ctx, 0.0, vec![], height); + pass_in(&mut app, &ctx, 0.0, vec![], height); + let newest = app.toasts.list.last().unwrap().rect.unwrap(); + assert!(newest.top() >= MARGIN - 0.5 && newest.bottom() <= height - MARGIN + 0.5, "{newest:?}"); + assert_eq!(app.toasts.list.len(), MAX_SHOWN); + } + + #[test] + fn no_message_draws_nothing() { + let (mut app, ctx) = app(); + assert!(pass(&mut app, &ctx, 0.0, vec![]).is_empty()); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index a27f99feba..12f8376324 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3157,6 +3157,23 @@ enabled while the document has a saved view. In the desktop app the views are li checked when it opens: past 25, blank or repeated names, and views without a finite centre and a positive zoom are dropped. +## Messages over the window + +`app.toast {message, level?, seconds?}` shows a short message over the desktop app's window without stopping work +→ `{message, level, seconds}`. `message` is 1 to 500 characters and not only spaces. `level` is `info` (the +default), `success`, `warning` or `error`, and sets the color of the message's edge. `seconds` is how long it shows, +0.5 to 60 (4 by default); a click on it closes it sooner. Messages stack at the window's bottom right, the newest +lowest, at most 5 at once: a sixth closes the oldest. A message shows at most 6 lines, with the whole text on hover, +and a stack taller than the window scrolls. A missing `message` or a value outside these ranges is an error, +and nothing shows. The command edits no document and adds no undo step. Scripts raise one with `vc.run('app.toast', +{...})`, a plug-in whose manifest lists `app.toast` calls it like its other commands, and an action recording records it as a step that shows the message again when the action plays. A session +without a window (MCP, `vectorcraft-cli`) keeps the last 32 messages it was given and shows none. These limits are +VectorCraft's own values. + +```json +{"name":"run_command","arguments":{"command":"app.toast","params":{"message":"Exported 4 artboards","level":"success"}}} +``` + ## Navigator panel options The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index db61a96f73..5b5f596a9f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -904,6 +904,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`. + - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. From 5af51906dcac12a298d5e3a2f2711cfc40205d7c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:00:58 -0800 Subject: [PATCH 2/4] Messages: a press on a message closes it when an older message goes first The click took the frame's automatic id, which follows its position among the messages, so a message pressed while an older one expired did not close on release. The click now takes an id from the message's own scope. --- crates/ui-egui/src/toasts.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/toasts.rs b/crates/ui-egui/src/toasts.rs index 0d47c4e3b4..a8bdb46be5 100644 --- a/crates/ui-egui/src/toasts.rs +++ b/crates/ui-egui/src/toasts.rs @@ -138,7 +138,9 @@ fn message(ui: &mut egui::Ui, e: &Entry, t: &Tokens) -> egui::Response { ui.add(egui::Label::new(galley).selectable(false)); elided }); - let r = frame.response.interact(egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); + // The click takes its id from the message's own scope, not from the frame's position among + // the messages, so a press survives an older message going. + let r = ui.interact(frame.response.rect, ui.scope_id().with("toast"), egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); // A message cut short shows in full on hover. if frame.inner { r.on_hover_text(&e.toast.message) } else { r } } @@ -257,6 +259,26 @@ mod tests { assert_eq!(messages(&app), vec!["top", "bottom"]); } + #[test] + fn a_message_pressed_while_an_older_one_goes_still_closes_on_release() { + let (mut app, ctx) = app(); + for (message, seconds) in [("older", 0.5), ("pressed", 60.0), ("bottom", 60.0)] { + app.session.toast(Toast { seconds, ..Toast::new(message, Level::Info) }); + } + pass(&mut app, &ctx, 0.0, vec![]); + pass(&mut app, &ctx, 0.0, vec![]); + let at = app.toasts.list[1].rect.unwrap().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + pass(&mut app, &ctx, 0.1, vec![egui::Event::PointerMoved(at)]); + pass(&mut app, &ctx, 0.2, vec![press(true)]); + // "older" goes while the button is down; the newer messages stay where they were. + pass(&mut app, &ctx, 0.6, vec![]); + assert_eq!(messages(&app), vec!["pressed", "bottom"]); + pass(&mut app, &ctx, 0.7, vec![]); + pass(&mut app, &ctx, 0.8, vec![press(false)]); + assert_eq!(messages(&app), vec!["bottom"]); + } + #[test] fn an_action_records_a_message_and_shows_it_again_when_played() { use crate::panels::actions::{START_RECORDING, STOP_RECORDING, play}; From 12f7e34f2100dc6bea4ee135b1906e6f32b465f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 12:06:08 -0800 Subject: [PATCH 3/4] Messages: a success token, and the docs state the plug-in and rollback rules - The success level takes a new `success` theme token (the same green) instead of the 3D axis color. - docs/mcp.md names the plug-in conditions for `vc_call`, says no step is recorded while a drag or typing is in progress, says a failed script run keeps the messages it raised, and names the headless MCP server and `vectorcraft-cli run` as the sessions without a window. Lines wrap like the rest of the file. - The params text and the error say "whitespace", which is what the check rejects. - A new test runs a script that draws, raises a message and throws: the drawing is put back and the message is kept. - The long-message test also checks that the stack stays inside the window. - The evidence line in docs/target-app-parity.md moves after the Scripts entries. --- crates/engine/src/cmd/toast.rs | 34 ++++++++++++++++++++++++++++------ crates/ui-egui/src/theme.rs | 3 +++ crates/ui-egui/src/toasts.rs | 11 +++++++---- docs/mcp.md | 14 ++++++++------ docs/target-app-parity.md | 2 +- 5 files changed, 47 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/toast.rs b/crates/engine/src/cmd/toast.rs index c692ad702d..bf6ed66fee 100644 --- a/crates/engine/src/cmd/toast.rs +++ b/crates/engine/src/cmd/toast.rs @@ -1,7 +1,8 @@ //! `app.toast`: a short message shown over the window that does not stop work and goes away by -//! itself (a toast). Scripts (`vc.run`), actions (a recorded step), MCP clients and the app's own -//! code ([`Session::toast`]) raise one. The engine queues the messages and the desktop app takes -//! them each frame ([`Session::take_toasts`]) and shows them. +//! itself (a toast). Scripts (`vc.run`), actions (a recorded step), MCP clients and plug-ins raise +//! one with the command, and the app's code can raise one with [`Session::toast`]. The engine +//! queues the messages and the desktop app takes them each frame ([`Session::take_toasts`]) and +//! shows them. A failed script run puts the documents back but keeps the messages it raised. use std::collections::VecDeque; @@ -22,7 +23,7 @@ pub const MIN_SECONDS: f64 = 0.5; pub const MAX_SECONDS: f64 = 60.0; /// The most messages waiting for the app to take them: past it the oldest one goes. A session -/// without a window (MCP, the command line) never takes them. +/// without a window (the headless MCP server, `vectorcraft-cli run`) never takes them. pub const MAX_QUEUED: usize = 32; /// What kind of news a message is, which sets its color. @@ -95,7 +96,7 @@ pub fn specs() -> Vec { "Show Message", [], None, - "{message: string (1 to 500 characters, not only spaces), level?: \"info\" | \"success\" | \"warning\" | \"error\" (default \"info\"), seconds?: number 0.5 to 60 (default 4)} show `message` over the window without stopping work: it goes away after `seconds` or when clicked; messages stack at the window's bottom right, the newest lowest, at most 5 at once; edits no document; an action records it as a step → {message, level, seconds}", + "{message: string (1 to 500 characters, not only whitespace), level?: \"info\" | \"success\" | \"warning\" | \"error\" (default \"info\"), seconds?: number 0.5 to 60 (default 4)} show `message` over the window without stopping work: it goes away after `seconds` or when clicked; messages stack at the window's bottom right, the newest lowest, at most 5 at once; edits no document; an action records it as a step → {message, level, seconds}", always, run )] @@ -116,7 +117,7 @@ fn parse(p: &Value) -> Result { None => return Err(bad(ID, "`message` is required")), }; if message.trim().is_empty() { - return Err(bad(ID, "`message` must have a character other than a space")); + return Err(bad(ID, "`message` must have a character other than whitespace")); } let chars = message.chars().count(); if chars > MAX_CHARS { @@ -231,6 +232,27 @@ mod tests { assert_eq!(s.take_toasts(), vec![Toast::new("Done: 2", Level::Success)]); } + #[test] + fn a_failed_script_run_puts_the_documents_back_and_keeps_its_messages() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let art = format!("{:?}", s.active().unwrap().doc.layers); + let e = s + .execute( + "script.run", + &json!({ + "source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.run('app.toast', {message: 'Failed: no artboard'}); throw new Error('stop');", + "name": "t.js", + "answers": [], + }), + ) + .unwrap_err() + .to_string(); + assert!(e.contains("stop"), "{e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art, "the rectangle is put back"); + assert_eq!(s.take_toasts(), vec![Toast::new("Failed: no artboard", Level::Info)]); + } + #[test] fn a_command_batch_raises_its_messages_in_order() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index eeb00ceb62..8e4a7267bf 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -163,6 +163,8 @@ pub struct Tokens { pub error: Color32, /// Warning marks (a modified linked file). pub warning: Color32, + /// Success marks (a message of level `success`). + pub success: Color32, /// Rotation gizmo axes, also labelled X, Y and Z. pub axis_x: Color32, pub axis_y: Color32, @@ -215,6 +217,7 @@ impl Tokens { artboard_mark: hex(0x808080), error: hex(0xe34850), warning: hex(0xf0a330), + success: hex(0x45af63), axis_x: hex(0xef6058), axis_y: hex(0x45af63), axis_z: hex(0x378ef0), diff --git a/crates/ui-egui/src/toasts.rs b/crates/ui-egui/src/toasts.rs index a8bdb46be5..d1f35f6326 100644 --- a/crates/ui-egui/src/toasts.rs +++ b/crates/ui-egui/src/toasts.rs @@ -1,6 +1,6 @@ -//! Messages that `app.toast` and the app's own code ([`vectorcraft_engine::Session::toast`]) queue, -//! shown over the window without taking the keyboard or stopping work: a stack at the window's -//! bottom right, the newest lowest. Each one goes after its time or when clicked; past +//! Messages that `app.toast` or a call of [`vectorcraft_engine::Session::toast`] queues, shown +//! over the window without taking the keyboard or stopping work: a stack at the window's bottom +//! right, the newest lowest. Each one goes after its time or when clicked; past //! [`MAX_SHOWN`] the oldest goes first. A message shows at most [`MAX_ROWS`] lines, and the whole //! text on hover; a stack taller than the window scrolls. @@ -64,7 +64,7 @@ impl Shown { fn color(t: &Tokens, level: Level) -> egui::Color32 { match level { Level::Info => t.text_dim, - Level::Success => t.axis_y, + Level::Success => t.success, Level::Warning => t.warning, Level::Error => t.error, } @@ -319,6 +319,9 @@ mod tests { pass_in(&mut app, &ctx, 0.0, vec![], height); let newest = app.toasts.list.last().unwrap().rect.unwrap(); assert!(newest.top() >= MARGIN - 0.5 && newest.bottom() <= height - MARGIN + 0.5, "{newest:?}"); + // The stack scrolls inside the window instead of growing past its top. + let stack = ctx.memory(|m| m.area_rect(egui::Id::unique("toasts"))).unwrap(); + assert!(stack.top() >= MARGIN - 0.5 && stack.bottom() <= height - MARGIN + 0.5, "{stack:?}"); assert_eq!(app.toasts.list.len(), MAX_SHOWN); } diff --git a/docs/mcp.md b/docs/mcp.md index 7c67124632..c780fceb17 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3160,15 +3160,17 @@ dropped. ## Messages over the window `app.toast {message, level?, seconds?}` shows a short message over the desktop app's window without stopping work -→ `{message, level, seconds}`. `message` is 1 to 500 characters and not only spaces. `level` is `info` (the +→ `{message, level, seconds}`. `message` is 1 to 500 characters and not only whitespace. `level` is `info` (the default), `success`, `warning` or `error`, and sets the color of the message's edge. `seconds` is how long it shows, 0.5 to 60 (4 by default); a click on it closes it sooner. Messages stack at the window's bottom right, the newest lowest, at most 5 at once: a sixth closes the oldest. A message shows at most 6 lines, with the whole text on hover, -and a stack taller than the window scrolls. A missing `message` or a value outside these ranges is an error, -and nothing shows. The command edits no document and adds no undo step. Scripts raise one with `vc.run('app.toast', -{...})`, a plug-in whose manifest lists `app.toast` calls it like its other commands, and an action recording records it as a step that shows the message again when the action plays. A session -without a window (MCP, `vectorcraft-cli`) keeps the last 32 messages it was given and shows none. These limits are -VectorCraft's own values. +and a stack taller than the window scrolls. A missing `message` or a value outside these ranges is an error, and +nothing shows. The command edits no document and adds no undo step. Scripts raise one with `vc.run('app.toast', +{...})`. A plug-in calls it through `vc_call` under the conditions in [Plug-ins](#plug-ins): API level 2, the +`commands` and `doc.read` permissions, and `app.toast` in its `commandAllowlist`. An action recording records it as a +step that shows the message again when the action plays, except while a drag or typing is in progress, when no +command is recorded. A script run that fails puts the documents back, and the messages it raised still show. The headless MCP server and `vectorcraft-cli run` have no window: they keep the last 32 messages they were +given and show none. These limits are VectorCraft's own values. ```json {"name":"run_command","arguments":{"command":"app.toast","params":{"message":"Exported 4 artboards","level":"success"}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 618b0f4be4..a3497e92c5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -905,7 +905,6 @@ 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`. - - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. @@ -922,6 +921,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; writing, the file dialogs and `execute` are not available yet. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. + - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. - Saves, Export for Screens and Package under `--automation-read-root`: a save without a path leaves the document's own file out of its reply, and a save without a path known leaves out the suggested folder, when they are outside the read roots; Export for Screens into an export preset's folder outside them lists its files relative to that folder and names that folder by its name in an error, and the export settings and saved presets leave out a folder outside them when read or exported; Package's report and warnings, and Document Info's linked images, name a file outside them by its file name. A path the client gives stays in the reply. `crates/engine/src/tests/save.rs`, `crates/engine/src/cmd/fileio/tests_screens.rs`, `crates/engine/src/tests/package.rs`, `crates/ui-egui/src/tests/automation.rs`. - Errors under `--automation-read-root`: a refused save without a path and `file.revert` (also as an `action.batch` step), `script.listInstalled` and `links.relink {copy}` name the document's own file, the Scripts folder or the document's folder by its file name when it is outside the read roots, and keep the roots and the reason; `links.relink`'s copies name such a file by its file name too. A path the client gives stays whole. `crates/engine/src/tests/save.rs` (`pathless_save_rejection_hides_document_folder`), `crates/engine/src/cmd/fileio/action_batch.rs`, `crates/engine/src/tests/links.rs`, `crates/engine/src/tests/script_folder.rs`. From ae2e920cc1a61549b9d85c1ea71036dd0dccbeb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:43:10 -0800 Subject: [PATCH 4/4] Toasts: messages narrow to fit a narrow window, and app messages keep the time limits In a window narrower than 352 points, messages narrow to the window's width less the stack's margins, with 32 points as the least, and the text wraps to that width. A message the app queues with Session::toast shows for 0.5 to 60 seconds, as app.toast allows; a time that is not a number shows for 4 seconds. --- crates/engine/src/cmd/toast.rs | 17 ++++++++++++-- crates/ui-egui/src/toasts.rs | 43 ++++++++++++++++++++++++++-------- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/toast.rs b/crates/engine/src/cmd/toast.rs index bf6ed66fee..e2eb41bd21 100644 --- a/crates/engine/src/cmd/toast.rs +++ b/crates/engine/src/cmd/toast.rs @@ -76,8 +76,11 @@ impl Toast { pub struct Queue(VecDeque); impl Session { - /// Queue `toast` for the app to show. With [`MAX_QUEUED`] waiting, the oldest one goes. - pub fn toast(&mut self, toast: Toast) { + /// Queue `toast` for the app to show. With [`MAX_QUEUED`] waiting, the oldest one goes. Its + /// time is held to [`MIN_SECONDS`] to [`MAX_SECONDS`], and a time that is not a number is + /// [`DEFAULT_SECONDS`]. + pub fn toast(&mut self, mut toast: Toast) { + toast.seconds = if toast.seconds.is_nan() { DEFAULT_SECONDS } else { toast.seconds.clamp(MIN_SECONDS, MAX_SECONDS) }; while self.toasts.0.len() >= MAX_QUEUED { self.toasts.0.pop_front(); } @@ -192,6 +195,16 @@ mod tests { assert_eq!(s.take_toasts().len(), 1); } + #[test] + fn a_message_queued_by_the_app_shows_for_0_5_to_60_seconds() { + let mut s = Session::new(); + for seconds in [f64::INFINITY, 1e9, f64::NEG_INFINITY, 0.0, f64::NAN, 10.0] { + s.toast(Toast { seconds, ..Toast::new("m", Level::Info) }); + } + let got: Vec = s.take_toasts().iter().map(|t| t.seconds).collect(); + assert_eq!(got, vec![MAX_SECONDS, MAX_SECONDS, MIN_SECONDS, MIN_SECONDS, DEFAULT_SECONDS, 10.0]); + } + #[test] fn the_oldest_waiting_message_goes_past_the_limit() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/toasts.rs b/crates/ui-egui/src/toasts.rs index d1f35f6326..c6868e0cfc 100644 --- a/crates/ui-egui/src/toasts.rs +++ b/crates/ui-egui/src/toasts.rs @@ -17,6 +17,10 @@ pub const MAX_SHOWN: usize = 5; /// The widest a message is, in points; longer text wraps. const WIDTH: f32 = 320.0; +/// The narrowest a message gets in a narrow window, in points: its frame's margin and edge (22 +/// points) and room for one character. +const MIN_WIDTH: f32 = 32.0; + /// The most lines a message shows; the rest shows on hover. const MAX_ROWS: usize = 6; @@ -91,10 +95,12 @@ pub(crate) fn show_at(app: &mut VectorcraftApp, ctx: &egui::Context, now: f64) { let area = egui::Area::new(egui::Id::unique("toasts")).order(egui::Order::Foreground).anchor(egui::Align2::RIGHT_BOTTOM, corner); // A stack taller than the window scrolls, kept at its newest message. let height = (ctx.content_rect().height() - 2.0 * MARGIN).max(0.0); + // In a window narrower than a message, the messages narrow to fit it. + let width = WIDTH.min(ctx.content_rect().width() - 2.0 * MARGIN).max(MIN_WIDTH); let dismissed = area .show(ctx, |ui| { let scroll = egui::ScrollArea::vertical().max_height(height).stick_to_bottom(true); - scroll.show(ui, |ui| stack(ui, &mut app.toasts.list, &t)).inner + scroll.show(ui, |ui| stack(ui, &mut app.toasts.list, &t, width)).inner }) .inner; if let Some(id) = dismissed { @@ -103,14 +109,14 @@ pub(crate) fn show_at(app: &mut VectorcraftApp, ctx: &egui::Context, now: f64) { } } -/// Draw `list`, oldest first; the id of the message clicked. -fn stack(ui: &mut egui::Ui, list: &mut [Entry], t: &Tokens) -> Option { - ui.set_max_width(WIDTH); +/// Draw `list`, oldest first, `width` points wide; the id of the message clicked. +fn stack(ui: &mut egui::Ui, list: &mut [Entry], t: &Tokens, width: f32) -> Option { + ui.set_max_width(width); let mut clicked = None; for e in list { // Each message's widgets keep its id when the messages before it go, so a press and a // release land on the same message. - let r = ui.push_id(e.id, |ui| message(ui, e, t)).inner; + let r = ui.push_id(e.id, |ui| message(ui, e, t, width)).inner; if r.clicked() { clicked = Some(e.id); } @@ -120,18 +126,19 @@ fn stack(ui: &mut egui::Ui, list: &mut [Entry], t: &Tokens) -> Option { clicked } -/// Draw one message → its response to clicks. -fn message(ui: &mut egui::Ui, e: &Entry, t: &Tokens) -> egui::Response { +/// Draw one message `width` points wide → its response to clicks. +fn message(ui: &mut egui::Ui, e: &Entry, t: &Tokens, width: f32) -> egui::Response { let frame = egui::Frame::new() .fill(t.panel) .stroke(egui::Stroke::new(1.0, color(t, e.toast.level))) .corner_radius(t.radius) .inner_margin(egui::Margin::symmetric(10, 8)) .show(ui, |ui| { - ui.set_width(WIDTH - 20.0); + // The frame's margin and edge take 11 points on each side. + ui.set_width(width - 22.0); let format = egui::TextFormat::simple(egui::TextStyle::Body.resolve(ui.style()), t.text); let mut job = egui::text::LayoutJob::single_section(e.toast.message.clone(), format); - job.wrap.max_width = WIDTH - 20.0; + job.wrap.max_width = width - 22.0; job.wrap.max_rows = MAX_ROWS; let galley = ui.painter().layout_job(job); let elided = galley.elided; @@ -168,7 +175,12 @@ mod tests { /// [`pass`] in a window `height` points tall. fn pass_in(app: &mut VectorcraftApp, ctx: &egui::Context, now: f64, events: Vec, height: f32) -> Vec { - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, height)); + pass_sized(app, ctx, now, events, egui::vec2(1000.0, height)) + } + + /// [`pass`] in a window of `size` points. + fn pass_sized(app: &mut VectorcraftApp, ctx: &egui::Context, now: f64, events: Vec, size: egui::Vec2) -> Vec { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; let mut output = ctx.run_ui(input, |ui| show_at(app, ui.ctx(), now)); output.textures_delta.clear(); @@ -325,6 +337,17 @@ mod tests { assert_eq!(app.toasts.list.len(), MAX_SHOWN); } + #[test] + fn a_message_in_a_narrow_window_stays_inside_it() { + let (mut app, ctx) = app(); + app.run("app.toast", json!({"message": "A message long enough to wrap onto more than one line"})).unwrap(); + let size = egui::vec2(200.0, 700.0); + pass_sized(&mut app, &ctx, 0.0, vec![], size); + pass_sized(&mut app, &ctx, 0.0, vec![], size); + let rect = app.toasts.list[0].rect.unwrap(); + assert!(rect.left() >= MARGIN - 0.5 && rect.right() <= size.x - MARGIN + 0.5, "{rect:?}"); + } + #[test] fn no_message_draws_nothing() { let (mut app, ctx) = app();