Debian Codegraph @

src/activation_token/wayland.rs

raw
1 use wayland_backend::sys::client::Backend;
2 use wayland_client::{
3 Proxy, QueueHandle,
4 protocol::{wl_registry, wl_seat::WlSeat, wl_surface::WlSurface},
5 };
6 use wayland_protocols::xdg::activation::v1::client::{
7 xdg_activation_token_v1::{Event, XdgActivationTokenV1},
8 xdg_activation_v1::XdgActivationV1,
9 };
10
11 use crate::{ActivationToken, AppID};
12
13 // Supported versions.
14 const XDG_ACTIVATION_V1_VERSION: u32 = 1;
15
16 #[derive(Default)]
17 struct WaylandHandle {
18 wl_token: Option<XdgActivationTokenV1>,
19 raw_token: Option<String>,
20 }
21
22 impl Drop for WaylandHandle {
23 fn drop(&mut self) {
24 if let Some(wl_token) = self.wl_token.take() {
25 wl_token.destroy();
26 }
27 }
28 }
29
30 impl ActivationToken {
31 #[cfg(feature = "wayland")]
32 #[cfg_attr(docsrs, doc(cfg(feature = "wayland")))]
33 /// Create an instance of [`ActivationToken`] from a Wayland surface.
34 pub async fn from_surface(app_id: Option<AppID>, surface: &WlSurface) -> Option<Self> {
35 let backend = surface.backend().upgrade()?;
36 let conn = wayland_client::Connection::from_backend(backend);
37
38 Self::new_wayland_inner(app_id, conn, surface, None, None).await
39 }
40
41 #[cfg(feature = "wayland")]
42 #[cfg_attr(docsrs, doc(cfg(feature = "wayland")))]
43 /// Create an instance of [`ActivationToken`] from a Wayland surface with
44 /// serial and seat.
45 ///
46 /// The serial and seat information prove that the activation is in response
47 /// to a recent user action. Some compositors might refuse to activate
48 /// windows when the token doesn't have a valid and recent event serial.
49 ///
50 /// The serial typically comes from input events like `wl_pointer.button` or
51 /// `wl_keyboard.key`.
52 pub async fn from_surface_with_serial(
53 app_id: Option<AppID>,
54 surface: &WlSurface,
55 serial: u32,
56 seat: &WlSeat,
57 ) -> Option<Self> {
58 let backend = surface.backend().upgrade()?;
59 let conn = wayland_client::Connection::from_backend(backend);
60
61 Self::new_wayland_inner(app_id, conn, surface, Some(serial), Some(seat)).await
62 }
63
64 #[cfg(feature = "wayland")]
65 #[cfg_attr(docsrs, doc(cfg(feature = "wayland")))]
66 /// Create an instance of [`ActivationToken`] from a Wayland surface.
67 ///
68 /// # Safety
69 ///
70 /// Both surface and display pointers have to be valid.
71 pub async unsafe fn from_wayland_raw(
72 app_id: Option<AppID>,
73 surface_ptr: *mut std::ffi::c_void,
74 display_ptr: *mut std::ffi::c_void,
75 ) -> Option<Self> {
76 if surface_ptr.is_null() || display_ptr.is_null() {
77 return None;
78 }
79
80 let backend = unsafe { Backend::from_foreign_display(display_ptr as *mut _) };
81 let conn = wayland_client::Connection::from_backend(backend);
82 let obj_id = unsafe {
83 wayland_backend::sys::client::ObjectId::from_ptr(
84 WlSurface::interface(),
85 surface_ptr as *mut _,
86 )
87 }
88 .ok()?;
89
90 let surface = WlSurface::from_id(&conn, obj_id).ok()?;
91
92 Self::new_wayland_inner(app_id, conn, &surface, None, None).await
93 }
94
95 #[cfg(feature = "wayland")]
96 #[cfg_attr(docsrs, doc(cfg(feature = "wayland")))]
97 /// Create an instance of [`ActivationToken`] from a Wayland surface with
98 /// serial and seat.
99 ///
100 /// The serial and seat information prove that the activation is in response
101 /// to a recent user action. Some compositors might refuse to activate
102 /// windows when the token doesn't have a valid and recent event serial.
103 ///
104 /// The serial typically comes from input events like `wl_pointer.button` or
105 /// `wl_keyboard.key`.
106 ///
107 /// # Safety
108 ///
109 /// Both surface, display, and seat pointers have to be valid.
110 pub async unsafe fn from_wayland_raw_with_serial(
111 app_id: Option<AppID>,
112 surface_ptr: *mut std::ffi::c_void,
113 display_ptr: *mut std::ffi::c_void,
114 serial: u32,
115 seat_ptr: *mut std::ffi::c_void,
116 ) -> Option<Self> {
117 if surface_ptr.is_null() || display_ptr.is_null() {
118 return None;
119 }
120
121 let backend = unsafe { Backend::from_foreign_display(display_ptr as *mut _) };
122 let conn = wayland_client::Connection::from_backend(backend);
123 let surface_obj_id = unsafe {
124 wayland_backend::sys::client::ObjectId::from_ptr(
125 WlSurface::interface(),
126 surface_ptr as *mut _,
127 )
128 }
129 .ok()?;
130
131 let surface = WlSurface::from_id(&conn, surface_obj_id).ok()?;
132
133 let seat = if !seat_ptr.is_null() {
134 let seat_obj_id = unsafe {
135 wayland_backend::sys::client::ObjectId::from_ptr(
136 WlSeat::interface(),
137 seat_ptr as *mut _,
138 )
139 }
140 .ok()?;
141
142 Some(WlSeat::from_id(&conn, seat_obj_id).ok()?)
143 } else {
144 None
145 };
146 Self::new_wayland_inner(app_id, conn, &surface, Some(serial), seat.as_ref()).await
147 }
148
149 async fn new_wayland_inner(
150 app_id: Option<AppID>,
151 conn: wayland_client::Connection,
152 surface: &WlSurface,
153 serial: Option<u32>,
154 seat: Option<&WlSeat>,
155 ) -> Option<Self> {
156 let (sender, receiver) = futures_channel::oneshot::channel::<Option<Self>>();
157
158 // Cheap clone, protocol objects are essentially smart pointers
159 let surface = surface.clone();
160 let seat = seat.cloned();
161 std::thread::spawn(move || {
162 match wayland_export_token(app_id, conn, &surface, serial, seat.as_ref()) {
163 Ok(window_handle) => sender.send(Some(window_handle)).unwrap(),
164 Err(_err) => {
165 #[cfg(feature = "tracing")]
166 tracing::info!("Could not get wayland window identifier: {_err}");
167 sender.send(None).unwrap();
168 }
169 }
170 });
171
172 receiver.await.unwrap()
173 }
174 }
175
176 impl wayland_client::Dispatch<XdgActivationTokenV1, ()> for WaylandHandle {
177 fn event(
178 state: &mut Self,
179 _proxy: &XdgActivationTokenV1,
180 event: <XdgActivationTokenV1 as Proxy>::Event,
181 _data: &(),
182 _connhandle: &wayland_client::Connection,
183 _qhandle: &QueueHandle<Self>,
184 ) {
185 if let Event::Done { token } = event {
186 state.raw_token = Some(token);
187 }
188 }
189 }
190
191 impl wayland_client::Dispatch<wl_registry::WlRegistry, ()> for WaylandHandle {
192 fn event(
193 state: &mut Self,
194 registry: &wl_registry::WlRegistry,
195 event: wl_registry::Event,
196 _data: &(),
197 _connhandle: &wayland_client::Connection,
198 qhandle: &QueueHandle<Self>,
199 ) {
200 if let wl_registry::Event::Global {
201 name,
202 interface,
203 version,
204 } = event
205 && &interface == "xdg_activation_v1"
206 {
207 #[cfg(feature = "tracing")]
208 tracing::info!("Found wayland interface {interface} v{version}");
209 let wl_activation = registry.bind::<XdgActivationV1, (), Self>(
210 name,
211 version.min(XDG_ACTIVATION_V1_VERSION),
212 qhandle,
213 (),
214 );
215 let wl_token = wl_activation.get_activation_token(qhandle, ());
216 state.wl_token = Some(wl_token);
217 wl_activation.destroy();
218 }
219 }
220 }
221
222 impl wayland_client::Dispatch<XdgActivationV1, ()> for WaylandHandle {
223 fn event(
224 _state: &mut Self,
225 _activation: &XdgActivationV1,
226 _event: wayland_protocols::xdg::activation::v1::client::xdg_activation_v1::Event,
227 _data: &(),
228 _connhandle: &wayland_client::Connection,
229 _qhandle: &QueueHandle<Self>,
230 ) {
231 }
232 }
233
234 fn wayland_export_token(
235 app_id: Option<AppID>,
236 conn: wayland_client::Connection,
237 surface: &WlSurface,
238 serial: Option<u32>,
239 seat: Option<&WlSeat>,
240 ) -> Result<ActivationToken, Box<dyn std::error::Error>> {
241 let display = conn.display();
242 let mut event_queue = conn.new_event_queue();
243 let mut state = WaylandHandle::default();
244 let qhandle = event_queue.handle();
245 display.get_registry(&qhandle, ());
246 event_queue.roundtrip(&mut state)?;
247
248 if let Some(wl_token) = state.wl_token.take() {
249 if let Some(app_id) = app_id {
250 wl_token.set_app_id(app_id.to_string());
251 }
252 wl_token.set_surface(surface);
253 if let Some(serial) = serial
254 && let Some(seat) = seat
255 {
256 wl_token.set_serial(serial, seat);
257 }
258 wl_token.commit();
259
260 event_queue.roundtrip(&mut state)?;
261 };
262
263 if let Some(raw_token) = state.raw_token.take() {
264 Ok(ActivationToken::from(raw_token))
265 } else {
266 #[cfg(feature = "tracing")]
267 tracing::error!("Failed to get a response from the wayland server");
268
269 Err(Box::new(crate::Error::NoResponse))
270 }
271 }