Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-daemon/src/shortcuts/mod.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! Super Voice's keyboard shortcuts, which the daemon owns: `/v1/shortcuts`.
3
//!
4
//! The daemon owns them so every client sees the same answer, and so a client
5
//! that cannot write desktop settings, like a sandboxed app, can still add
6
//! one. How a shortcut gets onto the desktop depends on the desktop:
7
//!
8
//! 1. COSMIC: an entry in its custom-shortcuts file
9
//!    ([`super_voice_shared::cosmic_shortcuts`]), which runs `voice`.
10
//! 2. A desktop with the `GlobalShortcuts` portal, such as KDE Plasma, GNOME
11
//!    or Hyprland: the daemon binds it in a portal session it holds
12
//!    ([`portal`]), and runs the same `voice` when it is pressed. The ones
13
//!    the user added are in the config, and bound again at every start. The
14
//!    portal cannot unbind one: on KDE Plasma, KDE's shortcut service is told
15
//!    to forget it, on GNOME it is taken out of GNOME's record of the app's
16
//!    shortcuts, and elsewhere the user removes it in the desktop's settings.
17
//!    GNOME holds Super Voice's keys for input-source switching, so there the
18
//!    daemon takes them over first, as Dictate's entry does on COSMIC
19
//!    ([`gnome`]). Hyprland's portal binds no keys: the daemon binds them in
20
//!    Hyprland's config, in a file of its own the config loads
21
//!    ([`hyprland`]), and where it cannot, the user binds them there, to the
22
//!    global shortcut the list names.
23
//! 3. Anything else: the user binds the command in the desktop's settings.
24
//!
25
//! Contract: `docs/protocol/endpoints/v1/shortcuts.md`.
26
27
#[cfg(target_os = "linux")]
28
mod gnome;
29
pub mod hyprland;
30
pub mod pause;
31
#[cfg(target_os = "linux")]
32
pub mod portal;
33
34
use log::{info, warn};
35
use super_voice_shared::cosmic_shortcuts::{self, Status};
36
use super_voice_shared::hyprland_shortcuts::{self, Format};
37
use super_voice_shared::models::shortcuts::{
38
    Shortcut, ShortcutId, ShortcutList, ShortcutMethod, ShortcutState,
39
};
40
41
/// Why a shortcut could not be added or removed.
42
#[derive(Debug, PartialEq, Eq)]
43
pub enum Error {
44
    /// Another shortcut holds its keys.
45
    KeysTaken,
46
    /// The user said no in the desktop's dialog.
47
    Refused,
48
    /// This desktop has no method the daemon can add it with.
49
    Unsupported,
50
    /// The desktop's settings could not be changed.
51
    Write(String),
52
}
53
54
/// One shortcut the desktop has bound through the portal, and its keys as the
55
/// desktop describes them.
56
#[cfg(target_os = "linux")]
57
pub use portal::Bound;
58
59
/// One shortcut the desktop has bound through the portal. Only Linux has the
60
/// portal, so elsewhere there never is one.
61
#[cfg(not(target_os = "linux"))]
62
#[derive(Debug, Clone, PartialEq, Eq)]
63
pub struct Bound {
64
    pub id: ShortcutId,
65
    pub keys: String,
66
}
67
68
/// The daemon's hold on the desktop's shortcuts: how it puts them there, and
69
/// on a desktop with the portal, the session that holds them.
70
#[derive(Default)]
71
pub struct Shortcuts {
72
    /// The method, once one is found. `manual` is not kept: the portal may
73
    /// only have been slow to start, and asking again is cheap.
74
    method: std::sync::OnceLock<ShortcutMethod>,
75
    /// Held across a whole change, so two at once cannot each bind the set
76
    /// the other is replacing.
77
    changing: tokio::sync::Mutex<()>,
78
    #[cfg(target_os = "linux")]
79
    session: tokio::sync::Mutex<Option<portal::Session>>,
80
    /// The app id the portal knew the last session by, when the daemon could
81
    /// tell: on Hyprland, what a shortcut's global shortcut is named under,
82
    /// even once its session is closed.
83
    #[cfg(target_os = "linux")]
84
    app_id: std::sync::Mutex<Option<String>>,
85
    /// Whether the macOS shortcut listener is paused while a client records
86
    /// new keys. See [`pause`].
87
    pub pause: pause::Pause,
88
}
89
90
impl Shortcuts {
91
    /// How the daemon puts shortcuts on the desktop it runs in. Only a Linux
92
    /// desktop takes them from the daemon: anywhere else it is `manual`.
93
    // `allow`, not `expect`: clippy 1.98 files these under `unused_async_trait_impl`
94
    // and later releases under `unused_async`, so either `expect` goes unfulfilled
95
    // on some toolchain.
96
    #[cfg_attr(
97
        not(target_os = "linux"),
98
        allow(
99
            clippy::unused_async,
100
            clippy::unused_async_trait_impl,
101
            reason = "detecting COSMIC and the portal is Linux's: elsewhere there is nothing to await"
102
        )
103
    )]
104
96
    pub async fn method(&self) -> ShortcutMethod {
105
96
        if let Some(method) = self.method.get() {
106
70
            return *method;
107
26
        }
108
        #[cfg(target_os = "linux")]
109
26
        let method = detect_method().await;
110
        #[cfg(not(target_os = "linux"))]
111
        let method = ShortcutMethod::Manual;
112
26
        if method == ShortcutMethod::Manual {
113
2
            log::debug!(
"Keyboard shortcuts: manual"0
);
114
24
        } else if self.method.set(method).is_ok() {
115
24
            info!("Keyboard shortcuts: {method}");
116
0
        }
117
26
        method
118
96
    }
119
120
    /// Taken across a change to the shortcuts.
121
45
    pub async fn changing(&self) -> tokio::sync::MutexGuard<'_, ()> {
122
45
        self.changing.lock().await
123
45
    }
124
125
    /// Every shortcut and where it stands.
126
51
    pub async fn list(&self) -> ShortcutList {
127
51
        let method = self.method().await;
128
51
        let cosmic_file = if method == ShortcutMethod::Cosmic {
129
6
            tokio::task::spawn_blocking(cosmic_file)
130
6
                .await
131
                .unwrap_or_default()
132
        } else {
133
45
            String::new()
134
        };
135
51
        let bound = self.bound().await;
136
51
        let app_id = self.app_id();
137
51
        let desktop = desktop_name();
138
        #[cfg(target_os = "linux")]
139
51
        let hypr = if method == ShortcutMethod::Portal && 
is_hyprland(Some(&desktop))44
{
140
20
            Some(hyprland_view().await)
141
        } else {
142
31
            None
143
        };
144
        #[cfg(not(target_os = "linux"))]
145
        let hypr: Option<hyprland::View> = None;
146
51
        list_from(
147
51
            method,
148
51
            &desktop,
149
51
            &cosmic_file,
150
51
            &bound,
151
51
            app_id.as_deref(),
152
51
            hypr.as_ref(),
153
51
        )
154
51
    }
155
156
    /// The app id the portal knew the last session by, when the daemon could
157
    /// tell. None before a session was opened, and off Linux.
158
    #[cfg_attr(
159
        not(target_os = "linux"),
160
        expect(clippy::unused_self, reason = "the portal session it reads is Linux's")
161
    )]
162
63
    fn app_id(&self) -> Option<String> {
163
        #[cfg(target_os = "linux")]
164
        {
165
63
            self.app_id
166
63
                .lock()
167
63
                .unwrap_or_else(std::sync::PoisonError::into_inner)
168
63
                .clone()
169
        }
170
        #[cfg(not(target_os = "linux"))]
171
        None
172
63
    }
173
174
    /// Open a portal session ([`open_session`]), and keep the app id the
175
    /// portal knows it by.
176
    #[cfg(target_os = "linux")]
177
33
    async fn open_session(&self) -> Result<portal::Session, Error> {
178
33
        let session = open_session().await
?0
;
179
33
        *self
180
33
            .app_id
181
33
            .lock()
182
33
            .unwrap_or_else(std::sync::PoisonError::into_inner) =
183
33
            session.app_id().map(str::to_string);
184
33
        Ok(session)
185
33
    }
