sk-app 0.5.0

The Skathi host: windows, the event loop, the JS bindings and the embedding API
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Is a window covered by the windows above it?
//!
//! gpui presents through DirectComposition, which keeps a fully covered window drawing at the display
//! rate. Chromium's `NativeWindowOcclusionTrackerWin` counts such a window as hidden, as it does a
//! minimised or cloaked one, and so does this ([`crate::window::occluded`]): `document.hidden`, no
//! `requestAnimationFrame`, and JS on the background tick (src/background.rs).
//!
//! Chromium recomputes on window events from a thread of its own. Here the frame pump asks, and
//! [`RECHECK`] bounds how often the walk runs, unless what the answer was computed under changed
//! since: the foreground window, the display's power state, our window's placement, or, while the
//! window is covered, any top-level window ([`Watch`]). A display the system turned off counts as
//! covering every window, as in Chromium.

use std::time::Duration;

pub const RECHECK: Duration = Duration::from_millis(200);

/// What a cached answer was computed under.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Seen {
    pub foreground: isize,
    pub display_off: bool,
    /// Our window: minimised, and its rect.
    pub own: (bool, Rect),
    /// [`Watch`]'s count of window events.
    pub events: u64,
}

/// Whether an answer computed `age` ago under `then` still stands `now`.
pub fn still_holds(age: Duration, then: Seen, now: Seen) -> bool {
    age < RECHECK && then == now
}

/// `GUID_CONSOLE_DISPLAY_STATE`'s value: 0 off, 1 on, 2 dimmed.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn display_off_state(state: u32) -> bool {
    state == 0
}

/// Past this many uncovered pieces the answer is "not covered": a pathological
/// tiling must not make the walk expensive, and drawing is the safe default.
const MAX_PIECES: usize = 256;

pub type Rect = (i32, i32, i32, i32);

fn empty(r: Rect) -> bool {
    r.0 >= r.2 || r.1 >= r.3
}

fn intersect(a: Rect, b: Rect) -> Rect {
    (a.0.max(b.0), a.1.max(b.1), a.2.min(b.2), a.3.min(b.3))
}

fn subtract(r: Rect, cut: Rect, out: &mut Vec<Rect>) {
    let i = intersect(r, cut);
    if empty(i) {
        out.push(r);
        return;
    }
    for piece in [
        (r.0, r.1, r.2, i.1),
        (r.0, i.3, r.2, r.3),
        (r.0, i.1, i.0, i.3),
        (i.2, i.1, r.2, i.3),
    ] {
        if !empty(piece) {
            out.push(piece);
        }
    }
}

#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub fn covered(target: Rect, displays: &[Rect], above: impl IntoIterator<Item = Rect>) -> bool {
    let mut visible: Vec<Rect> = displays
        .iter()
        .map(|&d| intersect(target, d))
        .filter(|&r| !empty(r))
        .collect();
    if visible.is_empty() {
        return true;
    }
    let mut next = Vec::new();
    for cut in above {
        next.clear();
        for &r in &visible {
            subtract(r, cut, &mut next);
        }
        std::mem::swap(&mut visible, &mut next);
        if visible.is_empty() {
            return true;
        }
        if visible.len() > MAX_PIECES {
            return false;
        }
    }
    false
}

#[cfg(target_os = "windows")]
mod win {
    use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
    use std::sync::Arc;

    use super::Rect;
    use windows::Win32::System::Threading::GetCurrentThreadId;
    use windows::Win32::UI::Accessibility::{SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK};
    use windows::Win32::UI::WindowsAndMessaging::{
        DispatchMessageW, GetAncestor, GetMessageW, PeekMessageW, PostThreadMessageW, CHILDID_SELF,
        EVENT_OBJECT_CLOAKED, EVENT_OBJECT_DESTROY, EVENT_OBJECT_LOCATIONCHANGE,
        EVENT_OBJECT_REORDER, EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_MINIMIZEEND,
        EVENT_SYSTEM_MINIMIZESTART, GA_ROOT, MSG, OBJID_WINDOW, PM_NOREMOVE, WINEVENT_OUTOFCONTEXT,
        WM_QUIT,
    };

