ashpd 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7781d7f11fe631e9217fcb0863e03731abdd68aaf67b44ce3e95686f08aca3e8
4
- data.tar.gz: 6ab630873869405be039f9fe8e9ce31ddb1f9a80ae1c87298327206140fa364f
3
+ metadata.gz: 2702509efa646991cf729e5ecc200b0f9777169f7f2fc04dece25c0cc0056be5
4
+ data.tar.gz: 3d82f5c06c77c2b3585ddf9b5a5a4b4cc08e93b4935fbd8cffa27206a365def3
5
5
  SHA512:
6
- metadata.gz: 749b020c76013dd05c6d0903b4d73f82c86d39fc17c0c323594acee9c9c7943bfc45b473f3628335dd97b234648e0eabbcb2b794f3a13797b1523ed2dcf794e1
7
- data.tar.gz: c06e85fe999e35cb89264beaaec5986120855e95181aa216a0da20d47873be5733796f922999aaf02df3627ff0287a92a03d1bdb0fff429c74d268b9991336ce
6
+ metadata.gz: 49f5638e4b389a6cab17baa59f2e10ddc0a20a3cbf228f18d77f6836b05ab82d4422ff6f1dff90a63a46bca1c02f07ad503eb9e609b5d729157c8abe1d152b97
7
+ data.tar.gz: 4fd2f10ec98dc2b90e079ba38bb9a7dc68a512d542e74baca73362a04f90d4d59952fd07c634edc676da836a90d8b43d8575349b4373c10b02f7fe75e96f5090
data/CHANGELOG.md ADDED
@@ -0,0 +1,66 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [0.2.0] - 2026-11-14
6
+
7
+ ### Added
8
+
9
+ - `Ashpd::ScreenCast::Session`, the first stateful portal: `new`,
10
+ `select_sources`, `start`, `restore_token`, `open_pipe_wire_remote` and
11
+ `close`. The session must be kept alive for as long as the stream is wanted,
12
+ and `open_pipe_wire_remote` hands back the descriptor a PipeWire consumer
13
+ needs to reach the node id that `start` returns. Alongside it, the plain
14
+ queries `Ashpd::ScreenCast.available_source_types`,
15
+ `Ashpd::ScreenCast.available_cursor_modes` and `Ashpd::ScreenCast.version`.
16
+ - `Ashpd::GlobalShortcuts::Session` for shortcuts that fire whether or not the
17
+ application has focus: `new`, `bind`, `list`, `next_activated` and `close`.
18
+ `bind` returns what the user agreed to, which is not necessarily what was
19
+ asked for.
20
+ - `Ashpd::RemoteDesktop::Session` for driving someone's pointer and keyboard:
21
+ `new`, `select_devices`, `start`, `restore_token`, `move_pointer`,
22
+ `pointer_button`, `key`, `connect_to_eis` and `close`. Also the capability
23
+ query `Ashpd::RemoteDesktop.available_device_types`.
24
+ - `Ashpd::Location::Session` for the user's position as a stream of updates:
25
+ `new`, `start`, `next_location` and `close`. `next_location` takes a timeout
26
+ in seconds because the first fix can be slow.
27
+ - `Ashpd::NetworkMonitor.available?`, `.metered?`, `.connectivity`, `.status`
28
+ and `.can_reach?`. `connectivity` and the `"connectivity"` key in `status`
29
+ come back as one of the symbols `:local`, `:limited`, `:captive_portal` or
30
+ `:full_network`.
31
+ - `Ashpd::PowerProfileMonitor.power_saver_enabled?`, so a UI can do less when
32
+ the host asks it to.
33
+ - `Ashpd::ProxyResolver.lookup`, which returns the proxies to try for a URI in
34
+ order. `"direct://"` is the no-proxy answer.
35
+ - `Ashpd::Realtime.limits`, returning the host's priority, nice level and
36
+ rt-time caps.
37
+ - `Ashpd::GameMode.active?`, `.status`, `.register` and `.unregister`.
38
+ `.status` returns `:inactive`, `:active`, `:registered` or `:rejected`.
39
+ - `Ashpd::Email.compose` for opening the user's mail program on a draft.
40
+ - `Ashpd::Background.request` and `Ashpd::Background.set_status`. `request`
41
+ returns `{"run_in_background" =>, "auto_start" =>}` — what the user granted.
42
+ - `Ashpd::Notification.add` and `Ashpd::Notification.remove`. Re-adding the
43
+ same id replaces what is on screen rather than stacking another one.
44
+ - `Ashpd::Wallpaper.set` from a URI, with `:set_on` of `:lockscreen`,
45
+ `:background` or `:both`.
46
+ - `Ashpd::Inhibit.inhibit`, taking any of `:logout`, `:user_switch`,
47
+ `:suspend`, `:idle`. The inhibition lasts until the process exits; there is
48
+ deliberately no release yet.
49
+ - `Ashpd::Secret.retrieve`, the single master secret this host keeps for the
50
+ application, as a `String` of bytes.
51
+ - `Ashpd::FileChooser.open_file` and `Ashpd::FileChooser.save_file`, both
52
+ returning a list of URIs (empty when the user cancelled).
53
+ - `Ashpd::DynamicLauncher.supported_launcher_types`,
54
+ `Ashpd::DynamicLauncher.desktop_entry`, `Ashpd::DynamicLauncher.launch` and
55
+ `Ashpd::DynamicLauncher.uninstall`.
56
+ - `Ashpd::OpenUri.scheme_supported?`, `Ashpd::OpenUri.open_path` (by path,
57
+ through a descriptor) and `Ashpd::OpenUri.open_directory`.
58
+ - `Ashpd::Camera.request_access` and `Ashpd::Camera.open_pipe_wire_remote`.
59
+ The descriptor only works while the grant is live, and Ruby owns it once
60
+ returned.
61
+ - `Ashpd::Usb.devices`, the enumeration only — acquiring a device is not bound
62
+ yet.
63
+ - `Ashpd::InputCapture.supported_capabilities`.
64
+ - `Ashpd::Settings.contrast` and `Ashpd::Settings.reduced_motion`.
65
+ - `Ashpd::Screenshot.available_targets`, as a list of `:screen`, `:window`,
66
+ `:area` or `:active_window` symbols.
data/Cargo.lock CHANGED
@@ -16,6 +16,7 @@ name = "ashpd"
16
16
  version = "0.1.0"
