niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·ce9dd33·sodiboo·1 year ago·2737 commits
| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::sync::Arc; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use calloop::generic::Generic; |
| 7 | use calloop::{Interest, LoopHandle, Mode, PostAction}; |
| 8 | use smithay::backend::allocator::dmabuf::Dmabuf; |
| 9 | use smithay::backend::allocator::{Buffer, Fourcc}; |
| 10 | use smithay::backend::renderer::damage::OutputDamageTracker; |
| 11 | use smithay::backend::renderer::sync::SyncPoint; |
| 12 | use smithay::output::{Output, WeakOutput}; |
| 13 | use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::{ |
| 14 | zwlr_screencopy_frame_v1, zwlr_screencopy_manager_v1, |
| 15 | }; |
| 16 | use smithay::reexports::wayland_server::protocol::wl_buffer::WlBuffer; |
| 17 | use smithay::reexports::wayland_server::protocol::wl_shm::Format; |
| 18 | use smithay::reexports::wayland_server::{ |
| 19 | Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, |
| 20 | }; |
| 21 | use smithay::utils::{Physical, Point, Rectangle, Size, Transform}; |
| 22 | use smithay::wayland::{dmabuf, shm}; |
| 23 | use wayland_backend::server::Credentials; |
| 24 | use zwlr_screencopy_frame_v1::{Flags, ZwlrScreencopyFrameV1}; |
| 25 | use zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1; |
| 26 | |
| 27 | use crate::utils::{get_credentials_for_client, get_monotonic_time, CastSessionId, CastStreamId}; |
| 28 | |
| 29 | const VERSION: u32 = 3; |
| 30 | |
| 31 | /// Inactivity timeout for considering a screencopy cast as stopped. |
| 32 | /// |
| 33 | /// xdg-desktop-portal-wlr keeps the screencopy manager alive across casts, so there's no way to |
| 34 | /// tell that a screencast had stopped. So we use a timeout: if no new with_damage frames are |
| 35 | /// requested for this timeout, consider the screencast finished. |
| 36 | const CAST_TIMEOUT: Duration = Duration::from_secs(10); |
| 37 | |
| 38 | pub struct ScreencopyQueue { |
| 39 | /// Credentials of this wlr-screencopy client, if known. |
| 40 | credentials: Option<Credentials>, |
| 41 | damage_tracker: OutputDamageTracker, |
| 42 | /// Frames waiting for the client to call copy or destroy. |
| 43 | pending_frames: HashSet<ZwlrScreencopyFrameV1>, |
| 44 | /// Queue of screencopies waiting for a corresponding output redraw with damage. |
| 45 | screencopies: Vec<Screencopy>, |
| 46 | /// Cast tracking, set when the first with_damage request arrives. |
| 47 | cast: Option<ScreencopyCast>, |
| 48 | } |
| 49 | |
| 50 | pub struct ScreencopyCast { |
| 51 | pub session_id: CastSessionId, |
| 52 | pub stream_id: CastStreamId, |
| 53 | /// Output being captured. |
| 54 | /// |
| 55 | /// Generally equal to the front entry in the queue, and persisted here when the queue becomes |
| 56 | /// empty. |
| 57 | pub output: WeakOutput, |
| 58 | /// Cached name of the output. |
| 59 | pub output_name: String, |
| 60 | /// Deadline after which this cast is considered stopped if no new frames arrive. |
| 61 | pub deadline: Duration, |
| 62 | } |
| 63 | |
| 64 | impl ScreencopyCast { |
| 65 | fn new(output: &Output) -> Self { |
| 66 | Self { |
| 67 | session_id: CastSessionId::next(), |
| 68 | stream_id: CastStreamId::next(), |
| 69 | output: output.downgrade(), |
| 70 | output_name: output.name(), |
| 71 | deadline: get_monotonic_time() + CAST_TIMEOUT, |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | fn update_deadline(&mut self) { |
| 76 | self.deadline = get_monotonic_time() + CAST_TIMEOUT; |
| 77 | } |
| 78 | |
| 79 | fn update_output(&mut self, output: &Output) { |
| 80 | // Only allocate a new name when the output differs. |
| 81 | let weak = output.downgrade(); |
| 82 | if self.output != weak { |
| 83 | self.output = weak; |
| 84 | self.output_name = output.name(); |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | impl ScreencopyQueue { |
| 90 | pub fn new(credentials: Option<Credentials>) -> Self { |
| 91 | Self { |
| 92 | damage_tracker: OutputDamageTracker::new((0, 0), 1.0, Transform::Normal), |
| 93 | pending_frames: HashSet::new(), |
| 94 | screencopies: Vec::new(), |
| 95 | cast: None, |
| 96 | credentials, |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | pub fn is_empty(&self) -> bool { |
| 101 | self.pending_frames.is_empty() && self.screencopies.is_empty() |
| 102 | } |
| 103 | |
| 104 | /// Get the cast tracking info, if this queue is tracking a cast. |
| 105 | pub fn cast(&self) -> Option<&ScreencopyCast> { |
| 106 | self.cast.as_ref() |
| 107 | } |
| 108 | |
| 109 | pub fn credentials(&self) -> Option<Credentials> { |
| 110 | self.credentials |
| 111 | } |
| 112 | |
| 113 | pub fn split(&mut self) -> (&mut OutputDamageTracker, Option<&Screencopy>) { |
| 114 | let ScreencopyQueue { |
| 115 | damage_tracker, |
| 116 | screencopies, |
| 117 | .. |
| 118 | } = self; |
| 119 | (damage_tracker, screencopies.first()) |
| 120 | } |
| 121 | |
| 122 | pub fn push(&mut self, screencopy: Screencopy) { |
| 123 | // Screencopy without damage is rendered immediately without the queue. |
| 124 | if !screencopy.with_damage() { |
| 125 | error!("only screencopy with damage can be pushed in the queue"); |
| 126 | } |
| 127 | |
| 128 | if let Some(cast) = &mut self.cast { |
| 129 | // Update cast output when pushing a new front screencopy. |
| 130 | if self.screencopies.is_empty() { |
| 131 | cast.update_output(screencopy.output()); |
| 132 | } |
| 133 | } else { |
| 134 | // First with_damage request, mark this as a screencast. |
| 135 | let output = screencopy.output(); |
| 136 | self.cast = Some(ScreencopyCast::new(output)); |
| 137 | } |
| 138 | |
| 139 | self.screencopies.push(screencopy); |
| 140 | } |
| 141 | |
| 142 | pub fn pop(&mut self) -> Screencopy { |
| 143 | let rv = self.screencopies.remove(0); |
| 144 | |
| 145 | let cast = self.cast.as_mut().unwrap(); |
| 146 | if let Some(first) = self.screencopies.first() { |
| 147 | // Update cast output (most of the time we expect this to be the same). |
| 148 | cast.update_output(first.output()); |
| 149 | } else { |
| 150 | // Queue became empty, update deadline for considering the cast stopped. |
| 151 | cast.update_deadline(); |
| 152 | } |
| 153 | |
| 154 | rv |
| 155 | } |
| 156 | |
| 157 | pub fn clear_expired_cast(&mut self) { |
| 158 | if let Some(cast) = &self.cast { |
| 159 | // Check deadline if there are no in-flight frames. |
| 160 | if self.screencopies.is_empty() && cast.deadline <= get_monotonic_time() { |
| 161 | self.cast = None; |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | fn remove_output(&mut self, output: &Output) { |
| 167 | if self.screencopies.is_empty() { |
| 168 | return; |
| 169 | } |
| 170 | |
| 171 | self.screencopies |
| 172 | .retain(|screencopy| screencopy.output() != output); |
| 173 | |
| 174 | if let Some(cast) = &mut self.cast { |
| 175 | if self.screencopies.is_empty() { |
| 176 | // Queue became empty, update deadline for considering the cast stopped. |
| 177 | cast.update_deadline(); |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | fn remove_frame(&mut self, frame: &ZwlrScreencopyFrameV1) { |
| 183 | self.pending_frames.remove(frame); |
| 184 | |
| 185 | if self.screencopies.is_empty() { |
| 186 | return; |
| 187 | } |
| 188 | |
| 189 | self.screencopies |
| 190 | .retain(|screencopy| screencopy.frame != *frame); |
| 191 | |
| 192 | if let Some(cast) = &mut self.cast { |
| 193 | if self.screencopies.is_empty() { |
| 194 | // Queue became empty, update deadline for considering the cast stopped. |
| 195 | cast.update_deadline(); |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | #[derive(Default)] |
| 202 | pub struct ScreencopyManagerState { |
| 203 | queues: HashMap<ZwlrScreencopyManagerV1, ScreencopyQueue>, |
| 204 | } |
| 205 | |
| 206 | pub struct ScreencopyManagerGlobalData { |
| 207 | filter: Box<dyn for<'c> Fn(&'c Client) -> bool + Send + Sync>, |
| 208 | } |
| 209 | |
| 210 | impl ScreencopyManagerState { |
| 211 | pub fn new<D, F>(display: &DisplayHandle, filter: F) -> Self |
| 212 | where |
| 213 | D: GlobalDispatch<ZwlrScreencopyManagerV1, ScreencopyManagerGlobalData>, |
| 214 | D: Dispatch<ZwlrScreencopyManagerV1, ()>, |
| 215 | D: Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState>, |
| 216 | D: ScreencopyHandler, |
| 217 | D: 'static, |
| 218 | F: for<'c> Fn(&'c Client) -> bool + Send + Sync + 'static, |
| 219 | { |
| 220 | let global_data = ScreencopyManagerGlobalData { |
| 221 | filter: Box::new(filter), |
| 222 | }; |
| 223 | display.create_global::<D, ZwlrScreencopyManagerV1, _>(VERSION, global_data); |
| 224 | |
| 225 | Self { |
| 226 | queues: HashMap::new(), |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | pub fn push(&mut self, manager: &ZwlrScreencopyManagerV1, screencopy: Screencopy) { |
| 231 | let Some(queue) = self.queues.get_mut(manager) else { |
| 232 | // Destroying the manager does not invalidate existing frames, so the queue should |
| 233 | // keep existing. |
| 234 | error!("screencopy queue must not be deleted as long as frames exist"); |
| 235 | return; |
| 236 | }; |
| 237 | |
| 238 | queue.push(screencopy); |
| 239 | } |
| 240 | |
| 241 | pub fn damage_tracker( |
| 242 | &mut self, |
| 243 | manager: &ZwlrScreencopyManagerV1, |
| 244 | ) -> Option<&mut OutputDamageTracker> { |
| 245 | let queue = self.queues.get_mut(manager)?; |
| 246 | Some(&mut queue.damage_tracker) |
| 247 | } |
| 248 | |
| 249 | pub fn remove_output(&mut self, output: &Output) { |
| 250 | for queue in self.queues.values_mut() { |
| 251 | queue.remove_output(output); |
| 252 | } |
| 253 | |
| 254 | self.cleanup_queues(); |
| 255 | } |
| 256 | |
| 257 | pub fn queues(&self) -> impl Iterator<Item = &ScreencopyQueue> { |
| 258 | self.queues.values() |
| 259 | } |
| 260 | |
| 261 | pub fn with_queues_mut(&mut self, mut f: impl FnMut(&mut ScreencopyQueue)) { |
| 262 | for queue in self.queues.values_mut() { |
| 263 | f(queue); |
| 264 | } |
| 265 | |
| 266 | self.cleanup_queues(); |
| 267 | } |
| 268 | |
| 269 | fn cleanup_queues(&mut self) { |
| 270 | self.queues |
| 271 | .retain(|manager, queue| manager.is_alive() || !queue.is_empty()); |
| 272 | } |
| 273 | |
| 274 | pub fn clear_expired_casts(&mut self) { |
| 275 | for queue in self.queues.values_mut() { |
| 276 | queue.clear_expired_cast(); |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | impl<D> GlobalDispatch<ZwlrScreencopyManagerV1, ScreencopyManagerGlobalData, D> |
| 282 | for ScreencopyManagerState |
| 283 | where |
| 284 | D: GlobalDispatch<ZwlrScreencopyManagerV1, ScreencopyManagerGlobalData>, |
| 285 | D: Dispatch<ZwlrScreencopyManagerV1, ()>, |
| 286 | D: Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState>, |
| 287 | D: ScreencopyHandler, |
| 288 | D: 'static, |
| 289 | { |
| 290 | fn bind( |
| 291 | state: &mut D, |
| 292 | dh: &DisplayHandle, |
| 293 | client: &Client, |
| 294 | manager: New<ZwlrScreencopyManagerV1>, |
| 295 | _manager_state: &ScreencopyManagerGlobalData, |
| 296 | data_init: &mut DataInit<'_, D>, |
| 297 | ) { |
| 298 | let manager = data_init.init(manager, ()); |
| 299 | |
| 300 | let state = state.screencopy_state(); |
| 301 | let credentials = get_credentials_for_client(dh, client); |
| 302 | let queue = ScreencopyQueue::new(credentials); |
| 303 | state.queues.insert(manager.clone(), queue); |
| 304 | } |
| 305 | |
| 306 | fn can_view(client: Client, global_data: &ScreencopyManagerGlobalData) -> bool { |
| 307 | (global_data.filter)(&client) |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | impl<D> Dispatch<ZwlrScreencopyManagerV1, (), D> for ScreencopyManagerState |
| 312 | where |
| 313 | D: GlobalDispatch<ZwlrScreencopyManagerV1, ScreencopyManagerGlobalData>, |
| 314 | D: Dispatch<ZwlrScreencopyManagerV1, ()>, |
| 315 | D: Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState>, |
| 316 | D: ScreencopyHandler, |
| 317 | D: 'static, |
| 318 | { |
| 319 | fn request( |
| 320 | state: &mut D, |
| 321 | _client: &Client, |
| 322 | manager: &ZwlrScreencopyManagerV1, |
| 323 | request: zwlr_screencopy_manager_v1::Request, |
| 324 | _data: &(), |
| 325 | _display: &DisplayHandle, |
| 326 | data_init: &mut DataInit<'_, D>, |
| 327 | ) { |
| 328 | let (frame, overlay_cursor, buffer_size, region_loc, output) = match request { |
| 329 | zwlr_screencopy_manager_v1::Request::CaptureOutput { |
| 330 | frame, |
| 331 | overlay_cursor, |
| 332 | output, |
| 333 | } => { |
| 334 | let Some(output) = Output::from_resource(&output) else { |
| 335 | trace!("screencopy client requested non-existent output"); |
| 336 | let frame = data_init.init(frame, ScreencopyFrameState::Failed); |
| 337 | frame.failed(); |
| 338 | return; |
| 339 | }; |
| 340 | |
| 341 | let buffer_size = output.current_mode().unwrap().size; |
| 342 | let region_loc = Point::from((0, 0)); |
| 343 | |
| 344 | (frame, overlay_cursor, buffer_size, region_loc, output) |
| 345 | } |
| 346 | zwlr_screencopy_manager_v1::Request::CaptureOutputRegion { |
| 347 | frame, |
| 348 | overlay_cursor, |
| 349 | x, |
| 350 | y, |
| 351 | width, |
| 352 | height, |
| 353 | output, |
| 354 | } => { |
| 355 | if width <= 0 || height <= 0 { |
| 356 | trace!("screencopy client requested invalid sized region"); |
| 357 | let frame = data_init.init(frame, ScreencopyFrameState::Failed); |
| 358 | frame.failed(); |
| 359 | return; |
| 360 | } |
| 361 | |
| 362 | let Some(output) = Output::from_resource(&output) else { |
| 363 | trace!("screencopy client requested non-existent output"); |
| 364 | let frame = data_init.init(frame, ScreencopyFrameState::Failed); |
| 365 | frame.failed(); |
| 366 | return; |
| 367 | }; |
| 368 | |
| 369 | let output_transform = output.current_transform(); |
| 370 | let output_physical_size = |
| 371 | output_transform.transform_size(output.current_mode().unwrap().size); |
| 372 | let output_rect = Rectangle::from_size(output_physical_size); |
| 373 | |
| 374 | let rect = Rectangle::new(Point::from((x, y)), Size::from((width, height))); |
| 375 | |
| 376 | let output_scale = output.current_scale().fractional_scale(); |
| 377 | let physical_rect = rect.to_physical_precise_round(output_scale); |
| 378 | |
| 379 | // Clamp captured region to the output. |
| 380 | let Some(clamped_rect) = physical_rect.intersection(output_rect) else { |
| 381 | trace!("screencopy client requested region outside of output"); |
| 382 | let frame = data_init.init(frame, ScreencopyFrameState::Failed); |
| 383 | frame.failed(); |
| 384 | return; |
| 385 | }; |
| 386 | |
| 387 | let untransformed_rect = output_transform |
| 388 | .invert() |
| 389 | .transform_rect_in(clamped_rect, &output_physical_size); |
| 390 | |
| 391 | ( |
| 392 | frame, |
| 393 | overlay_cursor, |
| 394 | untransformed_rect.size, |
| 395 | clamped_rect.loc, |
| 396 | output, |
| 397 | ) |
| 398 | } |
| 399 | zwlr_screencopy_manager_v1::Request::Destroy => return, |
| 400 | _ => unreachable!(), |
| 401 | }; |
| 402 | |
| 403 | // Create the frame. |
| 404 | let overlay_cursor = overlay_cursor != 0; |
| 405 | let info = ScreencopyFrameInfo { |
| 406 | output, |
| 407 | overlay_cursor, |
| 408 | buffer_size, |
| 409 | region_loc, |
| 410 | }; |
| 411 | let frame = data_init.init( |
| 412 | frame, |
| 413 | ScreencopyFrameState::Pending { |
| 414 | manager: manager.clone(), |
| 415 | info, |
| 416 | copied: Arc::new(AtomicBool::new(false)), |
| 417 | }, |
| 418 | ); |
| 419 | |
| 420 | // Send desired SHM buffer parameters. |
| 421 | frame.buffer( |
| 422 | Format::Xrgb8888, |
| 423 | buffer_size.w as u32, |
| 424 | buffer_size.h as u32, |
| 425 | buffer_size.w as u32 * 4, |
| 426 | ); |
| 427 | |
| 428 | if frame.version() >= 3 { |
| 429 | // Send desired DMA buffer parameters. |
| 430 | frame.linux_dmabuf( |
| 431 | Fourcc::Xrgb8888 as u32, |
| 432 | buffer_size.w as u32, |
| 433 | buffer_size.h as u32, |
| 434 | ); |
| 435 | |
| 436 | // Notify client that all supported buffers were enumerated. |
| 437 | frame.buffer_done(); |
| 438 | } |
| 439 | |
| 440 | let state = state.screencopy_state(); |
| 441 | let queue = state.queues.get_mut(manager).unwrap(); |
| 442 | queue.pending_frames.insert(frame); |
| 443 | } |
| 444 | |
| 445 | fn destroyed( |
| 446 | state: &mut D, |
| 447 | _client: wayland_backend::server::ClientId, |
| 448 | manager: &ZwlrScreencopyManagerV1, |
| 449 | _data: &(), |
| 450 | ) { |
| 451 | let state = state.screencopy_state(); |
| 452 | |
| 453 | let Some(queue) = state.queues.get_mut(manager) else { |
| 454 | // This happened once. I'm really not sure how exactly though. |
| 455 | // |
| 456 | // I've dug into wayland-server and wayland-backend, and apparently there are a bunch |
| 457 | // of places where calling destroyed() is delayed (even on a +1 ms timer). Then, it's |
| 458 | // quite possible for some code to run cleanup_queues() *before* this destroyed() |
| 459 | // handler, and delete the queue because the manager is no longer .is_alive() by then. |
| 460 | // Then, queue will be None here. |
| 461 | // |
| 462 | // My attempts to reproduce this in a test have failed though. Perhaps it requires a |
| 463 | // tricky timing condition where the client disconnects at some precise spot inside our |
| 464 | // State::refresh_and_flush_clients() call. |
| 465 | return; |
| 466 | }; |
| 467 | |
| 468 | // Clean up the queue if this was the last object. |
| 469 | if queue.is_empty() { |
| 470 | state.queues.remove(manager); |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | /// Handler trait for wlr-screencopy. |
| 476 | pub trait ScreencopyHandler { |
| 477 | /// Handle new screencopy request. |
| 478 | /// |
| 479 | /// The handler must synchronously either ready/fail the screencopy, or submit it to the |
| 480 | /// manager queue. |
| 481 | fn frame(&mut self, manager: &ZwlrScreencopyManagerV1, screencopy: Screencopy); |
| 482 | |
| 483 | fn screencopy_state(&mut self) -> &mut ScreencopyManagerState; |
| 484 | } |
| 485 | |
| 486 | #[allow(missing_docs)] |
| 487 | #[macro_export] |
| 488 | macro_rules! delegate_screencopy { |
| 489 | ($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => { |
| 490 | smithay::reexports::wayland_server::delegate_global_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [ |
| 491 | smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1: $crate::protocols::screencopy::ScreencopyManagerGlobalData |
| 492 | ] => $crate::protocols::screencopy::ScreencopyManagerState); |
| 493 | |
| 494 | smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [ |
| 495 | smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1: () |
| 496 | ] => $crate::protocols::screencopy::ScreencopyManagerState); |
| 497 | |
| 498 | smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [ |
| 499 | smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_frame_v1::ZwlrScreencopyFrameV1: $crate::protocols::screencopy::ScreencopyFrameState |
| 500 | ] => $crate::protocols::screencopy::ScreencopyManagerState); |
| 501 | }; |
| 502 | } |
| 503 | |
| 504 | #[derive(Clone)] |
| 505 | pub struct ScreencopyFrameInfo { |
| 506 | output: Output, |
| 507 | buffer_size: Size<i32, Physical>, |
| 508 | region_loc: Point<i32, Physical>, |
| 509 | overlay_cursor: bool, |
| 510 | } |
| 511 | |
| 512 | pub enum ScreencopyFrameState { |
| 513 | Failed, |
| 514 | Pending { |
| 515 | manager: ZwlrScreencopyManagerV1, |
| 516 | info: ScreencopyFrameInfo, |
| 517 | copied: Arc<AtomicBool>, |
| 518 | }, |
| 519 | } |
| 520 | |
| 521 | impl<D> Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState, D> for ScreencopyManagerState |
| 522 | where |
| 523 | D: Dispatch<ZwlrScreencopyFrameV1, ScreencopyFrameState>, |
| 524 | D: ScreencopyHandler, |
| 525 | D: 'static, |
| 526 | { |
| 527 | fn request( |
| 528 | state: &mut D, |
| 529 | _client: &Client, |
| 530 | frame: &ZwlrScreencopyFrameV1, |
| 531 | request: zwlr_screencopy_frame_v1::Request, |
| 532 | data: &ScreencopyFrameState, |
| 533 | _display: &DisplayHandle, |
| 534 | _data_init: &mut DataInit<'_, D>, |
| 535 | ) { |
| 536 | if matches!(request, zwlr_screencopy_frame_v1::Request::Destroy) { |
| 537 | return; |
| 538 | } |
| 539 | |
| 540 | let ScreencopyFrameState::Pending { |
| 541 | manager, |
| 542 | info, |
| 543 | copied, |
| 544 | } = data |
| 545 | else { |
| 546 | return; |
| 547 | }; |
| 548 | |
| 549 | if copied.load(Ordering::SeqCst) { |
| 550 | frame.post_error( |
| 551 | zwlr_screencopy_frame_v1::Error::AlreadyUsed, |
| 552 | "copy was already requested", |
| 553 | ); |
| 554 | return; |
| 555 | } |
| 556 | |
| 557 | let (buffer, with_damage) = match request { |
| 558 | zwlr_screencopy_frame_v1::Request::Copy { buffer } => (buffer, false), |
| 559 | zwlr_screencopy_frame_v1::Request::CopyWithDamage { buffer } => (buffer, true), |
| 560 | _ => unreachable!(), |
| 561 | }; |
| 562 | |
| 563 | let size = info.buffer_size; |
| 564 | |
| 565 | let buffer = if let Ok(dmabuf) = dmabuf::get_dmabuf(&buffer) { |
| 566 | if dmabuf.format().code == Fourcc::Xrgb8888 |
| 567 | && dmabuf.width() == size.w as u32 |
| 568 | && dmabuf.height() == size.h as u32 |
| 569 | { |
| 570 | ScreencopyBuffer::Dmabuf(dmabuf.clone()) |
| 571 | } else { |
| 572 | frame.post_error( |
| 573 | zwlr_screencopy_frame_v1::Error::InvalidBuffer, |
| 574 | "invalid dmabuf parameters", |
| 575 | ); |
| 576 | return; |
| 577 | } |
| 578 | } else if shm::with_buffer_contents(&buffer, |_, shm_len, buffer_data| { |
| 579 | buffer_data.format == Format::Xrgb8888 |
| 580 | && buffer_data.width == size.w |
| 581 | && buffer_data.height == size.h |
| 582 | && buffer_data.stride == size.w * 4 |
| 583 | && shm_len == buffer_data.stride as usize * buffer_data.height as usize |
| 584 | }) |
| 585 | .unwrap_or(false) |
| 586 | { |
| 587 | ScreencopyBuffer::Shm(buffer) |
| 588 | } else { |
| 589 | frame.post_error( |
| 590 | zwlr_screencopy_frame_v1::Error::InvalidBuffer, |
| 591 | "invalid buffer", |
| 592 | ); |
| 593 | return; |
| 594 | }; |
| 595 | |
| 596 | copied.store(true, Ordering::SeqCst); |
| 597 | |
| 598 | state.frame( |
| 599 | manager, |
| 600 | Screencopy { |
| 601 | buffer, |
| 602 | frame: frame.clone(), |
| 603 | info: info.clone(), |
| 604 | with_damage, |
| 605 | submitted: false, |
| 606 | }, |
| 607 | ); |
| 608 | |
| 609 | // By this point the frame should've been either copied or failed or pushed to the queue, |
| 610 | // so remove it from pending frames. |
| 611 | let state = state.screencopy_state(); |
| 612 | let queue = state.queues.get_mut(manager).unwrap(); |
| 613 | queue.pending_frames.remove(frame); |
| 614 | if queue.is_empty() && !manager.is_alive() { |
| 615 | state.queues.remove(manager); |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | fn destroyed( |
| 620 | state: &mut D, |
| 621 | _client: wayland_backend::server::ClientId, |
| 622 | frame: &ZwlrScreencopyFrameV1, |
| 623 | data: &ScreencopyFrameState, |
| 624 | ) { |
| 625 | let ScreencopyFrameState::Pending { manager, .. } = data else { |
| 626 | return; |
| 627 | }; |
| 628 | |
| 629 | let state = state.screencopy_state(); |
| 630 | let Some(queue) = state.queues.get_mut(manager) else { |
| 631 | // I think this can happen when we post_error() on a pending frame? Either way better |
| 632 | // safe than sorry. |
| 633 | return; |
| 634 | }; |
| 635 | |
| 636 | queue.remove_frame(frame); |
| 637 | |
| 638 | // Clean up the queue if this was the last object. |
| 639 | if queue.is_empty() && !manager.is_alive() { |
| 640 | state.queues.remove(manager); |
| 641 | } |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | /// Screencopy buffer. |
| 646 | #[derive(Clone)] |
| 647 | pub enum ScreencopyBuffer { |
| 648 | Dmabuf(Dmabuf), |
| 649 | Shm(WlBuffer), |
| 650 | } |
| 651 | |
| 652 | /// Screencopy frame. |
| 653 | pub struct Screencopy { |
| 654 | info: ScreencopyFrameInfo, |
| 655 | frame: ZwlrScreencopyFrameV1, |
| 656 | buffer: ScreencopyBuffer, |
| 657 | with_damage: bool, |
| 658 | submitted: bool, |
| 659 | } |
| 660 | |
| 661 | impl Drop for Screencopy { |
| 662 | fn drop(&mut self) { |
| 663 | if !self.submitted { |
| 664 | self.frame.failed(); |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | impl Screencopy { |
| 670 | /// Get the target buffer to copy to. |
| 671 | pub fn buffer(&self) -> &ScreencopyBuffer { |
| 672 | &self.buffer |
| 673 | } |
| 674 | |
| 675 | pub fn region_loc(&self) -> Point<i32, Physical> { |
| 676 | self.info.region_loc |
| 677 | } |
| 678 | |
| 679 | pub fn buffer_size(&self) -> Size<i32, Physical> { |
| 680 | self.info.buffer_size |
| 681 | } |
| 682 | |
| 683 | pub fn output(&self) -> &Output { |
| 684 | &self.info.output |
| 685 | } |
| 686 | |
| 687 | pub fn overlay_cursor(&self) -> bool { |
| 688 | self.info.overlay_cursor |
| 689 | } |
| 690 | |
| 691 | pub fn with_damage(&self) -> bool { |
| 692 | self.with_damage |
| 693 | } |
| 694 | |
| 695 | pub fn damage(&self, damages: impl Iterator<Item = Rectangle<i32, smithay::utils::Buffer>>) { |
| 696 | for Rectangle { loc, size } in damages { |
| 697 | self.frame |
| 698 | .damage(loc.x as u32, loc.y as u32, size.w as u32, size.h as u32); |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | /// Submit the copied content. |
| 703 | fn submit(mut self, y_invert: bool, timestamp: Duration) { |
| 704 | // Notify client that buffer is ordinary. |
| 705 | self.frame.flags(if y_invert { |
| 706 | Flags::YInvert |
| 707 | } else { |
| 708 | Flags::empty() |
| 709 | }); |
| 710 | |
| 711 | // Notify client about successful copy. |
| 712 | let tv_sec_hi = (timestamp.as_secs() >> 32) as u32; |
| 713 | let tv_sec_lo = (timestamp.as_secs() & 0xFFFFFFFF) as u32; |
| 714 | let tv_nsec = timestamp.subsec_nanos(); |
| 715 | self.frame.ready(tv_sec_hi, tv_sec_lo, tv_nsec); |
| 716 | |
| 717 | // Mark frame as submitted to ensure destructor isn't run. |
| 718 | self.submitted = true; |
| 719 | } |
| 720 | |
| 721 | pub fn submit_after_sync<T>( |
| 722 | self, |
| 723 | y_invert: bool, |
| 724 | sync_point: Option<SyncPoint>, |
| 725 | event_loop: &LoopHandle<'_, T>, |
| 726 | ) { |
| 727 | let timestamp = get_monotonic_time(); |
| 728 | match sync_point.and_then(|s| s.export()) { |
| 729 | None => self.submit(y_invert, timestamp), |
| 730 | Some(sync_fd) => { |
| 731 | let source = Generic::new(sync_fd, Interest::READ, Mode::OneShot); |
| 732 | let mut screencopy = Some(self); |
| 733 | event_loop |
| 734 | .insert_source(source, move |_, _, _| { |
| 735 | screencopy.take().unwrap().submit(y_invert, timestamp); |
| 736 | Ok(PostAction::Remove) |
| 737 | }) |
| 738 | .unwrap(); |
| 739 | } |
| 740 | } |
| 741 | } |
| 742 | } |