    static EVENTS: AtomicU64 = AtomicU64::new(0);
    /// A frame was asked for since the last [`events`]: one is enough to walk again.
    static WOKEN: AtomicBool = AtomicBool::new(false);

    unsafe extern "system" fn window_event(
        _: HWINEVENTHOOK,
        event: u32,
        hwnd: HWND,
        object: i32,
        child: i32,
        _: u32,
        _: u32,
    ) {
        if object != OBJID_WINDOW.0 || child != CHILDID_SELF as i32 || hwnd.is_invalid() {
            return;
        }
        // A destroyed window has no ancestors left to ask about.
        if event != EVENT_OBJECT_DESTROY && unsafe { GetAncestor(hwnd, GA_ROOT) } != hwnd {
            return;
        }
        EVENTS.fetch_add(1, Ordering::SeqCst);
        if !WOKEN.swap(true, Ordering::SeqCst) {
            sk_runtime::frames::wake();
        }
    }

    pub fn events() -> u64 {
        WOKEN.store(false, Ordering::SeqCst);
        EVENTS.load(Ordering::SeqCst)
    }

    /// Counts top-level windows shown, hidden, moved, restacked, minimised or cloaked, and asks for
    /// a frame on the first since the last look, while it lives. The hooks run on a thread of their
    /// own: a moving mouse alone sends them hundreds of events a second.
    pub struct Watch {
        thread: Arc<AtomicU32>,
        stop: Arc<AtomicBool>,
    }

