Skip to main content

egui_pop_platform/
open.rs

1//! The links service's system opener (ADR 0017): local files and folders
2//! opened with the system's default application, and Reveal, the file
3//! manager with the file selected. Web pages and mail still go through
4//! egui's `OpenUrl` (the browser, `$BROWSER` honoured; a new tab on the
5//! web build).
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! | | Open a file or folder | Reveal |
11//! |---|---|---|
12//! | Linux | `xdg-open` (inside Flatpak, the runtime's forwards to the OpenURI portal, which opens what the sandbox can read) | the freedesktop file manager interface (`org.freedesktop.FileManager1.ShowItems`), else the OpenURI portal's `OpenDirectory` |
13//! | macOS | `open` | `open -R` |
14//! | Windows | `ShellExecuteW` (programs never reach it: the policy refuses them first) | Explorer's selection (`SHOpenFolderAndSelectItems`) |
15//! | The web build | refused with the reason | refused |
16//!
17//! The work is done on a thread (a D-Bus call may take a moment): the
18//! `link.open` step ends `opening`, then the journal says `link.opened`,
19//! or `link.failed` with a warning toast.
20//!
21//! ```no_run
22//! use egui_pop_api::App;
23//! use egui_pop_platform::open::OpenPlugin;
24//!
25//! let app = App::builder()
26//!     .plugins(egui_pop_api::DefaultPlugins)
27//!     .plugin(OpenPlugin)
28//!     .build(&egui::Context::default())
29//!     .unwrap();
30//! ```
31
32use std::sync::Arc;
33
34use egui_pop_api::links::{self, Caps, EguiOpener, How, OpenCall, Opener, Opening};
35use egui_pop_api::{Ctx, Plugin, PluginError};
36use egui_pop_model::ids::PluginId;
37
38/// The plugin's id.
39pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.open");
40
41/// Opens local files and folders, and reveals them, with the system;
42/// web pages and mail through egui's opener.
43#[derive(Clone, Copy, Debug, Default)]
44pub struct SystemOpener;
45
46impl Opener for SystemOpener {
47    fn name(&self) -> &str {
48        "system"
49    }
50
51    fn caps(&self) -> Caps {
52        if cfg!(target_arch = "wasm32") {
53            Caps::WEB
54        } else {
55            Caps {
56                web: true,
57                files: true,
58                reveal: true,
59                inside: false,
60                video: false,
61                web_video: false,
62            }
63        }
64    }
65
66    fn open(&self, call: &OpenCall<'_>) -> Opening {
67        let local = call.target.local_path();
68        match (call.how, local) {
69            (How::Outside, None) => EguiOpener.open(call),
70            (how, Some(path)) => system(how, path),
71            (_, None) => Opening::Done(Err(
72                "only a local file or folder can be shown in its folder".into(),
73            )),
74        }
75    }
76}
77
78#[cfg(not(target_arch = "wasm32"))]
79fn system(how: How, path: String) -> Opening {
80    let (pending, resolver) = egui_pop_api::host::pending();
81    let spawned = std::thread::Builder::new()
82        .name("egui-pop-open".into())
83        .spawn(move || {
84            let result = match how {
85                How::Reveal => opener::reveal(&path),
86                _ => opener::open(&path),
87            };
88            resolver.resolve(
89                result
90                    .map(|()| serde_json::Value::Null)
91                    .map_err(|e| e.to_string()),
92            );
93        });
94    match spawned {
95        Ok(_) => Opening::Later(pending),
96        Err(e) => Opening::Done(Err(format!("no thread to open it from: {e}"))),
97    }
98}
99
100#[cfg(target_arch = "wasm32")]
101fn system(_: How, _: String) -> Opening {
102    Opening::Done(Err("local files cannot be opened from the web".into()))
103}
104
105/// Installs [`SystemOpener`] in the links service.
106#[derive(Clone, Copy, Debug, Default)]
107pub struct OpenPlugin;
108
109impl Plugin for OpenPlugin {
110    fn id(&self) -> PluginId {
111        PLUGIN
112    }
113
114    fn title(&self) -> String {
115        "System opener".into()
116    }
117
118    fn requires(&self) -> Vec<PluginId> {
119        vec![links::PLUGIN]
120    }
121
122    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
123        let l = links::links(&ctx.app())
124            .ok_or_else(|| PluginError::Failed("the links service is not there".into()))?;
125        l.set_opener(Arc::new(SystemOpener));
126        Ok(())
127    }
128
129    fn disconnect(&mut self, ctx: &mut Ctx<'_>) {
130        if let Some(l) = links::links(&ctx.app()) {
131            l.set_opener(Arc::new(EguiOpener));
132        }
133    }
134}