nsh-core 0.6.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
//! `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, QuitRequestOptions},
    element::{
        CallCx, Callback, JsError, JsHost, JsIn, JsObject, JsOwned, JsValue, Local, ModuleCx,
        PropEnum, PropError, Ret, 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 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: its windows close and the app stops as when
    /// its last window closes, then 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 the additional sources of `quitRequest` on standalone macOS
    /// apps. `system` includes logout, restart and shutdown;
    /// `mainWindowClose` includes a user closing the main window when that
    /// would end the app. Both default to false, and each call replaces
    /// them. 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 main window
    /// is already brought forward (shown when hidden); 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`: Open With, a double click, a drop on its icon) on macOS,
    /// iOS, Windows or Linux, at launch or while it runs; `paths` are
    /// absolute. Files that came while nothing listened, those that launched
    /// the app included, go to the next listener at once (at most 64, the
    /// oldest dropped). The app reads them with `fs`, which their opening
    /// does not grant. `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 (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 and main-window
    /// closes; answer with `quit()` or `cancelQuitRequest()`.
    /// 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.
    /// Returns a function that stops listening.
    #[overload(fn(event: ApplicationSecondInstanceEvent, #[args(launch)] listener: Callback<ApplicationSecondInstance>) -> Stop)]
    #[overload(fn(event: ApplicationOpenFilesEvent, #[args(files)] listener: Callback<ApplicationOpenFiles>) -> Stop)]
    #[overload(fn(event: ApplicationQuitEvent, listener: Callback<()>) -> Stop)]
    #[overload(fn(event: ApplicationQuitRequestEvent, listener: Callback<()>) -> Stop)]
    pub(crate) fn on(
        event: ApplicationEvent,
        #[args(payload)] listener: Callback<Payload>,
        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),
        }
    }
}

fn second_instance(listener: Callback<Payload>, 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>, 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>, 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>, 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);
    })
}

/// The VM's `quitRequest` listeners.
#[derive(Default)]
struct QuitRequests {
    listeners: RefCell<Vec<(u32, Callback<Payload>)>>,
    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);
}

/// `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 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,
}

#[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,
}

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 => 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>)>>,
    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>)>>,
    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>)>>,
    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;
}