sk-desktop 0.3.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
//! `NSOpenPanel` / `NSSavePanel`, `NSAlert` and `NSColorPanel`, for a `sk-dialog` thread (mod.rs).
//!
//! AppKit panels belong to the main thread, which is also the frame thread and JSC's. The dialog thread
//! hands the panel to the main queue and waits on a channel; nothing runs modal (no `runModal`), so gpui
//! and JS keep running. With an owner window on screen the panel is a sheet on it; without one a file
//! panel is modeless, and a question (which needs its window) is dismissed.
//!
//! The owner (`Owner::hwnd`) is the `NSWindow` resolved from gpui's `NSView` ([`ns_window_of_view`]); the
//! main thread uses that earlier-captured pointer only after finding it in `[NSApp windows]`.
//!
//! Cancellation: the dialog thread checks its owner every 100 ms; once it is closing, the main thread ends
//! the panel as its Cancel would. Every completion handler orders its panel out before answering, so when
//! the thread returns (`is_idle`) no sheet is attached. After [`GIVE_UP`] the thread stops waiting.
//!
//! The colour picker is the shared `NSColorPanel`: not modal, no OK button. The colour it shows when it
//! closes is the answer, an unchanged colour is a cancel, and one is open app-wide.

use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::c_void;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::ptr::NonNull;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc;
use std::time::{Duration, Instant};

use block2::RcBlock;
use objc2::rc::{autoreleasepool, Retained, Weak};
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2::{define_class, msg_send, sel, DefinedClass, MainThreadMarker, MainThreadOnly};
use objc2_app_kit::{
    NSAlert, NSAlertStyle, NSApplication, NSButton, NSColor, NSColorPanel, NSColorSpace,
    NSModalResponse, NSModalResponseCancel, NSModalResponseOK, NSOpenPanel, NSPopUpButton,
    NSRequestUserAttentionType, NSSavePanel, NSTextField, NSView, NSWindow,
    NSWindowWillCloseNotification,
};
use objc2_foundation::{
    NSArray, NSFileManager, NSNotification, NSNotificationCenter, NSObject, NSObjectProtocol,
    NSPoint, NSRect, NSSearchPathDirectory, NSSearchPathDomainMask, NSSize, NSString,
    NSUserDefaults, NSURL,
};

use super::ask::label_of;
use super::mac_plan::{self, Format};
use super::{Ask, Cancellation, Kind, Known, Native, Start};
use crate::Fail;

// `UTType` is looked up by name; linking makes sure its framework is loaded (macOS 11+).
#[link(name = "UniformTypeIdentifiers", kind = "framework")]
unsafe extern "C" {}

const POLL: Duration = Duration::from_millis(100);
const GIVE_UP: Duration = Duration::from_secs(3);

type Answer<T> = Result<Option<T>, Fail>;
type Reply<T> = mpsc::Sender<Answer<T>>;

struct Live {
    close: Rc<dyn Fn()>,
    force: Box<dyn FnOnce()>,
    asked: bool,
}

thread_local! {
    static LIVE: RefCell<HashMap<u64, Live>> = RefCell::new(HashMap::new());
}

static NEXT: AtomicU64 = AtomicU64::new(1);

/// Registered before the panel begins, so a completion handler AppKit calls at once finds it to forget.
fn register(id: u64, close: Rc<dyn Fn()>, force: Box<dyn FnOnce()>) {
    LIVE.with(|l| {
        l.borrow_mut().insert(
            id,
            Live {
                close,
                force,
                asked: false,
            },
        )
    });
}

fn forget(id: u64) {
    // Dropped outside the borrow: the closures release AppKit objects.
    let gone = LIVE.with(|l| l.borrow_mut().remove(&id));
    drop(gone);
}

/// Main thread: dialog `id`'s owner is closing. The first request ends the dialog as Cancel would; a
/// later one forces it. AppKit is called outside the borrow: ending a panel runs its completion handler.
fn close(id: u64) {
    enum Step {
        Ask(Rc<dyn Fn()>),
        Force(Box<dyn FnOnce()>),
    }
    let step = LIVE.with(|l| {
        let mut l = l.borrow_mut();
        let live = l.get_mut(&id)?;
        if live.asked {
            l.remove(&id).map(|live| Step::Force(live.force))
        } else {
            live.asked = true;
            Some(Step::Ask(live.close.clone()))
        }
    });
    match step {
        Some(Step::Ask(f)) => f(),
        Some(Step::Force(f)) => f(),
        None => {}
    }
}