186
187
    /// The shortcuts bound through the portal now: none without a session.
188
    // `allow`, not `expect`: clippy 1.98 files these under `unused_async_trait_impl`
189
    // and later releases under `unused_async`, so either `expect` goes unfulfilled
190
    // on some toolchain.
191
    #[cfg_attr(
192
        not(target_os = "linux"),
193
        allow(
194
            clippy::unused_async,
195
            clippy::unused_async_trait_impl,
196
            reason = "the portal session it awaits is Linux's"
197
        )
198
    )]
199
51
    async fn bound(&self) -> Vec<Bound> {
200
        #[cfg(target_os = "linux")]
201
51
        if let Some(session) = self.session.lock().await.as_ref() {
202
31
            let listed = session.list().await.unwrap_or_else(|e| 
{0
203
0
                warn!("Could not list the bound shortcuts: {e}");
204
0
                Vec::new()
205
0
            });
206
31
            return held(&desktop_name(), listed, &session.bound_at_bind());
207
20
        }
208
20
        Vec::new()
209
51
    }
210
211
    /// Bind exactly `set` through the portal, in a new session that replaces
212
    /// the one held, or close it when `set` is empty. Answers what the desktop
213
    /// bound.
214
    ///
215
    /// # Errors
216
    ///
217
    /// [`Error::Refused`] when the user turned every one down,
218
    /// [`Error::Write`] when the portal failed, and [`Error::Unsupported`]
219
    /// where there is no portal.
220
    // `allow`, not `expect`: clippy 1.98 files these under `unused_async_trait_impl`
221
    // and later releases under `unused_async`, so either `expect` goes unfulfilled
222
    // on some toolchain.
223
    #[cfg_attr(
224
        not(target_os = "linux"),
225
        allow(
226
            clippy::unused_async,
227
            clippy::unused_async_trait_impl,
228
            reason = "the portal session it awaits is Linux's"
229
        )
230
    )]
231
38
    pub async fn bind(&self, set: &[ShortcutId]) -> Result<Vec<Bound>, Error> {
232
        #[cfg(target_os = "linux")]
233
        {
234
38
            let mut held = self.session.lock().await;
235
38
            if let Some(old) = held.take() {
236
17
                old.close().await;
237
21
            }
238
38
            if set.is_empty() {
239
8
                return Ok(Vec::new());
240
30
            }
241
30
            let session = self.open_session().await
?0
;
242
30
            let bound = session.bind(set).await.map_err(Error::from)
?2
;
243
28
            *held = Some(session);
244
28
            Ok(bound)
245
        }
246
        #[cfg(not(target_os = "linux"))]
247
        {
248
            let _ = set;
249
            Err(Error::Unsupported)
250
        }
251
38
    }
252
253
    /// [`Shortcuts::bind`] `set`, which the user just added `id` to. Answers
254
    /// what the desktop bound, without `id` when the user turned it down.
255
    ///
256
    /// KDE Plasma takes its dialog's Cancel as binding the shortcut with no
257
    /// keys, where it does nothing. So on KDE one bound with none is turned
258
    /// down: it is bound no more, and KDE is told to forget it, so adding it
259
    /// again asks again.
260
    ///
261
    /// # Errors
262
    ///
263
    /// As [`Shortcuts::bind`], and [`Error::Write`] when KDE could not be
264
    /// told to forget one turned down.
265
26
    pub async fn bind_added(
266
26
        &self,
267
26
        set: &[ShortcutId],
268
26
        id: ShortcutId,
269
26
    ) -> Result<Vec<Bound>, Error> {
270
26
        let bound = self.bind(set).await
?2
;
271
        #[cfg(target_os = "linux")]
272
24
        if on_kde() && 
bound.iter()8
.any(|b|
b.id == id10
&&
b.keys.is_empty()8
) {
273
1
            info!("KDE bound shortcut {id} with no keys: the user turned it down");
274
1
            let bound = self.bind(&with(set, id, false)).await
?0
;
275
1
            forget_on_kde(id).await
?0
;
276
1
            return Ok(bound);
277
23
        }
278
        #[cfg(not(target_os = "linux"))]
279
        let _ = id;
280
23
        Ok(bound)
281
26
    }
282
283
    /// [`Shortcuts::bind`] `set`, which the user just took `id` out of.
284
    ///
285
    /// The desktop is told to forget `id` too, so it leaves the desktop's
286
    /// settings and frees its keys: on KDE Plasma by KDE's shortcut service,
287
    /// and on GNOME by taking it out of GNOME's record of the app's
288
    /// shortcuts. Hyprland keeps its registration until it quits, but its
289
    /// presses reach Super Voice no more; the daemon takes its bind out of
290
    /// Hyprland's config after ([`Shortcuts::unbind_keys_on_hyprland`]).
291
    /// Elsewhere the desktop keeps it in its settings until the user removes
292
    /// it there.
293
    ///
294
    /// # Errors
295
    ///
296
    /// As [`Shortcuts::bind`], and [`Error::Write`] when the desktop could
297
    /// not be told to forget it.
298
9
    pub async fn bind_removed(
299
9
        &self,
300
9
        set: &[ShortcutId],
301
9
        id: ShortcutId,
302
9
    ) -> Result<Vec<Bound>, Error> {
303
9
        let bound = self.bind(set).await
?0
;
304
        #[cfg(target_os = "linux")]
305
9
        if on_kde() {
306
2
            forget_on_kde(id).await
?0
;
307
7
        } else if on_gnome() {
308
4
            forget_on_gnome(id).await
?0
;
309
3
        }
310
        #[cfg(not(target_os = "linux"))]
311
        let _ = id;
312
9
        Ok(bound)
313
9
    }
314
315
    /// Bind the shortcuts `saved` at a start, and answer the ones kept: one
316
    /// the user removed in the desktop's settings is not, so the page offers
317
    /// to add it again.
318
    ///
319
    /// 1. KDE Plasma lists, in a new session, the shortcuts it kept, so only
320
    ///    those are bound.
321
    /// 2. GNOME and Hyprland list nothing until a bind, so every saved one
322
    ///    is bound. GNOME asks again, in its dialog, for one removed in its
323
    ///    settings: one the user turns down there is not kept.
324
    ///
325
    /// # Errors
326
    ///
327
    /// As [`Shortcuts::bind`].
328
    // `allow`, not `expect`: clippy 1.98 files these under `unused_async_trait_impl`
329
    // and later releases under `unused_async`, so either `expect` goes unfulfilled
330
    // on some toolchain.
331
    #[cfg_attr(
332
        not(target_os = "linux"),
333
        allow(
334
            clippy::unused_async,
335
            clippy::unused_async_trait_impl,
336
            reason = "the portal session it awaits is Linux's"
337
        )
338
    )]
339
3
    pub async fn bind_saved(&self, saved: &[ShortcutId]) -> Result<Vec<ShortcutId>, Error> {
340
        #[cfg(target_os = "linux")]
341
        {
342
3
            let mut held = self.session.lock().await;
343
3
            if let Some(old) = held.take() {
344
0
                old.close().await;
345
3
            }
346
3
            let session = self.open_session().await
?0
;
347
            // Only KDE Plasma lists, before a bind, the shortcuts it kept.
348
3
            let asked = if on_kde() {
349
2
                match session.list().await {
350
2
                    Ok(listed) => still_kept(saved, &listed),
351
                    Err(e) => {
352
0
                        warn!("Could not ask which shortcuts the desktop kept: {e:#}");
353
0
                        saved.to_vec()
354
                    }
355
                }
356
            } else {
357
1
                saved.to_vec()
358
            };
359
3
            if asked.is_empty() {
360
0
                session.close().await;
361
0
                return Ok(asked);
362
3
            }
363
3
            match session.bind(&asked).await {
364
                Ok(bound) => {
365
3
                    *held = Some(session);
366
3
                    Ok(still_kept(&asked, &bound))
367
                }
368
                Err(portal::BindError::Cancelled) => {
369
0
                    session.close().await;
370
0
                    Ok(Vec::new())
371
                }
372
0
                Err(e) => Err(e.into()),
373
            }
374
        }
375
        #[cfg(not(target_os = "linux"))]
376
        {
377
            let _ = saved;
378
            Err(Error::Unsupported)
379
        }
380
3
    }