17
17
  dependencies = [
18
18
  "ashpd 0.13.13",
19
+ "futures-util",
19
20
  "magnus",
20
21
  "tokio",
21
22
  ]
data/ext/ashpd/Cargo.toml CHANGED
@@ -27,6 +27,11 @@ magnus = "0.9"
27
27
  # current-thread.
28
28
  tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "net"] }
29
29
 
30
+ # The session portals deliver their events as async streams, and a Ruby caller
31
+ # wants one event at a time with a timeout rather than a stream. StreamExt is
32
+ # what turns the former into the latter.
33
+ futures-util = { version = "0.3", default-features = false }
34
+
30
35
  # ashpd 0.13, MIT. It speaks the XDG Desktop Portal D-Bus interfaces through
31
36
  # zbus directly, so this binding loads no libportal and no libxdp -- the same
32
37
  # trade as oo7-rb makes against libsecret.
@@ -38,8 +43,10 @@ tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "net"] }
38
43
  # gdk4wayland crates. It exists to turn a GTK window into a parent handle
39
44
  # for a modal portal dialog, which is what the XdpGtk4 gap needs.
40
45
  # - `pipewire` pulls in libpipewire, needed only to consume a screencast
41
- # stream rather than to request one.
46
+ # stream rather than to request one. The ScreenCast binding here requests
47
+ # one and hands the descriptor to the caller, so it stays off: whatever
48
+ # reads the stream -- GStreamer, usually -- links libpipewire itself.
42
49
  [dependencies.ashpd_core]
43
50
  package = "ashpd"
44
51
  version = "0.13"
