Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-daemon/src/portal.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! What every XDG desktop portal call shares: the portal's bus name and
3
//! object, and the `org.freedesktop.portal.Request` round trip a method
4
//! answers through. The `RemoteDesktop` session ([`remote_desktop`]), with
5
//! its clipboard ([`clipboard`]), and the `GlobalShortcuts` shortcuts
6
//! (`shortcuts::portal`) all call through it.
7
8
pub(crate) mod clipboard;
9
pub(crate) mod remote_desktop;
10
11
use anyhow::{Context, Result};
12
use futures::StreamExt;
13
use log::{debug, warn};
14
use std::collections::HashMap;
15
use std::sync::atomic::{AtomicU64, Ordering};
16
use zbus::zvariant::{OwnedObjectPath, OwnedValue};
17
18
/// The portal frontend's bus name.
19
pub(crate) const PORTAL_BUS: &str = "org.freedesktop.portal.Desktop";
20
/// The one object every portal interface is on.
21
pub(crate) const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop";
22
const REQUEST_IFACE: &str = "org.freedesktop.portal.Request";
23
const REGISTRY_IFACE: &str = "org.freedesktop.host.portal.Registry";
24
25
/// The app id the daemon registers: the app's, from its
26
/// `super-voice-app.desktop`.
27
pub const APP_ID: &str = "super-voice-app";
28
29
/// Register [`APP_ID`] as who `conn` calls the portal for. Must come before
30
/// any other portal call on it.
31
///
32
/// The portal asks who is calling by app id, and the daemon, a service the
33
/// host runs, has none. Registered, the desktop can name Super Voice in its
34
/// dialogs, as the shortcuts dialogs of KDE and GNOME do. A portal older than
35
/// 1.21 has no registry and finds the id itself. Answers whether the portal
36
/// registered it.
37
41
pub(crate) async fn register(conn: &zbus::Connection) -> zbus::Result<()> {
38
41
    let registered = async {
39
41
        let registry = zbus::Proxy::new(conn, PORTAL_BUS, PORTAL_PATH, REGISTRY_IFACE).await
?0
;
40
41
        registry
41
41
            .call::<_, _, ()>(
42
41
                "Register",
43
41
                &(APP_ID, HashMap::<&str, zbus::zvariant::Value<'_>>::new()),
44
41
            )
45
41
            .await
46
41
    };
47
41
    let registered = registered.await;
48
41
    match &registered {
49
40
        Ok(()) => debug!("Portal: registered as {
APP_ID0
}"),
50
1
        Err(e) => debug!("Portal: could not register as {
APP_ID0
}: {
e0
}"),
51
    }
52
41
    registered
53
41
}
54
55
/// A `handle_token` no other request from this process is using.
56
127
pub(crate) fn next_handle_token() -> String {
57
    static NEXT: AtomicU64 = AtomicU64::new(0);
58
127
    format!("superstt_r{}", NEXT.fetch_add(1, Ordering::Relaxed))
59
127
}
60
61
/// The object path the portal gives a request that `unique_name` made with
62
/// `handle_token`, per the `org.freedesktop.portal.Request` naming scheme.
63
126
fn request_path(unique_name: &str, handle_token: &str) -> String {
64
126
    let sender = unique_name.trim_start_matches(':').replace('.', "_");
65
126
    format!("{PORTAL_PATH}/request/{sender}/{handle_token}")
66
126
}
67
68
/// Start listening for `Response` on one request path.
69
125
async fn subscribe_response(
70
125
    conn: &zbus::Connection,
71
125
    path: String,
72
125
) -> Result<zbus::proxy::SignalStream<'static>> {
73
125
    let proxy = zbus::Proxy::new(conn, PORTAL_BUS, path, REQUEST_IFACE).await
?0
;
74
125
    Ok(proxy.receive_signal("Response").await
?0
)
75
125
}
76
77
/// Call a portal method and wait for its Response signal.
78
///
79
/// Subscribes before calling. The portal can answer before the call has even
80
/// returned: on COSMIC, `Response` arrived 0.2 ms after the reply carrying the
81
/// request path, and a subscription made after that reply landed 0.7 ms too
82
/// late. The answer was lost and every step timed out, so the dialog at
83
/// `Start` almost never came up. The portal documents this race and its fix:
84
/// the caller sends `handle_token` in the method's options, which makes the
85
/// request path predictable before the call.
86
14
pub(crate) async fn portal_call(
87
14
    conn: &zbus::Connection,
88
14
    portal: &zbus::Proxy<'_>,
89
14
    method: &str,
90
14
    handle_token: &str,
91
14
    body: &(impl serde::Serialize + zbus::zvariant::DynamicType),
92
14
    timeout_secs: u64,
93
14
) -> Result<HashMap<String, OwnedValue>> {
94
    let (code, results) =
95
14
        portal_request(conn, portal, method, handle_token, body, timeout_secs).await
?0
;
96
14
    if code != 0 {
97
0
        return Err(anyhow::anyhow!(
98
0
            "Portal {method} failed (response code {code})"
99
0
        ));
100
14
    }
101
14
    Ok(results)
102
14
}
103
104
/// How a request ended, as its `Response` says: the user said no in the
105
/// desktop's dialog.
106
pub(crate) const RESPONSE_CANCELLED: u32 = 1;
107
108
/// How a request ended, as its `Response` says: another way than the user
109
/// saying yes or no. GNOME answers its dialog's Cancel this way.
110
pub(crate) const RESPONSE_ENDED: u32 = 2;
111
112
/// [`portal_call`], answering the `Response`'s code with its results rather
113
/// than refusing any but `0`, for a caller that tells a cancelled dialog
114
/// ([`RESPONSE_CANCELLED`]) from a failure.
115
125
pub(crate) async fn portal_request(
116
125
    conn: &zbus::Connection,
117
125
    portal: &zbus::Proxy<'_>,
118
125
    method: &str,
119
125
    handle_token: &str,
120
125
    body: &(impl serde::Serialize + zbus::zvariant::DynamicType),
121
125
    timeout_secs: u64,
122
125
) -> Result<(u32, HashMap<String, OwnedValue>)> {
123
125
    let unique_name = conn
124
125
        .unique_name()
125
125
        .context("Session bus connection has no unique name")
?0
;
126
125
    let expected = request_path(unique_name.as_str(), handle_token);
127
125
    let mut signals = subscribe_response(conn, expected.clone()).await
?0
;
128
129
125
    let request_path: OwnedObjectPath = portal
130
125
        .call(method, body)
131
125
        .await
132
125
        .context(format!("Portal {method} call failed"))
?0
;
133
134
125
    debug!("Portal {
method0
}: request path = {
request_path0
}");
135
136
125
    if request_path.as_str() != expected {
137
        // A portal older than 0.9 ignores `handle_token` and picks its own
138
        // path. Listening there now reopens the race, but it is all such a
139
        // portal allows.
140
0
        warn!("Portal {method}: request path {request_path} is not the predicted {expected}");
141
0
        signals = subscribe_response(conn, request_path.to_string()).await?;
142
125
    }
143
144
125
    let signal = tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), signals.next())