381
}
382
383
/// The global shortcut `id` is under `app_id`: `super-voice-app:dictate`.
384
52
fn global_name(app_id: &str, id: ShortcutId) -> String {
385
52
    format!("{app_id}:{id}")
386
52
}
387
388
/// Run `work` off the async runtime: it reads and writes files.
389
#[cfg(target_os = "linux")]
390
27
async fn blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> Option<T> {
391
27
    tokio::task::spawn_blocking(work).await.ok()
392
27
}
393
394
/// What the list reads from Hyprland: its binds, and whether the daemon can
395
/// bind keys in its config.
396
#[cfg(target_os = "linux")]
397
32
async fn hyprland_view() -> hyprland::View {
398
32
    let Some(found) = hyprland::Hyprland::find() else {
399
18
        log::debug!(
"Hyprland: no instance to ask"0
);
400
18
        return hyprland::View {
401
18
            binds: None,
402
18
            format: Format::Lua,
403
18
            writable: false,
404
18
        };
405
    };
406
14
    let binds = found
407
14
        .binds()
408
14
        .await
409
0
        .inspect_err(|e| log::debug!("Hyprland: could not read its binds: {e:#}"))
410
        .ok();
411
14
    let (format, fit) = blocking(move || match found.config() {
412
14
        Some(config) => (config.format(), config.check()),
413
0
        None => (Format::Lua, Err(hyprland_shortcuts::Unfit::Missing)),
414
14
    })
415
14
    .await
416
14
    .unwrap_or((Format::Lua, Err(hyprland_shortcuts::Unfit::Missing)));
417
14
    if let Err(why) = &fit {
418
2
        log::debug!("Hyprland: the user binds the keys, since {
why0
}");
419
12
    }
420
    hyprland::View {
421
14
        binds: binds.clone(),
422
14
        format,
423
14
        writable: binds.is_some() && fit.is_ok(),
424
    }
425
32
}
426
427
impl Shortcuts {
428
    /// On Hyprland, whether another bind holds shortcut `id`'s keys, where
429
    /// the daemon binds them in its config. Elsewhere false.
430
    // `allow`, not `expect`: see `Shortcuts::method`.
431
    #[cfg_attr(
432
        not(target_os = "linux"),
433
        allow(
434
            clippy::unused_async,
435
            clippy::unused_async_trait_impl,
436
            reason = "Hyprland is Linux's: elsewhere there is nothing to await"
437
        )
438
    )]
439
27
    pub async fn keys_taken_on_hyprland(&self, id: ShortcutId) -> bool {
440
        #[cfg(target_os = "linux")]
441
27
        if is_hyprland(desktop().as_deref()) {
442
12
            return hyprland_view().await.taken(id);
443
15
        }
444
15
        let _ = id;
445
15
        false
446
27
    }
447
448
    /// On Hyprland, bind shortcut `id`'s keys to its global shortcut in
449
    /// Hyprland's config, which its portal does not, and have Hyprland
450
    /// reload it. Nothing is written when a bind runs it already, or the
451
    /// config cannot be written: the list then says the user binds it. A
452
    /// bind Hyprland does not take is put back. Elsewhere nothing.
453
    // `allow`, not `expect`: see `Shortcuts::method`.
454
    #[cfg_attr(
455
        not(target_os = "linux"),
456
        allow(
457
            clippy::unused_async,
458
            clippy::unused_async_trait_impl,
459
            reason = "Hyprland is Linux's: elsewhere there is nothing to await"
460
        )
461
    )]
462
22
    pub async fn bind_keys_on_hyprland(&self, id: ShortcutId) {
463
        #[cfg(target_os = "linux")]
464
22
        if is_hyprland(desktop().as_deref()) {
465
11
            let Some(app_id) = self.app_id() else {
466
1
                info!("Hyprland: no app id known for shortcut {id}: the user binds it");
467
1
                return;
468
            };
469
10
            bind_on_hyprland(id, &global_name(&app_id, id)).await;
470
11
        }
471
        #[cfg(not(target_os = "linux"))]
472
        let _ = id;
473
22
    }
474
475
    /// On Hyprland, take shortcut `id`'s bind out of Super Voice's file in
476
    /// Hyprland's config, and have Hyprland reload it. Elsewhere nothing.
477
    ///
478
    /// # Errors
479
    ///
480
    /// [`Error::Write`] when the file could not be written.
481
    // `allow`, not `expect`: see `Shortcuts::method`.
482
    #[cfg_attr(
483
        not(target_os = "linux"),
484
        allow(
485
            clippy::unused_async,
486
            clippy::unused_async_trait_impl,
487
            reason = "Hyprland is Linux's: elsewhere there is nothing to await"
488
        )
489
    )]
490
9
    pub async fn unbind_keys_on_hyprland(&self, id: ShortcutId) -> Result<(), Error> {
491
        #[cfg(target_os = "linux")]
492
9
        if is_hyprland(desktop().as_deref()) {
493
3
            return unbind_on_hyprland(id).await;
494
6
        }
495
6
        let _ = id;
496
6
        Ok(())
497
9
    }
498
499
    /// On Hyprland, point the binds of `ids` in Super Voice's file at the
500
    /// app id the portal knows the daemon by now: a daemon the portal knew
501
    /// by another one before wrote them under that. Elsewhere nothing.
502
    // `allow`, not `expect`: see `Shortcuts::method`.
503
    #[cfg_attr(
504
        not(target_os = "linux"),
505
        allow(
506
            clippy::unused_async,
507
            clippy::unused_async_trait_impl,
508
            reason = "Hyprland is Linux's: elsewhere there is nothing to await"
509
        )
510
    )]
511
3
    pub async fn retarget_on_hyprland(&self, ids: &[ShortcutId]) {
512
        #[cfg(target_os = "linux")]
513
3
        if is_hyprland(desktop().as_deref())
514
1
            && let Some(app_id) = self.app_id()
515
        {
516
1
            retarget_on_hyprland(ids, &app_id).await;
517
2
        }
518
        #[cfg(not(target_os = "linux"))]
519
        let _ = ids;
520
3
    }
