mod app;
mod columns;
mod detail;
mod events;
mod glyph;
mod journal;
mod render;
mod terminal;
mod theme;
mod view;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::time::Duration;
use blubat_core::{Config, Paths, Poll, Tiers, Timestamp};
use crate::effects::{Effects, Observed};
use crate::hooks::Outcome;
use crate::{Failure, lock};
use app::{App, Event, Notice, update};
use glyph::Glyphs;
use theme::Look;
const DASHBOARD_INTERVAL: Duration = Duration::from_secs(5);
const REDRAW: Duration = Duration::from_millis(250);
pub fn run(paths: &Paths) -> Result<(), Failure> {
let (dashboard, unlocked) = claim(paths);
let owned = dashboard.is_some();
let (config, unreadable) = load(paths);
let tiers = tiers(&config.poll);
let (notes, events) = events::events(blubat_core::poll(tiers));
let (effects, stale_state) = Effects::live(paths, reporter(notes));
let mut effects = effects.deferring_to(move || !owned);
let mut session = terminal::Session::open()?;
let mut app = App {
notice: notice([unreadable, stale_state, unlocked]),
advertised: effects.advertised().clone(),
..App::new(
tiers.fast,
Timestamp::now(),
Look::of(&config.theme, Glyphs::detected()),
config,
)
};
while app.running {
session.draw(&app)?;
let Some(event) = next(&events) else { break };
let observed = match &event {
Event::Reading(reading) => effects.observe(reading, &app.config),
_ => Observed::default(),
};
app = update(app, event);
if !observed.raised.is_empty() {
app = update(app, Event::Raised(observed.raised));
}
if !observed.problems.is_empty() {
app = update(
app,
Event::Note(Notice::problem(observed.problems.join("; "))),
);
}
if app.reload {
app = update(app, Event::Reloaded(effects.reload()));
}
if app.save_hidden {
let written = effects.save_hidden(&app.view.hidden);
app = update(app, Event::Saved(written));
}
}
Ok(())
}
fn claim(paths: &Paths) -> (Option<lock::Held>, Option<String>) {
match lock::take(&paths.tui_lock()) {
Ok(Some(held)) => (Some(held), None),
Ok(None) => (
None,
Some("another blubat owns the notifications and hooks".to_string()),
),
Err(problem) => (None, Some(problem)),
}
}
fn load(paths: &Paths) -> (Config, Option<String>) {
Config::load(paths.config_file()).map_or_else(
|error| (Config::default(), Some(error.to_string())),
|config| (config, None),
)
}
fn tiers(poll: &Poll) -> Tiers {
let asked_for = poll.foreground_interval != Poll::default().foreground_interval;
Tiers {
fast: if asked_for {
poll.foreground_interval
} else {
DASHBOARD_INTERVAL
},
slow: poll.profiler_interval,
timeout: poll.profiler_timeout,
}
}
fn notice(problems: [Option<String>; 3]) -> Option<Notice> {
let problems: Vec<String> = problems.into_iter().flatten().collect();
(!problems.is_empty()).then(|| Notice::problem(problems.join("; ")))
}
fn reporter(notes: Sender<Event>) -> impl Fn(Outcome) + Send + Sync + 'static {
move |outcome| {
if outcome.went_wrong() {
let _ = notes.send(Event::Note(Notice::problem(outcome.to_string())));
}
}
}
fn next(events: &Receiver<Event>) -> Option<Event> {
match events.recv_timeout(REDRAW) {
Ok(event) => Some(event),
Err(RecvTimeoutError::Timeout) => Some(Event::Tick(Timestamp::now())),
Err(RecvTimeoutError::Disconnected) => None,
}
}
#[cfg(test)]
mod tests {
use crate::scratch::Scratch;
use super::*;
fn poll(written: &str) -> Poll {
Config::parse(written).expect("the test config parses").poll
}
#[test]
fn a_second_dashboard_hands_the_side_effects_to_the_first() {
let scratch = Scratch::new();
let paths = scratch.paths();
let (first, quiet) = claim(&paths);
let (second, deferring) = claim(&paths);
assert!(first.is_some());
assert_eq!(quiet, None);
assert!(second.is_none(), "the first one up keeps them");
assert!(
deferring.is_some_and(|line| line.contains("another blubat")),
"and the second one says so"
);
assert!(
lock::held(&paths.tui_lock()),
"the file the daemon checks is the file the dashboard took"
);
}
#[test]
fn the_dashboard_closing_hands_the_side_effects_back() {
let scratch = Scratch::new();
let paths = scratch.paths();
let (first, _) = claim(&paths);
drop(first);
assert!(!lock::held(&paths.tui_lock()));
assert!(claim(&paths).0.is_some());
}
#[test]
fn the_dashboard_polls_faster_than_the_core_default_it_overrides() {
assert!(DASHBOARD_INTERVAL < Tiers::default().fast);
assert!(
REDRAW < DASHBOARD_INTERVAL,
"the countdown has to move between readings"
);
}
#[test]
fn an_unconfigured_dashboard_keeps_its_own_faster_interval() {
assert_eq!(tiers(&Poll::default()).fast, DASHBOARD_INTERVAL);
assert_eq!(
tiers(&poll("[poll]\nforeground_interval = \"30s\"\n")).fast,
DASHBOARD_INTERVAL,
"a file repeating the default back is a file that asked for nothing"
);
}
#[test]
fn an_interval_the_file_asks_for_is_the_one_it_gets() {
let configured = tiers(&poll(
"[poll]\nforeground_interval = \"90s\"\nprofiler_interval = \"10m\"\n",
));
assert_eq!(configured.fast, Duration::from_secs(90));
assert_eq!(
configured.slow,
Duration::from_secs(600),
"the slow tier is the file's either way: the dashboard has no view \
on how often system_profiler is worth calling"
);
}
#[test]
fn a_startup_problem_becomes_one_line_and_a_clean_start_becomes_none() {
assert_eq!(notice([None, None, None]), None);
assert_eq!(
notice([Some("config.toml: line 3".to_string()), None, None]),
Some(Notice::problem("config.toml: line 3"))
);
assert_eq!(
notice([
Some("bad config".to_string()),
Some("bad state".to_string()),
Some("no lock".to_string())
])
.map(|notice| notice.text),
Some("bad config; bad state; no lock".to_string())
);
}
#[test]
fn a_quiet_channel_becomes_a_redraw_rather_than_a_wait() {
let (sender, events) = std::sync::mpsc::channel();
assert!(matches!(next(&events), Some(Event::Tick(_))));
drop(sender);
assert_eq!(next(&events), None, "nothing can change once both are gone");
}
#[test]
fn only_a_hook_that_went_wrong_is_worth_a_line() {
let (notes, reported) = std::sync::mpsc::channel();
let report = reporter(notes);
let outcome = |ran| Outcome {
command: String::from("~/bin/nag"),
event: blubat_core::Event::LowBattery,
device: String::from("Trackpad"),
ran,
};
report(outcome(crate::hooks::Ran::Exited(0)));
report(outcome(crate::hooks::Ran::TimedOut));
assert_eq!(
reported.try_iter().collect::<Vec<_>>(),
[Event::Note(Notice::problem(
"low_battery hook `~/bin/nag` for Trackpad: timed out and was killed"
))]
);
}
}