mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 02:03:02 +00:00
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.
This commit is contained in:
@@ -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());
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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> {
|
||||
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.
|
||||
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<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 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<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 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<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_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)]);
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<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.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<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)).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<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> {
|
||||
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<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 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());
|
||||
}
|
||||
}
|
||||
+17
@@ -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`),
|
||||
|
||||
@@ -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`.
|
||||
|
||||
Reference in New Issue
Block a user