sk-desktop 0.5.0

Skathi's desktop integration: argv, shell, single instance, custom protocols and the tray
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! ScreenCaptureKit sources (macOS 13+) on the pool worker. SCK answers on its own queues into channels the
//! worker waits on with a deadline; `NSScreen` is read on the main queue. Thumbnails use
//! `SCScreenshotManager` on macOS 14+, else `CGWindowListCreateImage`.

use std::collections::HashMap;
use std::ffi::{c_char, c_void, CStr};
use std::ptr::NonNull;
use std::sync::mpsc;
use std::time::{Duration, Instant};

use block2::RcBlock;
use objc2::encode::{Encoding, RefEncode};
use objc2::msg_send;
use objc2::rc::{autoreleasepool, Allocated, Retained};
use objc2::runtime::{AnyClass, AnyObject, Bool};
use objc2::MainThreadMarker;
use objc2_app_kit::NSView;
use objc2_core_foundation::{CGPoint, CGRect, CGSize};
use objc2_foundation::NSString;
use serde_json::Value;

use super::listing::{self, DisplayRow, Rect, WindowRow};
use super::{fit, png_url, Options};
use crate::Fail;

#[repr(C)]
struct CGImage {
    _private: [u8; 0],
}

unsafe impl RefEncode for CGImage {
    const ENCODING_REF: Encoding = Encoding::Pointer(&Encoding::Struct("CGImage", &[]));
}

#[link(name = "ScreenCaptureKit", kind = "framework")]
unsafe extern "C" {}
#[link(name = "AppKit", kind = "framework")]
unsafe extern "C" {}

#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
    fn CGMainDisplayID() -> u32;
    fn CGDisplayCopyDisplayMode(display: u32) -> *mut c_void;
    fn CGDisplayModeGetPixelWidth(mode: *mut c_void) -> usize;
    fn CGDisplayModeRelease(mode: *mut c_void);
    fn CGImageRetain(image: *mut CGImage) -> *mut CGImage;
    fn CGImageRelease(image: *mut CGImage);
    fn CGImageGetWidth(image: *mut CGImage) -> usize;
    fn CGImageGetHeight(image: *mut CGImage) -> usize;
    fn CGColorSpaceCreateWithName(name: *const c_void) -> *mut c_void;
    fn CGColorSpaceRelease(space: *mut c_void);
    fn CGBitmapContextCreate(
        data: *mut c_void,
        width: usize,
        height: usize,
        bits_per_component: usize,
        bytes_per_row: usize,
        space: *mut c_void,
        bitmap_info: u32,
    ) -> *mut c_void;
    fn CGContextSetInterpolationQuality(context: *mut c_void, quality: i32);
    fn CGContextDrawImage(context: *mut c_void, rect: CGRect, image: *mut CGImage);
    fn CGContextRelease(context: *mut c_void);
    static kCGColorSpaceSRGB: *const c_void;
}

unsafe extern "C" {
    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}

const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;
const PREMULTIPLIED_RGBA: u32 = 1 | (4 << 12);
const INTERPOLATION_HIGH: i32 = 3;
const LIST_ON_SCREEN_ONLY: u32 = 1 << 0;
const LIST_INCLUDING_WINDOW: u32 = 1 << 3;
const IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
const IMAGE_BEST_RESOLUTION: u32 = 1 << 3;
const IMAGE_NOMINAL_RESOLUTION: u32 = 1 << 4;
const USER_DECLINED: isize = -3801;
const PREVIEW_DEADLINE: Duration = Duration::from_secs(2);

struct CgImage(NonNull<CGImage>);
// SAFETY: CGImage is immutable and its retain count is thread-safe.
unsafe impl Send for CgImage {}

impl CgImage {
    unsafe fn retain(image: *mut CGImage) -> Option<Self> {
        NonNull::new(image).map(|image| {
            unsafe { CGImageRetain(image.as_ptr()) };
            CgImage(image)
        })
    }
    unsafe fn adopt(image: *mut CGImage) -> Option<Self> {
        NonNull::new(image).map(CgImage)
    }
}