45
- features = ["location", "file_chooser", "notification", "open_uri", "screenshot", "settings", "trash", "camera", "background", "account"]
52
+ features = ["frontend"]
@@ -0,0 +1,152 @@
1
+ //! The portals that hand over a device, or say what devices there are.
2
+ //!
3
+ //! Two of these answer with a file descriptor rather than data - the camera's
4
+ //! PipeWire remote, and remote desktop's EIS socket - and the rule for both is
5
+ //! the one {crate::screencast} documents: the descriptor only works while the
6
+ //! session that produced it is alive, and Ruby owns it once it is handed over.
7
+ //!
8
+ //! - org.freedesktop.portal.Camera
9
+ //! - org.freedesktop.portal.Usb
10
+ //! - org.freedesktop.portal.RemoteDesktop (what it can do)
11
+ //! - org.freedesktop.portal.InputCapture (what it can do)
12
+
13
+ use std::os::fd::IntoRawFd;
14
+
15
+ use magnus::{function, prelude::*, Error, RArray, RHash, RModule, Ruby};
16
+
17
+ use ashpd_core::desktop::camera::{Camera, CameraAccessOptions, OpenPipeWireRemoteOptions};
18
+ use ashpd_core::desktop::input_capture::{Capabilities, InputCapture};
19
+ use ashpd_core::desktop::remote_desktop::{DeviceType, RemoteDesktop};
20
+ use ashpd_core::desktop::usb::{EnumerateDevicesOptions, UsbProxy};
21
+
22
+ use crate::{block, rt_err};
23
+
24
+ // --- org.freedesktop.portal.Camera -----------------------------------------
25
+
26
+ /// Ask the user for the camera.
27
+ ///
28
+ /// Returns true if there is now access. The dialog is shown once and the
29
+ /// answer remembered, so a second call on a granted camera returns at once.
30
+ fn camera_request_access() -> Result<bool, Error> {
31
+ block(async {
32
+ Camera::new()
33
+ .await?
34
+ .request_access(CameraAccessOptions::default())
35
+ .await?
36
+ .response()
37
+ })?
38
+ .map_err(rt_err)?;
39
+
40
+ Ok(true)
41
+ }
42
+
43
+ /// A descriptor for the PipeWire remote the cameras are on.
44
+ ///
45
+ /// As with screen casting, the node to read is not addressable on the ordinary
46
+ /// PipeWire: this descriptor is the way in. Access must have been granted
47
+ /// first, so call {camera_request_access} before this.
48
+ fn camera_open_pipe_wire_remote() -> Result<i32, Error> {
49
+ let fd = block(async {
50
+ Camera::new()
51
+ .await?
52
+ .open_pipe_wire_remote(OpenPipeWireRemoteOptions::default())
53
+ .await
54
+ })?
55
+ .map_err(rt_err)?;
56
+
57
+ Ok(fd.into_raw_fd())
58
+ }
59
+
60
+ // --- org.freedesktop.portal.Usb --------------------------------------------
61
+
62
+ /// Every USB device the host will tell us about, as
63
+ /// `[{"id" =>, "vendor" =>, "model" =>, "device_file" =>, "readable" =>, "writable" =>}]`.
64
+ ///
65
+ /// This is the enumeration only, which shows the user nothing. Acquiring a
66
+ /// device - which hands back a descriptor and does ask - needs a session, and
67
+ /// is not bound yet.
68
+ fn usb_devices(ruby: &Ruby) -> Result<RArray, Error> {
69
+ let devices = block(async {
70
+ UsbProxy::new()
71
+ .await?
72
+ .enumerate_devices(EnumerateDevicesOptions::default())
73
+ .await
74
+ })?
75
+ .map_err(rt_err)?;
76
+
77
+ let array = ruby.ary_new_capa(devices.len());
78
+ for (id, device) in devices {
79
+ let hash = ruby.hash_new();
80
+ hash.aset("id", id.as_str())?;
81
+ hash.aset("vendor", device.vendor())?;
82
+ hash.aset("model", device.model())?;
83
+ hash.aset("device_file", device.device_file())?;
84
+ hash.aset("readable", device.is_readable())?;
85
+ hash.aset("writable", device.is_writable())?;
86
+ let _ = array.push(hash);
87
+ }
88
+
89
+ Ok(array)
90
+ }
91
+
92
+ // --- what the input portals can do -----------------------------------------
93
+
94
+ /// Which input devices this host will let an application drive remotely, as
95
+ /// `[:keyboard, :pointer, :touchscreen]`.
96
+ fn remote_desktop_device_types(ruby: &Ruby) -> Result<RArray, Error> {
97
+ let types = block(async { RemoteDesktop::new().await?.available_device_types().await })?
98
+ .map_err(rt_err)?;
99
+
100
+ let array = ruby.ary_new();
101
+ for device_type in types.iter() {
102
+ let _ = array.push(ruby.to_symbol(match device_type {
103
+ DeviceType::Keyboard => "keyboard",
104
+ DeviceType::Pointer => "pointer",
105
+ DeviceType::Touchscreen => "touchscreen",
106
+ }));
107
+ }
108
+
109
+ Ok(array)
110
+ }
111
+
112
+ /// Which kinds of input this host will let an application capture at a screen
113
+ /// edge, as `[:keyboard, :pointer, :touchscreen]`.
114
+ fn input_capture_capabilities(ruby: &Ruby) -> Result<RArray, Error> {
115
+ let capabilities = block(async { InputCapture::new().await?.supported_capabilities().await })?
116
+ .map_err(rt_err)?;
117
+
118
+ let array = ruby.ary_new();
119
+ for capability in capabilities.iter() {
120
+ let _ = array.push(ruby.to_symbol(match capability {
121
+ Capabilities::Keyboard => "keyboard",
122
+ Capabilities::Pointer => "pointer",
123
+ Capabilities::Touchscreen => "touchscreen",
124
+ }));
125
+ }
126
+
127
+ Ok(array)
128
+ }
129
+
130
+ pub fn init(namespace: RModule) -> Result<(), Error> {
131
+ let camera = namespace.define_module("Camera")?;
132
+ camera.define_singleton_method("request_access", function!(camera_request_access, 0))?;
133
+ camera.define_singleton_method(
134
+ "open_pipe_wire_remote",
135
+ function!(camera_open_pipe_wire_remote, 0),
136
+ )?;
137
+
138
+ let usb = namespace.define_module("Usb")?;
139
+ usb.define_singleton_method("devices", function!(usb_devices, 0))?;
140
+
141
+ let remote_desktop = namespace.define_module("RemoteDesktop")?;
142
+ remote_desktop
143
+ .define_singleton_method("available_device_types", function!(remote_desktop_device_types, 0))?;
144
+
145
+ let input_capture = namespace.define_module("InputCapture")?;
146
+ input_capture
147
+ .define_singleton_method("supported_capabilities", function!(input_capture_capabilities, 0))?;
148
+
149
+ let _: Option<RHash> = None;
150
+
151
+ Ok(())
152
+ }
@@ -0,0 +1,211 @@
1
+ //! The portals that deal in files: choosing them, opening them, launching
2
+ //! things that handle them.
3
+ //!
4
+ //! The file chooser is the reason the portals exist at all. A sandboxed
5
+ //! application cannot see the user's files, so it asks the host to run the
6
+ //! dialog; what comes back is a URI the application has been granted, rather
7
+ //! than a path it guessed. Unsandboxed, these behave the same way, which is
8
+ //! what makes code written against them portable into a sandbox later.
9
+ //!
10
+ //! - org.freedesktop.portal.FileChooser
11
+ //! - org.freedesktop.portal.DynamicLauncher
12
+ //! - org.freedesktop.portal.OpenURI (the parts beyond a plain URI)
13
+
14
+ use magnus::{function, prelude::*, Error, RArray, RHash, RModule, Ruby};
15
+
16
+ use ashpd_core::desktop::dynamic_launcher::{DynamicLauncherProxy, LaunchOptions, LauncherType, UninstallOptions};
17
+ use ashpd_core::desktop::file_chooser::{OpenFileRequest, SaveFileRequest, SelectedFiles};
18
+ use ashpd_core::desktop::open_uri::{OpenDirectoryRequest, OpenFileRequest as OpenUriFileRequest, SchemeSupportedOptions};
19
+ use ashpd_core::desktop::open_uri::OpenURIProxy;
20
+
21
+ use crate::{block, option_bool, option_name, rt_err};
22
+
23
+ /// The URIs a chooser came back with. Always a list, because a chooser that
24
+ /// allows several returns several and one that does not returns one - and a
25
+ /// caller that handles the list handles both.
26
+ fn uris_of(ruby: &Ruby, files: &SelectedFiles) -> RArray {
27
+ let array = ruby.ary_new_capa(files.uris().len());
28
+ for uri in files.uris() {
29
+ let _ = array.push(uri.as_str());
30
+ }
31
+ array
32
+ }
33
+
34
+ // --- org.freedesktop.portal.FileChooser ------------------------------------
35
+
36
+ /// Ask the user to choose a file to open, returning the URIs chosen.
37
+ ///
38
+ /// An empty list is not an error: it is the user saying no, which an
39
+ /// application has to handle anyway.
40
+ fn open_file(ruby: &Ruby, title: String, options: RHash) -> Result<RArray, Error> {
41
+ let multiple = option_bool(ruby, options, "multiple");
42
+ let directory = option_bool(ruby, options, "directory");
43
+ let modal = option_bool(ruby, options, "modal");
44
+ let accept_label = option_name(ruby, options, "accept_label")?;
45
+
46
+ let files = block(async {
47
+ OpenFileRequest::default()
48
+ .title(title.as_str())
49
+ .accept_label(accept_label.as_deref())
50
+ .modal(modal)
51
+ .multiple(multiple)
52
+ .directory(directory)
53
+ .send()
54
+ .await?
55
+ .response()
56
+ })?
57
+ .map_err(rt_err)?;
58
+
59
+ Ok(uris_of(ruby, &files))
60
+ }
61
+
62
+ /// Ask the user where to save something, returning the URI chosen.
63
+ fn save_file(ruby: &Ruby, title: String, options: RHash) -> Result<RArray, Error> {
64
+ let modal = option_bool(ruby, options, "modal");
65
+ let accept_label = option_name(ruby, options, "accept_label")?;
66
+ let current_name = option_name(ruby, options, "current_name")?;
67
+
68
+ let files = block(async {
69
+ SaveFileRequest::default()
70
+ .title(title.as_str())
71
+ .accept_label(accept_label.as_deref())
72
+ .modal(modal)
73
+ .current_name(current_name.as_deref())
74
+ .send()
75
+ .await?
76
+ .response()
77
+ })?
78
+ .map_err(rt_err)?;
79
+
80
+ Ok(uris_of(ruby, &files))
81
+ }
82
+
83
+ // --- org.freedesktop.portal.OpenURI ----------------------------------------
84
+
85
+ /// Whether the host has anything that opens this kind of URI, which is worth
86
+ /// knowing before offering the user a button that would do nothing.
87
+ fn scheme_supported(scheme: String) -> Result<bool, Error> {
88
+ block(async {
89
+ OpenURIProxy::new()
90
+ .await?
91
+ .scheme_supported(&scheme, SchemeSupportedOptions::default())
92
+ .await
93
+ })?
94
+ .map_err(rt_err)
95
+ }
96
+
97
+ /// Open a local file with whatever handles it.
98
+ ///
99
+ /// The interface takes a descriptor rather than a path, so the file is opened
100
+ /// here - read-only, because opening is all the handler needs and asking for
101
+ /// write would fail on a file the user can read but not change.
102
+ fn open_path(path: String, ask: bool) -> Result<(), Error> {
103
+ let file = std::fs::File::open(&path).map_err(rt_err)?;
104
+
105
+ block(async {
106
+ OpenUriFileRequest::default()
107
+ .ask(ask)
108
+ .send_file(&file)
109
+ .await?
110
+ .response()
111
+ })?
112
+ .map_err(rt_err)?;
113
+
114
+ Ok(())
115
+ }
116
+
117
+ /// Open a directory in the user's file manager, with the entry selected.
118
+ fn open_directory(path: String) -> Result<(), Error> {
119
+ let directory = std::fs::File::open(&path).map_err(rt_err)?;
120
+
121
+ block(async {
122
+ OpenDirectoryRequest::default()
123
+ .send(&directory)
124
+ .await?
125
+ .response()
126
+ })?
127
+ .map_err(rt_err)?;
128
+
129
+ Ok(())
130
+ }
131
+
132
+ // --- org.freedesktop.portal.DynamicLauncher --------------------------------
133
+
134
+ fn launcher_type_name(launcher_type: LauncherType) -> &'static str {
135
+ match launcher_type {
136
+ LauncherType::Application => "application",
137
+ LauncherType::WebApplication => "web_application",
138
+ }
139
+ }
140
+
141
+ /// Which kinds of launcher this host will install, as symbols.
142
+ fn supported_launcher_types(ruby: &Ruby) -> Result<RArray, Error> {
143
+ let types = block(async {
144
+ DynamicLauncherProxy::new()
145
+ .await?
146
+ .supported_launcher_types()
147
+ .await
148
+ })?
149
+ .map_err(rt_err)?;
150
+
151
+ let array = ruby.ary_new();
152
+ for launcher_type in types.iter() {
153
+ let _ = array.push(ruby.to_symbol(launcher_type_name(launcher_type)));
154
+ }
155
+
156
+ Ok(array)
157
+ }
158
+
159
+ /// The desktop entry of a launcher this application installed, as the text of
160
+ /// the file.
161
+ fn desktop_entry(desktop_file_id: String) -> Result<String, Error> {
162
+ block(async {
163
+ DynamicLauncherProxy::new()
164
+ .await?
165
+ .desktop_entry(&desktop_file_id)
166
+ .await
167
+ })?
168
+ .map_err(rt_err)
169
+ }
170
+
171
+ /// Launch something this application installed earlier.
172
+ fn launch(desktop_file_id: String) -> Result<(), Error> {
173
+ block(async {
174
+ DynamicLauncherProxy::new()
175
+ .await?
176
+ .launch(&desktop_file_id, LaunchOptions::default())
177
+ .await
178
+ })?
179
+ .map_err(rt_err)
180
+ }
181
+
182
+ /// Remove a launcher this application installed. The portal only allows an
183
+ /// application to remove its own.
184
+ fn uninstall(desktop_file_id: String) -> Result<(), Error> {
185
+ block(async {
186
+ DynamicLauncherProxy::new()
187
+ .await?
188
+ .uninstall(&desktop_file_id, UninstallOptions::default())
189
+ .await
190
+ })?
191
+ .map_err(rt_err)
192
+ }
193
+
194
+ pub fn init(namespace: RModule) -> Result<(), Error> {
195
+ let chooser = namespace.define_module("FileChooser")?;
196
+ chooser.define_singleton_method("open_file", function!(open_file, 2))?;
197
+ chooser.define_singleton_method("save_file", function!(save_file, 2))?;
198
+
199
+ let open_uri = namespace.define_module("OpenUri")?;
200
+ open_uri.define_singleton_method("scheme_supported?", function!(scheme_supported, 1))?;
201
+ open_uri.define_singleton_method("open_path", function!(open_path, 2))?;
202
+ open_uri.define_singleton_method("open_directory", function!(open_directory, 1))?;
203
+
204
+ let launcher = namespace.define_module("DynamicLauncher")?;
205
+ launcher.define_singleton_method("supported_launcher_types", function!(supported_launcher_types, 0))?;
206
+ launcher.define_singleton_method("desktop_entry", function!(desktop_entry, 1))?;
207
+ launcher.define_singleton_method("launch", function!(launch, 1))?;
208
+ launcher.define_singleton_method("uninstall", function!(uninstall, 1))?;
209
+
210
+ Ok(())
211
+ }
data/ext/ashpd/src/lib.rs CHANGED
@@ -8,7 +8,8 @@
8
8
  //!
