1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
use core::ptr::NonNull;
use log::{debug, info, warn};
use objc2::rc::Retained;
use objc2::{AllocAnyThread, DefinedClass, define_class, msg_send, sel};
use objc2_app_kit::{
NSApplicationActivationPolicy, NSRunningApplication, NSWorkspace, NSWorkspaceApplicationKey,
};
use objc2_foundation::{
NSDictionary, NSDistributedNotificationCenter, NSKeyValueChangeNewKey, NSNotification,
NSNotificationCenter, NSNumber, NSObject, NSString,
};
use std::ffi::c_void;
use stdext::function_name;
use crate::events::{Event, EventSender};
use crate::manager::Process;
/// `Ivars` is a helper struct to hold instance variables for Objective-C classes implemented in Rust.
/// It primarily stores an `EventSender` for communication with the main event loop.
#[derive(Debug, Clone)]
pub struct Ivars {
/// The `EventSender` to dispatch events.
events: EventSender,
}
define_class!(
// SAFETY:
// - The superclass NSObject does not have any subclassing requirements.
// - `Observer` does not implement `Drop`.
#[unsafe(super(NSObject))]
// If we were implementing delegate methods like `NSApplicationDelegate`,
// we would specify the object to only be usable on the main thread:
// #[thread_kind = MainThreadOnly]
#[name = "Observer"]
#[ivars = Ivars]
#[derive(Debug)]
pub struct WorkspaceObserver;
impl WorkspaceObserver {
/// Called when the active display changes.
///
/// # Arguments
///
/// * `_` - The notification object (unused).
#[unsafe(method(activeDisplayDidChange:))]
fn display_changed(&self, _: &NSNotification) {
_ = self.ivars().events.send(Event::DisplayChanged);
}
/// Called when the active space changes.
///
/// # Arguments
///
/// * `_` - The notification object (unused).
#[unsafe(method(activeSpaceDidChange:))]
fn space_changed(&self, _: &NSNotification) {
_ = self.ivars().events.send(Event::SpaceChanged);
}
/// Called when an application is hidden.
///
/// # Arguments
///
/// * `notification` - The notification object containing application info.
#[unsafe(method(didHideApplication:))]
fn application_hidden(&self, notification: &NSObject) {
let pid = unsafe {
let user_info: &NSDictionary = msg_send![notification, userInfo];
let app: &NSRunningApplication = msg_send![user_info, objectForKey: NSWorkspaceApplicationKey];
app.processIdentifier()
};
let msg = Event::ApplicationHidden{ pid };
_ = self.ivars().events.send(msg);
}
/// Called when an application is unhidden.
///
/// # Arguments
///
/// * `notification` - The notification object containing application info.
#[unsafe(method(didUnhideApplication:))]
fn application_unhidden(&self, notification: &NSObject) {
let pid = unsafe {
let user_info: &NSDictionary = msg_send![notification, userInfo];
let app: &NSRunningApplication = msg_send![user_info, objectForKey: NSWorkspaceApplicationKey];
app.processIdentifier()
};
let msg = Event::ApplicationVisible{ pid };
_ = self.ivars().events.send(msg);
}
/// Called when the system wakes from sleep.
///
/// # Arguments
///
/// * `notification` - The notification object.
#[unsafe(method(didWake:))]
fn system_woke(&self, notification: &NSObject) {
let msg = Event::SystemWoke{
msg: format!("WorkspaceObserver: {notification:?}"),
};
_ = self.ivars().events.send(msg);
}
/// Called when the menu bar hiding state changes.
///
/// # Arguments
///
/// * `notification` - The notification object.
#[unsafe(method(didChangeMenuBarHiding:))]
fn menubar_hidden(&self, notification: &NSObject) {
let msg = Event::MenuBarHiddenChanged{
msg: format!("WorkspaceObserver: {notification:?}"),
};
_ = self.ivars().events.send(msg);
}
/// Called when the Dock restarts.
///
/// # Arguments
///
/// * `notification` - The notification object.
#[unsafe(method(didRestartDock:))]
fn dock_restarted(&self, notification: &NSObject) {
let msg = Event::DockDidRestart{
msg: format!("WorkspaceObserver: {notification:?}"),
};
_ = self.ivars().events.send(msg);
}
/// Called when Dock preferences change.
///
/// # Arguments
///
/// * `notification` - The notification object.
#[unsafe(method(didChangeDockPref:))]
fn dock_pref_changed(&self, notification: &NSObject) {
let msg = Event::DockDidChangePref{
msg: format!("WorkspaceObserver: {notification:?}"),
};
_ = self.ivars().events.send(msg);
}
/// Called when a key-value observed property changes for a process.
///
/// # Arguments
///
/// * `key_path` - The key path of the changed property.
/// * `_object` - The object being observed (unused).
/// * `change` - A dictionary containing details of the change.
/// * `context` - The context pointer, expected to be a `*mut Process`.
#[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
fn observe_value_for_keypath(
&self,
key_path: &NSString,
_object: &NSObject,
change: &NSDictionary,
context: *mut c_void,
) {
let Some(process) = NonNull::new(context).map(|ptr| unsafe { ptr.cast::<Process>().as_mut() }) else {
warn!("{}: null pointer passed as context", function_name!());
return;
};
let result = unsafe { change.objectForKey(NSKeyValueChangeNewKey) };
let policy = result.and_then(|result| result.downcast_ref::<NSNumber>().map(NSNumber::intValue));
match key_path.to_string().as_ref() {
"finishedLaunching" => {
if policy.is_some_and(|value| value != 1) {
return;
}
process.unobserve_finished_launching();
}
"activationPolicy" => {
if policy.is_some_and(|value| i32::try_from(process.policy.0).is_ok_and(|policy| value == policy)) {
return;
}
process.policy = NSApplicationActivationPolicy(policy.unwrap() as isize);
process.unobserve_activation_policy();
}
err => {
warn!("{}: unknown key path {err:?}", function_name!());
return;
}
}
let msg = Event::ApplicationLaunched {
psn: process.psn,
observer: process.observer.clone(),
};
_= self.ivars().events.send(msg);
debug!(
"{}: got {key_path:?} for {}",
function_name!(),
process.name
);
}
}
);
impl WorkspaceObserver {
/// Creates a new `WorkspaceObserver` instance.
///
/// # Arguments
///
/// * `events` - An `EventSender` to send workspace-related events.
///
/// # Returns
///
/// A `Retained<Self>` containing the new `WorkspaceObserver` instance.
pub(super) fn new(events: EventSender) -> Retained<Self> {
// Initialize instance variables.
let this = Self::alloc().set_ivars(Ivars { events });
// Call `NSObject`'s `init` method.
unsafe { msg_send![super(this), init] }
}
/// Starts observing workspace notifications by registering selectors with `NSWorkspace` and `NSDistributedNotificationCenter`.
pub(super) fn start(&self) {
let methods = [
(
sel!(activeDisplayDidChange:),
"NSWorkspaceActiveDisplayDidChangeNotification",
),
(
sel!(activeSpaceDidChange:),
"NSWorkspaceActiveSpaceDidChangeNotification",
),
(
sel!(didHideApplication:),
"NSWorkspaceDidHideApplicationNotification",
),
(
sel!(didUnhideApplication:),
"NSWorkspaceDidUnhideApplicationNotification",
),
(sel!(didWake:), "NSWorkspaceDidWakeNotification"),
];
let shared_ws = NSWorkspace::sharedWorkspace();
let notification_center = shared_ws.notificationCenter();
for (sel, name) in &methods {
debug!("{}: registering {} with {name}", function_name!(), *sel);
let notification_type = NSString::from_str(name);
unsafe {
notification_center.addObserver_selector_name_object(
self,
*sel,
Some(¬ification_type),
None,
);
};
}
let methods = [
(
sel!(didChangeMenuBarHiding:),
"AppleInterfaceMenuBarHidingChangedNotification",
),
(sel!(didChangeDockPref:), "com.apple.dock.prefchanged"),
];
let distributed_notification_center = NSDistributedNotificationCenter::defaultCenter();
for (sel, name) in &methods {
debug!("{}: registering {} with {name}", function_name!(), *sel);
let notification_type = NSString::from_str(name);
unsafe {
distributed_notification_center.addObserver_selector_name_object(
self,
*sel,
Some(¬ification_type),
None,
);
};
}
let methods = [(
sel!(didRestartDock:),
"NSApplicationDockDidRestartNotification",
)];
let default_center = NSNotificationCenter::defaultCenter();
for (sel, name) in &methods {
debug!("{}: registering {} with {name}", function_name!(), *sel);
let notification_type = NSString::from_str(name);
unsafe {
default_center.addObserver_selector_name_object(
self,
*sel,
Some(¬ification_type),
None,
);
};
}
}
}
impl Drop for WorkspaceObserver {
/// Deregisters all previously registered notification callbacks when the `WorkspaceObserver` is dropped.
fn drop(&mut self) {
info!("{}: deregistering callbacks.", function_name!());
unsafe {
NSWorkspace::sharedWorkspace()
.notificationCenter()
.removeObserver(self);
NSNotificationCenter::defaultCenter().removeObserver(self);
NSDistributedNotificationCenter::defaultCenter().removeObserver(self);
}
}
}