diff --git a/Cargo.lock b/Cargo.lock index 84fbe3bf3..c96be1eee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6960,6 +6960,7 @@ dependencies = [ "richtext", "serde", "serde_json", + "strum", "tempfile", "text", "tokio", diff --git a/Cargo.toml b/Cargo.toml index f487eae4a..ea829ad1d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -85,6 +85,7 @@ sha2 = "0.11.0" sha3 = "0.12.0" similar = "3.2.0" skrifa = "0.44.0" +strum = { version = "0.27.2", features = ["derive"] } syntect = { version = "5.3.0", default-features = false, features = ["parsing", "regex-onig", "yaml-load"] } sys-locale = "0.3.2" tempfile = "3.27.0" diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index 532a8088c..9596df39e 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -30,6 +30,7 @@ serde_json.workspace = true rayon.workspace = true zeroize.workspace = true log.workspace = true +strum.workspace = true base64.workspace = true png.workspace = true image.workspace = true diff --git a/crates/ui/src/action.rs b/crates/ui/src/action.rs index 35c9f807e..f9ae47a93 100644 --- a/crates/ui/src/action.rs +++ b/crates/ui/src/action.rs @@ -5,7 +5,7 @@ use crate::state::Area; use crate::theme::Appearance; -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Action { App(AppAction), Gate(crate::gate::Action), @@ -17,8 +17,108 @@ pub enum Action { Global(GlobalAction), } +impl Action { + /// What the person did, by the names of the variants alone (`Notes::Editor::Close`): never + /// the payload, which may be a title, a body, a URL or a field's value. ⚠️ Never `{:?}`. + pub fn name(&self) -> String { + let mut path: Vec<&'static str> = vec![self.into()]; + match self { + Self::App(action) => { + path.push(action.into()); + if let AppAction::Window(ask) = action { + path.push(ask.into()); + } + } + Self::Gate(action) => path.push(action.into()), + Self::Notes(action) => notes(action, &mut path), + Self::Http(action) => http(action, &mut path), + Self::Tools(action) => path.push(action.into()), + Self::Menu(action) => menu(action, &mut path), + Self::Palette(asked) => path.push(asked.into()), + Self::Global(action) => path.push(action.into()), + } + path.join("::") + } + + /// Once, as it is applied, under its number in the session. + pub fn log(&self, number: u64) { + let name = self.name(); + let level = if FREQUENT.contains(&name.as_str()) { log::Level::Trace } else { log::Level::Info }; + log::log!(target: "ui::action", level, "#{number} {name}"); + } +} + +/// Sent at each key typed, or by the screen itself as it shows something: at `trace`, so that +/// the terminal reads as what the person did. +const FREQUENT: [&str; 14] = [ + "Notes::Search", + "Notes::Trash::Search", + "Notes::Thumbnail", + "Notes::Picture", + "Notes::Editor::Fields::Preview", + "Notes::Editor::Evaluate", + "Notes::Editor::Explore", + "Http::Edit", + "Http::EditSettings", + "Http::Environments::Rows", + "Http::Explore", + "Http::ResponseImage", + "Menu::Preferences::TypedCurrent", + "Palette::Type", +]; + +/// A variant that carries what is asked of a part of the area is named by that too. +fn notes(action: &crate::notes::Action, path: &mut Vec<&'static str>) { + use crate::notes::{Action, Editing}; + path.push(action.into()); + match action { + Action::Editor(editing) => { + path.push(editing.into()); + match editing { + Editing::Fields(fields) => path.push(fields.into()), + Editing::Attachment(asked) => path.push(asked.into()), + Editing::Revisions(asked) => path.push(asked.into()), + _ => {} + } + } + Action::Board(gesture) => path.push(gesture.into()), + Action::Canvas(key) => path.push(key.into()), + Action::Batch(batch) => path.push(batch.into()), + Action::Trash(trash) => path.push(trash.into()), + Action::Tags(tags) => path.push(tags.into()), + Action::Fill(fill) => path.push(fill.into()), + _ => {} + } +} + +fn http(action: &crate::http::Action, path: &mut Vec<&'static str>) { + use crate::http::Action; + path.push(action.into()); + match action { + Action::Write(write) => path.push(write.into()), + Action::Environments(asked) => path.push(asked.into()), + Action::Cookies(asked) => path.push(asked.into()), + Action::History(asked) => path.push(asked.into()), + Action::Code(asked) => path.push(asked.into()), + Action::Runner(asked) => path.push(asked.into()), + Action::Leave(asked) => path.push(asked.into()), + _ => {} + } +} + +fn menu(action: &crate::titlebar::Action, path: &mut Vec<&'static str>) { + use crate::titlebar::Action; + path.push(action.into()); + match action { + Action::Libraries(ask) => path.push(ask.into()), + Action::Preferences(ask) => path.push(ask.into()), + Action::Update(ask) => path.push(ask.into()), + _ => {} + } +} + /// The frame's: the areas, the look, the window. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] pub enum AppAction { ShowArea(Area), SetAppearance(Appearance), @@ -40,7 +140,7 @@ pub enum AppAction { } /// Asked from outside the window: a global shortcut, the tray, a second launch. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] pub enum GlobalAction { Capture, NewNote, @@ -86,7 +186,98 @@ impl Actions { #[cfg(test)] mod tests { + use std::collections::BTreeMap; + + use engine::notes::checklist::ChecklistItem; + use super::*; + use crate::notes::{Action as Notes, Editing, Fields}; + use crate::state::editor::{Body, Edit}; + use crate::state::held::held; + use crate::state::http::tabs::DraftEdit; + use crate::testing; + + #[test] + fn each_action_is_logged_once_by_name_numbered_in_order() { + let heard = testing::listen(); + let mut held = held(testing::unlocked()); + let before = heard.here("ui::action").len(); + + for action in [ + Action::App(AppAction::ToggleRail), + Action::Gate(crate::gate::Action::ToggleReveal), + Action::Notes(Notes::ClearSearch), + Action::Notes(Notes::Editor(Editing::Close)), + Action::Http(crate::http::Action::ToggleConsole), + Action::Tools(crate::tools::Action::SearchAsked), + Action::Menu(crate::titlebar::Action::CloseHelp), + Action::Global(GlobalAction::PaletteHere), + Action::Palette(crate::palette::Asked::Type("walrus".to_owned())), + Action::Palette(crate::palette::Asked::Close), + ] { + held.apply(action); + } + + let lines = &heard.here("ui::action")[before..]; + let (numbers, said): (Vec, Vec<(log::Level, &str)>) = lines + .iter() + .map(|(level, text)| { + let (number, name) = text.strip_prefix('#').unwrap().split_once(' ').unwrap(); + (number.parse::().unwrap(), (*level, name)) + }) + .unzip(); + let info = log::Level::Info; + assert_eq!( + said, + [ + (info, "App::ToggleRail"), + (info, "Gate::ToggleReveal"), + (info, "Notes::ClearSearch"), + (info, "Notes::Editor::Close"), + (info, "Http::ToggleConsole"), + (info, "Tools::SearchAsked"), + (info, "Menu::CloseHelp"), + (info, "Global::PaletteHere"), + (log::Level::Trace, "Palette::Type"), + (info, "Palette::Close"), + ] + ); + assert!(numbers.windows(2).all(|pair| pair[1] == pair[0] + 1), "{numbers:?}"); + } + + #[test] + fn what_an_action_carries_is_never_logged() { + const TITLE: &str = "sentinel-title-6c1e"; + const BODY: &str = "sentinel-body-6c1e"; + const ITEM: &str = "sentinel-item-6c1e"; + const URL: &str = "https://sentinel-url-6c1e.example"; + const VALUE: &str = "sentinel-value-6c1e"; + let heard = testing::listen(); + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let mut held = held((backend, profile)); + + held.apply(Action::Notes(Notes::Duplicate { id: id.clone(), title: TITLE.to_owned() })); + let item = ChecklistItem { text: ITEM.to_owned(), done: true }; + held.apply(Action::Notes(Notes::SetItems { id: id.clone(), items: vec![item] })); + held.apply(Action::Notes(Notes::OpenNote(id))); + let session = held.state.editor.opened().unwrap().session; + let edit = Edit { body: Some(Body::Content(format!("{BODY} {{{{user}}}}"))), ..Edit::default() }; + held.apply(Action::Notes(Notes::Editor(Editing::Save { session, edit }))); + let values = BTreeMap::from([("user".to_owned(), VALUE.to_owned())]); + held.apply(Action::Notes(Notes::Editor(Editing::Fields(Fields::Keep(values))))); + held.apply(Action::Http(crate::http::Action::NewRequest(engine::http::model::RequestKind::Http))); + let key = held.state.http.tabs().active().unwrap().key.clone(); + held.apply(Action::Http(crate::http::Action::Edit { key, edit: DraftEdit::Url(URL.to_owned()) })); + + let named: Vec = heard.here("ui::action").into_iter().map(|(_, text)| text).collect(); + assert!(named.iter().any(|text| text.ends_with(" Notes::Editor::Fields::Keep")), "{named:?}"); + for line in heard.lines() { + for sentinel in [TITLE, BODY, ITEM, URL, VALUE] { + assert!(!line.text.contains(sentinel), "{} logged {sentinel}: {}", line.target, line.text); + } + } + } #[test] fn every_global_action_is_found_by_its_name() { diff --git a/crates/ui/src/api/preferences.rs b/crates/ui/src/api/preferences.rs index 1d423eb09..aef715631 100644 --- a/crates/ui/src/api/preferences.rs +++ b/crates/ui/src/api/preferences.rs @@ -51,32 +51,12 @@ fn written(preferences: &Preferences, file: &std::path::Path) -> Result<(), AppE #[cfg(test)] mod tests { - use std::sync::Mutex; - use super::*; use crate::testing; - /// What the log was told, for the test that reads it: no other test here sets a logger. - struct Heard(Mutex>); - - impl log::Log for Heard { - fn enabled(&self, _: &log::Metadata<'_>) -> bool { - true - } - - fn log(&self, record: &log::Record<'_>) { - self.0.lock().unwrap().push(record.args().to_string()); - } - - fn flush(&self) {} - } - - static HEARD: Heard = Heard(Mutex::new(Vec::new())); - #[test] fn a_preference_write_that_fails_is_logged() { - let _ = log::set_logger(&HEARD); - log::set_max_level(log::LevelFilter::Warn); + let heard = testing::listen(); let (backend, _profile) = testing::unlocked(); let directory = engine::db::run_here(backend.engine(), libraries::open_library_directory).unwrap(); // A folder where the file goes: no write can take its place. @@ -87,7 +67,8 @@ mod tests { backend.settle(); assert!(written.poll().unwrap().is_err()); - let heard = HEARD.0.lock().unwrap(); - assert!(heard.iter().any(|line| line.contains("preferences")), "{heard:?}"); + let warned = heard.lines().into_iter().filter(|line| line.level == log::Level::Warn); + let said: Vec = warned.map(|line| line.text).collect(); + assert!(said.iter().any(|text| text.contains("preferences")), "{said:?}"); } } diff --git a/crates/ui/src/app.rs b/crates/ui/src/app.rs index 21afb20dc..7cdb67ef4 100644 --- a/crates/ui/src/app.rs +++ b/crates/ui/src/app.rs @@ -187,7 +187,7 @@ impl DevNotesApp { let action = if action == GlobalAction::Palette && in_front(ctx) { GlobalAction::PaletteHere } else { action }; reveal(ctx); - self.state.apply(Action::Global(action), ctx, &self.backend); + self.state.act(Action::Global(action), ctx, &self.backend); } /// A second launch's `--action`. The `e2e` flavour also hears `close`, the event the close @@ -209,7 +209,7 @@ impl DevNotesApp { Some(action @ (GlobalAction::Palette | GlobalAction::Capture | GlobalAction::NewNote)) => { self.asked_from_outside(action, ctx); } - Some(action) => self.state.apply(Action::Global(action), ctx, &self.backend), + Some(action) => self.state.act(Action::Global(action), ctx, &self.backend), None => log::warn!("A second launch asked for an unknown action"), } } @@ -221,7 +221,7 @@ impl DevNotesApp { tray::Asked::Capture => self.asked_from_outside(GlobalAction::Capture, ctx), tray::Asked::Palette => self.asked_from_outside(GlobalAction::Palette, ctx), tray::Asked::Quit => { - self.state.apply(Action::Global(GlobalAction::Quit), ctx, &self.backend); + self.state.act(Action::Global(GlobalAction::Quit), ctx, &self.backend); } } } @@ -420,7 +420,7 @@ impl eframe::App for DevNotesApp { actions.push(action); } for action in actions.drain() { - self.state.apply(action, ui.ctx(), &self.backend); + self.state.act(action, ui.ctx(), &self.backend); } } diff --git a/crates/ui/src/backend.rs b/crates/ui/src/backend.rs index 4c93bd95a..4e925a33d 100644 --- a/crates/ui/src/backend.rs +++ b/crates/ui/src/backend.rs @@ -7,6 +7,7 @@ //! - `compute`: pure work, on rayon's pool. //! - `spawn`: the network, on tokio. +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{self, Receiver, SyncSender, TryRecvError}; use std::sync::{Arc, Condvar, Mutex}; use std::time::Instant; @@ -39,6 +40,8 @@ pub struct Backend { runtime: tokio::runtime::Runtime, waker: Waker, in_flight: Arc, + /// The person's actions applied in this session: the last one's number. + actions: AtomicU64, } impl Backend { @@ -54,7 +57,13 @@ impl Backend { .enable_all() .build()?; let engine = Arc::new(Engine::new(paths, events, runtime.handle().clone())); - Ok(Self { engine, runtime, waker, in_flight: Arc::default() }) + Ok(Self { engine, runtime, waker, in_flight: Arc::default(), actions: AtomicU64::new(0) }) + } + + /// The number of the action about to be applied, from 1: what it asks of the core is said to + /// be its doing. + pub fn next_action(&self) -> u64 { + self.actions.fetch_add(1, Ordering::Relaxed) + 1 } pub fn engine(&self) -> &Arc { @@ -136,7 +145,7 @@ impl Backend { /// Tests only: how many jobs were ever launched, answered or not. #[cfg(test)] pub fn launched(&self) -> usize { - self.in_flight.launched.load(std::sync::atomic::Ordering::SeqCst) + self.in_flight.launched.load(Ordering::SeqCst) } } @@ -226,7 +235,7 @@ struct InFlight { impl InFlight { fn add(&self) { - self.launched.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + self.launched.fetch_add(1, Ordering::SeqCst); if let Ok(mut count) = self.count.lock() { *count += 1; } diff --git a/crates/ui/src/banners/update_prompt.rs b/crates/ui/src/banners/update_prompt.rs index 23945dcfd..cc99d5b57 100644 --- a/crates/ui/src/banners/update_prompt.rs +++ b/crates/ui/src/banners/update_prompt.rs @@ -26,7 +26,7 @@ pub(crate) struct UpdateView { } /// What the prompt asks. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] pub enum Ask { Check, /// The known update's offer, put away by « Later », shown again. diff --git a/crates/ui/src/gate/mod.rs b/crates/ui/src/gate/mod.rs index e59812d9e..810237fb4 100644 --- a/crates/ui/src/gate/mod.rs +++ b/crates/ui/src/gate/mod.rs @@ -19,7 +19,7 @@ use crate::services::errors::ErrorNotifier; use crate::services::status::StatusNotifier; /// What the gate's controls ask, applied at the end of the frame. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] pub enum Action { Submit, ToggleReveal, diff --git a/crates/ui/src/http/mod.rs b/crates/ui/src/http/mod.rs index 7529e67d5..4dd36e4fe 100644 --- a/crates/ui/src/http/mod.rs +++ b/crates/ui/src/http/mod.rs @@ -35,7 +35,7 @@ use crate::theme::{palette, spacing}; use crate::widgets::{self}; /// What the area's controls ask, applied at the end of the frame. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Action { /// A collection or a folder folded or unfolded. Toggle(String), diff --git a/crates/ui/src/notes/canvas/shortcuts.rs b/crates/ui/src/notes/canvas/shortcuts.rs index 2d22d473d..d323b416d 100644 --- a/crates/ui/src/notes/canvas/shortcuts.rs +++ b/crates/ui/src/notes/canvas/shortcuts.rs @@ -13,7 +13,7 @@ use crate::keys::{Binding, Read}; use crate::services::shortcuts::Bindings; /// What a key asks of the canvas; the card it acts on is the one with the focus. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] pub enum CanvasKey { New(NoteKind), Move(Direction), diff --git a/crates/ui/src/notes/mod.rs b/crates/ui/src/notes/mod.rs index c5ac9620b..1c5560fa8 100644 --- a/crates/ui/src/notes/mod.rs +++ b/crates/ui/src/notes/mod.rs @@ -30,7 +30,7 @@ use crate::state::drawing_pictures::Stamp; use destinations::Destination; /// What the area's controls ask, applied at the end of the frame. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Action { /// The view, asked again after it failed to load. Reload, @@ -174,7 +174,7 @@ pub struct DrawingExport { } /// What the editor's fields panel asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Fields { Keep(std::collections::BTreeMap), Preview { @@ -192,7 +192,7 @@ pub enum Fields { Fold(bool), } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Editing { /// A sheet's results shown to so many decimals; `None` reads the value. Decimals(Option), @@ -263,7 +263,7 @@ pub enum Editing { } /// What the history under the editor asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Revisions { Toggle, /// A kept body compared with the current text. @@ -274,7 +274,7 @@ pub enum Revisions { } /// What the `{{fields}}` form asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Fill { /// Filled with these, copied, and kept. Submit(std::collections::BTreeMap), @@ -284,7 +284,7 @@ pub enum Fill { } /// What the tag manager asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Tags { Open, Close, @@ -297,7 +297,7 @@ pub enum Tags { } /// What the trash panel asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Trash { Open, Close, @@ -311,7 +311,7 @@ pub enum Trash { } /// What a board gesture commits. Membership comes from the drop, and from nothing else. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum BoardGesture { /// `folder`: the zone under the card, `None` the ground, which files it in the board's root. DropCard { note_id: String, folder: Option, at: engine::folders::board::BoardPoint }, @@ -329,7 +329,7 @@ pub enum BoardGesture { } /// What the selection bar does to every ticked note at once. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Batch { MoveTo(Destination), Prioritise(engine::notes::priority::Priority), diff --git a/crates/ui/src/palette/mod.rs b/crates/ui/src/palette/mod.rs index f8122297b..8c591f4df 100644 --- a/crates/ui/src/palette/mod.rs +++ b/crates/ui/src/palette/mod.rs @@ -31,7 +31,7 @@ use options::{Chosen, Group, Item}; const WIDTH: f32 = 640.0; /// What the palette asks, applied at the end of the frame. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Asked { Type(String), Chip(Chip), diff --git a/crates/ui/src/state/attachments.rs b/crates/ui/src/state/attachments.rs index 3f4c7688e..64aa81a0f 100644 --- a/crates/ui/src/state/attachments.rs +++ b/crates/ui/src/state/attachments.rs @@ -36,7 +36,7 @@ pub fn is_shown(attachment: &Attachment) -> bool { } /// What the strip asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Asked { /// From the system's dialog. Pick, diff --git a/crates/ui/src/state/held.rs b/crates/ui/src/state/held.rs index 42ca6665a..0c284939e 100644 --- a/crates/ui/src/state/held.rs +++ b/crates/ui/src/state/held.rs @@ -26,8 +26,14 @@ pub(crate) fn held((backend, profile): (Backend, tempfile::TempDir)) -> Held { } impl Held { + /// As the frame's loop does, its name checked first: every action the state tests apply. pub(crate) fn apply(&mut self, action: Action) { - self.state.apply(action, &self.ctx, &self.backend); + let name = action.name(); + let named = name + .split("::") + .all(|part| !part.is_empty() && part.chars().all(char::is_alphanumeric)); + assert!(named, "{name:?} is no name"); + self.state.act(action, &self.ctx, &self.backend); self.settle(); } diff --git a/crates/ui/src/state/http/code.rs b/crates/ui/src/state/http/code.rs index 0baa71360..fbba7190f 100644 --- a/crates/ui/src/state/http/code.rs +++ b/crates/ui/src/state/http/code.rs @@ -22,7 +22,7 @@ pub enum Switch { } /// What the dialog asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Asked { /// On the tab it was opened from. Open(String), diff --git a/crates/ui/src/state/http/cookies.rs b/crates/ui/src/state/http/cookies.rs index e9e933476..9e16faf38 100644 --- a/crates/ui/src/state/http/cookies.rs +++ b/crates/ui/src/state/http/cookies.rs @@ -11,7 +11,7 @@ use crate::state::Revision; use crate::state::query::QueryCell; /// What the dialog asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Asked { Open, Close, diff --git a/crates/ui/src/state/http/environments.rs b/crates/ui/src/state/http/environments.rs index 0fcf2f2c8..2a49bab17 100644 --- a/crates/ui/src/state/http/environments.rs +++ b/crates/ui/src/state/http/environments.rs @@ -29,7 +29,7 @@ pub enum Target { } /// What the page asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Asked { Select(Target), Create(String), diff --git a/crates/ui/src/state/http/history.rs b/crates/ui/src/state/http/history.rs index e3c8dc96e..caad8ace4 100644 --- a/crates/ui/src/state/http/history.rs +++ b/crates/ui/src/state/http/history.rs @@ -13,7 +13,7 @@ use crate::state::query::QueryCell; use crate::state::undo::UNDO_WINDOW; /// What the page asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Asked { Select(String), Delete(String), diff --git a/crates/ui/src/state/http/leave.rs b/crates/ui/src/state/http/leave.rs index 262d617e1..9643e65b8 100644 --- a/crates/ui/src/state/http/leave.rs +++ b/crates/ui/src/state/http/leave.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] pub enum Asked { Cancel, Discard, diff --git a/crates/ui/src/state/http/mod.rs b/crates/ui/src/state/http/mod.rs index 5fe05760e..0ade4716d 100644 --- a/crates/ui/src/state/http/mod.rs +++ b/crates/ui/src/state/http/mod.rs @@ -50,7 +50,7 @@ pub const COLLAPSED_KEY: &str = "devnotes.notes.http.collapsed"; pub const MARK_SECONDS: f64 = crate::theme::motion::MARK as f64; /// A write the rail asked for. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Write { CreateCollection(String), /// At the collection's root when `folder_id` is `None`. diff --git a/crates/ui/src/state/http/runner.rs b/crates/ui/src/state/http/runner.rs index 864bab528..a9b0eb01c 100644 --- a/crates/ui/src/state/http/runner.rs +++ b/crates/ui/src/state/http/runner.rs @@ -86,7 +86,7 @@ pub struct DataFile { pub data: RunData, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Asked { Open(Target), Move { diff --git a/crates/ui/src/state/mod.rs b/crates/ui/src/state/mod.rs index ab24af93d..151cd328d 100644 --- a/crates/ui/src/state/mod.rs +++ b/crates/ui/src/state/mod.rs @@ -506,6 +506,13 @@ impl AppState { } } + /// The person's action, numbered and logged, then applied: what the frame's loop and the + /// outside (the tray, a second launch) call. `apply` logs nothing: an action may apply another. + pub fn act(&mut self, action: Action, ctx: &egui::Context, backend: &Backend) { + action.log(backend.next_action()); + self.apply(action, ctx, backend); + } + /// At the end of the frame, in the order the actions were pushed. pub fn apply(&mut self, action: Action, ctx: &egui::Context, backend: &Backend) { match action { diff --git a/crates/ui/src/testing.rs b/crates/ui/src/testing.rs index ddf3f6d3d..83b6d7062 100644 --- a/crates/ui/src/testing.rs +++ b/crates/ui/src/testing.rs @@ -236,6 +236,66 @@ pub(crate) fn serve() -> u16 { port } +/// A line our crates logged. +#[derive(Clone)] +pub(crate) struct Line { + pub(crate) thread: std::thread::ThreadId, + pub(crate) level: log::Level, + pub(crate) target: String, + pub(crate) text: String, +} + +/// The one logger of the crate's tests, set by the first that listens: tests run side by side, so +/// a test reads its own thread's lines, or looks for what it alone could have written. +pub(crate) struct Heard(std::sync::Mutex>); + +static HEARD: Heard = Heard(std::sync::Mutex::new(Vec::new())); + +impl log::Log for Heard { + fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { + let target = metadata.target(); + ["ui", "engine"] + .iter() + .any(|ours| target == *ours || target.starts_with(&format!("{ours}::"))) + } + + fn log(&self, record: &log::Record<'_>) { + if self.enabled(record.metadata()) { + self.0.lock().unwrap().push(Line { + thread: std::thread::current().id(), + level: record.level(), + target: record.target().to_owned(), + text: record.args().to_string(), + }); + } + } + + fn flush(&self) {} +} + +impl Heard { + /// Every line since the first test listened, whatever the thread. + pub(crate) fn lines(&self) -> Vec { + self.0.lock().unwrap().clone() + } + + /// What `target` was told on this thread, at its level. + pub(crate) fn here(&self, target: &str) -> Vec<(log::Level, String)> { + let thread = std::thread::current().id(); + let lines = self.0.lock().unwrap(); + let here = lines.iter().filter(|line| line.thread == thread && line.target == target); + here.map(|line| (line.level, line.text.clone())).collect() + } +} + +/// Every level of our crates, from now on. +pub(crate) fn listen() -> &'static Heard { + if log::set_logger(&HEARD).is_ok() { + log::set_max_level(log::LevelFilter::Trace); + } + &HEARD +} + /// A 4 × 4 PNG: what `/image` answers. fn picture() -> Vec { let mut bytes = std::io::Cursor::new(Vec::new()); diff --git a/crates/ui/src/titlebar/libraries.rs b/crates/ui/src/titlebar/libraries.rs index 7fe841b6e..e1a280aee 100644 --- a/crates/ui/src/titlebar/libraries.rs +++ b/crates/ui/src/titlebar/libraries.rs @@ -16,7 +16,7 @@ use crate::widgets::{self, Button, Kind, TextField}; const WIDTH: f32 = 560.0; /// What the panel asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Ask { Close, Create(String), diff --git a/crates/ui/src/titlebar/mod.rs b/crates/ui/src/titlebar/mod.rs index 2398b044c..81c060f9a 100644 --- a/crates/ui/src/titlebar/mod.rs +++ b/crates/ui/src/titlebar/mod.rs @@ -29,7 +29,7 @@ use crate::theme::{Appearance, palette}; use crate::widgets::{self, tooltip}; /// What the bar's menus ask. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Action { Import, ExportAll, diff --git a/crates/ui/src/titlebar/preferences/mod.rs b/crates/ui/src/titlebar/preferences/mod.rs index c05e830b2..a0103fbc4 100644 --- a/crates/ui/src/titlebar/preferences/mod.rs +++ b/crates/ui/src/titlebar/preferences/mod.rs @@ -31,7 +31,7 @@ const FOOTER: f32 = 56.0; const BUTTONS: f32 = 270.0; /// What the panel asks. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Ask { /// The theme or the density changed in the draft. Preview, diff --git a/crates/ui/src/titlebar/window.rs b/crates/ui/src/titlebar/window.rs index 4f5e53d13..9071d5a62 100644 --- a/crates/ui/src/titlebar/window.rs +++ b/crates/ui/src/titlebar/window.rs @@ -27,7 +27,7 @@ const EDGE: f32 = 4.0; const CORNER: f32 = 8.0; /// What the window is asked. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)] pub enum Ask { Minimize, /// Maximised, or restored: what it becomes. diff --git a/crates/ui/src/tools/mod.rs b/crates/ui/src/tools/mod.rs index dc5916d36..6cb55d838 100644 --- a/crates/ui/src/tools/mod.rs +++ b/crates/ui/src/tools/mod.rs @@ -28,7 +28,7 @@ use live::Turn; use ui::note_picker::{self, PickedNote, Picker}; /// What the area's controls ask, applied at the end of the frame. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] pub enum Action { /// The whole catalogue, one category of it, or the favourites. Home(Option), diff --git a/docs/architecture/interface.md b/docs/architecture/interface.md index 96d900412..3f5461f13 100644 --- a/docs/architecture/interface.md +++ b/docs/architecture/interface.md @@ -51,7 +51,9 @@ text being typed, editor buffers, open menus, scroll, gestures); everything else is an `Action` it pushes, applied by `AppState::apply` at the end of the frame (D13). Data flows down as arguments, so a screen is tested with a literal; an action goes straight to the state that owns it rather than up through its parents. `widgets/` is the exception that pushes nothing -and reads no state: it is the kit (→ "The widget kit"). +and reads no state: it is the kit (→ "The widget kit"). The frame's loop, the tray and a second +launch hand each action to `AppState::act`, which logs its name and number, then applies it +(→ "What the person did"). A card cannot decide what its own click means — ticking, extending a range or opening depends on the visible list — so it answers what was pressed and the canvas decides. diff --git a/docs/architecture/logs.md b/docs/architecture/logs.md index ee78ff807..eac6fcaac 100644 --- a/docs/architecture/logs.md +++ b/docs/architecture/logs.md @@ -40,6 +40,27 @@ is in it. A panic is logged by its place and its thread, never its message. ⚠ value that carries content: a derived `Debug` prints the payload, a checklist's items or a request's URL. +## What the person did + +Each action of the person — a click, a key, a menu, the palette, the tray, a second launch — is +logged once, at `info`, as it is applied: its number in the session, then its name. + +```text +2026-12-04 10:12:05.031 INFO [main] ui::action: #412 Notes::Editor::Close +``` + +`AppState::act` numbers it (`Backend::next_action`, which a call to the core can read), logs it, +then applies it: the frame's loop, the tray and a second launch call it, never `apply`, which one +action may call again for another. The name is `Action::name`, the variants alone, read by +`strum::IntoStaticStr`: the area, the variant, and, for a variant that carries what is asked of a +part of the area, that part's own (`Http::Runner::Start`, `Notes::Editor::Fields::Keep`). A new +action is logged without a line for it, and never its payload, not even an id. + +What is sent at each key typed, or by the screen as it shows a card — a search, a request's draft, +a drawing's picture —, is at `trace`, by the list `FREQUENT` beside `name`, so that the terminal +reads as what the person did; `ui::action=trace` in `DEVNOTES_LOG` shows it. In a session's log, what +follows `#412` was done by that action or after it, and its number goes up by one each time. + ## Changing the levels for one run `DEVNOTES_LOG`, in `flexi_logger`'s syntax, replaces the levels for one run, in any build: