clairlune-live 0.33.1

Clairlune's live wallpaper: plays a scene behind the desktop icons, drawing only what changed
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
//! The live wallpaper on macOS: one borderless window per screen at the
//! desktop picture's window level (above the wallpaper, below the desktop
//! icons), on every Space, ignoring the mouse. Its view shows the frame
//! through two IOSurfaces ([`crate::surface`]): only the rectangles that
//! changed are written, and the window server composites the surface as
//! it is, with no GPU device or swapchain in the app (they cost far more
//! memory and threads than a wallpaper needs).
//!
//! A screen whose window is fully covered (a full-screen app, the lock
//! screen, a sleeping display) reports itself occluded, and isn't drawn
//! until it shows again. A zoomed window leaves the menu bar and the Dock
//! showing, so twice a second the host also asks the window server where the
//! other apps' windows are: a screen whose usable area they all but fill
//! counts as covered too ([`crate::cover`]).
//!
//! Everything here runs on the main thread (AppKit's rule), which is where
//! the app ticks it.

use crate::cover::{self, Rect};
use crate::surface::SurfaceView;
use crate::{CoverPolicy, FrameStats, Player};
use clairlune_platform::Monitor;
use clairlune_platform::macos::find_screen;
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2::{ClassType, MainThreadMarker, MainThreadOnly, msg_send};
use objc2_app_kit::{
    NSBackingStoreType, NSScreen, NSWindow, NSWindowCollectionBehavior, NSWindowOcclusionState,
    NSWindowStyleMask,
};
use objc2_core_foundation::{CFArray, CFRetained};
use objc2_core_graphics::{
    CGWindowLevelForKey, CGWindowLevelKey, CGWindowListCopyWindowInfo,
    CGWindowListCreateDescriptionFromArray, CGWindowListOption,
};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSPoint, NSRect, NSString, ns_string};
use std::ffi::c_void;
use std::time::{Duration, Instant};

/// One screen's window and the view that shows it. The view goes before
/// the window (field order).
struct Output {
    monitor: Monitor,
    view: SurfaceView,
    covered: bool,
    window: Retained<NSWindow>,
}

/// Live wallpapers on every screen given.
pub struct MacDesktop {
    outputs: Vec<Output>,
    pub cover_policy: CoverPolicy,
    /// Per output: other apps' windows all but fill its screen.
    filled: Vec<bool>,
    /// When that was last worked out.
    checked: Option<Instant>,
}

/// How often to ask where the other apps' windows are.
pub(crate) const WINDOW_CHECK: Duration = Duration::from_millis(500);

/// Where the other apps' windows are, shared by all that want to know.
#[derive(Default)]
pub struct AppWindows {
    rects: Vec<Rect>,
    /// The windows' numbers, to ask about those alone.
    ids: Vec<u32>,
    raw_ids: Vec<*const c_void>,
    asked: Option<Instant>,
}

impl AppWindows {
    /// As they were, at most [`WINDOW_CHECK`] ago.
    pub(crate) fn look(&mut self) -> &[Rect] {
        // A little early rather than late: two that ask in turn share one.
        let fresh = WINDOW_CHECK * 9 / 10;
        if self.asked.is_none_or(|t| t.elapsed() >= fresh) {
            self.look_now();
        }
        &self.rects
    }

    /// As they are.
    pub(crate) fn look_now(&mut self) -> &[Rect] {
        self.asked = Some(Instant::now());
        let options =
            CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements;
        self.keep(CGWindowListCopyWindowInfo(options, 0));
        &self.rects
    }

    /// Where the same windows are now, which costs a fraction of finding them
    /// among everything on screen. New ones aren't seen.
    pub(crate) fn look_again(&mut self) -> &[Rect] {
        if self.ids.is_empty() {
            return &self.rects;
        }
        self.raw_ids.clear();
        self.raw_ids
            .extend(self.ids.iter().map(|id| *id as usize as *const c_void));
        // SAFETY: an array of window numbers, kept as they are (no callbacks),
        // is what the window list takes.
        let info = unsafe {
            CFArray::new(
                None,
                self.raw_ids.as_mut_ptr(),
                self.raw_ids.len() as isize,
                std::ptr::null(),
            )
            .and_then(|a| CGWindowListCreateDescriptionFromArray(Some(&a)))
        };
        self.keep(info);
        &self.rects
    }

    /// Keeps the on-screen windows of other apps at the normal level (no
    /// menus, panels or the Dock), in the window server's points (top-left
    /// origin). Their bounds need no permission; their titles aren't read.
    fn keep(&mut self, info: Option<CFRetained<CFArray>>) {
        self.rects.clear();
        self.ids.clear();
        let Some(info) = info else {
            return;
        };
        // SAFETY: a CFArray is an NSArray (toll-free bridged), and the window
        // list holds dictionaries; each item is checked before it's read.
        let list: &NSArray<AnyObject> =
            unsafe { &*(&*info as *const _ as *const NSArray<AnyObject>) };
        let me = f64::from(std::process::id());
        for i in 0..list.count() {
            let item = list.objectAtIndex(i);
            let Some(d) = dict(&item) else {
                continue;
            };
            if number(d, ns_string!("kCGWindowLayer")) != Some(0.0)
                || number(d, ns_string!("kCGWindowOwnerPID")) == Some(me)
                || number(d, ns_string!("kCGWindowAlpha")).unwrap_or(1.0) < 0.05
                || number(d, ns_string!("kCGWindowIsOnscreen")) != Some(1.0)
            {
                continue;
            }
            let Some(bounds) = value(d, ns_string!("kCGWindowBounds")) else {
                continue;
            };
            let Some(b) = dict(&bounds) else {
                continue;
            };
            if let (Some(id), Some(x), Some(y), Some(w), Some(h)) = (
                number(d, ns_string!("kCGWindowNumber")),
                number(b, ns_string!("X")),
                number(b, ns_string!("Y")),
                number(b, ns_string!("Width")),
                number(b, ns_string!("Height")),
            ) {
                self.ids.push(id as u32);
                self.rects.push(Rect { x, y, w, h });
            }
        }
    }
}

fn is_kind(obj: &AnyObject, class: &objc2::runtime::AnyClass) -> bool {
    // SAFETY: isKindOfClass: is on every NSObject.
    unsafe { msg_send![obj, isKindOfClass: class] }
}

fn dict(obj: &AnyObject) -> Option<&NSDictionary<AnyObject, AnyObject>> {
    // SAFETY: checked to be a dictionary first.
    is_kind(obj, NSDictionary::<AnyObject, AnyObject>::class()).then(|| unsafe {
        &*(obj as *const AnyObject as *const NSDictionary<AnyObject, AnyObject>)
    })
}

fn value(d: &NSDictionary<AnyObject, AnyObject>, key: &NSString) -> Option<Retained<AnyObject>> {
    let key: &AnyObject = key;
    d.objectForKey(key)
}

fn number(d: &NSDictionary<AnyObject, AnyObject>, key: &NSString) -> Option<f64> {
    let v = value(d, key)?;
    // SAFETY: checked to be a number first.
    is_kind(&v, NSNumber::class())
        .then(|| unsafe { &*(&*v as *const AnyObject as *const NSNumber) }.doubleValue())
}

/// The usable part of a screen (without the menu bar and the Dock), in the
/// window server's points: AppKit's origin is the main screen's bottom left,
/// y up; the window server's its top left, y down.
pub(crate) fn usable_area(mtm: MainThreadMarker, screen: &NSScreen) -> Option<Rect> {
    let main = NSScreen::screens(mtm).firstObject()?.frame();
    Some(usable_area_in(main.size.height, screen))
}

fn usable_area_in(main_height: f64, screen: &NSScreen) -> Rect {
    let v = screen.visibleFrame();
    Rect {
        x: v.origin.x,
        y: main_height - (v.origin.y + v.size.height),
        w: v.size.width,
        h: v.size.height,
    }
}

/// The desktop picture's window level.
pub(crate) fn desktop_level() -> isize {
    CGWindowLevelForKey(CGWindowLevelKey::DesktopWindowLevelKey) as isize
}

/// Makes a window part of the desktop: on every Space, out of the way of the
/// mouse and of Mission Control.
pub(crate) fn join_desktop(window: &NSWindow, level: isize) {
    // Owned by the Retained handle, not released again on close.
    unsafe { window.setReleasedWhenClosed(false) };
    window.setLevel(level);
    window.setCollectionBehavior(
        NSWindowCollectionBehavior::CanJoinAllSpaces
            | NSWindowCollectionBehavior::Stationary
            | NSWindowCollectionBehavior::IgnoresCycle,
    );
    window.setIgnoresMouseEvents(true);
    window.setHasShadow(false);
}

/// A borderless window covering the screen, at the desktop picture's level.
fn desktop_window(mtm: MainThreadMarker, monitor: &Monitor) -> Result<Retained<NSWindow>, String> {
    let screen = find_screen(mtm, &monitor.id)
        .ok_or_else(|| format!("screen {} isn't connected", monitor.id))?;
    let frame = screen.frame();
    let window = unsafe {
        NSWindow::initWithContentRect_styleMask_backing_defer(
            NSWindow::alloc(mtm),
            frame,
            NSWindowStyleMask::Borderless,
            NSBackingStoreType::Buffered,
            false,
        )
    };
    join_desktop(&window, desktop_level());
    window.setOpaque(true);
    window.setFrame_display(frame, false);
    Ok(window)
}

