tilo-process-services 0.5.2

The services an app borrows from its process.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Process services that record every effect instead of performing it — for
//! tests, and for any process that must observe an app without letting it reach
//! the desktop.

use std::collections::VecDeque;
use std::sync::{Arc, Mutex, MutexGuard};

use super::{
    FilePicker, LocationProvider, MediaSession, MediaSessionFactory, MediaSessionPublisher,
    Notification, Notifier, NotifyError, ProcessServices, ScreenCaptureProvider, SpeechFactory,
    UriOpener, answered,
};
use crate::capture::{ScreenCaptureChannel, ScreenCaptureOutcome, ScreenCaptureRequest};
use crate::clipboard::{
    ClipboardBackend, ClipboardImage, ClipboardTarget, InProcessClipboard, RichTextOffer,
};
use crate::location::{LocationChannel, LocationOutcome};
use crate::mpris::{MprisConfig, PlayerSnapshot};
use crate::portal::{
    LaunchChannel, LaunchOutcome, LaunchRequest, MultiChannel, MultiOutcome, OpenFileChannel,
    OpenFileOutcome, PickRequest, PortalChannel, PortalOutcome,
};
use tilo_lock::MutexRecover as _;

#[derive(Default)]
struct Log {
    copies: Vec<(ClipboardTarget, String)>,
    secret_copies: Vec<String>,
    /// The HTML of every formatted copy, in order; its words are among
    /// `copies`.
    rich_copies: Vec<String>,
    /// What another app last copied, when it was an image.
    clipboard_image: Option<ClipboardImage>,
    opened_uris: Vec<String>,
    pick_requests: Vec<PickRequest>,
    launch_requests: Vec<LaunchRequest>,
    pick_outcomes: VecDeque<PortalOutcome>,
    multi_outcomes: VecDeque<MultiOutcome>,
    open_file_outcomes: VecDeque<OpenFileOutcome>,
    reopen_outcomes: VecDeque<OpenFileOutcome>,
    launch_outcomes: VecDeque<LaunchOutcome>,
    utterances: Vec<tts::Utterance>,
    notifications: Vec<Notification>,
    media_sessions: Vec<MprisConfig>,
    location_requests: usize,
    screen_capture_requests: Vec<ScreenCaptureRequest>,
    screen_capture_outcomes: VecDeque<ScreenCaptureOutcome>,
    location_outcomes: VecDeque<LocationOutcome>,
    published: Vec<PlayerSnapshot>,
}

/// What a [`ProcessServices::recording`] process was asked to do, and the answers
/// it will give.
///
/// Copies round-trip through an in-process clipboard; pickers and launches
/// answer queued outcomes, then `Cancelled` (launches: `Opened`); location
/// requests answer queued fixes, then `Unavailable`; screen-capture requests
/// answer queued outcomes, then `Cancelled`; URIs, utterances
/// and notifications are recorded; media sessions start and record what the
/// player publishes.
#[derive(Clone, Default)]
pub struct ProcessRecorder {
    log: Arc<Mutex<Log>>,
}

