a7n-platform 0.39.1

Native desktop backends for the Apeirogon software KVM
Documentation
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// SPDX-License-Identifier: GPL-3.0-or-later

//! Edge glow, landing ring and haptic ticks on macOS; contract in [`super`].
//!
//! Two click-through, non-activating panels live on the process main thread,
//! which [`crate::main_thread::run`] keeps in its `CFRunLoop` (`AppKit` only
//! allows windows there). A bridge thread blocks on the tokio receiver, passes
//! commands over a std channel and signals a run-loop source on the main loop,
//! so nothing polls. The panels are created lazily inside that source's
//! callback, on the main thread. Without `main_thread::run` there is no main
//! run loop and [`start`] returns `None`, so tests never touch `AppKit`.

use std::ffi::c_void;
use std::sync::mpsc as sync;
use std::thread;
use std::time::{Duration, Instant};

use objc2::MainThreadMarker;
use objc2::rc::{Retained, autoreleasepool};
use objc2_app_kit::{
    NSBackingStoreType, NSBox, NSBoxType, NSColor, NSEvent, NSHapticFeedbackManager,
    NSHapticFeedbackPattern, NSHapticFeedbackPerformanceTime, NSHapticFeedbackPerformer, NSPanel,
    NSScreen, NSStatusWindowLevel, NSTitlePosition, NSWindowCollectionBehavior,
    NSWindowSharingType, NSWindowStyleMask, NSWorkspace,
};
use objc2_core_foundation::{
    CFAbsoluteTimeGetCurrent, CFRetained, CFRunLoop, CFRunLoopTimer, CFRunLoopTimerContext,
    kCFRunLoopDefaultMode,
};
use objc2_foundation::{NSPoint, NSRect, NSSize};
use tokio::sync::mpsc;

use super::look::{self, BEAM_THICKNESS};
use super::macos_geometry::{self as geometry, LANDING_DIAMETER, Rect};
use super::{Color, Command, Feedback, Landing, Look, Style};
use crate::main_thread::{self, Waker};

const GLOW_ALPHA: f64 = 0.65;
const LANDING_RING_WIDTH: f64 = 4.0;
/// Long enough to notice, short enough not to linger over the new window.
const LANDING_FADE: Duration = Duration::from_millis(700);
/// With Reduce Motion on the ring stays put instead of fading.
const LANDING_STATIC_HOLD: Duration = Duration::from_millis(500);
/// Never fires on its own; every landing re-arms it.
const TIMER_DISARMED_SECONDS: f64 = 1.0e12;
const LANDING_FRAME_SECONDS: f64 = 0.016;

/// State of the main-thread callbacks. Leaked on purpose: it lives as long as
/// the process and is only touched from main run-loop callbacks.
struct Ui {
    commands: sync::Receiver<Command>,
    panels: Option<Panels>,
}

struct Panels {
    mtm: MainThreadMarker,
    glow: Retained<NSPanel>,
    glow_fill: Retained<NSBox>,
    colors: [(Color, Retained<NSColor>); 4],
    landing: Retained<NSPanel>,
    landing_fill: Retained<NSBox>,
    landing_started: Instant,
    landing_center: (f64, f64),
    landing_look: Look,
    animate: bool,
    hide_landing: CFRetained<CFRunLoopTimer>,
}

pub(super) fn start() -> Option<Feedback> {
    if !main_thread::active() {
        return None;
    }
    let (feedback, receiver) = super::channel();
    let (command_tx, command_rx) = sync::channel();
    let ui = Box::leak(Box::new(Ui {
        commands: command_rx,
        panels: None,
    }));
    // SAFETY: `ui` is leaked, so the pointer is valid forever, and
    // `drain_commands` only runs on the main thread, one callback at a time.
    let waker = unsafe {
        Waker::new(
            CFRunLoop::main()?,
            drain_commands,
            std::ptr::from_mut(ui).cast(),
        )
    }?;
    thread::Builder::new()
        .name("a7n-macos-feedback".into())
        .spawn(move || forward_commands(receiver, command_tx, &waker))
        .ok()?;
    Some(feedback)
}