impl MacDesktop {
    /// Puts each player on its screen (the player's scene must be the
    /// screen's size in pixels) and shows its first frame. Main thread only.
    pub fn start(scenes: Vec<(Monitor, Player)>) -> Result<MacDesktop, String> {
        let mtm = MainThreadMarker::new().ok_or("live wallpapers start on the main thread")?;
        let mut outputs = Vec::new();
        for (monitor, mut player) in scenes {
            // The screen's size, or half of it (Lighter on Retina screens:
            // shown pixel-doubled).
            let (pw, ph) = player.size();
            let fits = |p: u32, m: u32| p == m || (p * 2).abs_diff(m) <= 1;
            if !(fits(pw, monitor.width) && fits(ph, monitor.height)) {
                return Err(format!(
                    "the scene is {:?} but screen {} is {}x{}",
                    player.size(),
                    monitor.id,
                    monitor.width,
                    monitor.height
                ));
            }
            let window = desktop_window(mtm, &monitor)?;
            // Sub-cell particles, as on the GPU: drawing only what changed
            // keeps a higher frame rate cheap.
            player.set_smooth(true);
            let t = player.now_ms();
            player.advance(t);
            let size = window.frame().size;
            let view = SurfaceView::new(mtm, NSRect::new(NSPoint::new(0.0, 0.0), size), player)
                .ok_or("no IOSurface for the screen")?;
            window.setContentView(Some(view.view()));
            window.orderFrontRegardless();
            outputs.push(Output {
                monitor,
                view,
                covered: false,
                window,
            });
        }
        if outputs.is_empty() {
            return Err("no screens to play on".into());
        }
        tracing::info!(target: "clairlune", screens = outputs.len(), "live: showing IOSurfaces");
        let n = outputs.len();
        Ok(MacDesktop {
            outputs,
            cover_policy: CoverPolicy::default(),
            filled: vec![false; n],
            checked: None,
        })
    }

    /// "iosurface".
    pub fn presenter(&self) -> String {
        "iosurface".into()
    }

    /// The highest frame rate worth asking for (a journey redraws the
    /// whole screen: at most Very smooth).
    pub fn max_fps(&self) -> u32 {
        if self.outputs.iter().any(|o| o.view.player().is_journey()) {
            crate::JOURNEY_MAX_FPS
        } else {
            60
        }
    }

    /// The screens playing.
    pub fn monitors(&self) -> impl Iterator<Item = &Monitor> {
        self.outputs.iter().map(|o| &o.monitor)
    }

    /// Re-checks window cover on the next tick (an app activated, hid or
    /// unhid, or Spaces changed).
    pub fn note_windows_changed(&mut self) {
        self.checked = None;
    }

    /// Draws the current time on every screen that shows.
    pub fn tick(&mut self, windows: &mut AppWindows) -> Result<FrameStats, String> {
        if clairlune_platform::macos::screens_asleep() {
            return Ok(FrameStats {
                covered: self.outputs.len(),
                away: true,
                ..Default::default()
            });
        }
        let started = Instant::now();
        if self.cover_policy == CoverPolicy::Off {
            self.filled.fill(false);
        } else if self.checked.is_none_or(|t| t.elapsed() >= WINDOW_CHECK)
            && let Some(mtm) = MainThreadMarker::new()
        {
            self.checked = Some(Instant::now());
            let main_height = NSScreen::screens(mtm)
                .firstObject()
                .map(|s| s.frame().size.height);
            let windows = windows.look();
            for (o, dst) in self.outputs.iter().zip(&mut self.filled) {
                *dst = match (main_height, o.window.screen()) {
                    (Some(mh), Some(s)) => cover::filled(usable_area_in(mh, &s), windows),
                    _ => false,
                };
            }
        }
        let shown: Vec<bool> = self
            .outputs
            .iter()
            .zip(&self.filled)
            .map(|(o, filled)| {
                !filled
                    && o.window
                        .occlusionState()
                        .contains(NSWindowOcclusionState::Visible)
            })
            .collect();
        let any_hidden = shown.iter().any(|v| !v);
        for (o, visible) in self.outputs.iter_mut().zip(&shown) {
            let covered = match self.cover_policy {
                CoverPolicy::Off => false,
                CoverPolicy::ThatMonitor => !visible,
                CoverPolicy::AllMonitors => any_hidden,
            };
            if covered != o.covered {
                if covered {
                    tracing::info!(target: "clairlune", screen = %o.monitor.id, "live: covered, paused");
                } else {
                    tracing::info!(target: "clairlune", screen = %o.monitor.id, "live: showing again, playing");
                }
            }
            o.covered = covered;
        }
        let (mut pixels, mut count) = (0u64, 0usize);
        for o in &mut self.outputs {
            if o.covered {
                continue; // nobody sees it; resumes at the time it is then
            }
            let (p, n) = o.view.advance();
            pixels += p;
            count += n;
        }
        let busy = started.elapsed();
        Ok(FrameStats {
            pixels,
            rects: count,
            covered: self.outputs.iter().filter(|o| o.covered).count(),
            away: false,
            stalls: 0,
            busy,
            upload: busy,
            present: Duration::ZERO,
        })
    }
}

impl Drop for MacDesktop {
    fn drop(&mut self) {
        for o in &self.outputs {
            o.window.orderOut(None);
            o.window.close();
        }
    }
}