9
9
  //! Each portal is a module function or a class method under `Ashpd`, named for
10
10
  //! the interface it speaks to: `Ashpd::Screenshot`, `Ashpd::OpenUri`,
11
- //! `Ashpd::Trash`, `Ashpd::Settings`, `Ashpd::Camera`, `Ashpd::Account`.
11
+ //! `Ashpd::Trash`, `Ashpd::Settings`, `Ashpd::Camera`, `Ashpd::Account`,
12
+ //! `Ashpd::ScreenCast`.
12
13
  //!
13
14
  //! # Blocking
14
15
  //!
@@ -40,20 +41,28 @@ use std::fs::File;
40
41
  use std::future::Future;
41
42
  use std::sync::OnceLock;
42
43
 
43
- use magnus::{function, prelude::*, Error, RArray, RHash, Ruby};
44
+ use magnus::{function, prelude::*, Error, RArray, RHash, Ruby, TryConvert, Value};
44
45
 
45
46
  use ashpd_core::desktop::account::UserInformation;
46
47
  use ashpd_core::desktop::camera::Camera;
47
48
  use ashpd_core::desktop::open_uri::OpenFileRequest;
48
49
  use ashpd_core::desktop::screenshot::Screenshot;
49
- use ashpd_core::desktop::settings::{ColorScheme, Settings};
50
+ use ashpd_core::desktop::screenshot::AvailableTargets;
51
+ use ashpd_core::desktop::settings::{ColorScheme, Contrast, ReducedMotion, Settings};
50
52
  use ashpd_core::desktop::trash;