    impl Watch {
        pub fn start() -> Self {
            let thread = Arc::new(AtomicU32::new(0));
            let stop = Arc::new(AtomicBool::new(false));
            let (id, stopping) = (thread.clone(), stop.clone());
            let _ = std::thread::Builder::new()
                .name("sk-occlusion".into())
                .spawn(move || {
                    let mut msg = MSG::default();
                    // SAFETY: creates this thread's queue, so a WM_QUIT posted from now on lands.
                    let _ = unsafe { PeekMessageW(&mut msg, None, 0, 0, PM_NOREMOVE) };
                    let hooks: Vec<HWINEVENTHOOK> = [
                        (EVENT_SYSTEM_MINIMIZESTART, EVENT_SYSTEM_MINIMIZEEND),
                        (EVENT_OBJECT_DESTROY, EVENT_OBJECT_REORDER),
                        (EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE),
                        (EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED),
                    ]
                    .into_iter()
                    .map(|(from, to)| unsafe {
                        SetWinEventHook(
                            from,
                            to,
                            None,
                            Some(window_event),
                            0,
                            0,
                            WINEVENT_OUTOFCONTEXT,
                        )
                    })
                    .filter(|h| !h.is_invalid())
                    .collect();
                    id.store(unsafe { GetCurrentThreadId() }, Ordering::SeqCst);
                    if !stopping.load(Ordering::SeqCst) {
                        // Out-of-context hooks are called from inside GetMessageW.
                        while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
                            unsafe { DispatchMessageW(&msg) };
                        }
                    }
                    for hook in hooks {
                        let _ = unsafe { UnhookWinEvent(hook) };
                    }
                });
            Self { thread, stop }
        }
    }

    impl Drop for Watch {
        fn drop(&mut self) {
            self.stop.store(true, Ordering::SeqCst);
            let id = self.thread.load(Ordering::SeqCst);
            if id != 0 {
                let _ = unsafe { PostThreadMessageW(id, WM_QUIT, WPARAM(0), LPARAM(0)) };
            }
        }
    }

    pub fn own(raw: isize) -> (bool, Rect) {
        let h = HWND(raw as *mut _);
        let mut r = RECT::default();
        let _ = unsafe { GetWindowRect(h, &mut r) };
        (
            unsafe { IsIconic(h) }.as_bool(),
            (r.left, r.top, r.right, r.bottom),
        )
    }
    use windows::Win32::Foundation::{COLORREF, HANDLE, HWND, LPARAM, RECT, WPARAM};
    use windows::Win32::Graphics::Dwm::{
        DwmGetWindowAttribute, DWMWA_CLOAKED, DWMWA_EXTENDED_FRAME_BOUNDS,
    };
    use windows::Win32::Graphics::Gdi::{EnumDisplayMonitors, GetWindowRgnBox, HDC, HMONITOR};
    use windows::Win32::System::Power::{
        PowerSettingRegisterNotification, DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS,
        POWERBROADCAST_SETTING,
    };
    use windows::Win32::UI::WindowsAndMessaging::{
        GetForegroundWindow, GetLayeredWindowAttributes, GetWindow, GetWindowLongW, GetWindowRect,
        IsIconic, IsWindowVisible, DEVICE_NOTIFY_CALLBACK, GWL_EXSTYLE, GW_HWNDPREV,
        LAYERED_WINDOW_ATTRIBUTES_FLAGS, LWA_ALPHA, LWA_COLORKEY, PBT_POWERSETTINGCHANGE,
        WS_EX_LAYERED, WS_EX_TRANSPARENT,
    };

    const CONSOLE_DISPLAY_STATE: windows::core::GUID =
        windows::core::GUID::from_u128(0x6fe69556_704a_47a0_8f24_c28d936fda47);

    static DISPLAY_OFF: AtomicBool = AtomicBool::new(false);

    unsafe extern "system" fn display_changed(
        _: *const std::ffi::c_void,
        kind: u32,
        setting: *const std::ffi::c_void,
    ) -> u32 {
        if kind == PBT_POWERSETTINGCHANGE && !setting.is_null() {
            // SAFETY: a power setting change passes a POWERBROADCAST_SETTING, `DataLength` bytes
            // of data following its header.
            let setting = unsafe { &*setting.cast::<POWERBROADCAST_SETTING>() };
            if setting.PowerSetting == CONSOLE_DISPLAY_STATE && setting.DataLength >= 4 {
                // SAFETY: as above; at least four bytes.
                let state = unsafe { setting.Data.as_ptr().cast::<u32>().read_unaligned() };
                DISPLAY_OFF.store(super::display_off_state(state), Ordering::Relaxed);
                sk_runtime::frames::wake();
            }
        }
        0
    }

    /// The system turned the displays off. Watched from the first ask; the system reports the
    /// state at once on registering.
    pub fn display_off() -> bool {
        static WATCH: std::sync::Once = std::sync::Once::new();
        WATCH.call_once(|| {
            let params = Box::leak(Box::new(DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS {
                Callback: Some(display_changed),
                Context: std::ptr::null_mut(),
            }));
            let mut handle = std::ptr::null_mut();
            // SAFETY: the parameters are leaked, so they outlive the registration, which lasts
            // for the process.
            let _ = unsafe {
                PowerSettingRegisterNotification(
                    &CONSOLE_DISPLAY_STATE,
                    DEVICE_NOTIFY_CALLBACK,
                    HANDLE(std::ptr::from_mut(params).cast()),
                    &mut handle,
                )
            };
        });
        DISPLAY_OFF.load(Ordering::Relaxed)
    }

    pub fn foreground() -> isize {
        unsafe { GetForegroundWindow() }.0 as isize
    }

    /// The rect DWM draws: `GetWindowRect` includes the invisible resize
    /// borders, which would cover a strip of whatever is beside the window.
    fn bounds(h: HWND) -> Option<Rect> {
        let mut r = RECT::default();
        let dwm = unsafe {
            DwmGetWindowAttribute(
                h,
                DWMWA_EXTENDED_FRAME_BOUNDS,
                &mut r as *mut RECT as *mut _,
                std::mem::size_of::<RECT>() as u32,
            )
        };
        if dwm.is_err() {
            unsafe { GetWindowRect(h, &mut r) }.ok()?;
        }
        Some((r.left, r.top, r.right, r.bottom))
    }

    fn cloaked(h: HWND) -> bool {
        let mut c: u32 = 0;
        let ok = unsafe {
            DwmGetWindowAttribute(
                h,
                DWMWA_CLOAKED,
                &mut c as *mut u32 as *mut _,
                std::mem::size_of::<u32>() as u32,
            )
        };
        ok.is_ok() && c != 0
    }

    pub fn shown(h: HWND) -> bool {
        let shown = unsafe { IsWindowVisible(h).as_bool() && !IsIconic(h).as_bool() };
        shown && !cloaked(h)
    }

    fn opaque(h: HWND) -> bool {
        if !shown(h) {
            return false;
        }
        let ex = unsafe { GetWindowLongW(h, GWL_EXSTYLE) } as u32;
        if ex & WS_EX_TRANSPARENT.0 != 0 {
            return false;
        }
        if ex & WS_EX_LAYERED.0 != 0 {
            let mut key = COLORREF(0);
            let mut alpha = 0u8;
            let mut flags = LAYERED_WINDOW_ATTRIBUTES_FLAGS(0);
            // Fails for a window that draws with per-pixel alpha
            // (`UpdateLayeredWindow`): it may be transparent anywhere.
            let ok = unsafe {
                GetLayeredWindowAttributes(h, Some(&mut key), Some(&mut alpha), Some(&mut flags))
            };
            if ok.is_err()
                || flags.0 & LWA_COLORKEY.0 != 0
                || (flags.0 & LWA_ALPHA.0 != 0 && alpha != 255)
            {
                return false;
            }
        }
        let mut rgn = RECT::default();
        if unsafe { GetWindowRgnBox(h, &mut rgn) }.0 != 0 {
            return false;
        }
        true
    }

    fn displays() -> Vec<Rect> {
        unsafe extern "system" fn each(
            _: HMONITOR,
            _: HDC,
            r: *mut RECT,
            data: LPARAM,
        ) -> windows::core::BOOL {
            let out = unsafe { &mut *(data.0 as *mut Vec<Rect>) };
            let r = unsafe { *r };
            out.push((r.left, r.top, r.right, r.bottom));
            true.into()
        }
        let mut out: Vec<Rect> = Vec::new();
        let _ = unsafe {
            EnumDisplayMonitors(
                None,
                None,
                Some(each),
                LPARAM(&mut out as *mut Vec<Rect> as isize),
            )
        };
        out
    }

    pub fn covered(raw: isize) -> bool {
        let h = HWND(raw as *mut _);
        let Some(target) = bounds(h) else {
            return false;
        };
        let displays = displays();
        let mut above = Vec::new();
        let mut w = unsafe { GetWindow(h, GW_HWNDPREV) }.ok();
        while let Some(next) = w {
            if opaque(next) {
                if let Some(r) = bounds(next) {
                    above.push(r);
                }
            }
            w = unsafe { GetWindow(next, GW_HWNDPREV) }.ok();
        }
        super::covered(target, &displays, above)
    }

    pub fn unseen(raw: isize) -> bool {
        !shown(HWND(raw as *mut _)) || covered(raw)
    }
}