145
125
        .await
146
125
        .context("Timeout waiting for portal Response")
?0
147
125
        .context("Signal stream ended without Response")
?0
;
148
149
125
    let body = signal.body();
150
125
    let (code, results): (u32, HashMap<String, OwnedValue>) = body
151
125
        .deserialize()
152
125
        .context("Failed to deserialize portal Response")
?0
;
153
154
125
    debug!("Portal {
method0
}: response code = {
code0
}");
155
125
    Ok((code, results))
156
125
}
157
158
#[cfg(test)]
159
mod tests {
160
    use super::*;
161
162
    /// The portal names a request after its sender and `handle_token`. A path
163
    /// predicted wrong is a subscription on the wrong object, which is the race
164
    /// again: every step would wait out its timeout.
165
    #[test]
166
1
    fn request_path_follows_the_portal_naming_scheme() {
167
1
        assert_eq!(
168
1
            request_path(":1.676039", "superstt_r0"),
169
1
            "/org/freedesktop/portal/desktop/request/1_676039/superstt_r0"
170
        );
171
1
    }
172
173
    #[test]
174
1
    fn handle_tokens_are_not_reused() {
175
1
        let first = next_handle_token();
176
1
        let second = next_handle_token();
177
1
        assert_ne!(first, second);
178
        // The portal accepts only [A-Za-z0-9_] in a token.
179
1
        assert!(
180
11
            
first.chars()1
.all(|c| c.is_ascii_alphanumeric() ||
c == '_'1
),
181
            "{first}"
182
        );
183
1
    }
184
}