fn forward_commands(
    mut receiver: mpsc::Receiver<Command>,
    commands: sync::Sender<Command>,
    waker: &Waker,
) {
    while let Some(command) = receiver.blocking_recv() {
        if commands.send(command).is_err() {
            return;
        }
        waker.wake();
    }
    // Waking with the sender gone lets the main thread hide the panels.
    drop(commands);
    waker.wake();
}

unsafe extern "C-unwind" fn drain_commands(info: *mut c_void) {
    autoreleasepool(|_| {
        // SAFETY: start passes a leaked, process-long Ui; main run-loop
        // callbacks run one at a time on the main thread.
        let ui = unsafe { &mut *info.cast::<Ui>() };
        loop {
            match ui.commands.try_recv() {
                Ok(command) => ui.apply(command),
                Err(sync::TryRecvError::Empty) => return,
                Err(sync::TryRecvError::Disconnected) => {
                    ui.hide_all();
                    return;
                }
            }
        }
    });
}

unsafe extern "C-unwind" fn hide_landing(_: *mut CFRunLoopTimer, info: *mut c_void) {
    // SAFETY: Same contract as drain_commands.
    let ui = unsafe { &mut *info.cast::<Ui>() };
    if let Some(panels) = &mut ui.panels {
        panels.fade_landing();
    }
}

impl Ui {
    fn apply(&mut self, command: Command) {
        match command {
            Command::Tick => tick_haptics(),
            Command::Clear => self.hide_glow(),
            Command::Edge {
                display,
                edge,
                progress,
                look,
            } => {
                if let Some(panels) = self.panels() {
                    panels.show_glow(display, edge, progress, look);
                }
            }
            Command::Landing { x, y, look } => {
                if let Some(panels) = self.panels() {
                    panels.show_landing(x, y, look);
                }
            }
            Command::LandingAtCursor { look } => {
                if let Some(panels) = self.panels() {
                    let point = NSEvent::mouseLocation();
                    panels.show_landing_at((point.x, point.y), look);
                }
            }
        }
    }

    fn hide_glow(&self) {
        if let Some(panels) = &self.panels {
            panels.glow.orderOut(None);
        }
    }

    fn hide_all(&self) {
        self.hide_glow();
        if let Some(panels) = &self.panels {
            panels.landing.orderOut(None);
            panels.hide_landing.invalidate();
        }
    }

    /// The panels, created on first use; callbacks run on the main thread.
    fn panels(&mut self) -> Option<&mut Panels> {
        if self.panels.is_none() {
            let info = std::ptr::from_mut(self).cast();
            self.panels = Panels::new(MainThreadMarker::new()?, info);
        }
        self.panels.as_mut()
    }
}

impl Panels {
    fn new(mtm: MainThreadMarker, timer_info: *mut c_void) -> Option<Self> {
        let colors = [Color::Accent, Color::Green, Color::Orange, Color::Pink].map(|color| {
            let [r, g, b] = color.rgb(true);
            (
                color,
                NSColor::colorWithSRGBRed_green_blue_alpha(
                    f64::from(r) / 255.0,
                    f64::from(g) / 255.0,
                    f64::from(b) / 255.0,
                    1.0,
                ),
            )
        });
        let accent = NSColor::controlAccentColor();
        let glow_fill = filled_box(mtm, &accent.colorWithAlphaComponent(GLOW_ALPHA));
        let glow = make_panel(mtm, &glow_fill);
        let landing_fill = plain_box(mtm);
        let landing = make_panel(mtm, &landing_fill);
        let mut timer_context = CFRunLoopTimerContext {
            version: 0,
            info: timer_info,
            retain: None,
            release: None,
            copyDescription: None,
        };
        // SAFETY: The default allocator accepts None; `timer_info` is the
        // leaked Ui that `hide_landing` expects and the context is copied.
        let hide_landing = unsafe {
            CFRunLoopTimer::new(
                None,
                CFAbsoluteTimeGetCurrent() + TIMER_DISARMED_SECONDS,
                LANDING_FRAME_SECONDS,
                0,
                0,
                Some(hide_landing),
                &raw mut timer_context,
            )
        }?;
        // SAFETY: Core Foundation's default run-loop mode is an immutable global.
        CFRunLoop::current()?.add_timer(Some(&hide_landing), unsafe { kCFRunLoopDefaultMode });
        Some(Self {
            mtm,
            glow,
            glow_fill,
            colors,
            landing,
            landing_fill,
            landing_started: Instant::now(),
            landing_center: (0.0, 0.0),
            landing_look: Look::default(),
            animate: true,
            hide_landing,
        })
    }