impl ProcessRecorder {
    fn log(&self) -> MutexGuard<'_, Log> {
        self.log.lock_recover()
    }

    /// Every text copy, in order.
    pub fn copies(&self) -> Vec<(ClipboardTarget, String)> {
        self.log().copies.clone()
    }

    /// The HTML of every formatted copy, in order. Their words are among
    /// [`Self::copies`].
    pub fn rich_copies(&self) -> Vec<String> {
        self.log().rich_copies.clone()
    }

    /// Every secret copy, in order. These are not among [`Self::copies`].
    pub fn secret_copies(&self) -> Vec<String> {
        self.log().secret_copies.clone()
    }

    /// Another app copies `image`, as a screenshot tool does: the next paste
    /// reads it, until something copies text.
    pub fn copy_image_elsewhere(&self, image: ClipboardImage) {
        self.log().clipboard_image = Some(image);
    }

    /// Every URI handed to the opener, in order.
    pub fn opened_uris(&self) -> Vec<String> {
        self.log().opened_uris.clone()
    }

    /// Every chooser request, in order.
    pub fn pick_requests(&self) -> Vec<PickRequest> {
        self.log().pick_requests.clone()
    }

    /// Every desktop-open request, in order.
    pub fn launch_requests(&self) -> Vec<LaunchRequest> {
        self.log().launch_requests.clone()
    }

    /// Answer the next single-file chooser with `outcome`.
    pub fn respond_to_pick(&self, outcome: PortalOutcome) {
        self.log().pick_outcomes.push_back(outcome);
    }

    /// Answer the next multi-select chooser with `outcome`.
    pub fn respond_to_pick_multiple(&self, outcome: MultiOutcome) {
        self.log().multi_outcomes.push_back(outcome);
    }

    /// Answer the next descriptor-retaining chooser with `outcome`.
    pub fn respond_to_open_file(&self, outcome: OpenFileOutcome) {
        self.log().open_file_outcomes.push_back(outcome);
    }

    /// Answer the next reopen of a reference with `outcome`: what a window restored on the file
    /// it showed waits for.
    pub fn respond_to_reopen(&self, outcome: OpenFileOutcome) {
        self.log().reopen_outcomes.push_back(outcome);
    }

    /// Answer the next desktop-open request with `outcome`.
    pub fn respond_to_launch(&self, outcome: LaunchOutcome) {
        self.log().launch_outcomes.push_back(outcome);
    }

    /// Answer the next location request with `outcome`.
    pub fn respond_to_location(&self, outcome: LocationOutcome) {
        self.log().location_outcomes.push_back(outcome);
    }

    /// How many location fixes were requested.
    pub fn location_requests(&self) -> usize {
        self.log().location_requests
    }

    /// Every screen-capture request, in order.
    pub fn screen_capture_requests(&self) -> Vec<ScreenCaptureRequest> {
        self.log().screen_capture_requests.clone()
    }

    /// Everything the screen reader was asked to say, in order.
    pub fn utterances(&self) -> Vec<tts::Utterance> {
        self.log().utterances.clone()
    }

    /// Every notification shown, in order.
    pub fn notifications(&self) -> Vec<Notification> {
        self.log().notifications.clone()
    }

    /// The configuration of every media session started, in order.
    pub fn media_sessions(&self) -> Vec<MprisConfig> {
        self.log().media_sessions.clone()
    }

    /// Every player state published to a media session, in order.
    pub fn published_media_state(&self) -> Vec<PlayerSnapshot> {
        self.log().published.clone()
    }
}

impl ProcessServices {
    /// Services that record every effect in the returned [`ProcessRecorder`].
    pub fn recording() -> (Self, ProcessRecorder) {
        let recorder = ProcessRecorder::default();
        let services = Self {
            clipboard: Arc::new(RecordingClipboard {
                recorder: recorder.clone(),
                buffer: InProcessClipboard::default(),
            }),
            files: Arc::new(recorder.clone()),
            opener: Arc::new(recorder.clone()),
            speech: Arc::new(recorder.clone()),
            notifications: Arc::new(recorder.clone()),
            media_session: Arc::new(recorder.clone()),
            location: Arc::new(recorder.clone()),
            screen_capture: Arc::new(recorder.clone()),
            secrets: Arc::new(super::InProcessSecrets::default()),
        };
        (services, recorder)
    }
}

struct RecordingClipboard {
    recorder: ProcessRecorder,
    buffer: InProcessClipboard,
}

impl ClipboardBackend for RecordingClipboard {
    fn set_text(&self, target: ClipboardTarget, text: &str) -> bool {
        {
            let mut log = self.recorder.log();
            log.copies.push((target, text.to_string()));
            if target == ClipboardTarget::Clipboard {
                log.clipboard_image = None;
            }
        }
        self.buffer.set_text(target, text)
    }

    fn set_secret_text(&self, text: &str) -> bool {
        {
            let mut log = self.recorder.log();
            log.secret_copies.push(text.to_string());
            log.clipboard_image = None;
        }
        self.buffer.set_text(ClipboardTarget::Clipboard, text)
    }

    fn set_rich_text(&self, html: &str, plain: &str) -> bool {
        {
            let mut log = self.recorder.log();
            log.copies
                .push((ClipboardTarget::Clipboard, plain.to_string()));
            log.rich_copies.push(html.to_string());
            log.clipboard_image = None;
        }
        self.buffer.set_rich_text(html, plain)
    }

    fn rich_text(&self) -> Option<RichTextOffer> {
        if self.recorder.log().clipboard_image.is_some() {
            return None;
        }
        self.buffer.rich_text()
    }

    fn text(&self, target: ClipboardTarget) -> Option<String> {
        if target == ClipboardTarget::Clipboard && self.recorder.log().clipboard_image.is_some() {
            return None;
        }
        self.buffer.text(target)
    }

    fn image(&self) -> Option<ClipboardImage> {
        self.recorder.log().clipboard_image.clone()
    }

    fn name(&self) -> &'static str {
        "recording"
    }
}

