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
use bevy::time::Timer;
use log::{debug, warn};
use objc2::rc::Retained;
use objc2_app_kit::{NSApplicationActivationPolicy, NSRunningApplication};
use objc2_core_foundation::{CFRetained, CFString};
use objc2_foundation::{
NSKeyValueObservingOptions, NSObjectNSKeyValueObserverRegistration, NSString,
};
use std::pin::Pin;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, Ordering};
use stdext::function_name;
use crate::platform::{Pid, ProcessSerialNumber, WorkspaceObserver};
use crate::skylight::OSStatus;
unsafe extern "C" {
/// Get a copy of the name of a process.
///
/// # Deprecated
/// Use the `localizedName` property of the appropriate `NSRunningApplication` object.
///
/// # Discussion
/// Use this call to get the name of a process as a `CFString`. The name returned is a copy,
/// so the caller must `CFRelease` the name when finished with it. The difference between
/// this call and the `processName` field filled in by `GetProcessInformation` is that
/// the name here is a `CFString`, and thus is capable of representing a multi-lingual name,
/// whereas previously only a mac-encoded string was possible.
///
/// # Mac OS X threading
/// Thread safe since version 10.3
///
/// # Arguments
///
/// * `psn` - Serial number of the target process.
/// * `name` - `CFString` representing the name of the process (must be released by caller with `CFRelease`).
///
/// # Returns
///
/// An `OSStatus` indicating success or failure.
///
/// # Original signature:
/// `OSStatus` CopyProcessName(const `ProcessSerialNumber` *psn, `CFStringRef` *name);
fn CopyProcessName(psn: *const ProcessSerialNumber, name: *mut *const CFString) -> OSStatus;
/// Get the UNIX process ID corresponding to a process.
///
/// # Deprecated
/// Use the `processIdentifier` property of the appropriate `NSRunningApplication` object.
///
/// # Discussion
/// Given a Process serial number, this call will get the UNIX process ID for that process.
/// Note that this call does not make sense for Classic apps, since they all share a single
/// UNIX process ID.
///
/// # Mac OS X threading
/// Thread safe since version 10.3
///
/// # Arguments
///
/// * `psn` - Serial number of the target process.
/// * `pid` - UNIX process ID of the process.
///
/// # Returns
///
/// An `OSStatus` indicating success or failure.
/// # Original signature:
/// `OSStatus` GetProcessPID(const `ProcessSerialNumber` *psn, `pid_t` *pid);
fn GetProcessPID(psn: *const ProcessSerialNumber, pid: *mut Pid) -> OSStatus;
}
pub type ProcessRef = Pin<Box<Process>>;
#[repr(C)]
pub struct Process {
pub psn: ProcessSerialNumber,
pub pid: Pid,
pub name: String,
pub terminated: bool,
pub application: Option<Retained<NSRunningApplication>>,
pub policy: NSApplicationActivationPolicy,
pub ready_timer: Timer,
pub observer: Retained<WorkspaceObserver>,
pub observing_launched: AtomicBool,
pub observing_activated: AtomicBool,
}
impl Drop for Process {
/// Cleans up observers when the `Process` object is dropped.
fn drop(&mut self) {
self.unobserve_finished_launching();
self.unobserve_activation_policy();
}
}
impl Process {
/// Creates a new `Process` instance. It retrieves process information and attempts to get an `NSRunningApplication` instance.
///
/// # Arguments
///
/// * `psn` - A reference to the `ProcessSerialNumber` of the process.
/// * `observer` - A `Retained<WorkspaceObserver>` for observing workspace events.
///
/// # Returns
///
/// A `Pin<Box<Self>>` containing the new `Process` instance.
pub fn new(psn: &ProcessSerialNumber, observer: Retained<WorkspaceObserver>) -> Pin<Box<Self>> {
const READY_TIMEOUT_SEC: f32 = 2.0;
let mut pid: Pid = 0;
unsafe { GetProcessPID(psn, NonNull::from(&mut pid).as_ptr()) };
let mut nameref: *const CFString = std::ptr::null();
unsafe { CopyProcessName(psn, &raw mut nameref) };
let name = NonNull::new(nameref.cast_mut())
.map(|ptr| unsafe { CFRetained::from_raw(ptr) })
.map(|name| name.to_string())
.unwrap_or_default();
// [[NSRunningApplication runningApplicationWithProcessIdentifier:process->pid] retain];
let apps = NSRunningApplication::runningApplicationWithProcessIdentifier(pid);
Box::pin(Process {
psn: psn.clone(),
name,
pid,
terminated: false,
application: apps,
policy: NSApplicationActivationPolicy::Prohibited,
ready_timer: Timer::from_seconds(READY_TIMEOUT_SEC, bevy::time::TimerMode::Once),
observer,
observing_launched: AtomicBool::new(false),
observing_activated: AtomicBool::new(false),
})
}
/// Checks if the application associated with this process is observable (i.e., has a regular activation policy).
/// It updates the internal `policy` field.
///
/// # Returns
///
/// `true` if the application is observable, `false` otherwise.
pub fn is_observable(&mut self) -> bool {
if let Some(app) = &self.application {
self.policy = app.activationPolicy();
self.policy == NSApplicationActivationPolicy::Regular
} else {
self.policy = NSApplicationActivationPolicy::Prohibited;
false
}
}
/// Checks if the application associated with this process has finished launching.
///
/// # Returns
///
/// `true` if the application has finished launching, `false` otherwise.
pub fn finished_launching(&self) -> bool {
self.application
.as_ref()
.is_some_and(|app| app.isFinishedLaunching())
}
/// Subscribes to "finishedLaunching" key-value observations for the associated `NSRunningApplication`.
pub fn observe_finished_launching(&self) {
if !self.observing_launched.swap(true, Ordering::Relaxed) {
self.observe("finishedLaunching");
}
}
/// Unsubscribes from "finishedLaunching" key-value observations.
pub fn unobserve_finished_launching(&self) {
if self.observing_launched.swap(false, Ordering::Relaxed) {
self.unobserve("finishedLaunching");
}
}
/// Subscribes to "activationPolicy" key-value observations for the associated `NSRunningApplication`.
pub fn observe_activation_policy(&self) {
if !self.observing_activated.swap(true, Ordering::Relaxed) {
self.observe("activationPolicy");
}
}
/// Unsubscribes from "activationPolicy" key-value observations.
pub fn unobserve_activation_policy(&self) {
if self.observing_activated.swap(false, Ordering::Relaxed) {
self.unobserve("activationPolicy");
}
}
/// Helper function to add a key-value observer for a specified `flavor` (key path).
///
/// # Arguments
///
/// * `flavor` - The key path string to observe (e.g., "finishedLaunching", "activationPolicy").
fn observe(&self, flavor: &str) {
if let Some(app) = self.application.as_ref() {
unsafe {
let key_path = NSString::from_str(flavor);
let options = NSKeyValueObservingOptions::New | NSKeyValueObservingOptions::Initial;
app.addObserver_forKeyPath_options_context(
&self.observer,
key_path.as_ref(),
options,
NonNull::from(self).as_ptr().cast(),
);
}
debug!(
"{}: observing {flavor} for {}",
function_name!(),
&self.name
);
}
}
/// Helper function to remove a key-value observer for a specified `flavor` (key path).
///
/// # Arguments
///
/// * `flavor` - The key path string to unobserve.
fn unobserve(&self, flavor: &str) {
if let Some(app) = self.application.as_ref() {
unsafe {
let key_path = NSString::from_str(flavor);
app.removeObserver_forKeyPath_context(
&self.observer,
key_path.as_ref(),
NonNull::from(self).as_ptr().cast(),
);
}
debug!(
"{}: removed {flavor} observers for {}",
function_name!(),
&self.name
);
}
}
/// Checks if the process is ready for window management (finished launching and is observable).
/// It subscribes to and unsubscribes from observers as needed to ensure the ready state.
///
/// # Returns
///
/// `true` if the process is ready, `false` otherwise.
pub fn ready(&mut self) -> bool {
if !self.finished_launching() {
debug!(
"{}: {} ({}) is not finished launching, subscribing to finishedLaunching changes",
function_name!(),
self.name,
self.pid
);
self.observe_finished_launching();
// NOTE: Do this again in case of race-conditions between the previous check and
// key-value observation subscription. Not actually sure if this can happen in
// practice..
if !self.finished_launching() {
return false;
}
self.unobserve_finished_launching();
warn!(
"{}: {} suddenly finished launching",
function_name!(),
self.name
);
}
if !self.is_observable() {
debug!(
"{}: {} ({}) is not observable, subscribing to activationPolicy changes",
function_name!(),
self.name,
self.pid
);
self.observe_activation_policy();
// NOTE: Do this again in case of race-conditions between the previous check and
// key-value observation subscription. Not actually sure if this can happen in
// practice..
if !self.is_observable() {
return false;
}
self.unobserve_activation_policy();
warn!(
"{}: {} suddenly became observable",
function_name!(),
self.name
);
}
true
}
}