impl Drop for CgImage {
    fn drop(&mut self) {
        unsafe { CGImageRelease(self.0.as_ptr()) }
    }
}

struct Sent(Retained<AnyObject>);
// SAFETY: only immutable ScreenCaptureKit results (SCShareableContent) cross.
unsafe impl Send for Sent {}

fn class(name: &CStr) -> Result<&'static AnyClass, Fail> {
    AnyClass::get(name).ok_or_else(|| {
        Fail::new(
            "NotSupportedError",
            format!("{} is unavailable", name.to_string_lossy()),
        )
    })
}

unsafe fn error_info(error: *mut AnyObject) -> (isize, String) {
    let Some(error) = (unsafe { error.as_ref() }) else {
        return (0, "unknown error".into());
    };
    let code: isize = unsafe { msg_send![error, code] };
    let text: Option<Retained<NSString>> = unsafe { msg_send![error, localizedDescription] };
    (
        code,
        text.map_or_else(|| "unknown error".into(), |t| t.to_string()),
    )
}

fn sck_failure(code: isize, text: &str) -> Fail {
    if code == USER_DECLINED {
        let (name, message) = sk_permissions::display_capture_refusal();
        return Fail::new(name, message);
    }
    Fail::new(
        "OperationError",
        format!("ScreenCaptureKit: {text} ({code})"),
    )
}

unsafe fn objects(array: &AnyObject) -> Vec<Retained<AnyObject>> {
    let count: usize = unsafe { msg_send![array, count] };
    (0..count)
        .filter_map(|i| -> Option<Retained<AnyObject>> {
            unsafe { msg_send![array, objectAtIndex: i] }
        })
        .collect()
}

fn text(value: Option<Retained<NSString>>) -> String {
    value.map(|v| v.to_string()).unwrap_or_default()
}

fn rect(frame: CGRect) -> Rect {
    Rect {
        x: frame.origin.x,
        y: frame.origin.y,
        width: frame.size.width,
        height: frame.size.height,
    }
}

fn cg_rect(rect: Rect) -> CGRect {
    CGRect::new(
        CGPoint::new(rect.x, rect.y),
        CGSize::new(rect.width, rect.height),
    )
}

pub(super) fn sources(options: Options) -> Result<Vec<Value>, Fail> {
    autoreleasepool(|_| unsafe { list(options) })
}

