nsh-core 0.7.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! `nsh/desktop`'s app functions (macOS, Windows, Linux; elsewhere `quit`
//! and `restart` do nothing and the app does not launch at login). Windows and
//! menus, which call the app's functions and live in its reactive graph,
//! are `nsh-js`'s.

use std::{
    cell::{Cell, RefCell},
    rc::{Rc, Weak},
};

use crate::{
    Command, ROOT_ID,
    desktop::{DesktopCommand, LaunchAtLoginError, QuitMode, QuitRequestOptions},
    element::{
        CallCx, Callback, JsError, JsHost, JsIn, JsObject, JsOwned, JsValue, Local, ModuleCx,
        PropEnum, PropError, Ret, Settles, Stop, System, TsTypes, codes, io_code, module,
        quit::{QuitRequestListener, Subscription},
        task::Action,
    },
    single_instance::SecondInstance,
};

fn desktop(cx: &mut ModuleCx, command: DesktopCommand) {
    cx.act(Action::Command(
        ROOT_ID,
        Command::Desktop(Box::new(command)),
    ));
}

/// What a `setLaunchAtLogin` call rejects with.
fn launch_at_login_error(error: LaunchAtLoginError) -> JsError {
    match error {
        LaunchAtLoginError::Unavailable => {
            JsError::Error(error.to_string()).with_code(codes::UNAVAILABLE)
        }
        LaunchAtLoginError::Denied => JsError::access_denied(error.to_string(), "application", ""),
        // Every failure has a code to branch on: the error's own, else EIO.
        LaunchAtLoginError::System(io) => {
            let code = io_code(&io).unwrap_or("EIO");
            JsError::Error(LaunchAtLoginError::System(io).to_string()).with_code(code)
        }
    }
}

/// The application as a whole (desktops; its functions do nothing elsewhere,
/// and of its events only `openFiles` comes on iOS and Android too).
#[module]
pub(crate) struct Application;

#[module]
impl Application {
    /// Quits the app, as the application menu's `quit` role and the
    /// platform's quit key do: it ends the app, not its windows one by one
    /// (their `onOpenChange` may not run), and its run ends, also while
    /// closing the window alone would leave it running (a window kept
    /// hidden, a tray icon). It quits while the app listens to `quitRequest` too: that is
    /// how an app that asks first quits once it is ready. A view embedded
    /// in another app leaves the app's lifecycle to that app. On the web,
    /// called while a `quitRequest` listener runs, it lets the page leave
    /// without a question.
    pub(crate) fn quit(cx: &mut ModuleCx) {
        desktop(cx, DesktopCommand::Quit);
    }

    /// Sets when closing the app's last window quits it: `"platform"` (the
    /// default) follows the platform (macOS stays in the Dock; Windows and
    /// Linux quit), `"lastWindowClosed"` quits on every platform, and
    /// `"explicit"` leaves the app running so it can open another window,
    /// show a tray menu or call `quit()`. The app root stays alive while no
    /// window is open.
    pub(crate) fn set_quit_mode(quit_mode: QuitMode, cx: &mut ModuleCx) {
        desktop(cx, DesktopCommand::SetQuitMode(quit_mode));
    }

    /// Sets the additional sources of `quitRequest` on standalone macOS
    /// apps. `system` includes logout, restart and shutdown. Both default to
    /// false, and each call replaces them. `mainWindowClose` is legacy in
    /// window model v2: there is no user-closable main window, so it has no
    /// close to intercept. A window with `closeOnPress: false` keeps its own
    /// close handler; a window kept alive on close still hides. Requires a
    /// `quitRequest` listener. Changing the options cancels a pending
    /// request. Replacing the app cancels its request and restores the
    /// default options. Other platforms and embedded views ignore it.
    pub(crate) fn set_quit_request_options(options: QuitRequestOptions, cx: &mut ModuleCx) {
        desktop(cx, DesktopCommand::SetQuitRequestOptions(options));
    }

