egui_pop_platform/instance.rs
1//! A single instance, and deep links.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! [`single`], called at the top of `main`, before any window: the first
7//! launch listens on a local socket named after the application (an
8//! abstract socket on Linux, a named pipe on Windows, a socket in `/tmp`
9//! elsewhere) and gets [`Single::First`]; a later launch hands its
10//! arguments, its working directory and its activation token to the
11//! running one and gets [`Single::Handed`]: it exits.
12//!
13//! [`InstancePlugin`] takes what the first launch holds into the
14//! application. Its steps (ADR 0011):
15//!
16//! - `instance.second_launch`: a later launch handed over, with
17//! `{ "args", "cwd", "links" }` (`links`: the arguments in one of the
18//! plugin's [`schemes`](InstancePlugin::scheme)). By default the main
19//! window comes to the front ([`crate::window::raise`]) and each link
20//! runs `deeplink.open`. Veto it to stay in the background; replace it
21//! to open the files a second launch names.
22//! - `deeplink.open`: a link to open, `{ "url", "origin" }`, from a later
23//! launch or from the first launch's own arguments (at start). By
24//! default the plugin's [`links`](InstancePlugin::links) command runs
25//! with `{ "url" }`; without one the step fails, and says so.
26//!
27//! A link from a launch is not the user's gesture: any program of the
28//! user's (a web page in a browser, another application) may launch the
29//! application with one. Its command runs as [`deeplink_origin`]
30//! (`Origin::Remote("deeplink")`, `remote:deeplink` on the journal and in
31//! the step's `origin`): the handler sees it in `Call::origin`, the
32//! commands it starts inherit it, it may not run one as the user, and it
33//! writes values as `remote:deeplink`, held to their writers. A handler
34//! that changes or deletes anything on a link asks the user first (a
35//! dialog: the user's answer runs as the user). A link of the
36//! application's scheme clicked inside the application runs as the click
37//! did.
38//!
39//! The launches handed over are kept ([`LAUNCHES`], [`Launches::history`]);
40//! [`Launches::deliver`] hands one over in-process, as a test or the
41//! gallery does.
42//!
43//! Without `App` and its plugin, [`single`] works the same; the
44//! application takes the later launches itself: [`Instance::launches`]
45//! from [`Single::First`], [`Launches::set_waker`] with its egui context
46//! so a launch handed over repaints the window, and [`Launches::take`]
47//! each frame (bringing the window to the front with
48//! [`crate::window::raise`], opening what the launch names). Registering the scheme with the system is the
49//! packager's part: see `docs/packaging.md`.
50//!
51//! On Linux a connection from another user is refused (the abstract
52//! socket namespace is shared by the users of a machine). Inside a
53//! Flatpak sandbox the socket is a file in the directory the
54//! application's sandboxes share ([`flatpak_socket`]). Elsewhere the
55//! socket or pipe is the user's own by its place (`/tmp` with the user's
56//! name in the socket's, a pipe in the user's session).
57//!
58//! ```
59//! use egui_pop_api::App;
60//! use egui_pop_platform::instance::{self, InstancePlugin, Launch};
61//!
62//! let launch = Launch { args: vec!["demo://open/7".into()], ..Launch::default() };
63//! let first = instance::Instance::detached(launch);
64//! let ctx = egui::Context::default();
65//! let mut app = App::builder()
66//! .plugin(InstancePlugin::new(first).scheme("demo"))
67//! .build(&ctx)
68//! .unwrap();
69//! app.logic(&ctx);
70//! // No command opens links: the step says so.
71//! let trace = app.handle().step_traces().into_iter().rev()
72//! .find(|t| t.step.as_str() == "deeplink.open").unwrap();
73//! assert_eq!(trace.args["url"], "demo://open/7");
74//! ```
75
76use std::collections::VecDeque;
77use std::io;
78use std::sync::{Arc, Mutex};
79
80use egui_pop_api::hooks::On;
81use egui_pop_api::services::ServiceToken;
82use egui_pop_api::steps::StepSpec;
83use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
84use egui_pop_core::lock;
85use egui_pop_model::commands::{CommandSpec, Origin};
86use egui_pop_model::ids::{CommandId, PluginId, StepId};
87use serde::{Deserialize, Serialize};
88use serde_json::{Value as Json, json};
89
90/// The plugin's id.
91pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.instance");
92/// A later launch handed over: `{ "args", "cwd", "links" }`.
93pub const STEP_SECOND_LAUNCH: StepId = StepId::from_static("instance.second_launch");
94/// A link to open: `{ "url" }`.
95pub const STEP_DEEPLINK: StepId = StepId::from_static("deeplink.open");
96/// Opens a link of the application's own scheme (`url`), through
97/// [`STEP_DEEPLINK`]: what the links service runs for a click on one.
98pub const CMD_DEEPLINK: CommandId = CommandId::from_static("deeplink.open");
99/// The launches handed over, as a service.
100pub const LAUNCHES: ServiceToken<Launches> = ServiceToken::new("platform.instance");
101/// How many launches [`Launches::history`] keeps.
102pub const HISTORY: usize = 32;
103
104/// What a launch says: its arguments (without the program), its working
105/// directory, and the activation token the desktop gave it
106/// (`XDG_ACTIVATION_TOKEN`, `DESKTOP_STARTUP_ID`).
107#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
108pub struct Launch {
109 pub args: Vec<String>,
110 #[serde(default)]
111 pub cwd: Option<String>,
112 #[serde(default)]
113 pub activation: Option<String>,
114}
115
116impl Launch {
117 /// This process's launch.
118 pub fn current() -> Launch {
119 Launch {
120 args: std::env::args().skip(1).collect(),
121 cwd: std::env::current_dir()
122 .ok()
123 .map(|p| p.to_string_lossy().into_owned()),
124 activation: std::env::var("XDG_ACTIVATION_TOKEN")
125 .or_else(|_| std::env::var("DESKTOP_STARTUP_ID"))
126 .ok(),
127 }
128 }
129
130 /// Its arguments that are links in one of `schemes` (`myapp:` or
131 /// `myapp://`, whatever the case of the scheme).
132 pub fn links(&self, schemes: &[String]) -> Vec<String> {
133 self.args
134 .iter()
135 .filter(|a| {
136 a.split_once(':')
137 .is_some_and(|(s, _)| schemes.iter().any(|w| w.eq_ignore_ascii_case(s)))
138 })
139 .cloned()
140 .collect()
141 }
142}
143
144#[derive(Debug, Default)]
145struct State {
146 pending: VecDeque<Launch>,
147 history: VecDeque<Launch>,
148 waker: Option<egui::Context>,
149}
150
151/// The launches handed over to this one: shared with the thread that
152/// listens, taken at the next pass of the application.
153#[derive(Clone, Debug, Default)]
154pub struct Launches(Arc<Mutex<State>>);
155
156impl Launches {
157 /// Hands a launch over, as a later launch does through the socket.
158 pub fn deliver(&self, launch: Launch) {
159 let waker = {
160 let mut s = lock(&self.0);
161 s.pending.push_back(launch.clone());
162 s.history.push_back(launch);
163 while s.history.len() > HISTORY {
164 s.history.pop_front();
165 }
166 s.waker.clone()
167 };
168 if let Some(ctx) = waker {
169 ctx.request_repaint();
170 }
171 }
172
173 /// The launches handed over, oldest first.
174 pub fn history(&self) -> Vec<Launch> {
175 lock(&self.0).history.iter().cloned().collect()
176 }
177
178 /// The launches handed over since the last call, oldest first, taken
179 /// out (each is taken once; [`Launches::history`] keeps them). What
180 /// [`InstancePlugin`] runs `instance.second_launch` for at each pass;
181 /// an application without `App` calls it each frame instead (see
182 /// [`Launches::set_waker`]).
183 pub fn take(&self) -> Vec<Launch> {
184 lock(&self.0).pending.drain(..).collect()
185 }
186
187 /// The egui context to repaint when a launch is handed over (`None`:
188 /// none), so that a window waiting for input sees it at once.
189 /// [`InstancePlugin`] sets its application's; an application without
190 /// `App` sets its own and [takes](Launches::take) the launches in
191 /// its frame:
192 ///
193 /// ```
194 /// use egui_pop_platform::instance::{self, Launch, Single};
195 ///
196 /// // At the top of `main`: `instance::single("org.example.App")?`.
197 /// let single = Single::First(instance::Instance::detached(Launch::default()));
198 /// let Single::First(instance) = single else {
199 /// return; // Handed over to the running instance: exit.
200 /// };
201 /// let launches = instance.launches();
202 /// let ctx = egui::Context::default(); // eframe's, in `App::new`.
203 /// launches.set_waker(Some(ctx.clone()));
204 ///
205 /// // A later launch, as the listening thread hands it over.
206 /// launches.deliver(Launch { args: vec!["photo.jpg".into()], ..Launch::default() });
207 ///
208 /// // In the frame (`eframe::App::update`):
209 /// for launch in launches.take() {
210 /// egui_pop_platform::window::raise(&ctx);
211 /// assert_eq!(launch.args, ["photo.jpg"]); // Open what it names.
212 /// }
213 /// assert!(launches.take().is_empty());
214 /// ```
215 pub fn set_waker(&self, ctx: Option<egui::Context>) {
216 lock(&self.0).waker = ctx;
217 }
218}
219
220/// The first launch: what it was launched with, and the launches the
221/// later ones hand over.
222#[derive(Debug)]
223pub struct Instance {
224 first: Launch,
225 launches: Launches,
226 name: Option<String>,
227}
228
229impl Instance {
230 /// An instance listening to nothing: the launches come through
231 /// [`Launches::deliver`] (tests, the gallery, an application with
232 /// its own way of being single).
233 pub fn detached(first: Launch) -> Instance {
234 Instance {
235 first,
236 launches: Launches::default(),
237 name: None,
238 }
239 }
240
241 /// What this launch was launched with.
242 pub fn first(&self) -> &Launch {
243 &self.first
244 }
245
246 /// The launches handed over: shared, the same each call. Without
247 /// `App`, [take](Launches::take) them each frame.
248 pub fn launches(&self) -> Launches {
249 self.launches.clone()
250 }
251
252 /// The socket's name, when it listens.
253 pub fn socket(&self) -> Option<&str> {
254 self.name.as_deref()
255 }
256}
257
258/// What [`single`] found.
259#[derive(Debug)]
260pub enum Single {
261 /// This is the first launch: go on, with the instance.
262 First(Instance),
263 /// Another instance runs and took this launch's arguments: exit.
264 Handed,
265}
266
267/// The socket's name for an application: its id and the user's name,
268/// kept to what every platform accepts.
269pub fn socket_name(app_id: &str) -> String {
270 let user = std::env::var("USER")
271 .or_else(|_| std::env::var("USERNAME"))
272 .unwrap_or_default();
273 let clean = |s: &str| -> String {
274 s.chars()
275 .map(|c| {
276 if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
277 c
278 } else {
279 '_'
280 }
281 })
282 .collect()
283 };
284 format!("{}.{}.instance", clean(app_id), clean(&user))
285}
286
287/// Inside a Flatpak sandbox, the socket's file in the directory every
288/// instance of the application shares (`$XDG_RUNTIME_DIR/app/<id>`):
289/// each sandbox may have a network namespace of its own, where abstract
290/// sockets are not seen.
291pub fn flatpak_socket(name: &str) -> Option<std::path::PathBuf> {
292 flatpak_socket_with(name, |v| std::env::var(v).ok())
293}
294
295/// [`flatpak_socket`] from the environment `env` gives.
296pub fn flatpak_socket_with(
297 name: &str,
298 env: impl Fn(&str) -> Option<String>,
299) -> Option<std::path::PathBuf> {
300 let id = env("FLATPAK_ID").filter(|i| !i.is_empty())?;
301 let run = env("XDG_RUNTIME_DIR").filter(|r| !r.is_empty())?;
302 Some(
303 std::path::Path::new(&run)
304 .join("app")
305 .join(id)
306 .join(format!("{name}.sock")),
307 )
308}
309
310/// Makes this launch the application's only instance, or hands it to the
311/// one running (see the module). `app_id`: a reverse-DNS id
312/// (`org.example.App`).
313pub fn single(app_id: &str) -> io::Result<Single> {
314 single_with(app_id, Launch::current())
315}
316
317/// [`single`] with a launch of the caller's.
318#[cfg(not(target_arch = "wasm32"))]
319pub fn single_with(app_id: &str, launch: Launch) -> io::Result<Single> {
320 use interprocess::local_socket::{
321 GenericFilePath, GenericNamespaced, ListenerOptions, prelude::*,
322 };
323
324 let name = socket_name(app_id);
325 let in_sandbox = flatpak_socket(&name);
326 let ns = || match &in_sandbox {
327 Some(path) => path.as_path().to_fs_name::<GenericFilePath>(),
328 None => name.as_str().to_ns_name::<GenericNamespaced>(),
329 };
330 if hand_over(ns()?, &launch).is_ok() {
331 return Ok(Single::Handed);
332 }
333 let listener = match ListenerOptions::new()
334 .name(ns()?)
335 .try_overwrite(true)
336 .max_spin_time(std::time::Duration::from_millis(500))
337 .create_sync()
338 {
339 Ok(l) => l,
340 // Another first launch won the race: hand over to it.
341 Err(e) if e.kind() == io::ErrorKind::AddrInUse => {
342 hand_over(ns()?, &launch)?;
343 return Ok(Single::Handed);
344 }
345 Err(e) => return Err(e),
346 };
347 let launches = Launches::default();
348 let to = launches.clone();
349 std::thread::Builder::new()
350 .name("egui-pop instance".into())
351 .spawn(move || {
352 for conn in listener.incoming() {
353 match conn {
354 Ok(stream) => {
355 if let Err(e) = receive(stream, &to) {
356 log::warn!(target: "egui_pop", "a second launch: {e}");
357 }
358 }
359 Err(e) => log::warn!(target: "egui_pop", "instance socket: {e}"),
360 }
361 }
362 })?;
363 Ok(Single::First(Instance {
364 first: launch,
365 launches,
366 name: Some(match in_sandbox {
367 Some(p) => p.to_string_lossy().into_owned(),
368 None => name,
369 }),
370 }))
371}
372
373/// [`single`] on the web: always the first.
374#[cfg(target_arch = "wasm32")]
375pub fn single_with(_: &str, launch: Launch) -> io::Result<Single> {
376 Ok(Single::First(Instance::detached(launch)))
377}
378
379#[cfg(not(target_arch = "wasm32"))]
380fn hand_over(name: interprocess::local_socket::Name<'_>, launch: &Launch) -> io::Result<()> {
381 use interprocess::local_socket::prelude::*;
382 use std::io::{BufRead as _, BufReader, Write as _};
383
384 let mut stream = LocalSocketStream::connect(name)?;
385 let mut line = serde_json::to_string(launch).map_err(io::Error::other)?;
386 line.push('\n');
387 stream.write_all(line.as_bytes())?;
388 stream.flush()?;
389 let mut answer = String::new();
390 BufReader::new(stream).read_line(&mut answer)?;
391 if answer.trim() == "ok" {
392 Ok(())
393 } else {
394 Err(io::Error::other(format!(
395 "the running instance answered `{}`",
396 answer.trim()
397 )))
398 }
399}
400
401#[cfg(not(target_arch = "wasm32"))]
402fn receive(stream: interprocess::local_socket::Stream, to: &Launches) -> io::Result<()> {
403 use std::io::{BufRead as _, BufReader, Write as _};
404
405 // The peer's credentials are read on Linux only: the prelude's
406 // stream trait is needed there alone.
407 #[cfg(target_os = "linux")]
408 {
409 use interprocess::local_socket::prelude::*;
410 use std::os::unix::fs::MetadataExt as _;
411 let own = std::fs::metadata("/proc/self")?.uid();
412 let peer = stream.peer_creds()?.euid();
413 if peer.is_none_or(|uid| u64::from(uid) != u64::from(own)) {
414 return Err(io::Error::other("a launch from another user, refused"));
415 }
416 }
417 let mut reader = BufReader::new(stream);
418 let mut line = String::new();
419 reader.read_line(&mut line)?;
420 let launch: Launch = serde_json::from_str(line.trim()).map_err(io::Error::other)?;
421 to.deliver(launch);
422 reader.get_mut().write_all(b"ok\n")?;
423 Ok(())
424}
425
426/// The single instance in the application (see the module).
427#[derive(Debug)]
428pub struct InstancePlugin {
429 instance: Instance,
430 schemes: Vec<String>,
431 links: Option<CommandId>,
432}
433
434impl InstancePlugin {
435 pub fn new(instance: Instance) -> Self {
436 Self {
437 instance,
438 schemes: Vec::new(),
439 links: None,
440 }
441 }
442
443 /// A URL scheme whose links the application opens (`myapp`, for
444 /// `myapp://...`).
445 pub fn scheme(mut self, scheme: &str) -> Self {
446 self.schemes.push(scheme.trim_end_matches(':').into());
447 self
448 }
449
450 /// The command `deeplink.open` runs by default, with `{ "url" }`.
451 pub fn links(mut self, command: CommandId) -> Self {
452 self.links = Some(command);
453 self
454 }
455}
456
457/// The origin of a link from outside the application: a launch, the
458/// first one's arguments or a later one's through the single-instance
459/// socket. Any program of the user's may launch the application with a
460/// link (a web page's, another application's), so the link is not the
461/// user's own gesture.
462pub fn deeplink_origin() -> Origin {
463 Origin::Remote("deeplink".into())
464}
465
466/// Runs `deeplink.open` for a link, for `origin`: [`deeplink_origin`]
467/// for a launch's, the click's own for a link clicked in the
468/// application (`deeplink.open`, the command).
469fn open_link(app: &AppHandle, links: Option<&CommandId>, url: &str, origin: Origin) {
470 let links = links.cloned();
471 let args = json!({ "url": url, "origin": egui_pop_api::host::source_of(&origin) });
472 app.step(&STEP_DEEPLINK, args, move |app, args| {
473 let Some(command) = links else {
474 return Err("no command opens links (InstancePlugin::links)".into());
475 };
476 app.run_as(command.clone(), json!({ "url": args["url"] }), origin);
477 Ok(json!({ "command": command }))
478 });
479}
480
481impl Plugin for InstancePlugin {
482 fn id(&self) -> PluginId {
483 PLUGIN
484 }
485
486 fn title(&self) -> String {
487 "Single instance".into()
488 }
489
490 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
491 ctx.step(
492 StepSpec::new(
493 STEP_SECOND_LAUNCH,
494 "A later launch handed its arguments over (`args`, `cwd`, `links`); by default the window comes to the front and each link is opened.",
495 )
496 .args(json!({ "args": ["--open", "photo.jpg"], "cwd": "/home/me", "links": [] })),
497 )?
498 .step(
499 StepSpec::new(
500 STEP_DEEPLINK,
501 "A link to open (`url`); by default the plugin's links command runs with it.",
502 )
503 .args(json!({ "url": "myapp://open/42" })),
504 )?;
505 // A click on one of these links inside the application (the
506 // links service) opens it here, through the same step.
507 let links = self.links.clone();
508 ctx.command(
509 CommandSpec::new(CMD_DEEPLINK, "Open an application link", "Links")
510 .description("Opens a link of the application's own scheme (`url`) through the `deeplink.open` step.")
511 .args(json!({ "url": "myapp://open/42" }))
512 .hidden()
513 .no_agent(),
514 move |call| {
515 let url = call.args["url"].as_str().ok_or("`url` is missing")?;
516 open_link(call.app, links.as_ref(), url, call.origin.clone());
517 Ok(json!({ "url": url }))
518 },
519 )?;
520 let schemes = self.schemes.clone();
521 ctx.on(On::Started, move |app, _| {
522 if let Some(l) = egui_pop_api::links::links(app) {
523 l.update_policy(|p| {
524 for s in &schemes {
525 *p = std::mem::take(p).app_scheme(s);
526 }
527 });
528 }
529 });
530 let launches = self.instance.launches();
531 ctx.service(&LAUNCHES, launches.clone())?;
532 launches.set_waker(Some(ctx.app().egui()));
533 // The first launch's own links, once started.
534 let first = self.instance.first().links(&self.schemes);
535 let links = self.links.clone();
536 let mut opened = false;
537 ctx.on(On::Started, move |app, _| {
538 if !std::mem::replace(&mut opened, true) {
539 for url in &first {
540 open_link(app, links.as_ref(), url, deeplink_origin());
541 }
542 }
543 });
544 let (schemes, links) = (self.schemes.clone(), self.links.clone());
545 ctx.on(On::Pass, move |app, _| {
546 for launch in launches.take() {
547 let found = launch.links(&schemes);
548 let args = json!({
549 "args": launch.args,
550 "cwd": launch.cwd,
551 "links": found,
552 });
553 let links = links.clone();
554 app.step(&STEP_SECOND_LAUNCH, args, move |app, args| {
555 crate::window::raise_app(app);
556 let urls: Vec<String> = args["links"]
557 .as_array()
558 .map(|l| {
559 l.iter()
560 .filter_map(Json::as_str)
561 .map(String::from)
562 .collect()
563 })
564 .unwrap_or_default();
565 for url in &urls {
566 open_link(app, links.as_ref(), url, deeplink_origin());
567 }
568 Ok(json!({ "raised": true, "links": urls.len() }))
569 });
570 }
571 });
572 Ok(())
573 }
574
575 fn disconnect(&mut self, _ctx: &mut Ctx<'_>) {
576 self.instance.launches.set_waker(None);
577 }
578}