mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 23:36:11 +00:00
feat(gui): native Slint GUI with ksni tray, replacing grove-bridge
Folds the bridge library into grove-gui (src/bridge.rs) and drops the HTTP server. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0884d556ce
commit
fe2999d5b0
13 files changed
+6753
-215
No files matched your search
@@ -1,12 +0,0 @@
|
||||
[package]
|
||||
name = "grove-bridge"
|
||||
description = "Backend of the grove GUI: daemon IPC + allow-listed CLI calls, and a localhost dev server"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
grove-daemon = { version = "0.1.0", path = "../grove-daemon" }
|
||||
serde_json = "1.0.154"
|
||||
toml = "1.2.1"
|
||||
@@ -1,155 +0,0 @@
|
||||
//! Localhost dev server for the GUI frontend: static files plus the `Bridge` calls over HTTP.
|
||||
//! Binds to 127.0.0.1 only. POSTs need the `X-Grove: 1` header (not sendable cross-origin
|
||||
//! without a preflight, which is never answered); the Host must be exactly 127.0.0.1:<port> or
|
||||
//! localhost:<port> and any Origin must match too (DNS rebinding).
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use grove_bridge::Bridge;
|
||||
use serde_json::{Value, json};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn arg(name: &str) -> Option<String> {
|
||||
let a: Vec<String> = std::env::args().collect();
|
||||
a.iter()
|
||||
.position(|x| x == name)
|
||||
.and_then(|i| a.get(i + 1))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let ui = PathBuf::from(arg("--ui").unwrap_or_else(|| "gui/ui".into()));
|
||||
let port: u16 = arg("--port")
|
||||
.map_or(Ok(4780), |p| p.parse())
|
||||
.context("bad --port")?;
|
||||
let bridge = Arc::new(Bridge {
|
||||
grove_bin: arg("--grove-bin").map_or_else(|| "grove".into(), PathBuf::from),
|
||||
config: arg("--config").map(PathBuf::from),
|
||||
socket: arg("--socket")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(grove_daemon::ipc::default_socket_path),
|
||||
});
|
||||
let l = TcpListener::bind(("127.0.0.1", port)).with_context(|| format!("port {port}"))?;
|
||||
eprintln!(
|
||||
"grove GUI dev server on http://127.0.0.1:{port}/ (ui: {})",
|
||||
ui.display()
|
||||
);
|
||||
for s in l.incoming().filter_map(Result::ok) {
|
||||
let (b, ui) = (bridge.clone(), ui.clone());
|
||||
let _ = s.set_read_timeout(Some(std::time::Duration::from_secs(10)));
|
||||
std::thread::spawn(move || {
|
||||
let _ = handle(s, &b, &ui, port);
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn respond(s: &mut TcpStream, status: &str, ctype: &str, body: &[u8]) -> std::io::Result<()> {
|
||||
write!(
|
||||
s,
|
||||
"HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
)?;
|
||||
s.write_all(body)
|
||||
}
|
||||
|
||||
fn handle(mut s: TcpStream, b: &Bridge, ui: &std::path::Path, port: u16) -> std::io::Result<()> {
|
||||
// Cap what a client can make us buffer while reading the request head.
|
||||
let mut r = BufReader::new(s.try_clone()?.take(64 * 1024));
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line)?;
|
||||
let mut it = line.split_whitespace();
|
||||
let (method, path) = (
|
||||
it.next().unwrap_or("").to_string(),
|
||||
it.next().unwrap_or("/").to_string(),
|
||||
);
|
||||
let (mut len, mut host, mut marker, mut origin) = (0usize, String::new(), false, None);
|
||||
loop {
|
||||
let mut h = String::new();
|
||||
if r.read_line(&mut h)? == 0 || h.trim().is_empty() {
|
||||
break;
|
||||
}
|
||||
let lower = h.to_ascii_lowercase();
|
||||
if let Some(v) = lower.strip_prefix("content-length:") {
|
||||
len = v.trim().parse().unwrap_or(0);
|
||||
} else if let Some(v) = lower.strip_prefix("host:") {
|
||||
host = v.trim().to_string();
|
||||
} else if let Some(v) = lower.strip_prefix("origin:") {
|
||||
origin = Some(v.trim().to_string());
|
||||
} else if lower.starts_with("x-grove:") {
|
||||
marker = true;
|
||||
}
|
||||
}
|
||||
// Exact match: a prefix check would accept `localhost.evil.com` (DNS rebinding).
|
||||
let local = [format!("127.0.0.1:{port}"), format!("localhost:{port}")];
|
||||
if !local.contains(&host) {
|
||||
return respond(&mut s, "403 Forbidden", "text/plain", b"bad host");
|
||||
}
|
||||
if let Some(o) = &origin
|
||||
&& !local.iter().any(|h| *o == format!("http://{h}"))
|
||||
{
|
||||
return respond(&mut s, "403 Forbidden", "text/plain", b"bad origin");
|
||||
}
|
||||
if method == "POST" {
|
||||
if !marker || len > 1 << 20 {
|
||||
return respond(&mut s, "403 Forbidden", "text/plain", b"forbidden");
|
||||
}
|
||||
r.get_mut().set_limit(1 << 20); // head parsed; allow the (capped) body
|
||||
let mut body = vec![0u8; len];
|
||||
r.read_exact(&mut body)?;
|
||||
let req: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
|
||||
let out = match path.as_str() {
|
||||
"/api/ipc" => b.ipc(&req),
|
||||
"/api/cli" => {
|
||||
let args: Vec<String> = req["args"]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
b.cli(&args, req["stdin"].as_str().unwrap_or(""))
|
||||
}
|
||||
_ => return respond(&mut s, "404 Not Found", "text/plain", b"not found"),
|
||||
};
|
||||
return respond(
|
||||
&mut s,
|
||||
"200 OK",
|
||||
"application/json",
|
||||
out.to_string().as_bytes(),
|
||||
);
|
||||
}
|
||||
if path == "/api/config" {
|
||||
let body = match b.config_json() {
|
||||
Some(c) => json!({"exists": true, "config": c}),
|
||||
None => json!({"exists": false}),
|
||||
};
|
||||
return respond(
|
||||
&mut s,
|
||||
"200 OK",
|
||||
"application/json",
|
||||
body.to_string().as_bytes(),
|
||||
);
|
||||
}
|
||||
let name = match path.split('?').next().unwrap_or("/") {
|
||||
"/" => "index.html",
|
||||
p => p.trim_start_matches('/'),
|
||||
};
|
||||
if name.contains("..") {
|
||||
return respond(&mut s, "403 Forbidden", "text/plain", b"forbidden");
|
||||
}
|
||||
let ctype = match name.rsplit('.').next() {
|
||||
Some("html") => "text/html; charset=utf-8",
|
||||
Some("js") => "text/javascript; charset=utf-8",
|
||||
Some("css") => "text/css; charset=utf-8",
|
||||
Some("svg") => "image/svg+xml",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
match std::fs::read(ui.join(name)) {
|
||||
Ok(data) => respond(&mut s, "200 OK", ctype, &data),
|
||||
Err(_) => respond(&mut s, "404 Not Found", "text/plain", b"not found"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "grove-gui"
|
||||
description = "Native desktop GUI for grove: tray icon, window, daemon IPC"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "grove-gui"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
grove-daemon = { version = "0.1.0", path = "../grove-daemon" }
|
||||
# async-io instead of the default tokio: no second async runtime in a small tray app.
|
||||
ksni = { version = "0.3.7", default-features = false, features = ["async-io", "blocking"] }
|
||||
serde_json = "1.0.154"
|
||||
slint = { version = "=1.18.1", default-features = false, features = ["std", "backend-winit", "renderer-software", "compat-1-2"] }
|
||||
toml = "1.2.1"
|
||||
|
||||
[build-dependencies]
|
||||
slint-build = "=1.18.1"
|
||||
@@ -0,0 +1,5 @@
|
||||
fn main() {
|
||||
// `fluent` is a pure-Slint style: no Qt needed on the machine.
|
||||
let config = slint_build::CompilerConfiguration::new().with_style("fluent".into());
|
||||
slint_build::compile_with_config("ui/app.slint", config).expect("slint compile");
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Everything the GUI needs from the machine, behind three calls. The Tauri shell and the
|
||||
//! localhost dev server both expose exactly these.
|
||||
//! Everything the GUI needs from the machine: daemon IPC, allow-listed `grove` calls, config.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use std::io::Write;
|
||||
@@ -91,7 +90,18 @@ impl Bridge {
|
||||
/// Per-command flag table: (flags without value, flags taking one value).
|
||||
fn flag_spec(sub: &str) -> (&'static [&'static str], &'static [&'static str]) {
|
||||
match sub {
|
||||
"init" => (&[], &["--machine", "--root", "--provider", "--kind", "--group", "--config-repo", "--url"]),
|
||||
"init" => (
|
||||
&[],
|
||||
&[
|
||||
"--machine",
|
||||
"--root",
|
||||
"--provider",
|
||||
"--kind",
|
||||
"--group",
|
||||
"--config-repo",
|
||||
"--url",
|
||||
],
|
||||
),
|
||||
"new" => (&["--public"], &[]),
|
||||
"resolve" => (&["--take-remote", "--keep-local"], &["--save-as"]),
|
||||
_ => (&[], &[]),
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Single instance: the first process listens on a Unix socket; a second launch asks it to show
|
||||
//! its window and exits.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::{UnixListener, UnixStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// `$XDG_RUNTIME_DIR/grove/gui.sock` (same private directory as the daemon socket).
|
||||
pub fn default_socket_path() -> PathBuf {
|
||||
let base = std::env::var_os("XDG_RUNTIME_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(std::env::temp_dir);
|
||||
base.join("grove").join("gui.sock")
|
||||
}
|
||||
|
||||
pub enum Role {
|
||||
/// Another instance is running and has been told to show (or ignore, when `show` is false).
|
||||
Secondary,
|
||||
/// This process owns the socket.
|
||||
Primary(UnixListener),
|
||||
}
|
||||
|
||||
/// Tries to hand over to a running instance; otherwise becomes the primary one.
|
||||
pub fn acquire(path: &Path, show: bool) -> std::io::Result<Role> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
for _ in 0..3 {
|
||||
if notify(path, if show { "show" } else { "ping" }).is_ok() {
|
||||
return Ok(Role::Secondary);
|
||||
}
|
||||
// Nobody answers: a stale socket from a crash is replaced.
|
||||
let _ = std::fs::remove_file(path);
|
||||
match UnixListener::bind(path) {
|
||||
Ok(l) => return Ok(Role::Primary(l)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Err(std::io::Error::other("cannot acquire the instance socket"))
|
||||
}
|
||||
|
||||
fn notify(path: &Path, msg: &str) -> std::io::Result<()> {
|
||||
let mut c = UnixStream::connect(path)?;
|
||||
c.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
writeln!(c, "{msg}")?;
|
||||
let mut line = String::new();
|
||||
BufReader::new(c).read_line(&mut line)?;
|
||||
if line.trim() == "ok" {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::other("unexpected answer"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Serves the primary socket forever; calls `on_show` for every `show` request.
|
||||
pub fn serve(listener: UnixListener, on_show: impl Fn() + Send + 'static) {
|
||||
for conn in listener.incoming().flatten() {
|
||||
let _ = conn.set_read_timeout(Some(Duration::from_secs(2)));
|
||||
let mut line = String::new();
|
||||
let mut conn = BufReader::new(conn);
|
||||
if conn.read_line(&mut line).is_err() {
|
||||
continue;
|
||||
}
|
||||
if line.trim() == "show" {
|
||||
on_show();
|
||||
}
|
||||
let _ = writeln!(conn.get_mut(), "ok");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::mpsc;
|
||||
|
||||
fn tmp_sock(tag: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("gg-{tag}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d.join("gui.sock")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_launch_asks_first_to_show() {
|
||||
let p = tmp_sock("show");
|
||||
let Role::Primary(l) = acquire(&p, true).unwrap() else {
|
||||
panic!("first must be primary");
|
||||
};
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || serve(l, move || tx.send(()).unwrap()));
|
||||
assert!(matches!(acquire(&p, true).unwrap(), Role::Secondary));
|
||||
rx.recv_timeout(Duration::from_secs(2))
|
||||
.expect("show callback");
|
||||
// A hidden (autostart) relaunch does not pop the window.
|
||||
assert!(matches!(acquire(&p, false).unwrap(), Role::Secondary));
|
||||
assert!(rx.recv_timeout(Duration::from_millis(200)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_socket_is_replaced() {
|
||||
let p = tmp_sock("stale");
|
||||
drop(UnixListener::bind(&p).unwrap()); // leaves the socket file behind
|
||||
assert!(p.exists());
|
||||
assert!(matches!(acquire(&p, true).unwrap(), Role::Primary(_)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
//! grove-gui: native desktop GUI (Slint) with a StatusNotifierItem tray.
|
||||
//!
|
||||
//! Threads: the Slint event loop (main), a worker that polls the daemon, a subscriber that wakes
|
||||
//! the worker on daemon events, the tray service, the single-instance listener, and short-lived
|
||||
//! threads for CLI calls. Nothing runs on a timer while the daemon is quiet.
|
||||
|
||||
mod bridge;
|
||||
mod instance;
|
||||
mod model;
|
||||
mod tray;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use bridge::Bridge;
|
||||
use model::{Aggregate, TrayState};
|
||||
use serde_json::{Value, json};
|
||||
use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel, Weak};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use tray::Action;
|
||||
|
||||
slint::include_modules!();
|
||||
|
||||
/// Fallback poll interval; daemon events wake the worker earlier.
|
||||
const POLL_VISIBLE: Duration = Duration::from_secs(5);
|
||||
const POLL_HIDDEN: Duration = Duration::from_secs(30);
|
||||
const MIN_GAP: Duration = Duration::from_millis(500);
|
||||
const RECONNECT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Everything the UI shows, taken from one refresh.
|
||||
struct Snapshot {
|
||||
status: Option<Value>,
|
||||
log: Vec<Value>,
|
||||
config: Option<Value>,
|
||||
alerts: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// State shared between threads.
|
||||
struct Core {
|
||||
bridge: Bridge,
|
||||
tx: Mutex<Sender<()>>,
|
||||
paused: AtomicBool,
|
||||
visible: AtomicBool,
|
||||
tray_ok: AtomicBool,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
fn wake(&self) {
|
||||
let _ = self.tx.lock().unwrap().send(());
|
||||
}
|
||||
|
||||
fn set_visible(&self, v: bool) {
|
||||
self.visible.store(v, Ordering::SeqCst);
|
||||
let _ = self.tx.lock().unwrap().send(());
|
||||
}
|
||||
|
||||
/// Fire-and-forget daemon command; `then` runs on the UI thread with the answer.
|
||||
fn ipc_bg(self: &Arc<Self>, req: Value, then: impl FnOnce(&Value) + Send + 'static) {
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
let r = core.bridge.ipc(&req);
|
||||
let _ = slint::invoke_from_event_loop(move || then(&r));
|
||||
core.wake();
|
||||
});
|
||||
}
|
||||
|
||||
fn toggle_pause(self: &Arc<Self>) {
|
||||
let cmd = if self.paused.load(Ordering::SeqCst) {
|
||||
"resume"
|
||||
} else {
|
||||
"pause"
|
||||
};
|
||||
self.ipc_bg(json!({"v": 1, "cmd": cmd}), |_| {});
|
||||
}
|
||||
|
||||
fn sync(self: &Arc<Self>, repo: Option<&str>, weak: Weak<MainWindow>) {
|
||||
let mut req = json!({"v": 1, "cmd": "sync"});
|
||||
let msg = if let Some(r) = repo {
|
||||
req["repo"] = json!(r);
|
||||
"Sync queued"
|
||||
} else {
|
||||
"Sync queued for all repositories"
|
||||
};
|
||||
self.ipc_bg(req, move |r| {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
let ok = r["ok"] == true;
|
||||
toast(
|
||||
&ui,
|
||||
if ok {
|
||||
msg
|
||||
} else {
|
||||
r["error"].as_str().unwrap_or("failed")
|
||||
},
|
||||
!ok,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Ctx {
|
||||
core: Arc<Core>,
|
||||
weak: Weak<MainWindow>,
|
||||
}
|
||||
|
||||
/// UI-thread state.
|
||||
struct UiState {
|
||||
snap: Option<Snapshot>,
|
||||
outputs: HashMap<String, (bool, String)>,
|
||||
filter: String,
|
||||
pending: Option<Vec<String>>,
|
||||
picks: Rc<VecModel<Pick>>,
|
||||
toast_gen: u32,
|
||||
last_groups: Vec<String>,
|
||||
last_providers: Vec<String>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ST: RefCell<UiState> = RefCell::new(UiState {
|
||||
snap: None,
|
||||
outputs: HashMap::new(),
|
||||
filter: String::new(),
|
||||
pending: None,
|
||||
picks: Rc::new(VecModel::default()),
|
||||
toast_gen: 0,
|
||||
last_groups: Vec::new(),
|
||||
last_providers: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
fn s(v: &Value, k: &str) -> String {
|
||||
v.get(k).and_then(Value::as_str).unwrap_or("").to_string()
|
||||
}
|
||||
|
||||
fn utc_offset_s() -> i64 {
|
||||
let out = std::process::Command::new("date").arg("+%z").output().ok();
|
||||
let z = out
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
|
||||
.unwrap_or_default();
|
||||
if z.len() == 5 {
|
||||
let sign = if z.starts_with('-') { -1 } else { 1 };
|
||||
if let (Ok(h), Ok(m)) = (z[1..3].parse::<i64>(), z[3..5].parse::<i64>()) {
|
||||
return sign * (h * 3600 + m * 60);
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn pill_key(t: TrayState) -> &'static str {
|
||||
match t {
|
||||
TrayState::Ok => "ok",
|
||||
TrayState::Syncing => "warn",
|
||||
TrayState::Attention => "bad",
|
||||
TrayState::Paused => "paused",
|
||||
TrayState::Offline => "offline",
|
||||
}
|
||||
}
|
||||
|
||||
fn str_model(v: &[String]) -> ModelRc<SharedString> {
|
||||
ModelRc::from(Rc::new(VecModel::from(
|
||||
v.iter().map(SharedString::from).collect::<Vec<_>>(),
|
||||
)))
|
||||
}
|
||||
|
||||
fn render(ui: &MainWindow) {
|
||||
ST.with(|st| {
|
||||
let mut st = st.borrow_mut();
|
||||
let st = &mut *st;
|
||||
let Some(snap) = &st.snap else {
|
||||
return;
|
||||
};
|
||||
let agg = model::aggregate(snap.status.as_ref());
|
||||
let now = snap
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s["now"].as_u64())
|
||||
.unwrap_or(0);
|
||||
ui.set_loading(false);
|
||||
ui.set_offline(snap.status.is_none());
|
||||
ui.set_paused(agg.state == TrayState::Paused);
|
||||
ui.set_pill_text(agg.text.clone().into());
|
||||
ui.set_pill_key(pill_key(agg.state).into());
|
||||
ui.set_machine(
|
||||
snap.status
|
||||
.as_ref()
|
||||
.map(|s| s["machine"].as_str().unwrap_or("").to_string())
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
);
|
||||
ui.set_repo_count(agg.repos as i32);
|
||||
ui.set_wt_count(agg.worktrees as i32);
|
||||
ui.set_attention_count(agg.attention as i32);
|
||||
ui.set_has_config(snap.config.is_some());
|
||||
|
||||
let empty = Vec::new();
|
||||
let repos: Vec<Repo> = snap
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s["repos"].as_array())
|
||||
.unwrap_or(&empty)
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let wts: Vec<Wt> = r["worktrees"]
|
||||
.as_array()
|
||||
.unwrap_or(&empty)
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let state = s(w, "state");
|
||||
let key = model::state_name(&state).to_string();
|
||||
let path = s(w, "path");
|
||||
let (out, out_ok) = st
|
||||
.outputs
|
||||
.get(&path)
|
||||
.map(|(ok, t)| (t.clone(), *ok))
|
||||
.unwrap_or_default();
|
||||
let branch = s(w, "branch");
|
||||
Wt {
|
||||
branch: if branch.is_empty() {
|
||||
"(detached)".into()
|
||||
} else {
|
||||
branch.into()
|
||||
},
|
||||
path: path.into(),
|
||||
label: model::state_label(&state).into(),
|
||||
plan: model::state_plan(&state).into(),
|
||||
state: key.into(),
|
||||
out: out.into(),
|
||||
out_ok,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let path = s(r, "path");
|
||||
Repo {
|
||||
name: model::short(&path).into(),
|
||||
phase: s(r, "phase").into(),
|
||||
last_sync: model::ago(r["last_sync"].as_u64().unwrap_or(0), now).into(),
|
||||
error: r["last_error"].as_str().unwrap_or("").into(),
|
||||
path: path.into(),
|
||||
wts: ModelRc::from(Rc::new(VecModel::from(wts))),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let selected = ui.get_selected_path().to_string();
|
||||
if let Some(r) = repos.iter().find(|r| r.path == selected) {
|
||||
ui.set_detail(r.clone());
|
||||
ui.set_detail_found(true);
|
||||
} else {
|
||||
ui.set_detail_found(false);
|
||||
}
|
||||
// Long errors are cut in the list; the detail view shows them in full.
|
||||
let repos: Vec<Repo> = repos
|
||||
.into_iter()
|
||||
.map(|mut r| {
|
||||
if r.error.chars().count() > 160 {
|
||||
r.error = format!("{}…", r.error.chars().take(160).collect::<String>()).into();
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect();
|
||||
ui.set_repos(ModelRc::from(Rc::new(VecModel::from(repos))));
|
||||
|
||||
// The activity log is only built while its view is open.
|
||||
if ui.get_view() == "activity" {
|
||||
let f = st.filter.to_lowercase();
|
||||
let off = utc_offset_s();
|
||||
let rows: Vec<LogRow> = snap
|
||||
.log
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|e| {
|
||||
f.is_empty()
|
||||
|| format!("{} {} {}", s(e, "kind"), s(e, "repo"), s(e, "msg"))
|
||||
.to_lowercase()
|
||||
.contains(&f)
|
||||
})
|
||||
.map(|e| LogRow {
|
||||
time: model::clock(e["ts"].as_u64().unwrap_or(0), off).into(),
|
||||
kind: s(e, "kind").into(),
|
||||
repo: e["repo"].as_str().unwrap_or("–").into(),
|
||||
msg: s(e, "msg").lines().next().unwrap_or("").into(),
|
||||
})
|
||||
.collect();
|
||||
ui.set_log(ModelRc::from(Rc::new(VecModel::from(rows))));
|
||||
}
|
||||
|
||||
if let Some(cfg) = &snap.config {
|
||||
let groups: Vec<String> = cfg["groups"]
|
||||
.as_array()
|
||||
.unwrap_or(&empty)
|
||||
.iter()
|
||||
.map(|g| format!("{} → {}", s(g, "name"), s(g, "primary")))
|
||||
.collect();
|
||||
let providers: Vec<String> = cfg["providers"]
|
||||
.as_object()
|
||||
.map(|m| m.keys().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
// Re-setting a combo model would reset its selection: only on change.
|
||||
if groups != st.last_groups {
|
||||
ui.set_groups(str_model(&groups));
|
||||
st.last_groups = groups;
|
||||
}
|
||||
if providers != st.last_providers {
|
||||
ui.set_providers(str_model(&providers));
|
||||
st.last_providers = providers;
|
||||
}
|
||||
let secs: Vec<Section> = model::settings_sections(cfg)
|
||||
.into_iter()
|
||||
.map(|(title, rows)| Section {
|
||||
title: title.into(),
|
||||
rows: ModelRc::from(Rc::new(VecModel::from(
|
||||
rows.into_iter()
|
||||
.map(|(k, v)| Kv {
|
||||
key: k.into(),
|
||||
value: v.into(),
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
))),
|
||||
})
|
||||
.collect();
|
||||
ui.set_sections(ModelRc::from(Rc::new(VecModel::from(secs))));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn toast(ui: &MainWindow, msg: &str, bad: bool) {
|
||||
let gen_ = ST.with(|st| {
|
||||
let mut st = st.borrow_mut();
|
||||
st.toast_gen += 1;
|
||||
st.toast_gen
|
||||
});
|
||||
ui.set_toast_text(msg.into());
|
||||
ui.set_toast_bad(bad);
|
||||
let weak = ui.as_weak();
|
||||
slint::Timer::single_shot(Duration::from_secs(5), move || {
|
||||
if let Some(ui) = weak.upgrade()
|
||||
&& ST.with(|st| st.borrow().toast_gen) == gen_
|
||||
{
|
||||
ui.set_toast_text("".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn show_window(ui: &MainWindow, core: &Core) {
|
||||
let _ = ui.show();
|
||||
// On Wayland a window shown from an idle (hidden) loop is not mapped until another event
|
||||
// arrives; a one-shot redraw request provides it.
|
||||
let w = ui.as_weak();
|
||||
slint::Timer::single_shot(Duration::from_millis(100), move || {
|
||||
if let Some(ui) = w.upgrade() {
|
||||
ui.window().request_redraw();
|
||||
}
|
||||
});
|
||||
core.set_visible(true);
|
||||
render(ui);
|
||||
}
|
||||
|
||||
/// Runs an allow-listed `grove` subcommand off the UI thread; `done` runs on the UI thread.
|
||||
fn run_cli(
|
||||
ctx: &Ctx,
|
||||
ui: &MainWindow,
|
||||
args: Vec<String>,
|
||||
stdin: String,
|
||||
done: impl FnOnce(&MainWindow, bool, String) + Send + 'static,
|
||||
) {
|
||||
ui.set_busy(true);
|
||||
let (core, weak) = (ctx.core.clone(), ctx.weak.clone());
|
||||
std::thread::spawn(move || {
|
||||
let r = core.bridge.cli(&args, &stdin);
|
||||
let ok = r["ok"] == true;
|
||||
let text = r["output"].as_str().unwrap_or("").to_string();
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.set_busy(false);
|
||||
done(&ui, ok, text);
|
||||
}
|
||||
});
|
||||
core.wake();
|
||||
});
|
||||
}
|
||||
|
||||
fn out(ok: bool, text: String) -> Out {
|
||||
Out {
|
||||
ok,
|
||||
text: text.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn scan(ctx: &Ctx, ui: &MainWindow, group: String) {
|
||||
ui.set_import_note("Scanning…".into());
|
||||
ui.set_import_out(out(true, String::new()));
|
||||
ST.with(|st| st.borrow().picks.set_vec(vec![]));
|
||||
run_cli(
|
||||
ctx,
|
||||
ui,
|
||||
vec!["import".into(), group],
|
||||
String::new(),
|
||||
|ui, ok, text| {
|
||||
ui.set_import_note("".into());
|
||||
if !ok {
|
||||
ui.set_import_out(out(false, text));
|
||||
return;
|
||||
}
|
||||
let names = model::parse_import_listing(&text);
|
||||
if names.is_empty() {
|
||||
ui.set_import_note(
|
||||
"Nothing to import: every remote repository is already on this machine.".into(),
|
||||
);
|
||||
}
|
||||
ST.with(|st| {
|
||||
st.borrow().picks.set_vec(
|
||||
names
|
||||
.into_iter()
|
||||
.map(|n| Pick {
|
||||
name: n.into(),
|
||||
checked: false,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn first_or(v: &str, list: &ModelRc<SharedString>) -> String {
|
||||
if v.is_empty() {
|
||||
list.row_data(0).map(|x| x.to_string()).unwrap_or_default()
|
||||
} else {
|
||||
v.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn wire(ui: &MainWindow, ctx: &Ctx) {
|
||||
ST.with(|st| ui.set_picks(ModelRc::from(st.borrow().picks.clone())));
|
||||
|
||||
ui.on_view_changed({
|
||||
let c = ctx.clone();
|
||||
move |_| c.core.wake()
|
||||
});
|
||||
ui.on_open_repo({
|
||||
let w = ui.as_weak();
|
||||
move |p| {
|
||||
if let Some(ui) = w.upgrade() {
|
||||
ui.set_selected_path(p);
|
||||
ui.set_view("repo".into());
|
||||
render(&ui);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.on_sync_repo({
|
||||
let c = ctx.clone();
|
||||
move |p| c.core.sync(Some(p.as_str()), c.weak.clone())
|
||||
});
|
||||
ui.on_sync_all({
|
||||
let c = ctx.clone();
|
||||
move || c.core.sync(None, c.weak.clone())
|
||||
});
|
||||
ui.on_toggle_pause({
|
||||
let c = ctx.clone();
|
||||
move || c.core.toggle_pause()
|
||||
});
|
||||
ui.on_filter_changed({
|
||||
let w = ui.as_weak();
|
||||
move |t| {
|
||||
ST.with(|st| st.borrow_mut().filter = t.to_string());
|
||||
if let Some(ui) = w.upgrade() {
|
||||
render(&ui);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ui.on_create_repo({
|
||||
let c = ctx.clone();
|
||||
move |group, name, public| {
|
||||
let Some(ui) = c.weak.upgrade() else { return };
|
||||
let group = model::group_name(&first_or(group.as_str(), &ui.get_groups())).to_string();
|
||||
let mut args = vec!["new".to_string(), group, name.trim().to_string()];
|
||||
if public {
|
||||
args.push("--public".into());
|
||||
}
|
||||
ui.set_new_out(out(true, String::new()));
|
||||
run_cli(&c, &ui, args, String::new(), |ui, ok, text| {
|
||||
ui.set_new_out(out(ok, text));
|
||||
if ok {
|
||||
toast(ui, "Repository created", false);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ui.on_scan_import({
|
||||
let c = ctx.clone();
|
||||
move |group| {
|
||||
let Some(ui) = c.weak.upgrade() else { return };
|
||||
let group = model::group_name(&first_or(group.as_str(), &ui.get_groups())).to_string();
|
||||
scan(&c, &ui, group);
|
||||
}
|
||||
});
|
||||
ui.on_pick_toggled(|i, checked| {
|
||||
ST.with(|st| {
|
||||
let m = st.borrow().picks.clone();
|
||||
if let Some(mut p) = m.row_data(i as usize) {
|
||||
p.checked = checked;
|
||||
m.set_row_data(i as usize, p);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.on_import_selected({
|
||||
let c = ctx.clone();
|
||||
move |group| {
|
||||
let Some(ui) = c.weak.upgrade() else { return };
|
||||
let group = model::group_name(&first_or(group.as_str(), &ui.get_groups())).to_string();
|
||||
let picked: Vec<String> = ST.with(|st| {
|
||||
st.borrow()
|
||||
.picks
|
||||
.iter()
|
||||
.filter(|p| p.checked)
|
||||
.map(|p| p.name.to_string())
|
||||
.collect()
|
||||
});
|
||||
if picked.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut args = vec!["import".to_string(), group.clone()];
|
||||
args.extend(picked);
|
||||
let c2 = c.clone();
|
||||
run_cli(&c, &ui, args, String::new(), move |ui, ok, text| {
|
||||
ui.set_import_out(out(ok, text));
|
||||
if ok {
|
||||
scan(&c2, ui, group);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ui.on_resolve({
|
||||
let w = ui.as_weak();
|
||||
move |path, mode, branch| {
|
||||
let Some(ui) = w.upgrade() else { return };
|
||||
let (flags, label): (Vec<String>, String) = match mode.as_str() {
|
||||
"save" => {
|
||||
let b = branch.trim().to_string();
|
||||
if b.is_empty() {
|
||||
toast(&ui, "Enter a branch name first", true);
|
||||
return;
|
||||
}
|
||||
(
|
||||
vec!["--save-as".into(), b.clone()],
|
||||
format!("Keep your commits on branch “{b}” and move this branch to the remote tip."),
|
||||
)
|
||||
}
|
||||
"remote" => (vec!["--take-remote".into()], "Discard your local commits and take the remote tip.".into()),
|
||||
_ => (vec!["--keep-local".into()], "Overwrite the remote branch with your local commits.".into()),
|
||||
};
|
||||
let mut args = vec!["resolve".to_string(), path.to_string()];
|
||||
args.extend(flags);
|
||||
ST.with(|st| st.borrow_mut().pending = Some(args));
|
||||
ui.set_confirm_text(label.into());
|
||||
}
|
||||
});
|
||||
ui.on_confirm_cancel({
|
||||
let w = ui.as_weak();
|
||||
move || {
|
||||
ST.with(|st| st.borrow_mut().pending = None);
|
||||
if let Some(ui) = w.upgrade() {
|
||||
ui.set_confirm_text("".into());
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.on_confirm_accept({
|
||||
let c = ctx.clone();
|
||||
move || {
|
||||
let Some(ui) = c.weak.upgrade() else { return };
|
||||
ui.set_confirm_text("".into());
|
||||
let Some(args) = ST.with(|st| st.borrow_mut().pending.take()) else {
|
||||
return;
|
||||
};
|
||||
let path = args[1].clone();
|
||||
run_cli(&c, &ui, args, String::new(), move |ui, ok, text| {
|
||||
ST.with(|st| st.borrow_mut().outputs.insert(path, (ok, text)));
|
||||
render(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ui.on_run_settings({
|
||||
let c = ctx.clone();
|
||||
move |what| {
|
||||
let Some(ui) = c.weak.upgrade() else { return };
|
||||
let args: Vec<String> = what.split('-').map(String::from).collect();
|
||||
let args = if args[0] == "config" {
|
||||
vec!["config-repo-init".to_string()]
|
||||
} else {
|
||||
args
|
||||
};
|
||||
run_cli(&c, &ui, args, String::new(), |ui, ok, text| {
|
||||
ui.set_settings_out(out(ok, text))
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.on_login({
|
||||
let c = ctx.clone();
|
||||
move |provider, token| {
|
||||
let Some(ui) = c.weak.upgrade() else { return };
|
||||
let provider = first_or(provider.as_str(), &ui.get_providers());
|
||||
run_cli(
|
||||
&c,
|
||||
&ui,
|
||||
vec!["login".into(), provider],
|
||||
format!("{token}\n"),
|
||||
|ui, ok, text| {
|
||||
ui.set_settings_out(out(ok, text));
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
ui.on_onboard({
|
||||
let c = ctx.clone();
|
||||
move |machine, root, kind, provider, url, group, crepo, token| {
|
||||
let Some(ui) = c.weak.upgrade() else { return };
|
||||
let mut init: Vec<String> = [
|
||||
"init",
|
||||
"--machine",
|
||||
&machine,
|
||||
"--root",
|
||||
&root,
|
||||
"--provider",
|
||||
&provider,
|
||||
"--kind",
|
||||
&kind,
|
||||
"--group",
|
||||
&group,
|
||||
"--config-repo",
|
||||
&crepo,
|
||||
]
|
||||
.iter()
|
||||
.map(|x| x.to_string())
|
||||
.collect();
|
||||
if !url.is_empty() {
|
||||
init.push("--url".into());
|
||||
init.push(url.to_string());
|
||||
}
|
||||
let token = format!("{token}\n");
|
||||
ui.set_busy(true);
|
||||
ui.set_onboard_out(out(true, String::new()));
|
||||
let (core, weak) = (c.core.clone(), c.weak.clone());
|
||||
std::thread::spawn(move || {
|
||||
let mut steps: Vec<(Vec<String>, String)> = Vec::new();
|
||||
// A previous attempt may already have written the config.
|
||||
if core.bridge.config_json().is_none() {
|
||||
steps.push((init, String::new()));
|
||||
}
|
||||
steps.push((vec!["login".into(), provider.to_string()], token));
|
||||
steps.push((vec!["bootstrap".into()], String::new()));
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
let mut all_ok = true;
|
||||
for (args, stdin) in steps {
|
||||
let r = core.bridge.cli(&args, &stdin);
|
||||
let ok = r["ok"] == true;
|
||||
lines.push(format!(
|
||||
"$ grove {}\n{}",
|
||||
args[0],
|
||||
r["output"].as_str().unwrap_or("")
|
||||
));
|
||||
let text = lines.join("\n\n");
|
||||
let w = weak.clone();
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
if let Some(ui) = w.upgrade() {
|
||||
ui.set_onboard_out(out(ok, text));
|
||||
}
|
||||
});
|
||||
if !ok {
|
||||
all_ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.set_busy(false);
|
||||
if all_ok {
|
||||
toast(&ui, "All set", false);
|
||||
ui.set_view("repos".into());
|
||||
}
|
||||
}
|
||||
});
|
||||
core.wake();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- worker: daemon polling -----------------------------------------------------------------
|
||||
|
||||
fn worker(
|
||||
core: Arc<Core>,
|
||||
rx: Receiver<()>,
|
||||
tray: Option<tray::TrayHandle>,
|
||||
weak: Weak<MainWindow>,
|
||||
) {
|
||||
let mut last_states: HashMap<String, String> = HashMap::new();
|
||||
let mut last_agg: Option<Aggregate> = None;
|
||||
let mut last_run = Instant::now() - MIN_GAP;
|
||||
loop {
|
||||
let interval = if core.visible.load(Ordering::SeqCst) {
|
||||
POLL_VISIBLE
|
||||
} else {
|
||||
POLL_HIDDEN
|
||||
};
|
||||
match rx.recv_timeout(interval) {
|
||||
Ok(_) | Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => return,
|
||||
}
|
||||
// Coalesce bursts of events.
|
||||
let gap = last_run.elapsed();
|
||||
if gap < MIN_GAP {
|
||||
std::thread::sleep(MIN_GAP - gap);
|
||||
}
|
||||
while rx.try_recv().is_ok() {}
|
||||
last_run = Instant::now();
|
||||
|
||||
let visible = core.visible.load(Ordering::SeqCst);
|
||||
let st = core.bridge.ipc(&json!({"v": 1, "cmd": "status"}));
|
||||
let status = (st["ok"] == true).then(|| st["data"].clone());
|
||||
let agg = model::aggregate(status.as_ref());
|
||||
core.paused
|
||||
.store(agg.state == TrayState::Paused, Ordering::SeqCst);
|
||||
|
||||
let mut alerts = Vec::new();
|
||||
if let Some(s_) = &status {
|
||||
for r in s_["repos"].as_array().into_iter().flatten() {
|
||||
for w in r["worktrees"].as_array().into_iter().flatten() {
|
||||
let path = s(r, "path");
|
||||
let branch = s(w, "branch");
|
||||
let key = format!("{path}|{branch}");
|
||||
let n = model::state_name(w["state"].as_str().unwrap_or("")).to_string();
|
||||
if let Some(prev) = last_states.get(&key)
|
||||
&& *prev != n
|
||||
&& (n == "diverged" || n == "error")
|
||||
{
|
||||
let title = if n == "diverged" {
|
||||
"Diverged"
|
||||
} else {
|
||||
"Sync error"
|
||||
};
|
||||
alerts.push((
|
||||
title.to_string(),
|
||||
format!("{} · {branch}", model::short(&path)),
|
||||
));
|
||||
}
|
||||
last_states.insert(key, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !visible {
|
||||
for (t, b) in &alerts {
|
||||
let _ = std::process::Command::new("notify-send")
|
||||
.args(["-a", "Grove", "-i", "grove", t, b])
|
||||
.spawn()
|
||||
.map(|mut c| std::thread::spawn(move || c.wait()));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(t) = &tray
|
||||
&& last_agg.as_ref() != Some(&agg)
|
||||
{
|
||||
tray::set_state(t, &agg);
|
||||
}
|
||||
last_agg = Some(agg);
|
||||
|
||||
if visible {
|
||||
let log = if status.is_some() {
|
||||
let l = core
|
||||
.bridge
|
||||
.ipc(&json!({"v": 1, "cmd": "log", "limit": 200}));
|
||||
l["data"].as_array().cloned().unwrap_or_default()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let snap = Snapshot {
|
||||
status,
|
||||
log,
|
||||
config: core.bridge.config_json(),
|
||||
alerts,
|
||||
};
|
||||
let w = weak.clone();
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
if let Some(ui) = w.upgrade() {
|
||||
for (t, b) in &snap.alerts {
|
||||
toast(&ui, &format!("{t}: {b}"), true);
|
||||
}
|
||||
ST.with(|st| st.borrow_mut().snap = Some(snap));
|
||||
render(&ui);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Keep the last status for the moment the window opens; drop the heavy parts.
|
||||
let snap = Snapshot {
|
||||
status,
|
||||
log: Vec::new(),
|
||||
config: core.bridge.config_json(),
|
||||
alerts: Vec::new(),
|
||||
};
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
ST.with(|st| st.borrow_mut().snap = Some(snap))
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wakes the worker whenever the daemon emits an activity event.
|
||||
fn subscriber(core: Arc<Core>) {
|
||||
loop {
|
||||
if let Ok(mut c) = UnixStream::connect(&core.bridge.socket) {
|
||||
if writeln!(c, r#"{{"v":1,"cmd":"subscribe"}}"#).is_ok() {
|
||||
for line in BufReader::new(c).lines() {
|
||||
if line.is_err() {
|
||||
break;
|
||||
}
|
||||
core.wake();
|
||||
}
|
||||
}
|
||||
core.wake(); // connection ended: the daemon went away
|
||||
}
|
||||
std::thread::sleep(RECONNECT);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- entry ----------------------------------------------------------------------------------
|
||||
|
||||
fn default_grove_bin() -> PathBuf {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| p.parent().map(|d| d.join("grove")))
|
||||
.filter(|p| p.exists())
|
||||
.unwrap_or_else(|| "grove".into())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let arg = |name: &str| {
|
||||
args.iter()
|
||||
.position(|a| a == name)
|
||||
.and_then(|i| args.get(i + 1))
|
||||
.cloned()
|
||||
};
|
||||
if args.iter().any(|a| a == "--help" || a == "-h") {
|
||||
println!(
|
||||
"grove-gui [--hidden] [--config PATH] [--socket PATH] [--grove-bin PATH] [--view NAME]\n --hidden start in the tray without opening the window"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let hidden = args.iter().any(|a| a == "--hidden");
|
||||
let inst_path = arg("--instance-socket")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(instance::default_socket_path);
|
||||
let listener = match instance::acquire(&inst_path, !hidden).context("single-instance check")? {
|
||||
instance::Role::Secondary => return Ok(()),
|
||||
instance::Role::Primary(l) => l,
|
||||
};
|
||||
|
||||
let bridge = Bridge {
|
||||
grove_bin: arg("--grove-bin")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(default_grove_bin),
|
||||
config: arg("--config").map(PathBuf::from),
|
||||
socket: arg("--socket")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(grove_daemon::ipc::default_socket_path),
|
||||
};
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let core = Arc::new(Core {
|
||||
bridge,
|
||||
tx: Mutex::new(tx),
|
||||
paused: AtomicBool::new(false),
|
||||
visible: AtomicBool::new(false),
|
||||
tray_ok: AtomicBool::new(false),
|
||||
});
|
||||
|
||||
slint::set_xdg_app_id("grove").ok();
|
||||
let ui = MainWindow::new().context("create window")?;
|
||||
let ctx = Ctx {
|
||||
core: core.clone(),
|
||||
weak: ui.as_weak(),
|
||||
};
|
||||
wire(&ui, &ctx);
|
||||
if let Some(v) = arg("--view") {
|
||||
// Start on a given view (`repo:<path>` for a repository); handy for screenshots.
|
||||
match v.split_once(':') {
|
||||
Some(("repo", p)) => {
|
||||
ui.set_selected_path(p.into());
|
||||
ui.set_view("repo".into());
|
||||
}
|
||||
_ => ui.set_view(v.into()),
|
||||
}
|
||||
}
|
||||
|
||||
// Tray actions arrive on the tray's thread.
|
||||
let on_action: Arc<dyn Fn(Action) + Send + Sync> = {
|
||||
let ctx = ctx.clone();
|
||||
Arc::new(move |a| match a {
|
||||
Action::Show => {
|
||||
let c = ctx.clone();
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
if let Some(ui) = c.weak.upgrade() {
|
||||
show_window(&ui, &c.core);
|
||||
}
|
||||
});
|
||||
}
|
||||
Action::SyncNow => ctx.core.sync(None, ctx.weak.clone()),
|
||||
Action::TogglePause => ctx.core.toggle_pause(),
|
||||
Action::Quit => {
|
||||
let _ = slint::invoke_from_event_loop(|| {
|
||||
let _ = slint::quit_event_loop();
|
||||
});
|
||||
}
|
||||
})
|
||||
};
|
||||
let tray = match tray::spawn(on_action) {
|
||||
Ok(h) => {
|
||||
core.tray_ok.store(true, Ordering::SeqCst);
|
||||
Some(h)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("grove-gui: no system tray ({e}); closing the window will quit");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
ui.window().on_close_requested({
|
||||
let c = ctx.clone();
|
||||
move || {
|
||||
c.core.set_visible(false);
|
||||
if !c.core.tray_ok.load(Ordering::SeqCst) {
|
||||
let _ = slint::quit_event_loop();
|
||||
}
|
||||
slint::CloseRequestResponse::HideWindow
|
||||
}
|
||||
});
|
||||
|
||||
{
|
||||
let (c, w) = (core.clone(), ui.as_weak());
|
||||
std::thread::spawn(move || worker(c, rx, tray, w));
|
||||
}
|
||||
{
|
||||
let c = core.clone();
|
||||
std::thread::spawn(move || subscriber(c));
|
||||
}
|
||||
{
|
||||
let c = ctx.clone();
|
||||
std::thread::spawn(move || {
|
||||
instance::serve(listener, move || {
|
||||
let c = c.clone();
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
if let Some(ui) = c.weak.upgrade() {
|
||||
show_window(&ui, &c.core);
|
||||
}
|
||||
});
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
if !hidden || !core.tray_ok.load(Ordering::SeqCst) {
|
||||
show_window(&ui, &core);
|
||||
} else {
|
||||
core.wake();
|
||||
}
|
||||
slint::run_event_loop_until_quit().context("event loop")?;
|
||||
let _ = std::fs::remove_file(&inst_path);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
//! UI-independent logic: daemon status -> aggregate state, formatting, CLI output parsing.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// What the tray icon and the status pill show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum TrayState {
|
||||
Ok,
|
||||
Syncing,
|
||||
Attention,
|
||||
Paused,
|
||||
#[default]
|
||||
Offline,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Aggregate {
|
||||
pub state: TrayState,
|
||||
pub text: String,
|
||||
pub repos: usize,
|
||||
pub worktrees: usize,
|
||||
pub attention: usize,
|
||||
}
|
||||
|
||||
/// `error: <detail>` states collapse to `error`.
|
||||
pub fn state_name(s: &str) -> &str {
|
||||
if s.starts_with("error") { "error" } else { s }
|
||||
}
|
||||
|
||||
pub fn state_label(s: &str) -> &'static str {
|
||||
match state_name(s) {
|
||||
"synced" => "Synced",
|
||||
"dirty" => "Editing",
|
||||
"ahead" => "Ahead",
|
||||
"behind" => "Behind",
|
||||
"behinddirty" => "Behind + editing",
|
||||
"diverged" => "Diverged",
|
||||
"error" => "Error",
|
||||
_ => "Unknown",
|
||||
}
|
||||
}
|
||||
|
||||
/// What the next sync pass will do for a worktree in this state.
|
||||
pub fn state_plan(s: &str) -> &'static str {
|
||||
match state_name(s) {
|
||||
"synced" => "Nothing to do.",
|
||||
"dirty" => "Snapshot the working changes and push the snapshot ref.",
|
||||
"ahead" => "Nothing automatic: push your commits yourself.",
|
||||
"behind" => "Fast-forward to the remote tip.",
|
||||
"behinddirty" => "Keep your edits; adopt the remote tip only if the content is identical.",
|
||||
"diverged" => "Nothing automatic: choose how to resolve it.",
|
||||
"error" => "Retry with backoff; see the error.",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
fn str_of<'a>(v: &'a Value, key: &str) -> &'a str {
|
||||
v.get(key).and_then(Value::as_str).unwrap_or("")
|
||||
}
|
||||
|
||||
/// Summarises the `status` answer of the daemon. `None` means the daemon is unreachable.
|
||||
pub fn aggregate(status: Option<&Value>) -> Aggregate {
|
||||
let Some(s) = status else {
|
||||
return Aggregate {
|
||||
state: TrayState::Offline,
|
||||
text: "Daemon offline".into(),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
let empty = Vec::new();
|
||||
let repos = s.get("repos").and_then(Value::as_array).unwrap_or(&empty);
|
||||
let (mut attention, mut dirty, mut total) = (0, 0, 0);
|
||||
for r in repos {
|
||||
let wts = r
|
||||
.get("worktrees")
|
||||
.and_then(Value::as_array)
|
||||
.unwrap_or(&empty);
|
||||
let has_err = wts
|
||||
.iter()
|
||||
.any(|w| state_name(str_of(w, "state")) == "error");
|
||||
if r.get("last_error").is_some_and(|e| !e.is_null()) && !has_err {
|
||||
attention += 1;
|
||||
}
|
||||
for w in wts {
|
||||
total += 1;
|
||||
match state_name(str_of(w, "state")) {
|
||||
"diverged" | "error" => attention += 1,
|
||||
"synced" => {}
|
||||
_ => dirty += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
let (state, text) = if s.get("paused").and_then(Value::as_bool) == Some(true) {
|
||||
(TrayState::Paused, "Paused".to_string())
|
||||
} else if attention > 0 {
|
||||
let verb = if attention == 1 { "needs" } else { "need" };
|
||||
(
|
||||
TrayState::Attention,
|
||||
format!("{attention} {verb} attention"),
|
||||
)
|
||||
} else if dirty > 0 {
|
||||
(TrayState::Syncing, format!("{dirty} syncing"))
|
||||
} else {
|
||||
(TrayState::Ok, "All synced".to_string())
|
||||
};
|
||||
Aggregate {
|
||||
state,
|
||||
text,
|
||||
repos: repos.len(),
|
||||
worktrees: total,
|
||||
attention,
|
||||
}
|
||||
}
|
||||
|
||||
/// Last two path components, e.g. `work/api`.
|
||||
pub fn short(path: &str) -> String {
|
||||
let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();
|
||||
parts[parts.len().saturating_sub(2)..].join("/")
|
||||
}
|
||||
|
||||
pub fn ago(ts: u64, now: u64) -> String {
|
||||
if ts == 0 {
|
||||
return "never".into();
|
||||
}
|
||||
let d = now.saturating_sub(ts);
|
||||
match d {
|
||||
0..=4 => "just now".into(),
|
||||
5..=59 => format!("{d}s ago"),
|
||||
60..=3599 => format!("{} min ago", (d + 30) / 60),
|
||||
3600..=86399 => format!("{} h ago", (d + 1800) / 3600),
|
||||
_ => format!("{} d ago", (d + 43200) / 86400),
|
||||
}
|
||||
}
|
||||
|
||||
/// `HH:MM:SS` (UTC offset applied by the caller) for the activity log.
|
||||
pub fn clock(ts: u64, utc_offset_s: i64) -> String {
|
||||
let t = (ts as i64 + utc_offset_s).rem_euclid(86400);
|
||||
format!("{:02}:{:02}:{:02}", t / 3600, (t / 60) % 60, t % 60)
|
||||
}
|
||||
|
||||
/// Repository names from `grove import <group>` listing lines: ` owner/name on <provider>[ (private)]`.
|
||||
pub fn parse_import_listing(output: &str) -> Vec<String> {
|
||||
let mut names = Vec::new();
|
||||
for line in output.lines() {
|
||||
if !line.starts_with(char::is_whitespace) {
|
||||
continue;
|
||||
}
|
||||
let mut words = line.split_whitespace();
|
||||
let Some(first) = words.next() else { continue };
|
||||
let Some((_, name)) = first.split_once('/') else {
|
||||
continue;
|
||||
};
|
||||
let rest: Vec<&str> = words.collect();
|
||||
let ok = matches!(
|
||||
rest.as_slice(),
|
||||
[] | ["(private)"] | ["on", _] | ["on", _, "(private)"]
|
||||
);
|
||||
if ok && !name.is_empty() && !name.contains('/') {
|
||||
names.push(name.to_string());
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
fn names(v: Option<&Value>) -> Vec<String> {
|
||||
v.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// One line per group: routes (private + public), owners and layout.
|
||||
pub fn group_summary(g: &Value) -> String {
|
||||
let mut s = format!("primary {}", str_of(g, "primary"));
|
||||
let mirrors = names(g.get("mirror_to"));
|
||||
if !mirrors.is_empty() {
|
||||
s += &format!(" · mirrors: {}", mirrors.join(", "));
|
||||
}
|
||||
if let Some(p) = g.get("public").filter(|p| p.is_object()) {
|
||||
s += &format!(" · public: {}", str_of(p, "primary"));
|
||||
let pm = names(p.get("mirror_to"));
|
||||
if !pm.is_empty() {
|
||||
s += &format!(" → {}", pm.join(", "));
|
||||
}
|
||||
}
|
||||
if let Some(o) = g
|
||||
.get("owners")
|
||||
.and_then(Value::as_object)
|
||||
.filter(|o| !o.is_empty())
|
||||
{
|
||||
let list: Vec<String> = o
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={}", v.as_str().unwrap_or("")))
|
||||
.collect();
|
||||
s += &format!(" · owners: {}", list.join(", "));
|
||||
}
|
||||
let layout = g
|
||||
.get("layout")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("bare-worktrees");
|
||||
format!("{s} · {layout}")
|
||||
}
|
||||
|
||||
pub type Section = (String, Vec<(String, String)>);
|
||||
|
||||
/// The settings view: sections of key/value rows, from `config.toml` as JSON.
|
||||
pub fn settings_sections(cfg: &Value) -> Vec<Section> {
|
||||
let sync = cfg.get("sync");
|
||||
let num = |k: &str, d: u64| {
|
||||
sync.and_then(|s| s.get(k))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(d)
|
||||
};
|
||||
let machine = vec![
|
||||
(
|
||||
"Name".to_string(),
|
||||
str_of(&cfg["machine"], "name").to_string(),
|
||||
),
|
||||
(
|
||||
"Workspace root".into(),
|
||||
str_of(&cfg["root"], "path").to_string(),
|
||||
),
|
||||
(
|
||||
"Fetch interval".into(),
|
||||
format!("{} s", num("fetch_interval_s", 60)),
|
||||
),
|
||||
(
|
||||
"Largest synced file".into(),
|
||||
format!("{} MiB", num("max_file_mb", 50)),
|
||||
),
|
||||
];
|
||||
let providers = cfg
|
||||
.get("providers")
|
||||
.and_then(Value::as_object)
|
||||
.map(|m| {
|
||||
m.iter()
|
||||
.map(|(id, p)| {
|
||||
let url = str_of(p, "url");
|
||||
let url = if url.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" · {url}")
|
||||
};
|
||||
(id.clone(), format!("{}{url}", str_of(p, "kind")))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let groups = cfg
|
||||
.get("groups")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|g| (str_of(g, "name").to_string(), group_summary(g)))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let crepo = match cfg.get("config_repo").filter(|c| c.is_object()) {
|
||||
Some(c) => format!("{} on {}", str_of(c, "name"), str_of(c, "provider")),
|
||||
None => "not configured".into(),
|
||||
};
|
||||
vec![
|
||||
("This machine".into(), machine),
|
||||
("Providers".into(), providers),
|
||||
("Groups".into(), groups),
|
||||
(
|
||||
"Config repository".into(),
|
||||
vec![("Repository".into(), crepo)],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Group name from a combo entry (`name → primary`).
|
||||
pub fn group_name(entry: &str) -> &str {
|
||||
entry.split(" → ").next().unwrap_or(entry)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn status(paused: bool, states: &[&str], last_error: Option<&str>) -> Value {
|
||||
let wts: Vec<Value> = states
|
||||
.iter()
|
||||
.map(|s| json!({"branch": "main", "state": s, "path": "/w/a/main"}))
|
||||
.collect();
|
||||
json!({"machine": "m", "paused": paused, "now": 100,
|
||||
"repos": [{"path": "/w/a", "phase": "idle", "last_sync": 90,
|
||||
"last_error": last_error, "worktrees": wts}]})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_when_no_status() {
|
||||
let a = aggregate(None);
|
||||
assert_eq!(a.state, TrayState::Offline);
|
||||
assert_eq!(a.text, "Daemon offline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_to_tray_mapping() {
|
||||
let agg = |s: Value| aggregate(Some(&s));
|
||||
assert_eq!(agg(status(false, &["synced"], None)).state, TrayState::Ok);
|
||||
assert_eq!(
|
||||
agg(json!({"paused": false, "repos": []})).state,
|
||||
TrayState::Ok
|
||||
);
|
||||
assert_eq!(
|
||||
agg(status(false, &["synced", "dirty"], None)).state,
|
||||
TrayState::Syncing
|
||||
);
|
||||
assert_eq!(
|
||||
agg(status(false, &["behind"], None)).state,
|
||||
TrayState::Syncing
|
||||
);
|
||||
assert_eq!(
|
||||
agg(status(false, &["diverged"], None)).state,
|
||||
TrayState::Attention
|
||||
);
|
||||
assert_eq!(
|
||||
agg(status(false, &["error: boom"], None)).state,
|
||||
TrayState::Attention
|
||||
);
|
||||
assert_eq!(
|
||||
agg(status(false, &["synced"], Some("fetch failed"))).state,
|
||||
TrayState::Attention
|
||||
);
|
||||
// Paused wins over everything else.
|
||||
assert_eq!(
|
||||
agg(status(true, &["diverged"], None)).state,
|
||||
TrayState::Paused
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attention_counts_and_text() {
|
||||
let a = aggregate(Some(&status(
|
||||
false,
|
||||
&["diverged", "error: x", "dirty"],
|
||||
None,
|
||||
)));
|
||||
assert_eq!((a.attention, a.worktrees, a.repos), (2, 3, 1));
|
||||
assert_eq!(a.text, "2 need attention");
|
||||
let a = aggregate(Some(&status(false, &["diverged"], None)));
|
||||
assert_eq!(a.text, "1 needs attention");
|
||||
// An error on the repo that no worktree shows counts once.
|
||||
let a = aggregate(Some(&status(false, &["error: x"], Some("x"))));
|
||||
assert_eq!(a.attention, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_listing_parses_every_line_shape() {
|
||||
let out = "remote repositories in group work not on this machine:\n me/alpha on main\n me/beta on main (private)\n me/gamma\n me/delta (private)\nnot indented/line on x\n nonsense line here\n";
|
||||
assert_eq!(
|
||||
parse_import_listing(out),
|
||||
["alpha", "beta", "gamma", "delta"]
|
||||
);
|
||||
assert!(parse_import_listing("nothing to import").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatting() {
|
||||
assert_eq!(short("/home/u/Workspace/work/api"), "work/api");
|
||||
assert_eq!(short("api"), "api");
|
||||
assert_eq!(ago(0, 100), "never");
|
||||
assert_eq!(ago(98, 100), "just now");
|
||||
assert_eq!(ago(70, 100), "30s ago");
|
||||
assert_eq!(ago(100, 400), "5 min ago");
|
||||
assert_eq!(ago(1, 7201), "2 h ago");
|
||||
assert_eq!(clock(3661, 0), "01:01:01");
|
||||
assert_eq!(clock(3600 * 23, 7200), "01:00:00");
|
||||
assert_eq!(state_label("error: x"), "Error");
|
||||
assert!(state_plan("diverged").contains("resolve"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_show_public_route_and_owners() {
|
||||
let cfg = json!({
|
||||
"machine": {"name": "pca"}, "root": {"path": "/w"},
|
||||
"providers": {"gitea": {"kind": "gitea", "url": "https://g.example"}, "gh": {"kind": "github"}},
|
||||
"groups": [{"name": "work", "primary": "gitea", "mirror_to": ["gh"],
|
||||
"owners": {"gitea": "Org", "gh": "org-gh"},
|
||||
"public": {"primary": "gh", "mirror_to": ["gitea"]}}],
|
||||
"config_repo": {"name": "grove-config", "provider": "gitea"}
|
||||
});
|
||||
let s = settings_sections(&cfg);
|
||||
assert_eq!(s[0].1[0], ("Name".into(), "pca".into()));
|
||||
assert_eq!(s[0].1[2].1, "60 s");
|
||||
// Providers come out sorted by id.
|
||||
assert_eq!(s[1].1[0].1, "github");
|
||||
assert_eq!(s[1].1[1].1, "gitea · https://g.example");
|
||||
assert_eq!(
|
||||
s[2].1[0].1,
|
||||
"primary gitea · mirrors: gh · public: gh → gitea · owners: gh=org-gh, gitea=Org · bare-worktrees"
|
||||
);
|
||||
assert_eq!(s[3].1[0].1, "grove-config on gitea");
|
||||
assert_eq!(group_name("work → gitea"), "work");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
//! StatusNotifierItem tray (ksni). Icons are drawn in code, one per state, so no image decoder
|
||||
//! is needed.
|
||||
|
||||
use crate::model::{Aggregate, TrayState};
|
||||
use ksni::blocking::{Handle, TrayMethods};
|
||||
use ksni::menu::StandardItem;
|
||||
use ksni::{Icon, MenuItem, Status, ToolTip};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Action {
|
||||
Show,
|
||||
SyncNow,
|
||||
TogglePause,
|
||||
Quit,
|
||||
}
|
||||
|
||||
pub struct GroveTray {
|
||||
agg: Aggregate,
|
||||
on_action: Arc<dyn Fn(Action) + Send + Sync>,
|
||||
}
|
||||
|
||||
pub type TrayHandle = Handle<GroveTray>;
|
||||
|
||||
/// Starts the tray service. Fails when there is no D-Bus session.
|
||||
pub fn spawn(on_action: Arc<dyn Fn(Action) + Send + Sync>) -> Result<TrayHandle, ksni::Error> {
|
||||
GroveTray {
|
||||
agg: Aggregate::default(),
|
||||
on_action,
|
||||
}
|
||||
.spawn()
|
||||
}
|
||||
|
||||
pub fn set_state(handle: &TrayHandle, agg: &Aggregate) {
|
||||
let agg = agg.clone();
|
||||
handle.update(move |t| {
|
||||
if t.agg != agg {
|
||||
t.agg = agg;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
impl ksni::Tray for GroveTray {
|
||||
fn id(&self) -> String {
|
||||
"grove".into()
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
"Grove".into()
|
||||
}
|
||||
|
||||
fn status(&self) -> Status {
|
||||
match self.agg.state {
|
||||
TrayState::Attention => Status::NeedsAttention,
|
||||
_ => Status::Active,
|
||||
}
|
||||
}
|
||||
|
||||
fn icon_pixmap(&self) -> Vec<Icon> {
|
||||
icons(self.agg.state)
|
||||
}
|
||||
|
||||
fn attention_icon_pixmap(&self) -> Vec<Icon> {
|
||||
icons(TrayState::Attention)
|
||||
}
|
||||
|
||||
fn tool_tip(&self) -> ToolTip {
|
||||
ToolTip {
|
||||
title: format!("Grove: {}", self.agg.text),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn activate(&mut self, _x: i32, _y: i32) {
|
||||
(self.on_action)(Action::Show);
|
||||
}
|
||||
|
||||
fn menu(&self) -> Vec<MenuItem<Self>> {
|
||||
let online = self.agg.state != TrayState::Offline;
|
||||
let paused = self.agg.state == TrayState::Paused;
|
||||
let item = |label: &str, enabled: bool, a: Action| {
|
||||
StandardItem {
|
||||
label: label.into(),
|
||||
enabled,
|
||||
activate: Box::new(move |t: &mut Self| (t.on_action)(a)),
|
||||
..Default::default()
|
||||
}
|
||||
.into()
|
||||
};
|
||||
vec![
|
||||
StandardItem {
|
||||
label: self.agg.text.clone(),
|
||||
enabled: false,
|
||||
..Default::default()
|
||||
}
|
||||
.into(),
|
||||
MenuItem::Separator,
|
||||
item("Open Grove", true, Action::Show),
|
||||
item("Sync now", online && !paused, Action::SyncNow),
|
||||
item(
|
||||
if paused { "Resume sync" } else { "Pause sync" },
|
||||
online,
|
||||
Action::TogglePause,
|
||||
),
|
||||
MenuItem::Separator,
|
||||
item("Quit", true, Action::Quit),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
// ---- icon drawing ----------------------------------------------------------------------------
|
||||
|
||||
fn colour(s: TrayState) -> [u8; 3] {
|
||||
match s {
|
||||
TrayState::Ok => [0x2e, 0x9e, 0x5b],
|
||||
TrayState::Syncing => [0x2f, 0x7d, 0xd1],
|
||||
TrayState::Attention => [0xd9, 0x48, 0x3b],
|
||||
TrayState::Paused => [0x8a, 0x8f, 0x98],
|
||||
TrayState::Offline => [0x4a, 0x4f, 0x58],
|
||||
}
|
||||
}
|
||||
|
||||
fn seg(px: f32, py: f32, a: (f32, f32), b: (f32, f32), half: f32) -> bool {
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
let t = (((px - a.0) * dx + (py - a.1) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0);
|
||||
let (cx, cy) = (a.0 + t * dx, a.1 + t * dy);
|
||||
(px - cx).hypot(py - cy) <= half
|
||||
}
|
||||
|
||||
/// Glyph in a 32x32 box, white on the coloured disc.
|
||||
fn glyph(s: TrayState, x: f32, y: f32) -> bool {
|
||||
match s {
|
||||
TrayState::Ok => {
|
||||
seg(x, y, (9.0, 16.5), (14.0, 21.5), 1.6) || seg(x, y, (14.0, 21.5), (23.0, 11.0), 1.6)
|
||||
}
|
||||
TrayState::Syncing => {
|
||||
// Ring with a gap at the upper right, like a refresh symbol.
|
||||
let (dx, dy) = (x - 16.0, y - 16.0);
|
||||
let r = dx.hypot(dy);
|
||||
let gap = dx > 0.0 && dy < 0.0 && dx.abs() * 0.6 < dy.abs() * 1.6;
|
||||
(5.0..=8.0).contains(&r) && !gap
|
||||
}
|
||||
TrayState::Attention => {
|
||||
(14.4..=17.6).contains(&x) && (8.0..=18.0).contains(&y)
|
||||
|| (x - 16.0).hypot(y - 22.5) <= 2.0
|
||||
}
|
||||
TrayState::Paused => {
|
||||
(10.0..=14.0).contains(&x) && (9.0..=23.0).contains(&y)
|
||||
|| (18.0..=22.0).contains(&x) && (9.0..=23.0).contains(&y)
|
||||
}
|
||||
TrayState::Offline => {
|
||||
seg(x, y, (10.0, 10.0), (22.0, 22.0), 1.5) || seg(x, y, (22.0, 10.0), (10.0, 22.0), 1.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ARGB32 (network byte order) pixmap of `size` x `size`, 3x3 supersampled.
|
||||
pub fn render(s: TrayState, size: u32) -> Icon {
|
||||
let [r, g, b] = colour(s);
|
||||
let scale = 32.0 / size as f32;
|
||||
let mut data = Vec::with_capacity((size * size * 4) as usize);
|
||||
for py in 0..size {
|
||||
for px in 0..size {
|
||||
let (mut disc, mut mark) = (0u32, 0u32);
|
||||
for sy in 0..3 {
|
||||
for sx in 0..3 {
|
||||
let x = (px as f32 + (sx as f32 + 0.5) / 3.0) * scale;
|
||||
let y = (py as f32 + (sy as f32 + 0.5) / 3.0) * scale;
|
||||
if (x - 16.0).hypot(y - 16.0) <= 15.0 {
|
||||
disc += 1;
|
||||
if glyph(s, x, y) {
|
||||
mark += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let a = (disc * 255 / 9) as u8;
|
||||
// Blend the white glyph over the disc colour by its share of the covered samples.
|
||||
let w = (mark * 255).checked_div(disc).unwrap_or(0);
|
||||
let mix = |c: u8| ((c as u32 * (255 - w) + 255 * w) / 255) as u8;
|
||||
data.extend_from_slice(&[a, mix(r), mix(g), mix(b)]);
|
||||
}
|
||||
}
|
||||
Icon {
|
||||
width: size as i32,
|
||||
height: size as i32,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
fn icons(s: TrayState) -> Vec<Icon> {
|
||||
vec![render(s, 22), render(s, 32), render(s, 64)]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ALL: [TrayState; 5] = [
|
||||
TrayState::Ok,
|
||||
TrayState::Syncing,
|
||||
TrayState::Attention,
|
||||
TrayState::Paused,
|
||||
TrayState::Offline,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn every_state_has_a_distinct_non_empty_icon() {
|
||||
let imgs: Vec<_> = ALL.iter().map(|s| render(*s, 32)).collect();
|
||||
for (i, a) in imgs.iter().enumerate() {
|
||||
assert_eq!(a.data.len(), 32 * 32 * 4);
|
||||
assert!(a.data.chunks(4).any(|p| p[0] == 255), "opaque pixels");
|
||||
assert_eq!(a.data[0], 0, "corner is transparent");
|
||||
for b in &imgs[i + 1..] {
|
||||
assert_ne!(a.data, b.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyph_is_drawn_in_white() {
|
||||
let ok = render(TrayState::Ok, 32);
|
||||
let white = ok
|
||||
.data
|
||||
.chunks(4)
|
||||
.filter(|p| p[0] == 255 && p[1] == 255 && p[2] == 255)
|
||||
.count();
|
||||
assert!(white > 20, "{white}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixmap_sizes() {
|
||||
let sizes: Vec<_> = icons(TrayState::Ok).iter().map(|i| i.width).collect();
|
||||
assert_eq!(sizes, [22, 32, 64]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user