Skip to main content

tilo_process_services/
process.rs

1//! Process services — the capabilities an app borrows from its process.
2//!
3//! Widgets and apps reach the clipboard, file choosers, URI handlers, speech,
4//! notifications and media controls through [`ProcessServices`] instead of
5//! calling a platform API directly. The same toolkit then runs under the
6//! native desktop runner, inside an app process such as the compositor's, or
7//! in a test that records every effect instead of performing it.
8//!
9//! # Resolution
10//!
11//! [`current`] answers, in order:
12//!
13//! 1. the innermost [`scoped`] set on this thread — a process running several
14//!    apps wraps each app's dispatch so its effects reach that app's services;
15//! 2. the default an app process installed with [`install_default`];
16//! 3. [`ProcessServices::null`], which performs nothing outside the process.
17//!
18//! The existing free functions (`text_selection::clipboard_copy`,
19//! `portal::PickRequest::send`, `widget::try_open_external_url`, …) resolve
20//! through [`current`], so apps need no changes. New code that holds a
21//! `ui::application::ProcessContext` can use its `services()` directly.
22
23use std::cell::RefCell;
24use std::sync::mpsc::Receiver;
25use std::sync::{Arc, OnceLock, RwLock};
26
27use crate::capture::{ScreenCaptureChannel, ScreenCaptureOutcome, ScreenCaptureRequest};
28use crate::clipboard::{ClipboardBackend, InProcessClipboard};
29use crate::mpris::{MprisCommand, MprisConfig, PlayerSnapshot};
30
31/// The native desktop implementation; see [`crate::native::services`].
32#[cfg(feature = "native")]
33pub use crate::native::services as native;
34/// Process inputs: who the process is and where its files live, kept with the
35/// current process (`tilo_process::environment`).
36pub use tilo_process::environment;
37mod recording;
38
39pub use environment::{
40    AccessibilityInputs, ContinuationMetadata, NO_WINDOW_ENV, NO_WINDOW_IDLE_ENV,
41    ProcessEnvironment, ProcessIdentity, ProcessPaths, REVEAL_ENV, RunnerDiagnostics, environment,
42    install_environment, parse_posix_locale,
43};
44pub use recording::ProcessRecorder;
45
46pub use tilo_dialogs::{FilePicker, UriOpener};
47
48/// Creates the speech output the built-in screen reader narrates through.
49pub trait SpeechFactory: Send + Sync {
50    /// A fresh speaker. Must not fail: a process without speech returns a
51    /// [`tts::NullSpeaker`].
52    fn make(&self) -> Box<dyn tts::Speaker>;
53}
54
55pub use tilo_notify::{Notification, Notifier, NotifyError};
56
57pub use crate::location::LocationProvider;
58
59pub use tilo_secrets::{SecretBackend, SecretStore};
60
61/// Opens an app's secret store: the system's, or a process's own.
62pub trait SecretsProvider: Send + Sync {
63    /// The secrets of the app `app_id`, and no other app's.
64    fn store(&self, app_id: &str) -> SecretStore;
65}
66
67/// Each app's secrets in this target's secret store: the workspace's vault for a process its
68/// launcher handed a connection to the daemon, else the Secret Service, the Keychain, or the
69/// browser's wrapped store.
70struct SystemSecrets;
71
72impl SecretsProvider for SystemSecrets {
73    fn store(&self, app_id: &str) -> SecretStore {
74        #[cfg(target_os = "linux")]
75        if let Some(vault) = handed_vault() {
76            return SecretStore::with_backend(app_id, vault);
77        }
78        SecretStore::for_app(app_id)
79    }
80}
81
82/// The workspace's vault over the connection the launcher handed this process, made once: `None`
83/// for a process it handed none.
84#[cfg(target_os = "linux")]
85fn handed_vault() -> Option<Arc<dyn SecretBackend>> {
86    static VAULT: std::sync::OnceLock<Option<Arc<dyn SecretBackend>>> = std::sync::OnceLock::new();
87    VAULT
88        .get_or_init(|| {
89            crate::vault_secrets::VaultStore::handed()
90                .map(|vault| Arc::new(vault) as Arc<dyn SecretBackend>)
91        })
92        .clone()
93}
94
95/// Secrets in one map that lives as long as the provider, for processes that
96/// keep nothing outside the process.
97pub struct InProcessSecrets(Arc<dyn SecretBackend>);
98
99impl Default for InProcessSecrets {
100    fn default() -> Self {
101        Self(tilo_secrets::memory_backend())
102    }
103}
104
105impl SecretsProvider for InProcessSecrets {
106    fn store(&self, app_id: &str) -> SecretStore {
107        SecretStore::with_backend(app_id, self.0.clone())
108    }
109}
110
111/// Process-provided screen capture.
112pub trait ScreenCaptureProvider: Send + Sync {
113    /// Ask the user for a screen or window to capture. Answers over the
114    /// channel, never blocking the caller while the process shows its picker.
115    fn request(&self, request: ScreenCaptureRequest) -> ScreenCaptureChannel;
116}
117
118/// Receives player state for the process's media controls.
119pub trait MediaSessionPublisher: Send {
120    /// Publish the latest player state. Must not block.
121    fn publish(&mut self, snapshot: PlayerSnapshot);
122}
123
124/// A live media-control session: commands from the process (media keys, a
125/// now-playing widget) and the sink the player publishes its state into.
126pub struct MediaSession {
127    pub commands: Receiver<MprisCommand>,
128    pub publisher: Box<dyn MediaSessionPublisher>,
129}
130
131/// Starts media-control sessions for players such as the `VideoPlayer` widget.
132pub trait MediaSessionFactory: Send + Sync {
133    /// Register a player described by `config`, starting from `initial`.
134    /// `None` when the process has no media controls; the player then stays
135    /// inert.
136    fn start(&self, config: MprisConfig, initial: PlayerSnapshot) -> Option<MediaSession>;
137}
138
139/// Everything a `ui` process may ask of its process.
140///
141/// Cheap to clone: each service is shared.
142#[derive(Clone)]
143pub struct ProcessServices {
144    pub clipboard: Arc<dyn ClipboardBackend>,
145    pub files: Arc<dyn FilePicker>,
146    pub opener: Arc<dyn UriOpener>,
147    pub speech: Arc<dyn SpeechFactory>,
148    pub notifications: Arc<dyn Notifier>,
149    pub media_session: Arc<dyn MediaSessionFactory>,
150    pub location: Arc<dyn LocationProvider>,
151    pub screen_capture: Arc<dyn ScreenCaptureProvider>,
152    pub secrets: Arc<dyn SecretsProvider>,
153}
154
155impl ProcessServices {
156    /// Services that never leave the process: an in-process clipboard, file
157    /// choosers that fail, no URI handler, silent speech, no notifications,
158    /// no media controls, no location, no screen capture, and secrets kept
159    /// in the process.
160    pub fn null() -> Self {
161        Self {
162            clipboard: Arc::new(InProcessClipboard::default()),
163            files: tilo_dialogs::unavailable_picker(),
164            opener: tilo_dialogs::unavailable_opener(),
165            speech: Arc::new(SilentSpeech),
166            notifications: tilo_notify::unavailable(),
167            media_session: Arc::new(NoMediaSession),
168            location: crate::location::unavailable(),
169            screen_capture: Arc::new(NoScreenCapture),
170            secrets: Arc::new(InProcessSecrets::default()),
171        }
172    }
173
174    /// This target's services for the app `app_id`: the clipboard over the connection its
175    /// session serves it, each platform crate's system backend (file choosers and URI opening,
176    /// notifications, secrets) and, with the `native` feature, speech, media controls and screen
177    /// capture. Location is the device's own action, which the host installs with
178    /// [`Self::with_location`]; a process given none answers that location is not available.
179    /// Without an app id notifications are unavailable.
180    pub fn system(app_id: Option<&str>) -> Self {
181        let services = Self {
182            clipboard: tilo_clipboard::system(),
183            files: tilo_dialogs::unavailable_picker(),
184            opener: tilo_dialogs::system_opener(),
185            notifications: tilo_notify::system(app_id),
186            location: crate::location::unavailable(),
187            secrets: Arc::new(SystemSecrets),
188            ..Self::null()
189        };
190        #[cfg(all(feature = "native", not(target_os = "android")))]
191        let services = crate::native::services::with_native_backends(services);
192        services
193    }
194
195    /// Replace the clipboard, keeping every other service.
196    #[must_use]
197    pub fn with_clipboard(mut self, clipboard: Arc<dyn ClipboardBackend>) -> Self {
198        self.clipboard = clipboard;
199        self
200    }
201
202    /// Replace file choosing and opening, keeping every other service.
203    #[must_use]
204    pub fn with_files(mut self, files: Arc<dyn FilePicker>) -> Self {
205        self.files = files;
206        self
207    }
208
209    /// Replace location, keeping every other service: the host installs one that asks the
210    /// device's own action, so a sandboxed process never reaches the platform's location
211    /// service itself.
212    #[must_use]
213    pub fn with_location(mut self, location: Arc<dyn LocationProvider>) -> Self {
214        self.location = location;
215        self
216    }
217}
218
219impl std::fmt::Debug for ProcessServices {
220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221        f.debug_struct("ProcessServices")
222            .field("clipboard", &self.clipboard.name())
223            .finish_non_exhaustive()
224    }
225}
226
227fn answered<T>(outcome: T) -> Receiver<T> {
228    let (tx, rx) = std::sync::mpsc::channel();
229    let _ = tx.send(outcome);
230    rx
231}
232
233struct SilentSpeech;
234
235impl SpeechFactory for SilentSpeech {
236    fn make(&self) -> Box<dyn tts::Speaker> {
237        Box::new(tts::NullSpeaker::new())
238    }
239}
240
241struct NoMediaSession;
242
243impl MediaSessionFactory for NoMediaSession {
244    fn start(&self, _config: MprisConfig, _initial: PlayerSnapshot) -> Option<MediaSession> {
245        None
246    }
247}
248
249struct NoScreenCapture;
250
251impl ScreenCaptureProvider for NoScreenCapture {
252    fn request(&self, _request: ScreenCaptureRequest) -> ScreenCaptureChannel {
253        answered(ScreenCaptureOutcome::Unavailable(
254            "Screen capture isn't available here".to_string(),
255        ))
256    }
257}
258
259static DEFAULT: RwLock<Option<ProcessServices>> = RwLock::new(None);
260
261thread_local! {
262    static SCOPES: RefCell<Vec<ProcessServices>> = const { RefCell::new(Vec::new()) };
263}
264
265/// Install `services` as this process's default, replacing any earlier one.
266///
267/// A runner calls this once before constructing its app.
268pub fn install_default(services: ProcessServices) {
269    install_resolvers();
270    if let Ok(mut slot) = DEFAULT.write() {
271        tracing::debug!(
272            target: "tilo_ui::process",
273            clipboard = services.clipboard.name(),
274            "process services installed"
275        );
276        *slot = Some(services);
277    }
278}
279
280/// Install `make()` as the default unless one is already installed. Returns
281/// whether it installed.
282pub fn install_default_if_unset(make: impl FnOnce() -> ProcessServices) -> bool {
283    install_resolvers();
284    let Ok(mut slot) = DEFAULT.write() else {
285        return false;
286    };
287    if slot.is_some() {
288        return false;
289    }
290    *slot = Some(make());
291    true
292}
293
294pub fn installed_default() -> Option<ProcessServices> {
295    DEFAULT.read().ok()?.clone()
296}
297
298/// Run `f` with `services` as [`current`] on this thread.
299///
300/// Nests: the innermost scope wins, and the previous one is restored when `f`
301/// returns or unwinds.
302pub fn scoped<R>(services: &ProcessServices, f: impl FnOnce() -> R) -> R {
303    let _scope = enter(services);
304    f()
305}
306
307/// Make `services` [`current`] on this thread until the returned guard drops.
308///
309/// The guard form of [`scoped`], for a scope that spans several statements
310/// (a test, a process's dispatch of one event). Guards must drop in reverse
311/// order of creation, which Rust's scoping gives for free.
312#[must_use = "the services are current only while the guard lives"]
313pub fn enter(services: &ProcessServices) -> ProcessScope {
314    install_resolvers();
315    SCOPES.with(|scopes| scopes.borrow_mut().push(services.clone()));
316    ProcessScope {
317        _not_send: std::marker::PhantomData,
318    }
319}
320
321/// Keeps a set of services [`current`] on this thread; see [`enter`].
322pub struct ProcessScope {
323    // The scope lives in a thread-local stack; dropping it elsewhere would
324    // pop another thread's entry.
325    _not_send: std::marker::PhantomData<*const ()>,
326}
327
328impl Drop for ProcessScope {
329    fn drop(&mut self) {
330        SCOPES.with(|scopes| {
331            scopes.borrow_mut().pop();
332        });
333    }
334}
335
336/// Let the platform crates' free functions (`portal::PickRequest::send`,
337/// `portal::open_uri`, …) reach [`current`]. Runs before any services other
338/// than [`ProcessServices::null`] can be current.
339fn install_resolvers() {
340    tilo_dialogs::install_resolver(tilo_dialogs::Resolver {
341        picker: || current().files,
342        opener: || current().opener,
343    });
344}
345
346/// The services effects on this thread should reach right now; see the
347/// module docs for the resolution order.
348pub fn current() -> ProcessServices {
349    static NULL: OnceLock<ProcessServices> = OnceLock::new();
350    if let Some(scoped) = SCOPES.with(|scopes| scopes.borrow().last().cloned()) {
351        return scoped;
352    }
353    if let Some(installed) = installed_default() {
354        return installed;
355    }
356    NULL.get_or_init(ProcessServices::null).clone()
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362    use crate::clipboard::ClipboardTarget;
363    use crate::portal::{
364        LaunchOutcome, LaunchRequest, MultiOutcome, OpenFileOutcome, PickRequest, PortalOutcome,
365    };
366
367    /// A request reaches whatever process is current: a recording process answers
368    /// immediately, so a test never opens a chooser on the user's screen.
369    #[test]
370    fn requests_reach_the_current_host() {
371        let (services, recorder) = ProcessServices::recording();
372        recorder.respond_to_pick(PortalOutcome::Opened("/tmp/a.qvp".into()));
373        scoped(&services, || {
374            let single = PickRequest::open("Open", "Open").send();
375            assert_eq!(
376                single.try_recv(),
377                Ok(PortalOutcome::Opened("/tmp/a.qvp".into()))
378            );
379            let save = PickRequest::save("Save", "Save", "x.qvp").send();
380            assert_eq!(save.try_recv(), Ok(PortalOutcome::Cancelled));
381            let many = PickRequest::open_multiple("Import", "Import").send_multiple();
382            assert_eq!(many.try_recv(), Ok(MultiOutcome::Cancelled));
383            let descriptor = PickRequest::open("Open", "Open").send_open_handle();
384            assert!(matches!(
385                descriptor.try_recv(),
386                Ok(OpenFileOutcome::Cancelled)
387            ));
388            let launch = LaunchRequest::reveal("/tmp/a.qvp").send();
389            assert_eq!(launch.try_recv(), Ok(LaunchOutcome::Opened));
390            assert!(crate::portal::open_uri("tilo://recorded").is_ok());
391        });
392        assert_eq!(recorder.pick_requests().len(), 4);
393        assert_eq!(recorder.launch_requests().len(), 1);
394        assert_eq!(recorder.opened_uris(), ["tilo://recorded"]);
395    }
396
397    #[test]
398    fn host_services_are_inert_and_scopes_nest_and_restore_even_on_panic() {
399        {
400            let null = ProcessServices::null();
401            assert!(null.clipboard.set_text(ClipboardTarget::Clipboard, "local"));
402            assert_eq!(
403                null.clipboard.text(ClipboardTarget::Clipboard).as_deref(),
404                Some("local")
405            );
406            assert!(
407                !null
408                    .clipboard
409                    .set_shared_text(ClipboardTarget::Clipboard, "secret"),
410                "an in-process buffer must not claim a shared copy"
411            );
412            assert!(
413                !null.clipboard.set_secret_text("secret"),
414                "an in-process buffer must not claim a secret copy"
415            );
416            assert_eq!(
417                null.opener
418                    .open("https://example.invalid")
419                    .unwrap_err()
420                    .kind(),
421                std::io::ErrorKind::Unsupported
422            );
423            assert!(matches!(
424                null.files.pick(PickRequest::open("Open", "Open")).recv(),
425                Ok(PortalOutcome::Failed(_))
426            ));
427            assert!(matches!(
428                null.files.launch(LaunchRequest::open("/tmp/x")).recv(),
429                Ok(LaunchOutcome::Failed(_))
430            ));
431            assert_eq!(
432                null.notifications.withdraw("tag"),
433                Err(NotifyError::Unavailable)
434            );
435            assert!(
436                null.media_session
437                    .start(MprisConfig::new("app", "App"), PlayerSnapshot::default())
438                    .is_none()
439            );
440        }
441
442        {
443            let (outer, outer_record) = ProcessServices::recording();
444            let (inner, inner_record) = ProcessServices::recording();
445            scoped(&outer, || {
446                let _ = current().opener.open("outer://1");
447                scoped(&inner, || {
448                    let _ = current().opener.open("inner://1");
449                });
450                let _ = current().opener.open("outer://2");
451            });
452            assert_eq!(outer_record.opened_uris(), ["outer://1", "outer://2"]);
453            assert_eq!(inner_record.opened_uris(), ["inner://1"]);
454        }
455
456        {
457            let (services, record) = ProcessServices::recording();
458            let depth = || SCOPES.with(|scopes| scopes.borrow().len());
459            let before = depth();
460            let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
461                scoped(&services, || panic!("dispatch failed"));
462            }));
463            assert!(unwound.is_err());
464            assert_eq!(depth(), before);
465            assert!(record.opened_uris().is_empty());
466        }
467    }
468}