    fn show_glow(
        &self,
        display: crate::input::Bounds,
        edge: a7n_proto::v1::Edge,
        progress: u16,
        look: Look,
    ) {
        let screens = screen_frames(self.mtm);
        let Some(primary) = screens.first() else {
            return;
        };
        let top = primary.height - f64::from(display.y);
        let Some(mut screen) = geometry::screen_containing(
            &screens,
            f64::from(display.x) + f64::from(display.width) / 2.0,
            top - f64::from(display.height) / 2.0,
        ) else {
            return;
        };
        // The daemon narrows the display rectangle for a notch push.
        if f64::from(display.width) < screen.width {
            screen.x = f64::from(display.x);
            screen.width = f64::from(display.width);
            screen.height = top - screen.y;
        }
        let rect = if look.style == Style::Beam {
            let pointer = NSEvent::mouseLocation();
            let flipped = match edge {
                a7n_proto::v1::Edge::Top => a7n_proto::v1::Edge::Bottom,
                a7n_proto::v1::Edge::Bottom => a7n_proto::v1::Edge::Top,
                other => other,
            };
            look::beam_rect(
                screen,
                flipped,
                (pointer.x, pointer.y),
                progress,
                BEAM_THICKNESS * look.size.multiplier(),
            )
        } else {
            geometry::glow_rect(screen, edge, progress, look.size)
        };
        let Some(rect) = rect else {
            self.glow.orderOut(None);
            return;
        };
        if let Some((_, color)) = self.colors.iter().find(|(color, _)| *color == look.color) {
            self.glow_fill.setFillColor(color);
        }
        self.glow.setAlphaValue(if look.style == Style::Beam {
            1.0
        } else {
            GLOW_ALPHA
        });
        self.glow.setFrame_display(ns_rect(rect), true);
        self.glow.orderFrontRegardless();
    }

    fn show_landing(&mut self, x: i32, y: i32, look: Look) {
        let primary_height = screen_frames(self.mtm)
            .first()
            .map_or(0.0, |frame| frame.height);
        let rect = geometry::landing_rect(x, y, primary_height);
        self.show_landing_at(
            (rect.x + rect.width / 2.0, rect.y + rect.height / 2.0),
            look,
        );
    }

    fn show_landing_at(&mut self, center: (f64, f64), look: Look) {
        self.landing_center = center;
        self.landing_started = Instant::now();
        self.landing_look = look;
        self.animate = !reduce_motion();
        self.fade_landing();
        self.landing.orderFrontRegardless();
        self.hide_landing
            .set_next_fire_date(CFAbsoluteTimeGetCurrent() + LANDING_FRAME_SECONDS);
    }

