use std::sync::{Arc, Mutex};
use objc2::MainThreadMarker;
use objc2_app_kit::{NSAlert, NSAlertFirstButtonReturn};
use objc2_foundation::NSString;
use tauri::menu::{Menu, MenuItem, Submenu};
use tauri::{AppHandle, Runtime};
use tauri_plugin_sparkle_updater::SparkleUpdaterExt;
static QUEUED_UPDATE: Mutex<Option<String>> = Mutex::new(None);
pub const CHECK_FOR_UPDATES_ID: &str = "check-for-updates";
#[cfg(target_arch = "x86_64")]
const INTEL_FEED_URL: &str =
"https://git.quineglobal.com/quine-global/homebrew-tap.git/tree/appcasts/quple-x86_64.xml?raw=true";
pub fn setup<R: Runtime>(app: &AppHandle<R>) {
let Some(updater) = app.sparkle_updater() else {
return;
};
updater.set_event_callback(Some(Arc::new(|name, payload| {
if name == "sparkle://will-install-update-on-quit" {
let version = payload
.get("version")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
*QUEUED_UPDATE.lock().unwrap() = Some(version);
}
})));
#[cfg(target_arch = "x86_64")]
if let Err(err) = updater.set_feed_url_override(Some(INTEL_FEED_URL.to_string())) {
eprintln!("quple: couldn't set the Intel appcast: {err}");
}
if updater.automatically_checks_for_updates().unwrap_or(false) {
if let Err(err) = updater.check_for_updates_in_background() {
eprintln!("quple: launch update check failed: {err}");
}
}
}
pub fn menu<R: Runtime>(handle: &AppHandle<R>) -> tauri::Result<Menu<R>> {
let menu = Menu::default(handle)?;
let app_menu = menu
.items()?
.into_iter()
.next()
.and_then(|item| item.as_submenu().cloned());
if let Some(app_menu) = app_menu {
insert_check_for_updates(handle, &app_menu)?;
}
Ok(menu)
}
fn insert_check_for_updates<R: Runtime>(
handle: &AppHandle<R>,
app_menu: &Submenu<R>,
) -> tauri::Result<()> {
let item = MenuItem::with_id(
handle,
CHECK_FOR_UPDATES_ID,
"Check for Updatesβ¦",
true,
None::<&str>,
)?;
app_menu.insert(&item, 1)?;
Ok(())
}
pub fn check_for_updates<R: Runtime>(app: &AppHandle<R>) {
let queued = QUEUED_UPDATE.lock().unwrap().clone();
if let Some(version) = queued {
if update_queued_alert(&version) {
app.exit(0);
}
return;
}
match app.sparkle_updater() {
Some(updater) => {
if let Err(err) = updater.check_for_updates() {
eprintln!("quple: update check failed: {err}");
}
}
None => eprintln!("quple: updates are only available in the packaged app"),
}
}
fn update_queued_alert(version: &str) -> bool {
let Some(mtm) = MainThreadMarker::new() else {
return false;
};
let title = if version.is_empty() {
"An update is ready to install".to_string()
} else {
format!("Quple {version} is ready to install")
};
let alert = NSAlert::new(mtm);
alert.setMessageText(&NSString::from_str(&title));
alert.setInformativeText(&NSString::from_str(
"It's already downloaded and installs when you quit Quple. Open the app again afterwards to use the new version.",
));
alert.addButtonWithTitle(&NSString::from_str("Quit Now"));
alert.addButtonWithTitle(&NSString::from_str("Later"));
alert.runModal() == NSAlertFirstButtonReturn
}