unsafe fn list(options: Options) -> Result<Vec<Value>, Fail> {
    let content = shareable_content()?;
    let main = unsafe { CGMainDisplayID() };
    let mut displays = Vec::new();
    let mut display_objects = HashMap::new();
    let all: Retained<AnyObject> = unsafe { msg_send![&*content, displays] };
    for display in unsafe { objects(&all) } {
        let id: u32 = unsafe { msg_send![&*display, displayID] };
        let frame = rect(unsafe { msg_send![&*display, frame] });
        displays.push(DisplayRow {
            id,
            frame,
            scale: unsafe { pixel_scale(id, frame.width) },
            primary: id == main,
            work_area: None,
            name: None,
        });
        display_objects.insert(id, display);
    }
    listing::order_displays(&mut displays);
    let mut windows = Vec::new();
    if options.windows {
        let own = std::process::id() as i32;
        let all: Retained<AnyObject> = unsafe { msg_send![&*content, windows] };
        for window in unsafe { objects(&all) } {
            let row = unsafe { window_row(&window) };
            if listing::keep_window(&row, own) && windows.len() < listing::MAX_WINDOWS {
                windows.push((row, window));
            }
        }
    }
    if options.screens {
        screen_details(&mut displays);
    }

    let modern = AnyClass::get(c"SCScreenshotManager").is_some();
    let size = |frame: &Rect| {
        fit(
            frame.width.round() as u32,
            frame.height.round() as u32,
            options.thumbnail_width,
            options.thumbnail_height,
        )
    };
    let mut screen_shots = Vec::new();
    if options.screens {
        for display in &displays {
            let target = display_objects
                .get(&display.id)
                .map(|d| Target::Display(d, display.frame));
            let size = size(&display.frame);
            screen_shots.push((unsafe { start_preview(target, size, modern) }, size));
        }
    }
    let mut window_shots = Vec::new();
    for (row, window) in &windows {
        let size = size(&row.frame);
        window_shots.push((
            unsafe { start_preview(Some(Target::Window(window, row.id)), size, modern) },
            size,
        ));
    }
    let deadline = Instant::now() + PREVIEW_DEADLINE;

    let mut result = Vec::new();
    if options.screens {
        for (index, (display, (shot, size))) in displays.iter().zip(screen_shots).enumerate() {
            result.push(listing::screen_json(
                index,
                display,
                finish_preview(shot, size, deadline),
            ));
        }
    }
    let mut icons: HashMap<i32, Option<String>> = HashMap::new();
    for ((row, _), (shot, size)) in windows.iter().zip(window_shots) {
        let thumbnail = finish_preview(shot, size, deadline);
        let icon = match row.pid {
            Some(pid) if options.with_icons => icons
                .entry(pid)
                .or_insert_with(|| unsafe { app_icon(pid) })
                .clone(),
            _ => None,
        };
        let display = listing::display_for(&row.frame, &displays);
        result.push(listing::window_json(row, display, thumbnail, icon));
    }
    Ok(result)
}

fn shareable_content() -> Result<Retained<AnyObject>, Fail> {
    let cls = class(c"SCShareableContent")?;
    let (send, receive) = mpsc::sync_channel::<Result<Sent, (isize, String)>>(1);
    let handler = RcBlock::new(move |content: *mut AnyObject, error: *mut AnyObject| {
        let result = match unsafe { Retained::retain(content) } {
            Some(content) => Ok(Sent(content)),
            None => Err(unsafe { error_info(error) }),
        };
        let _ = send.try_send(result);
    });
    unsafe {
        let _: () = msg_send![
            cls,
            getShareableContentExcludingDesktopWindows: Bool::YES,
            onScreenWindowsOnly: Bool::YES,
            completionHandler: &*handler
        ];
    }
    match receive.recv_timeout(Duration::from_secs(10)) {
        Ok(Ok(content)) => Ok(content.0),
        Ok(Err((code, text))) => Err(sck_failure(code, &text)),
        Err(_) => Err(Fail::new(
            "TimeoutError",
            "ScreenCaptureKit did not list the shareable content within 10s",
        )),
    }
}

unsafe fn pixel_scale(display: u32, width: f64) -> f64 {
    let mode = unsafe { CGDisplayCopyDisplayMode(display) };
    if mode.is_null() || width <= 0.0 {
        return 1.0;
    }
    let pixels = unsafe { CGDisplayModeGetPixelWidth(mode) };
    unsafe { CGDisplayModeRelease(mode) };
    if pixels == 0 {
        1.0
    } else {
        pixels as f64 / width
    }
}

unsafe fn window_row(window: &AnyObject) -> WindowRow {
    let frame: CGRect = unsafe { msg_send![window, frame] };
    let on_screen: Bool = unsafe { msg_send![window, isOnScreen] };
    let app: Option<Retained<AnyObject>> = unsafe { msg_send![window, owningApplication] };
    let mut row = WindowRow {
        id: unsafe { msg_send![window, windowID] },
        title: unsafe { text(msg_send![window, title]) },
        frame: rect(frame),
        layer: unsafe { msg_send![window, windowLayer] },
        on_screen: on_screen.as_bool(),
        ..WindowRow::default()
    };
    if let Some(app) = app {
        let pid: i32 = unsafe { msg_send![&*app, processID] };
        row.pid = Some(pid);
        row.bundle_id = unsafe { text(msg_send![&*app, bundleIdentifier]) };
        row.app_name = unsafe { text(msg_send![&*app, applicationName]) };
    }
    row
}

