Skip to main content

nsh_core/
single_instance.rs

1//! One instance of the app (`nsh.json` `"singleInstance": true`, desktops):
2//! a second launch of the app hands its command line to the running
3//! instance and exits before it opens a window or starts an engine.
4//!
5//! The release runner checks for a running instance as it starts, keyed on
6//! the app's id (Windows: a named mutex and `WM_COPYDATA`; Linux:
7//! GApplication's D-Bus uniqueness). The running instance's platform
8//! reports the launch as the root's
9//! [`EventKind::SecondInstance`](crate::EventKind::SecondInstance); the
10//! core holds launches until the app listens
11//! ([`crate::element::next_second_instance`]), at most [`MAX_PENDING`]. The
12//! running instance's main window is brought forward; what else the launch
13//! means (a path on the command line, say) is the app's.
14//!
15//! macOS runs one instance of an app bundle already (Launch Services
16//! activates the running one), so nothing is reported there; files and
17//! links come through `UrlScheme` as always. iOS, Android and the web have
18//! no second launch.
19
20use crate::{EventPayload, JsonValue};
21
22/// The most launches kept while no listener takes them: past it the oldest
23/// goes.
24pub const MAX_PENDING: usize = 16;
25
26/// A later launch of the app (TS: `Application.on("secondInstance", ...)`,
27/// Rust: [`next_second_instance`](crate::element::next_second_instance)).
28/// Anyone can start the app with any arguments: they are untrusted input.
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct SecondInstance {
32    /// Its command line's arguments, the program's path not included.
33    pub args: Vec<String>,
34    /// The directory it was started in, which relative paths among
35    /// [`args`](Self::args) are relative to; empty when unknown.
36    pub cwd: String,
37}
38
39impl SecondInstance {
40    /// A launch with `args` started in `cwd`.
41    pub fn new(args: Vec<String>, cwd: impl Into<String>) -> Self {
42        Self {
43            args,
44            cwd: cwd.into(),
45        }
46    }
47
48    /// The payload of [`EventKind::SecondInstance`](crate::EventKind::SecondInstance)
49    /// carrying it.
50    pub fn to_payload(&self) -> EventPayload {
51        EventPayload::Json(self.to_json())
52    }
53
54    /// As JSON: `{ "args": [...], "cwd": "..." }`, the form a second
55    /// process hands the first.
56    pub fn to_json(&self) -> JsonValue {
57        serde_json::json!({ "args": self.args, "cwd": self.cwd })
58    }
59
60    /// The launch [`Self::to_json`] wrote; `None` for anything else.
61    pub fn from_json(value: &JsonValue) -> Option<Self> {
62        let args = value
63            .get("args")?
64            .as_array()?
65            .iter()
66            .map(|arg| arg.as_str().map(str::to_owned))
67            .collect::<Option<Vec<_>>>()?;
68        let cwd = value
69            .get("cwd")
70            .and_then(JsonValue::as_str)
71            .unwrap_or_default();
72        Some(Self::new(args, cwd))
73    }
74
75    /// The launch a payload of
76    /// [`EventKind::SecondInstance`](crate::EventKind::SecondInstance) carries.
77    pub fn from_payload(payload: &EventPayload) -> Option<Self> {
78        match payload {
79            EventPayload::Json(value) => Self::from_json(value),
80            _ => None,
81        }
82    }
83
84    /// This process's launch: its arguments after the program and its
85    /// working directory.
86    pub fn current() -> Self {
87        Self::new(
88            std::env::args().skip(1).collect(),
89            std::env::current_dir()
90                .map(|dir| dir.to_string_lossy().into_owned())
91                .unwrap_or_default(),
92        )
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn a_launch_goes_through_its_payload() {
102        let launch = SecondInstance::new(vec!["--open".into(), "a b.txt".into()], "/home/u");
103        assert_eq!(
104            SecondInstance::from_payload(&launch.to_payload()),
105            Some(launch.clone())
106        );
107        assert_eq!(
108            launch.to_json(),
109            serde_json::json!({ "args": ["--open", "a b.txt"], "cwd": "/home/u" })
110        );
111    }
112
113    #[test]
114    fn other_payloads_are_no_launch() {
115        assert_eq!(SecondInstance::from_payload(&EventPayload::None), None);
116        assert_eq!(
117            SecondInstance::from_json(&serde_json::json!({ "args": [1] })),
118            None
119        );
120        assert_eq!(
121            SecondInstance::from_json(&serde_json::json!({ "args": [] })),
122            Some(SecondInstance::default())
123        );
124    }
125}