fn run<T: Send + 'static>(
    what: &'static str,
    cancel: &Cancellation,
    show: impl FnOnce(MainThreadMarker, u64, Reply<T>) -> Result<(), Fail> + Send + 'static,
) -> Answer<T> {
    if cancel.is_requested() {
        return Ok(None);
    }
    let id = NEXT.fetch_add(1, Ordering::Relaxed);
    let (tx, rx) = mpsc::channel();
    let gate = cancel.clone();
    dispatch2::DispatchQueue::main().exec_async(move || {
        let failed = tx.clone();
        let shown = std::panic::catch_unwind(AssertUnwindSafe(|| {
            if gate.is_requested() {
                let _ = tx.send(Ok(None));
                return Ok(());
            }
            autoreleasepool(|_| match MainThreadMarker::new() {
                Some(mtm) => show(mtm, id, tx),
                None => Err(Fail::new(
                    "InvalidStateError",
                    "the main queue ran off the main thread",
                )
                .code("EIO")),
            })
        }));
        let failure = match shown {
            Ok(Ok(())) => return,
            Ok(Err(f)) => f,
            Err(_) => {
                forget(id);
                Fail::new(
                    "InvalidStateError",
                    format!("the {what} panel could not be shown"),
                )
                .code("EIO")
            }
        };
        let _ = failed.send(Err(failure));
    });
    let mut closing: Option<Instant> = None;
    loop {
        match rx.recv_timeout(POLL) {
            Ok(answer) => return answer,
            Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(None),
            Err(mpsc::RecvTimeoutError::Timeout) => {}
        }
        if !cancel.is_requested() {
            continue;
        }
        let since = *closing.get_or_insert_with(Instant::now);
        if since.elapsed() >= GIVE_UP {
            crate::log_later("dialog", format!("[dialog] the {what} panel did not close with its window; no longer waiting for it"));
            return Ok(None);
        }
        dispatch2::DispatchQueue::main().exec_async(move || close(id));
    }
}

/// Runs a completion handler's body; a panic answers with a failure instead of unwinding into AppKit.
fn guarded<T>(reply: &Reply<T>, body: impl FnOnce() -> Answer<T>) {
    let answer = std::panic::catch_unwind(AssertUnwindSafe(body)).unwrap_or_else(|_| {
        Err(Fail::new("InvalidStateError", "the dialog's answer could not be read").code("EIO"))
    });
    let _ = reply.send(answer);
}

/// The `NSWindow` of gpui's `NSView`: a dialog owner. Main thread only.
pub fn ns_window_of_view(ns_view: *mut c_void) -> Option<isize> {
    MainThreadMarker::new()?;
    // SAFETY: gpui's raw handle is its live `NSView`, read on the main thread.
    let view = unsafe { (ns_view as *const NSView).as_ref() }?;
    view.window().map(|w| Retained::as_ptr(&w) as isize)
}

pub(crate) fn window_of(mtm: MainThreadMarker, owner: isize) -> Option<Retained<NSWindow>> {
    if owner == 0 {
        return None;
    }
    NSApplication::sharedApplication(mtm)
        .windows()
        .iter()
        .find(|w| Retained::as_ptr(w) as isize == owner)
}

fn sheet_parent(mtm: MainThreadMarker, owner: isize) -> Option<Retained<NSWindow>> {
    window_of(mtm, owner)
        .filter(|w| w.isVisible() && !w.isMiniaturized() && w.attachedSheet().is_none())
}

pub(super) fn known_folder(k: Known) -> Option<PathBuf> {
    let dir = match k {
        Known::Desktop => NSSearchPathDirectory::DesktopDirectory,
        Known::Documents => NSSearchPathDirectory::DocumentDirectory,
        Known::Downloads => NSSearchPathDirectory::DownloadsDirectory,
        Known::Music => NSSearchPathDirectory::MusicDirectory,
        Known::Pictures => NSSearchPathDirectory::PicturesDirectory,
        Known::Videos => NSSearchPathDirectory::MoviesDirectory,
    };
    let found = autoreleasepool(|_| {
        NSFileManager::defaultManager()
            .URLsForDirectory_inDomains(dir, NSSearchPathDomainMask::UserDomainMask)
            .firstObject()
            .and_then(|url| url.to_file_path())
    });
    found
        .or_else(|| std::env::var_os("HOME").map(|home| mac_plan::home_folder(Path::new(&home), k)))
}