/// Each display's work area and name, from `NSScreen` on the main queue; if it does not answer within
/// half a second the whole display is the work area.
fn screen_details(displays: &mut [DisplayRow]) {
    let (send, receive) = mpsc::sync_channel(1);
    dispatch2::DispatchQueue::main().exec_async(move || {
        let screens = std::panic::catch_unwind(|| autoreleasepool(|_| unsafe { read_screens() }));
        let _ = send.try_send(screens.unwrap_or_default());
    });
    let Ok(screens) = receive.recv_timeout(Duration::from_millis(500)) else {
        return;
    };
    for display in displays {
        if let Some((_, work_area, name)) = screens.iter().find(|(id, ..)| *id == display.id) {
            display.work_area = Some(*work_area);
            display.name = name.clone();
        }
    }
}

unsafe fn read_screens() -> Vec<(u32, Rect, Option<String>)> {
    let Some(cls) = AnyClass::get(c"NSScreen") else {
        return Vec::new();
    };
    let screens: Option<Retained<AnyObject>> = unsafe { msg_send![cls, screens] };
    let Some(screens) = screens else {
        return Vec::new();
    };
    let screens = unsafe { objects(&screens) };
    let Some(primary) = screens.first() else {
        return Vec::new();
    };
    let primary: CGRect = unsafe { msg_send![&**primary, frame] };
    let key = NSString::from_str("NSScreenNumber");
    let mut out = Vec::new();
    for screen in &screens {
        let description: Option<Retained<AnyObject>> =
            unsafe { msg_send![&**screen, deviceDescription] };
        let number: Option<Retained<AnyObject>> =
            description.and_then(|d| unsafe { msg_send![&*d, objectForKey: &*key] });
        let Some(number) = number else { continue };
        let id: u32 = unsafe { msg_send![&*number, unsignedIntValue] };
        let visible: CGRect = unsafe { msg_send![&**screen, visibleFrame] };
        let name: Option<Retained<NSString>> = unsafe { msg_send![&**screen, localizedName] };
        out.push((
            id,
            listing::flip(rect(visible), primary.size.height),
            name.map(|n| n.to_string()),
        ));
    }
    out
}

