Debian Codegraph @

src/lib.rs

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #![cfg_attr(docsrs, feature(doc_cfg))]
2 #![deny(rustdoc::broken_intra_doc_links)]
3 #![deny(missing_docs)]
4 #![doc(
5 html_logo_url = "https://raw.githubusercontent.com/bilelmoussaoui/ashpd/main/ashpd-demo/data/icons/com.belmoussaoui.ashpd.demo.svg",
6 html_favicon_url = "https://raw.githubusercontent.com/bilelmoussaoui/ashpd/main/ashpd-demo/data/icons/com.belmoussaoui.ashpd.demo-symbolic.svg"
7 )]
8 #![doc = include_str!("../README.md")]
9 #[cfg(all(all(feature = "tokio", feature = "async-io"), not(doc)))]
10 compile_error!("You can't enable both async-io & tokio features at once");
11 #[cfg(all(not(feature = "tokio"), not(feature = "async-io"), not(doc)))]
12 compile_error!("Either the `async-io` or the `tokio` feature has to be enabled");
13
14 /// Alias for a [`Result`] with the error type `ashpd::Error`.
15 pub type Result<T> = std::result::Result<T, Error>;
16
17 static IS_SANDBOXED: OnceLock<bool> = OnceLock::new();
18
19 mod activation_token;
20 /// Interact with the user's desktop such as taking a screenshot, setting a
21 /// background or querying the user's location.
22 pub mod desktop;
23 /// Interact with the documents store or transfer files across apps.
24 #[cfg(feature = "documents")]
25 #[cfg_attr(docsrs, doc(cfg(feature = "documents")))]
26 pub mod documents;
27 mod error;
28 mod window_identifier;
29
30 pub use self::{activation_token::ActivationToken, window_identifier::WindowIdentifier};
31 mod app_id;
32 mod registry;
33 mod uri;
34 #[cfg(feature = "backend")]
35 pub use self::app_id::MaybeAppID;
36 pub use self::{
37 app_id::AppID,
38 registry::{register_host_app, register_host_app_with_connection},
39 uri::Uri,
40 };
41 mod file_path;
42 pub use self::file_path::FilePath;
43
44 mod proxy;
45
46 pub use self::window_identifier::WindowIdentifierType;
47 #[cfg(feature = "backend")]
48 #[cfg_attr(docsrs, doc(cfg(feature = "backend")))]
49 #[allow(missing_docs)]
50 /// Build your custom portals backend.
51 pub mod backend;
52 /// Spawn commands outside the sandbox or monitor if the running application has
53 /// received an update & install it.
54 #[cfg(feature = "flatpak")]
55 #[cfg_attr(docsrs, doc(cfg(feature = "flatpak")))]
56 pub mod flatpak;
57 mod helpers;
58 use std::sync::OnceLock;
59
60 #[cfg(feature = "backend")]
61 #[cfg_attr(docsrs, doc(cfg(feature = "backend")))]
62 pub use async_trait;
63 pub use enumflags2;
64 pub use zbus::{self, zvariant};
65
66 /// Check whether the application is running inside a sandbox.
67 ///
68 /// The function checks whether the file `/.flatpak-info` exists, or if the app
69 /// is running as a snap, or if the environment variable `GTK_USE_PORTAL` is set
70 /// to `1`. As the return value of this function will not change during the
71 /// runtime of a program; it is cached for future calls.
72 pub fn is_sandboxed() -> bool {
73 if let Some(cached_value) = IS_SANDBOXED.get() {
74 return *cached_value;
75 }
76 let new_value = crate::helpers::is_flatpak() || crate::helpers::is_snap();
77
78 *IS_SANDBOXED.get_or_init(|| new_value)
79 }
80
81 pub use self::error::{Error, PortalError};
82
83 mod sealed {
84 /// Use as a supertrait for public traits that users should not be able to
85 /// implement
86 pub trait Sealed {}
87 }
88
89 pub(crate) use sealed::Sealed;
90
91 /// Process ID.
92 ///
93 /// Matches the type used in std.
94 pub type Pid = u32;
95
96 #[cfg(test)]
97 mod tests {
98 use std::{collections::HashMap, fs, path::PathBuf};
99
100 use quick_xml::{Reader, events::Event};
101
102 // Helper to convert PascalCase to snake_case
103 fn pascal_to_snake_case(s: &str) -> String {
104 let mut result = String::new();
105 for (i, c) in s.chars().enumerate() {
106 if c.is_ascii_uppercase() {
107 if i > 0 {
108 result.push('_');
109 }
110 result.push(c.to_ascii_lowercase());
111 } else {
112 result.push(c);
113 }
114 }
115 result
116 }
117
118 fn extract_names_from_xml(xml_content: &str) -> HashMap<String, Vec<String>> {
119 let mut interfaces = HashMap::new();
120 let mut reader = Reader::from_str(xml_content);
121 reader.config_mut().trim_text(true);
122 let mut buf = Vec::new();
123 let mut current_interface_name = String::new();
124 let mut current_names = Vec::new();
125
126 loop {
127 match reader.read_event_into(&mut buf) {
128 Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
129 Ok(Event::Eof) => break,
130 Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
131 // Handle both Start and Empty events
132 if let Some(Ok(attr)) = e
133 .attributes()
134 .find(|a| a.as_ref().map_or(false, |a| a.key.as_ref() == b"name"))
135 {
136 if let Ok(value) = attr.decode_and_unescape_value(reader.decoder()) {
137 match e.name().as_ref() {
138 b"interface" => {
139 current_interface_name = value.to_string();
140 current_names.clear();
141 }
142 b"method" | b"property" | b"signal" => {
143 if value != "version" {
144 current_names.push(value.to_string());
145 }
146 }
147 _ => (),
148 }
149 }
150 }
151 }
152 Ok(Event::End(e)) => {
153 if e.name().as_ref() == b"interface" {
154 interfaces.insert(current_interface_name.clone(), current_names.clone());
155 }
156 }
157 _ => (),
158 }
159 buf.clear();
160 }
161 interfaces
162 }
163
164 struct TestConfig {
165 interfaces_dir: PathBuf,
166 rust_src_prefix: &'static str,
167 rust_file_mappings: HashMap<&'static str, &'static str>,
168 ignored_interfaces: &'static [&'static str],
169 interface_prefix: &'static str,
170 }
171
172 fn check_doc_aliases_for_config(config: TestConfig) {
173 assert!(
174 config.interfaces_dir.exists(),
175 "Interfaces directory not found at {}",
176 config.interfaces_dir.display()
177 );
178
179 let entries =
180 fs::read_dir(&config.interfaces_dir).expect("Failed to read interfaces directory");
181
182 for entry in entries.filter_map(|e| e.ok()) {
183 let path = entry.path();
184 if path.is_file() && path.extension().map_or(false, |ext| ext == "xml") {
185 println!("Checking XML file: {}", path.display());
186
187 let xml_content = fs::read_to_string(&path).unwrap();
188 let interfaces = extract_names_from_xml(&xml_content);
189
190 for (interface_name, names_to_check) in interfaces {
191 // Map the D-Bus interface name to the corresponding Rust file path
192 let interface_name_suffix = interface_name
193 .strip_prefix(config.interface_prefix)
194 .expect("Interface name does not have the expected prefix.");
195
196 if config.ignored_interfaces.contains(&interface_name_suffix) {
197 continue;
198 }
199
200 let rust_path = if let Some(mapped_path) =
201 config.rust_file_mappings.get(interface_name.as_str())
202 {
203 PathBuf::from(mapped_path)
204 } else {
205 let rust_file_name_snake = pascal_to_snake_case(interface_name_suffix);
206 PathBuf::from(format!(
207 "{}{}.rs",
208 config.rust_src_prefix, rust_file_name_snake
209 ))
210 };
211
212 // Check if the Rust file exists
213 assert!(
214 rust_path.exists(),
215 "Corresponding Rust file not found for interface '{}' at {}",
216 interface_name,
217 rust_path.display()
218 );
219
220 // Read the Rust file content
221 let rust_content = fs::read_to_string(&rust_path).unwrap();
222
223 // Assert that each name has a corresponding doc alias
224 for name in &names_to_check {
225 let alias_str = format!("#[doc(alias = \"{}\")]", name);
226 assert!(
227 rust_content.contains(&alias_str),
228 "Missing doc alias '{}' for interface '{}' in file {}",
229 alias_str,
230 interface_name,
231 rust_path.display()
232 );
233 }
234 }
235 }
236 }
237 }
238
239 #[cfg(feature = "backend")]
240 #[test]
241 fn all_interfaces_have_backend_implementations() {
242 let rust_file_mappings: HashMap<&str, &str> = HashMap::from([(
243 "org.freedesktop.impl.portal.ScreenCast",
244 "src/backend/screencast.rs",
245 )]);
246
247 const IGNORED_BACKEND_PORTALS: &[&str; 7] = &[
248 "Clipboard",
249 "DynamicLauncher",
250 "GlobalShortcuts",
251 "Inhibit",
252 "InputCapture",
253 "Notification",
254 "RemoteDesktop",
255 ];
256
257 let config = TestConfig {
258 interfaces_dir: PathBuf::from("./../interfaces/backend"),
259 rust_src_prefix: "src/backend/",
260 rust_file_mappings,
261 ignored_interfaces: IGNORED_BACKEND_PORTALS,
262 interface_prefix: "org.freedesktop.impl.portal.",
263 };
264
265 check_doc_aliases_for_config(config);
266 }
267
268 #[test]
269 fn all_interfaces_have_implementations() {
270 let rust_file_mappings: HashMap<&str, &str> = HashMap::from([
271 (
272 "org.freedesktop.portal.ScreenCast",
273 "src/desktop/screencast.rs",
274 ),
275 ("org.freedesktop.portal.OpenURI", "src/desktop/open_uri.rs"),
276 (
277 "org.freedesktop.portal.FileTransfer",
278 "src/documents/file_transfer.rs",
279 ),
280 ("org.freedesktop.portal.Documents", "src/documents/mod.rs"),
281 ("org.freedesktop.portal.Flatpak", "src/flatpak/mod.rs"),
282 (
283 "org.freedesktop.portal.Flatpak.UpdateMonitor",
284 "src/flatpak/update_monitor.rs",
285 ),
286 ]);
287
288 const NO_IGNORED_INTERFACES: &[&str; 0] = &[];
289
290 let config = TestConfig {
291 interfaces_dir: PathBuf::from("./../interfaces"),
292 rust_src_prefix: "src/desktop/",
293 rust_file_mappings,
294 ignored_interfaces: NO_IGNORED_INTERFACES,
295 interface_prefix: "org.freedesktop.portal.",
296 };
297
298 check_doc_aliases_for_config(config);
299 }
300 }