    /// Cancels the pending quit request on standalone macOS apps,
    /// including an intercepted logout or shutdown. Call `quit()` to
    /// approve instead. Repeated requests share the pending confirmation
    /// until answered. An unanswered system request is cancelled after
    /// 110 seconds, before AppKit's logout timeout. Removing the last
    /// listener also cancels it. Does nothing without a pending request
    /// or on other platforms.
    pub(crate) fn cancel_quit_request(cx: &mut ModuleCx) {
        desktop(cx, DesktopCommand::CancelQuitRequest);
    }

    /// Restarts the app: it quits as `quit` does, and once the app has
    /// exited it starts again with the arguments it was started with. For a
    /// setting that takes effect at the next start (the app's language, say):
    /// ask the user first, then call it. Standalone apps on macOS, Windows
    /// and Linux; a view embedded in another app leaves the app's lifecycle
    /// to that app.
    pub(crate) fn restart(cx: &mut ModuleCx) {
        desktop(cx, DesktopCommand::Restart);
    }

    /// Whether the system opens the app when the user logs in, as the
    /// system has it now: ask again when the app shows it, as the user may
    /// change it in the system's settings. `false` wherever the app cannot
    /// launch at login (a view embedded in another app, `nsh run`, iOS,
    /// Android, the web) and while macOS waits for the user to approve it
    /// in Login Items.
    pub(crate) async fn launch_at_login() -> bool {
        crate::element::desktop::launch_at_login().await
    }

    /// Turns launching at login on or off: turning on what is on and off
    /// what is off succeed. Call it when the user turns the app's own
    /// setting on or off, never at every start: what the user chose in the
    /// system's settings stands. Rejects with
    /// `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` where the app cannot launch at
    /// login, with `ERR_ACCESS_DENIED` (`permission` `"application"`) for an
    /// app that declares capabilities without `application`, and with the
    /// system's error (Node's code, `EIO` without one).
    pub(crate) async fn set_launch_at_login(enabled: bool) -> Result<(), JsError> {
        crate::element::desktop::set_launch_at_login(enabled)
            .await
            .map_err(launch_at_login_error)
    }