pub(super) fn pick(n: &Native, owner: isize, cancel: &Cancellation) -> Answer<Vec<PathBuf>> {
    let n = n.clone();
    run("file", cancel, move |mtm, id, reply| {
        show_panel(mtm, id, &n, owner, reply)
    })
}

fn content_types(exts: Option<&[String]>) -> Retained<NSArray<AnyObject>> {
    let (Some(exts), Some(cls)) = (exts, AnyClass::get(c"UTType")) else {
        return NSArray::new();
    };
    let types: Vec<Retained<AnyObject>> = exts
        .iter()
        .filter_map(|e| -> Option<Retained<AnyObject>> {
            unsafe { msg_send![cls, typeWithFilenameExtension: &*NSString::from_str(e)] }
        })
        .collect();
    NSArray::from_retained_slice(&types)
}

fn set_allowed(panel: &NSSavePanel, types: &NSArray<AnyObject>) {
    unsafe {
        let _: () = msg_send![panel, setAllowedContentTypes: types];
    }
}

struct FormatIvars {
    panel: Weak<NSSavePanel>,
    types: Vec<Retained<NSArray<AnyObject>>>,
}

define_class!(
    // SAFETY: NSObject has no subclassing requirements, and FormatTarget
    // does not implement Drop.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "SkathiDialogFormatTarget"]
    #[ivars = FormatIvars]
    struct FormatTarget;

    impl FormatTarget {
        #[unsafe(method(formatChanged:))]
        fn format_changed(&self, sender: &NSPopUpButton) {
            let ivars = self.ivars();
            let types = usize::try_from(sender.indexOfSelectedItem()).ok().and_then(|i| ivars.types.get(i));
            if let (Some(panel), Some(types)) = (ivars.panel.load(), types) {
                set_allowed(&panel, types);
            }
        }
    }
);

impl FormatTarget {
    fn new(
        mtm: MainThreadMarker,
        panel: &NSSavePanel,
        types: Vec<Retained<NSArray<AnyObject>>>,
    ) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(FormatIvars {
            panel: Weak::new(panel),
            types,
        });
        unsafe { msg_send![super(this), init] }
    }
}

fn format_view(
    mtm: MainThreadMarker,
    formats: &[Format],
    target: &FormatTarget,
) -> Retained<NSView> {
    let label = NSTextField::labelWithString(&NSString::from_str("Format:"), mtm);
    let popup =
        NSPopUpButton::initWithFrame_pullsDown(NSPopUpButton::alloc(mtm), NSRect::ZERO, false);
    for f in formats {
        popup.addItemWithTitle(&NSString::from_str(&f.name));
    }
    popup.selectItemAtIndex(0);
    unsafe {
        popup.setTarget(Some(target));
        popup.setAction(Some(sel!(formatChanged:)));
    }
    label.sizeToFit();
    popup.sizeToFit();
    let (l, p) = (label.frame().size, popup.frame().size);
    let (gap, pad) = (8.0, 12.0);
    let popup_width = p.width.max(160.0);
    let height = l.height.max(p.height) + 2.0 * pad;
    let width = pad + l.width + gap + popup_width + pad;
    let view = NSView::initWithFrame(
        NSView::alloc(mtm),
        NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(width, height)),
    );
    label.setFrameOrigin(NSPoint::new(pad, (height - l.height) / 2.0));
    popup.setFrame(NSRect::new(
        NSPoint::new(pad + l.width + gap, (height - p.height) / 2.0),
        NSSize::new(popup_width, p.height),
    ));
    view.addSubview(&label);
    view.addSubview(&popup);
    view
}

fn picked(panel: &NSSavePanel, open: Option<&NSOpenPanel>) -> Result<Vec<PathBuf>, Fail> {
    let urls: Vec<Retained<NSURL>> = match open {
        Some(open) => open.URLs().to_vec(),
        None => panel.URL().into_iter().collect(),
    };
    urls.iter()
        .map(|url| {
            url.to_file_path().ok_or_else(|| {
                Fail::new("InvalidStateError", "a picked item is not a file path").code("EIO")
            })
        })
        .collect()
}

