diff --git a/desktop/crates/radicle-tauri/capabilities/default.json b/desktop/crates/radicle-tauri/capabilities/default.json index 5b2a7eaca..260b1e9c5 100644 --- a/desktop/crates/radicle-tauri/capabilities/default.json +++ b/desktop/crates/radicle-tauri/capabilities/default.json @@ -14,6 +14,7 @@ "core:resources:default", "core:tray:default", "core:webview:default", + "core:window:allow-close", "core:window:allow-set-badge-count", "core:window:allow-start-dragging", "core:window:default", diff --git a/desktop/crates/radicle-tauri/src/lib.rs b/desktop/crates/radicle-tauri/src/lib.rs index 58dfd9497..8b2198918 100644 --- a/desktop/crates/radicle-tauri/src/lib.rs +++ b/desktop/crates/radicle-tauri/src/lib.rs @@ -1,7 +1,12 @@ mod commands; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + use radicle_types::AppState; -use tauri::Manager; +#[cfg(target_os = "macos")] +use tauri::menu::{Menu, MenuItem, MenuItemKind}; +use tauri::{Emitter, Manager}; use tauri_plugin_log::{Target, TargetKind}; use commands::{auth, cob, diff, identity, inbox, profile, repo, startup, thread}; @@ -52,7 +57,7 @@ pub fn run() { .build(), ); - builder + let builder = builder .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_clipboard_manager::init()) @@ -61,7 +66,18 @@ pub fn run() { .setup(|app| { register_rad_scheme(app); Ok(()) - }) + }); + // Tauri only installs a default menu on macOS, so only there is one + // replaced. + #[cfg(target_os = "macos")] + let builder = builder.menu(app_menu).on_menu_event(|app, event| { + if event.id() == QUIT { + quit(app); + } + }); + + builder + .on_window_event(flush_before_close) .invoke_handler(tauri::generate_handler![ auth::authenticate, auth::init, @@ -151,6 +167,71 @@ pub fn run() { .expect("error while running tauri application"); } +#[cfg(target_os = "macos")] +const QUIT: &str = "quit"; + +// The default menu's Quit terminates the app without closing its window, which +// would skip the flush below, so it's replaced by one that closes the window. +#[cfg(target_os = "macos")] +fn app_menu(app: &tauri::AppHandle) -> tauri::Result> { + let menu = Menu::default(app)?; + for item in menu.items()? { + let MenuItemKind::Submenu(submenu) = item else { + continue; + }; + for (index, entry) in submenu.items()?.into_iter().enumerate() { + let MenuItemKind::Predefined(predefined) = entry else { + continue; + }; + let text = predefined.text()?; + if !text.trim_start_matches('&').starts_with("Quit") { + continue; + } + submenu.remove(&predefined)?; + let item = MenuItem::with_id(app, QUIT, text, true, Some("CmdOrCtrl+Q"))?; + submenu.insert(&item, index)?; + } + } + Ok(menu) +} + +#[cfg(target_os = "macos")] +fn quit(app: &tauri::AppHandle) { + match app.get_webview_window("main") { + Some(window) => { + if let Err(e) = window.close() { + log::warn!("Unable to close the main window: {e}"); + app.exit(0); + } + } + None => app.exit(0), + } +} + +// The frontend holds back some writes, such as board changes, to batch them. +// The first close asks it to flush and close the window itself, which it does +// as soon as the flush is through; if it doesn't within five seconds, the +// window closes anyway. +fn flush_before_close(window: &tauri::Window, event: &tauri::WindowEvent) { + static CLOSING: AtomicBool = AtomicBool::new(false); + + let tauri::WindowEvent::CloseRequested { api, .. } = event else { + return; + }; + if CLOSING.swap(true, Ordering::SeqCst) { + return; + } + api.prevent_close(); + if let Err(e) = window.emit("close-requested", ()) { + log::warn!("Unable to ask the frontend to flush before closing: {e}"); + } + let window = window.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_secs(5)); + let _ = window.close(); + }); +} + // Installers register the scheme; an AppImage has to do it at runtime. It // must never keep the app from starting, nor take the scheme from another // handler, such as an installed package or one the user chose. diff --git a/desktop/src/lib/closeFlush.ts b/desktop/src/lib/closeFlush.ts new file mode 100644 index 000000000..0831c004d --- /dev/null +++ b/desktop/src/lib/closeFlush.ts @@ -0,0 +1,39 @@ +import { listen } from "@tauri-apps/api/event"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import once from "lodash/once"; + +// A flush writes what a view holds back; `announce` is whether the writes +// are announced to the network as well. +type Flush = (announce: boolean) => Promise; + +const flushes = new Set(); + +// Closing writes locally only: the commits and signed refs land, and peers +// learn of them with the next announcement for the repository or when the +// node restarts. +async function flushAll() { + await Promise.allSettled([...flushes].map(flush => flush(false))); +} + +// The backend holds the first close of the window until the frontend has +// written what it was holding back, and closing the window once that's done +// lets it go right away. The test backend has no window, so the page flushes +// as it goes away or is hidden instead. +export const listenForClose = once(async () => { + if (!window.__TAURI_INTERNALS__) { + window.addEventListener("pagehide", () => void flushAll()); + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "hidden") void flushAll(); + }); + return; + } + await listen("close-requested", async () => { + await flushAll(); + await getCurrentWindow().close(); + }); +}); + +export function flushBeforeClose(flush: Flush): () => void { + flushes.add(flush); + return () => flushes.delete(flush); +} diff --git a/desktop/src/main.ts b/desktop/src/main.ts index f3ae2816f..cc2ea98e2 100644 --- a/desktop/src/main.ts +++ b/desktop/src/main.ts @@ -2,6 +2,7 @@ import "overlayscrollbars/overlayscrollbars.css"; import { mount } from "svelte"; import App from "./App.svelte"; +import { listenForClose } from "./lib/closeFlush"; import { disableDropNavigation } from "./lib/disableDropNavigation"; import { disableNativeContextMenu } from "./lib/disableNativeContextMenu"; @@ -9,5 +10,6 @@ const app = mount(App, { target: document.body }); disableNativeContextMenu(); disableDropNavigation(); +void listenForClose(); export default app;