    fn fade_landing(&self) {
        let look = self.landing_look;
        let duration = if self.animate {
            LANDING_FADE
        } else {
            LANDING_STATIC_HOLD
        };
        let (radius, alpha) =
            look.landing
                .frame(self.landing_started.elapsed(), duration, self.animate);
        if alpha == 0.0 {
            self.landing.orderOut(None);
            self.hide_landing
                .set_next_fire_date(CFAbsoluteTimeGetCurrent() + TIMER_DISARMED_SECONDS);
            return;
        }
        let radius = LANDING_DIAMETER / 2.0 * look.size.multiplier() * radius;
        let dot = look.landing == Landing::Dot;
        if let Some((_, color)) = self.colors.iter().find(|(color, _)| *color == look.color) {
            self.landing_fill.setBorderColor(color);
            if dot {
                self.landing_fill.setFillColor(color);
            } else {
                self.landing_fill.setFillColor(&NSColor::clearColor());
            }
        }
        self.landing_fill.setBorderWidth(if dot {
            0.0
        } else {
            LANDING_RING_WIDTH * look.size.multiplier()
        });
        self.landing_fill.setCornerRadius(radius);
        self.landing.setAlphaValue(alpha);
        self.landing.setFrame_display(
            ns_rect(Rect {
                x: self.landing_center.0 - radius,
                y: self.landing_center.1 - radius,
                width: radius * 2.0,
                height: radius * 2.0,
            }),
            true,
        );
    }
}

/// A borderless panel that cannot become key, ignores the mouse, floats over
/// every Space and full-screen app, and is excluded from screen capture.
fn make_panel(mtm: MainThreadMarker, content: &NSBox) -> Retained<NSPanel> {
    let style = NSWindowStyleMask::Borderless | NSWindowStyleMask::NonactivatingPanel;
    let panel = NSPanel::initWithContentRect_styleMask_backing_defer(
        mtm.alloc::<NSPanel>(),
        NSRect::ZERO,
        style,
        NSBackingStoreType::Buffered,
        false,
    );
    panel.setOpaque(false);
    panel.setBackgroundColor(Some(&NSColor::clearColor()));
    panel.setHasShadow(false);
    panel.setIgnoresMouseEvents(true);
    panel.setLevel(NSStatusWindowLevel);
    panel.setSharingType(NSWindowSharingType::None);
    panel.setHidesOnDeactivate(false);
    panel.setCollectionBehavior(
        NSWindowCollectionBehavior::CanJoinAllSpaces
            | NSWindowCollectionBehavior::Stationary
            | NSWindowCollectionBehavior::IgnoresCycle
            | NSWindowCollectionBehavior::FullScreenAuxiliary,
    );
    panel.setContentView(Some(content));
    panel
}

fn filled_box(mtm: MainThreadMarker, fill: &NSColor) -> Retained<NSBox> {
    let view = plain_box(mtm);
    view.setBorderWidth(0.0);
    view.setFillColor(fill);
    view
}

fn plain_box(mtm: MainThreadMarker) -> Retained<NSBox> {
    let view = NSBox::initWithFrame(mtm.alloc::<NSBox>(), NSRect::ZERO);
    view.setBoxType(NSBoxType::Custom);
    view.setTitlePosition(NSTitlePosition::NoTitle);
    view
}

fn reduce_motion() -> bool {
    NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
}

fn tick_haptics() {
    NSHapticFeedbackManager::defaultPerformer().performFeedbackPattern_performanceTime(
        NSHapticFeedbackPattern::Alignment,
        NSHapticFeedbackPerformanceTime::Now,
    );
}

/// All screen frames in `AppKit` space, the primary screen first.
fn screen_frames(mtm: MainThreadMarker) -> Vec<Rect> {
    NSScreen::screens(mtm)
        .iter()
        .map(|screen| {
            let frame = screen.frame();
            Rect {
                x: frame.origin.x,
                y: frame.origin.y,
                width: frame.size.width,
                height: frame.size.height,
            }
        })
        .collect()
}

fn ns_rect(rect: Rect) -> NSRect {
    NSRect::new(
        NSPoint::new(rect.x, rect.y),
        NSSize::new(rect.width, rect.height),
    )
}