    /// Listens to `event`. `secondInstance`: with nsh.json
    /// `"singleInstance": true`, the app was launched again on Windows or
    /// Linux; that launch exited without opening a window and handed this
    /// one its `args` (the program's path not included) and `cwd`, the
    /// directory relative paths among them are relative to. The app has
    /// already heard `reopen`; nothing is brought forward implicitly. What
    /// else the launch means is the app's. Anyone can start the app with any arguments:
    /// treat them as untrusted input. Launches while nothing listened go to
    /// the next listener (at most 16, the oldest dropped). macOS runs one
    /// instance of an app on its own and reports nothing; files and links
    /// come as `openFiles`, links through `UrlScheme`. `openFiles`: the
    /// system opened the app with files of the types it declares (nsh.json
    /// `fileTypes`) on macOS, iOS, Windows or Linux, or another app shared
    /// files to it on Android. This can happen at launch or while the app
    /// runs; `paths` are absolute. Files that came while nothing listened,
    /// including those that launched the app, go to the next listener at
    /// once (at most 64, the oldest dropped). Opening a file does not grant
    /// the `fs` capability. On desktops a link, a file or a second launch that
    /// brings the app forward also reports `reopen` first. `quit`: the app is quitting (its Quit
    /// item, `quit()`, its last window closing, the system ending it, a host
    /// app removing its view, on the web the page going, once, however the
    /// user left it; a page the browser keeps to come back to keeps the app
    /// running), for its cleanup, as GPUI's `on_app_quit`: it cannot keep
    /// the app running, and it is not a per-window close sequence (its
    /// windows' `onOpenChange` may not run); an app that asks first listens to
    /// `quitRequest`). A promise the listener returns is awaited, 200 ms at
    /// most for all of them, while the platform waits too. `quitRequest`:
    /// the user asked to quit the app with its Quit item or the platform's
    /// quit key (Command-Q, Ctrl+Q), as AppKit's
    /// `applicationShouldTerminate:`. While anything listens, these no
    /// longer quit: the app decides (it asks the user, saves, waits for work
    /// to finish), then calls `quit()`. The system ending the app (logging
    /// out, shutting down) does not ask by default. On macOS,
    /// `setQuitRequestOptions` includes system requests; answer with `quit()`
    /// or `cancelQuitRequest()`. Its `mainWindowClose` option is legacy in
    /// window model v2: there is no user-closable main window.
    /// Standalone apps on macOS, Windows and Linux; on the web, the user
    /// leaving the page (closing its tab,
    /// reloading) is the request: a `quit()` the listener calls at once lets
    /// the page go without a question, otherwise the browser asks the user
    /// whether to leave; `quit` listeners run once the page is gone.
    /// `reopen`: the OS asked the app to show itself (a macOS Dock or Finder
    /// reopen, or a later launch on Windows or Linux); the app opens or
    /// focuses the window it wants. `lastWindowClosed`: the app's last
    /// window closed, after its own close path. The quit mode is decided
    /// at that close; a JS listener runs in a later commit, after the
    /// decision, so an app that stays alive with no windows sets
    /// `quitMode: "explicit"` before the last close. (A Rust
    /// listener runs synchronously, before the decision.) Only a `quit`
    /// listener's returned promise is awaited; the other events run their
    /// listeners as void, so listening for them is not a way to delay the
    /// event.
    /// Returns a function that stops listening.
    #[overload(fn(event: ApplicationSecondInstanceEvent, #[args(launch)] listener: Callback<ApplicationSecondInstance, Settles>) -> Stop)]
    #[overload(fn(event: ApplicationOpenFilesEvent, #[args(files)] listener: Callback<ApplicationOpenFiles, Settles>) -> Stop)]
    #[overload(fn(event: ApplicationQuitEvent, listener: Callback<(), Settles>) -> Stop)]
    #[overload(fn(event: ApplicationQuitRequestEvent, listener: Callback<(), Settles>) -> Stop)]
    #[overload(fn(event: ApplicationReopenEvent, listener: Callback<(), Settles>) -> Stop)]
    #[overload(fn(event: ApplicationLastWindowClosedEvent, listener: Callback<(), Settles>) -> Stop)]
    pub(crate) fn on(
        event: ApplicationEvent,
        #[args(payload)] listener: Callback<Payload, Settles>,
        sys: System,
        cx: CallCx<'_>,
    ) -> Stop {
        match event {
            ApplicationEvent::SecondInstance => second_instance(listener, &sys, cx),
            ApplicationEvent::OpenFiles => open_files(listener, &sys, cx),
            ApplicationEvent::Quit => quit(listener, &sys, cx),
            ApplicationEvent::QuitRequest => quit_request(listener, &sys, cx),
            ApplicationEvent::Reopen => reopen(listener, &sys, cx),
            ApplicationEvent::LastWindowClosed => last_window_closed(listener, &sys, cx),
        }
    }
}

fn second_instance(listener: Callback<Payload, Settles>, sys: &System, cx: CallCx<'_>) -> Stop {
    let launches = sys.locals.get::<Launches>();
    let id = launches.next.get();
    launches.next.set(id.wrapping_add(1));
    for launch in launches.unheard.take() {
        listener.post(Payload::SecondInstance(launch.into()));
    }
    launches.listeners.borrow_mut().push((id, listener));
    if !launches.started.replace(true) {
        cx.start(deliver(Rc::downgrade(&launches)));
    }
    let launches = Rc::downgrade(&launches);
    Stop::new(move || {
        if let Some(launches) = launches.upgrade() {
            launches.listeners.borrow_mut().retain(|(i, _)| *i != id);
        }
    })
}

