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