fn show_panel(
    mtm: MainThreadMarker,
    id: u64,
    n: &Native,
    owner: isize,
    reply: Reply<Vec<PathBuf>>,
) -> Result<(), Fail> {
    let open = (n.kind != Kind::Save).then(|| NSOpenPanel::openPanel(mtm));
    let panel: Retained<NSSavePanel> = match &open {
        Some(open) => Retained::into_super(open.clone()),
        None => NSSavePanel::savePanel(mtm),
    };
    if let Some(open) = &open {
        open.setCanChooseFiles(n.kind == Kind::Open);
        open.setCanChooseDirectories(n.kind == Kind::Folder);
        open.setAllowsMultipleSelection(n.multiple);
        open.setResolvesAliases(true);
        panel.setTreatsFilePackagesAsDirectories(true);
    }
    panel.setCanCreateDirectories(n.kind != Kind::Open);
    if n.kind == Kind::Save {
        if let Some(name) = &n.suggested_name {
            panel.setNameFieldStringValue(&NSString::from_str(name));
        }
    }

    let defaults = NSUserDefaults::standardUserDefaults();
    let key = NSString::from_str(&mac_plan::remembered_key(n.client));
    let remembered = defaults
        .stringForKey(&key)
        .map(|s| PathBuf::from(s.to_string()))
        .filter(|p| p.is_dir());
    let start = match &n.start {
        Some(Start::Known(k)) => known_folder(*k),
        Some(Start::Path(p)) => Some(p.clone()),
        None => None,
    };
    if let Some(url) = mac_plan::start_folder(start, n.force_start, remembered)
        .and_then(NSURL::from_directory_path)
    {
        panel.setDirectoryURL(Some(&url));
    }

    let formats = mac_plan::formats(n);
    let types: Vec<_> = formats
        .iter()
        .map(|f| content_types(f.exts.as_deref()))
        .collect();
    if let Some(first) = types.first() {
        set_allowed(&panel, first);
    }
    let target = (formats.len() > 1).then(|| {
        let target = FormatTarget::new(mtm, &panel, types);
        panel.setAccessoryView(Some(&format_view(mtm, &formats, &target)));
        if let Some(open) = &open {
            open.setAccessoryViewDisclosed(true);
        }
        target
    });

    let parent = sheet_parent(mtm, owner);
    let done = {
        let (panel, reply) = (panel.clone(), reply.clone());
        RcBlock::new(move |response: NSModalResponse| {
            let _target = &target;
            guarded(&reply, || {
                panel.orderOut(None);
                forget(id);
                if response != NSModalResponseOK {
                    return Ok(None);
                }
                if let Some(dir) = panel.directoryURL().and_then(|u| u.to_file_path()) {
                    let dir = NSString::from_str(&dir.to_string_lossy());
                    unsafe { defaults.setObject_forKey(Some(&dir), &key) };
                }
                picked(&panel, open.as_deref()).map(Some)
            });
        })
    };
    let close: Rc<dyn Fn()> = {
        let panel = panel.clone();
        Rc::new(move || unsafe { panel.cancel(None) })
    };
    let force: Box<dyn FnOnce()> = {
        let (panel, parent) = (panel.clone(), parent.clone());
        Box::new(move || {
            if let Some(parent) = &parent {
                parent.endSheet_returnCode(&panel, NSModalResponseCancel);
            }
            panel.orderOut(None);
            let _ = reply.send(Ok(None));
        })
    };
    register(id, close, force);
    match &parent {
        Some(parent) => panel.beginSheetModalForWindow_completionHandler(parent, &done),
        None => panel.beginWithCompletionHandler(&done),
    }
    Ok(())
}

/// Asks `q` in an `NSAlert` sheet on `owner`: the index of the button pressed, or `Ok(None)` when the owner's closing ends it.
pub(super) fn ask(q: &Ask, owner: isize, cancel: &Cancellation) -> Answer<usize> {
    let q = q.clone();
    run("question", cancel, move |mtm, id, reply| {
        show_alert(mtm, id, &q, owner, reply)
    })
}