521
}
522
523
/// [`Shortcuts::bind_keys_on_hyprland`], for the global shortcut `global`.
524
#[cfg(target_os = "linux")]
525
10
async fn bind_on_hyprland(id: ShortcutId, global: &str) {
526
10
    let Some(found) = hyprland::Hyprland::find() else {
527
5
        info!("Hyprland: no instance to bind shortcut {id} in: the user binds it");
528
5
        return;
529
    };
530
9
    let bound = |binds: &[hyprland::Bind]| hyprland::bind_for(binds, id, Some(global)).is_some();
531
5
    match found.binds().await {
532
5
        Ok(binds) if bound(&binds) => {
533
0
            info!("Hyprland: {global} is bound already");
534
0
            return;
535
        }
536
5
        Ok(_) => {}
537
        Err(e) => {
538
0
            warn!("Hyprland: could not read its binds, so {global} is not bound: {e:#}");
539
0
            return;
540
        }
541
    }
542
5
    let lookup = found.clone();
543
5
    let Some(config) = blocking(move || lookup.config()).await.flatten() else {
544
0
        info!("Hyprland: no config found to bind {global} in: the user binds it");
545
0
        return;
546
    };
547
5
    let keys = hyprland::own_keys(id);
548
5
    let writer = config.clone();
549
5
    let global_owned = global.to_string();
550
5
    let written = blocking(move || writer.add(id, &keys, &global_owned))
551
5
        .await
552
0
        .unwrap_or_else(|| {
553
0
            Err(hyprland_shortcuts::Unfit::Io(
554
0
                "the write did not run".into(),
555
0
            ))
556
0
        });
557
5
    let undo = match written {
558
4
        Ok(undo) => undo,
559
        Err(why) => {
560
1
            info!("Hyprland: not binding {global} in its config, since {why}: the user binds it");
561
1
            return;
562
        }
563
    };
564
4
    if let Err(e) = found.reload().await {
565
0
        warn!("Hyprland: could not have it reload its config: {e:#}");
566
4
    }
567
4
    let taken = found.binds().await.is_ok_and(|binds| bound(&binds));
568
4
    if taken {
569
3
        info!(
570
3
            "Hyprland: bound {global} to {} in {}",
571
3
            cosmic(id).keys(),
572
3
            config.ours().display()
573
        );
574
3
        return;
575
1
    }
576
1
    warn!(
577
1
        "Hyprland did not take the bind for {global} from {}: put back, the user binds it",
578
1
        config.ours().display()
579
    );
580
1
    if let Some(undo) = undo {
581
1
        let writer = config.clone();
582
1
        match blocking(move || writer.undo(&undo)).await {
583
1
            Some(Ok(())) => {}
584
0
            Some(Err(e)) => warn!("Hyprland: could not put its config back: {e}"),
585
0
            None => warn!("Hyprland: could not put its config back"),
586
        }
587
1
        if let Err(e) = found.reload().await {
588
0
            warn!("Hyprland: could not have it reload its config: {e:#}");
589
1
        }
590
0
    }
591
10
}
592
593
/// [`Shortcuts::unbind_keys_on_hyprland`].
594
#[cfg(target_os = "linux")]
595
3
async fn unbind_on_hyprland(id: ShortcutId) -> Result<(), Error> {
596
3
    let Some(found) = hyprland::Hyprland::find() else {
597
2
        return Ok(());
598
    };
599
1
    let lookup = found.clone();
600
1
    let Some(config) = blocking(move || lookup.config()).await.flatten() else {
601
0
        return Ok(());
602
    };
603
1
    let writer = config.clone();
604
1
    let removed = blocking(move || writer.remove(id))
605
1
        .await
606
0
        .unwrap_or_else(|| {
607
0
            Err(hyprland_shortcuts::Unfit::Io(
608
0
                "the write did not run".into(),
609
0
            ))
610
0
        });
611
1
    match removed {
612
0
        Ok(false) => Ok(()),
613
        Ok(true) => {
614
1
            info!(
615
1
                "Hyprland: took shortcut {id}'s bind out of {}",
616
1
                config.ours().display()
617
            );
618
1
            if let Err(e) = found.reload().await {
619
0
                warn!("Hyprland: could not have it reload its config: {e:#}");
620
1
            }
621
1
            Ok(())
622
        }
623
0
        Err(why) => Err(Error::Write(format!(
624
0
            "could not take shortcut {id}'s bind out of {}: {why}",
625
0
            config.ours().display()
626
0
        ))),
627
    }
628
3
}
629
630
/// [`Shortcuts::retarget_on_hyprland`].
631
#[cfg(target_os = "linux")]
632
1
async fn retarget_on_hyprland(ids: &[ShortcutId], app_id: &str) {
633
1
    let Some(found) = hyprland::Hyprland::find() else {
634
1
        return;
635
    };
636
0
    let lookup = found.clone();
637
0
    let Some(config) = blocking(move || lookup.config()).await.flatten() else {
638
0
        return;
639
    };
640
0
    let mut changed = false;
641
0
    for &id in ids {
642
0
        let global = global_name(app_id, id);
643
0
        let writer = config.clone();
644
0
        let target = global.clone();
645
0
        match blocking(move || writer.retarget(id, &target)).await {
646
            Some(Ok(Some(_))) => {
647
0
                info!("Hyprland: pointed shortcut {id}'s bind at {global}");
648
0
                changed = true;
649
            }
650
            Some(Err(e)) => {
651
0
                warn!("Hyprland: could not point shortcut {id}'s bind at {global}: {e}");
652
            }
653
0
            Some(Ok(None)) | None => {}
654
        }
655
    }
656
0
    if changed && let Err(e) = found.reload().await {
657
0
        warn!("Hyprland: could not have it reload its config: {e:#}");
658
0
    }
659
1
}
660
661
#[cfg(target_os = "linux")]
662
impl From<portal::BindError> for Error {
663
2
    fn from(e: portal::BindError) -> Self {
664
2
        match e {
665
2
            portal::BindError::Cancelled => Self::Refused,
666
0
            portal::BindError::Failed(e) => Self::Write(format!("{e:#}")),
667
        }
668
2
    }
669
}
670
671
/// A portal session on a connection of its own: the app id registered on it
672
/// is the portal's first call there. Each press runs the shortcut's command.
673
#[cfg(target_os = "linux")]
674
33
async fn open_session() -> Result<portal::Session, Error> {
675
33
    let conn = async { zbus::connection::Builder::session()
?0
.build().await }
676
33
        .await
677
0
        .map_err(|e: zbus::Error| Error::Write(e.to_string()))?;
678
33
    portal::Session::open(conn, run)
679
33
        .await
680
0
        .map_err(|e| Error::Write(format!("{e:#}")))
681
33
}
682
683
/// On GNOME, take the keys of `ids` from GNOME's input-source switching,
684
/// which holds them by default, before they are bound ([`gnome`]). Answers
685
/// the ones whose keys were taken. Elsewhere none, and a failure is logged:
686
/// the shortcut is bound all the same.
687
// `allow`, not `expect`: clippy 1.98 files these under `unused_async_trait_impl`
688
// and later releases under `unused_async`, so either `expect` goes unfulfilled
689
// on some toolchain.
690
#[cfg_attr(
691
    not(target_os = "linux"),
692
    allow(
693
        clippy::unused_async,
694
        clippy::unused_async_trait_impl,
695
        reason = "GNOME's settings are Linux's: elsewhere there is nothing to await"
696
    )
697
)]
698
29
pub async fn take_desktop_keys(ids: &[ShortcutId]) -> Vec<ShortcutId> {
699
    #[cfg(target_os = "linux")]
700
29
    if on_gnome() {
701
5
        let mut taken = Vec::new();
702
5
        for &id in ids {
703
5
            match gnome::take(id).await {
704
                Ok(true) => {
705
4
                    info!("Took shortcut {id}'s keys from GNOME's input-source switching");
706
4
                    taken.push(id);
707
                }
708
1
                Ok(false) => {}
709
0
                Err(e) => warn!("Could not take shortcut {id}'s keys from GNOME: {e:#}"),
710
            }
711
        }
712
5
        return taken;
713
24
    }
714
    #[cfg(not(target_os = "linux"))]
715
    let _ = ids;
716
24
    Vec::new()
717
29
}
718
719
/// On GNOME, give the keys of `ids` back to GNOME's input-source switching.
720
/// Answers the ones given back. Elsewhere none.
721
// `allow`, not `expect`: see `take_desktop_keys`.
722
#[cfg_attr(
723
    not(target_os = "linux"),
724
    allow(
725
        clippy::unused_async,
726
        clippy::unused_async_trait_impl,
727
        reason = "GNOME's settings are Linux's: elsewhere there is nothing to await"
728
    )