#[cfg(not(target_os = "windows"))]
mod win {
    pub fn covered(_raw: isize) -> bool {
        false
    }
    pub fn unseen(_raw: isize) -> bool {
        false
    }
    pub fn display_off() -> bool {
        false
    }
    pub fn foreground() -> isize {
        0
    }
    pub fn own(_raw: isize) -> (bool, super::Rect) {
        (false, (0, 0, 0, 0))
    }
    pub fn events() -> u64 {
        0
    }
    pub struct Watch;
    impl Watch {
        pub fn start() -> Self {
            Watch
        }
    }
}

pub use win::{
    covered as hwnd_covered, display_off, events, foreground, own, unseen as hwnd_unseen, Watch,
};

#[cfg(test)]
mod tests {
    use super::*;

    const SCREEN: Rect = (0, 0, 1920, 1080);

    #[test]
    fn a_window_under_a_bigger_one_is_covered() {
        assert!(covered(
            (100, 100, 900, 700),
            &[SCREEN],
            [(0, 0, 1920, 1040)]
        ));
    }

    #[test]
    fn a_sliver_left_uncovered_is_enough_to_draw() {
        assert!(!covered(
            (100, 100, 900, 700),
            &[SCREEN],
            [(101, 100, 900, 700)]
        ));
        assert!(!covered(
            (100, 100, 900, 700),
            &[SCREEN],
            [(100, 100, 900, 699)]
        ));
    }

