//! Lune for the Mac (M7): the sync engine in the menu bar, a small window for what needs a person, connecting //! from a link, signed updates from the hub, and a clean uninstall. mod commands; use lune_core::config::{self, Config}; use lune_core::{membership, remote, runner, status, supervisor}; use std::collections::VecDeque; use std::io::Write; use std::sync::atomic::Ordering; use std::sync::{Mutex, OnceLock}; use std::time::Duration; use tauri::image::Image; use tauri::menu::{Menu, MenuItem, PredefinedMenuItem}; use tauri::tray::{TrayIcon, TrayIconBuilder}; use tauri::{AppHandle, Manager, WindowEvent}; use tauri_plugin_autostart::{MacosLauncher, ManagerExt as _}; use tauri_plugin_deep_link::DeepLinkExt; use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind}; use tauri_plugin_updater::UpdaterExt; /// A request to connect this Mac, from a `lune://` link the website opened. #[derive(Clone)] pub enum Connect { /// An invite link: creates the person's account and this device. Join { link: String }, /// A pairing code made for a signed-in person. Pair { hub: String, code: String }, } impl Connect { pub fn hub(&self) -> String { match self { Connect::Join { link } => link.split("/join/").next().unwrap_or_default().to_string(), Connect::Pair { hub, .. } => hub.clone(), } } fn from_url(url: &url::Url) -> Option { let param = |name: &str| url.query_pairs().find(|(k, _)| k == name).map(|(_, v)| v.into_owned()); match url.host_str()? { "join" => Some(Connect::Join { link: param("link")? }), "pair" => Some(Connect::Pair { hub: param("hub")?, code: param("code")? }), _ => None, } } } #[derive(Default)] pub struct AppState { pub pending: Mutex>, /// A newer version, downloaded and installed; it runs after a restart. pub update_ready: Mutex>, tray: Mutex>, } struct TrayParts { icon: TrayIcon, status: MenuItem, canvas: MenuItem, update: MenuItem, level: String, } static APP: OnceLock = OnceLock::new(); static RECENT: Mutex> = Mutex::new(VecDeque::new()); /// The engine's log: kept briefly for the window and appended to `lune.log` next to the config. fn log_line(vault: &str, msg: &str) { let line = format!("{} {vault:<10} {msg}", chrono::Local::now().format("%H:%M:%S")); { let mut recent = RECENT.lock().unwrap(); recent.push_back(line.clone()); while recent.len() > 50 { recent.pop_front(); } } if let Ok(dir) = config::config_dir() { let path = dir.join("lune.log"); if std::fs::metadata(&path).is_ok_and(|m| m.len() > 2_000_000) { let _ = std::fs::remove_file(&path); } if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { let _ = writeln!(f, "{line}"); } } } pub fn recent_log() -> Vec { RECENT.lock().unwrap().iter().rev().take(12).cloned().collect() } pub fn show_window(app: &AppHandle) { if let Some(w) = app.get_webview_window("main") { let _ = w.show(); let _ = w.unminimize(); let _ = w.set_focus(); } // Opening the window is a good moment to look for an update. let app = app.clone(); tauri::async_runtime::spawn(async move { check_for_update(&app).await }); } fn tray_image(level: &str) -> Image<'static> { let bytes: &[u8] = match level { "secret" => include_bytes!("../icons/tray-red.png"), "behind" => include_bytes!("../icons/tray-amber.png"), "offline" => include_bytes!("../icons/tray-grey.png"), _ => include_bytes!("../icons/tray-green.png"), }; Image::from_bytes(bytes).expect("tray icons are valid PNGs") } /// One line for the menu bar: the worst thing going on, in plain words. pub fn summary(config: &Config) -> (String, String) { if config.hubs.is_empty() && config.vaults.is_empty() { return ("offline".into(), "Not connected to a team yet".into()); } let label = config.device_label(); let all: Vec = config.vaults.iter().map(|v| status::of(v, &label)).collect(); let level = status::worst(all.iter().map(|s| s.level)).to_string(); let text = match all.iter().find(|s| s.level == level && level != "current") { Some(s) if !s.secrets.is_empty() => format!("{}: a note was held back (possible secret)", s.name), Some(s) if !s.held.is_empty() => format!("{}: a big change is waiting for you", s.name), Some(s) if !s.tidy.is_empty() && s.headline == "Synced" => { format!("{}: {} to tidy", s.name, if s.tidy.len() == 1 { "1 note".to_string() } else { format!("{} notes", s.tidy.len()) }) } Some(s) => format!("{}: {}", s.name, s.headline), None if all.is_empty() => "Waiting for vaults to arrive".into(), None => "All synced".into(), }; (level, text) } fn refresh_tray(app: &AppHandle) { let config = Config::load().unwrap_or_default(); let (level, text) = summary(&config); let state = app.state::(); let update = state.update_ready.lock().unwrap().clone(); let mut tray = state.tray.lock().unwrap(); let Some(t) = tray.as_mut() else { return }; if t.level != level { let _ = t.icon.set_icon(Some(tray_image(&level))); t.level = level; } let _ = t.status.set_text(&text); let _ = t.icon.set_tooltip(Some(format!("Lune — {text}"))); let _ = t.canvas.set_enabled(!config.hubs.is_empty()); match update { Some(v) => { let _ = t.update.set_text(format!("Restart to update (Lune {v})")); let _ = t.update.set_enabled(true); } None => { let _ = t.update.set_text(format!("Lune {}", app.package_info().version)); let _ = t.update.set_enabled(false); } } } fn build_tray(app: &AppHandle) -> tauri::Result<()> { let status = MenuItem::with_id(app, "status", "Starting…", false, None::<&str>)?; let open = MenuItem::with_id(app, "open", "Open Lune", true, None::<&str>)?; let canvas = MenuItem::with_id(app, "canvas", "Open team canvas", false, None::<&str>)?; let share = MenuItem::with_id(app, "share", "Share now", true, None::<&str>)?; let update = MenuItem::with_id(app, "update", "", false, None::<&str>)?; let uninstall_item = MenuItem::with_id(app, "uninstall", "Uninstall Lune…", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "Quit Lune", true, None::<&str>)?; let sep = || PredefinedMenuItem::separator(app); let menu = Menu::with_items(app, &[&status, &sep()?, &open, &canvas, &share, &sep()?, &update, &uninstall_item, &quit])?; let icon = TrayIconBuilder::with_id("lune") .icon(tray_image("offline")) .icon_as_template(false) .menu(&menu) .show_menu_on_left_click(true) .on_menu_event(|app, event| match event.id.as_ref() { "open" => show_window(app), "canvas" => { // One team: straight to its canvas. Several: the window lists them. if Config::load().unwrap_or_default().hubs.len() > 1 { show_window(app); } else { let app = app.clone(); std::thread::spawn(move || { if let Err(e) = commands::open_canvas_now(&app, None) { log_line("hub", &format!("couldn't open the canvas: {e}")); } }); } } "share" => supervisor::share_now(&Config::load().unwrap_or_default()), "update" => app.restart(), "uninstall" => { let app = app.clone(); std::thread::spawn(move || uninstall(&app)); } "quit" => app.exit(0), _ => {} }) .build(app)?; let state = app.state::(); *state.tray.lock().unwrap() = Some(TrayParts { icon, status, canvas, update, level: "offline".into() }); Ok(()) } /// Looks for a newer version on this Mac's hubs (they all serve releases signed with the one key); downloads and /// installs it, ready for a restart (D3). pub async fn check_for_update(app: &AppHandle) { let hubs = Config::load().map(|c| c.hubs).unwrap_or_default(); if hubs.is_empty() { return; } if app.state::().update_ready.lock().unwrap().is_some() { return; } let configured = app .config() .plugins .0 .get("updater") .and_then(|u| u.get("pubkey")) .and_then(|k| k.as_str()) .is_some_and(|k| !k.is_empty()); if !configured { return; // a build without the hub's public key can't verify updates, so it doesn't take any } let endpoints = hubs.iter().filter_map(|h| format!("{}/api/update/{{{{target}}}}/{{{{arch}}}}/{{{{current_version}}}}", h.url).parse().ok()); let result = async { let updater = app .updater_builder() .endpoints(endpoints.collect())? .header("User-Agent", remote::user_agent())? .build()?; if let Some(update) = updater.check().await? { log_line("app", &format!("downloading Lune {}", update.version)); update.download_and_install(|_, _| {}, || {}).await?; return Ok::<_, anyhow::Error>(Some(update.version)); } Ok(None) } .await; match result { Ok(Some(version)) => { log_line("app", &format!("Lune {version} is ready — restart to use it")); *app.state::().update_ready.lock().unwrap() = Some(version); refresh_tray(app); } Ok(None) => {} Err(e) => log_line("app", &format!("couldn't check for an update: {e:#}")), } } /// Uninstall Lune… (D5): asks once, then shares, hands over, removes what Lune made, and moves itself to the Trash. fn uninstall(app: &AppHandle) { let ok = app .dialog() .message( "Lune first shares anything not yet shared and hands the rest to your team, then removes:\n\n\ • the vault folders Lune created\n• this Mac from your team\n• Lune's settings and login item\n• the app itself\n\n\ Folders you added yourself stay, and so does any folder whose changes couldn't be shared.", ) .title("Uninstall Lune from this Mac?") .kind(MessageDialogKind::Warning) .buttons(MessageDialogButtons::OkCancelCustom("Uninstall".into(), "Cancel".into())) .blocking_show(); if !ok { return; } runner::STOP.store(true, Ordering::Relaxed); let mut config = Config::load().unwrap_or_default(); config.use_hub_credentials(); let done = membership::uninstall(&mut config); let _ = app.autolaunch().disable(); let mut leftovers = vec![]; if let Ok(dir) = config::config_dir() { leftovers.push(dir); } let paths = app.path(); leftovers.extend([paths.app_data_dir(), paths.app_cache_dir(), paths.app_log_dir(), paths.app_config_dir()].into_iter().flatten()); if let Some(home) = std::env::home_dir() { let id = &app.config().identifier; leftovers.push(home.join("Library/WebKit").join(id)); leftovers.push(home.join("Library/Caches").join(id)); } let message = match done { Ok(done) => { for dir in leftovers.iter().filter(|d| d.exists()) { let _ = std::fs::remove_dir_all(dir); } let bundle = std::env::current_exe() .ok() .and_then(|exe| exe.ancestors().find(|p| p.extension().is_some_and(|e| e == "app")).map(|p| p.to_path_buf())); let mut text = String::from("Lune is uninstalled."); if let Some(bundle) = bundle && let Err(e) = move_to_trash(&bundle) { log_line("app", &format!("couldn't move the app to the Trash: {e}")); text = format!("Lune is uninstalled. Drag {} to the Trash to finish.", bundle.display()); } if !done.removed.is_empty() { text.push_str(&format!("\n\nRemoved:\n{}", done.removed.join("\n"))); } if !done.kept.is_empty() { text.push_str(&format!("\n\nKept:\n{}", done.kept.join("\n"))); } if let Some(p) = done.hub_problem { text.push_str(&format!("\n\nNote: {p}")); } text } Err(e) => format!("Uninstall stopped before removing anything else: {e:#}\n\nOpen Lune again to keep syncing."), }; app.dialog().message(message).title("Lune").buttons(MessageDialogButtons::Ok).blocking_show(); app.exit(0); } /// The system's own "move to Trash" (Finder's way needs an extra permission and fails quietly without it). fn move_to_trash(path: &std::path::Path) -> Result<(), trash::Error> { let mut ctx = trash::TrashContext::default(); #[cfg(target_os = "macos")] { use trash::macos::{DeleteMethod, TrashContextExtMacos}; ctx.set_delete_method(DeleteMethod::NsFileManager); } ctx.delete(path) } fn handle_links(app: &AppHandle, urls: Vec) { for url in urls { if let Some(c) = Connect::from_url(&url) { *app.state::().pending.lock().unwrap() = Some(c); show_window(app); } } } fn main() { tauri::Builder::default() .plugin(tauri_plugin_deep_link::init()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, None)) .manage(AppState::default()) .invoke_handler(tauri::generate_handler![ commands::overview, commands::connect, commands::choose_folder, commands::share_now, commands::held_share, commands::held_undo, commands::secret_pointer, commands::not_a_secret, commands::compare, commands::tidy, commands::open_canvas, commands::open_folder, commands::restart, ]) .setup(|app| { let handle = app.handle().clone(); let _ = APP.set(handle.clone()); remote::set_client_version(&app.package_info().version.to_string()); #[cfg(target_os = "macos")] app.set_activation_policy(tauri::ActivationPolicy::Accessory); build_tray(&handle)?; // The engine: the same one `lunesync run` uses, in this process. std::thread::spawn(|| { loop { if let Err(e) = supervisor::supervise(log_line) { log_line("app", &format!("sync stopped: {e:#} — restarting in 10 s")); } if runner::STOP.load(Ordering::Relaxed) { return; } std::thread::sleep(Duration::from_secs(10)); } }); let tray_handle = handle.clone(); std::thread::spawn(move || { loop { refresh_tray(&tray_handle); std::thread::sleep(Duration::from_secs(3)); } }); let update_handle = handle.clone(); tauri::async_runtime::spawn(async move { tokio_sleep(Duration::from_secs(15)).await; loop { check_for_update(&update_handle).await; tokio_sleep(Duration::from_secs(6 * 3600)).await; } }); let link_handle = handle.clone(); app.deep_link().on_open_url(move |event| handle_links(&link_handle, event.urls())); if let Ok(Some(urls)) = app.deep_link().get_current() { handle_links(&handle, urls); } if Config::load().map(|c| c.hubs.is_empty() && c.vaults.is_empty()).unwrap_or(true) { show_window(&handle); } Ok(()) }) .on_window_event(|window, event| { // Closing the window keeps Lune running in the menu bar. if let WindowEvent::CloseRequested { api, .. } = event { api.prevent_close(); let _ = window.hide(); } }) .run(tauri::generate_context!()) .expect("Lune couldn't start"); } async fn tokio_sleep(d: Duration) { let _ = tauri::async_runtime::spawn_blocking(move || std::thread::sleep(d)).await; }