fn show_alert(
    mtm: MainThreadMarker,
    id: u64,
    q: &Ask,
    owner: isize,
    reply: Reply<usize>,
) -> Result<(), Fail> {
    let Some(parent) = window_of(mtm, owner).filter(|w| w.isVisible() || w.isMiniaturized()) else {
        return Err(Fail::new(
            "NotSupportedError",
            "the question has no window on screen to be asked in",
        ));
    };
    let alert = NSAlert::new(mtm);
    alert.setAlertStyle(NSAlertStyle::Informational);
    alert.setMessageText(&NSString::from_str(&q.instruction));
    if !q.content.is_empty() {
        alert.setInformativeText(&NSString::from_str(&q.content));
    }
    let buttons: Vec<Retained<NSButton>> = q
        .buttons
        .iter()
        .map(|b| alert.addButtonWithTitle(&NSString::from_str(&label_of(b))))
        .collect();
    let count = buttons.len();
    let default = q.default.min(count.saturating_sub(1));
    if default != 0 {
        buttons[0].setKeyEquivalent(&NSString::from_str(""));
        buttons[default].setKeyEquivalent(&NSString::from_str("\r"));
    }
    let sheet = alert.window();
    sheet.setTitle(&NSString::from_str(&q.title));

    let app = NSApplication::sharedApplication(mtm);
    if parent.isMiniaturized() || !app.isActive() {
        app.requestUserAttention(NSRequestUserAttentionType::InformationalRequest);
    }
    let done = {
        let (alert, reply) = (alert.clone(), reply.clone());
        RcBlock::new(move |response: NSModalResponse| {
            guarded(&reply, || {
                alert.window().orderOut(None);
                forget(id);
                Ok(mac_plan::button_of(response, count))
            });
        })
    };
    let close: Rc<dyn Fn()> = {
        let (parent, sheet) = (parent.clone(), sheet.clone());
        Rc::new(move || parent.endSheet_returnCode(&sheet, NSModalResponseCancel))
    };
    let force: Box<dyn FnOnce()> = Box::new(move || {
        sheet.orderOut(None);
        let _ = reply.send(Ok(None));
    });
    register(id, close, force);
    alert.beginSheetModalForWindow_completionHandler(&parent, Some(&done));
    Ok(())
}

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

/// Shows the shared colour panel at `value` and answers with the colour it shows when closed; `Ok(None)` when unchanged.
pub(super) fn color(value: &str, _owner: isize, cancel: &Cancellation) -> Answer<String> {
    if COLOR_OPEN.swap(true, Ordering::AcqRel) {
        return Err(Fail::new("NotAllowedError", "Color picker already active.").code("EBUSY"));
    }
    struct Open;
    impl Drop for Open {
        fn drop(&mut self) {
            COLOR_OPEN.store(false, Ordering::Release);
        }
    }
    let _open = Open;
    let initial = value.to_string();
    run("colour", cancel, move |mtm, id, reply| {
        show_color(mtm, id, initial, reply)
    })
}

fn hex_of_color(color: &NSColor, fallback: &str) -> String {
    match color.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace()) {
        Some(c) => mac_plan::hex_of(c.redComponent(), c.greenComponent(), c.blueComponent()),
        None => fallback.to_string(),
    }
}

type Observer = Rc<RefCell<Option<Retained<ProtocolObject<dyn NSObjectProtocol>>>>>;

fn stop_observing(observer: &Observer) {
    if let Some(token) = observer.borrow_mut().take() {
        unsafe {
            NSNotificationCenter::defaultCenter()
                .removeObserver(AsRef::<AnyObject>::as_ref(&*token))
        };
    }
}

fn show_color(
    mtm: MainThreadMarker,
    id: u64,
    initial: String,
    reply: Reply<String>,
) -> Result<(), Fail> {
    let panel = NSColorPanel::sharedColorPanel(mtm);
    let (r, g, b) = mac_plan::rgb_of(&initial);
    panel.setShowsAlpha(false);
    panel.setColor(&NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0));

    let observer: Observer = Rc::default();
    let closed = {
        let (panel, observer, reply) = (panel.clone(), observer.clone(), reply.clone());
        RcBlock::new(move |_: NonNull<NSNotification>| {
            guarded(&reply, || {
                stop_observing(&observer);
                forget(id);
                let picked = hex_of_color(&panel.color(), &initial);
                Ok((picked != initial).then_some(picked))
            });
        })
    };
    let token = unsafe {
        NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
            Some(NSWindowWillCloseNotification),
            Some(&panel),
            None,
            &closed,
        )
    };
    *observer.borrow_mut() = Some(token);

    let close: Rc<dyn Fn()> = {
        let panel = panel.clone();
        Rc::new(move || panel.close())
    };
    let force: Box<dyn FnOnce()> = {
        let panel = panel.clone();
        Box::new(move || {
            stop_observing(&observer);
            panel.orderOut(None);
            let _ = reply.send(Ok(None));
        })
    };
    register(id, close, force);
    panel.makeKeyAndOrderFront(None);
    Ok(())
}