use ferrokit_core::kept::{UiCell, UiLocal};
use objc2::rc::{Allocated, Retained};
use objc2::runtime::{AnyClass, AnyObject, Bool, NSObject};
use objc2::{MainThreadOnly, define_class, msg_send};
use objc2_foundation::{NSBundle, NSDate, NSError, NSString};
use std::path::Path;
use std::rc::Rc;
use std::time::{Duration, SystemTime};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum UpdateEvent {
Found {
version: String,
},
UpToDate,
ReadyOnQuit {
version: String,
},
Failed {
message: String,
},
}
type Handler = Rc<dyn Fn(&UpdateEvent)>;
struct Sparkle {
controller: Retained<NSObject>,
updater: Retained<NSObject>,
_delegate: Retained<Delegate>,
}
thread_local! {
static SPARKLE: UiCell<Option<Sparkle>> = const { UiCell::new(None) };
static HANDLERS: UiCell<Vec<Handler>> = const { UiCell::new(Vec::new()) };
static STARTUP_ERROR: UiCell<Option<String>> = const { UiCell::new(None) };
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitUpdatesDelegate"]
struct Delegate;
impl Delegate {
#[unsafe(method(updater:didFindValidUpdate:))]
fn found(&self, _updater: &AnyObject, item: &AnyObject) {
crate::failure::guard("the updater (found)", (), || {
emit(UpdateEvent::Found { version: version_of(item) });
})
}
#[unsafe(method(updaterDidNotFindUpdate:))]
fn up_to_date(&self, _updater: &AnyObject) {
crate::failure::guard("the updater (up_to_date)", (), || {
emit(UpdateEvent::UpToDate);
})
}
#[unsafe(method(updater:didAbortWithError:))]
fn aborted(&self, _updater: &AnyObject, error: &NSError) {
crate::failure::guard("the updater (aborted)", (), || {
if error.code() != NO_UPDATE {
emit(UpdateEvent::Failed { message: error.localizedDescription().to_string() });
}
})
}
#[unsafe(method(updater:willInstallUpdateOnQuit:immediateInstallationBlock:))]
fn ready(&self, _updater: &AnyObject, item: &AnyObject, _install_now: *mut std::ffi::c_void) -> Bool {
emit(UpdateEvent::ReadyOnQuit { version: version_of(item) });
Bool::NO
}
}
);
const NO_UPDATE: isize = 1001;
fn version_of(item: &AnyObject) -> String {
let v: Option<Retained<NSString>> = unsafe { msg_send![item, displayVersionString] };
v.map(|v| v.to_string()).unwrap_or_default()
}
fn emit(event: UpdateEvent) {
let handlers: Vec<Handler> = HANDLERS.with_borrow(Clone::clone);
for h in handlers {
crate::failure::entry("an update event's handler", (), || h(&event));
}
}
fn failed(message: String) {
eprintln!("ferrokit: updates are off: {message}");
STARTUP_ERROR.with_borrow_mut(|e| *e = Some(message));
}
pub(crate) fn start() -> Option<Retained<NSObject>> {
let main = NSBundle::mainBundle();
let info = |key: &str| main.objectForInfoDictionaryKey(&NSString::from_str(key));
let framework = main.privateFrameworksPath().map(|p| Path::new(&p.to_string()).join("Sparkle.framework"));
let has_framework = framework.as_ref().is_some_and(|f| f.exists());
let has_feed = info("SUFeedURL").is_some();
match (has_framework, has_feed) {
(false, false) => return None,
(false, true) => {
failed("the app names an update feed (SUFeedURL) but its bundle has no Sparkle.framework: bundle it with `cargo ferrokit bundle` and [package.metadata.ferrokit.updates]".into());
return None;
}
(true, false) => {
failed("the app's bundle has Sparkle.framework but no update feed (SUFeedURL in Info.plist)".into());
return None;
}
(true, true) => {}
}
if info("SUPublicEDKey").is_none() {
failed("the app's Info.plist has no SUPublicEDKey: Sparkle won't install updates it can't check".into());
return None;
}
let framework = framework?;
let path = NSString::from_str(&framework.to_string_lossy());
let loaded = match NSBundle::bundleWithPath(&path) {
Some(b) => unsafe { b.loadAndReturnError() }.map_err(|e| {
let debug = e.userInfo().objectForKey(&NSString::from_str("NSDebugDescription")).and_then(|d| d.downcast::<NSString>().ok()).map(|d| format!(" ({d})")).unwrap_or_default();
format!("{}{debug}", e.localizedDescription())
}),
None => Err("not a bundle".into()),
};
let class = loaded.and_then(|()| AnyClass::get(c"SPUStandardUpdaterController").ok_or_else(|| "no SPUStandardUpdaterController".into()));
let class = match class {
Ok(c) => c,
Err(e) => {
failed(format!("couldn't load {}: {e}", framework.display()));
return None;
}
};
let delegate: Retained<Delegate> = {
let d = Delegate::alloc(crate::mtm()).set_ivars(());
unsafe { msg_send![super(d), init] }
};
let controller: Option<Retained<NSObject>> = unsafe {
let alloc: Allocated<NSObject> = msg_send![class, alloc];
msg_send![alloc, initWithStartingUpdater: true, updaterDelegate: &*delegate, userDriverDelegate: Option::<&AnyObject>::None]
};
let Some(controller) = controller else {
failed("Sparkle's updater controller didn't start".into());
return None;
};
let updater: Retained<NSObject> = unsafe { msg_send![&controller, updater] };
SPARKLE.with_borrow_mut(|s| *s = Some(Sparkle { controller: controller.clone(), updater, _delegate: delegate }));
Some(controller)
}
fn with_updater<R>(f: impl FnOnce(&NSObject) -> R) -> Option<R> {
let updater = SPARKLE.with_borrow(|s| s.as_ref().map(|s| s.updater.clone()))?;
Some(f(&updater))
}
pub fn available() -> bool {
SPARKLE.with_borrow(Option::is_some)
}
pub fn check() {
if let Some(controller) = SPARKLE.with_borrow(|s| s.as_ref().map(|s| s.controller.clone())) {
let _: () = unsafe { msg_send![&controller, checkForUpdates: Option::<&AnyObject>::None] };
}
}
pub fn check_in_background() {
with_updater(|u| unsafe { msg_send![u, checkForUpdatesInBackground] }).unwrap_or(());
}
pub fn can_check() -> bool {
with_updater(|u| unsafe { msg_send![u, canCheckForUpdates] }).unwrap_or(false)
}
pub fn automatic_checks() -> bool {
with_updater(|u| unsafe { msg_send![u, automaticallyChecksForUpdates] }).unwrap_or(false)
}
pub fn set_automatic_checks(on: bool) {
with_updater(|u| unsafe { msg_send![u, setAutomaticallyChecksForUpdates: on] }).unwrap_or(());
}
pub fn automatic_downloads() -> bool {
with_updater(|u| unsafe { msg_send![u, automaticallyDownloadsUpdates] }).unwrap_or(false)
}
pub fn set_automatic_downloads(on: bool) {
with_updater(|u| unsafe { msg_send![u, setAutomaticallyDownloadsUpdates: on] }).unwrap_or(());
}
pub fn last_check() -> Option<SystemTime> {
let date: Option<Retained<NSDate>> = with_updater(|u| unsafe { msg_send![u, lastUpdateCheckDate] }).flatten();
date.map(|d| SystemTime::UNIX_EPOCH + Duration::from_secs_f64(d.timeIntervalSince1970().max(0.0)))
}
pub fn on_event(f: impl Fn(&UpdateEvent) + 'static) {
let f: Handler = Rc::new(f);
HANDLERS.with_borrow_mut(|h| h.push(f.clone()));
if let Some(message) = STARTUP_ERROR.with_borrow(Clone::clone) {
crate::later(move || {
let event = UpdateEvent::Failed { message: message.clone() };
crate::failure::entry("an update event's handler", (), || f(&event));
});
}
}