fn open_files(listener: Callback<Payload, Settles>, sys: &System, cx: CallCx<'_>) -> Stop {
    let files = sys.locals.get::<Files>();
    let id = files.next.get();
    files.next.set(id.wrapping_add(1));
    let unheard = files.unheard.take();
    if !unheard.is_empty() {
        listener.post(Payload::OpenFiles(ApplicationOpenFiles::new(unheard)));
    }
    files.listeners.borrow_mut().push((id, listener));
    if !files.started.replace(true) {
        cx.start(deliver_files(Rc::downgrade(&files)));
    }
    let files = Rc::downgrade(&files);
    Stop::new(move || {
        if let Some(files) = files.upgrade() {
            files.listeners.borrow_mut().retain(|(i, _)| *i != id);
        }
    })
}

fn quit(listener: Callback<Payload, Settles>, sys: &System, cx: CallCx<'_>) -> Stop {
    let quits = sys.locals.get::<Quits>();
    let id = quits.next.get();
    quits.next.set(id.wrapping_add(1));
    quits.listeners.borrow_mut().push((id, listener));
    if !quits.started.replace(true) {
        cx.start(hold(Rc::downgrade(&quits)));
    }
    let quits = Rc::downgrade(&quits);
    Stop::new(move || {
        if let Some(quits) = quits.upgrade() {
            quits.listeners.borrow_mut().retain(|(i, _)| *i != id);
        }
    })
}

/// Hears the user ask to quit while the listener lasts: as long as one
/// is there, the platform leaves quitting to the app.
fn quit_request(listener: Callback<Payload, Settles>, sys: &System, cx: CallCx<'_>) -> Stop {
    let requests = sys.locals.get::<QuitRequests>();
    let id = requests.next.get();
    requests.next.set(id.wrapping_add(1));
    requests.listeners.borrow_mut().push((id, listener));
    // The core's listener is added by a task of the core, where its
    // registry is; one at a time.
    if requests.subscription.borrow().is_none() && !requests.adding.replace(true) {
        cx.start(subscribe(Rc::downgrade(&requests)));
    }
    let requests = Rc::downgrade(&requests);
    Stop::new(move || {
        let Some(requests) = requests.upgrade() else {
            return;
        };
        let removed = {
            let mut listeners = requests.listeners.borrow_mut();
            listeners.retain(|(i, _)| *i != id);
            // The last one gone: quit requests quit again.
            listeners
                .is_empty()
                .then(|| requests.subscription.borrow_mut().take())
        };
        drop(removed);
    })
}

fn reopen(listener: Callback<Payload, Settles>, sys: &System, cx: CallCx<'_>) -> Stop {
    let reopens = sys.locals.get::<Reopens>();
    let id = reopens.next.get();
    reopens.next.set(id.wrapping_add(1));
    reopens.listeners.borrow_mut().push((id, listener));
    if reopens.subscription.borrow().is_none() && !reopens.adding.replace(true) {
        cx.start(subscribe_reopens(Rc::downgrade(&reopens)));
    }
    let reopens = Rc::downgrade(&reopens);
    Stop::new(move || {
        if let Some(reopens) = reopens.upgrade() {
            let removed = {
                let mut listeners = reopens.listeners.borrow_mut();
                listeners.retain(|(i, _)| *i != id);
                listeners
                    .is_empty()
                    .then(|| reopens.subscription.borrow_mut().take())
            };
            drop(removed);
        }
    })
}