impl FilePicker for ProcessRecorder {
    fn pick(&self, request: PickRequest) -> PortalChannel {
        let mut log = self.log();
        log.pick_requests.push(request);
        answered(
            log.pick_outcomes
                .pop_front()
                .unwrap_or(PortalOutcome::Cancelled),
        )
    }

    fn pick_multiple(&self, request: PickRequest) -> MultiChannel {
        let mut log = self.log();
        log.pick_requests.push(request);
        answered(
            log.multi_outcomes
                .pop_front()
                .unwrap_or(MultiOutcome::Cancelled),
        )
    }

    fn open_handle(&self, request: PickRequest) -> OpenFileChannel {
        let mut log = self.log();
        log.pick_requests.push(request);
        answered(
            log.open_file_outcomes
                .pop_front()
                .unwrap_or(OpenFileOutcome::Cancelled),
        )
    }

    fn reopen(&self, _reference: &std::path::Path, _write: bool) -> OpenFileChannel {
        let mut log = self.log();
        answered(
            log.reopen_outcomes
                .pop_front()
                .unwrap_or(OpenFileOutcome::Cancelled),
        )
    }

    fn launch(&self, request: LaunchRequest) -> LaunchChannel {
        let mut log = self.log();
        log.launch_requests.push(request);
        answered(
            log.launch_outcomes
                .pop_front()
                .unwrap_or(LaunchOutcome::Opened),
        )
    }
}

impl UriOpener for ProcessRecorder {
    fn open(&self, uri: &str) -> std::io::Result<()> {
        self.log().opened_uris.push(uri.to_string());
        Ok(())
    }
}

struct RecordingSpeaker {
    recorder: ProcessRecorder,
}

impl tts::Speaker for RecordingSpeaker {
    fn speak_utterance(&mut self, utterance: tts::Utterance) {
        self.recorder.log().utterances.push(utterance);
    }

    fn stop(&mut self) {}

    fn set_rate(&mut self, _rate: f32) {}

    fn set_voice(&mut self, _voice: &str) {}

    fn is_speaking(&self) -> bool {
        false
    }

    fn backend_name(&self) -> &'static str {
        "recording"
    }
}

impl SpeechFactory for ProcessRecorder {
    fn make(&self) -> Box<dyn tts::Speaker> {
        Box::new(RecordingSpeaker {
            recorder: self.clone(),
        })
    }
}

impl Notifier for ProcessRecorder {
    fn show(&self, notification: &Notification) -> Result<(), NotifyError> {
        self.log().notifications.push(notification.clone());
        Ok(())
    }

    fn withdraw(&self, tag: &str) -> Result<(), NotifyError> {
        self.log().notifications.retain(|shown| shown.tag != tag);
        Ok(())
    }
}

impl MediaSessionPublisher for ProcessRecorder {
    fn publish(&mut self, snapshot: PlayerSnapshot) {
        self.log().published.push(snapshot);
    }
}

impl MediaSessionFactory for ProcessRecorder {
    fn start(&self, config: MprisConfig, _initial: PlayerSnapshot) -> Option<MediaSession> {
        self.log().media_sessions.push(config);
        // The sender is dropped: a recording process never sends commands.
        let (_commands, receiver) = std::sync::mpsc::channel();
        Some(MediaSession {
            commands: receiver,
            publisher: Box::new(self.clone()),
        })
    }
}

impl LocationProvider for ProcessRecorder {
    fn locate(&self) -> LocationChannel {
        let mut log = self.log();
        log.location_requests = log.location_requests.saturating_add(1);
        answered(
            log.location_outcomes
                .pop_front()
                .unwrap_or_else(|| LocationOutcome::Unavailable("no location queued".to_string())),
        )
    }
}

impl ScreenCaptureProvider for ProcessRecorder {
    fn request(&self, request: ScreenCaptureRequest) -> ScreenCaptureChannel {
        let mut log = self.log();
        log.screen_capture_requests.push(request);
        answered(
            log.screen_capture_outcomes
                .pop_front()
                .unwrap_or(ScreenCaptureOutcome::Cancelled),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn media_sessions_record_published_state() {
        let (services, recorder) = ProcessServices::recording();
        let mut handle = super::super::scoped(&services, || {
            crate::mpris::MprisHandle::spawn(
                MprisConfig::new("player", "Player"),
                PlayerSnapshot::default(),
            )
        });
        assert!(handle.is_active());
        handle.publish(PlayerSnapshot {
            title: "Now playing".into(),
            ..PlayerSnapshot::default()
        });
        assert_eq!(recorder.media_sessions().len(), 1);
        assert_eq!(recorder.published_media_state()[0].title, "Now playing");
    }
}