mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 15:26:09 +00:00
feat(gui): migrate clones from the GUI; diagnostics log and tray restart
- Migrate / Migrate all with confirmation, sequential runs, per-repo results - bridge: allow 'add' only for dirs directly under a group - log panics, exit reasons and daemon/tray events to <state>/grove-gui.log - restart the tray service if its D-Bus connection ends Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
28e07aab56
commit
ec6a3a04f3
10 files changed
+528
-25
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// `grove` subcommands the GUI may run. Everything else is refused.
|
||||
@@ -11,6 +11,7 @@ const ALLOWED: &[&str] = &[
|
||||
"login",
|
||||
"new",
|
||||
"import",
|
||||
"add",
|
||||
"config-repo-init",
|
||||
"bootstrap",
|
||||
"resolve",
|
||||
@@ -44,6 +45,11 @@ impl Bridge {
|
||||
if let Err(e) = validate(args) {
|
||||
return json!({"ok": false, "output": format!("rejected: {e}")});
|
||||
}
|
||||
if sub == "add"
|
||||
&& let Err(e) = self.check_migrate_args(args)
|
||||
{
|
||||
return json!({"ok": false, "output": format!("rejected: {e}")});
|
||||
}
|
||||
let mut cmd = Command::new(&self.grove_bin);
|
||||
if let Some(c) = &self.config {
|
||||
cmd.arg("--config").arg(c);
|
||||
@@ -79,6 +85,28 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
fn loaded_config(&self) -> Option<grove_core::config::Config> {
|
||||
let p = self
|
||||
.config
|
||||
.clone()
|
||||
.or_else(grove_core::config::Config::default_path)?;
|
||||
grove_core::config::Config::load(&p).ok()
|
||||
}
|
||||
|
||||
/// `add <path>` only for an existing directory directly under `<root>/<group>/`.
|
||||
fn check_migrate_args(&self, args: &[String]) -> Result<(), String> {
|
||||
let [_, path] = args else {
|
||||
return Err("add takes exactly one path".into());
|
||||
};
|
||||
let cfg = self.loaded_config().ok_or("no readable configuration")?;
|
||||
check_migrate_path(&cfg, Path::new(path)).map(|_| ())
|
||||
}
|
||||
|
||||
/// Where `grove add` writes its safety backup.
|
||||
pub fn backup_dir() -> Option<PathBuf> {
|
||||
grove_core::config::Config::state_dir().map(|d| d.join("backups"))
|
||||
}
|
||||
|
||||
/// `config.toml` as JSON (it holds no secrets), or `None` before onboarding.
|
||||
pub fn config_json(&self) -> Option<Value> {
|
||||
let p = self.config.clone().or_else(grove_core_default_config)?;
|
||||
@@ -135,6 +163,31 @@ pub fn validate(args: &[String]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A clone the GUI may migrate: an existing directory (not a symlink) whose parent is one of the
|
||||
/// configured group directories. Returns its canonical path.
|
||||
pub fn check_migrate_path(
|
||||
cfg: &grove_core::config::Config,
|
||||
path: &Path,
|
||||
) -> Result<PathBuf, String> {
|
||||
let meta = std::fs::symlink_metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if !meta.is_dir() {
|
||||
return Err(format!("{} is not a directory", path.display()));
|
||||
}
|
||||
let canon = path.canonicalize().map_err(|e| e.to_string())?;
|
||||
let parent = canon.parent().ok_or("path has no parent directory")?;
|
||||
let root = cfg.root_path();
|
||||
let root = root.canonicalize().unwrap_or(root);
|
||||
if cfg.groups.iter().any(|g| root.join(&g.name) == parent) {
|
||||
Ok(canon)
|
||||
} else {
|
||||
Err(format!(
|
||||
"{} is not directly inside a group directory under {}",
|
||||
path.display(),
|
||||
root.display()
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn grove_core_default_config() -> Option<PathBuf> {
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
@@ -160,6 +213,72 @@ mod tests {
|
||||
assert!(v(&["secrets", "pull"]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migrate_path_must_be_a_clone_directly_under_a_group() {
|
||||
let base = std::env::temp_dir().join(format!("grove-mig-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("work/proj/sub")).unwrap();
|
||||
std::fs::create_dir_all(base.join("other/proj")).unwrap();
|
||||
std::fs::write(base.join("work/file"), "x").unwrap();
|
||||
std::os::unix::fs::symlink(base.join("other/proj"), base.join("work/link")).unwrap();
|
||||
let cfg = grove_core::config::Config::parse(&format!(
|
||||
"[machine]\nname=\"m\"\n[root]\npath=\"{}\"\n[providers.p]\nkind=\"gitea\"\n[[groups]]\nname=\"work\"\nprimary=\"p\"\n",
|
||||
base.display()
|
||||
))
|
||||
.unwrap();
|
||||
assert!(check_migrate_path(&cfg, &base.join("work/proj")).is_ok());
|
||||
for bad in [
|
||||
"work/proj/sub",
|
||||
"other/proj",
|
||||
"work/file",
|
||||
"work/link",
|
||||
"work/none",
|
||||
"work",
|
||||
"work/../other/proj",
|
||||
] {
|
||||
assert!(check_migrate_path(&cfg, &base.join(bad)).is_err(), "{bad}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_runs_only_for_valid_clone_paths() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let base = std::env::temp_dir().join(format!("grove-add-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("work/proj")).unwrap();
|
||||
std::fs::create_dir_all(base.join("elsewhere")).unwrap();
|
||||
let cfg = base.join("config.toml");
|
||||
std::fs::write(&cfg, format!(
|
||||
"[machine]\nname=\"m\"\n[root]\npath=\"{}\"\n[providers.p]\nkind=\"gitea\"\n[[groups]]\nname=\"work\"\nprimary=\"p\"\n",
|
||||
base.display()
|
||||
)).unwrap();
|
||||
// A stand-in `grove` that reports what it was asked to do.
|
||||
let fake = base.join("grove");
|
||||
std::fs::write(&fake, "#!/bin/sh\necho \"migrated: $3/wt\"\n").unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let b = Bridge {
|
||||
grove_bin: fake,
|
||||
config: Some(cfg),
|
||||
socket: "/nonexistent".into(),
|
||||
};
|
||||
let ok = b.cli(
|
||||
&["add".into(), base.join("work/proj").display().to_string()],
|
||||
"",
|
||||
);
|
||||
assert_eq!(ok["ok"], true, "{ok}");
|
||||
assert!(ok["output"].as_str().unwrap().starts_with("migrated:"));
|
||||
let bad = b.cli(
|
||||
&["add".into(), base.join("elsewhere").display().to_string()],
|
||||
"",
|
||||
);
|
||||
assert_eq!(bad["ok"], false);
|
||||
assert!(bad["output"].as_str().unwrap().contains("rejected"));
|
||||
let flag = b.cli(&["add".into(), "--backup-dir".into(), "/x".into()], "");
|
||||
assert_eq!(flag["ok"], false);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
fn bridge() -> Bridge {
|
||||
Bridge {
|
||||
grove_bin: "/nonexistent/grove".into(),
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! A small log file (`<state dir>/grove-gui.log`) for things that would otherwise vanish when the
|
||||
//! GUI runs from autostart with stdout/stderr closed: panics, fatal errors and why it exited.
|
||||
|
||||
use std::io::Write;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
static PATH: OnceLock<std::path::PathBuf> = OnceLock::new();
|
||||
/// Set when the process leaves on purpose (tray "Quit", window closed without a tray).
|
||||
pub static EXPECTED_EXIT: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
const MAX_BYTES: u64 = 256 * 1024;
|
||||
|
||||
/// Opens the log (truncating a file past 256 KiB) and installs the panic hook.
|
||||
pub fn init() {
|
||||
let Some(dir) = grove_core::config::Config::state_dir() else {
|
||||
return;
|
||||
};
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let path = dir.join("grove-gui.log");
|
||||
if std::fs::metadata(&path).is_ok_and(|m| m.len() > MAX_BYTES) {
|
||||
let _ = std::fs::rename(&path, dir.join("grove-gui.log.old"));
|
||||
}
|
||||
let _ = PATH.set(path);
|
||||
let default = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
let t = std::thread::current();
|
||||
let bt = std::backtrace::Backtrace::force_capture();
|
||||
line(&format!(
|
||||
"PANIC in thread {:?}: {info}\n{bt}",
|
||||
t.name().unwrap_or("<unnamed>")
|
||||
));
|
||||
default(info);
|
||||
}));
|
||||
}
|
||||
|
||||
/// Appends one timestamped line; never fails and never panics.
|
||||
pub fn line(msg: &str) {
|
||||
let Some(p) = PATH.get() else { return };
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(p)
|
||||
{
|
||||
let _ = writeln!(f, "{} [{}] {msg}", stamp(), std::process::id());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expected_exit() {
|
||||
EXPECTED_EXIT.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// `YYYY-MM-DD HH:MM:SSZ` (UTC) from the system clock.
|
||||
fn stamp() -> String {
|
||||
let s = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
let (days, rem) = (s / 86400, s % 86400);
|
||||
// Civil-from-days (Howard Hinnant).
|
||||
let z = days as i64 + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||
format!(
|
||||
"{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z",
|
||||
rem / 3600,
|
||||
rem % 3600 / 60,
|
||||
rem % 60
|
||||
)
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
mod autostart;
|
||||
mod bridge;
|
||||
mod instance;
|
||||
mod log;
|
||||
mod model;
|
||||
mod tray;
|
||||
|
||||
@@ -125,6 +126,10 @@ struct UiState {
|
||||
detail_fp: String,
|
||||
filter: String,
|
||||
pending: Option<Vec<String>>,
|
||||
/// Clones waiting for the migration confirmation, and what happened to each so far.
|
||||
mig_pending: Option<Vec<String>>,
|
||||
mig: HashMap<String, (String, String)>,
|
||||
migrating: bool,
|
||||
picks: Rc<VecModel<Pick>>,
|
||||
/// Last successful scan per import group, for the session (names still to import).
|
||||
import_cache: HashMap<String, Vec<String>>,
|
||||
@@ -145,6 +150,9 @@ thread_local! {
|
||||
detail_fp: String::new(),
|
||||
filter: String::new(),
|
||||
pending: None,
|
||||
mig_pending: None,
|
||||
mig: HashMap::new(),
|
||||
migrating: false,
|
||||
picks: Rc::new(VecModel::default()),
|
||||
import_cache: HashMap::new(),
|
||||
import_current: String::new(),
|
||||
@@ -224,16 +232,25 @@ fn render(ui: &MainWindow) {
|
||||
ui.set_attention_count(agg.attention as i32);
|
||||
ui.set_has_config(snap.config.is_some());
|
||||
ui.set_autostart(autostart::config_home().is_some_and(|d| autostart::is_enabled(&d)));
|
||||
let nm: Vec<SharedString> = snap
|
||||
let nm: Vec<MigRow> = snap
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s["not_migrated"].as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|p| p.as_str().map(SharedString::from))
|
||||
.filter_map(|p| p.as_str())
|
||||
.map(|p| {
|
||||
let (state, msg) = st.mig.get(p).cloned().unwrap_or_default();
|
||||
MigRow {
|
||||
path: p.into(),
|
||||
state: state.into(),
|
||||
msg: msg.into(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ui.set_migrating(st.migrating);
|
||||
ui.set_not_migrated(ModelRc::from(Rc::new(VecModel::from(nm))));
|
||||
|
||||
let empty = Vec::new();
|
||||
@@ -568,6 +585,91 @@ fn scan(ctx: &Ctx, ui: &MainWindow, group: String, force: bool, note: Option<Str
|
||||
});
|
||||
}
|
||||
|
||||
/// Opens the confirmation dialog for migrating `paths` (nothing runs before the user accepts).
|
||||
fn ask_migrate(ui: &MainWindow, paths: Vec<String>) {
|
||||
if paths.is_empty() || ST.with(|st| st.borrow().migrating) {
|
||||
return;
|
||||
}
|
||||
let backup = Bridge::backup_dir()
|
||||
.map(|d| d.display().to_string())
|
||||
.unwrap_or_else(|| "grove's state directory".into());
|
||||
let what = match paths.as_slice() {
|
||||
[one] => one.clone(),
|
||||
many => format!("{} clones", many.len()),
|
||||
};
|
||||
ST.with(|st| st.borrow_mut().mig_pending = Some(paths));
|
||||
ui.set_migrate_confirm_text(
|
||||
format!(
|
||||
"Migrate {what} to grove's bare + worktrees layout?\n\nA full backup of each clone (a tar archive and a git ref) is taken first, in {backup}. A clone grove cannot migrate safely (linked worktrees, submodules, detached HEAD...) is refused and left untouched."
|
||||
)
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Migrates the clones one after the other on a worker thread, reporting each result as it comes.
|
||||
fn run_migrations(ctx: &Ctx, ui: &MainWindow, paths: Vec<String>) {
|
||||
ST.with(|st| {
|
||||
let mut st = st.borrow_mut();
|
||||
st.migrating = true;
|
||||
for p in &paths {
|
||||
st.mig.remove(p);
|
||||
}
|
||||
});
|
||||
render(ui);
|
||||
let (core, weak) = (ctx.core.clone(), ctx.weak.clone());
|
||||
std::thread::spawn(move || {
|
||||
let total = paths.len();
|
||||
let (mut done, mut failed) = (0, 0);
|
||||
for p in paths {
|
||||
let (w, p1) = (weak.clone(), p.clone());
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
ST.with(|st| {
|
||||
st.borrow_mut()
|
||||
.mig
|
||||
.insert(p1, ("running".into(), String::new()))
|
||||
});
|
||||
if let Some(ui) = w.upgrade() {
|
||||
render(&ui);
|
||||
}
|
||||
});
|
||||
let r = core.bridge.cli(&["add".to_string(), p.clone()], "");
|
||||
let ok = r["ok"] == true;
|
||||
let text = r["output"].as_str().unwrap_or("").to_string();
|
||||
let msg = if ok {
|
||||
done += 1;
|
||||
text.lines()
|
||||
.find_map(|l| l.strip_prefix("migrated:"))
|
||||
.map(|m| format!("Migrated to {}", m.trim()))
|
||||
.unwrap_or_else(|| "Migrated".into())
|
||||
} else {
|
||||
failed += 1;
|
||||
text.lines().next().unwrap_or("failed").to_string()
|
||||
};
|
||||
let (w, p2) = (weak.clone(), p);
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
let state = if ok { "ok" } else { "failed" };
|
||||
ST.with(|st| st.borrow_mut().mig.insert(p2, (state.into(), msg)));
|
||||
if let Some(ui) = w.upgrade() {
|
||||
render(&ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
let w = weak.clone();
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
ST.with(|st| st.borrow_mut().migrating = false);
|
||||
if let Some(ui) = w.upgrade() {
|
||||
render(&ui);
|
||||
toast(
|
||||
&ui,
|
||||
&format!("Migration finished: {done} of {total} migrated, {failed} failed"),
|
||||
failed > 0,
|
||||
);
|
||||
}
|
||||
});
|
||||
core.wake(); // refresh the status
|
||||
});
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -736,6 +838,47 @@ fn wire(ui: &MainWindow, ctx: &Ctx) {
|
||||
ui.set_autostart(autostart::config_home().is_some_and(|d| autostart::is_enabled(&d)));
|
||||
}
|
||||
});
|
||||
ui.on_migrate_one({
|
||||
let w = ui.as_weak();
|
||||
move |path| {
|
||||
if let Some(ui) = w.upgrade() {
|
||||
ask_migrate(&ui, vec![path.to_string()]);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.on_migrate_all({
|
||||
let w = ui.as_weak();
|
||||
move || {
|
||||
let Some(ui) = w.upgrade() else { return };
|
||||
let todo: Vec<String> = ui
|
||||
.get_not_migrated()
|
||||
.iter()
|
||||
.filter(|r| r.state != "ok" && r.state != "running")
|
||||
.map(|r| r.path.to_string())
|
||||
.collect();
|
||||
ask_migrate(&ui, todo);
|
||||
}
|
||||
});
|
||||
ui.on_migrate_confirm_cancel({
|
||||
let w = ui.as_weak();
|
||||
move || {
|
||||
ST.with(|st| st.borrow_mut().mig_pending = None);
|
||||
if let Some(ui) = w.upgrade() {
|
||||
ui.set_migrate_confirm_text("".into());
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.on_migrate_confirm_accept({
|
||||
let c = ctx.clone();
|
||||
move || {
|
||||
let Some(ui) = c.weak.upgrade() else { return };
|
||||
ui.set_migrate_confirm_text("".into());
|
||||
let Some(paths) = ST.with(|st| st.borrow_mut().mig_pending.take()) else {
|
||||
return;
|
||||
};
|
||||
run_migrations(&c, &ui, paths);
|
||||
}
|
||||
});
|
||||
ui.on_confirm_cancel({
|
||||
let w = ui.as_weak();
|
||||
move || {
|
||||
@@ -918,9 +1061,11 @@ fn wire(ui: &MainWindow, ctx: &Ctx) {
|
||||
fn worker(
|
||||
core: Arc<Core>,
|
||||
rx: Receiver<()>,
|
||||
tray: Option<tray::TrayHandle>,
|
||||
mut tray: Option<tray::TrayHandle>,
|
||||
respawn_tray: impl Fn() -> Option<tray::TrayHandle>,
|
||||
weak: Weak<MainWindow>,
|
||||
) {
|
||||
let mut tray_lost = false;
|
||||
let mut last_states: HashMap<String, String> = HashMap::new();
|
||||
let mut last_agg: Option<Aggregate> = None;
|
||||
let mut last_run = Instant::now() - MIN_GAP_HIDDEN;
|
||||
@@ -996,10 +1141,25 @@ fn worker(
|
||||
}
|
||||
}
|
||||
|
||||
// The tray service ends when its D-Bus connection is lost (e.g. the session bus or the
|
||||
// desktop shell restarted): bring it back instead of leaving a running app with no icon.
|
||||
if core.tray_ok.load(Ordering::SeqCst) && tray.as_ref().is_none_or(|t| t.is_closed()) {
|
||||
if !tray_lost {
|
||||
log::line("tray service ended; trying to restart it");
|
||||
tray_lost = true;
|
||||
}
|
||||
if let Some(h) = respawn_tray() {
|
||||
log::line("tray service restarted");
|
||||
tray = Some(h);
|
||||
tray_lost = false;
|
||||
last_agg = None;
|
||||
}
|
||||
}
|
||||
if let Some(t) = &tray
|
||||
&& last_agg.as_ref() != Some(&agg)
|
||||
&& !tray::set_state(t, &agg)
|
||||
{
|
||||
tray::set_state(t, &agg);
|
||||
log::line("tray update failed: service closed");
|
||||
}
|
||||
last_agg = Some(agg);
|
||||
|
||||
@@ -1034,17 +1194,27 @@ fn worker(
|
||||
|
||||
/// Wakes the worker whenever the daemon emits an activity event.
|
||||
fn subscriber(core: Arc<Core>) {
|
||||
let mut connected = false;
|
||||
loop {
|
||||
if let Ok(mut c) = UnixStream::connect(&core.bridge.socket) {
|
||||
if !connected {
|
||||
log::line("daemon: subscribed");
|
||||
connected = true;
|
||||
}
|
||||
if writeln!(c, r#"{{"v":1,"cmd":"subscribe"}}"#).is_ok() {
|
||||
for line in BufReader::new(c).lines() {
|
||||
if line.is_err() {
|
||||
if let Err(e) = line {
|
||||
log::line(&format!("daemon: event stream error: {e}"));
|
||||
break;
|
||||
}
|
||||
core.wake();
|
||||
}
|
||||
}
|
||||
core.wake(); // connection ended: the daemon went away
|
||||
if connected {
|
||||
log::line("daemon: event stream ended");
|
||||
connected = false;
|
||||
}
|
||||
}
|
||||
std::thread::sleep(RECONNECT);
|
||||
}
|
||||
@@ -1061,6 +1231,20 @@ fn default_grove_bin() -> PathBuf {
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
log::init();
|
||||
log::line(&format!(
|
||||
"start {}",
|
||||
std::env::args().skip(1).collect::<Vec<_>>().join(" ")
|
||||
));
|
||||
let r = run();
|
||||
match &r {
|
||||
Ok(()) => log::line("exit: ok"),
|
||||
Err(e) => log::line(&format!("exit: error: {e:#}")),
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let arg = |name: &str| {
|
||||
args.iter()
|
||||
@@ -1154,18 +1338,21 @@ fn main() -> Result<()> {
|
||||
Action::SyncNow => ctx.core.sync(None, ctx.weak.clone()),
|
||||
Action::TogglePause => ctx.core.toggle_pause(),
|
||||
Action::Quit => {
|
||||
log::line("quit requested from the tray menu");
|
||||
log::expected_exit();
|
||||
let _ = slint::invoke_from_event_loop(|| {
|
||||
let _ = slint::quit_event_loop();
|
||||
});
|
||||
}
|
||||
})
|
||||
};
|
||||
let tray = match tray::spawn(on_action) {
|
||||
let tray = match tray::spawn(on_action.clone()) {
|
||||
Ok(h) => {
|
||||
core.tray_ok.store(true, Ordering::SeqCst);
|
||||
Some(h)
|
||||
}
|
||||
Err(e) => {
|
||||
log::line(&format!("no system tray: {e}"));
|
||||
eprintln!("grove-gui: no system tray ({e}); closing the window will quit");
|
||||
None
|
||||
}
|
||||
@@ -1176,6 +1363,8 @@ fn main() -> Result<()> {
|
||||
move || {
|
||||
c.core.set_visible(false);
|
||||
if !c.core.tray_ok.load(Ordering::SeqCst) {
|
||||
log::line("window closed and no tray: quitting");
|
||||
log::expected_exit();
|
||||
let _ = slint::quit_event_loop();
|
||||
}
|
||||
slint::CloseRequestResponse::HideWindow
|
||||
@@ -1184,7 +1373,10 @@ fn main() -> Result<()> {
|
||||
|
||||
{
|
||||
let (c, w) = (core.clone(), ui.as_weak());
|
||||
std::thread::spawn(move || worker(c, rx, tray, w));
|
||||
let respawn = on_action.clone();
|
||||
std::thread::spawn(move || {
|
||||
worker(c, rx, tray, move || tray::spawn(respawn.clone()).ok(), w)
|
||||
});
|
||||
}
|
||||
{
|
||||
let c = core.clone();
|
||||
@@ -1197,7 +1389,12 @@ fn main() -> Result<()> {
|
||||
} else {
|
||||
core.wake();
|
||||
}
|
||||
slint::run_event_loop_until_quit().context("event loop")?;
|
||||
let r = slint::run_event_loop_until_quit();
|
||||
log::line(&format!(
|
||||
"event loop ended: {r:?} (expected: {})",
|
||||
log::EXPECTED_EXIT.load(Ordering::SeqCst)
|
||||
));
|
||||
r.context("event loop")?;
|
||||
let _ = std::fs::remove_file(&inst_path);
|
||||
Ok(())
|
||||
}
|
||||
@@ -31,13 +31,16 @@ pub fn spawn(on_action: Arc<dyn Fn(Action) + Send + Sync>) -> Result<TrayHandle,
|
||||
.spawn()
|
||||
}
|
||||
|
||||
pub fn set_state(handle: &TrayHandle, agg: &Aggregate) {
|
||||
/// Returns false when the tray service has ended (D-Bus connection lost).
|
||||
pub fn set_state(handle: &TrayHandle, agg: &Aggregate) -> bool {
|
||||
let agg = agg.clone();
|
||||
handle.update(move |t| {
|
||||
if t.agg != agg {
|
||||
t.agg = agg;
|
||||
}
|
||||
});
|
||||
handle
|
||||
.update(move |t| {
|
||||
if t.agg != agg {
|
||||
t.agg = agg;
|
||||
}
|
||||
})
|
||||
.is_some()
|
||||
}
|
||||
|
||||
impl ksni::Tray for GroveTray {
|
||||
|
||||
Reference in new issue
Block a user