fn last_window_closed(listener: Callback<Payload, Settles>, sys: &System, cx: CallCx<'_>) -> Stop {
    let closed = sys.locals.get::<Closed>();
    let id = closed.next.get();
    closed.next.set(id.wrapping_add(1));
    closed.listeners.borrow_mut().push((id, listener));
    if closed.subscription.borrow().is_none() && !closed.adding.replace(true) {
        cx.start(subscribe_closed(Rc::downgrade(&closed)));
    }
    let closed = Rc::downgrade(&closed);
    Stop::new(move || {
        if let Some(closed) = closed.upgrade() {
            let removed = {
                let mut listeners = closed.listeners.borrow_mut();
                listeners.retain(|(i, _)| *i != id);
                listeners
                    .is_empty()
                    .then(|| closed.subscription.borrow_mut().take())
            };
            drop(removed);
        }
    })
}

/// The VM's `reopen` listeners.
#[derive(Default)]
struct Reopens {
    listeners: RefCell<Vec<(u32, Callback<Payload, Settles>)>>,
    next: Cell<u32>,
    subscription: RefCell<Option<Subscription<crate::element::quit::ReopenListener>>>,
    adding: Cell<bool>,
}

impl Local for Reopens {
    fn close(&self) {
        self.listeners.borrow_mut().clear();
        let subscription = self.subscription.borrow_mut().take();
        drop(subscription);
    }
}

/// The VM's `lastWindowClosed` listeners.
#[derive(Default)]
struct Closed {
    listeners: RefCell<Vec<(u32, Callback<Payload, Settles>)>>,
    next: Cell<u32>,
    subscription: RefCell<Option<Subscription<crate::element::quit::LastWindowClosedListener>>>,
    adding: Cell<bool>,
}

impl Local for Closed {
    fn close(&self) {
        self.listeners.borrow_mut().clear();
        let subscription = self.subscription.borrow_mut().take();
        drop(subscription);
    }
}

async fn subscribe_reopens(reopens: Weak<Reopens>) {
    let Some(this) = reopens.upgrade() else {
        return;
    };
    this.adding.set(false);
    if this.listeners.borrow().is_empty() || this.subscription.borrow().is_some() {
        return;
    }
    let subscription = crate::element::desktop::add_reopen_listener(Rc::new(move || {
        let Some(reopens) = reopens.upgrade() else {
            return;
        };
        for (_, listener) in &*reopens.listeners.borrow() {
            listener.post(Payload::Reopen);
        }
    }));
    *this.subscription.borrow_mut() = Some(subscription);
}

async fn subscribe_closed(closed: Weak<Closed>) {
    let Some(this) = closed.upgrade() else {
        return;
    };
    this.adding.set(false);
    if this.listeners.borrow().is_empty() || this.subscription.borrow().is_some() {
        return;
    }
    let subscription =
        crate::element::desktop::add_last_window_closed_listener(Rc::new(move || {
            let Some(closed) = closed.upgrade() else {
                return;
            };
            for (_, listener) in &*closed.listeners.borrow() {
                listener.post(Payload::LastWindowClosed);
            }
        }));
    *this.subscription.borrow_mut() = Some(subscription);
}

/// The VM's `quitRequest` listeners.
#[derive(Default)]
struct QuitRequests {
    listeners: RefCell<Vec<(u32, Callback<Payload, Settles>)>>,
    next: Cell<u32>,
    /// The core's listener, while the VM's has any: the platform asks the
    /// app while it is there.
    subscription: RefCell<Option<Subscription<QuitRequestListener>>>,
    /// A task adding it is on its way.
    adding: Cell<bool>,
}

impl Local for QuitRequests {
    fn close(&self) {
        self.listeners.borrow_mut().clear();
        let subscription = self.subscription.borrow_mut().take();
        drop(subscription);
    }
}

/// Adds the core's listener of quit requests for the VM's, unless they
/// went meanwhile: it posts each request to all of them.
async fn subscribe(requests: Weak<QuitRequests>) {
    let Some(this) = requests.upgrade() else {
        return;
    };
    this.adding.set(false);
    if this.listeners.borrow().is_empty() || this.subscription.borrow().is_some() {
        return;
    }
    let subscription = crate::element::desktop::add_quit_request_listener(Rc::new(move || {
        let Some(requests) = requests.upgrade() else {
            return;
        };
        for (_, listener) in &*requests.listeners.borrow() {
            listener.post(Payload::QuitRequest);
        }
    }));
    *this.subscription.borrow_mut() = Some(subscription);
}

impl JsValue for QuitMode {
    fn ts_type(_types: &mut TsTypes) -> String {
        "\"platform\" | \"lastWindowClosed\" | \"explicit\"".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        match value.as_string().as_deref() {
            Some("platform") => Ok(Self::Platform),
            Some("lastWindowClosed") => Ok(Self::LastWindowClosed),
            Some("explicit") => Ok(Self::Explicit),
            _ => Err(value.expected("\"platform\", \"lastWindowClosed\" or \"explicit\"")),
        }
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let mode = match self {
            Self::Platform => "platform",
            Self::LastWindowClosed => "lastWindowClosed",
            Self::Explicit => "explicit",
        };
        Ok(JsOwned::new(host, host.new_string(mode)?))
    }
}

/// `Application.on`'s events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub(crate) enum ApplicationEvent {
    /// The app was launched again (nsh.json `singleInstance`).
    #[default]
    SecondInstance,
    /// The system opened the app with files (nsh.json `fileTypes`).
    OpenFiles,
    /// The app is quitting.
    Quit,
    /// The user asked to quit the app.
    QuitRequest,
    /// The OS asked the app to show itself.
    Reopen,
    /// The app's last window closed.
    LastWindowClosed,
}

/// The event of a later launch (`on`'s first overload).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
pub(crate) enum ApplicationSecondInstanceEvent {
    SecondInstance,
}

/// The event of quitting (`on`'s second overload).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
pub(crate) enum ApplicationQuitEvent {
    Quit,
}

/// The event of the user asking to quit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
pub(crate) enum ApplicationQuitRequestEvent {
    QuitRequest,
}

/// The event of the OS asking the app to show itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
pub(crate) enum ApplicationReopenEvent {
    Reopen,
}

