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`, `ui::platform::try_os_open`, …) 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`, `portal::open_uri`,
337/// `tilo_clipboard::current`, `tts::current_speaker`, …) reach [`current`]. Runs before any
338/// services other 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    tilo_clipboard::install_resolver(|| current().clipboard);
345    tts::install_speaker_resolver(|| current().speech.make());
346}
347
348/// The services effects on this thread should reach right now; see the
349/// module docs for the resolution order.
350pub fn current() -> ProcessServices {
351    static NULL: OnceLock<ProcessServices> = OnceLock::new();
352    if let Some(scoped) = SCOPES.with(|scopes| scopes.borrow().last().cloned()) {
353        return scoped;
354    }
355    if let Some(installed) = installed_default() {
356        return installed;
357    }
358    NULL.get_or_init(ProcessServices::null).clone()
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use crate::clipboard::ClipboardTarget;
365    use crate::portal::{
366        LaunchOutcome, LaunchRequest, MultiOutcome, OpenFileOutcome, PickRequest, PortalOutcome,
367    };
368
369    /// A request reaches whatever process is current: a recording process answers
370    /// immediately, so a test never opens a chooser on the user's screen.
371    #[test]
372    fn requests_reach_the_current_host() {
373        let (services, recorder) = ProcessServices::recording();
374        recorder.respond_to_pick(PortalOutcome::Opened("/tmp/a.qvp".into()));
375        scoped(&services, || {
376            let single = PickRequest::open("Open", "Open").send();
377            assert_eq!(
378                single.try_recv(),
379                Ok(PortalOutcome::Opened("/tmp/a.qvp".into()))
380            );
381            let save = PickRequest::save("Save", "Save", "x.qvp").send();
382            assert_eq!(save.try_recv(), Ok(PortalOutcome::Cancelled));
383            let many = PickRequest::open_multiple("Import", "Import").send_multiple();
384            assert_eq!(many.try_recv(), Ok(MultiOutcome::Cancelled));
385            let descriptor = PickRequest::open("Open", "Open").send_open_handle();
386            assert!(matches!(
387                descriptor.try_recv(),
388                Ok(OpenFileOutcome::Cancelled)
389            ));
390            let launch = LaunchRequest::reveal("/tmp/a.qvp").send();
391            assert_eq!(launch.try_recv(), Ok(LaunchOutcome::Opened));
392            assert!(crate::portal::open_uri("tilo://recorded").is_ok());
393        });
394        assert_eq!(recorder.pick_requests().len(), 4);
395        assert_eq!(recorder.launch_requests().len(), 1);
396        assert_eq!(recorder.opened_uris(), ["tilo://recorded"]);
397    }
398
399    #[test]
400    fn host_services_are_inert_and_scopes_nest_and_restore_even_on_panic() {
401        {
402            let null = ProcessServices::null();
403            assert!(null.clipboard.set_text(ClipboardTarget::Clipboard, "local"));
404            assert_eq!(
405                null.clipboard.text(ClipboardTarget::Clipboard).as_deref(),
406                Some("local")
407            );
408            assert!(
409                !null
410                    .clipboard
411                    .set_shared_text(ClipboardTarget::Clipboard, "secret"),
412                "an in-process buffer must not claim a shared copy"
413            );
414            assert!(
415                !null.clipboard.set_secret_text("secret"),
416                "an in-process buffer must not claim a secret copy"
417            );
418            assert_eq!(
419                null.opener
420                    .open("https://example.invalid")
421                    .unwrap_err()
422                    .kind(),
423                std::io::ErrorKind::Unsupported
424            );
425            assert!(matches!(
426                null.files.pick(PickRequest::open("Open", "Open")).recv(),
427                Ok(PortalOutcome::Failed(_))
428            ));
429            assert!(matches!(
430                null.files.launch(LaunchRequest::open("/tmp/x")).recv(),
431                Ok(LaunchOutcome::Failed(_))
432            ));
433            assert_eq!(
434                null.notifications.withdraw("tag"),
435                Err(NotifyError::Unavailable)
436            );
437            assert!(
438                null.media_session
439                    .start(MprisConfig::new("app", "App"), PlayerSnapshot::default())
440                    .is_none()
441            );
442        }
443
444        {
445            let (outer, outer_record) = ProcessServices::recording();
446            let (inner, inner_record) = ProcessServices::recording();
447            scoped(&outer, || {
448                let _ = current().opener.open("outer://1");
449                scoped(&inner, || {
450                    let _ = current().opener.open("inner://1");
451                });
452                let _ = current().opener.open("outer://2");
453            });
454            assert_eq!(outer_record.opened_uris(), ["outer://1", "outer://2"]);
455            assert_eq!(inner_record.opened_uris(), ["inner://1"]);
456        }
457
458        {
459            let (services, record) = ProcessServices::recording();
460            let depth = || SCOPES.with(|scopes| scopes.borrow().len());
461            let before = depth();
462            let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
463                scoped(&services, || panic!("dispatch failed"));
464            }));
465            assert!(unwound.is_err());
466            assert_eq!(depth(), before);
467            assert!(record.opened_uris().is_empty());
468        }
469    }
470}