    #[test]
    fn several_windows_can_cover_it_together() {
        let target = (0, 0, 1000, 1000);
        let halves = [
            (0, 0, 500, 1000),
            (500, 0, 1000, 600),
            (400, 500, 1200, 1100),
        ];
        assert!(covered(target, &[SCREEN], halves));
        assert!(!covered(target, &[SCREEN], halves[..2].iter().copied()));
    }

    #[test]
    fn no_windows_above_leaves_it_visible() {
        assert!(!covered((100, 100, 900, 700), &[SCREEN], []));
    }

    #[test]
    fn only_the_part_on_a_display_counts() {
        let target = (1500, 100, 2300, 700);
        assert!(covered(target, &[SCREEN], [(1400, 0, 1920, 1080)]));
        assert!(!covered(
            target,
            &[SCREEN, (1920, 0, 3840, 1080)],
            [(1400, 0, 1920, 1080)]
        ));
        assert!(covered((-3000, 0, -2000, 500), &[SCREEN], []));
    }

    #[test]
    fn subtraction_leaves_the_ring_around_a_hole() {
        let mut out = Vec::new();
        subtract((0, 0, 10, 10), (3, 3, 6, 6), &mut out);
        let area: i32 = out.iter().map(|r| (r.2 - r.0) * (r.3 - r.1)).sum();
        assert_eq!(area, 100 - 9);
        for (i, a) in out.iter().enumerate() {
            for b in &out[i + 1..] {
                assert!(empty(intersect(*a, *b)), "{a:?} overlaps {b:?}");
            }
        }
    }

    #[test]
    fn a_cached_answer_lasts_a_recheck_unless_the_foreground_or_the_display_changes() {
        let seen = Seen {
            foreground: 7,
            display_off: false,
            own: (false, (100, 100, 900, 700)),
            events: 3,
        };
        let short = Duration::from_millis(50);
        assert!(still_holds(short, seen, seen));
        assert!(!still_holds(RECHECK, seen, seen));
        let other = Seen {
            foreground: 8,
            ..seen
        };
        assert!(
            !still_holds(short, seen, other),
            "a cover took the foreground"
        );
        let off = Seen {
            display_off: true,
            ..seen
        };
        assert!(!still_holds(short, seen, off));
        assert!(!still_holds(short, off, seen), "the display came back");
    }

    #[test]
    fn a_cached_answer_is_dropped_when_our_window_or_another_one_changes() {
        let minimised = Seen {
            foreground: 7,
            display_off: false,
            own: (true, (-32000, -32000, -31840, -31972)),
            events: 3,
        };
        let short = Duration::from_millis(1);
        let restored = Seen {
            own: (false, (100, 100, 900, 700)),
            ..minimised
        };
        assert!(!still_holds(short, minimised, restored));
        let resized = Seen {
            own: (false, (100, 100, 1000, 700)),
            ..restored
        };
        assert!(!still_holds(short, restored, resized));
        let moved_away = Seen {
            events: 4,
            ..restored
        };
        assert!(
            !still_holds(short, restored, moved_away),
            "the cover went away"
        );
    }

    #[test]
    fn only_a_display_turned_off_counts_as_off() {
        assert!(display_off_state(0));
        assert!(!display_off_state(1));
        assert!(!display_off_state(2), "dimmed still shows");
    }

    #[test]
    fn a_pathological_tiling_gives_up_and_draws() {
        let cuts = (0..40)
            .flat_map(|y| (0..40).map(move |x| (x * 20 + 5, y * 20 + 5, x * 20 + 6, y * 20 + 6)));
        assert!(!covered((0, 0, 800, 800), &[SCREEN], cuts));
    }
}