51
53
  use ashpd_core::Uri;
52
54
  use tokio::runtime::{Builder, Runtime};
53
55
 
56
+ mod devices;
57
+ mod files;
58
+ mod screencast;
59
+ mod sessions;
60
+ mod shell;
61
+ mod system;
62
+
54
63
  // --- helpers ---------------------------------------------------------------
55
64
 
56
- fn rt_err<E: std::fmt::Display>(e: E) -> Error {
65
+ pub(crate) fn rt_err<E: std::fmt::Display>(e: E) -> Error {
57
66
  // Safe: every caller runs inside a Ruby method invocation (GVL held).
58
67
  let ruby = Ruby::get().expect("rt_err called outside the Ruby VM");
59
68
  Error::new(ruby.exception_runtime_error(), e.to_string())
@@ -65,7 +74,7 @@ fn rt_err<E: std::fmt::Display>(e: E) -> Error {
65
74
  /// task, so the runtime has to keep driving background work while a portal
66
75
  /// request waits for the user to answer a dialog. Hence the multi-thread
67
76
  /// flavour with one worker, as in oo7-rb.
68
- fn runtime() -> Result<&'static Runtime, Error> {
77
+ pub(crate) fn runtime() -> Result<&'static Runtime, Error> {
69
78
  static RUNTIME: OnceLock<std::io::Result<Runtime>> = OnceLock::new();
70
79
 
71
80
  RUNTIME
@@ -74,7 +83,7 @@ fn runtime() -> Result<&'static Runtime, Error> {
74
83
  .map_err(rt_err)
75
84
  }
76
85
 
77
- fn block<F: Future>(future: F) -> Result<F::Output, Error> {
86
+ pub(crate) fn block<F: Future>(future: F) -> Result<F::Output, Error> {
78
87
  Ok(runtime()?.block_on(future))
79
88
  }
80
89
 
@@ -91,6 +100,58 @@ fn uri_from(uri: &str) -> Result<Uri, Error> {
91
100
  Uri::parse(uri).map_err(rt_err)
92
101
  }
93
102
 
103
+ /// Reads an option, as the string it names. Absent and nil read alike, so a
104
+ /// caller can pass a key through without having to decide whether to omit it.
105
+ pub(crate) fn option_name(ruby: &Ruby, options: RHash, key: &str) -> Result<Option<String>, Error> {
106
+ let Some(value) = options.get(ruby.to_symbol(key)) else {
107
+ return Ok(None);
108
+ };
109
+
110
+ if value.is_nil() {
111
+ return Ok(None);
112
+ }
113
+
114
+ Ok(Some(value.to_r_string()?.to_string()?))
115
+ }
116
+
117
+ pub(crate) fn option_bool(ruby: &Ruby, options: RHash, key: &str) -> Option<bool> {
118
+ options
119
+ .get(ruby.to_symbol(key))
120
+ .filter(|value: &Value| !value.is_nil())
121
+ .map(|value| value.to_bool())
122
+ }
123
+
124
+
125
+ /// Reads an option that is a number, absent and nil alike.
126
+ pub(crate) fn option_number(ruby: &Ruby, options: RHash, key: &str) -> Result<Option<f64>, Error> {
127
+ let Some(value) = options.get(ruby.to_symbol(key)) else {
128
+ return Ok(None);
129
+ };
130
+
131
+ if value.is_nil() {
132
+ return Ok(None);
133
+ }
134
+
135
+ Ok(Some(f64::try_convert(value)?))
136
+ }
137
+
138
+ /// Reads an option that is a list of strings, empty when absent. Several
139
+ /// portals take one and treat "none given" and "an empty list" alike.
140
+ pub(crate) fn option_strings(ruby: &Ruby, options: RHash, key: &str) -> Result<Vec<String>, Error> {
141
+ let Some(value) = options.get(ruby.to_symbol(key)) else {
142
+ return Ok(Vec::new());
143
+ };
144
+
145
+ if value.is_nil() {
146
+ return Ok(Vec::new());
147
+ }
148
+
149
+ RArray::try_convert(value)?
150
+ .into_iter()
151
+ .map(|item| item.to_r_string()?.to_string())
152
+ .collect()
153
+ }
154
+
94
155
  // --- org.freedesktop.portal.Screenshot -------------------------------------
95
156
 
96
157
  /// Take a screenshot, returning the URI of the file the portal wrote.
@@ -169,6 +230,51 @@ fn accent_color(ruby: &Ruby) -> Result<RArray, Error> {
169
230
  Ok(color_to(ruby, color.red(), color.green(), color.blue()))
170
231
  }
171
232
 
233
+ /// Whether the user asked for more contrast, as "no_preference" or "high".
234
+ fn contrast() -> Result<String, Error> {
235
+ let settings = block(Settings::new())?.map_err(rt_err)?;
236
+ let contrast = block(settings.contrast())?.map_err(rt_err)?;
237
+
238
+ Ok(match contrast {
239
+ Contrast::NoPreference => "no_preference",
240
+ Contrast::High => "high",
241
+ }
242
+ .to_owned())
243
+ }
244
+
245
+ /// Whether the user asked for less animation, as "no_preference" or
246
+ /// "reduced_motion". Worth honouring: it is an accessibility setting, not a
247
+ /// taste one.
248
+ fn reduced_motion() -> Result<String, Error> {
249
+ let settings = block(Settings::new())?.map_err(rt_err)?;
250
+ let reduced = block(settings.reduced_motion())?.map_err(rt_err)?;
251
+
252
+ Ok(match reduced {
253
+ ReducedMotion::NoPreference => "no_preference",
254
+ ReducedMotion::ReducedMotion => "reduced_motion",
255
+ }
256
+ .to_owned())
257
+ }
258
+
259
+ /// Which kinds of screenshot this host offers, as `[:screen, :window, :area,
260
+ /// :active_window]` -- what an interactive shot may let the user pick.
261
+ fn available_targets(ruby: &Ruby) -> Result<RArray, Error> {
262
+ let proxy = block(ashpd_core::desktop::screenshot::ScreenshotProxy::new())?.map_err(rt_err)?;
263
+ let targets = block(proxy.available_targets())?.map_err(rt_err)?;
264
+
265
+ let array = ruby.ary_new();
266
+ for target in targets.iter() {
267
+ let _ = array.push(ruby.to_symbol(match target {
268
+ AvailableTargets::Screen => "screen",
269
+ AvailableTargets::Window => "window",
270
+ AvailableTargets::Area => "area",
271
+ AvailableTargets::ActiveWindow => "active_window",
272
+ }));
273
+ }
274
+
275
+ Ok(array)
276
+ }
277
+
172
278
  // --- org.freedesktop.portal.Camera -----------------------------------------
173
279
 
174
280
  /// Whether the host has a camera at all.
@@ -209,6 +315,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
209
315
  let screenshot_module = namespace.define_module("Screenshot")?;
210
316
  screenshot_module.define_singleton_method("capture", function!(screenshot, 2))?;
211
317
  screenshot_module.define_singleton_method("pick_color", function!(pick_color, 0))?;
318
+ screenshot_module.define_singleton_method("available_targets", function!(available_targets, 0))?;
212
319
 
213
320
  let open_uri_module = namespace.define_module("OpenUri")?;
214
321
  open_uri_module.define_singleton_method("open", function!(open_uri, 3))?;
@@ -219,6 +326,8 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
219
326
  let settings_module = namespace.define_module("Settings")?;
220
327
  settings_module.define_singleton_method("color_scheme", function!(color_scheme, 0))?;
221
328
  settings_module.define_singleton_method("accent_color", function!(accent_color, 0))?;
329
+ settings_module.define_singleton_method("contrast", function!(contrast, 0))?;
330
+ settings_module.define_singleton_method("reduced_motion", function!(reduced_motion, 0))?;
222
331
 
223
332
  let camera_module = namespace.define_module("Camera")?;
224
333
  camera_module.define_singleton_method("present?", function!(camera_present, 0))?;
@@ -226,5 +335,14 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
226
335
  let account_module = namespace.define_module("Account")?;
227
336
  account_module.define_singleton_method("user_information", function!(user_information, 1))?;
228
337
 
338
+ // ScreenCast is a session rather than a single call, so it defines a class
339
+ // of its own and registers itself.
340
+ screencast::init(ruby, namespace)?;
341
+ devices::init(namespace)?;
342
+ files::init(namespace)?;
343
+ sessions::init(ruby, namespace)?;
344
+ shell::init(namespace)?;
345
+ system::init(namespace)?;
346
+
229
347
  Ok(())
230
348
  }