729
)]
730
4
pub async fn give_back_desktop_keys(ids: &[ShortcutId]) -> Vec<ShortcutId> {
731
    #[cfg(target_os = "linux")]
732
4
    if on_gnome() {
733
4
        let mut given = Vec::new();
734
4
        for &id in ids {
735
4
            match gnome::give_back(id).await {
736
                Ok(()) => {
737
4
                    info!("Gave shortcut {id}'s keys back to GNOME's input-source switching");
738
4
                    given.push(id);
739
                }
740
0
                Err(e) => warn!("Could not give shortcut {id}'s keys back to GNOME: {e:#}"),
741
            }
742
        }
743
4
        return given;
744
0
    }
745
    #[cfg(not(target_os = "linux"))]
746
    let _ = ids;
747
0
    Vec::new()
748
4
}
749
750
/// Have KDE Plasma's shortcut service forget shortcut `id`.
751
#[cfg(target_os = "linux")]
752
3
async fn forget_on_kde(id: ShortcutId) -> Result<(), Error> {
753
3
    let forgot = async {
754
3
        let conn = zbus::Connection::session().await
?0
;
755
3
        portal::forget_on_kde(&conn, id).await
756
3
    };
757
3
    match forgot.await {
758
        Ok(had) => {
759
3
            info!("KDE forgot shortcut {id} (it had it: {had})");
760
3
            Ok(())
761
        }
762
0
        Err(e) => Err(Error::Write(format!(
763
0
            "could not have KDE forget shortcut {id}: {e:#}"
764
0
        ))),
765
    }
766
3
}
767
768
/// Take shortcut `id` out of GNOME's record of the app's shortcuts.
769
#[cfg(target_os = "linux")]
770
4
async fn forget_on_gnome(id: ShortcutId) -> Result<(), Error> {
771
4
    match gnome::forget(id).await {
772
        Ok(had) => {
773
4
            info!("GNOME forgot shortcut {id} (it had it: {had})");
774
4
            Ok(())
775
        }
776
0
        Err(e) => Err(Error::Write(format!(
777
0
            "could not have GNOME forget shortcut {id}: {e:#}"
778
0
        ))),
779
    }
780
4
}
781
782
/// The shortcuts a session holds, given what its `ListShortcuts` listed and
783
/// what its last `BindShortcuts` answered, on `desktop`
784
/// (`XDG_CURRENT_DESKTOP`).
785
///
786
/// Hyprland's portal keeps a shortcut registered for the app after the
787
/// session that bound it closes. Bound again in a new session, it is
788
/// "already registered": the bind answers it and its presses arrive in the
789
/// new session, but that session's list leaves it out. So on Hyprland what
790
/// the bind answered is held too. Elsewhere the list is what the desktop has
791
/// now, with any keys the user changed in its settings.
792
#[cfg(target_os = "linux")]
793
36
fn held(desktop: &str, listed: Vec<Bound>, at_bind: &[Bound]) -> Vec<Bound> {
794
36
    if !is_hyprland(Some(desktop)) {
795
17
        return listed;
796
19
    }
797
19
    let mut held = listed;
798
19
    for bound in at_bind {
799
26
        if !held.iter().any(|b| 
b.id19
==
bound.id19
) {
800
14
            held.push(bound.clone());
801
12
        }
802
    }
803
21
    
held19
.sort_by_key(|b|
ShortcutId::ALL.iter()14
.position(|id| *id == b.id));
804
19
    held
805
36
}
806
807
/// The ones of `saved` the desktop still lists.
808
#[cfg(target_os = "linux")]
809
7
fn still_kept(saved: &[ShortcutId], listed: &[Bound]) -> Vec<ShortcutId> {
810
7
    saved
811
7
        .iter()
812
7
        .copied()
813
9
        .filter(|id| listed.iter().any(|b| 
b.id8
==
*id8
))
814
        .collect()
815
7
}
816
817
/// [`Shortcuts::method`] on Linux: COSMIC by its name in
818
/// `XDG_CURRENT_DESKTOP`, then the portal when the desktop offers
819
/// `GlobalShortcuts`.
820
#[cfg(target_os = "linux")]
821
26
async fn detect_method() -> ShortcutMethod {
822
26
    let desktop = std::env::var("XDG_CURRENT_DESKTOP").ok();
823
26
    if is_cosmic(desktop.as_deref()) {
824
2
        ShortcutMethod::Cosmic
825
    } else {
826
24
        method_for(desktop.as_deref(), portal_available().await)
827
    }
828
26
}
829
830
#[cfg(target_os = "linux")]
831
24
async fn portal_available() -> bool {
832
24
    match zbus::Connection::session().await {
833
22
        Ok(conn) => portal::available(&conn).await,
834
        Err(e) => {
835
2
            log::debug!("GlobalShortcuts portal: no session bus ({
e0
})");
836
2
            false
837
        }
838
    }
839
24
}
840
841
/// The desktop the daemon runs in: `XDG_CURRENT_DESKTOP`.
842
454
fn desktop() -> Option<String> {
843
454
    std::env::var("XDG_CURRENT_DESKTOP").ok()
844
454
}
845
846
/// The desktop the daemon runs in, as the config files the shortcuts added
847
/// on it under: `XDG_CURRENT_DESKTOP`, or nothing when it is unset.
848
#[must_use]
849
317
pub fn desktop_name() -> String {
850
317
    desktop().unwrap_or_default()
851
317
}
852
853
/// Whether `XDG_CURRENT_DESKTOP`, a `:`-separated list, names `name`.
854
454
fn names(desktop: Option<&str>, name: &str) -> bool {
855
455
    
desktop454
.is_some_and(|desktop|
desktop.split(':')452
.any(|d| d.eq_ignore_ascii_case(name)))
856
454
}
857
858
/// Whether `XDG_CURRENT_DESKTOP` names COSMIC.
859
#[cfg(target_os = "linux")]
860
58
fn is_cosmic(desktop: Option<&str>) -> bool {
861
58
    names(desktop, "COSMIC")
862
58
}
863
864
/// Whether `XDG_CURRENT_DESKTOP` names KDE Plasma, whose portal differs from
865
/// the others in three ways the daemon minds:
866
///
867
/// 1. It lists, in a new session and before anything is bound in it, the
868
///    shortcuts it kept from the app's sessions before. GNOME and Hyprland
869
///    list nothing until a bind.
870
/// 2. KDE's shortcut service forgets a shortcut when asked, which the portal
871
///    cannot.
872
/// 3. Its dialog's Cancel binds the shortcut with no keys.
873
97
fn is_kde(desktop: Option<&str>) -> bool {
874
97
    names(desktop, "KDE")
875
97
}
876
877
/// Whether `XDG_CURRENT_DESKTOP` names Hyprland, whose portal binds no
878
/// keys: the user binds them in Hyprland's config, to the global shortcut the
879
/// portal registers. It keeps that registration for the app after the session
880
/// closes, until Hyprland quits.
881
221
fn is_hyprland(desktop: Option<&str>) -> bool {
882
221
    names(desktop, "Hyprland")
883
221
}
884
885
/// Whether the daemon runs on KDE Plasma.
886
#[cfg(target_os = "linux")]
887
36
fn on_kde() -> bool {
888
36
    is_kde(desktop().as_deref())
889
36
}
890
891
/// Whether the daemon runs on GNOME.
892
#[cfg(target_os = "linux")]
893
40
fn on_gnome() -> bool {
894
40
    is_gnome(desktop().as_deref())
895
40
}
896
897
/// Whether `XDG_CURRENT_DESKTOP` names GNOME.
898
78
fn is_gnome(desktop: Option<&str>) -> bool {
899
78
    names(desktop, "GNOME")
900
78
}
901
902
/// Whether `DELETE /shortcuts/{id}` takes a shortcut off the desktop by
903
/// `method`: COSMIC's file the daemon writes itself, KDE Plasma's shortcut
904
/// service forgets one when asked, and GNOME's record of the app's shortcuts
905
/// is a setting the daemon can change. On Hyprland one the daemon binds no
906
/// more reaches it no more, though Hyprland still lists it. Through the
907
/// portal elsewhere the desktop keeps it until the user removes it in its
908
/// own settings.
909
68
fn removable(method: ShortcutMethod, desktop: &str) -> bool {
910
68
    match method {
911
9
        ShortcutMethod::Cosmic => true,
912
        ShortcutMethod::Portal => {
913
56
            is_kde(Some(desktop)) || 
is_gnome(Some(desktop))38
||
is_hyprland(Some(desktop))28
914
        }
915
3
        ShortcutMethod::Manual => false,
916
    }
917
68
}
918
919
/// The method for an `XDG_CURRENT_DESKTOP`, given whether the desktop offers
920
/// the `GlobalShortcuts` portal. COSMIC's own file comes first: COSMIC has no
921
/// such portal, but another desktop's backend for it may be installed.
922
#[cfg(target_os = "linux")]
923
32
fn method_for(desktop: Option<&str>, portal: bool) -> ShortcutMethod {
924
32
    if is_cosmic(desktop) {
925
3
        ShortcutMethod::Cosmic
926
29
    } else if portal {
927
24
        ShortcutMethod::Portal
928
    } else {
929
5
        ShortcutMethod::Manual
930
    }
931
32
}
932
933
/// The COSMIC shortcut `id` is.
934
225
fn cosmic(id: ShortcutId) -> &'static cosmic_shortcuts::Shortcut {
935
225
    match id {
936
116
        ShortcutId::Dictate => &cosmic_shortcuts::DICTATE,
937
109
        ShortcutId::ReadAloud => &cosmic_shortcuts::READ_ALOUD,
938
    }
