shell-w15: net change of 3 commits

- shell-w15: written from its sheet
- shell-w15: repair 1
- shell-w15: finished by an agent
This commit is contained in:
bflatastic
2026-11-21 23:22:57 +07:00
parent 51dd1e0288
commit e256590336
6 changed files with 574 additions and 964 deletions
+125 -104
View File
@@ -1,24 +1,35 @@
//! Safe Mode in the app: the choice after a launch that stopped while a plug-in was loading
//! ([`ask_about_stopped`]: Disable and Continue, Start Normally, or Start in Safe Mode), and Help ›
//! Safe Mode ([`open`]), which lists the disabled plug-ins with Enable on Re-launch. Safe Mode
//! itself, the disabled list and the launch marker are `vectorcraft_plugins::safe_mode`'s.
//! itself, the disabled list and the launch marker are `vectorcraft_plugins::safe_mode`'s. Both
//! dialogs live on the dialog host; [`pump`] reads their answers.
use serde_json::{Value, json};
use craft_ui::contract::Bind;
use craft_ui::dialog::{DialogResult, PromptChoice, StandardPrompt, StartupStage, dialog_id};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
use serde_json::Value;
use vectorcraft_plugins::safe_mode::{self, Item};
use super::DialogSpec;
use crate::VectorcraftApp;
use crate::state::Dialog;
use crate::theme::Tokens;
/// Dialog kind of the choice after a launch that stopped. Fields: `item` (`{id, file, name, label}`)
/// and `normal` (Start Normally instead of Disable and Continue). Cancel starts in Safe Mode.
/// Key of the choice after a launch that stopped. It holds `UiState::stopped_plugin` (the item as
/// `{id, file, name, label}`) until answered. Cancel starts in Safe Mode.
pub const STOPPED: &str = "pluginStopped";
/// Dialog kind of Help › Safe Mode. Fields: `items` (`[{id, file, name, label, enable}]`, the
/// disabled plug-ins, `enable` being Enable on Re-launch).
/// Key of Help › Safe Mode's dialog. It has a check box `enable-{k}` (Enable on Re-launch) and the
/// plug-in it stands for, `item-{k}`, for each disabled plug-in listed.
pub const KIND: &str = "safeMode";
/// The field holding the plug-in of row `k`.
fn item_key(k: usize) -> String {
format!("item-{k}")
}
/// The field holding Enable on Re-launch of row `k`.
fn enable_key(k: usize) -> String {
format!("enable-{k}")
}
/// Before any plug-in loads (desktop): starts this launch's marker in `marker_dir` (none: no
/// marker), and turns Safe Mode on for `--safe-mode` (`flag`), or until the user chooses after a
/// launch that stopped while a plug-in was loading → that plug-in, for [`after_start`]. With `flag`
@@ -54,30 +65,20 @@ pub fn after_start(app: &mut VectorcraftApp, stopped: Option<Item>) {
}
/// Ask what to do about `item`, the plug-in the last launch was loading when it stopped. Safe Mode
/// is on until the user chooses. A dialog that takes the choice's place leaves it waiting: it opens
/// again once no dialog is open ([`reopen`]).
/// is on until the user chooses. The app holds the item; [`pump`] puts the question on the dialog
/// host once the host exists and no other dialog holds it, so a dialog that takes the choice's
/// place leaves it waiting.
pub fn ask_about_stopped(app: &mut VectorcraftApp, item: &Item) {
let item = item.to_json();
app.ui.stopped_plugin = Some(item.clone());
app.ui.dialog = Some(Dialog::new(STOPPED, json!({ "item": item })));
}
/// With no dialog open, the choice about a stopped plug-in that another dialog replaced opens again.
pub(super) fn reopen(app: &mut VectorcraftApp) {
if app.ui.dialog.is_none()
&& let Some(item) = app.ui.stopped_plugin.clone()
{
app.ui.dialog = Some(Dialog::new(STOPPED, json!({ "item": item })));
}
app.ui.stopped_plugin = Some(item.to_json());
}
/// The choice's Cancel, Start in Safe Mode: Safe Mode stays on for this launch, and the plug-in
/// stays pending for the next one.
pub(super) fn cancel_stopped(app: &mut VectorcraftApp) {
fn cancel_stopped(app: &mut VectorcraftApp) {
app.ui.stopped_plugin = None;
}
/// The choice about a stopped plug-in is waiting for the user (shown, or replaced by another
/// The choice about a stopped plug-in is waiting for the user (shown, or held back by another
/// dialog): Safe Mode is on, and nothing has loaded yet.
pub fn choosing(app: &VectorcraftApp) -> bool {
app.ui.stopped_plugin.is_some()
@@ -88,20 +89,33 @@ pub fn staying_on(app: &VectorcraftApp) -> bool {
safe_mode::active() && !choosing(app)
}
/// The item a dialog field holds.
/// The item a held plug-in value names.
fn item_of(v: &Value) -> Item {
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
Item { id: s("id"), file: s("file"), name: s("name") }
}
/// The choice's Disable and Continue (OK) or Start Normally: Safe Mode ends and the plug-ins load,
/// without the stopped one for Disable and Continue (kept off for later launches too).
fn confirm_stopped(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
app.ui.dialog = None;
app.ui.stopped_plugin = None;
let item = item_of(d.fields.get("item").unwrap_or(&Value::Null));
/// The question about the stopped plug-in `item`.
fn stopped_prompt(item: &Value) -> StandardPrompt {
let name = item_of(item).label();
let text = crate::i18n::fmt(
tl!("The last launch of VectorCraft stopped while the plug-in {name} was loading. It may not be what stopped it."),
&[("name", &name)],
);
StandardPrompt::custom(text)
.title(tl!("Safe Mode").to_string())
.button(PromptChoice::Proceed, tl!("Disable and Continue").to_string())
.button(PromptChoice::Alternate, tl!("Start Normally").to_string())
.button(PromptChoice::Cancel, tl!("Start in Safe Mode").to_string())
}
/// The choice's Disable and Continue (`normal` false) or Start Normally: Safe Mode ends and the
/// plug-ins load, without the stopped one for Disable and Continue (kept off for later launches
/// too).
fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) {
let item = item_of(&app.ui.stopped_plugin.take().unwrap_or(Value::Null));
// When the disabled plug-in can't be saved for the next launch, that launch asks again.
let saved = d.bool("normal") || (safe_mode::disable(item) && app.session.store_disabled_plugins());
let saved = normal || (safe_mode::disable(item) && app.session.store_disabled_plugins());
if saved {
safe_mode::forget_previous();
} else {
@@ -109,7 +123,6 @@ fn confirm_stopped(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String
}
safe_mode::set_active(None);
vectorcraft_engine::cmd::plugin::load_prefs_folder(&mut app.session);
Ok(Value::Null)
}
/// Help › Safe Mode: the disabled plug-ins, none ticked for Enable on Re-launch. A plug-in disabled
@@ -117,30 +130,55 @@ fn confirm_stopped(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String
/// Enable on Re-launch turns on every entry with its id.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let disabled = safe_mode::disabled();
let items: Vec<Value> = disabled
.iter()
.enumerate()
.filter(|(k, i)| i.id.is_none() || !disabled[..*k].iter().any(|e| e.id == i.id))
.map(|(_, i)| {
let mut v = i.to_json();
v["enable"] = json!(false);
v
})
.collect();
app.ui.dialog = Some(Dialog::new(KIND, json!({ "items": items })));
let items: Vec<&Item> =
disabled.iter().enumerate().filter(|(k, i)| i.id.is_none() || !disabled[..*k].iter().any(|e| e.id == i.id)).map(|(_, i)| i).collect();
let mut fields = DialogFields::new();
let mut params = Vec::new();
if safe_mode::active() {
params.push(
Param::read_only_text(
"note",
"",
tl!("VectorCraft is in Safe Mode: no plug-ins load or run until it starts normally.").to_string(),
)
.full_width(),
);
}
params.push(Param::section(tl!("Disabled plug-ins").to_string()));
if items.is_empty() {
params.push(Param::read_only_text("none", "", tl!("No plug-ins are disabled.").to_string()).full_width());
}
for (k, item) in items.iter().enumerate() {
// A name made safe to show: control and reordering characters removed, bounded.
let label = format!("{}: {}", safe_mode::display_name(&item.label()), tl!("Enable on Re-launch"));
params.push(Param::new(enable_key(k), label, ParamKind::bool(false)));
fields.set(item_key(k), FieldValue::Json(item.to_json()));
}
// PLAN: `open` has no context, and the dialog remembers no values, so none is read from it; assumed `VectorcraftApp::dialogs()` (wg.S1).
let dialog = HostedParamDialog::new(&egui::Context::default(), KIND, fields, move |values| {
ParamDialog::new(KIND, tl!("Safe Mode").to_string(), params.clone()).values(Bind::bound(values))
});
app.dialogs().ok_or("no window")?.with(|h| {
h.open(dialog);
});
Ok(Value::Null)
}
/// Help › Safe Mode's OK: each ticked plug-in loads again from the next launch
/// (`plugin.setEnabled`).
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
app.ui.dialog = None;
fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) {
let mut errors = vec![];
let mut unsaved = false;
for v in d.fields.get("items").and_then(Value::as_array).into_iter().flatten().filter(|v| v["enable"] == true) {
let mut k = 0;
while let Some(FieldValue::Json(v)) = fields.get(&item_key(k)) {
let ticked = fields.bool(&enable_key(k)) == Some(true);
k += 1;
if !ticked {
continue;
}
let p = match (v["id"].as_str(), v["file"].as_str()) {
(Some(id), _) => json!({"id": id, "enabled": true}),
(None, Some(file)) => json!({"file": file, "enabled": true}),
(Some(id), _) => serde_json::json!({"id": id, "enabled": true}),
(None, Some(file)) => serde_json::json!({"file": file, "enabled": true}),
(None, None) => continue,
};
match app.run("plugin.setEnabled", p) {
@@ -148,10 +186,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
Err(e) => errors.push(e),
}
}
if unsaved {
if !errors.is_empty() {
app.status(errors.join("; "));
} else if unsaved {
not_saved(app);
}
if errors.is_empty() { Ok(Value::Null) } else { Err(errors.join("; ")) }
}
/// The disabled plug-ins couldn't be written to the plug-in folder: the next launch doesn't have
@@ -160,57 +199,39 @@ fn not_saved(app: &mut VectorcraftApp) {
app.status("Couldn't save the disabled plug-ins for the next launch");
}
pub(super) const STOPPED_SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Safe Mode").into(),
body: |_, ui, d| {
let t = Tokens::get(ui.ctx());
let name = item_of(d.fields.get("item").unwrap_or(&Value::Null)).label();
let text = crate::i18n::fmt(
tl!("The last launch of VectorCraft stopped while the plug-in {name} was loading. It may not be what stopped it."),
&[("name", &name)],
);
ui.label(egui::RichText::new(text).color(t.text));
false
},
confirm: confirm_stopped,
ok: Some("Disable and Continue"),
cancel: Some("Start in Safe Mode"),
alternate: Some(("Start Normally", "normal")),
min_width: 380.0,
max_width: Some(520.0),
..DialogSpec::FORM
};
/// After the shell pass: puts the choice about a stopped plug-in on the host when nothing else
/// holds it, and carries out the answers of the choice and of Help › Safe Mode.
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
pump_stopped(app, ctx);
pump_help(app);
}
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Safe Mode").into(),
body: |_, ui, d| {
let t = Tokens::get(ui.ctx());
if safe_mode::active() {
ui.label(egui::RichText::new(tl!("VectorCraft is in Safe Mode: no plug-ins load or run until it starts normally.")).color(t.text));
ui.add_space(8.0);
fn pump_stopped(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(item) = app.ui.stopped_plugin.clone() else { return };
// PLAN: assumed `VectorcraftApp::dialogs() -> Option<handle>` whose `with(|host: &mut DialogHost| ..)` runs on the host (wg.S1).
let Some(dialogs) = app.dialogs() else { return };
let answered = dialogs.with(|h| {
let answered = h.take::<StandardPrompt>();
// An empty host has neither an open dialog nor a queued one: otherwise the choice waits.
if answered.is_none() && h.is_empty() {
h.enqueue(StartupStage::Warning, stopped_prompt(&item));
ctx.request_repaint();
}
ui.label(egui::RichText::new(tl!("Disabled plug-ins")).color(t.text_dim));
let Some(items) = d.fields.get_mut("items").and_then(Value::as_array_mut).filter(|i| !i.is_empty()) else {
ui.label(egui::RichText::new(tl!("No plug-ins are disabled.")).color(t.text_dim));
return false;
};
egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| {
for (k, v) in items.iter_mut().enumerate() {
ui.horizontal(|ui| {
// A name made safe to show: control and reordering characters removed, bounded.
let label = safe_mode::display_name(v["label"].as_str().unwrap_or_default());
ui.label(egui::RichText::new(label).color(t.text));
let mut on = v["enable"] == true;
if ui.push_id(k, |ui| ui.checkbox(&mut on, tl!("Enable on Re-launch"))).inner.changed() {
v["enable"] = json!(on);
}
});
}
});
false
},
confirm,
min_width: 380.0,
max_width: Some(520.0),
..DialogSpec::FORM
};
answered
});
match answered.map(|r| r.ok().map(|a| a.choice)) {
None => {}
Some(Some(PromptChoice::Proceed)) => confirm_stopped(app, false),
Some(Some(PromptChoice::Alternate)) => confirm_stopped(app, true),
Some(_) => cancel_stopped(app),
}
}
fn pump_help(app: &mut VectorcraftApp) {
let Some(dialogs) = app.dialogs() else { return };
// A dialog made with an instance keeps its result apart from every other form's.
let answered = dialogs.with(|h| h.take_by_id::<HostedParamDialog>(dialog_id(KIND)));
if let Some(DialogResult::Ok(result)) = answered {
confirm(app, &result.fields);
}
}
@@ -1,19 +0,0 @@
//! Save Changes (closing a modified document): Save / Don't Save / Cancel. The flow lives in
//! [`crate::unsaved`]; this is its face in the shared dialog frame.
use super::DialogSpec;
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |d| crate::i18n::fmt(tl!("Do you want to save the changes you made to “{name}”?"), &[("name", &d.str("name"))]),
body: |_, ui, _| {
let t = crate::theme::Tokens::get(ui.ctx());
ui.label(egui::RichText::new(tl!("Your changes will be lost if you don't save them.")).color(t.text_dim));
false
},
confirm: |app, _| crate::unsaved::confirm(app),
ok: Some("Save"),
discard: Some("Don't Save"),
// Long document names wrap instead of widening the dialog.
max_width: Some(420.0),
..DialogSpec::FORM
};
-356
View File
@@ -1,356 +0,0 @@
//! 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());
}
}
+253 -128
View File
@@ -1,27 +1,60 @@
//! Closing documents with unsaved changes. File → Close / Close All, a tab's ×, Quit and the
//! window's close button first ask Save / Don't Save / Cancel for each modified document (one
//! dialog per document); Cancel stops the whole operation and a cancelled Save As keeps the
//! question per document); Cancel stops the whole operation and a cancelled Save As keeps the
//! document open.
//!
//! The question is an ordinary dialog (`UiState::dialog`, kind [`KIND`]), so agents answer it
//! like any other: `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then
//! confirm discards, `ui.dialog.cancel` cancels.
//! The question is the framework's `UnsavedChangesDialog` on the dialog host, and a `CloseGuard`
//! (`VectorcraftApp::closing`) decides what comes next. Agents answer it like any other dialog:
//! `ui.dialog.set {field: "choice", value: "dontSave"}` then `ui.dialog.confirm`, or
//! `ui.dialog.cancel`. [`pump`] reads the answer each frame.
use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep};
use craft_ui::dialog::UnsavedChangesDialog;
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio::SaveMode;
use crate::state::Dialog;
use crate::{VectorcraftApp, io};
/// Dialog kind. Fields: `index` (document), `uid` (the same document, which `index` may no longer
/// point at once a file dialog answers), `name` (its title), `then` (`close`, `closeAll` or `quit`:
/// what continues after this document) and `discard` (Don't Save). With `then` = `close`, the
/// protected field [`FRONT`] holds the uid of the document that was in front before the question.
/// The `pending` value of the reply to a close that asks first (`{"pending": "saveChanges"}`); it
/// is not a dialog kind.
pub const KIND: &str = "saveChanges";
/// Field of a [`KIND`] dialog asked by File → Close or a tab's ×: the uid of the document in front
/// before the question showed the asked one. Once the asked document closes, that document is in
/// front again while it is still open.
const FRONT: &str = "__front";
/// What continues after the asked document is answered.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Then {
/// File → Close or a tab's ×: only the asked document.
Close,
/// File → Close All.
CloseAll,
/// Quit or the window's close button.
Quit,
}
impl Then {
fn scope(self) -> CloseScope {
if self == Then::Quit { CloseScope::Quit } else { CloseScope::Close }
}
/// The name [`close_all`] takes.
fn name(self) -> &'static str {
match self {
Then::Close => "close",
Then::CloseAll => "closeAll",
Then::Quit => "quit",
}
}
}
/// A close operation that is asking: the guard over the modified documents (by `Document::uid`)
/// and what the operation does once they are answered.
pub(crate) struct Closing {
guard: CloseGuard<u64>,
/// For [`Then::Close`], the uid of the document that was in front before the question showed
/// the asked one: once the asked document closes, that document is in front again while it is
/// still open.
front: Option<u64>,
then: Then,
}
/// Nothing closes while a file dialog's sheet is on the window (macOS): what asked for it runs
/// again when it answers. (Elsewhere the dialog is a window of its own, and closing goes on.)
@@ -43,18 +76,19 @@ pub fn close(app: &mut VectorcraftApp, i: usize) -> Result<Value, String> {
refuse_while_picking(app)?;
finish_pending(app);
let dirty = app.session.documents().get(i).ok_or("no such document")?.is_dirty();
if dirty { ask(app, i, "close") } else { close_now(app, i, None) }
if dirty { ask(app, i, Then::Close) } else { close_now(app, i, None) }
}
/// File → Close All (`then` = `closeAll`) or Quit (`quit`): ask about the next modified document,
/// or finish once none is left.
/// File → Close All (`then` = `closeAll`) or Quit (`quit`): ask about the modified documents, or
/// finish once none is left.
pub fn close_all(app: &mut VectorcraftApp, then: &str) -> Result<Value, String> {
refuse_while_picking(app)?;
finish_pending(app);
let then = if then == "quit" { Then::Quit } else { Then::CloseAll };
if let Some(i) = app.session.documents().iter().position(|d| d.is_dirty()) {
return ask(app, i, then);
}
if then == "quit" {
if then == Then::Quit {
// Nothing unsaved is left: no recovery copies either.
vectorcraft_engine::cmd::recovery::forget_all(&mut app.session);
// The host closes the window.
@@ -74,26 +108,44 @@ pub fn any_dirty(app: &VectorcraftApp) -> bool {
app.session.documents().iter().any(|d| d.is_dirty())
}
/// Show document `i` and ask whether to save it. For a single close (`then` = `close`), the
/// dialog also remembers the document in front before it ([`FRONT`]).
fn ask(app: &mut VectorcraftApp, i: usize, then: &str) -> Result<Value, String> {
let front = app.session.active().map(|d| d.uid);
app.session.set_active(i);
let doc = &app.session.documents()[i];
let (name, uid) = (doc.title(), doc.uid);
let mut fields = json!({ "index": i, "uid": uid, "name": name, "then": then });
if let Some(front) = front.filter(|f| then == "close" && *f != uid) {
fields[FRONT] = json!(front);
}
app.ui.dialog = Some(Dialog::new(KIND, fields));
/// The index of the open document with `uid`: documents may close while a question is open.
fn position(app: &VectorcraftApp, uid: u64) -> Option<usize> {
app.session.documents().iter().position(|d| d.uid == uid)
}
/// Starts the operation at document `i` and asks about it. A single close asks only about `i`;
/// Close All and Quit ask about every modified document from `i` on.
fn ask(app: &mut VectorcraftApp, i: usize, then: Then) -> Result<Value, String> {
let docs = app.session.documents();
let uid = docs.get(i).ok_or("no such document")?.uid;
let uids: Vec<u64> =
if then == Then::Close { vec![uid] } else { docs.iter().skip(i).filter(|d| d.is_dirty()).map(|d| d.uid).collect() };
let front = app.session.active().map(|d| d.uid).filter(|f| then == Then::Close && *f != uid);
let guard = CloseGuard::new(then.scope(), uids);
show_question(app, &guard, uid)?;
app.closing = Some(Closing { guard, front, then });
Ok(json!({ "pending": KIND }))
}
/// Shows document `uid` and opens the question about it on the dialog host.
fn show_question(app: &mut VectorcraftApp, guard: &CloseGuard<u64>, uid: u64) -> Result<(), String> {
let i = position(app, uid).ok_or("no such document")?;
app.session.set_active(i);
let name = app.session.documents().get(i).map(|d| d.title()).ok_or("no such document")?;
let (scope, remaining) = (guard.scope(), guard.remaining());
// PLAN: assumed `VectorcraftApp::dialogs() -> Option<handle>` whose `with(|host: &mut DialogHost| ..)` runs on the host (wg.S1).
let dialogs = app.dialogs().ok_or("no window")?;
dialogs.with(|h| {
h.open(UnsavedChangesDialog::new(scope, name).remaining(remaining));
});
Ok(())
}
/// Close document `i` through the engine command; [`VectorcraftApp::sync_views`] drops its view.
/// When `front` names a document that is still open, that document is in front afterwards.
fn close_now(app: &mut VectorcraftApp, i: usize, front: Option<u64>) -> Result<Value, String> {
let r = app.session.execute("file.close", &json!({ "index": i })).map_err(|e| e.to_string())?;
if let Some(j) = front.and_then(|uid| app.session.documents().iter().position(|d| d.uid == uid)) {
if let Some(j) = front.and_then(|uid| position(app, uid)) {
app.session.set_active(j);
}
app.sync_views();
@@ -107,39 +159,105 @@ fn close_now(app: &mut VectorcraftApp, i: usize, front: Option<u64>) -> Result<V
Ok(r)
}
/// Answer the open dialog: save (or, with `discard`, don't), close the document and carry on.
pub fn confirm(app: &mut VectorcraftApp) -> Result<Value, String> {
let d = app.ui.dialog.take().ok_or("no dialog open")?;
let docs = app.session.documents();
// By its uid: documents may have closed while its Save dialog was open.
let i = match d.fields.get("uid").and_then(Value::as_u64) {
Some(uid) => docs.iter().position(|doc| doc.uid == uid),
None => d.fields.get("index").and_then(Value::as_u64).map(|i| i as usize).filter(|i| *i < docs.len()),
};
let i = i.ok_or("no such document")?;
if !d.bool("discard") {
app.session.set_active(i);
let r = io::save(app, vectorcraft_engine::cmd::fileio::SaveMode::Save, &json!({}), false)?;
// A save that asks first (replacing a file that would lose what opening it left out) keeps
// the document open: it closes once saved.
if r.get("pending").is_some() {
return Ok(r);
/// Saves document `i` and closes it. `false` when the save asked first (replacing a file that
/// would lose what opening it left out): the document stays open and the guard waits.
fn save_then_close(app: &mut VectorcraftApp, i: usize, front: Option<u64>) -> Result<bool, String> {
app.session.set_active(i);
let r = io::save(app, SaveMode::Save, &json!({}), false)?;
if r.get("pending").is_some() {
return Ok(false);
}
// Closing needs the file written: wait for a background save, and stop if it failed.
if r["background"] == true {
crate::background::wait_all(app);
if let Some(d) = app.session.documents().get(i).filter(|d| d.is_dirty()) {
return Err(format!("{}: not saved, so not closed", d.title()));
}
// Closing needs the file written: wait for a background save, and stop if it failed.
if r["background"] == true {
crate::background::wait_all(app);
if let Some(d) = app.session.documents().get(i).filter(|d| d.is_dirty()) {
return Err(format!("{}: not saved, so not closed", d.title()));
}
close_now(app, i, front)?;
Ok(true)
}
/// Reads the answer to the open question and carries the operation on. An error stops the
/// operation (the document stays open) and is reported in the status line.
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
if app.closing.is_none() {
return;
}
let Some(result) = app.dialogs().and_then(|d| d.with(|h| h.take::<UnsavedChangesDialog>())) else { return };
let Some(mut closing) = app.closing.take() else { return };
// Closed from outside: the same as Cancel.
let (answer, all) = result.ok().map_or((CloseAnswer::Cancel, false), |a| (a.answer, a.apply_to_all));
let step = if all { closing.guard.answer_all(answer) } else { closing.guard.answer(answer) };
advance(app, closing, step);
ctx.request_repaint();
}
/// Acts on `step` until the guard asks a question again, waits, or stops.
fn advance(app: &mut VectorcraftApp, mut closing: Closing, mut step: GuardStep<u64>) {
loop {
step = match step {
GuardStep::Cancelled => return,
GuardStep::Finished => {
if closing.then != Then::Close
&& let Err(e) = close_all(app, closing.then.name())
{
app.status(e);
}
return;
}
}
}
close_now(app, i, d.fields.get(FRONT).and_then(Value::as_u64))?;
match d.str("then").as_str() {
"close" => Ok(Value::Null),
then => close_all(app, then),
GuardStep::Ask(uid) => match position(app, uid) {
// Closed meanwhile: there is nothing to ask about.
None => closing.guard.discarded(),
Some(_) => {
if let Err(e) = show_question(app, &closing.guard, uid) {
app.status(e);
return;
}
app.closing = Some(closing);
return;
}
},
GuardStep::Discard(uid) => {
if let Some(i) = position(app, uid)
&& let Err(e) = close_now(app, i, closing.front)
{
app.status(e);
return;
}
closing.guard.discarded()
}
GuardStep::Save(uid) => match position(app, uid) {
None => closing.guard.saved(),
Some(i) => match save_then_close(app, i, closing.front) {
Ok(true) => closing.guard.saved(),
// The replace-file question is open: the guard stays in `saving`.
Ok(false) => {
app.closing = Some(closing);
return;
}
Err(e) => {
app.status(e);
return;
}
},
},
// `GuardStep` is not exhaustive for this match only through its variants; a new one stops the operation.
#[allow(unreachable_patterns)]
_ => return,
};
}
}
/// One frame of the app, so it has its dialog host.
#[cfg(test)]
pub(crate) fn ready_for_test(app: &mut VectorcraftApp) -> egui::Context {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.ui(ui));
out.textures_delta.clear();
ctx
}
#[cfg(test)]
mod tests {
use super::*;
@@ -172,43 +290,23 @@ mod tests {
app.session.documents().len()
}
/// The index of the document the open question asks about.
fn pending(app: &VectorcraftApp) -> Option<usize> {
app.ui.dialog.as_ref().filter(|d| d.kind == KIND).and_then(|d| d.fields["index"].as_u64()).map(|i| i as usize)
let uid = *app.closing.as_ref()?.guard.current()?;
position(app, uid)
}
#[test]
fn clean_documents_close_at_once_keeping_views_aligned() {
let (mut app, _) = app();
for _ in 0..3 {
new_doc(&mut app, false);
}
assert!(!any_dirty(&app));
app.views[0].zoom = 2.0;
app.views[2].zoom = 3.0;
close(&mut app, 1).unwrap();
assert_eq!(docs(&app), 2);
assert_eq!(app.views.iter().map(|v| v.zoom).collect::<Vec<_>>(), vec![2.0, 3.0]);
assert_eq!(app.run("file.close", json!({})).unwrap(), Value::Null);
assert_eq!(docs(&app), 1);
assert!(app.ui.dialog.is_none());
fn question_open(app: &VectorcraftApp) -> bool {
app.dialogs().is_some_and(|d| d.with(|h| h.is_open::<UnsavedChangesDialog>()))
}
#[test]
fn closing_a_modified_document_asks_and_cancel_keeps_it() {
let (mut app, written) = app();
new_doc(&mut app, true);
new_doc(&mut app, false);
assert!(any_dirty(&app));
assert_eq!(app.run("file.close", json!({ "index": 0 })).unwrap(), json!({ "pending": KIND }));
assert_eq!((docs(&app), pending(&app), app.session.active_index()), (2, Some(0), Some(0)));
// Cancel (Esc / Cancel button / ui.dialog.cancel) closes nothing.
app.ui.dialog = None;
assert_eq!(docs(&app), 2);
// Save writes the file (Save As for an untitled document), then closes it.
app.run("file.close", json!({ "index": 0 })).unwrap();
confirm(&mut app).unwrap();
assert_eq!(*written.lock().unwrap(), vec!["out.vectorcraft".to_string()]);
assert_eq!((docs(&app), app.views.len()), (1, 1));
/// Answers the open question on the host as its button would, then runs the pump.
fn answer(app: &mut VectorcraftApp, ctx: &egui::Context, answer: CloseAnswer) {
app.dialogs().unwrap().with(|h| {
h.get_mut::<UnsavedChangesDialog>().unwrap().set_answer(answer);
assert!(h.confirm::<UnsavedChangesDialog>(ctx), "a question is open");
});
pump(app, ctx);
}
/// Three documents, A clean, B modified and C clean, with A in front: their uids.
@@ -225,15 +323,53 @@ mod tests {
app.session.active().map(|d| d.uid)
}
#[test]
fn clean_documents_close_at_once_keeping_views_aligned() {
let (mut app, _) = app();
for _ in 0..3 {
new_doc(&mut app, false);
}
let _ctx = ready_for_test(&mut app);
assert!(!any_dirty(&app));
app.views[0].zoom = 2.0;
app.views[2].zoom = 3.0;
close(&mut app, 1).unwrap();
assert_eq!(docs(&app), 2);
assert_eq!(app.views.iter().map(|v| v.zoom).collect::<Vec<_>>(), vec![2.0, 3.0]);
assert_eq!(app.run("file.close", json!({})).unwrap(), Value::Null);
assert_eq!(docs(&app), 1);
assert!(!question_open(&app));
}
#[test]
fn closing_a_modified_document_asks_and_cancel_keeps_it() {
let (mut app, written) = app();
new_doc(&mut app, true);
new_doc(&mut app, false);
let ctx = ready_for_test(&mut app);
assert!(any_dirty(&app));
assert_eq!(app.run("file.close", json!({ "index": 0 })).unwrap(), json!({ "pending": KIND }));
assert_eq!((docs(&app), pending(&app), app.session.active_index()), (2, Some(0), Some(0)));
assert!(question_open(&app));
answer(&mut app, &ctx, CloseAnswer::Cancel);
assert_eq!(docs(&app), 2);
assert!(app.closing.is_none() && !question_open(&app));
// Save writes the file (Save As for an untitled document), then closes it.
app.run("file.close", json!({ "index": 0 })).unwrap();
answer(&mut app, &ctx, CloseAnswer::Save);
assert_eq!(*written.lock().unwrap(), vec!["out.vectorcraft".to_string()]);
assert_eq!((docs(&app), app.views.len()), (1, 1));
}
#[test]
fn closing_a_modified_background_tab_keeps_the_front_document_after_dont_save() {
let (mut app, written) = app();
let [a, _, c] = front_and_modified_background_tab(&mut app);
let ctx = ready_for_test(&mut app);
assert_eq!(app.run("file.close", json!({ "index": 1 })).unwrap(), json!({ "pending": KIND }));
// The question shows the document it asks about.
assert_eq!((pending(&app), app.session.active_index()), (Some(1), Some(1)));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
confirm(&mut app).unwrap();
answer(&mut app, &ctx, CloseAnswer::DontSave);
let uids: Vec<u64> = app.session.documents().iter().map(|d| d.uid).collect();
assert_eq!((uids, front_uid(&app), app.views.len()), (vec![a, c], Some(a), 2));
assert!(written.lock().unwrap().is_empty());
@@ -243,8 +379,9 @@ mod tests {
fn closing_a_modified_background_tab_keeps_the_front_document_after_save() {
let (mut app, written) = app();
let [a, _, c] = front_and_modified_background_tab(&mut app);
let ctx = ready_for_test(&mut app);
close(&mut app, 1).unwrap();
confirm(&mut app).unwrap();
answer(&mut app, &ctx, CloseAnswer::Save);
assert_eq!(*written.lock().unwrap(), vec!["out.vectorcraft".to_string()]);
let uids: Vec<u64> = app.session.documents().iter().map(|d| d.uid).collect();
assert_eq!((uids, front_uid(&app)), (vec![a, c], Some(a)));
@@ -254,44 +391,27 @@ mod tests {
fn cancel_keeps_the_asked_background_tab_in_front() {
let (mut app, _) = app();
let [_, b, _] = front_and_modified_background_tab(&mut app);
let ctx = ready_for_test(&mut app);
close(&mut app, 1).unwrap();
app.ui.dialog = None;
answer(&mut app, &ctx, CloseAnswer::Cancel);
assert_eq!((docs(&app), front_uid(&app)), (3, Some(b)));
// A later close of the tab in front brings its neighbor to the front.
close(&mut app, 1).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
confirm(&mut app).unwrap();
answer(&mut app, &ctx, CloseAnswer::DontSave);
assert_eq!((docs(&app), app.session.active_index()), (2, Some(1)));
}
#[test]
fn closing_the_modified_front_document_brings_its_neighbor_to_the_front() {
let (mut app, _) = app();
new_doc(&mut app, false);
new_doc(&mut app, true);
new_doc(&mut app, false);
let c = app.session.documents()[2].uid;
app.session.set_active(1);
close(&mut app, 1).unwrap();
assert!(app.ui.dialog.as_ref().is_some_and(|d| !d.fields.contains_key(FRONT)));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
confirm(&mut app).unwrap();
assert_eq!((docs(&app), front_uid(&app)), (2, Some(c)));
}
/// The document in front before the question is remembered by its uid: when it closed while
/// the question was open, the closed document's neighbor comes to the front as before.
#[test]
fn a_front_document_closed_meanwhile_is_not_brought_back() {
let (mut app, _) = app();
let [a, _, c] = front_and_modified_background_tab(&mut app);
let ctx = ready_for_test(&mut app);
close(&mut app, 1).unwrap();
let d = app.ui.dialog.take().unwrap();
assert_eq!(d.fields.get(FRONT), Some(&json!(a)));
assert_eq!(app.closing.as_ref().and_then(|c| c.front), Some(a));
close(&mut app, 0).unwrap();
app.ui.dialog = Some(d);
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
confirm(&mut app).unwrap();
answer(&mut app, &ctx, CloseAnswer::DontSave);
assert_eq!((docs(&app), front_uid(&app)), (1, Some(c)));
}
@@ -299,8 +419,12 @@ mod tests {
fn close_all_does_not_remember_a_front_document() {
let (mut app, _) = app();
front_and_modified_background_tab(&mut app);
let ctx = ready_for_test(&mut app);
app.run("file.closeAll", json!({})).unwrap();
assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && !d.fields.contains_key(FRONT)));
assert!(question_open(&app) && app.closing.as_ref().is_some_and(|c| c.front.is_none()));
answer(&mut app, &ctx, CloseAnswer::DontSave);
assert_eq!((docs(&app), app.views.len()), (0, 0));
assert!(app.closing.is_none());
}
#[test]
@@ -308,10 +432,12 @@ mod tests {
let (mut app, _) = app();
app.services.pick_save = Some(Box::new(|_: &crate::FilePick| None));
new_doc(&mut app, true);
let ctx = ready_for_test(&mut app);
close(&mut app, 0).unwrap();
assert!(confirm(&mut app).is_err());
answer(&mut app, &ctx, CloseAnswer::Save);
assert_eq!(docs(&app), 1);
assert!(app.ui.dialog.is_none());
assert!(app.closing.is_none() && !question_open(&app));
assert!(!app.ui.status.is_empty(), "the failure is reported");
}
#[test]
@@ -320,22 +446,21 @@ mod tests {
new_doc(&mut app, false);
new_doc(&mut app, true);
new_doc(&mut app, true);
let ctx = ready_for_test(&mut app);
// Close All: asks about each modified document in turn, then closes the rest.
app.run("file.closeAll", json!({})).unwrap();
assert_eq!(pending(&app), Some(1));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
confirm(&mut app).unwrap();
answer(&mut app, &ctx, CloseAnswer::DontSave);
assert_eq!((docs(&app), pending(&app)), (2, Some(1)));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
confirm(&mut app).unwrap();
assert_eq!((docs(&app), app.views.len(), app.ui.dialog.is_none()), (0, 0, true));
answer(&mut app, &ctx, CloseAnswer::DontSave);
assert_eq!((docs(&app), app.views.len(), question_open(&app)), (0, 0, false));
assert!(written.lock().unwrap().is_empty());
// Quit: nothing modified quits at once; otherwise only after every answer.
new_doc(&mut app, true);
app.run("app.quit", json!({})).unwrap();
assert_ne!(app.ui.status, "quit");
assert_eq!(pending(&app), Some(0));
confirm(&mut app).unwrap();
answer(&mut app, &ctx, CloseAnswer::Save);
assert_eq!(app.ui.status, "quit");
app.ui.status.clear();
app.run("app.quit", json!({})).unwrap();
@@ -346,16 +471,16 @@ mod tests {
fn the_control_channels_quit_says_when_it_asks_first() {
// #830: it answered null at once, before the question.
let (mut app, _) = app();
let ctx = egui::Context::default();
new_doc(&mut app, true);
let ctx = ready_for_test(&mut app);
let quit = |app: &mut VectorcraftApp| {
let (req, _rx) = crate::control::ControlRequest::new("app.quit", json!({}));
let crate::control::Outcome::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("not done") };
r
};
new_doc(&mut app, true);
assert_eq!(quit(&mut app), json!({"ok": true, "result": {"pending": KIND}}));
assert_eq!((pending(&app), app.ui.status.as_str()), (Some(0), ""));
app.ui.dialog = None;
app.closing = None;
app.run("file.save", json!({"path": "/docs/saved.vectorcraft"})).unwrap();
assert_eq!(quit(&mut app), json!({"ok": true, "result": null}));
assert_eq!(app.ui.status, "quit");
+100 -277
View File
@@ -1,13 +1,16 @@
//! Software updates, background check at startup, and startup prompt modal.
//! Software updates: the check at startup, the startup prompt and the check-result dialog, both
//! on the dialog host.
use serde_json::Value;
use crate::VectorcraftApp;
#[cfg(target_arch = "wasm32")]
use craft_ui::dialog::{Alert, HostedAlert};
#[cfg(not(target_arch = "wasm32"))]
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog, UpdatePromptDialog};
#[cfg(not(target_arch = "wasm32"))]
use craft_update::updater::{Action, Status, Updater};
#[cfg(not(target_arch = "wasm32"))]
use craft_update::{CheckResultDialog, CheckResultResponse};
#[cfg_attr(target_arch = "wasm32", derive(Default))]
pub(crate) struct Runtime {
@@ -16,31 +19,15 @@ pub(crate) struct Runtime {
/// The desktop app turns the check at start on; tests and the web build leave it off.
#[cfg(not(target_arch = "wasm32"))]
startup_check: bool,
/// Whether a modal update dialog was open in the last pass.
#[cfg(not(target_arch = "wasm32"))]
check_requested: bool,
/// The context of the last frame, to wake the UI when a check is queued from a menu callback.
#[cfg(not(target_arch = "wasm32"))]
repaint: Option<egui::Context>,
/// Whether an update dialog held the input in the last frame.
#[cfg(not(target_arch = "wasm32"))]
was_blocking: bool,
/// The web build has no updater; its window only says so.
#[cfg(target_arch = "wasm32")]
pub(crate) manual_window_open: bool,
#[cfg(target_arch = "wasm32")]
pub(crate) status_message: Option<String>,
was_modal: bool,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for Runtime {
fn default() -> Self {
Self {
updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")),
startup_check: false,
check_requested: false,
repaint: None,
was_blocking: false,
}
Self { updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")), startup_check: false, was_modal: false }
}
}
@@ -60,138 +47,121 @@ impl VectorcraftApp {
}
}
pub(crate) fn check(app: &mut VectorcraftApp) -> Result<Value, String> {
#[cfg(not(target_arch = "wasm32"))]
{
app.updates_rt.check_requested = true;
if let Some(ctx) = &app.updates_rt.repaint {
ctx.request_repaint();
}
Ok(Value::Null)
}
#[cfg(target_arch = "wasm32")]
{
app.updates_rt.manual_window_open = true;
app.updates_rt.status_message = Some("Update check is not supported in the web browser.".into());
Ok(Value::Null)
}
/// The result dialog of a check; its status comes from [`pump`].
#[cfg(not(target_arch = "wasm32"))]
fn check_dialog() -> UpdateCheckDialog {
UpdateCheckDialog::new(env!("CARGO_PKG_VERSION"))
}
pub(crate) fn check(app: &mut VectorcraftApp) -> Result<Value, String> {
// PLAN: assumed `VectorcraftApp::dialogs() -> Option<handle>` whose `with(|host: &mut DialogHost| ..)` runs on the host (wg.S1).
let dialogs = app.dialogs().ok_or("no window")?;
#[cfg(not(target_arch = "wasm32"))]
{
// An open result dialog shows the new status itself.
dialogs.with(|h| {
let _ = h.open_unless_open(check_dialog());
});
app.updates_rt.updater.check_now();
}
#[cfg(target_arch = "wasm32")]
dialogs.with(|h| {
h.open(HostedAlert::new(Alert::new(
tl!("VectorCraft Updates").to_string(),
tl!("Update check is not supported in the web browser.").to_string(),
)));
});
Ok(Value::Null)
}
/// Before the shell pass: the updater works, and puts its startup prompt on the host, which must
/// happen before `DialogHost::run`.
pub(crate) fn tick(app: &mut VectorcraftApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
{
let rt = &mut app.updates_rt;
rt.repaint = Some(ctx.clone());
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now(ctx);
} else if rt.startup_check {
rt.updater.check_at_start(ctx);
if rt.startup_check {
rt.updater.check_at_start();
}
rt.updater.tick(ctx);
// An installation, and the close for a ready update, wait for unsaved and running work.
let safe = safe_to_close(app);
let Some(dialogs) = app.dialogs() else { return };
match dialogs.with(|h| app.updates_rt.updater.run(h, safe)) {
Action::OpenUrl(url) => app.open_url(&url),
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
_ => {}
}
}
#[cfg(target_arch = "wasm32")]
let _ = (app, ctx);
}
/// Whether the check result window shows: for every status but idle (a requested check, and the
/// first start after an update, which reports that it installed or why it failed), and never
/// over the startup prompt.
#[cfg(not(target_arch = "wasm32"))]
fn result_window_shows(status: &Status, prompt_open: bool) -> bool {
!prompt_open && !matches!(status, Status::Idle)
}
/// Whether the update prompt or the modal result window is open: keys, tool keys and clipboard
/// events then stay out of the documents behind it, and the app's other windows take no input.
pub(crate) fn blocks_input(app: &VectorcraftApp) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
let updater = &app.updates_rt.updater;
holds_keyboard(updater.status(), updater.prompt_open())
}
#[cfg(target_arch = "wasm32")]
{
let _ = app;
false
}
}
/// The prompt is modal, and so is the result window for every status but [`Status::Updated`], a
/// notice that leaves the app usable behind it.
#[cfg(not(target_arch = "wasm32"))]
fn holds_keyboard(status: &Status, prompt_open: bool) -> bool {
prompt_open || !matches!(status, Status::Idle | Status::Updated(_))
}
/// Whether an update may install and close the app: no document holds unsaved work, no save,
/// export, file opening, plug-in filter or Image Trace is running, no action is playing, no dialog
/// or file dialog is open, and no tool is in the middle of a drag or an edit it computes on
/// another thread.
/// export, file opening, plug-in filter or Image Trace is running, no action is playing, no
/// dialog (the update's own aside) or file dialog is open, and no tool is in the middle of a drag
/// or an edit it computes on another thread.
#[cfg(not(target_arch = "wasm32"))]
fn safe_to_close(app: &VectorcraftApp) -> bool {
let session = &app.session;
// The update's own dialogs would hold the install back forever.
let others_open = app.dialogs().is_some_and(|d| {
d.with(|h| h.open_dialogs().len() > usize::from(h.is_open::<UpdatePromptDialog>()) + usize::from(h.is_open::<UpdateCheckDialog>()))
});
!crate::unsaved::any_dirty(app)
&& app.background.jobs.is_empty()
&& !crate::opening::long_operation_busy(app)
&& app.ui.action_playing.is_none()
&& app.ui.dialog.is_none()
&& !others_open
&& !app.file_dialog_open()
&& !session.in_interaction()
&& !session.tool_busy()
&& !session.tool_editing()
}
pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
/// After the shell pass: feeds the check dialog the updater's status and opens it for every
/// status but idle (a requested check, and the first start after an update, which reports that it
/// installed or why it failed), never over the startup prompt; carries out what it answered.
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
{
// An installation, and the close for a ready update, wait for unsaved and running work.
let safe = safe_to_close(app);
match app.updates_rt.updater.show_if(ctx, safe) {
Action::OpenUrl(url) => app.open_url(&url),
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
Action::None => {}
}
// An available update goes to the prompt above, which replaces the result dialog.
let rt = &mut app.updates_rt;
if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) {
match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) {
CheckResultResponse::None => {}
let Some(dialogs) = app.dialogs() else { return };
let updater = &mut app.updates_rt.updater;
let status = updater.status().clone();
let prompt_open = updater.prompt_open();
let (answered, modal) = dialogs.with(|h| {
let answered = h.take::<UpdateCheckDialog>();
if answered.is_none() {
if let Some(dialog) = h.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status.clone());
} else if !prompt_open && status != Status::Idle {
let mut dialog = check_dialog();
dialog.set_status(status.clone());
h.open(dialog);
}
}
// The prompt is modal, and so is the result dialog for every status but `Updated`, a
// notice that leaves the app usable behind it.
(answered, prompt_open || (h.is_open::<UpdateCheckDialog>() && !matches!(status, Status::Updated(_))))
});
if let Some(result) = answered {
match result.ok() {
Some(CheckChoice::CheckAgain | CheckChoice::CheckNow) => updater.check_now(),
Some(CheckChoice::RestartToUpdate) => updater.restart_to_update(),
// Closing the dialog dismisses the outcome it showed.
CheckResultResponse::Close => rt.updater.dismiss_status(),
CheckResultResponse::CheckAgain => rt.updater.check_now(ctx),
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
Some(CheckChoice::Close) | None => updater.dismiss_status(),
// The app never offers a release itself, so Update and Download do not arrive.
Some(_) => {}
}
}
// A check at startup can open the prompt while a floating document's window covers it.
let blocking = blocks_input(app);
if blocking && !app.updates_rt.was_blocking {
if modal && !app.updates_rt.was_modal {
crate::doc_windows::focus_main_window(app, ctx);
}
app.updates_rt.was_blocking = blocking;
app.updates_rt.was_modal = modal;
}
#[cfg(target_arch = "wasm32")]
if app.updates_rt.manual_window_open {
let mut open = true;
egui::Window::new(tl!("VectorCraft Updates"))
.open(&mut open)
.collapsible(false)
.resizable(false)
.pivot(egui::Align2::CENTER_CENTER)
.default_pos(ctx.content_rect().center())
.show(ctx, |ui| {
if let Some(msg) = &app.updates_rt.status_message {
ui.label(msg);
}
ui.add_space(8.0);
if ui.button(tl!("OK")).clicked() {
app.updates_rt.manual_window_open = false;
}
});
if !open {
app.updates_rt.manual_window_open = false;
}
}
let _ = (app, ctx);
}
/// Opens the update prompt for a test in another module.
@@ -200,14 +170,16 @@ pub(crate) fn open_prompt_for_test(app: &mut VectorcraftApp) {
tests::offer(app);
}
/// Opens the result window of a running check for a test in another module.
/// Opens the result dialog of a running check for a test in another module.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn open_result_window_for_test(app: &mut VectorcraftApp, ctx: &egui::Context) {
app.updates_rt.updater = tests::isolated_updater(env!("CARGO_PKG_VERSION"), "result");
app.updates_rt.updater.check_now(ctx);
// Keeps `ctx` for the updater's threads.
app.updates_rt.updater.tick(ctx);
app.updates_rt.updater.check_now();
}
/// Closes the update prompt and the result window for a test in another module.
/// Closes the update prompt and the result dialog for a test in another module.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn close_dialogs_for_test(app: &mut VectorcraftApp) {
app.updates_rt.updater = tests::isolated_updater(env!("CARGO_PKG_VERSION"), "closed");
@@ -292,165 +264,13 @@ mod tests {
app
}
#[cfg(not(target_arch = "wasm32"))]
fn press(key: egui::Key) -> egui::Event {
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }
}
/// One frame in the app's order: the shortcuts read the input, then the update dialogs draw.
#[cfg(not(target_arch = "wasm32"))]
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) {
let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| {
crate::shortcuts::handle(app, ui.ctx());
show(app, ui.ctx());
});
output.textures_delta.clear();
}
/// A Copy, the Pen tool's key and Delete, in one frame each: none of them may act.
#[cfg(not(target_arch = "wasm32"))]
fn assert_keys_do_nothing(app: &mut VectorcraftApp, ctx: &egui::Context) {
let tool = app.session.tool_id();
let mut reached = Vec::new();
frame(app, ctx, vec![egui::Event::Copy]);
if !app.session.clipboard.is_empty() {
reached.push("Copy");
}
let tool_key =
egui::Event::Key { key: egui::Key::P, physical_key: Some(egui::Key::P), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
frame(app, ctx, vec![tool_key, egui::Event::Text("p".into())]);
if app.session.tool_id() != tool {
reached.push("the tool key");
}
frame(app, ctx, vec![press(egui::Key::Delete)]);
if app.session.doc().unwrap().selection.is_empty() {
reached.push("Delete");
}
assert_eq!(reached, Vec::<&str>::new(), "these reached the document");
assert!(!crate::unsaved::any_dirty(app), "a key edited the document");
}
#[test]
fn default_runtime_is_idle() {
let rt = Runtime::default();
#[cfg(target_arch = "wasm32")]
assert!(!rt.manual_window_open);
#[cfg(not(target_arch = "wasm32"))]
{
assert!(!rt.startup_check);
assert!(!rt.updater.prompt_open());
assert_eq!(rt.updater.status(), &Status::Idle);
}
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn result_window_shows_every_status_but_idle() {
let shown = [
Status::Checking,
Status::UpToDate,
Status::Failed("offline".into()),
Status::Installing,
Status::Ready,
Status::Managed,
Status::Updated("99.0.0".into()),
Status::InstallFailed("locked".into()),
];
for status in &shown {
assert!(result_window_shows(status, false), "{status:?} shows");
assert!(!result_window_shows(status, true), "{status:?} waits for the prompt");
}
assert!(!result_window_shows(&Status::Idle, false));
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn startup_prompt_shows_and_closes() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let ctx = egui::Context::default();
app.updates_rt.updater = isolated_updater(env!("CARGO_PKG_VERSION"), "startup");
offer_and_wait(&mut app.updates_rt.updater, release_99());
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
show(&mut app, ui.ctx());
});
output.textures_delta.clear();
assert!(app.updates_rt.updater.prompt_open());
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn the_prompt_and_the_result_window_hold_the_keyboard_but_the_updated_notice_does_not() {
for status in [
Status::Checking,
Status::UpToDate,
Status::Failed("offline".into()),
Status::Installing,
Status::Ready,
Status::Managed,
Status::InstallFailed("locked".into()),
] {
assert!(holds_keyboard(&status, false), "{status:?}");
}
assert!(!holds_keyboard(&Status::Idle, false));
assert!(!holds_keyboard(&Status::Updated("99.0.0".into()), false));
assert!(holds_keyboard(&Status::Idle, true), "the prompt");
}
/// The update prompt, drawn: keys stop at it, Escape closes it, and the next key acts again.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn keys_do_not_reach_the_document_behind_the_update_prompt() {
let mut app = app_with_saved_object();
let ctx = egui::Context::default();
offer(&mut app);
frame(&mut app, &ctx, vec![]);
assert_keys_do_nothing(&mut app, &ctx);
assert!(app.updates_rt.updater.prompt_open());
frame(&mut app, &ctx, vec![press(egui::Key::Escape)]);
assert!(!app.updates_rt.updater.prompt_open(), "Escape closes the prompt");
assert!(!app.session.doc().unwrap().selection.is_empty(), "Escape stops at the prompt");
frame(&mut app, &ctx, vec![press(egui::Key::Delete)]);
assert!(crate::unsaved::any_dirty(&app), "Delete acts once the prompt has closed");
}
/// The result window of a check that is still running, drawn: keys stop at it too.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn keys_do_not_reach_the_document_behind_the_check_result_window() {
let mut app = app_with_saved_object();
let ctx = egui::Context::default();
app.updates_rt.updater = isolated_updater("0.0.1", "checking");
app.updates_rt.updater.check_now(&ctx);
assert_eq!(app.updates_rt.updater.status(), &Status::Checking);
frame(&mut app, &ctx, vec![]);
assert_keys_do_nothing(&mut app, &ctx);
}
/// The notice of a finished update, drawn: the keys act behind it.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn keys_reach_the_document_behind_the_updated_notice() {
let mut app = app_with_saved_object();
let ctx = egui::Context::default();
let root = update_root("updated");
let records = craft_update::Paths::under(&root).data;
std::fs::create_dir_all(&records).unwrap();
std::fs::write(records.join("self-update-done.txt"), "v99.0.0").unwrap();
app.updates_rt.updater = isolated_updater("99.0.0", "updated");
app.updates_rt.updater.check_at_start(&ctx);
assert_eq!(app.updates_rt.updater.status(), &Status::Updated("99.0.0".into()));
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![press(egui::Key::Delete)]);
let _ = std::fs::remove_dir_all(&root);
assert!(crate::unsaved::any_dirty(&app), "Delete acts behind the notice");
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn unsaved_changes_dialogs_and_running_work_hold_an_update_back() {
use craft_ui::dialog::{Alert, HostedAlert};
let mut app = app_with_saved_object();
let ctx = crate::unsaved::ready_for_test(&mut app);
assert!(safe_to_close(&app));
app.run("shape.rectangle", json!({"x": 70, "y": 10, "width": 50, "height": 50})).unwrap();
@@ -458,9 +278,12 @@ mod tests {
app.run("file.save", json!({"path": "/docs/saved.vectorcraft"})).unwrap();
assert!(safe_to_close(&app));
app.ui.dialog = Some(crate::state::Dialog::new("about", json!({})));
app.dialogs().unwrap().with(|h| {
h.open(HostedAlert::new(Alert::new("About", "A dialog")));
});
assert!(!safe_to_close(&app), "a dialog");
app.ui.dialog = None;
app.dialogs().unwrap().with(|h| h.cancel::<HostedAlert>(&ctx));
assert!(safe_to_close(&app));
let (shown, _) = crate::tests_picks::off_the_ui_thread(&mut app.services);
// The command asks again with the answer: until then it reports that it has none.
+96 -80
View File
@@ -1,20 +1,22 @@
//! Safe Mode in the app: the choice after a launch that stopped while a plug-in was loading
//! (Disable and Continue, Start Normally, Start in Safe Mode), Help › Safe Mode with Enable on
//! Re-launch, and Safe Mode in the window title. Safe Mode and installed plug-ins are
//! process-wide, so these tests run in their own test binary, one at a time.
//! process-wide, so these tests run in their own test binary, one at a time. The dialogs are
//! answered through the control channel, the way agents do.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde_json::json;
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_plugins::safe_mode::{self, Item};
use vectorcraft_plugins::{registry, wat as tpl};
use vectorcraft_ui_egui::control::{ControlRequest, Outcome, handle};
use vectorcraft_ui_egui::dialogs::safe_mode as ui;
use vectorcraft_ui_egui::panels::appearance;
use vectorcraft_ui_egui::{Services, VectorcraftApp, chrome, dialogs, theme};
use vectorcraft_ui_egui::{Services, VectorcraftApp, chrome, theme};
static LOCK: Mutex<()> = Mutex::new(());
@@ -91,14 +93,33 @@ fn stopped_while_loading_x(launch: &Path, dir: &Path) {
std::fs::write(launch.join("launch-1-dead.json"), item.to_string()).unwrap();
}
/// One headless frame of the dialog layer.
fn frame(app: &mut VectorcraftApp) {
/// A window for one test, with the app's fonts.
fn window() -> egui::Context {
let ctx = egui::Context::default();
theme::install_fonts(&ctx);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs::show(app, ui.ctx()));
ctx
}
/// One headless frame of the app: its dialogs open and their answers are read.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.ui(ui));
out.textures_delta.clear();
}
/// A control request, then one frame; the reply says whether it was done.
fn control(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value {
let (req, _rx) = ControlRequest::new(method, params);
let Outcome::Done(reply) = handle(app, ctx, &req) else { panic!("{method}: not done") };
frame(app, ctx);
reply
}
/// Answers the top dialog with its default button.
fn confirm(app: &mut VectorcraftApp, ctx: &egui::Context) {
let reply = control(app, ctx, "ui.dialog.confirm", json!({}));
assert_eq!(reply["ok"], true, "{reply}");
}
fn done(launch: &Path) {
ui::end_launch();
safe_mode::set_active(None);
@@ -107,10 +128,6 @@ fn done(launch: &Path) {
let _ = std::fs::remove_dir_all(launch);
}
fn kind(app: &VectorcraftApp) -> Option<&str> {
app.ui.dialog.as_ref().map(|d| d.kind.as_str())
}
#[test]
fn disable_and_continue_loads_every_plug_in_but_the_one_that_was_loading() {
let _f = fresh();
@@ -118,20 +135,22 @@ fn disable_and_continue_loads_every_plug_in_but_the_one_that_was_loading() {
let launch_dir = dir.join("Launch");
stopped_while_loading_x(&launch_dir, &dir);
let mut app = launch(&dir, &launch_dir, false);
assert_eq!(kind(&app), Some(ui::STOPPED));
let ctx = window();
frame(&mut app, &ctx);
assert!(ui::choosing(&app));
assert!(safe_mode::active() && registry::list().is_empty(), "nothing loads until the user chooses");
assert!(chrome::window_title(&app).ends_with("(Safe Mode)"));
frame(&mut app);
dialogs::confirm(&mut app).unwrap();
assert!(!safe_mode::active() && kind(&app).is_none());
confirm(&mut app, &ctx);
assert!(!safe_mode::active() && !ui::choosing(&app));
assert!(registry::get("test.ui.x").is_none() && registry::get("test.ui.y").is_some(), "only the one that was loading is off");
assert_eq!(chrome::window_title(&app), "VectorCraft");
assert!(dir.join("disabled.json").is_file(), "kept off at later launches");
ui::end_launch();
// The next launch, which quit normally before: nothing is asked, and x stays off.
let app = launch(&dir, &launch_dir, false);
assert!(kind(&app).is_none() && !safe_mode::active());
let mut app = launch(&dir, &launch_dir, false);
frame(&mut app, &ctx);
assert!(!ui::choosing(&app) && !safe_mode::active());
assert!(registry::get("test.ui.x").is_none() && registry::get("test.ui.y").is_some());
done(&launch_dir);
let _ = std::fs::remove_dir_all(&dir);
@@ -144,8 +163,11 @@ fn start_normally_loads_everything_and_start_in_safe_mode_loads_nothing() {
let launch_dir = dir.join("Launch");
stopped_while_loading_x(&launch_dir, &dir);
let mut app = launch(&dir, &launch_dir, false);
app.ui.dialog.as_mut().unwrap().fields.insert("normal".into(), json!(true));
dialogs::confirm(&mut app).unwrap();
let ctx = window();
frame(&mut app, &ctx);
let reply = control(&mut app, &ctx, "ui.dialog.set", json!({"field": "choice", "value": "alternate"}));
assert_eq!(reply["ok"], true, "{reply}");
confirm(&mut app, &ctx);
assert!(!ui::choosing(&app) && !ui::staying_on(&app), "Start Normally ends Safe Mode");
assert!(registry::get("test.ui.x").is_some() && registry::get("test.ui.y").is_some());
assert!(safe_mode::disabled().is_empty() && !dir.join("disabled.json").exists(), "Start Normally changes no setting");
@@ -153,16 +175,19 @@ fn start_normally_loads_everything_and_start_in_safe_mode_loads_nothing() {
stopped_while_loading_x(&launch_dir, &dir);
let mut app = launch(&dir, &launch_dir, false);
frame(&mut app, &ctx);
assert!(ui::choosing(&app) && !ui::staying_on(&app), "Safe Mode until the user chooses");
dialogs::cancel(&mut app);
let reply = control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
assert_eq!(reply["ok"], true, "{reply}");
assert!(!ui::choosing(&app) && ui::staying_on(&app), "Safe Mode for the rest of the launch");
assert!(safe_mode::active() && registry::list().is_empty(), "Start in Safe Mode");
assert_eq!(safe_mode::source(), Some(safe_mode::Source::Startup));
assert!(safe_mode::disabled().is_empty(), "nothing turned off");
ui::end_launch();
safe_mode::set_active(None);
let app = launch(&dir, &launch_dir, false);
assert_eq!(kind(&app), Some(ui::STOPPED), "Start in Safe Mode leaves the choice to the next launch");
let mut app = launch(&dir, &launch_dir, false);
frame(&mut app, &ctx);
assert!(ui::choosing(&app), "Start in Safe Mode leaves the choice to the next launch");
done(&launch_dir);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -178,50 +203,24 @@ fn a_disabled_list_that_cannot_be_saved_says_so() {
std::fs::write(dir.join("disabled.json"), later).unwrap();
let unsaved = "Couldn't save the disabled plug-ins for the next launch";
let mut app = launch(&dir, &launch_dir, false);
dialogs::confirm(&mut app).unwrap();
let ctx = window();
frame(&mut app, &ctx);
confirm(&mut app, &ctx);
assert_eq!(app.ui.status, unsaved, "Disable and Continue");
assert!(safe_mode::previous().is_some(), "the next launch asks again");
assert!(registry::get("test.ui.x").is_none(), "this launch still skips it");
app.ui.status.clear();
app.run("help.safeMode", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields["items"][0]["enable"] = json!(true);
dialogs::confirm(&mut app).unwrap();
frame(&mut app, &ctx);
let reply = control(&mut app, &ctx, "ui.dialog.set", json!({"field": "enable-0", "value": true}));
assert_eq!(reply["ok"], true, "{reply}");
confirm(&mut app, &ctx);
assert_eq!(app.ui.status, unsaved, "Enable on Re-launch");
assert_eq!(std::fs::read_to_string(dir.join("disabled.json")).unwrap(), later);
done(&launch_dir);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_safe_mode_label_leaves_the_menus_their_room() {
let _f = fresh();
safe_mode::set_active(Some(safe_mode::Source::Flag));
let menu_names = ["File", "Edit", "Object", "Type", "Select", "Effect", "View", "Window", "Help"];
for width in [560.0, 720.0, 1280.0] {
let ctx = egui::Context::default();
theme::install_fonts(&ctx);
let mut app = VectorcraftApp::new(Session::new(), Services::default());
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 400.0))), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| chrome::app_bar(&mut app, ui));
out.textures_delta.clear();
let texts: Vec<_> = out
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Text(t) => Some((t.galley.job.text.clone(), t.visual_bounding_rect())),
_ => None,
})
.collect();
let menus: Vec<egui::Rect> = texts.iter().filter(|(t, _)| menu_names.contains(&t.as_str())).map(|(_, r)| *r).collect();
assert!(!menus.is_empty(), "{width}: the menus are drawn: {texts:?}");
let (start, end) = menus.iter().fold((f32::MAX, f32::MIN), |(a, b), r| (a.min(r.left()), b.max(r.right())));
assert!(texts.iter().any(|(t, _)| t == "Safe Mode"), "{width}: the label is drawn");
for (t, r) in texts.iter().filter(|(t, _)| !menu_names.contains(&t.as_str())) {
assert!(r.left() >= end || r.right() <= start, "{width}: {t:?} at {r:?} overlaps the menus from {start} to {end}");
}
}
}
#[test]
fn a_dialog_that_replaces_the_choice_leaves_it_waiting() {
let _f = fresh();
@@ -229,14 +228,16 @@ fn a_dialog_that_replaces_the_choice_leaves_it_waiting() {
let launch_dir = dir.join("Launch");
stopped_while_loading_x(&launch_dir, &dir);
let mut app = launch(&dir, &launch_dir, false);
let ctx = window();
// Help › Safe Mode (or any other dialog) takes the choice's place before it is answered.
frame(&mut app, &ctx);
app.run("help.safeMode", json!({})).unwrap();
assert_eq!(kind(&app), Some(ui::KIND));
frame(&mut app, &ctx);
assert!(ui::choosing(&app) && !ui::staying_on(&app), "still waiting for the choice");
dialogs::cancel(&mut app);
assert_eq!(kind(&app), Some(ui::STOPPED), "the choice opens again once no dialog is open");
assert!(ui::choosing(&app) && registry::list().is_empty());
dialogs::confirm(&mut app).unwrap();
let reply = control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
assert_eq!(reply["ok"], true, "{reply}");
assert!(ui::choosing(&app) && registry::list().is_empty(), "the choice is open again once Help is closed");
confirm(&mut app, &ctx);
assert!(!ui::choosing(&app) && !safe_mode::active());
assert!(registry::get("test.ui.x").is_none() && registry::get("test.ui.y").is_some());
done(&launch_dir);
@@ -248,8 +249,12 @@ fn the_safe_mode_flag_asks_nothing_and_loads_nothing() {
let _f = fresh();
let dir = store_with_two("flag");
let launch_dir = dir.join("Launch");
let app = launch(&dir, &launch_dir, true);
assert!(kind(&app).is_none() && ui::staying_on(&app));
let mut app = launch(&dir, &launch_dir, true);
let ctx = window();
frame(&mut app, &ctx);
assert!(!ui::choosing(&app) && ui::staying_on(&app));
let reply = control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
assert_eq!(reply["ok"], false, "no dialog is open: {reply}");
assert_eq!((safe_mode::source(), registry::list().len()), (Some(safe_mode::Source::Flag), 0));
assert_eq!(app.ui.status, vectorcraft_plugins::Error::SafeMode.to_string());
assert!(chrome::window_title(&app).ends_with("(Safe Mode)"));
@@ -273,23 +278,27 @@ fn a_safe_mode_flag_launch_leaves_the_stopped_plug_in_to_the_next_launch() {
let dir = store_with_two("flag-pending");
let launch_dir = dir.join("Launch");
stopped_while_loading_x(&launch_dir, &dir);
let app = launch(&dir, &launch_dir, true);
assert!(kind(&app).is_none() && registry::list().is_empty(), "--safe-mode asks nothing");
let mut app = launch(&dir, &launch_dir, true);
let ctx = window();
frame(&mut app, &ctx);
assert!(!ui::choosing(&app) && registry::list().is_empty(), "--safe-mode asks nothing");
assert!(safe_mode::previous().is_some(), "the plug-in is still pending");
ui::end_launch();
safe_mode::set_active(None);
// The next launch, without the flag, asks about it before anything loads.
let mut app = launch(&dir, &launch_dir, false);
assert_eq!(kind(&app), Some(ui::STOPPED));
frame(&mut app, &ctx);
assert!(ui::choosing(&app));
assert!(registry::list().is_empty());
dialogs::confirm(&mut app).unwrap();
confirm(&mut app, &ctx);
assert!(registry::get("test.ui.x").is_none() && registry::get("test.ui.y").is_some());
ui::end_launch();
// A launch after the choice asks nothing.
let app = launch(&dir, &launch_dir, false);
assert!(kind(&app).is_none() && !safe_mode::active());
let mut app = launch(&dir, &launch_dir, false);
frame(&mut app, &ctx);
assert!(!ui::choosing(&app) && !safe_mode::active());
done(&launch_dir);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -305,18 +314,22 @@ fn help_safe_mode_enables_a_plug_in_for_the_next_launch_only() {
assert!(safe_mode::set_enabled(&x, false));
assert!(s.store_disabled_plugins());
let mut app = launch(&dir, &launch_dir, false);
let ctx = window();
frame(&mut app, &ctx);
assert!(registry::get("test.ui.x").is_none());
// The dialog shows a name through this, so a name can't reorder its text.
assert_eq!(safe_mode::display_name(&x.label()), "Xgnp");
app.run("help.safeMode", json!({})).unwrap();
assert_eq!(kind(&app), Some(ui::KIND));
let d = app.ui.dialog.as_mut().unwrap();
assert_eq!(d.fields["items"][0]["label"], "Xgnp", "a name can't reorder the dialog's text");
frame(&mut app);
frame(&mut app, &ctx);
// Close keeps everything as it was.
dialogs::cancel(&mut app);
let reply = control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(safe_mode::disabled(), std::slice::from_ref(&x));
app.run("help.safeMode", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields["items"][0]["enable"] = json!(true);
dialogs::confirm(&mut app).unwrap();
frame(&mut app, &ctx);
let reply = control(&mut app, &ctx, "ui.dialog.set", json!({"field": "enable-0", "value": true}));
assert_eq!(reply["ok"], true, "{reply}");
confirm(&mut app, &ctx);
assert!(safe_mode::disabled().is_empty());
assert!(registry::get("test.ui.x").is_none(), "not loaded during this launch");
ui::end_launch();
@@ -332,6 +345,8 @@ fn help_safe_mode_lists_a_plug_in_found_under_several_files_once() {
let dir = store_with_two("help-files");
let launch_dir = dir.join("Launch");
let mut app = launch(&dir, &launch_dir, false);
let ctx = window();
frame(&mut app, &ctx);
let x = |file: &str| Item { id: Some("test.ui.x".into()), file: Some(file.into()), name: Some("X".into()) };
let y = Item { id: Some("test.ui.y".into()), file: None, name: Some("Y".into()) };
let z = Item { id: None, file: Some("z.wasm".into()), name: None };
@@ -345,12 +360,13 @@ fn help_safe_mode_lists_a_plug_in_found_under_several_files_once() {
assert!(app.session.store_disabled_plugins());
assert_eq!(safe_mode::disabled().len(), 4, "an entry for each of x's files");
app.run("help.safeMode", json!({})).unwrap();
let items = app.ui.dialog.as_ref().unwrap().fields["items"].as_array().unwrap().clone();
let labels: Vec<&str> = items.iter().map(|v| v["label"].as_str().unwrap()).collect();
assert_eq!(labels, ["X", "Y", "z.wasm"], "one row for each plug-in");
frame(&mut app);
app.ui.dialog.as_mut().unwrap().fields["items"][0]["enable"] = json!(true);
dialogs::confirm(&mut app).unwrap();
frame(&mut app, &ctx);
// One row for each plug-in: x, y and z, not an entry for each of x's files.
let row = |app: &mut VectorcraftApp, k: usize| control(app, &ctx, "ui.dialog.set", json!({"field": format!("enable-{k}"), "value": false}))["ok"];
assert_eq!((row(&mut app, 2), row(&mut app, 3)), (json!(true), json!(false)), "three rows");
let reply = control(&mut app, &ctx, "ui.dialog.set", json!({"field": "enable-0", "value": true}));
assert_eq!(reply["ok"], true, "{reply}");
confirm(&mut app, &ctx);
assert_eq!(safe_mode::disabled(), [y, z], "every entry with x's id is turned on");
done(&launch_dir);
let _ = std::fs::remove_dir_all(&dir);