From 1a219dbc1551687c5ce04dc50bc6456cb4b9936f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 23:25:04 +0700 Subject: [PATCH] menus-w21: net change of 2 commits - menus-w21: written from its sheet - menus-w21: repair 1 --- crates/ui-egui/src/scripts_menu.rs | 316 +++++++++------------- crates/ui-egui/src/tests/scripts_menu.rs | 317 +++++++---------------- 2 files changed, 218 insertions(+), 415 deletions(-) diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index 1afaf11d34..c892d45f6b 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -2,29 +2,32 @@ //! ([`vectorcraft_engine::Session::attach_scripts_dir`]), each `.js` or `.jsx` file by its name //! without the extension and each subfolder as a submenu, above Check Script… and Other Script…. //! -//! The folder is read on another thread ([`vectorcraft_engine::script::folder::list`]: names only, -//! within its limits), one read at a time: when the app starts, each time its window becomes the -//! active one, and each time the File menu of the window's menu bar opens ([`refresh`]). The menus show the last finished -//! listing ([`items`]), so a script added to the folder is listed without a restart. +//! The folder is read by a job of the host's queue ([`vectorcraft_engine::script::folder::list`]: +//! names only, within its limits), one read at a time: when the app starts, each time its window +//! becomes the active one, and each time a menu of the window's menu bar opens ([`refresh`]). The +//! menus show the last finished listing ([`items`]), so a script added to the folder is listed +//! without a restart. //! //! Until the first read ends the menu shows [`LOADING`], and [`SLOW`] once that read has taken -//! [`SLOW_SECS`]; a first read that cannot start or ends without a listing shows [`UNREADABLE`], -//! and the next read tries again. +//! [`SLOW_SECS`]. //! //! `ui.runInstalledScript {path}` runs a listed script (`script.run`) without the warning Other //! Script… shows: the file was put in the folder to be run from the menu. The path is one a //! listing gave; a file that is no longer a plain script under the folder is not run. -use std::path::Path; -use std::sync::mpsc::{Receiver, TryRecvError}; +// PLAN: needs craft-menu, craft-host and craft-platform in crates/ui-egui/Cargo.toml (shell owner). +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; +use craft::host::queue::{JobQueue, Priority, QueueOptions}; +use craft::host::{Host, Wake}; +use craft::menu::{CommandRef, Item, Node}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::NOT_LISTED; use vectorcraft_engine::script::folder::{Entry, Listing}; use crate::VectorcraftApp; -use crate::menus::Item; /// The command a listed script's menu item runs. pub const COMMAND: &str = "ui.runInstalledScript"; @@ -41,56 +44,56 @@ pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE, LOADING, SLOW]; /// How long the first read runs before the menu shows [`SLOW`]. pub const SLOW_SECS: f64 = 2.0; +/// The command Other Script… runs, which only File › Scripts itself lists. +const OTHER_SCRIPT: &str = "ui.runScript"; + #[derive(Default)] struct State { + /// The reads of the folder, keyed by the folder; built at the first read. + queue: Option>, /// The last finished listing. listing: Arc, - /// How many finished listings differed from the one before. + /// How many finished listings differed from the one before, and how often the note before the + /// first listing changed. revision: u64, - /// The listing being read on another thread. - reading: Option>, - /// Another read was asked for while one was under way; [`poll`] starts it when that one ends. - pending: bool, - /// A first read was asked for. - started: bool, - /// The window was the active one at the last [`poll`]. - focused: bool, /// A listing has been taken in. loaded: bool, - /// When the first read started ([`crate::clock::now_secs`]), while it is under way. + /// When the first read started, in seconds of [`craft::platform::clock::monotonic_ms`], until a + /// listing comes. first_read: Option, - /// The first read has taken [`SLOW_SECS`]. - slow: bool, - /// No listing yet, and the last read could not start or ended without one. - failed: bool, } impl State { - /// The note in place of a listing before the first one. - fn first_read_note(&self) -> Option<&'static str> { + /// The queue, built on the host's jobs; false without a host (no listing is read then). + fn ensure_queue(&mut self, ctx: &egui::Context) -> bool { + if self.queue.is_none() { + let Some(host) = Host::try_of_ctx(ctx) else { return false }; + let wake = ctx.clone(); + let wake = Wake::new(move || wake.request_repaint()); + self.queue = Some(JobQueue::new(host.jobs_shared().clone(), wake, QueueOptions::default())); + } + true + } + + /// The note in place of a listing before the first one, at `now` seconds. + fn note_at(&self, now: f64) -> Option<&'static str> { if self.loaded { return None; } - if self.reading.is_some() { - return Some(if self.slow { SLOW } else { LOADING }); - } - self.failed.then_some(UNREADABLE) + let started = self.first_read?; + Some(if now - started >= SLOW_SECS { SLOW } else { LOADING }) } - /// No listing yet, and the read under way ended without one or could not start. - fn first_read_failed(&mut self) { - if !self.loaded { - (self.first_read, self.slow, self.failed) = (None, false, true); - self.revision += 1; - } - } - - /// Show [`SLOW`] once the first read has run [`SLOW_SECS`] by `now`. - fn mark_slow(&mut self, now: f64) { - if !self.loaded && !self.slow && self.reading.is_some() && self.first_read.is_some_and(|t| now - t >= SLOW_SECS) { - self.slow = true; + /// Show a finished listing; the first one also takes the place of the loading note. + fn take_in(&mut self, listing: Listing) { + let changed = *self.listing != listing; + if changed { + self.listing = Arc::new(listing); + } + if changed || !self.loaded { self.revision += 1; } + (self.loaded, self.first_read) = (true, None); } } @@ -110,6 +113,11 @@ fn state() -> MutexGuard<'static, State> { state.lock().unwrap_or_else(|e| e.into_inner()) } +/// The clock the notes follow, in seconds. +fn now() -> f64 { + craft::platform::clock::monotonic_ms() / 1000.0 +} + /// The most different names the menu shows in one session. Each is kept for the rest of the /// session (menu items hold `&'static str` labels), at most 128 characters each. pub const MAX_NAMES: usize = 16_384; @@ -139,193 +147,118 @@ pub(crate) fn intern(s: &str) -> Option<&'static str> { Some(v) } -/// Changes whenever the menus' listing or the note before the first listing changes (the macOS -/// menu bar follows it). +/// Changes whenever the menus' listing or the note before the first listing changes, so the menus +/// are laid out again. The low bit is the [`SLOW`] note, which the clock brings in. pub fn revision() -> u64 { - state().revision + let state = state(); + state.revision * 2 + u64::from(state.note_at(now()) == Some(SLOW)) } -/// Read the Scripts folder again on another thread, unless the session has no folder (the web, and -/// a run without preferences). While a read is under way, another read starts when it ends -/// ([`poll`]). `ctx` is asked to draw when the read ends. -pub fn refresh(app: &VectorcraftApp, ctx: Option<&egui::Context>) { +/// Read the Scripts folder again, unless the session has no folder (the web, and a run without +/// preferences) or the context has no host. A read asked for while one runs waits for it (the +/// queue runs one job per folder). `ctx` is asked to draw when the read ends. +pub fn refresh(app: &VectorcraftApp, ctx: &egui::Context) { let Some(root) = app.session.scripts_dir().map(Path::to_path_buf) else { return }; let mut state = state(); - if state.reading.is_some() { - state.pending = true; + if !state.ensure_queue(ctx) { return; } - let (tx, rx) = std::sync::mpsc::channel(); - let worker_ctx = ctx.cloned(); - let spawned = std::thread::Builder::new().name("vectorcraft-scripts".into()).spawn(move || { + if let Some(queue) = &state.queue { + let read = root.clone(); // The app's own folder, read for the person at the keyboard. - let listing = vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&root)); - if tx.send(listing).is_ok() - && let Some(ctx) = worker_ctx - { - ctx.request_repaint(); - } - }); - if spawned.is_err() { - state.first_read_failed(); - return; + queue.submit(root, Priority::VISIBLE, move |_| vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&read))); } - state.reading = Some(rx); if !state.loaded && state.first_read.is_none() { // The menus show the loading note, and a frame comes when it is due to change to SLOW. - state.first_read = Some(crate::clock::now_secs()); + state.first_read = Some(now()); state.revision += 1; - if let Some(ctx) = ctx { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(SLOW_SECS)); - } + ctx.request_repaint_after(Duration::from_secs_f64(SLOW_SECS)); } } -/// Once per iteration: start a read on the first one and when the window becomes the active one, -/// take in a read that ended, and then start a read asked for while it was under way. +/// Once per pass: read the folder at the first pass and in a pass whose input says the window +/// became the active one, then take in the reads that ended. Only the pass that receives the +/// window event reads; a second pass of the frame just takes in. pub fn poll(app: &VectorcraftApp, ctx: &egui::Context) { - let focused = ctx.input(|i| i.focused); - let start = { - let mut state = state(); - let start = !state.started || (focused && !state.focused); - (state.started, state.focused) = (true, focused); - start - }; - if start { - refresh(app, Some(ctx)); + let first = state().queue.is_none(); + if first || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(true)))) { + refresh(app, ctx); } - take(false); - state().mark_slow(crate::clock::now_secs()); - let again = { - let mut state = state(); - let again = state.pending && state.reading.is_none(); - if again { - state.pending = false; - } - again - }; - if again { - refresh(app, Some(ctx)); + take(); +} + +/// Take in the reads that ended. +fn take() { + let mut state = state(); + let Some(queue) = &state.queue else { return }; + let done: Vec = std::iter::from_fn(|| queue.try_recv()).map(|done| done.result).collect(); + for listing in done { + state.take_in(listing); } } -/// Take in the read under way: when it has ended, or with `wait` once it ends. -fn take(wait: bool) { - let mut state = state(); - let Some(reading) = &state.reading else { return }; - let listing = if wait { reading.recv().map_err(|_| TryRecvError::Disconnected) } else { reading.try_recv() }; - match listing { - Ok(listing) => { - let changed = *state.listing != listing; - if changed { - state.listing = Arc::new(listing); - } - // The first listing also takes the place of the loading note. - if changed || !state.loaded { - state.revision += 1; - } - (state.loaded, state.first_read, state.slow, state.failed) = (true, None, false, false); - state.reading = None; - } - Err(TryRecvError::Empty) => {} - Err(TryRecvError::Disconnected) => { - state.reading = None; - state.first_read_failed(); +/// Wait for the reads under way and take them in. +#[cfg(test)] +pub(crate) fn finish() { + { + let state = state(); + if let Some(queue) = &state.queue { + queue.finish(Duration::from_secs(10)); } } -} - -/// Wait for the read under way and take it in. -#[cfg(test)] -pub(crate) fn wait() { - take(true); -} - -/// The read under way ends without a listing, as when its thread stops early. -#[cfg(test)] -pub(crate) fn lose_read() { - let mut state = state(); - if state.reading.is_some() { - state.reading = Some(std::sync::mpsc::channel::().1); - } -} - -/// When the first read started, while it is under way. -#[cfg(test)] -pub(crate) fn first_read_started() -> Option { - state().first_read -} - -/// What [`poll`] does about a slow first read, at `now` ([`crate::clock::now_secs`]). -#[cfg(test)] -pub(crate) fn check_slow(now: f64) { - state().mark_slow(now); -} - -/// Wait for the read under way to end and leave its listing to be taken in, so the read is under -/// way until the next [`poll`]. -#[cfg(test)] -pub(crate) fn end_untaken() { - let mut state = state(); - let Some(reading) = &state.reading else { return }; - let (tx, rx) = std::sync::mpsc::channel(); - if let Ok(listing) = reading.recv() { - let _ = tx.send(listing); - } - state.reading = Some(rx); + take(); } /// File › Scripts' items: the listed scripts and subfolders, a note when some may be missing or /// the folder cannot be read, or one before the first listing, then Check Script… and Other /// Script…. -pub fn items() -> Vec { - // A row whose name is past [`MAX_NAMES`] is left out (`dropped`). - fn level(entries: &[Entry], dropped: &mut bool) -> Vec { - let mut items = Vec::with_capacity(entries.len()); - for e in entries { - let item = match e { - Entry::Script { label, path } => intern(label).map(|l| Item::Cmd(l, COMMAND, json!({ "path": path.to_string_lossy() }))), - Entry::Folder { label, entries } => { - let inner = level(entries, dropped); - intern(label).filter(|_| !inner.is_empty()).map(|l| Item::Sub(l, inner)) +pub fn items() -> Vec { + items_at(now()) +} + +/// [`items`] with the notes as they are at `now` seconds. +pub(crate) fn items_at(now: f64) -> Vec { + fn level(entries: &[Entry]) -> Vec { + entries + .iter() + .filter_map(|e| match e { + Entry::Script { label, path } => { + let command = CommandRef::with_params(COMMAND, json!({ "path": path.to_string_lossy() })); + Some(Node::Item(Item::new(command, label.to_string()))) } - }; - match item { - Some(item) => items.push(item), - None => *dropped = true, - } - } - items + Entry::Folder { label, entries } => { + let inner = level(entries); + (!inner.is_empty()).then(|| Node::submenu(label.to_string(), inner)) + } + }) + .collect() } let (listing, note) = { let state = state(); - (state.listing.clone(), state.first_read_note()) + (state.listing.clone(), state.note_at(now)) }; - let mut dropped = false; - let mut items = level(&listing.entries, &mut dropped); - if listing.truncated || dropped { - items.push(Item::Header(TRUNCATED)); + let mut nodes = level(&listing.entries); + let notes = [listing.truncated.then_some(TRUNCATED), listing.unreadable.then_some(UNREADABLE), note]; + nodes.extend(notes.into_iter().flatten().map(Node::heading)); + if !nodes.is_empty() { + nodes.push(Node::Separator); } - if listing.unreadable { - items.push(Item::Header(UNREADABLE)); - } - items.extend(note.map(Item::Header)); - if !items.is_empty() { - items.push(Item::Sep); - } - items.extend([Item::Cmd("Check Script…", "ui.checkScript", Value::Null), Item::Cmd("Other Script…", "ui.runScript", Value::Null)]); - items + nodes.extend([ + Node::Item(Item::new(CommandRef::new("ui.checkScript"), "Check Script…")), + Node::Item(Item::new(CommandRef::new(OTHER_SCRIPT), "Other Script…")), + ]); + nodes } /// Is `children` a subfolder's submenu, named after the folder? Its first item is a listed script /// or another subfolder, and it has no Other Script…, which only File › Scripts itself has. -pub fn is_folder(children: &[Item]) -> bool { +pub fn is_folder(children: &[Node]) -> bool { let listed = match children.first() { - Some(Item::Cmd(_, id, _)) => *id == COMMAND, - Some(Item::Sub(_, inner)) => is_folder(inner), + Some(Node::Item(item)) => item.command.id == COMMAND, + Some(Node::Submenu { children, .. }) => is_folder(children), _ => false, }; - listed && !children.iter().any(|c| matches!(c, Item::Cmd(_, "ui.runScript", _))) + listed && !children.iter().any(|c| matches!(c, Node::Item(item) if item.command.id == OTHER_SCRIPT)) } /// May the request being served read the listed script `p` names? Under an automation read root @@ -342,9 +275,10 @@ pub fn readable(p: &Value) -> bool { pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?; app.run("script.run", json!({ "path": path, "installed": true })).inspect_err(|e| { - if e == NOT_LISTED { - let ctx = app.ui_ctx.clone(); - refresh(app, ctx.as_ref()); + if e == NOT_LISTED + && let Some(ctx) = app.ui_ctx.clone() + { + refresh(app, &ctx); } }) } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 02c077e9af..27a31a1cd3 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -1,14 +1,29 @@ //! File › Scripts lists the Scripts folder: its scripts and subfolders above Check Script… and //! Other Script…, names shown as they are, a listed script run without the warning, a script that -//! is gone, the notes, the macOS menu bar and the reads of the folder. +//! is gone, the notes and the reads of the folder. +use std::sync::Arc; +use std::time::Duration; + +use craft::host::{AppInfo, Host, ThreadJobs}; +use craft::menu::Node; use serde_json::{Value, json}; use vectorcraft_engine::Session; -use crate::menus::{self, Entry, Item}; -use crate::native_menu::{self, Node}; +use crate::menus::{self, Entry}; use crate::{VectorcraftApp, script_runs, scripts_menu}; +/// This thread's context, with a host whose jobs run on threads. Tests run on threads of their +/// own, each with its own listing. +fn ctx() -> egui::Context { + thread_local!(static CTX: egui::Context = { + let ctx = egui::Context::default(); + Host::builder(AppInfo { id: "vectorcraft", name: "VectorCraft", version: "0" }).jobs(Arc::new(ThreadJobs)).install(&ctx); + ctx + }); + CTX.with(Clone::clone) +} + /// A fresh folder for test `name`, holding an empty `Scripts` folder. fn folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-scripts-menu-{name}-{}", std::process::id())); @@ -22,14 +37,15 @@ fn app(dir: &std::path::Path) -> VectorcraftApp { let mut session = Session::new(); session.attach_scripts_dir(dir.join("Scripts")); let mut app = VectorcraftApp::new(session, crate::Services::default()); + app.ui_ctx = Some(ctx()); app.run("file.new", json!({})).unwrap(); app } /// Reads the folder again and waits for the listing. fn read(app: &VectorcraftApp) { - scripts_menu::refresh(app, None); - scripts_menu::wait(); + scripts_menu::refresh(app, &ctx()); + scripts_menu::finish(); } /// Writes the script `name` (`/` between its folders) in `dir`'s Scripts folder; returns its path @@ -42,26 +58,21 @@ fn write(dir: &std::path::Path, name: &str, text: &str) -> String { } /// File › Scripts' items. -fn scripts() -> Vec { - let (_, file) = menus::menu_tree().into_iter().find(|(title, _)| *title == "File").unwrap(); - file.into_iter() - .find_map(|item| match item { - Item::Sub("Scripts", items) => Some(items), - _ => None, - }) - .unwrap() +fn scripts() -> Vec { + scripts_menu::items() } /// Menu items as text: a command's label, `label/[…]` for a submenu, `(text)` for a note and `-` /// for a separator. -fn shape(items: &[Item]) -> String { - let one = |item: &Item| match item { - Item::Cmd(label, ..) | Item::Todo(label, _) => label.to_string(), - Item::Sub(label, items) => format!("{label}/[{}]", shape(items)), - Item::Header(text) => format!("({text})"), - Item::Sep => "-".to_string(), +fn shape(nodes: &[Node]) -> String { + let one = |node: &Node| match node { + Node::Item(item) => item.label.clone(), + Node::Submenu { label, children, .. } => format!("{label}/[{}]", shape(children)), + Node::Heading(text) => format!("({text})"), + Node::Separator => "-".to_string(), + _ => "?".to_string(), }; - items.iter().map(one).collect::>().join(", ") + nodes.iter().map(one).collect::>().join(", ") } fn objects(app: &VectorcraftApp) -> usize { @@ -96,7 +107,11 @@ fn the_folders_scripts_are_listed_above_check_script_and_other_script() { read(&app); let items = scripts(); assert_eq!(shape(&items), format!("Draw Two, Export/[All Artboards], -, {FIXED}")); - assert!(matches!(&items[0], Item::Cmd(_, scripts_menu::COMMAND, p) if *p == json!({ "path": draw })), "{:?}", items[0]); + assert!( + matches!(&items[0], Node::Item(i) if i.command.id == scripts_menu::COMMAND && i.command.params == json!({ "path": draw })), + "{:?}", + items[0] + ); // A script added to the folder is listed by the next read, with no restart. write(&dir, "Added.js", ""); assert!(shape(&scripts()).starts_with("Draw Two"), "the menus keep the last listing"); @@ -112,12 +127,13 @@ fn a_listed_script_runs_without_the_warning_as_one_undo_step() { write(&dir, "Dessin (été) #1.JSX", DRAW); read(&app); let items = scripts(); - let Item::Cmd(label, id, p) = &items[0] else { panic!("{:?}", items[0]) }; + let Node::Item(item) = &items[0] else { panic!("{:?}", items[0]) }; + let (label, id, p) = (item.label.as_str(), item.command.id.as_str(), &item.command.params); let undo = app.session.doc().unwrap().history.undo.len(); assert!(app.session.prefs.show_external_script_warning); let (id, p) = menus::click_target(label, id, p); menus::invoke(&mut app, &id, p); - assert!(app.ui.dialog.is_none(), "no warning for a script of the folder"); + assert!(!app.any_dialog_open(), "no warning for a script of the folder"); assert!(app.session.script_running()); finish(&mut app); assert_eq!(objects(&app), 2); @@ -137,7 +153,8 @@ fn a_script_runs_its_own_file_whatever_its_name_ends_with() { read(&app); let items = scripts(); assert_eq!(shape(&items[..2]), "Draw, Draw…"); - let Item::Cmd(label, id, p) = &items[1] else { panic!("{:?}", items[1]) }; + let Node::Item(item) = &items[1] else { panic!("{:?}", items[1]) }; + let (label, id, p) = (item.label.as_str(), item.command.id.as_str(), &item.command.params); assert_eq!(menus::click_target(label, id, p), (scripts_menu::COMMAND.to_string(), json!({ "path": dots }))); menus::run_ui_command(&mut app, id, p).unwrap().unwrap(); finish(&mut app); @@ -170,6 +187,7 @@ fn script_and_folder_names_are_shown_as_they_are_in_every_language() { assert!(crate::i18n::tr(de, "Layers") != "Layers" && crate::i18n::tr(de, "Export") != "Export", "German translates both words"); crate::i18n::set_current(de); let items = scripts(); + // PLAN: assumed `menus::entry(app: &VectorcraftApp, node: &Node) -> Option` (menus-w5). let labels: Vec = items .iter() .filter_map(|item| match menus::entry(&app, item)? { @@ -188,6 +206,7 @@ fn script_and_folder_names_are_shown_as_they_are_in_every_language() { write(&dir, "Zed/All Artboards.js", ""); read(&app); assert!(!menus::menu_strings().contains("All Artboards") && !menus::menu_strings().contains("Zed")); + // PLAN: assumed the palette's entry accessor keeps `(_, id, _)` rows (menus-w12). assert!(!crate::palette::items().iter().any(|(_, id, _)| id == scripts_menu::COMMAND), "a script runs from its menu item"); let _ = std::fs::remove_dir_all(dir); } @@ -203,7 +222,7 @@ fn a_script_that_left_the_folder_is_not_run_and_the_folder_is_read_again() { let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": gone })).unwrap().unwrap_err(); assert_eq!(e, "the script is no longer in the Scripts folder"); assert!(!app.session.script_running()); - scripts_menu::wait(); + scripts_menu::finish(); assert_eq!(shape(&scripts()), format!("kept, -, {FIXED}")); // A file outside the folder is not one of its scripts, and a call needs a path. let outside = dir.join("outside.js"); @@ -224,18 +243,15 @@ fn the_read_after_a_script_that_left_the_folder_asks_for_a_frame() { let gone = write(&dir, "gone.js", DRAW); read(&app); std::fs::remove_file(&gone).unwrap(); - let ctx = egui::Context::default(); let (tx, frames) = std::sync::mpsc::channel(); - ctx.set_request_repaint_callback(move |_| { + ctx().set_request_repaint_callback(move |_| { let _ = tx.send(()); }); - app.ui_ctx = Some(ctx); assert!(menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": gone })).unwrap().is_err()); - // With the app's copy of the context dropped, only the read's thread can still ask for a - // frame; the channel closes without one when that thread ends without asking. + // With the app's copy of the context dropped, only the queue's wake can still ask for a frame. app.ui_ctx = None; - assert_eq!(frames.recv(), Ok(()), "the finished read asks for a frame so an idle window takes it in"); - scripts_menu::wait(); + assert_eq!(frames.recv_timeout(Duration::from_secs(10)), Ok(()), "the finished read asks for a frame so an idle window takes it in"); + scripts_menu::finish(); let _ = std::fs::remove_dir_all(dir); } @@ -281,54 +297,32 @@ fn a_menu_listing_under_a_read_root_leaves_out_scripts_outside_it() { let _ = std::fs::remove_dir_all(dir); } -#[test] -fn names_past_the_session_limit_are_left_out_with_the_note() { - let dir = folder("names-limit"); - let app = app(&dir); - write(&dir, "Kept.js", ""); - read(&app); - assert_eq!(shape(&scripts()), format!("Kept, -, {FIXED}")); - // Names other listings showed fill what one session keeps. - for n in 0..scripts_menu::MAX_NAMES { - if scripts_menu::intern(&format!("renamed {n}")).is_none() { - break; - } - } - write(&dir, "New.js", ""); - write(&dir, "Folder/Inside.js", ""); - read(&app); - assert_eq!(shape(&scripts()), format!("Kept, ({}), -, {FIXED}", scripts_menu::TRUNCATED)); - let _ = std::fs::remove_dir_all(dir); -} - #[test] fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { let dir = folder("native"); let app = app(&dir); let path = write(&dir, "Export/All Artboards.js", ""); let before = scripts_menu::revision(); - read(&app); - // The loading note showed, then the listing took its place. - assert_eq!(scripts_menu::revision(), before + 2); - let bar = native_menu::from_tree(&app, &menus::menu_tree()); - let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); - let scripts = file.children.iter().find_map(|n| match n { - Node::Submenu { label, children } if label == "Scripts" => Some(children), - _ => None, - }); - let Some([Node::Submenu { label, children }, Node::Separator, Node::Item(check), Node::Item(other)]) = scripts.map(Vec::as_slice) else { - panic!("{scripts:?}") + scripts_menu::refresh(&app, &ctx()); + let noting = scripts_menu::revision(); + assert_ne!(noting, before, "the loading note changes what the menus show"); + scripts_menu::finish(); + let listed = scripts_menu::revision(); + assert_ne!(listed, noting, "the listing takes the note's place"); + let items = scripts_menu::items(); + let [Node::Submenu { label, children, .. }, Node::Separator, Node::Item(check), Node::Item(other)] = items.as_slice() else { + panic!("{items:?}") }; - assert_eq!((label.as_str(), check.command, other.command), ("Export", Some("ui.checkScript"), Some("ui.runScript"))); + assert_eq!((label.as_str(), check.command.id.as_str(), other.command.id.as_str()), ("Export", "ui.checkScript", "ui.runScript")); let [Node::Item(script)] = children.as_slice() else { panic!("{children:?}") }; - assert_eq!((script.label.as_str(), script.command, &script.params), ("All Artboards", Some(scripts_menu::COMMAND), &json!({ "path": path }))); + assert_eq!((script.label.as_str(), script.command.id.as_str(), &script.command.params), ("All Artboards", scripts_menu::COMMAND, &json!({ "path": path }))); assert!(script.enabled && script.shortcut.is_none()); // A read that finds the same scripts changes nothing the menu bar would rebuild for. read(&app); - assert_eq!(scripts_menu::revision(), before + 2); + assert_eq!(scripts_menu::revision(), listed); write(&dir, "More.jsx", ""); read(&app); - assert_eq!(scripts_menu::revision(), before + 3); + assert_ne!(scripts_menu::revision(), listed); let _ = std::fs::remove_dir_all(dir); } @@ -337,93 +331,25 @@ fn the_folder_is_read_at_the_first_frame_and_when_the_window_becomes_active() { let dir = folder("focus"); let app = app(&dir); write(&dir, "first.js", ""); - let ctx = egui::Context::default(); - let frame = |focused: bool| { - let mut out = ctx.run_ui(egui::RawInput { focused, ..Default::default() }, |ui| scripts_menu::poll(&app, ui.ctx())); + let ctx = ctx(); + let frame = |events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| scripts_menu::poll(&app, ui.ctx())); out.textures_delta.clear(); - scripts_menu::wait(); + scripts_menu::finish(); }; let listed = || shape(&scripts()); - frame(true); + frame(vec![]); assert!(listed().starts_with("first, -"), "{}", listed()); - // While the window stays active, or stays in the background, the folder is left alone. + // A pass without the window becoming active leaves the folder alone, focused or not. write(&dir, "second.js", ""); - frame(true); - frame(false); - frame(false); + frame(vec![]); + frame(vec![egui::Event::WindowFocused(false)]); assert!(listed().starts_with("first, -"), "{}", listed()); - frame(true); + frame(vec![egui::Event::WindowFocused(true)]); assert!(listed().starts_with("first, second, -"), "{}", listed()); let _ = std::fs::remove_dir_all(dir); } -/// A macOS menu bar that reports a menu opening at its next drain when `0` is set. -struct Opens(std::rc::Rc>); - -impl native_menu::Backend for Opens { - fn sync(&mut self, _: &native_menu::MenuBar) {} - fn drain(&mut self) -> Vec { - if self.0.replace(false) { vec![native_menu::Event::Opened] } else { Vec::new() } - } -} - -#[test] -fn a_menu_of_the_macos_menu_bar_opening_reads_the_folder_again() { - let dir = folder("native-open"); - let mut app = app(&dir); - write(&dir, "first.js", ""); - read(&app); - let opens = std::rc::Rc::new(std::cell::Cell::new(false)); - app.services.native_menu = Some(native_menu::NativeMenu::new(Box::new(Opens(opens.clone())))); - let ctx = egui::Context::default(); - let mut frame = |opened: bool| { - opens.set(opened); - assert_eq!(app.services.native_menu.as_mut().map(native_menu::NativeMenu::take_keys), Some(Vec::new())); - native_menu::run(&mut app, &ctx); - scripts_menu::wait(); - native_menu::layout(&app).bar - }; - let listed = |bar: &native_menu::MenuBar| { - let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); - let scripts = file.children.iter().find_map(|n| match n { - Node::Submenu { label, children } if label == "Scripts" => Some(children.as_slice()), - _ => None, - }); - scripts.unwrap_or_default().iter().filter_map(|n| if let Node::Item(it) = n { Some(it.label.clone()) } else { None }).collect::>() - }; - // While the window stays active and no menu opens, the folder is left alone. - write(&dir, "second.js", ""); - let bar = frame(false); - assert_eq!(listed(&bar)[..1], ["first"], "{:?}", listed(&bar)); - assert!(!listed(&bar).iter().any(|l| l == "second"), "{:?}", listed(&bar)); - let bar = frame(true); - assert_eq!(listed(&bar)[..2], ["first", "second"], "{:?}", listed(&bar)); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_read_asked_for_during_another_runs_when_that_one_ends() { - let dir = folder("pending"); - let app = app(&dir); - write(&dir, "first.js", ""); - let ctx = egui::Context::default(); - let frame = || { - let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| scripts_menu::poll(&app, ui.ctx())); - out.textures_delta.clear(); - }; - frame(); - scripts_menu::wait(); - // A read that has passed the folder when a script is added, and the File menu opening then. - scripts_menu::refresh(&app, None); - scripts_menu::end_untaken(); - write(&dir, "added.js", ""); - scripts_menu::refresh(&app, None); - frame(); - scripts_menu::wait(); - assert!(shape(&scripts()).starts_with("added, first, -"), "{}", shape(&scripts())); - let _ = std::fs::remove_dir_all(dir); -} - #[test] fn an_app_without_a_scripts_folder_keeps_the_two_fixed_items() { let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); @@ -435,52 +361,25 @@ fn an_app_without_a_scripts_folder_keeps_the_two_fixed_items() { let _: Value = app.run("script.listInstalled", json!({})).unwrap(); } -/// File › Scripts in the macOS menu bar as text, as [`shape`] gives the in-window menu. -fn native_shape(app: &VectorcraftApp) -> String { - fn one(nodes: &[Node]) -> String { - let node = |n: &Node| match n { - Node::Item(it) if it.command.is_none() => format!("({})", it.label), - Node::Item(it) => it.label.clone(), - Node::Header(label) => format!("({label})"), - Node::Submenu { label, children } => format!("{label}/[{}]", one(children)), - Node::Separator => "-".to_string(), - Node::Standard(s) => format!("{s:?}"), - }; - nodes.iter().map(node).collect::>().join(", ") - } - let bar = native_menu::from_tree(app, &menus::menu_tree()); - let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); - let scripts = file.children.iter().find_map(|n| match n { - Node::Submenu { label, children } if label == "Scripts" => Some(children), - _ => None, - }); - one(scripts.unwrap()) -} - #[test] fn the_first_read_shows_a_loading_note_until_its_listing_comes() { let dir = folder("loading"); let app = app(&dir); write(&dir, "first.js", ""); - let before = scripts_menu::revision(); - scripts_menu::refresh(&app, None); - scripts_menu::end_untaken(); - let loading = format!("({}), -, {FIXED}", scripts_menu::LOADING); - assert_eq!(shape(&scripts()), loading); - assert_eq!(native_shape(&app), loading, "the macOS menu bar shows the same note"); - assert_eq!(scripts_menu::revision(), before + 1, "the macOS menu bar rebuilds for the note"); - scripts_menu::wait(); + scripts_menu::refresh(&app, &ctx()); + // The job runs, or has ended with its result not taken yet. + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + scripts_menu::finish(); assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); - assert_eq!(native_shape(&app), format!("first, -, {FIXED}")); - assert_eq!(scripts_menu::revision(), before + 2); + let listed = scripts_menu::revision(); // A later read keeps the listing, with no note, while it is under way. write(&dir, "second.js", ""); - scripts_menu::refresh(&app, None); - scripts_menu::end_untaken(); + scripts_menu::refresh(&app, &ctx()); assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); - assert_eq!(scripts_menu::revision(), before + 2); - scripts_menu::wait(); + assert_eq!(scripts_menu::revision(), listed); + scripts_menu::finish(); assert_eq!(shape(&scripts()), format!("first, second, -, {FIXED}")); + assert_ne!(scripts_menu::revision(), listed); let _ = std::fs::remove_dir_all(dir); } @@ -488,10 +387,12 @@ fn the_first_read_shows_a_loading_note_until_its_listing_comes() { fn an_empty_or_unreadable_first_listing_takes_the_place_of_the_loading_note() { let dir = folder("loading-empty"); let app = app(&dir); - let before = scripts_menu::revision(); - read(&app); + scripts_menu::refresh(&app, &ctx()); + let noting = scripts_menu::revision(); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + scripts_menu::finish(); assert_eq!(shape(&scripts()), FIXED); - assert_eq!(scripts_menu::revision(), before + 2, "the note went, though the listing is the empty one it started from"); + assert_ne!(scripts_menu::revision(), noting, "the note went, though the listing is the empty one it started from"); let _ = std::fs::remove_dir_all(dir); // A thread of its own has a menu that has not listed yet. let dir = folder("loading-unreadable"); @@ -513,47 +414,15 @@ fn a_slow_first_read_says_so_until_its_listing_comes() { let dir = folder("slow"); let app = app(&dir); write(&dir, "first.js", ""); - scripts_menu::refresh(&app, None); - scripts_menu::end_untaken(); - let started = scripts_menu::first_read_started().unwrap(); + let asked = craft::platform::clock::monotonic_ms() / 1000.0; + scripts_menu::refresh(&app, &ctx()); + let started = craft::platform::clock::monotonic_ms() / 1000.0; + // The read started between `asked` and `started`, and its result is not taken in yet. let before = scripts_menu::revision(); - scripts_menu::check_slow(started + scripts_menu::SLOW_SECS / 2.0); - assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); - assert_eq!(scripts_menu::revision(), before); - // Past the threshold rather than at it: `(started + SLOW_SECS) - started` can round below - // SLOW_SECS, which made this test fail for some start times. - scripts_menu::check_slow(started + 1.5 * scripts_menu::SLOW_SECS); - assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::SLOW)); - assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::SLOW)); - assert_eq!(scripts_menu::revision(), before + 1); - // Asking again while it reads starts no second read. - scripts_menu::refresh(&app, None); - scripts_menu::check_slow(started + 10.0 * scripts_menu::SLOW_SECS); - assert_eq!(scripts_menu::revision(), before + 1); - scripts_menu::wait(); - assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); - assert_eq!(scripts_menu::first_read_started(), None); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_first_read_that_ends_without_a_listing_says_the_folder_cannot_be_read_and_the_next_read_tries_again() { - let dir = folder("lost"); - let app = app(&dir); - write(&dir, "first.js", ""); - scripts_menu::refresh(&app, None); - scripts_menu::end_untaken(); - scripts_menu::lose_read(); - let before = scripts_menu::revision(); - scripts_menu::wait(); - assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE), "no loading note left behind"); - assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); - assert_eq!(scripts_menu::revision(), before + 1); - assert_eq!(scripts_menu::first_read_started(), None); - scripts_menu::refresh(&app, None); - scripts_menu::end_untaken(); - assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); - scripts_menu::wait(); - assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(shape(&scripts_menu::items_at(asked + scripts_menu::SLOW_SECS / 2.0)), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + assert_eq!(shape(&scripts_menu::items_at(started + 1.5 * scripts_menu::SLOW_SECS)), format!("({}), -, {FIXED}", scripts_menu::SLOW)); + assert_eq!(scripts_menu::revision(), before, "the note follows the clock, not a flag"); + scripts_menu::finish(); + assert_eq!(shape(&scripts_menu::items_at(started + 10.0 * scripts_menu::SLOW_SECS)), format!("first, -, {FIXED}")); let _ = std::fs::remove_dir_all(dir); }