#[cfg(target_os = "macos")]
pub(crate) fn install() -> bool {
macos::install()
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn install() -> bool {
false
}
#[cfg(target_os = "macos")]
mod macos {
use block2::RcBlock;
use objc2::rc::Retained;
use objc2::runtime::NSObjectProtocol;
use objc2::sel;
use objc2_app_kit::{
NSApplication, NSApplicationActivationOptions, NSApplicationActivationPolicy,
NSApplicationDidBecomeActiveNotification, NSApplicationWillBecomeActiveNotification,
NSEventType, NSRunningApplication, NSWorkspace,
};
use objc2_foundation::{
MainThreadMarker, NSActivityOptions, NSNotification, NSNotificationCenter, NSProcessInfo,
NSString,
};
use std::cell::RefCell;
use std::ptr::NonNull;
use std::rc::Rc;
type Previous = Rc<RefCell<Option<Retained<NSRunningApplication>>>>;
pub(super) fn install() -> bool {
let Some(mtm) = MainThreadMarker::new() else {
eprintln!("iced-mcp: background launch needs the main thread; the app may take focus");
return false;
};
unsafe {
let me = NSRunningApplication::currentApplication().processIdentifier();
let previous: Previous = Rc::new(RefCell::new(frontmost_other(me)));
let remember = previous.clone();
let will = RcBlock::new(move |_: NonNull<NSNotification>| {
if let Some(app) = frontmost_other(me) {
*remember.borrow_mut() = Some(app);
}
});
let give_back = previous.clone();
let did = RcBlock::new(move |_: NonNull<NSNotification>| {
let app = NSApplication::sharedApplication(mtm);
app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
if clicked(&app) {
return;
}
match give_back.borrow().as_ref() {
Some(previous) => {
if app.respondsToSelector(sel!(yieldActivationToApplication:)) {
app.yieldActivationToApplication(previous);
}
previous.activateWithOptions(NSApplicationActivationOptions::empty());
}
None => app.deactivate(),
}
});
let center = NSNotificationCenter::defaultCenter();
let will = center.addObserverForName_object_queue_usingBlock(
Some(NSApplicationWillBecomeActiveNotification),
None,
None,
&will,
);
let did = center.addObserverForName_object_queue_usingBlock(
Some(NSApplicationDidBecomeActiveNotification),
None,
None,
&did,
);
std::mem::forget((will, did));
let activity = NSProcessInfo::processInfo().beginActivityWithOptions_reason(
NSActivityOptions::NSActivityUserInitiatedAllowingIdleSystemSleep,
&NSString::from_str("driven by iced-mcp"),
);
std::mem::forget(activity);
}
true
}
unsafe fn frontmost_other(me: i32) -> Option<Retained<NSRunningApplication>> {
NSWorkspace::sharedWorkspace()
.frontmostApplication()
.filter(|app| app.processIdentifier() != me)
}
fn clicked(app: &NSApplication) -> bool {
app.currentEvent().is_some_and(|event| {
matches!(
unsafe { event.r#type() },
NSEventType::LeftMouseDown
| NSEventType::RightMouseDown
| NSEventType::OtherMouseDown
)
})
}
}