mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 02:03:02 +00:00
Merge pull request #8403 from dotCooCoo/feat/toast-messages
Messages: app.toast shows a message over the window without stopping work
This commit is contained in:
@@ -105,6 +105,7 @@ mod retype;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
pub(crate) mod threads;
|
||||
pub mod toast;
|
||||
pub(crate) mod typecmd;
|
||||
mod typemenu;
|
||||
mod variablecmds;
|
||||
@@ -335,6 +336,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());
|
||||
|
||||
@@ -88,6 +88,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.type.textTweaker",
|
||||
"addon.units.convert",
|
||||
"addon.units.selectionSize",
|
||||
"app.toast",
|
||||
"appearance.addEffect",
|
||||
"appearance.addFill",
|
||||
"appearance.addStroke",
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
//! `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 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;
|
||||
|
||||
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 (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.
|
||||
#[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> {
|
||||
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<String>, 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<Toast>);
|
||||
|
||||
impl Session {
|
||||
/// 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();
|
||||
}
|
||||
self.toasts.0.push_back(toast);
|
||||
}
|
||||
|
||||
/// Take the messages queued since the last call, oldest first.
|
||||
pub fn take_toasts(&mut self) -> Vec<Toast> {
|
||||
self.toasts.0.drain(..).collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"app.toast",
|
||||
"Show Message",
|
||||
[],
|
||||
None,
|
||||
"{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
|
||||
)]
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Toast> {
|
||||
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 whitespace"));
|
||||
}
|
||||
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 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<f64> = 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();
|
||||
for i in 0..MAX_QUEUED + 2 {
|
||||
s.toast(Toast::new(format!("{i}"), Level::Info));
|
||||
}
|
||||
let left: Vec<String> = 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_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();
|
||||
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)]);
|
||||
}
|
||||
}
|
||||
@@ -360,6 +360,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 {
|
||||
|
||||
@@ -149,6 +149,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(),
|
||||
|
||||
@@ -164,6 +164,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(),
|
||||
@@ -638,6 +639,7 @@ impl VectorcraftApp {
|
||||
// After every window this pass may open, and before the palette's field takes the keyboard.
|
||||
panel_docking::close_overlays_for_modal(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 {
|
||||
|
||||
@@ -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;
|
||||
@@ -292,6 +293,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.
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
//! 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.
|
||||
|
||||
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 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;
|
||||
|
||||
/// 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<egui::Rect>,
|
||||
}
|
||||
|
||||
/// The messages shown, oldest first.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Shown {
|
||||
pub(crate) list: Vec<Entry>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
/// Show `new` from `now` on, dropping the oldest past [`MAX_SHOWN`].
|
||||
fn add(&mut self, new: Vec<Toast>, 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<f64> {
|
||||
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.success,
|
||||
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);
|
||||
// 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, width)).inner
|
||||
})
|
||||
.inner;
|
||||
if let Some(id) = dismissed {
|
||||
app.toasts.list.retain(|e| e.id != id);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<u64> {
|
||||
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, width)).inner;
|
||||
if r.clicked() {
|
||||
clicked = Some(e.id);
|
||||
}
|
||||
e.rect = Some(r.rect);
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
clicked
|
||||
}
|
||||
|
||||
/// 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| {
|
||||
// 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 - 22.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
|
||||
});
|
||||
// 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 }
|
||||
}
|
||||
|
||||
#[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<egui::Event>) -> Vec<String> {
|
||||
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<egui::Event>, height: f32) -> Vec<String> {
|
||||
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<egui::Event>, size: egui::Vec2) -> Vec<String> {
|
||||
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();
|
||||
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<f32> = 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 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};
|
||||
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:?}");
|
||||
// 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);
|
||||
}
|
||||
|
||||
#[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();
|
||||
assert!(pass(&mut app, &ctx, 0.0, vec![]).is_empty());
|
||||
}
|
||||
}
|
||||
+19
@@ -3382,6 +3382,25 @@ 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 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 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"}}}
|
||||
```
|
||||
|
||||
## Navigator panel options
|
||||
|
||||
The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`),
|
||||
|
||||
@@ -972,6 +972,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `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`.
|
||||
|
||||
Reference in New Issue
Block a user