Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions crates/ui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
197 changes: 194 additions & 3 deletions crates/ui/src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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),
Expand All @@ -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,
Expand Down Expand Up @@ -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<u64>, Vec<(log::Level, &str)>) = lines
.iter()
.map(|(level, text)| {
let (number, name) = text.strip_prefix('#').unwrap().split_once(' ').unwrap();
(number.parse::<u64>().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<String> = 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() {
Expand Down
27 changes: 4 additions & 23 deletions crates/ui/src/api/preferences.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<String>>);

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.
Expand All @@ -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<String> = warned.map(|line| line.text).collect();
assert!(said.iter().any(|text| text.contains("preferences")), "{said:?}");
}
}
8 changes: 4 additions & 4 deletions crates/ui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"),
}
}
Expand All @@ -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);
}
}
}
Expand Down Expand Up @@ -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);
}
}

Expand Down
15 changes: 12 additions & 3 deletions crates/ui/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -39,6 +40,8 @@ pub struct Backend {
runtime: tokio::runtime::Runtime,
waker: Waker,
in_flight: Arc<InFlight>,
/// The person's actions applied in this session: the last one's number.
actions: AtomicU64,
}

impl Backend {
Expand All @@ -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<Engine> {
Expand Down Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ui/src/banners/update_prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion crates/ui/src/gate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading