Skip to main content

sk_runtime/
standins.rs

1//! Inert app API objects for a host built or run without the crate behind one, so `appShell`, `appTray`
2//! and the rest always exist; each says once why it does nothing.
3
4use std::ffi::c_void;
5
6use redjs::webapi::util::*;
7use serde_json::json;
8
9use crate::host::{self, global, warn_compat};
10
11const PERMISSIONS: &str =
12    "the permissions host is missing (sk_permissions::install did not run) — \
13                           `appPermissions` is inert and every capability reads as 'unsupported'.";
14const STORAGE: &str = "the storage host is missing (sk_storage::install did not run, or the host was built \
15                       without the `storages` feature) — `appStorage` is inert and localStorage does not persist.";
16const SHELL: &str =
17    "the desktop host is missing (sk_desktop::install did not run) — `appShell` is inert and every call rejects.";
18const CAPTURE: &str =
19    "the desktop host is missing (sk_desktop::install did not run) — `appCapture` has no sources.";
20const LAUNCH: &str =
21    "the desktop host is missing (sk_desktop::install did not run) — `appLaunch` is empty.";
22const NO_HOTKEYS: &str =
23    "global hotkeys are unavailable in this host: its platform has none, or it was \
24     built without Skathi's `hotkeys` feature";
25const NO_TRAY: &str = "native tray is unavailable in this host";
26
27const PERMISSION_NAMES: [&str; 7] = [
28    "microphone",
29    "camera",
30    "display-capture",
31    "notifications",
32    "clipboard-read",
33    "clipboard-write",
34    "geolocation",
35];
36
37macro_rules! inert {
38    ($name:ident, $key:literal, $why:expr, |$g:ident, $args:ident| $body:block) => {
39        crate::host_fn!(fn $name($g, $args) {
40            unsafe { warn_compat($g, $key, $why) };
41            $body
42        });
43    };
44}
45
46unsafe fn no_desktop(g: *mut c_void, what: &str) -> u64 {
47    let e = host::error(g, "Error", &format!("{what}: no desktop host"));
48    define(g, e, "name", js_string(g, "NotSupportedError"), 2);
49    define(g, e, "code", js_string(g, "ENOSYS"), 2);
50    e
51}
52
53inert!(
54    permissions_platform,
55    "appPermissions",
56    PERMISSIONS,
57    |g, _args| { unsafe { js_string(g, "this platform") } }
58);
59inert!(
60    permissions_names,
61    "appPermissions",
62    PERMISSIONS,
63    |g, _args| { unsafe { host::to_js(g, &json!(PERMISSION_NAMES)) } }
64);
65inert!(
66    permissions_query,
67    "appPermissions",
68    PERMISSIONS,
69    |g, _args| { unsafe { js_string(g, "unsupported") } }
70);
71inert!(
72    permissions_list,
73    "appPermissions",
74    PERMISSIONS,
75    |g, _args| {
76        let rows: Vec<_> = PERMISSION_NAMES
77            .iter()
78            .map(|name| json!({ "name": name, "state": "unsupported", "canRequest": false }))
79            .collect();
80        unsafe { host::to_js(g, &json!(rows)) }
81    }
82);
83inert!(
84    permissions_request,
85    "appPermissions",
86    PERMISSIONS,
87    |g, _args| { unsafe { host::resolved(g, js_string(g, "unsupported")) } }
88);
89
90inert!(storage_kinds, "appStorage", STORAGE, |g, _args| {
91    unsafe { host::frozen_strings(g, &[] as &[&str]) }
92});
93inert!(storage_folder, "appStorage", STORAGE, |g, _args| {
94    unsafe { js_string(g, "") }
95});
96inert!(storage_encrypted, "appStorage", STORAGE, |_g, _args| {
97    FALSE
98});
99inert!(storage_info, "appStorage", STORAGE, |g, _args| {
100    let info = json!({
101        "folder": "", "file": "", "encrypted": false, "bytes": 0, "loaded": false, "pending": false,
102        "provider": "", "kinds": [], "error": "no storage host", "indexedDB": null,
103    });
104    unsafe { host::to_js(g, &info) }
105});
106inert!(storage_flush, "appStorage", STORAGE, |_g, _args| { FALSE });
107// A wrong path is worse than none: the app would write somewhere real.
108inert!(
109    storage_get_user_folder,
110    "appStorage",
111    STORAGE,
112    |g, _args| {
113        unsafe {
114            host::throw(
115                g,
116                "TypeError",
117                "appStorage.getUserFolder is unavailable: no storage host",
118            )
119        }
120    }
121);
122inert!(storage_set_folder, "appStorage", STORAGE, |g, _args| {
123    unsafe {
124        host::throw(
125            g,
126            "TypeError",
127            "appStorage.setStorageFolder is unavailable: no storage host",
128        )
129    }
130});
131
132macro_rules! shell_call {
133    ($name:ident, $what:literal) => {
134        inert!($name, "appShell", SHELL, |g, _args| {
135            unsafe { host::rejected_with(g, no_desktop(g, $what)) }
136        });
137    };
138}
139shell_call!(shell_open_external, "appShell.openExternal");
140shell_call!(shell_open_path, "appShell.openPath");
141shell_call!(shell_show_item, "appShell.showItemInFolder");
142shell_call!(shell_trash_item, "appShell.trashItem");
143shell_call!(shell_open_content, "appShell.openContent");
144
145inert!(capture_permission, "appCapture", CAPTURE, |g, _args| {
146    let row = json!({ "state": "unsupported", "canRequest": false, "deniedBySystem": false });
147    unsafe { host::to_js(g, &row) }
148});
149inert!(capture_request, "appCapture", CAPTURE, |g, _args| {
150    unsafe { host::resolved(g, js_string(g, "unsupported")) }
151});
152inert!(capture_hint, "appCapture", CAPTURE, |g, _args| {
153    unsafe { js_string(g, "") }
154});
155inert!(capture_sources, "appCapture", CAPTURE, |g, _args| {
156    unsafe { host::rejected_with(g, no_desktop(g, "appCapture.getSources")) }
157});
158inert!(capture_pending, "appCapture", CAPTURE, |_g, _args| {
159    FALSE
160});
161
162inert!(launch_list, "appLaunch", LAUNCH, |g, _args| {
163    unsafe { host::frozen_strings(g, &[] as &[&str]) }
164});
165inert!(launch_cwd, "appLaunch", LAUNCH, |g, _args| {
166    unsafe { js_string(g, "") }
167});
168inert!(launch_url, "appLaunch", LAUNCH, |_g, _args| { NULL });
169inert!(launch_false, "appLaunch", LAUNCH, |_g, _args| { FALSE });
170inert!(launch_register, "appLaunch", LAUNCH, |g, _args| {
171    unsafe {
172        host::throw(
173            g,
174            "TypeError",
175            "appLaunch.registerProtocol is unavailable: no desktop host",
176        )
177    }
178});
179
180crate::host_fn!(fn hotkeys_set_bindings(g, args) {
181    unsafe {
182        let bindings = args.arg(0).0;
183        if is_cell(bindings) && read_number(g, get(g, bindings, "length")) == 0.0 {
184            return FALSE;
185        }
186        host::throw(g, "NotSupportedError", NO_HOTKEYS)
187    }
188});
189
190crate::host_fn!(fn hotkeys_status(g, _args) {
191    let status = json!({
192        "running": false, "platform": "", "accessibilityGranted": false, "error": NO_HOTKEYS, "restarts": 0,
193    });
194    unsafe { host::to_js(g, &status) }
195});
196
197crate::host_fn!(fn hotkeys_restart(g, _args) {
198    unsafe { host::throw(g, "NotSupportedError", NO_HOTKEYS) }
199});
200
201crate::host_fn!(fn hotkeys_capture(g, _args) {
202    unsafe { host::rejected(g, "NotSupportedError", NO_HOTKEYS) }
203});
204
205crate::host_fn!(fn hotkeys_on_fired(g, _args) {
206    unsafe { make_fn(g, "off", 0, nothing) }
207});
208
209crate::host_fn!(fn tray_set(g, args) {
210    if args.arg(0).0 == NULL {
211        return UNDEF;
212    }
213    unsafe { host::throw(g, "NotSupportedError", NO_TRAY) }
214});
215
216crate::host_fn!(fn nothing(_g, _args) {
217    UNDEF
218});
219
220crate::host_fn!(fn answer_false(_g, _args) {
221    FALSE
222});
223
224unsafe fn absent(g: *mut c_void, name: &str) -> bool {
225    !is_cell(get(g, global(g), name))
226}
227
228/// Installs a stand-in for each app API object the host crates did not.
229pub unsafe fn install_missing(g: *mut c_void) {
230    let event_target = get(g, get(g, global(g), "EventTarget"), "prototype");
231    if absent(g, "__SK_PERMISSIONS__") {
232        let o = host::install_object(g, "__SK_PERMISSIONS__", event_target);
233        host::getter(g, o, "platform", permissions_platform);
234        host::getter(g, o, "names", permissions_names);
235        host::method(g, o, "query", 1, permissions_query);
236        host::method(g, o, "list", 0, permissions_list);
237        host::method(g, o, "request", 1, permissions_request);
238    }
239    if absent(g, "__SK_STORAGE__") {
240        let o = host::install_object(g, "__SK_STORAGE__", UNDEF);
241        host::getter(g, o, "kinds", storage_kinds);
242        host::getter(g, o, "folder", storage_folder);
243        host::getter(g, o, "encrypted", storage_encrypted);
244        host::method(g, o, "getUserFolder", 1, storage_get_user_folder);
245        host::method(g, o, "setStorageFolder", 1, storage_set_folder);
246        host::method(g, o, "info", 0, storage_info);
247        host::method(g, o, "flush", 0, storage_flush);
248    }
249    if absent(g, "__SK_SHELL__") {
250        let o = host::install_object(g, "__SK_SHELL__", UNDEF);
251        host::method(g, o, "openExternal", 1, shell_open_external);
252        host::method(g, o, "openPath", 1, shell_open_path);
253        host::method(g, o, "showItemInFolder", 1, shell_show_item);
254        host::method(g, o, "trashItem", 1, shell_trash_item);
255        host::method(g, o, "openContent", 1, shell_open_content);
256    }
257    if absent(g, "__SK_CAPTURE__") {
258        let o = host::install_object(g, "__SK_CAPTURE__", UNDEF);
259        host::method(g, o, "permission", 1, capture_permission);
260        host::method(g, o, "requestPermission", 1, capture_request);
261        host::method(g, o, "permissionHint", 1, capture_hint);
262        host::method(g, o, "getSources", 0, capture_sources);
263        host::method(g, o, "setPendingSource", 1, capture_pending);
264    }
265    if absent(g, "__SK_LAUNCH__") {
266        let o = host::install_object(g, "__SK_LAUNCH__", event_target);
267        host::getter(g, o, "argv", launch_list);
268        host::getter(g, o, "cwd", launch_cwd);
269        host::getter(g, o, "url", launch_url);
270        host::getter(g, o, "paths", launch_list);
271        host::getter(g, o, "singleInstance", launch_false);
272        host::method(g, o, "registerProtocol", 1, launch_register);
273        host::method(g, o, "unregisterProtocol", 1, launch_false);
274        host::method(g, o, "isProtocolRegistered", 1, launch_false);
275    }
276    if absent(g, "__sk_appHotkeys") {
277        let o = host::install_object(g, "__sk_appHotkeys", UNDEF);
278        define(g, o, "available", FALSE, 0);
279        host::method(g, o, "setBindings", 1, hotkeys_set_bindings);
280        host::method(g, o, "status", 0, hotkeys_status);
281        host::method(g, o, "requestAccessibility", 0, answer_false);
282        host::method(g, o, "restart", 0, hotkeys_restart);
283        host::method(g, o, "captureOnce", 0, hotkeys_capture);
284        host::method(g, o, "cancelCapture", 0, nothing);
285        host::method(g, o, "onFired", 1, hotkeys_on_fired);
286    }
287    if absent(g, "__sk_appTray") {
288        let o = host::install_object(g, "__sk_appTray", UNDEF);
289        define(g, o, "available", FALSE, 0);
290        host::method(g, o, "set", 1, tray_set);
291    }
292    if absent(g, "__sk_appDevtools") {
293        crate::app_devtools::install(g, None);
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use crate::testing::on_js_thread;
300    use crate::JsRuntime;
301
302    fn eval(src: &'static str) -> String {
303        on_js_thread(move || {
304            JsRuntime::with(|rt| {
305                let v = rt.ctx().eval(src).expect(src);
306                rt.ctx().drain_microtasks();
307                rt.ctx().to_rust_string(v).unwrap_or_default()
308            })
309        })
310    }
311
312    fn install() {
313        on_js_thread(|| JsRuntime::with(|rt| unsafe { super::install_missing(rt.raw()) }));
314    }
315
316    #[test]
317    fn missing_hosts_answer_without_doing_anything() {
318        install();
319        assert_eq!(
320            eval(
321                "(() => { const out = []; \
322                 const err = (f) => { try { f(); return 'none'; } catch (e) { return e.name; } }; \
323                 const h = __sk_appHotkeys, t = __sk_appTray; \
324                 out.push(h.available, h.setBindings([]), h.status().running, h.requestAccessibility(), \
325                   typeof h.onFired(() => {}), err(() => h.setBindings([{ id: 'x' }])), err(() => h.restart()), \
326                   t.available, err(() => t.set(null)), err(() => t.set({ tooltip: 'x' }))); \
327                 const p = __SK_PERMISSIONS__, s = __SK_STORAGE__, l = __SK_LAUNCH__, c = __SK_CAPTURE__; \
328                 out.push(p.query('camera'), p.list().length, p instanceof EventTarget, s.folder === '', \
329                   s.info().error, err(() => s.setStorageFolder('C:/x')), l.url, Object.isFrozen(l.argv), \
330                   err(() => l.registerProtocol('x')), c.permission('camera').state, c.setPendingSource('x')); \
331                 globalThis.rejections = []; \
332                 for (const p of [__SK_SHELL__.openExternal('https://x'), c.getSources(), h.captureOnce()]) \
333                   p.catch((e) => rejections.push(e.name + ':' + (typeof e.code === 'string' ? e.code : ''))); \
334                 return out.join('|'); })()"
335            ),
336            "false|false|false|false|function|NotSupportedError|NotSupportedError|false|none|NotSupportedError|\
337             unsupported|7|true|true|no storage host|TypeError||true|TypeError|unsupported|false"
338        );
339        assert_eq!(
340            eval("rejections.join(',')"),
341            "NotSupportedError:ENOSYS,NotSupportedError:ENOSYS,NotSupportedError:"
342        );
343    }
344}