Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions src-tauri/src/login_item.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
//! macOS autostart as a real login item: `SMAppService.mainApp` registers
//! Weave.app itself, so System Settings lists it with the app's icon. The
//! LaunchAgent of tauri-plugin-autostart points at the bare executable inside
//! the bundle and shows up as a generic "exec" icon instead.
//! A login item gets no command-line arguments; the launch Apple Event tells
//! whether macOS started Weave at login.

use objc2::msg_send;
use objc2::rc::Retained;
use objc2::runtime::{AnyClass, AnyObject, Bool};
use std::ffi::{c_char, CStr};
use std::ptr;

#[link(name = "ServiceManagement", kind = "framework")]
extern "C" {}

/// `SMAppServiceStatusEnabled`.
const STATUS_ENABLED: isize = 1;

fn four_cc(code: &[u8; 4]) -> u32 {
u32::from_be_bytes(*code)
}

fn main_app_service() -> Result<Retained<AnyObject>, String> {
let class = AnyClass::get(c"SMAppService").ok_or("SMAppService ist nicht verfügbar.")?;
let service: Option<Retained<AnyObject>> = unsafe { msg_send![class, mainAppService] };
service.ok_or_else(|| "SMAppService ist nicht verfügbar.".into())
}

pub fn is_enabled() -> bool {
main_app_service().is_ok_and(|service| {
let status: isize = unsafe { msg_send![&*service, status] };
status == STATUS_ENABLED
})
}

pub fn set_enabled(enabled: bool) -> Result<(), String> {
let service = main_app_service()?;
let mut error: *mut AnyObject = ptr::null_mut();
let ok: Bool = unsafe {
if enabled {
msg_send![&*service, registerAndReturnError: &mut error as *mut *mut AnyObject]
} else {
msg_send![&*service, unregisterAndReturnError: &mut error as *mut *mut AnyObject]
}
};
if ok.as_bool() {
return Ok(());
}
Err(describe(error).unwrap_or_else(|| "Autostart konnte nicht geändert werden.".into()))
}

fn describe(error: *mut AnyObject) -> Option<String> {
let error = unsafe { error.as_ref() }?;
let text: Option<Retained<AnyObject>> = unsafe { msg_send![error, localizedDescription] };
let utf8: *const c_char = unsafe { msg_send![&*text?, UTF8String] };
(!utf8.is_null()).then(|| unsafe { CStr::from_ptr(utf8) }.to_string_lossy().into_owned())
}

/// True when macOS opened Weave as a login item. Valid only while the launch
/// event is handled, i.e. during the app's setup (didFinishLaunching).
pub fn launched_at_login() -> bool {
let Some(class) = AnyClass::get(c"NSAppleEventManager") else { return false };
unsafe {
let manager: Option<Retained<AnyObject>> = msg_send![class, sharedAppleEventManager];
let Some(manager) = manager else { return false };
let event: Option<Retained<AnyObject>> = msg_send![&*manager, currentAppleEvent];
let Some(event) = event else { return false };
let id: u32 = msg_send![&*event, eventID];
if id != four_cc(b"oapp") {
return false;
}
let property: Option<Retained<AnyObject>> = msg_send![&*event, paramDescriptorForKeyword: four_cc(b"prdt")];
let Some(property) = property else { return false };
let code: u32 = msg_send![&*property, enumCodeValue];
code == four_cc(b"lgit")
}
}
40 changes: 35 additions & 5 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
mod api;
mod auth;
mod deeplink;
#[cfg(target_os = "macos")]
mod login_item;
mod settings;
mod update;

Expand Down Expand Up @@ -178,7 +180,7 @@ async fn get_state(app: AppHandle, state: State<'_, AppState>) -> Result<StateVi
hotkey: effective.hotkey,
hotkey_managed: state.managed.hotkey.is_some(),
default_agent: effective.default_agent,
autostart: app.autolaunch().is_enabled().unwrap_or(false),
autostart: autostart_enabled(&app),
signed_in: session.is_some(),
username: session.as_ref().and_then(|s| s.username.clone()),
chat_url: session.and_then(|s| s.chat_url),
Expand Down Expand Up @@ -281,11 +283,25 @@ fn set_busy(app: AppHandle, state: State<'_, AppState>, busy: bool) {
drop(app);
}

#[cfg_attr(target_os = "macos", allow(unused_variables))]
fn autostart_enabled(app: &AppHandle) -> bool {
#[cfg(target_os = "macos")]
let enabled = login_item::is_enabled();
#[cfg(not(target_os = "macos"))]
let enabled = app.autolaunch().is_enabled().unwrap_or(false);
enabled
}

#[tauri::command]
fn set_autostart(app: AppHandle, enabled: bool) -> Result<(), String> {
let launcher = app.autolaunch();
let result = if enabled { launcher.enable() } else { launcher.disable() };
result.map_err(|e| e.to_string())?;
#[cfg(target_os = "macos")]
login_item::set_enabled(enabled)?;
#[cfg(not(target_os = "macos"))]
{
let launcher = app.autolaunch();
let result = if enabled { launcher.enable() } else { launcher.disable() };
result.map_err(|e| e.to_string())?;
}
notify_state(&app);
Ok(())
}
Expand Down Expand Up @@ -892,6 +908,20 @@ fn main() {
});

let handle = app.handle().clone();
// Read before anything else: the launch event is only current now.
#[cfg(target_os = "macos")]
let launched_at_login = login_item::launched_at_login();
#[cfg(not(target_os = "macos"))]
let launched_at_login = false;
// Earlier versions used a LaunchAgent (generic "exec" icon in System
// Settings); move it over to the login item once.
#[cfg(target_os = "macos")]
if handle.autolaunch().is_enabled().unwrap_or(false) {
let _ = handle.autolaunch().disable();
if let Err(error) = login_item::set_enabled(true) {
eprintln!("login item not registered: {error}");
}
}
if let Some(quick) = handle.get_webview_window("quick") {
float_over_full_screen(&quick);
}
Expand All @@ -918,7 +948,7 @@ fn main() {
for url in &opened_by_link {
on_setup_link(&handle, url.as_str());
}
} else if !std::env::args().any(|arg| arg == AUTOSTART_ARG) {
} else if !launched_at_login && !std::env::args().any(|arg| arg == AUTOSTART_ARG) {
show_main(&handle);
}
let updater = handle.clone();
Expand Down
Loading