/// The event of the app's last window closing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
pub(crate) enum ApplicationLastWindowClosedEvent {
    LastWindowClosed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub(crate) enum ApplicationOpenFilesEvent {
    #[default]
    OpenFiles,
}

/// What a listener gets.
#[derive(Debug, Clone)]
pub(crate) enum Payload {
    SecondInstance(ApplicationSecondInstance),
    OpenFiles(ApplicationOpenFiles),
    Quit,
    QuitRequest,
    Reopen,
    LastWindowClosed,
}

impl JsValue for Payload {
    fn ts_type(types: &mut TsTypes) -> String {
        <ApplicationSecondInstance as JsValue>::ts_type(types)
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        Err(value.expected("no value (a payload goes to JS only)"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        match self {
            Payload::SecondInstance(launch) => launch.to_js(host),
            Payload::OpenFiles(files) => files.to_js(host),
            Payload::Quit | Payload::QuitRequest | Payload::Reopen | Payload::LastWindowClosed => {
                Ret::into_js((), host)
            }
        }
    }
}

/// A later launch of the app (the `secondInstance` event).
#[derive(Debug, Clone, Default, PartialEq, JsObject)]
pub(crate) struct ApplicationSecondInstance {
    /// Its command line's arguments, the program's path not included.
    args: Vec<String>,
    /// The directory it was started in; empty when unknown.
    cwd: String,
}

impl From<SecondInstance> for ApplicationSecondInstance {
    fn from(launch: SecondInstance) -> Self {
        Self {
            args: launch.args,
            cwd: launch.cwd,
        }
    }
}

/// The VM's `secondInstance` listeners.
#[derive(Default)]
struct Launches {
    listeners: RefCell<Vec<(u32, Callback<Payload, Settles>)>>,
    next: Cell<u32>,
    /// The task waiting for the core's launches started; it lasts as the
    /// VM does.
    started: Cell<bool>,
    /// Launches that came with no listener, for the next one.
    unheard: RefCell<Vec<SecondInstance>>,
}

impl Local for Launches {
    fn close(&self) {
        self.listeners.borrow_mut().clear();
    }
}

/// Posts the core's launches to the listeners, while the VM lasts.
async fn deliver(launches: Weak<Launches>) {
    loop {
        let launch = crate::prelude::next_second_instance().await;
        let Some(launches) = launches.upgrade() else {
            return;
        };
        let listeners = launches.listeners.borrow();
        if listeners.is_empty() {
            let mut unheard = launches.unheard.borrow_mut();
            if unheard.len() == crate::single_instance::MAX_PENDING {
                unheard.remove(0);
            }
            unheard.push(launch);
            continue;
        }
        for (_, listener) in &*listeners {
            listener.post(Payload::SecondInstance(launch.clone().into()));
        }
    }
}

/// Files the system opened the app with (the `openFiles` event).
#[derive(Debug, Clone, Default, PartialEq, JsObject)]
pub(crate) struct ApplicationOpenFiles {
    /// Their absolute paths.
    paths: Vec<String>,
}

impl ApplicationOpenFiles {
    fn new(paths: Vec<std::path::PathBuf>) -> Self {
        Self {
            paths: paths
                .into_iter()
                .map(|p| p.to_string_lossy().into_owned())
                .collect(),
        }
    }
}

/// The VM's `openFiles` listeners.
#[derive(Default)]
struct Files {
    listeners: RefCell<Vec<(u32, Callback<Payload, Settles>)>>,
    next: Cell<u32>,
    /// The task waiting for the core's files started; it lasts as the VM
    /// does.
    started: Cell<bool>,
    /// Files that came with no listener, for the next one.
    unheard: RefCell<Vec<std::path::PathBuf>>,
}

impl Local for Files {
    fn close(&self) {
        self.listeners.borrow_mut().clear();
    }
}

/// Posts the core's files to the listeners, while the VM lasts.
async fn deliver_files(files: Weak<Files>) {
    loop {
        let paths = crate::prelude::next_open_files().await;
        let Some(files) = files.upgrade() else {
            return;
        };
        let listeners = files.listeners.borrow();
        if listeners.is_empty() {
            let mut unheard = files.unheard.borrow_mut();
            unheard.extend(paths);
            let excess = unheard.len().saturating_sub(crate::file_type::MAX_PENDING);
            unheard.drain(..excess);
            continue;
        }
        let payload = ApplicationOpenFiles::new(paths);
        for (_, listener) in &*listeners {
            listener.post(Payload::OpenFiles(payload.clone()));
        }
    }
}

/// The VM's `quit` listeners.
#[derive(Default)]
struct Quits {
    listeners: RefCell<Vec<(u32, Callback<Payload, Settles>)>>,
    next: Cell<u32>,
    /// The task holding the core's quit listener started; it lasts as the
    /// VM does.
    started: Cell<bool>,
}

impl Local for Quits {
    fn close(&self) {
        self.listeners.borrow_mut().clear();
    }
}

/// Holds the core's quit listener for the VM's: as the app quits, it calls
/// each of them and waits for what they return.
async fn hold(quits: Weak<Quits>) {
    let _subscription = crate::element::desktop::add_quit_listener(Rc::new(move || {
        let calls: Vec<_> = quits
            .upgrade()
            .map(|quits| {
                let listeners = quits.listeners.borrow();
                listeners
                    .iter()
                    .map(|(_, listener)| listener.call_async(Payload::Quit))
                    .collect()
            })
            .unwrap_or_default();
        Box::pin(async move {
            for call in calls {
                if let Err(message) = call.await {
                    log::error!(target: "js", "a quit listener failed: {message}");
                }
            }
        })
    }));
    std::future::pending::<()>().await;
}