939
225
}
940
941
/// The `voice` a shortcut the daemon adds runs, and agy's hooks: the one
942
/// beside the daemon, under either name, since a build tree names it as its
943
/// crate does, or the one on `PATH` when there is none.
944
2
pub(crate) fn voice_program() -> String {
945
2
    std::env::current_exe()
946
2
        .ok()
947
2
        .and_then(|exe| {
948
2
            let dir = exe.parent()
?0
.to_path_buf();
949
2
            ["voice", "super-voice-cli"]
950
2
                .into_iter()
951
4
                .map(|name| dir.join(name))
952
4
                .find(|voice| voice.is_file())
953
2
        })
954
2
        .map_or_else(|| 
"voice"0
.to_string(), |voice| voice.display().to_string())
955
2
}
956
957
/// Run what shortcut `id` runs, as COSMIC's entry for it does: `voice` with
958
/// its arguments, which starts it or, pressed again, stops it. What `voice`
959
/// says when it fails is logged.
960
0
pub fn run(id: ShortcutId) {
961
0
    let args = cosmic(id).args;
962
0
    info!("Shortcut {id} pressed: voice {args}");
963
0
    let command = tokio::process::Command::new(voice_program())
964
0
        .args(args.split_whitespace())
965
0
        .stdin(std::process::Stdio::null())
966
0
        .output();
967
0
    tokio::spawn(async move {
968
0
        match command.await {
969
0
            Ok(out) if out.status.success() => {}
970
0
            Ok(out) => warn!(
971
0
                "voice {args} failed ({}): {}",
972
0
                out.status,
973
0
                String::from_utf8_lossy(&out.stderr).trim()
974
            ),
975
0
            Err(e) => warn!("Could not run voice {args}: {e}"),
976
        }
977
0
    });
978
0
}
979
980
/// Every shortcut and where it stands, given the method, the desktop
981
/// (`XDG_CURRENT_DESKTOP`), COSMIC's shortcuts file's text for COSMIC, and
982
/// for the portal what it has bound and the app id it knows the daemon by,
983
/// when the daemon can tell.
984
///
985
/// On Hyprland, `hypr` is what the daemon read from it. A shortcut's
986
/// keys are those of the bind in its config that runs its global shortcut,
987
/// `<app id>:<id>`, and none when there is no such bind. Where the daemon
988
/// cannot write that config, the list says the user binds the keys.
989
#[must_use]
990
62
pub fn list_from(
991
62
    method: ShortcutMethod,
992
62
    desktop: &str,
993
62
    cosmic_file: &str,
994
62
    bound: &[Bound],
995
62
    app_id: Option<&str>,
996
62
    hypr: Option<&hyprland::View>,
997
62
) -> ShortcutList {
998
62
    let on_hyprland = method == ShortcutMethod::Portal && 
is_hyprland(Some(desktop))52
;
999
62
    let user_binds_keys = on_hyprland && !
hypr26
.is_some_and(|view|
view22
.writable);
1000
62
    let format = hypr.map_or(Format::Lua, |view| 
view22
.format);
1001
62
    let shortcuts = ShortcutId::ALL
1002
62
        .into_iter()
1003
124
        .map(|id| {
1004
124
            let shortcut = cosmic(id);
1005
124
            let global = app_id
1006
                .filter(|_| on_hyprland)
1007
42
                .map(|app_id| global_name(app_id, id));
1008
124
            let (state, keys) = match method {
1009
16
                ShortcutMethod::Cosmic => match cosmic_shortcuts::status(cosmic_file, shortcut) {
1010
3
                    Status::Installed { keys } => (ShortcutState::Installed, keys),
1011
11
                    Status::Missing => (ShortcutState::Missing, shortcut.keys()),
1012
2
                    Status::Taken => (ShortcutState::Taken, shortcut.keys()),
1013
                },
1014
104
                ShortcutMethod::Portal => match (bound.iter().find(|b| 
b.id84
==
id84
), hypr) {
1015
22
                    (Some(_), Some(view)) if on_hyprland => (
1016
22
                        ShortcutState::Installed,
1017
22
                        view.bind(global.as_deref(), id)
1018
22
                            .map_or_else(String::new, hyprland::Bind::keys),
1019
22
                    ),
1020
24
                    (Some(bound), _) => (ShortcutState::Installed, bound.keys.clone()),
1021
22
                    (None, Some(view)) if on_hyprland && view.taken(id) => {
1022
3
                        (ShortcutState::Taken, shortcut.keys())
1023
                    }
1024
55
                    (None, _) => (ShortcutState::Missing, shortcut.keys()),
1025
                },
1026
4
                ShortcutMethod::Manual => (ShortcutState::Manual, shortcut.keys()),
1027
            };
1028
            Shortcut {
1029
124
                id,
1030
124
                state,
1031
124
                keys,
1032
124
                command: format!("voice {}", shortcut.args),
1033
124
                config_line: global.as_deref().map(|global| 
{42
1034
42
                    hyprland_shortcuts::bind_line(format, &hyprland::own_keys(id), global)
1035
42
                }),
1036
124
                global_shortcut: global,
1037
            }
1038
124
        })
1039
        .collect();
1040
62
    ShortcutList {
1041
62
        status: "success".to_string(),
1042
62
        method,
1043
62
        removable: removable(method, desktop),
1044
62
        user_binds_keys,
1045
62
        desktop: desktop.to_string(),
1046
62
        shortcuts,
1047
62
    }
1048
62
}
1049
1050
/// COSMIC's shortcuts file's text, or nothing when there is none yet.
1051
9
fn cosmic_file() -> String {
1052
9
    cosmic_shortcuts::file()
1053
9
        .and_then(|file| std::fs::read_to_string(file).ok())
1054
        .unwrap_or_default()
1055
9
}
1056
1057
/// Add shortcut `id` to COSMIC's shortcuts file. Adding one that is set up
1058
/// already changes nothing and succeeds. Reads and writes the file, so call
1059
/// it off the async runtime.
1060
///
1061
/// # Errors
1062
///
1063
/// [`Error::KeysTaken`] when another shortcut holds its keys, and
1064
/// [`Error::Write`] when the file could not be written.
1065
3
pub fn add_cosmic(id: ShortcutId) -> Result<(), Error> {
1066
3
    let shortcut = cosmic(id);
1067
3
    if cosmic_shortcuts::status(&cosmic_file(), shortcut) == Status::Taken {
1068
1
        return Err(Error::KeysTaken);
1069
2
    }
1070
2
    let command = format!("{} {}", voice_program(), shortcut.args);
1071
2
    cosmic_shortcuts::add(shortcut, &command)
1072
        .map(|_| ())
1073
0
        .map_err(|e| Error::Write(e.to_string()))
1074
3
}
1075
1076
/// Remove shortcut `id` from COSMIC's shortcuts file. Removing one that is
1077
/// not set up changes nothing and succeeds. Call it off the async runtime.
1078
///
1079
/// # Errors
1080
///
1081
/// [`Error::Write`] when the file could not be written.
1082
2
pub fn remove_cosmic(id: ShortcutId) -> Result<(), Error> {
1083
2
    cosmic_shortcuts::remove(cosmic(id))
1084
        .map(|_| ())
1085
0
        .map_err(|e| Error::Write(e.to_string()))
1086
2
}
1087
1088
/// `set` with `id` added or taken out, in the order a list shows them.
1089
#[must_use]
1090
40
pub fn with(set: &[ShortcutId], id: ShortcutId, present: bool) -> Vec<ShortcutId> {
1091
40
    ShortcutId::ALL
1092
40
        .into_iter()
1093
80
        .filter(|s| if *s == id { 
present40
} else {
set.contains(s)40
})
1094
        .collect()
1095
40
}
1096
1097
#[cfg(test)]
1098
mod tests {
1099
    use super::*;
1100
1101
    #[cfg(target_os = "linux")]
1102
    #[test]
1103
1
    fn cosmic_is_found_in_a_desktop_list() {
1104
1
        assert_eq!(method_for(Some("COSMIC"), false), ShortcutMethod::Cosmic);
1105
1
        assert_eq!(
1106
1
            method_for(Some("pop:COSMIC"), false),
1107
1
            ShortcutMethod::Cosmic
1108
        );
1109
1
        assert_eq!(method_for(Some("KDE"), false), ShortcutMethod::Manual);
1110
1
        assert_eq!(method_for(Some(""), false), ShortcutMethod::Manual);
1111
1
        assert_eq!(method_for(None, false), ShortcutMethod::Manual);
1112
1
    }
1113
1114
    #[test]
1115
1
    fn kde_is_found_in_a_desktop_list() {
1116
1
        assert!(is_kde(Some("KDE")));
1117
1
        assert!(is_kde(Some("kde:wayland")));
1118
1
        assert!(!is_kde(Some("GNOME")));
1119
1
        assert!(!is_kde(Some("Hyprland")));
1120
1
        assert!(!is_kde(None));
1121
1
    }
1122
1123
    /// The daemon takes a shortcut off COSMIC, off KDE Plasma through its
1124
    /// shortcut service, and off GNOME through its record of the app's
1125
    /// shortcuts. On Hyprland one it binds no more reaches it no more.
1126
    /// Through the portal elsewhere it cannot.
1127
    #[test]
1128
1
    fn cosmic_kde_gnome_and_hyprland_shortcuts_are_removable() {
1129
1
        assert!(removable(ShortcutMethod::Cosmic, "COSMIC"));
1130
1
        assert!(removable(ShortcutMethod::Portal, "KDE"));
1131
1
        assert!(removable(ShortcutMethod::Portal, "ubuntu:GNOME"));
1132
1
        assert!(removable(ShortcutMethod::Portal, "Hyprland"));
1133
1
        assert!(!removable(ShortcutMethod::Portal, "niri"));
1134
1
        assert!(!removable(ShortcutMethod::Manual, "KDE"));
1135
1
    }
1136
1137
    /// A saved shortcut the desktop no longer lists was removed in its
1138
    /// settings, and is not kept.
1139
    #[cfg(target_os = "linux")]
1140
    #[test]
1141
1
    fn a_shortcut_the_desktop_dropped_is_not_kept() {
1142
        use ShortcutId::{Dictate, ReadAloud};
1143
1
        let listed = [Bound {
1144
1
            id: ReadAloud,
1145
1
            keys: String::new(),
1146
1
        }];
1147
1
        assert_eq!(still_kept(&[Dictate, ReadAloud], &listed), [ReadAloud]);
1148
1
        assert_eq!(still_kept(&[Dictate], &[]), []);
1149
1
    }
1150
1151
    /// Hyprland leaves a shortcut it registered in an earlier session out of
1152
    /// a new session's list, though the bind answered it and it works: it
1153
    /// is held all the same. Elsewhere the list is what the desktop has.
1154
    #[cfg(target_os = "linux")]
1155
    #[test]
1156
1
    fn hyprland_holds_what_a_rebind_answered() {
1157
        use ShortcutId::{Dictate, ReadAloud};
1158
        let bound = |id| Bound {
1159
5
            id,
1160
5
            keys: String::new(),
1161
5
        };
1162
        // Read aloud added to Dictate: the new session lists only Read aloud.
1163
1
        let listed = vec![bound(ReadAloud)];
1164
1
        let at_bind = [bound(Dictate), bound(ReadAloud)];
1165
1
        assert_eq!(
1166
1
            held("Hyprland", listed.clone(), &at_bind),
1167
1
            [bound(Dictate), bound(ReadAloud)]
1168
        );
1169
        // Bound again after a restart: the new session lists nothing.
1170
1
        assert_eq!(held("Hyprland", Vec::new(), &at_bind), at_bind);
1171
1
        let list = list_from(
1172
1
            ShortcutMethod::Portal,
1173
1
            "Hyprland",
1174
1
            "",
1175
1
            &held("Hyprland", Vec::new(), &at_bind),
1176
1
            Some(portal::APP_ID),
1177
1
            None,
1178
1
        );
1179
1
        assert!(
1180
1
            list.shortcuts
1181
1
                .iter()
1182
2
                .all(|s| s.state == ShortcutState::Installed),
1183
            "{list:?}"
1184
        );
1185
        // GNOME and KDE list what they have: one removed in their settings
1186
        // is missing.
1187
1
        assert_eq!(held("GNOME", listed.clone(), &at_bind), listed);
1188
1
        assert_eq!(held("KDE", listed.clone(), &at_bind), listed);
1189
1
    }
1190
1191
    /// The portal is used wherever the desktop offers it, except on COSMIC,
1192
    /// whose own file comes first.
1193
    #[cfg(target_os = "linux")]
1194
    #[test]
1195
1
    fn the_portal_is_used_where_it_is_offered() {
1196
1
        assert_eq!(method_for(Some("KDE"), true), ShortcutMethod::Portal);
1197
1
        assert_eq!(method_for(Some("GNOME"), true), ShortcutMethod::Portal);
1198
1
        assert_eq!(method_for(Some("COSMIC"), true), ShortcutMethod::Cosmic);
1199
1
    }
1200
1201
    /// On COSMIC each shortcut reads from the file: set up on its keys,
1202
    /// missing, or blocked. Elsewhere both are the user's to bind.
1203
    #[test]
1204
1
    fn the_list_says_where_each_stands() {
1205
1
        let file = r#"{ (modifiers: [Super], key: "space", description: Some("Super Voice")): Spawn("/usr/local/bin/voice record --write"), (modifiers: [Super, Shift], key: "space"): Spawn("x"), }"#;
1206
1
        let list = list_from(ShortcutMethod::Cosmic, "COSMIC", file, &[], None, None);
1207
1
        assert_eq!(list.method, ShortcutMethod::Cosmic);
1208
1
        assert!(list.removable);
1209
1
        assert_eq!(list.desktop, "COSMIC");
1210
1
        let [dictate, read] = list.shortcuts.as_slice() else {
1211
0
            panic!("two shortcuts: {list:?}");
1212
        };
1213
1
        assert_eq!(
1214
1
            (dictate.id, dictate.state, dictate.keys.as_str()),
1215
1
            (ShortcutId::Dictate, ShortcutState::Installed, "Super+Space")
1216
        );
1217
1
        assert_eq!(
1218
1
            (read.id, read.state, read.keys.as_str()),
1219
1
            (
1220
1
                ShortcutId::ReadAloud,
1221
1
                ShortcutState::Taken,
1222
1
                "Super+Shift+Space"
1223
1
            )
1224
        );
1225
1
        assert_eq!(read.command, "voice speak --read");
1226
1227
1
        let missing = list_from(ShortcutMethod::Cosmic, "COSMIC", "", &[], None, None);
1228
1
        assert!(
1229
1
            missing
1230
1
                .shortcuts
1231
1
                .iter()
1232
2
                .all(|s| s.state == ShortcutState::Missing)
1233
        );
1234
1235
1
        let manual = list_from(ShortcutMethod::Manual, "Sway", file, &[], None, None);
1236
1
        assert!(
1237
1
            manual
1238
1
                .shortcuts
1239
1
                .iter()
1240
2
                .all(|s| s.state == ShortcutState::Manual)
1241
        );
1242
1
    }
1243
1244
    /// Through the portal, a shortcut is set up when the desktop bound it, on
1245
    /// the keys the desktop says, and missing otherwise.
1246
    #[test]
1247
1
    fn the_portal_list_is_what_the_desktop_bound() {
1248
1
        let bound = [Bound {
1249
1
            id: ShortcutId::ReadAloud,
1250
1
            keys: "Meta+Shift+Space".to_string(),
1251
1
        }];
1252
1
        let list = list_from(
1253
1
            ShortcutMethod::Portal,
1254
1
            "KDE",
1255
1
            "",
1256
1
            &bound,
1257
1
            Some("super-voice-app"),
1258
1
            None,
1259
1
        );
1260
1
        assert!(list.removable);
1261
1
        assert!(!list.user_binds_keys);
1262
1
        assert_eq!(list.desktop, "KDE");
1263
1
        let [dictate, read] = list.shortcuts.as_slice() else {
1264
0
            panic!("two shortcuts: {list:?}");
1265
        };
1266
1
        assert_eq!(
1267
1
            (dictate.state, dictate.keys.as_str()),
1268
1
            (ShortcutState::Missing, "Super+Space")
1269
        );
1270
1
        assert_eq!(
1271
1
            (read.state, read.keys.as_str()),
1272
1
            (ShortcutState::Installed, "Meta+Shift+Space")
1273
        );
1274
        // Only where the user binds the keys is a global shortcut named.
1275
1
        assert_eq!(read.global_shortcut, None);
1276
1
    }
1277
1278
    /// On Hyprland the portal binds no keys: the list says the user binds
1279
    /// them, and to which global shortcut, under the app id the portal
1280
    /// knows the daemon by.
1281
    #[test]
1282
1
    fn on_hyprland_the_user_binds_the_keys() {
1283
1
        let bound = [Bound {
1284
1
            id: ShortcutId::Dictate,
1285
1
            keys: String::new(),
1286
1
        }];
1287
1
        let list = list_from(
1288
1
            ShortcutMethod::Portal,
1289
1
            "Hyprland",
1290
1
            "",
1291
1
            &bound,
1292
1
            Some("super-voice-app"),
1293
1
            None,
1294
1
        );
1295
1
        assert!(list.user_binds_keys);
1296
1
        assert!(list.removable);
1297
1
        let [dictate, read] = list.shortcuts.as_slice() else {
1298
0
            panic!("two shortcuts: {list:?}");
1299
        };
1300
1
        assert_eq!(
1301
1
            (dictate.state, dictate.keys.as_str()),
1302
1
            (ShortcutState::Installed, "")
1303
        );
1304
1
        assert_eq!(
1305
1
            dictate.global_shortcut.as_deref(),
1306
1
            Some("super-voice-app:dictate")
1307
        );
1308
1
        assert_eq!(read.state, ShortcutState::Missing);
1309
1
        assert_eq!(
1310
1
            read.global_shortcut.as_deref(),
1311
1
            Some("super-voice-app:read_aloud")
1312
        );
1313
1314
        // The portal fell back to another app id.
1315
1
        let other = list_from(
1316
1
            ShortcutMethod::Portal,
1317
1
            "Hyprland",
1318
1
            "",
1319
1
            &bound,
1320
1
            Some("rio"),
1321
1
            None,
1322
1
        );
1323
1
        assert_eq!(
1324
1
            other.shortcuts[0].global_shortcut.as_deref(),
1325
1
            Some("rio:dictate")
1326
        );
1327
        // An app id the daemon cannot tell names none.
1328
1
        let unknown = list_from(ShortcutMethod::Portal, "Hyprland", "", &bound, None, None);
1329
1
        assert!(unknown.user_binds_keys);
1330
1
        assert!(
1331
1
            unknown
1332
1
                .shortcuts
1333
1
                .iter()
1334
2
                .all(|s| s.global_shortcut.is_none())
1335
        );
1336
1
    }
1337
1338
    /// Where the daemon binds the keys in Hyprland's config, a shortcut's
1339
    /// keys are those of the bind that runs it, and one another bind holds
1340
    /// the keys of is taken. Each names the line that binds it.
1341
    #[test]
1342
1
    fn on_hyprland_the_keys_are_those_of_its_bind() {
1343
1
        let bound = [Bound {
1344
1
            id: ShortcutId::Dictate,
1345
1
            keys: String::new(),
1346
1
        }];
1347
        let bind = |key: &str, dispatcher: &str, description: &str| hyprland::Bind {
1348
2
            modmask: 64,
1349
2
            key: key.to_string(),
1350
2
            dispatcher: dispatcher.to_string(),
1351
2
            description: description.to_string(),
1352
2
            ..hyprland::Bind::default()
1353
2
        };
1354
1
        let view = hyprland::View {
1355
1
            binds: Some(vec![
1356
1
                bind("D", "HL.Dispatcher(global)", "super-voice-app:dictate"),
1357
1
                hyprland::Bind {
1358
1
                    modmask: 65,
1359
1
                    ..bind("space", "HL.Dispatcher(exec_cmd)", "")
1360
1
                },
1361
1
            ]),
1362
1
            format: Format::Lua,
1363
1
            writable: true,
1364
1
        };
1365
1
        let list = list_from(
1366
1
            ShortcutMethod::Portal,
1367
1
            "Hyprland",
1368
1
            "",
1369
1
            &bound,
1370
1
            Some("super-voice-app"),
1371
1
            Some(&view),
1372
1
        );
1373
1
        assert!(!list.user_binds_keys);
1374
1
        let [dictate, read] = list.shortcuts.as_slice() else {
1375
0
            panic!("two shortcuts: {list:?}");
1376
        };
1377
1
        assert_eq!(
1378
1
            (dictate.state, dictate.keys.as_str()),
1379
1
            (ShortcutState::Installed, "Super+D"),
1380
            "keys the user changed in the file"
1381
        );
1382
1
        assert_eq!(
1383
1
            (read.state, read.keys.as_str()),
1384
1
            (ShortcutState::Taken, "Super+Shift+Space")
1385
        );
1386
1
        assert_eq!(
1387
1
            dictate.config_line.as_deref(),
1388
1
            Some(
1389
1
                r#"hl.bind("SUPER + space", hl.dsp.global("super-voice-app:dictate"), { description = "super-voice-app:dictate" })"#
1390
1
            )
1391
        );
1392
1393
        // Where the config cannot be written, the user binds the keys: none
1394
        // are taken, and one with no bind has none.
1395
1
        let read_only = hyprland::View {
1396
1
            binds: Some(Vec::new()),
1397
1
            writable: false,
1398
1
            ..view
1399
1
        };
1400
1
        let list = list_from(
1401
1
            ShortcutMethod::Portal,
1402
1
            "Hyprland",
1403
1
            "",
1404
1
            &bound,
1405
1
            Some("super-voice-app"),
1406
1
            Some(&read_only),
1407
1
        );
1408
1
        assert!(list.user_binds_keys);
1409
1
        assert_eq!(
1410
1
            (list.shortcuts[0].state, list.shortcuts[0].keys.as_str()),
1411
1
            (ShortcutState::Installed, "")
1412
        );
1413
1
        assert_eq!(list.shortcuts[1].state, ShortcutState::Missing);
1414
1
    }
1415
1416
    /// `GET /shortcuts` answers as it did before the Hyprland fields, which
1417
    /// are added beside the others: a client that does not know them reads
1418
    /// the rest unchanged.
1419
    #[test]
1420
1
    fn the_answer_keeps_its_fields() {
1421
1
        let list = list_from(
1422
1
            ShortcutMethod::Portal,
1423
1
            "KDE",
1424
1
            "",
1425
1
            &[],
1426
1
            Some("super-voice-app"),
1427
1
            None,
1428
1
        );
1429
1
        let json = serde_json::to_value(&list).expect("writes");
1430
1
        for field in ["status", "method", "removable", "desktop", "shortcuts"] {
1431
5
            assert!(json.get(field).is_some(), "no {field}: {json}");
1432
        }
1433
1
        assert_eq!(
1434
1
            json["shortcuts"][0],
1435
1
            serde_json::json!({
1436
1
                "id": "dictate",
1437
1
                "state": "missing",
1438
1
                "keys": "Super+Space",
1439
1
                "command": "voice record --write",
1440
            })
1441
        );
1442
1
    }
1443
1444
    #[test]
1445
1
    fn a_set_keeps_the_list_order() {
1446
        use ShortcutId::{Dictate, ReadAloud};
1447
1
        assert_eq!(with(&[ReadAloud], Dictate, true), [Dictate, ReadAloud]);
1448
1
        assert_eq!(with(&[Dictate, ReadAloud], Dictate, false), [ReadAloud]);
1449
1
        assert_eq!(with(&[], ReadAloud, false), []);
1450
1
        assert_eq!(with(&[ReadAloud], ReadAloud, true), [ReadAloud]);
1451
1
    }
1452
}