Skip to main content

sk_app/
embed.rs

1//! Skathi as a library: another program runs the whole engine on a thread of its own and gives
2//! the app native modules (`import { … } from "native:<name>"`): typed functions, tasks and
3//! events. On macOS, AppKit owns the process main thread: use `Builder::run_on_main_thread` with
4//! an application cleanup callback instead.
5//!
6//! **One per process, once.** The JS realm cannot be torn down and gpui is one `Application`, so
7//! [`Builder::spawn`] works once; after the app closes its thread sleeps for the rest of the process.
8//!
9//! **A module function runs on the Skathi thread**, inside the JS call, so one that blocks
10//! freezes the UI: slow work is a [`Module::task`], which runs on a worker and returns a promise.
11//!
12//! The exe keeps the host command-line flags, `singleInstance`, protocol handling and ending the
13//! process. F12 opens the inspector only when [`Builder::inspector_exe`] names a sk-app.exe.
14
15use std::collections::{HashMap, VecDeque};
16use std::ffi::c_void;
17use std::path::{Path, PathBuf};
18use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
19use std::sync::{Arc, Condvar, Mutex, OnceLock};
20use std::time::Duration;
21
22use sk_runtime::redjs::api::Value;
23use sk_runtime::{host_fn, JsRuntime};
24
25pub mod bytes;
26mod host_context;
27mod marshal;
28mod module;
29#[cfg(feature = "types")]
30mod types;
31pub use bytes::Bytes;
32pub use host_context::{HostContext, HostCookie, SameSite};
33pub use module::{Declared, Function, IntoModule, Job, Module, Task, Typed};
34pub use serde;
35
36/// What `#[skathi::module]` and `#[skathi::data]` expand to; not an API.
37#[doc(hidden)]
38pub mod __private {
39    pub use super::module::private::*;
40}
41
42/// [`SurfaceInfo::dynamic_range_limit`]'s type.
43pub use sk_css::DynamicRangeLimit;
44pub use sk_tree::surface::{
45    monotonic_ns, surface, D3D11Device, D3D12Device, D3D12Fence, FrameDropReason, FrameEvent,
46    FramePrecision, FramePresent, FrameWatch, MetalDevice, MetalEvent, SharedTexture,
47    SurfaceDisplay, SurfaceError, SurfaceEvent, SurfaceFormat, SurfaceHandle, SurfaceInfo,
48    SurfaceStats, SurfaceWatch,
49};
50#[cfg(feature = "types")]
51pub use specta::{self, Type};
52
53type Setup = Box<dyn FnOnce(&HostContext) -> Result<(), String> + Send + 'static>;
54type PrepareDataDir = Box<dyn FnOnce(&Path) -> Result<(), String> + Send + 'static>;
55
56#[derive(Default)]
57struct SetupHook(Mutex<Option<Setup>>);
58
59impl SetupHook {
60    fn run(&self, context: &HostContext) -> Result<(), String> {
61        let setup = self
62            .0
63            .lock()
64            .map_err(|_| "host setup lock was poisoned".to_string())?
65            .take();
66        let Some(setup) = setup else { return Ok(()) };
67        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| setup(context)))
68            .unwrap_or_else(|_| Err("host setup panicked".into()))
69    }
70}
71
72/// The exe's own stack size (`/STACK` in build.rs), which JSC's recursion limit is sized for.
73#[cfg(not(target_os = "macos"))]
74const STACK: usize = 8 * 1024 * 1024;
75
76const DRAIN_CAP: usize = 16;
77
78pub(crate) const HOST_TYPES_FLAG: &str = "--sk-host-types";
79
80#[cfg(feature = "types")]
81fn host_types(modules: &[Module]) -> Result<String, String> {
82    types::declarations(modules)
83}
84
85#[cfg(not(feature = "types"))]
86fn host_types(modules: &[Module]) -> Result<String, String> {
87    if modules.is_empty() {
88        return Ok(String::new());
89    }
90    Err("this program was built without skathi's types feature: turn it on to type its native modules".into())
91}
92
93/// A host function: called with the [`Call`] on the Skathi thread.
94pub type Handler = Arc<dyn Fn(Call) + Send + Sync + 'static>;
95
96struct Config {
97    data_dir: Option<PathBuf>,
98    #[cfg(feature = "storages")]
99    storage_encrypted: Option<bool>,
100    visible: bool,
101    desktop_launch: bool,
102    setup: SetupHook,
103    functions: HashMap<String, Handler>,
104    modules: Vec<Module>,
105    executor: Option<module::Executor>,
106    activate: bool,
107    #[cfg_attr(not(sk_devtools), allow(dead_code))]
108    inspector_exe: Option<PathBuf>,
109    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
110    desktop_id: Option<String>,
111}
112
113static CONFIG: OnceLock<Config> = OnceLock::new();
114static STARTED: AtomicBool = AtomicBool::new(false);
115
116pub(crate) fn active() -> bool {
117    CONFIG.get().is_some()
118}
119
120/// `spawn` already prepared the desktop launch policy.
121pub(crate) fn desktop_launch_prepared() -> bool {
122    CONFIG.get().is_some_and(|config| config.desktop_launch)
123}
124
125/// Always, unless embedded with [`Builder::activate`]`(false)`.
126pub(crate) fn activates() -> bool {
127    CONFIG
128        .get()
129        .is_none_or(|c| requests_activation(c.activate, c.visible))
130}
131
132pub(crate) fn visible() -> bool {
133    CONFIG.get().is_none_or(|c| c.visible)
134}
135
136/// Seals a dormant profile's localStorage with the OS provider, no plaintext fallback.
137pub fn encrypt_local_storage_at(directory: &Path) -> Result<bool, String> {
138    #[cfg(feature = "storages")]
139    {
140        sk_storage::encrypt_local_storage_at(directory)
141    }
142    #[cfg(not(feature = "storages"))]
143    {
144        let _ = directory;
145        Err("enable the storages feature to encrypt localStorage".into())
146    }
147}
148
149#[cfg(feature = "storages")]
150pub(crate) fn storage_encrypted() -> Option<bool> {
151    CONFIG.get()?.storage_encrypted
152}
153
154pub(crate) fn data_dir() -> Option<&'static Path> {
155    CONFIG.get()?.data_dir.as_deref()
156}
157
158fn resolve_data_dir(
159    configured: Option<PathBuf>,
160    override_dir: Option<std::ffi::OsString>,
161) -> Result<Option<PathBuf>, Error> {
162    let directory = override_dir
163        .filter(|path| !path.is_empty())
164        .map(PathBuf::from)
165        .or(configured);
166    if let Some(path) = &directory {
167        if !path.is_absolute() {
168            return Err(Error::DataDirectory(format!(
169                "data directory must be absolute: {}",
170                path.display()
171            )));
172        }
173    }
174    Ok(directory)
175}
176
177fn prepare_directory(
178    directory: Option<&Path>,
179    prepare: Option<PrepareDataDir>,
180) -> Result<(), Error> {
181    let Some(directory) = directory else {
182        return if prepare.is_some() {
183            Err(Error::DataDirectory(
184                "prepare_data_dir requires a data directory".into(),
185            ))
186        } else {
187            Ok(())
188        };
189    };
190    if let Some(prepare) = prepare {
191        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| prepare(directory)))
192            .unwrap_or_else(|_| Err("data directory preparation panicked".into()))
193            .map_err(Error::DataDirectory)?;
194    }
195    std::fs::create_dir_all(directory).map_err(|error| {
196        Error::DataDirectory(format!("could not create {}: {error}", directory.display()))
197    })
198}
199
200fn requests_activation(activate: bool, visible: bool) -> bool {
201    activate && visible
202}
203
204#[cfg_attr(not(sk_devtools), allow(dead_code))]
205pub(crate) fn inspector_exe() -> Option<PathBuf> {
206    CONFIG.get()?.inspector_exe.clone()
207}
208
209#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
210pub(crate) fn desktop_id() -> Option<String> {
211    CONFIG.get()?.desktop_id.clone()
212}
213
214// A dev build has no payload loader; it only refuses one.
215#[cfg_attr(not(feature = "prod"), allow(dead_code))]
216enum PayloadSource {
217    File(PathBuf),
218    Bytes(Vec<u8>),
219    Static(&'static [u8]),
220}
221
222#[cfg(any(feature = "prod", test))]
223impl PayloadSource {
224    /// The bytes, a label, and the folder of its asset packs (`None`: the executable's).
225    fn load(self) -> Result<(crate::payload::PayloadBytes, String, Option<PathBuf>), Error> {
226        use crate::payload::PayloadBytes;
227        match self {
228            Self::File(path) => {
229                let file = crate::mapped_file::MappedFile::open(&path)
230                    .map_err(|e| Error::Payload(format!("{}: {e}", path.display())))?;
231                let dir = path.parent().map(Path::to_path_buf);
232                Ok((PayloadBytes::File(file), path.display().to_string(), dir))
233            }
234            Self::Bytes(bytes) => Ok((PayloadBytes::Owned(bytes), "bytes".into(), None)),
235            Self::Static(bytes) => Ok((PayloadBytes::Embedded(bytes), "static bytes".into(), None)),
236        }
237    }
238}
239
240/// Why [`Builder::spawn`] did not start Skathi.
241#[derive(Debug)]
242pub enum Error {
243    /// It runs once per process.
244    AlreadyStarted,
245    /// A `--features prod` build with no payload given, stamped in, or in `SK_PAYLOAD`.
246    NoPayload,
247    /// A dev build boots the dev dist and has no payload loader.
248    PayloadNeedsProd,
249    /// The payload could not be read or parsed.
250    Payload(String),
251    /// Something read this process's arguments before `spawn`.
252    ArgsAlreadyRead,
253    /// Desktop launch policy forwarded this invocation or refused a duplicate: the embedding main
254    /// should return this exit code (0 means forwarded).
255    LaunchExit(i32),
256    /// The configured profile directory could not be prepared.
257    DataDirectory(String),
258    /// A native module is misdeclared: a bad or repeated name.
259    Module(String),
260    Spawn(std::io::Error),
261    /// AppKit needs the process main thread: use `run_on_main_thread`.
262    MainThreadRequired,
263}
264
265impl std::fmt::Display for Error {
266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267        match self {
268            Error::AlreadyStarted => write!(f, "Skathi already ran in this process; it runs once"),
269            Error::NoPayload => write!(
270                f,
271                "no app: give the builder a payload (`sk publish --payload-only` writes dist/release/.sk/app.skpk)"
272            ),
273            Error::PayloadNeedsProd => {
274                write!(f, "a payload needs sk-app's `prod` feature; a dev build boots the dev dist instead")
275            }
276            Error::Payload(e) => write!(f, "{e}"),
277            Error::ArgsAlreadyRead => write!(f, "Skathi's arguments were read before spawn"),
278            Error::LaunchExit(code) => write!(f, "desktop launch finished with exit code {code}"),
279            Error::DataDirectory(e) => write!(f, "data directory: {e}"),
280            Error::Module(e) => write!(f, "{e}"),
281            Error::Spawn(e) => write!(f, "the Skathi thread did not start: {e}"),
282            Error::MainThreadRequired => write!(f, "AppKit requires the process main thread; call Builder::run_on_main_thread from main"),
283        }
284    }
285}
286
287impl std::error::Error for Error {}
288
289/// Configures and starts an embedded Skathi.
290///
291/// ```no_run
292/// let ui = sk_app::embed::Builder::new()
293///     .payload_file("apps/hello/dist/release/.sk/app.skpk")
294///     .module("db", |m: &mut sk_app::embed::Module| {
295///         m.task("query", |sql: String| -> Result<Vec<String>, String> { Ok(vec![sql]) });
296///         m.event::<bool>("online");
297///     })
298///     .spawn()?;
299/// ui.emit_to("db", "online", &true)?;
300/// let exit = ui.wait();
301/// # Ok::<(), Box<dyn std::error::Error>>(())
302/// ```
303pub struct Builder {
304    data_dir: Option<PathBuf>,
305    storage_encrypted: Option<bool>,
306    prepare_data_dir: Option<PrepareDataDir>,
307    visible: bool,
308    desktop_launch: bool,
309    setup: Option<Setup>,
310    payload: Option<PayloadSource>,
311    args: Vec<String>,
312    functions: HashMap<String, Handler>,
313    modules: Vec<Module>,
314    executor: Option<module::Executor>,
315    activate: bool,
316    inspector_exe: Option<PathBuf>,
317    desktop_id: Option<String>,
318}
319
320impl Default for Builder {
321    fn default() -> Self {
322        Self::new()
323    }
324}
325
326impl Builder {
327    pub fn new() -> Self {
328        Builder {
329            data_dir: None,
330            storage_encrypted: None,
331            prepare_data_dir: None,
332            visible: true,
333            desktop_launch: false,
334            setup: None,
335            payload: None,
336            args: Vec::new(),
337            functions: HashMap::new(),
338            modules: Vec::new(),
339            executor: None,
340            activate: true,
341            inspector_exe: None,
342            desktop_id: None,
343        }
344    }
345
346    /// Sets the persistent profile root, before storage and cookies load. HTTP and bytecode caches
347    /// live in its `cache/http` and `cache/jsc`. `SK_DATA_DIR` overrides it. Must be absolute.
348    pub fn data_dir(mut self, directory: impl Into<PathBuf>) -> Self {
349        self.data_dir = Some(directory.into());
350        self
351    }
352
353    /// Sets storage encryption before any cookie, database or app code runs. `true` requires an OS
354    /// provider and seals existing plaintext localStorage before boot.
355    pub fn storage_encrypted(mut self, encrypted: bool) -> Self {
356        self.storage_encrypted = Some(encrypted);
357        self
358    }
359
360    /// Prepares or migrates the profile after single-instance handling, before any storage or VM
361    /// initialization. An error or panic stops startup.
362    pub fn prepare_data_dir<F>(mut self, prepare: F) -> Self
363    where
364        F: FnOnce(&Path) -> Result<(), String> + Send + 'static,
365    {
366        self.prepare_data_dir = Some(Box::new(prepare));
367        self
368    }
369
370    /// Lets this binary own the payload's single-instance and protocol policy, using the real command
371    /// line (a deep link's raw URL included). A forwarded launch returns `Error::LaunchExit(0)`.
372    pub fn desktop_launch(mut self, enabled: bool) -> Self {
373        self.desktop_launch = enabled;
374        self
375    }
376
377    /// Runs once on the Skathi thread after storage install, before any app JS or window. An
378    /// error or panic prevents startup. Keep it short.
379    pub fn setup<F>(mut self, setup: F) -> Self
380    where
381        F: FnOnce(&HostContext) -> Result<(), String> + Send + 'static,
382    {
383        self.setup = Some(Box::new(setup));
384        self
385    }
386
387    /// The `.skpk` file `sk build` writes (`--features prod` only), mapped read-only for the app's
388    /// lifetime: replace it atomically, never modify it in place.
389    pub fn payload_file(mut self, path: impl Into<PathBuf>) -> Self {
390        self.payload = Some(PayloadSource::File(path.into()));
391        self
392    }
393
394    /// Owned `.skpk` bytes. Prefer [`Self::payload_static`] for `include_bytes!`.
395    pub fn payload_bytes(mut self, bytes: impl Into<Vec<u8>>) -> Self {
396        self.payload = Some(PayloadSource::Bytes(bytes.into()));
397        self
398    }
399
400    /// A static `.skpk`, borrowed without copying.
401    pub fn payload_static(mut self, bytes: &'static [u8]) -> Self {
402        self.payload = Some(PayloadSource::Static(bytes));
403        self
404    }
405
406    /// `appLaunch.argv` after the exe; none of it is read as a host flag.
407    pub fn args<I, S>(mut self, args: I) -> Self
408    where
409        I: IntoIterator<Item = S>,
410        S: Into<String>,
411    {
412        self.args = args.into_iter().map(Into::into).collect();
413        self
414    }
415
416    /// A native module the app imports as `native:<name>`: a value of a `#[skathi::module]` type,
417    /// or a closure `|m: &mut Module| …` that registers its functions, tasks and events.
418    pub fn module(mut self, name: impl Into<String>, exports: impl IntoModule) -> Self {
419        let mut module = Module::new(name.into());
420        exports.register(&mut module);
421        self.modules.push(module);
422        self
423    }
424
425    /// Runs module tasks on the embedder's own executor (a tokio or rayon pool) instead of
426    /// Skathi's four worker threads. A job it drops unrun rejects its promise.
427    pub fn task_executor<F>(mut self, executor: F) -> Self
428    where
429        F: Fn(Job) + Send + Sync + 'static,
430    {
431        self.executor = Some(Arc::new(executor));
432        self
433    }
434
435    /// A function the app calls as `appHost.call(name, ...args)`; the handler gets the arguments
436    /// as a JSON array and answers through the [`Call`].
437    #[deprecated(
438        since = "0.4.0",
439        note = "use native modules: `Builder::module` and `import { … } from \"native:<name>\"`"
440    )]
441    pub fn function<F>(mut self, name: impl Into<String>, handler: F) -> Self
442    where
443        F: Fn(Call) + Send + Sync + 'static,
444    {
445        self.functions.insert(name.into(), Arc::new(handler));
446        self
447    }
448
449    /// Whether the primary window is shown at startup (default true). Hidden apps still boot JS and
450    /// pump background work, and do not activate or raise an already running instance.
451    pub fn visible(mut self, visible: bool) -> Self {
452        self.visible = visible;
453        self
454    }
455
456    /// Whether the app's window takes the foreground when it opens (default `true`).
457    pub fn activate(mut self, on: bool) -> Self {
458        self.activate = on;
459        self
460    }
461
462    /// A sk-app.exe of this Skathi version, started as the inspector on F12 and
463    /// `appDevtools.open()`. Without it they say why nothing opened; the devtools protocol works either way.
464    pub fn inspector_exe(mut self, path: impl Into<PathBuf>) -> Self {
465        self.inspector_exe = Some(path.into());
466        self
467    }
468
469    /// The app's desktop entry id on Linux (`gl.example.App`): the Wayland app id and X11 class of
470    /// its windows, which the desktop matches to the entry's icon and dock slot. Ignored elsewhere.
471    pub fn desktop_id(mut self, id: impl Into<String>) -> Self {
472        self.desktop_id = Some(id.into());
473        self
474    }
475
476    /// Starts Skathi on a thread of its own and returns at once; events emitted before the app
477    /// is ready wait for it. On macOS this returns `Error::MainThreadRequired`: use
478    /// `Self::run_on_main_thread` instead.
479    pub fn spawn(self) -> Result<Handle, Error> {
480        self.answer_host_types();
481        #[cfg(target_os = "macos")]
482        {
483            Err(Error::MainThreadRequired)
484        }
485        #[cfg(not(target_os = "macos"))]
486        {
487            let handle = self.prepare()?;
488            std::thread::Builder::new()
489                .name("skathi".into())
490                .stack_size(STACK)
491                .spawn(run_thread)
492                .map_err(Error::Spawn)?;
493            Ok(handle)
494        }
495    }
496
497    /// Runs AppKit and JSC on the process main thread until the app closes, then owns the rest of the
498    /// process: the cleanup callback runs on a separate lifecycle thread after shutdown hooks (or the
499    /// deadline), should stop workers and flush logs, and returns the exit code. A panic in it exits
500    /// with code 1. Startup validation errors return normally; calls from a background thread fail
501    /// before consuming the one-run state.
502    #[cfg(target_os = "macos")]
503    pub fn run_on_main_thread<F>(self, on_exit: F) -> Result<(), Error>
504    where
505        F: FnOnce(Exit) -> i32 + Send + 'static,
506    {
507        self.answer_host_types();
508        require_main_thread()?;
509        let handle = self.prepare()?;
510        std::thread::Builder::new()
511            .name("skathi-lifecycle".into())
512            .spawn(move || {
513                let exit = handle.wait();
514                let code = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| on_exit(exit)))
515                    .unwrap_or_else(|_| {
516                        eprintln!("[embed] the application shutdown callback panicked");
517                        1
518                    });
519                std::process::exit(code);
520            })
521            .map_err(Error::Spawn)?;
522        run_thread();
523        Ok(())
524    }
525
526    /// `<exe> --sk-host-types` (what `sk types` and `sk dev --exe` run): prints the modules'
527    /// declarations and ends the process before anything starts.
528    fn answer_host_types(&self) {
529        if std::env::args_os()
530            .nth(1)
531            .is_none_or(|a| a != HOST_TYPES_FLAG)
532        {
533            return;
534        }
535        let result = self
536            .module_problem()
537            .map_or_else(|| host_types(&self.modules), Err);
538        match result {
539            Ok(text) => {
540                print!("{text}");
541                std::process::exit(0);
542            }
543            Err(e) => {
544                eprintln!("{e}");
545                std::process::exit(1);
546            }
547        }
548    }
549
550    fn module_problem(&self) -> Option<String> {
551        for (i, m) in self.modules.iter().enumerate() {
552            if let Some(problem) = m.problem() {
553                return Some(problem.to_owned());
554            }
555            if self.modules[..i].iter().any(|other| other.name == m.name) {
556                return Some(format!("native:{} is registered twice", m.name));
557            }
558        }
559        None
560    }
561
562    fn prepare(mut self) -> Result<Handle, Error> {
563        if let Some(problem) = self.module_problem() {
564            return Err(Error::Module(problem));
565        }
566        let data_dir = resolve_data_dir(self.data_dir.take(), std::env::var_os("SK_DATA_DIR"))?;
567        #[cfg(not(feature = "storages"))]
568        if self.storage_encrypted.is_some() {
569            return Err(Error::DataDirectory(
570                "storage_encrypted requires the storages feature".into(),
571            ));
572        }
573        if STARTED.swap(true, Ordering::SeqCst) {
574            return Err(Error::AlreadyStarted);
575        }
576        if let Err(e) = self.load_payload() {
577            STARTED.store(false, Ordering::SeqCst);
578            return Err(e);
579        }
580        if self.desktop_launch {
581            // Preserve GetCommandLineW protocol recovery; rejoining Builder.args
582            // would corrupt quotes and repeated spaces inside a deep link.
583            let args = sk_desktop::args::process();
584            let launch = crate::boot_mode::launch_config();
585            if let sk_desktop::launch::Outcome::Exit(code) =
586                sk_desktop::launch::start_with_activation(
587                    args,
588                    launch.as_deref(),
589                    crate::boot_mode::app_name(),
590                    None,
591                    requests_activation(self.activate, self.visible),
592                )
593            {
594                return Err(Error::LaunchExit(code));
595            }
596            sk_desktop::launch::register_declared();
597        } else {
598            let exe = std::env::current_exe()
599                .map(|p| p.to_string_lossy().into_owned())
600                .unwrap_or_default();
601            if !sk_desktop::args::set_embedded(exe, self.args) {
602                return Err(Error::ArgsAlreadyRead);
603            }
604        }
605        prepare_directory(data_dir.as_deref(), self.prepare_data_dir.take())?;
606        let config = Config {
607            data_dir,
608            #[cfg(feature = "storages")]
609            storage_encrypted: self.storage_encrypted,
610            visible: self.visible,
611            desktop_launch: self.desktop_launch,
612            setup: SetupHook(Mutex::new(self.setup)),
613            functions: self.functions,
614            modules: self.modules,
615            executor: self.executor,
616            activate: self.activate,
617            inspector_exe: self.inspector_exe,
618            desktop_id: self.desktop_id,
619        };
620        if CONFIG.set(config).is_err() {
621            return Err(Error::AlreadyStarted);
622        }
623        Ok(Handle { _private: () })
624    }
625
626    #[cfg(feature = "prod")]
627    fn load_payload(&mut self) -> Result<(), Error> {
628        let Some(source) = self.payload.take() else {
629            return if crate::payload::get().is_some() {
630                Ok(())
631            } else {
632                Err(Error::NoPayload)
633            };
634        };
635        let (bytes, label, dir) = source.load()?;
636        crate::payload::set_external(bytes, label, dir.as_deref()).map_err(Error::Payload)
637    }
638
639    #[cfg(not(feature = "prod"))]
640    fn load_payload(&self) -> Result<(), Error> {
641        match self.payload {
642            Some(_) => Err(Error::PayloadNeedsProd),
643            None => Ok(()),
644        }
645    }
646}
647
648#[cfg(target_os = "macos")]
649fn require_main_thread() -> Result<(), Error> {
650    unsafe extern "C" {
651        fn pthread_main_np() -> std::ffi::c_int;
652    }
653    if unsafe { pthread_main_np() } == 0 {
654        Err(Error::MainThreadRequired)
655    } else {
656        Ok(())
657    }
658}
659
660fn run_thread() {
661    // `run_embedded` ends in `shutdown::finish`, which never returns; only a panic out of gpui's
662    // loop gets past it. The thread must not end even then (its thread-locals are the JS realm).
663    if let Err(p) = std::panic::catch_unwind(crate::run_embedded) {
664        let why = p
665            .downcast_ref::<&str>()
666            .map(|s| s.to_string())
667            .or_else(|| p.downcast_ref::<String>().cloned())
668            .unwrap_or_else(|| "a panic".into());
669        eprintln!("[embed] the Skathi thread panicked: {why}");
670        finished(false, format!("panicked: {why}"));
671    }
672    loop {
673        std::thread::park();
674    }
675}
676
677/// How the app ended.
678#[derive(Debug, Clone)]
679pub struct Exit {
680    /// `false` when the teardown ran past its deadline or the Skathi thread panicked.
681    pub clean: bool,
682    /// What closed it and how long each teardown step took (the exe's `[shutdown]` line).
683    pub summary: String,
684}
685
686static EXIT: Mutex<Option<Exit>> = Mutex::new(None);
687static EXIT_CV: Condvar = Condvar::new();
688static CLOSE: AtomicBool = AtomicBool::new(false);
689static SHOW: AtomicBool = AtomicBool::new(false);
690
691/// The first report wins.
692pub(crate) fn finished(clean: bool, summary: String) {
693    let Ok(mut exit) = EXIT.lock() else { return };
694    if exit.is_none() {
695        *exit = Some(Exit { clean, summary });
696        EXIT_CV.notify_all();
697    }
698}
699
700/// Why [`Handle::emit_to`] did not queue an event.
701#[derive(Debug, PartialEq, Eq)]
702pub enum EmitError {
703    /// `data` is not one JSON value.
704    NotJson,
705    /// The app has closed.
706    Closed,
707    /// No module of that name declared that event with `Module::event`.
708    NotDeclared,
709}
710
711impl std::fmt::Display for EmitError {
712    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713        match self {
714            EmitError::NotJson => write!(f, "the event's data is not JSON"),
715            EmitError::Closed => write!(f, "the app has closed"),
716            EmitError::NotDeclared => write!(
717                f,
718                "no native module declares that event: declare it with Module::event"
719            ),
720        }
721    }
722}
723
724impl std::error::Error for EmitError {}
725
726/// The embedder's side of a running Skathi. Cheap to clone; every method works from any thread.
727#[derive(Clone)]
728pub struct Handle {
729    _private: (),
730}
731
732impl Handle {
733    /// Delivers `data` to the `on(event)` handlers of `native:<module>` in the app's next frame.
734    /// The event must be declared with [`Module::event`].
735    pub fn emit_to<T: serde::Serialize + ?Sized>(
736        &self,
737        module: &str,
738        event: &str,
739        data: &T,
740    ) -> Result<(), EmitError> {
741        if self.is_closed() {
742            return Err(EmitError::Closed);
743        }
744        let Some((module, event)) = CONFIG.get().and_then(|c| {
745            let m = c.modules.iter().find(|m| m.name == module)?;
746            Some((m.name.as_str(), m.declared(event)?))
747        }) else {
748            return Err(EmitError::NotDeclared);
749        };
750        let data = module::event_data(data).ok_or(EmitError::NotJson)?;
751        module::emit(module, event, data);
752        Ok(())
753    }
754
755    /// Delivers `data` (one JSON value) to `appHost.on(event)` handlers in the app's next frame.
756    #[deprecated(
757        since = "0.4.0",
758        note = "declare the event on a native module and send it with `Handle::emit_to`"
759    )]
760    pub fn emit(&self, event: &str, data: &str) -> Result<(), EmitError> {
761        if self.is_closed() {
762            return Err(EmitError::Closed);
763        }
764        if crate::json::parse(data).is_none() {
765            return Err(EmitError::NotJson);
766        }
767        let json = format!(
768            "{{\"event\":{},\"data\":{data}}}",
769            crate::json::quote(event)
770        );
771        push(Item::Event { json });
772        Ok(())
773    }
774
775    /// Queues a show/activation on the UI thread, including the first show of an initially hidden
776    /// window. Returns whether it was accepted.
777    pub fn show(&self) -> bool {
778        if self.is_closed() || crate::shutdown::is_closing() || CLOSE.load(Ordering::Acquire) {
779            return false;
780        }
781        SHOW.store(true, Ordering::Release);
782        wake();
783        true
784    }
785
786    /// Closes the app as `appWindow.close()` does: the windows go at once, the teardown runs behind them.
787    pub fn close(&self) {
788        CLOSE.store(true, Ordering::Release);
789        wake();
790    }
791
792    pub fn is_closed(&self) -> bool {
793        EXIT.lock().is_ok_and(|e| e.is_some())
794    }
795
796    pub fn wait(&self) -> Exit {
797        let mut exit = EXIT.lock().unwrap_or_else(|p| p.into_inner());
798        loop {
799            if let Some(e) = exit.as_ref() {
800                return e.clone();
801            }
802            exit = EXIT_CV.wait(exit).unwrap_or_else(|p| p.into_inner());
803        }
804    }
805
806    /// [`Handle::wait`], for at most `timeout`.
807    pub fn wait_timeout(&self, timeout: Duration) -> Option<Exit> {
808        let exit = EXIT.lock().unwrap_or_else(|p| p.into_inner());
809        let (exit, _) = EXIT_CV
810            .wait_timeout_while(exit, timeout, |e| e.is_none())
811            .unwrap_or_else(|p| p.into_inner());
812        exit.clone()
813    }
814}
815
816/// One `appHost.call(name, ...args)`.
817pub struct Call {
818    name: String,
819    args: String,
820    reply: Reply,
821}
822
823impl Call {
824    pub fn name(&self) -> &str {
825        &self.name
826    }
827
828    /// One JSON array.
829    pub fn args(&self) -> &str {
830        &self.args
831    }
832
833    /// Resolves the call's promise with `json` (one JSON value).
834    pub fn resolve(self, json: impl Into<String>) {
835        self.reply.resolve(json)
836    }
837
838    /// Rejects the call's promise with an `AppHostError` saying `message`.
839    pub fn reject(self, message: impl Into<String>) {
840        self.reply.reject(message)
841    }
842
843    pub fn into_reply(self) -> Reply {
844        self.reply
845    }
846}
847
848/// Settles one call's promise, from any thread. Dropped unanswered, it rejects, so a promise never hangs.
849pub struct Reply {
850    token: u32,
851    settled: bool,
852}
853
854impl Reply {
855    /// Resolves with `json` (one JSON value); text that is not JSON rejects.
856    pub fn resolve(mut self, json: impl Into<String>) {
857        self.settled = true;
858        let json = json.into();
859        if crate::json::parse(&json).is_some() {
860            push(Item::Settle {
861                token: self.token,
862                ok: true,
863                text: json,
864            });
865        } else {
866            push(Item::Settle {
867                token: self.token,
868                ok: false,
869                text: "the host answered with text that is not JSON".into(),
870            });
871        }
872    }
873
874    pub fn reject(mut self, message: impl Into<String>) {
875        self.settled = true;
876        push(Item::Settle {
877            token: self.token,
878            ok: false,
879            text: message.into(),
880        });
881    }
882}
883
884impl Drop for Reply {
885    fn drop(&mut self) {
886        if self.settled {
887            return;
888        }
889        let why = if std::thread::panicking() {
890            "the host function panicked"
891        } else {
892            "the host dropped this call without answering"
893        };
894        push(Item::Settle {
895            token: self.token,
896            ok: false,
897            text: why.into(),
898        });
899    }
900}
901
902enum Item {
903    Settle { token: u32, ok: bool, text: String },
904    Event { json: String },
905}
906
907static QUEUE: Mutex<VecDeque<Item>> = Mutex::new(VecDeque::new());
908static QUEUED: AtomicUsize = AtomicUsize::new(0);
909/// Calls made and not yet settled: the event loop's in-flight work.
910static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0);
911static NEXT_TOKEN: AtomicU32 = AtomicU32::new(1);
912static RT_G: AtomicUsize = AtomicUsize::new(0);
913static RT_ID: AtomicU64 = AtomicU64::new(0);
914
915thread_local! {
916    static DISPATCHER: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
917}
918
919fn push(item: Item) {
920    if let Ok(mut q) = QUEUE.lock() {
921        q.push_back(item);
922        QUEUED.fetch_add(1, Ordering::AcqRel);
923    }
924    wake();
925}
926
927fn wake() {
928    let id = RT_ID.load(Ordering::Acquire);
929    if id != 0 {
930        sk_runtime::redjs::web::wake(sk_runtime::redjs::context::ContextId(id));
931    }
932    sk_runtime::frames::wake();
933    crate::background::prompt();
934}
935
936/// A call's answer, a module task's result or a native event is waiting for JS.
937pub(crate) fn queued() -> bool {
938    QUEUED.load(Ordering::Acquire) != 0 || module::queued()
939}
940
941fn is_ours(g: *mut c_void) -> bool {
942    !g.is_null() && g as usize == RT_G.load(Ordering::Acquire)
943}
944
945unsafe fn src_inflight(g: *mut c_void) -> bool {
946    is_ours(g) && IN_FLIGHT.load(Ordering::Acquire) != 0
947}
948
949unsafe fn src_ready(g: *mut c_void) -> bool {
950    is_ours(g) && QUEUED.load(Ordering::Acquire) != 0 && DISPATCHER.with(|d| d.get()) != 0
951}
952
953unsafe fn src_drain(g: *mut c_void) -> usize {
954    if !unsafe { src_ready(g) } {
955        return 0;
956    }
957    let budget = Duration::from_micros(sk_runtime::redjs::web::pump_budget_us() as u64);
958    let start = std::time::Instant::now();
959    let mut n = 0;
960    while n < DRAIN_CAP {
961        let Some(item) = QUEUE.lock().ok().and_then(|mut q| q.pop_front()) else {
962            break;
963        };
964        QUEUED.fetch_sub(1, Ordering::AcqRel);
965        match item {
966            Item::Settle { token, ok, text } => {
967                IN_FLIGHT.fetch_sub(1, Ordering::AcqRel);
968                deliver(token, ok, &text);
969            }
970            Item::Event { json } => deliver(0, true, &json),
971        }
972        n += 1;
973        if start.elapsed() >= budget {
974            break;
975        }
976    }
977    n
978}
979
980fn deliver(token: u32, ok: bool, text: &str) {
981    let dispatcher = DISPATCHER.with(|d| d.get());
982    if dispatcher == 0 {
983        return;
984    }
985    JsRuntime::with(|rt| {
986        let a = [
987            Value::number(f64::from(token)),
988            Value::boolean(ok),
989            rt.ctx().string(text),
990        ];
991        if let Err(sk_runtime::redjs::api::Error::Exception(e)) =
992            rt.ctx().call(Value(dispatcher), Value::undefined(), &a)
993        {
994            let err = rt.describe(e);
995            eprintln!("[appHost dispatch] {}\n{}", err.header, err.stack);
996        }
997    });
998}
999
1000pub(crate) fn setup(runtime: &JsRuntime) -> Result<(), String> {
1001    let Some(config) = CONFIG.get() else {
1002        return Ok(());
1003    };
1004    config.setup.run(&HostContext::installed(Some(runtime)))
1005}
1006
1007/// Dock click with no window visible (`applicationShouldHandleReopen:`): as [`Handle::show`].
1008#[cfg(target_os = "macos")]
1009pub(crate) fn reopen() {
1010    let _accepted = Handle { _private: () }.show();
1011}
1012
1013/// Applies a show or close the embedder asked for, from the frame's JS wave.
1014pub(crate) fn pump() {
1015    let show = SHOW.swap(false, Ordering::AcqRel);
1016    if CLOSE.swap(false, Ordering::AcqRel) {
1017        sk_tree::log::record("embed", "[embed] the embedder closed the app");
1018        crate::window::request_close();
1019    } else if show && !crate::shutdown::is_closing() {
1020        crate::window::request_activate();
1021    }
1022}
1023
1024host_fn!(fn sk_host_set_dispatcher(g, args) {
1025    let f = args.arg(0);
1026    unsafe { sk_runtime::redjs::ffi::redjs_protect(g, f.0) };
1027    let old = DISPATCHER.with(|d| d.replace(f.0));
1028    if old != 0 {
1029        unsafe { sk_runtime::redjs::ffi::redjs_unprotect(g, old) };
1030    }
1031    wake();
1032    Value::undefined().0
1033});
1034
1035// Returns a token, 0 for a name the embedder did not register (the shim rejects with the list it did).
1036host_fn!(fn sk_host_call(g, args) {
1037    let name = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }.unwrap_or_default();
1038    let call_args = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(1).0) }
1039        .filter(|a| crate::json::parse(a).is_some())
1040        .unwrap_or_else(|| "[]".into());
1041    let Some(handler) = CONFIG.get().and_then(|c| c.functions.get(&name)).cloned() else {
1042        return Value::number(0.0).0;
1043    };
1044    let token = loop {
1045        let t = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed);
1046        if t != 0 {
1047            break t;
1048        }
1049    };
1050    IN_FLIGHT.fetch_add(1, Ordering::AcqRel);
1051    let call = Call { name, args: call_args, reply: Reply { token, settled: false } };
1052    // A panic in the embedder's code rejects this call (via Reply's drop) rather than poisoning the runtime.
1053    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(call))).is_err() {
1054        eprintln!("[embed] the host function behind appHost.call panicked");
1055    }
1056    Value::number(f64::from(token)).0
1057});
1058
1059host_fn!(fn sk_host_functions(_g, _args) {
1060    let mut names: Vec<&String> = CONFIG.get().map(|c| c.functions.keys().collect()).unwrap_or_default();
1061    names.sort();
1062    let json = crate::json::Json::arr(names.into_iter().map(|n| crate::json::Json::s(n.as_str())).collect()).to_json();
1063    JsRuntime::with(|rt| rt.ctx().string(&json)).0
1064});
1065
1066/// Embedded only: in the exe `__sk_host_*` do not exist and `appHost.available` is `false`.
1067pub(crate) fn install(rt: &JsRuntime) {
1068    if !active() {
1069        return;
1070    }
1071    rt.register(
1072        "__sk_host_set_dispatcher",
1073        1,
1074        sk_host_set_dispatcher as *const _,
1075    );
1076    rt.register("__sk_host_call", 2, sk_host_call as *const _);
1077    rt.register("__sk_host_functions", 0, sk_host_functions as *const _);
1078    let g = rt.raw();
1079    RT_G.store(g as usize, Ordering::Release);
1080    if let Some(id) = sk_runtime::redjs::context::id_of(g) {
1081        RT_ID.store(id.0, Ordering::Release);
1082        let _ = sk_runtime::redjs::web::waker(id);
1083    }
1084    sk_runtime::redjs::web::register_pump_source(sk_runtime::redjs::web::PumpSource {
1085        inflight: src_inflight,
1086        ready: src_ready,
1087        drain: src_drain,
1088    });
1089    if let Some(config) = CONFIG.get() {
1090        if let Err(e) = module::install(rt.ctx(), &config.modules, config.executor.clone()) {
1091            eprintln!("[embed] the native modules could not be installed: {e}");
1092        }
1093    }
1094}
1095
1096#[cfg(test)]
1097mod tests {
1098    use super::*;
1099
1100    fn drain_queue() -> Vec<(u32, bool, String)> {
1101        let mut q = QUEUE.lock().unwrap();
1102        let out = q
1103            .drain(..)
1104            .map(|i| match i {
1105                Item::Settle { token, ok, text } => (token, ok, text),
1106                Item::Event { json } => (0, true, json),
1107            })
1108            .collect();
1109        QUEUED.store(0, Ordering::Release);
1110        out
1111    }
1112
1113    #[test]
1114    fn payload_source_moves_builder_bytes_and_maps_files_without_cloning() {
1115        let bytes = vec![1, 2, 3, 4];
1116        let pointer = bytes.as_ptr();
1117        let mut builder = Builder::new().payload_bytes(bytes);
1118        let (owned, _, _) = builder.payload.take().unwrap().load().unwrap();
1119        let crate::payload::PayloadBytes::Owned(owned) = owned else {
1120            panic!("owned bytes expected")
1121        };
1122        assert_eq!(owned.as_ptr(), pointer);
1123        assert!(builder.payload.is_none());
1124        static STATIC_PAYLOAD: &[u8] = b"static payload bytes";
1125        let mut builder = Builder::new().payload_static(STATIC_PAYLOAD);
1126        let (borrowed, _, _) = builder.payload.take().unwrap().load().unwrap();
1127        let crate::payload::PayloadBytes::Embedded(borrowed) = borrowed else {
1128            panic!("static bytes expected")
1129        };
1130        assert_eq!(borrowed.as_ptr(), STATIC_PAYLOAD.as_ptr());
1131        assert_eq!(borrowed.len(), STATIC_PAYLOAD.len());
1132        let mut files = crate::mapped_file::tests::Files::new();
1133        let path = files.write("app.skpk", b"file bytes");
1134        let mut builder = Builder::new().payload_file(&path);
1135        let (mapped, _, dir) = builder.payload.take().unwrap().load().unwrap();
1136        let crate::payload::PayloadBytes::File(mapped) = mapped else {
1137            panic!("mapped file expected")
1138        };
1139        assert_eq!(mapped.as_bytes(), b"file bytes");
1140        assert_eq!(dir.as_deref(), path.parent());
1141        assert!(builder.payload.is_none());
1142        #[cfg(target_os = "windows")]
1143        assert!(std::fs::OpenOptions::new().write(true).open(&path).is_err());
1144        drop(mapped);
1145        std::fs::write(&path, b"released").unwrap();
1146    }
1147
1148    #[test]
1149    fn data_directory_override_and_preparation_precede_storage() {
1150        let base = std::env::temp_dir().join(format!(
1151            "sk-data-dir-{}-{}",
1152            std::process::id(),
1153            std::time::SystemTime::now()
1154                .duration_since(std::time::UNIX_EPOCH)
1155                .unwrap()
1156                .as_nanos()
1157        ));
1158        let configured = base.join("configured");
1159        let overridden = base.join("override");
1160        assert_eq!(
1161            resolve_data_dir(
1162                Some(configured.clone()),
1163                Some(overridden.clone().into_os_string())
1164            )
1165            .unwrap(),
1166            Some(overridden)
1167        );
1168        assert_eq!(
1169            resolve_data_dir(Some(configured.clone()), Some("".into())).unwrap(),
1170            Some(configured.clone())
1171        );
1172        assert_eq!(resolve_data_dir(None, None).unwrap(), None);
1173        assert!(resolve_data_dir(Some(PathBuf::from("relative")), None).is_err());
1174        assert!(prepare_directory(None, Some(Box::new(|_| Ok(())))).is_err());
1175        let refused = base.join("refused");
1176        assert!(prepare_directory(
1177            Some(&refused),
1178            Some(Box::new(|_| Err("migration refused".into())))
1179        )
1180        .is_err());
1181        assert!(!refused.exists());
1182        prepare_directory(
1183            Some(&configured),
1184            Some(Box::new(|path| {
1185                assert!(!path.exists());
1186                std::fs::create_dir_all(path).map_err(|e| e.to_string())?;
1187                std::fs::write(path.join("prepared"), "profile").map_err(|e| e.to_string())
1188            })),
1189        )
1190        .unwrap();
1191        assert_eq!(
1192            std::fs::read_to_string(configured.join("prepared")).unwrap(),
1193            "profile"
1194        );
1195        std::fs::remove_file(configured.join("prepared")).unwrap();
1196        std::fs::remove_dir(configured).unwrap();
1197        std::fs::remove_dir(base).unwrap();
1198    }
1199
1200    #[cfg(target_os = "macos")]
1201    #[test]
1202    fn appkit_rejects_worker_entry_before_startup_state_changes() {
1203        std::thread::spawn(|| {
1204            assert!(matches!(
1205                require_main_thread(),
1206                Err(Error::MainThreadRequired)
1207            ));
1208            assert!(matches!(
1209                Builder::new().spawn(),
1210                Err(Error::MainThreadRequired)
1211            ));
1212            assert!(matches!(
1213                Builder::new().run_on_main_thread(|_| 0),
1214                Err(Error::MainThreadRequired)
1215            ));
1216        })
1217        .join()
1218        .unwrap();
1219    }
1220
1221    #[test]
1222    fn setup_receives_installed_context_once_and_propagates_failure() {
1223        let called = Arc::new(AtomicUsize::new(0));
1224        let observed = called.clone();
1225        let hook = SetupHook(Mutex::new(Some(Box::new(move |ctx| {
1226            assert_eq!(
1227                ctx.storage_dir().ok(),
1228                HostContext::installed(None).storage_dir().ok()
1229            );
1230            observed.fetch_add(1, Ordering::SeqCst);
1231            Err("bootstrap refused".into())
1232        }))));
1233        assert_eq!(
1234            hook.run(&HostContext::installed(None)),
1235            Err("bootstrap refused".into())
1236        );
1237        assert!(hook.run(&HostContext::installed(None)).is_ok());
1238        assert_eq!(called.load(Ordering::SeqCst), 1);
1239        let panic = SetupHook(Mutex::new(Some(Box::new(|_| panic!("plugin panic")))));
1240        assert!(panic.run(&HostContext::installed(None)).is_err());
1241    }
1242
1243    // One test, because the queue is the process's.
1244    #[test]
1245    #[allow(deprecated)]
1246    fn replies_settle_once_and_a_dropped_one_rejects() {
1247        drain_queue();
1248        Reply {
1249            token: 7,
1250            settled: false,
1251        }
1252        .resolve(r#"{"a":1}"#);
1253        Reply {
1254            token: 8,
1255            settled: false,
1256        }
1257        .resolve("not json");
1258        Reply {
1259            token: 9,
1260            settled: false,
1261        }
1262        .reject("nope");
1263        drop(Reply {
1264            token: 10,
1265            settled: false,
1266        });
1267        let got = drain_queue();
1268        assert_eq!(got[0], (7, true, r#"{"a":1}"#.to_string()));
1269        assert_eq!(got[1].0, 8);
1270        assert!(!got[1].1);
1271        assert_eq!(got[2], (9, false, "nope".to_string()));
1272        assert_eq!(got[3].0, 10);
1273        assert!(!got[3].1);
1274
1275        let h = Handle { _private: () };
1276        assert_eq!(h.emit("x", "{bad"), Err(EmitError::NotJson));
1277        h.emit("status", r#"{"online":true}"#).unwrap();
1278        assert_eq!(
1279            drain_queue()[0].2,
1280            r#"{"event":"status","data":{"online":true}}"#
1281        );
1282    }
1283}