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