From c9787dac833f1b545491815ab8654e94262a2837 Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-perception: add ui module --- crates/capri-perception/src/ui.rs | 193 ++++++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 crates/capri-perception/src/ui.rs diff --git a/crates/capri-perception/src/ui.rs b/crates/capri-perception/src/ui.rs new file mode 100644 index 0000000..89ed1a4 --- /dev/null +++ b/crates/capri-perception/src/ui.rs @@ -0,0 +1,193 @@ +//! Plain egui settings pages: Screen snapshot / observation, Initiative, Resources. +//! Screen buttons return [`ScreenRequest`]s (carrying the owner's [`UserGesture`]) for the app +//! to run on its runtime against [`crate::ScreenController`]. +use capri_core::SettingsStore; +use serde_json::Value; +use uuid::Uuid; + +use crate::policy::{SourceEntry, SourceKind, UserGesture}; +use crate::settings::{InitiativeSettings, Level, ResourceSettings, ScreenSettings}; + +pub enum ScreenRequest { + Refresh, + Capture(Uuid, UserGesture), + Start { source: Uuid, interval_ms: u64, duration_ms: u64, gesture: UserGesture }, + Stop, + OpenFolder, +} + +/// Picker state kept by the app between frames. +#[derive(Default)] +pub struct ScreenPanel { + pub sources: Vec, + pub selected: Option, +} + +fn save(store: &SettingsStore, value: &T) { + if let Err(e) = store.set_section(value) { + tracing::warn!("Settings not saved: {e}"); + } +} + +/// All three pages; `status` is `ScreenController::status` (capture + observation snapshot). +pub fn settings_ui(ui: &mut egui::Ui, store: &SettingsStore, panel: &mut ScreenPanel, status: &Value, initiative_status: &Value) -> Vec { + let mut requests = vec![]; + egui::CollapsingHeader::new("Screen snapshot").default_open(true).show(ui, |ui| requests = screen_page(ui, store, panel, status)); + egui::CollapsingHeader::new("Initiative").show(ui, |ui| initiative_page(ui, store, initiative_status)); + egui::CollapsingHeader::new("Resources").show(ui, |ui| resources_page(ui, store)); + requests +} + +pub fn screen_page(ui: &mut egui::Ui, store: &SettingsStore, panel: &mut ScreenPanel, status: &Value) -> Vec { + let mut out = vec![]; + let running = status["observation"]["active"] == true; + let mut s: ScreenSettings = store.section(); + let (mut secs, mut mins) = (s.interval_ms / 1000, s.duration_ms as f64 / 60_000.0); + ui.add_enabled_ui(!running, |ui| { + ui.add(egui::Slider::new(&mut secs, 15..=300).text("Interval (seconds)")); + ui.add(egui::Slider::new(&mut mins, 0.5..=120.0).step_by(0.5).text("Duration (minutes)")); + egui::ComboBox::from_label("Source") + .selected_text(panel.selected.and_then(|id| panel.sources.iter().find(|e| e.id == id)).map_or("Choose a window or monitor…".into(), label)) + .show_ui(ui, |ui| { + for e in &panel.sources { + ui.selectable_value(&mut panel.selected, Some(e.id), label(e)); + } + }); + if ui.button("Refresh sources").clicked() { + out.push(ScreenRequest::Refresh); + } + }); + let next = ScreenSettings { interval_ms: secs * 1000, duration_ms: (mins * 60_000.0) as u64 }.clamped(); + if next != s { + s = next; + save(store, &s); + } + if running { + ui.label("Stop observation before changing its interval or duration."); + } + ui.horizontal(|ui| { + if let Some(id) = panel.selected.filter(|_| !running) { + if ui.button("Capture").clicked() { + out.push(ScreenRequest::Capture(id, UserGesture::owner_clicked())); + } + if ui.button("Start observation").clicked() { + out.push(ScreenRequest::Start { source: id, interval_ms: s.interval_ms, duration_ms: s.duration_ms, gesture: UserGesture::owner_clicked() }); + } + } + if (running || status["capture"]["active"] == true) && ui.button("Stop screen access").clicked() { + out.push(ScreenRequest::Stop); + } + if ui.button("Open screenshots folder").clicked() { + out.push(ScreenRequest::OpenFolder); + } + }); + ui.label(observation_status(&status["observation"])); + ui.small("Observation stays on when this panel closes. OBS stops it immediately. Hiding Capri, locking the session or reaching the time limit also stops it. It never resumes automatically."); + out +} + +fn label(e: &SourceEntry) -> String { + match e.kind { + SourceKind::Window => format!("Window: {}", e.label), + SourceKind::Monitor => format!("Monitor: {}", e.label), + SourceKind::Monitors => "All monitors".into(), + } +} + +/// Capri's status line (`screen-panel.mjs`). +pub fn observation_status(o: &Value) -> String { + if let Some(w) = o["warning"].as_str() { + return w.into(); + } + if o["active"] != true { + return "Screen observation is off.".into(); + } + if o["analysing"] == true { + return "Analysing selected source…".into(); + } + if let Some(e) = o["error"].as_str() { + return e.into(); + } + match o["lastAnalysedAt"].as_i64().and_then(chrono::DateTime::from_timestamp_millis) { + None => "Waiting for an idle moment to analyse.".into(), + Some(t) => format!( + "Last screen update: {}{}", + t.with_timezone(&chrono::Local).format("%H:%M:%S"), + if o["changed"] == true { " · View changed; waiting for next update" } else { "" } + ), + } +} + +pub fn initiative_page(ui: &mut egui::Ui, store: &SettingsStore, status: &Value) { + let before: InitiativeSettings = store.section(); + let mut s = before.clone(); + ui.horizontal(|ui| { + for (level, name) in [(Level::Off, "Off"), (Level::Occasional, "Occasional"), (Level::Conversational, "Conversational")] { + if ui.selectable_label(s.level == level, name).clicked() { + s.level = level; + s.hourly_limit = None; // selecting a level clears the custom limit + } + } + }); + ui.add_enabled_ui(s.level != Level::Off, |ui| { + let mut limit = s.hourly_limit.unwrap_or(s.limit() as u8); + if ui.add(egui::Slider::new(&mut limit, 1..=30).text("Comments per hour")).changed() { + s.hourly_limit = Some(limit); + } + ui.checkbox(&mut s.spontaneous, "Spontaneous comments"); + ui.checkbox(&mut s.return_reactions, "React when I come back"); + ui.checkbox(&mut s.app_reactions, "React to media apps"); + ui.checkbox(&mut s.quiet_hours_enabled, "Quiet hours"); + ui.add_enabled_ui(s.quiet_hours_enabled, |ui| { + ui.add(egui::Slider::new(&mut s.quiet_start, 0..=23).text("Quiet from")); + ui.add(egui::Slider::new(&mut s.quiet_end, 0..=23).text("Quiet until")); + }); + let mut apps = s.excluded_apps.join(", "); + ui.label("Stay quiet while these apps are in front:"); + if ui.text_edit_singleline(&mut apps).lost_focus() { + s.excluded_apps = apps.split(',').map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).collect(); + } + }); + let s = s.validated(); + if s != before { + save(store, &s); + } + let reason = status["reason"].as_str().unwrap_or("waiting").replace('_', " "); + let next = status["nextAt"].as_i64().filter(|t| *t > crate::now_ms()).and_then(chrono::DateTime::from_timestamp_millis).map(|t| format!(" · Next attempt: {}", t.with_timezone(&chrono::Local).format("%H:%M"))).unwrap_or_default(); + ui.label(format!("Initiative status: {reason}{next}")); + ui.small("Supported media apps: VLC, mpv, Spotify, Celluloid, Haruna and Videos. Opening an app does not prove that anything is playing. Comments never control music, apps or files."); +} + +pub fn resources_page(ui: &mut egui::Ui, store: &SettingsStore) { + let before: ResourceSettings = store.section(); + let mut s = before.clone(); + ui.checkbox(&mut s.memory_monitor, "Resource monitor"); + ui.checkbox(&mut s.process_graphs, "Graphs and Capri process load"); + ui.horizontal(|ui| { + ui.selectable_value(&mut s.memory_style, "rings".into(), "Circles"); + ui.selectable_value(&mut s.memory_style, "bars".into(), "Bars"); + }); + ui.horizontal(|ui| { + ui.label("Refresh every"); + for n in [3u8, 5, 10] { + ui.selectable_value(&mut s.memory_interval_seconds, n, format!("{n} s")); + } + }); + if s != before { + save(store, &s); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn status_lines() { + assert_eq!(observation_status(&json!({"active": false})), "Screen observation is off."); + assert_eq!(observation_status(&json!({"active": true})), "Waiting for an idle moment to analyse."); + assert_eq!(observation_status(&json!({"active": true, "warning": "W"})), "W"); + assert!(observation_status(&json!({"active": true, "lastAnalysedAt": 1, "changed": true})).ends_with("waiting for next update")); + } +}