enum Target<'a> {
    Display(&'a Retained<AnyObject>, Rect),
    Window(&'a Retained<AnyObject>, u32),
}

type Shot = Result<CgImage, (isize, String)>;

enum Preview {
    None,
    Ready(Result<CgImage, Fail>),
    Waiting(mpsc::Receiver<Shot>),
}

unsafe fn start_preview(
    target: Option<Target<'_>>,
    (width, height): (u32, u32),
    modern: bool,
) -> Preview {
    let Some(target) = target else {
        return Preview::Ready(Err(Fail::new(
            "NotFoundError",
            "the display is no longer available",
        )));
    };
    if width == 0 || height == 0 {
        return Preview::None;
    }
    let result = if modern {
        unsafe { screenshot(&target, width, height) }.map(Preview::Waiting)
    } else {
        unsafe { window_list_image(&target) }.map(|image| Preview::Ready(Ok(image)))
    };
    result.unwrap_or_else(|error| Preview::Ready(Err(error)))
}

fn finish_preview(
    preview: Preview,
    (width, height): (u32, u32),
    deadline: Instant,
) -> Result<String, Fail> {
    let image = match preview {
        Preview::None => return Ok(String::new()),
        Preview::Ready(image) => image?,
        Preview::Waiting(receive) => receive
            .recv_timeout(deadline.saturating_duration_since(Instant::now()))
            .map_err(|_| {
                Fail::new(
                    "TimeoutError",
                    "the source did not supply a preview within 2s",
                )
            })?
            .map_err(|(code, text)| sck_failure(code, &text))?,
    };
    let mut rgba = render(&image, width, height)?;
    listing::opaque(&mut rgba);
    png_url(&rgba, width, height)
}

unsafe fn content_filter(target: &Target<'_>) -> Result<Retained<AnyObject>, Fail> {
    let filter: Allocated<AnyObject> = unsafe { msg_send![class(c"SCContentFilter")?, alloc] };
    let filter: Option<Retained<AnyObject>> = match target {
        Target::Display(display, _) => {
            let none: Retained<AnyObject> = unsafe { msg_send![class(c"NSArray")?, array] };
            unsafe { msg_send![filter, initWithDisplay: &***display, excludingWindows: &*none] }
        }
        Target::Window(window, _) => unsafe {
            msg_send![filter, initWithDesktopIndependentWindow: &***window]
        },
    };
    filter.ok_or_else(|| {
        Fail::new(
            "OperationError",
            "ScreenCaptureKit refused the content filter",
        )
    })
}

unsafe fn screenshot(
    target: &Target<'_>,
    width: u32,
    height: u32,
) -> Result<mpsc::Receiver<Shot>, Fail> {
    let manager = class(c"SCScreenshotManager")?;
    let filter = unsafe { content_filter(target)? };
    let config: Retained<AnyObject> = unsafe { msg_send![class(c"SCStreamConfiguration")?, new] };
    unsafe {
        let _: () = msg_send![&*config, setWidth: width as usize];
        let _: () = msg_send![&*config, setHeight: height as usize];
        let _: () = msg_send![&*config, setShowsCursor: Bool::NO];
    }
    let (send, receive) = mpsc::sync_channel(1);
    let handler = RcBlock::new(move |image: *mut CGImage, error: *mut AnyObject| {
        let result = unsafe { CgImage::retain(image) }.ok_or_else(|| unsafe { error_info(error) });
        let _ = send.try_send(result);
    });
    unsafe {
        let _: () = msg_send![
            manager,
            captureImageWithFilter: &*filter,
            configuration: &*config,
            completionHandler: &*handler
        ];
    }
    Ok(receive)
}

type WindowListCreateImage = unsafe extern "C" fn(CGRect, u32, u32, u32) -> *mut CGImage;

/// `CGWindowListCreateImage`, looked up rather than linked (the macOS 15 SDK marks it obsoleted).
fn window_list_create_image() -> Result<WindowListCreateImage, Fail> {
    let symbol = unsafe { dlsym(RTLD_DEFAULT, c"CGWindowListCreateImage".as_ptr()) };
    if symbol.is_null() {
        return Err(Fail::new(
            "NotSupportedError",
            "CGWindowListCreateImage is unavailable",
        ));
    }
    // SAFETY: the C prototype is `CGImageRef (CGRect, CGWindowListOption,
    // CGWindowID, CGWindowImageOption)`, both options `uint32_t`.
    Ok(unsafe { std::mem::transmute::<*mut c_void, WindowListCreateImage>(symbol) })
}

fn null_rect() -> CGRect {
    CGRect::new(
        CGPoint::new(f64::INFINITY, f64::INFINITY),
        CGSize::new(0.0, 0.0),
    )
}

/// This process's own window as the window server composes it, at backing resolution. A process
/// may read its own windows without screen recording consent.
pub(super) fn own_window(ns_view: *mut c_void) -> Result<super::WindowShot, Fail> {
    let fail = |message: &str| Fail::new("OperationError", message.to_string());
    MainThreadMarker::new().ok_or_else(|| fail("a window is read on the main thread"))?;
    // SAFETY: gpui's raw handle is its live `NSView`, read on the main thread.
    let view = unsafe { (ns_view as *const NSView).as_ref() }.ok_or_else(|| fail("no view"))?;
    let window = view
        .window()
        .ok_or_else(|| fail("the view is in no window"))?;
    let number = window.windowNumber();
    if number <= 0 {
        return Err(fail("the window has no window server number"));
    }
    let create = window_list_create_image()?;
    let image = unsafe {
        CgImage::adopt(create(
            null_rect(),
            LIST_INCLUDING_WINDOW,
            number as u32,
            IMAGE_IGNORE_FRAMING | IMAGE_BEST_RESOLUTION,
        ))
    }
    .ok_or_else(|| fail("the window server returned no image of the window"))?;
    let (width, height) = unsafe {
        (
            CGImageGetWidth(image.0.as_ptr()) as u32,
            CGImageGetHeight(image.0.as_ptr()) as u32,
        )
    };
    let frame = window.frame();
    if width == 0 || height == 0 || frame.size.width <= 0.0 {
        return Err(fail("the window server returned an empty image"));
    }
    let mut rgba = render(&image, width, height)?;
    listing::opaque(&mut rgba);
    let scale = f64::from(width) / frame.size.width;
    let content = view.convertRect_toView(view.bounds(), None);
    let top = frame.size.height - (content.origin.y + content.size.height);
    Ok(super::WindowShot {
        width,
        height,
        rgba,
        client_origin: (
            (content.origin.x * scale).round() as i32,
            (top * scale).round() as i32,
        ),
        window: number as isize,
    })
}

unsafe fn window_list_image(target: &Target<'_>) -> Result<CgImage, Fail> {
    let create = window_list_create_image()?;
    let image = match target {
        Target::Display(_, frame) => unsafe {
            create(
                cg_rect(*frame),
                LIST_ON_SCREEN_ONLY,
                0,
                IMAGE_NOMINAL_RESOLUTION,
            )
        },
        Target::Window(_, id) => unsafe {
            create(
                null_rect(),
                LIST_INCLUDING_WINDOW,
                *id,
                IMAGE_IGNORE_FRAMING | IMAGE_NOMINAL_RESOLUTION,
            )
        },
    };
    unsafe { CgImage::adopt(image) }
        .ok_or_else(|| Fail::new("OperationError", "the window server returned no image"))
}

fn render(image: &CgImage, width: u32, height: u32) -> Result<Vec<u8>, Fail> {
    let mut rgba = vec![0u8; width as usize * height as usize * 4];
    unsafe {
        let space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
        if space.is_null() {
            return Err(Fail::new(
                "OperationError",
                "CGColorSpaceCreateWithName failed",
            ));
        }
        let context = CGBitmapContextCreate(
            rgba.as_mut_ptr().cast(),
            width as usize,
            height as usize,
            8,
            width as usize * 4,
            space,
            PREMULTIPLIED_RGBA,
        );
        CGColorSpaceRelease(space);
        if context.is_null() {
            return Err(Fail::new("OperationError", "CGBitmapContextCreate failed"));
        }
        CGContextSetInterpolationQuality(context, INTERPOLATION_HIGH);
        CGContextDrawImage(
            context,
            cg_rect(Rect {
                width: width as f64,
                height: height as f64,
                ..Rect::default()
            }),
            image.0.as_ptr(),
        );
        CGContextRelease(context);
    }
    Ok(rgba)
}

unsafe fn app_icon(pid: i32) -> Option<String> {
    let cls = AnyClass::get(c"NSRunningApplication")?;
    let app: Option<Retained<AnyObject>> =
        unsafe { msg_send![cls, runningApplicationWithProcessIdentifier: pid] };
    let icon: Option<Retained<AnyObject>> = unsafe { msg_send![&*app?, icon] };
    let mut proposed = CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(32.0, 32.0));
    let image: *mut CGImage = unsafe {
        msg_send![
            &*icon?,
            CGImageForProposedRect: &mut proposed as *mut CGRect,
            context: None::<&AnyObject>,
            hints: None::<&AnyObject>
        ]
    };
    let image = unsafe { CgImage::retain(image) }?;
    let mut rgba = render(&image, 32, 32).ok()?;
    listing::unpremultiply(&mut rgba);
    png_url(&rgba, 32, 32).ok()
}