smithay/wayland/compositor/mod.rs
1//! Utilities for handling surfaces, subsurfaces and regions
2//!
3//! This module provides automatic handling of surfaces, subsurfaces
4//! and region Wayland objects, by registering an implementation for
5//! for the [`wl_compositor`](wayland_server::protocol::wl_compositor)
6//! and [`wl_subcompositor`](wayland_server::protocol::wl_subcompositor) globals.
7//!
8//! ## Why use this implementation
9//!
10//! This implementation does a simple job: it stores in a coherent way the state of
11//! surface trees with subsurfaces, to provide you direct access to the tree
12//! structure and all surface attributes, and handles the application of double-buffered
13//! state.
14//!
15//! As such, you can, given a root surface with a role requiring it to be displayed,
16//! you can iterate over the whole tree of subsurfaces to recover all the metadata you
17//! need to display the subsurface tree.
18//!
19//! This implementation will not do anything more than present you the metadata specified by the
20//! client in a coherent and practical way. All the logic regarding drawing itself, and
21//! the positioning of windows (surface trees) one relative to another is out of its scope.
22//!
23//! ## How to use it
24//!
25//! ### Initialization
26//!
27//! To initialize this implementation create the [`CompositorState`], store it inside your `State` struct
28//! and implement the [`CompositorHandler`], as shown in this example:
29//!
30//! ```
31//! # extern crate wayland_server;
32//! # #[macro_use] extern crate smithay;
33//! use smithay::wayland::compositor::{CompositorState, CompositorClientState, CompositorHandler};
34//!
35//! # struct State { compositor_state: CompositorState }
36//! # struct ClientState { compositor_state: CompositorClientState }
37//! # impl wayland_server::backend::ClientData for ClientState {}
38//! # let mut display = wayland_server::Display::<State>::new().unwrap();
39//! // Create the compositor state
40//! let compositor_state = CompositorState::new::<State>(
41//! &display.handle(),
42//! );
43//!
44//! // insert the CompositorState into your state
45//! // ..
46//!
47//! // implement the necessary traits
48//! impl CompositorHandler for State {
49//! fn compositor_state(&mut self) -> &mut CompositorState {
50//! &mut self.compositor_state
51//! }
52//!
53//! fn client_compositor_state<'a>(&self, client: &'a wayland_server::Client) -> &'a CompositorClientState {
54//! &client.get_data::<ClientState>().unwrap().compositor_state
55//! }
56//!
57//! fn commit(&mut self, surface: &wayland_server::protocol::wl_surface::WlSurface) {
58//! // called on every buffer commit.
59//! // .. your implementation ..
60//! }
61//! }
62//!
63//! smithay::delegate_dispatch2!(State);
64//!
65//! // You're now ready to go!
66//! ```
67//!
68//! ### Use the surface states
69//!
70//! The main access to surface states is done through the [`with_states`] function, which
71//! gives you access to the [`SurfaceData`] instance associated with this surface. It acts
72//! as a general purpose container for associating state to a surface, double-buffered or
73//! not. See its documentation for more details.
74//!
75//! ### State application and hooks
76//!
77//! On commit of a surface several steps are taken to update the state of the surface. Actions
78//! are taken by smithay in the following order:
79//!
80//! 1. Pre Commit hooks registered to this surface are invoked. Such hooks can be registered using
81//! the [`add_pre_commit_hook`] function. They are typically used by protocol extensions that
82//! add state to a surface and need to check on commit that client did not request an
83//! illegal state before it is applied on commit.
84//! 2. The pending state is either applied and made current, or cached for later application
85//! is the surface is a synchronize subsurface. If the current state is applied, state
86//! of the synchronized children subsurface are applied as well at this point.
87//! 3. Post Commit hooks registered to this surface are invoked. Such hooks can be registered using
88//! the [`add_post_commit_hook`] function. They are typically used by abstractions that further process
89//! the state.
90//! 4. Your implementation of [`CompositorHandler::commit`] is invoked, so that you can access
91//! the new current state of the surface. The state of sync children subsurfaces of your
92//! surface may have changed as well, so this is the place to check it, using functions
93//! like [`with_surface_tree_upward`] or [`with_surface_tree_downward`]. On the other hand,
94//! if the surface is a sync subsurface, its current state will note have changed as
95//! the result of that commit. You can check if it is using [`is_sync_subsurface`].
96//! 5. If the surface is destroyed, destruction hooks are invoked. Such hooks can be registered
97//! using the [`add_destruction_hook`] function. They are typically used to cleanup associated
98//! state.
99//!
100//! ### Surface roles
101//!
102//! The wayland protocol specifies that a surface needs to be assigned a role before it can
103//! be displayed. Furthermore, a surface can only have a single role during its whole lifetime.
104//! Smithay represents this role as a `&'static str` identifier, that can only be set once
105//! on a surface. See [`give_role`] and [`get_role`] for details. This module manages the
106//! subsurface role, which is identified by the string `"subsurface"`.
107
108mod cache;
109mod handlers;
110mod transaction;
111mod tree;
112
113use std::cell::RefCell;
114use std::sync::Arc;
115use std::sync::atomic::Ordering;
116use std::{any::Any, sync::Mutex};
117
118pub use self::cache::{Cacheable, CachedState, MultiCache};
119pub use self::handlers::{RegionUserData, SubsurfaceCachedState, SubsurfaceUserData, SurfaceUserData};
120use self::transaction::TransactionQueue;
121pub use self::transaction::{Barrier, Blocker, BlockerState};
122pub use self::tree::{AlreadyHasRole, TraversalAction};
123use self::tree::{PrivateSurfaceData, SuggestedSurfaceState};
124use crate::utils::Transform;
125pub use crate::utils::hook::HookId;
126use crate::utils::{Buffer, Logical, Point, Rectangle, user_data::UserDataMap};
127use crate::wayland::GlobalData;
128use atomic_float::AtomicF64;
129use wayland_server::backend::GlobalId;
130use wayland_server::protocol::wl_compositor::WlCompositor;
131use wayland_server::protocol::wl_subcompositor::WlSubcompositor;
132use wayland_server::protocol::{wl_buffer, wl_callback, wl_output, wl_region, wl_surface::WlSurface};
133use wayland_server::{Client, DisplayHandle, GlobalDispatch, Resource};
134
135/// The role of a subsurface surface.
136pub const SUBSURFACE_ROLE: &str = "subsurface";
137
138/// Description of a part of a surface that
139/// should be considered damaged and needs to be redrawn
140#[derive(Debug, PartialEq, Eq)]
141pub enum Damage {
142 /// A rectangle containing the damaged zone, in surface coordinates
143 Surface(Rectangle<i32, Logical>),
144 /// A rectangle containing the damaged zone, in buffer coordinates
145 ///
146 /// Note: Buffer scaling must be taken into consideration
147 Buffer(Rectangle<i32, Buffer>),
148}
149
150/// The state container associated with a surface
151///
152/// This general-purpose container provides 2 main storages:
153///
154/// - the `data_map` storage has typemap semantics and allows you
155/// to associate and access non-buffered data to the surface
156/// - the `cached_state` storages allows you to associate state to
157/// the surface that follows the double-buffering semantics associated
158/// with the `commit` procedure of surfaces, also with typemap-like
159/// semantics
160///
161/// See the respective documentation of each container for its usage.
162///
163/// By default, all surfaces have a [`SurfaceAttributes`] cached state,
164/// and subsurface also have a [`SubsurfaceCachedState`] state as well.
165#[derive(Debug)]
166pub struct SurfaceData {
167 /// The current role of the surface.
168 ///
169 /// If `None` if the surface has not yet been assigned a role
170 pub role: Option<&'static str>,
171 /// The non-buffered typemap storage of this surface
172 pub data_map: UserDataMap,
173 /// The double-buffered typemap storage of this surface
174 pub cached_state: MultiCache,
175}
176
177/// New buffer assignation for a surface
178#[derive(Debug)]
179pub enum BufferAssignment {
180 /// The surface no longer has a buffer attached to it
181 Removed,
182 /// A new buffer has been attached
183 NewBuffer(wl_buffer::WlBuffer),
184}
185
186/// General state associated with a surface
187///
188/// The fields `buffer`, `damage` and `frame_callbacks` should be
189/// reset (by clearing their contents) once you have adequately
190/// processed them, as their contents are aggregated from commit to commit.
191#[derive(Debug)]
192pub struct SurfaceAttributes {
193 /// Buffer defining the contents of the surface
194 ///
195 /// You are free to set this field to `None` to avoid processing it several
196 /// times. It'll be set to `Some(...)` if the user attaches a buffer (or `NULL`) to
197 /// the surface, and be left to `None` if the user does not attach anything.
198 pub buffer: Option<BufferAssignment>,
199
200 /// Location of the new buffer relative to the previous one
201 ///
202 /// The x and y arguments specify the location of the new pending buffer's upper left corner,
203 /// relative to the current buffer's upper left corner, in surface-local coordinates.
204 ///
205 /// In other words, the x and y, combined with the new surface size define in which directions
206 /// the surface's size changes.
207 ///
208 /// You are free to set this field to `None` to avoid processing it several times.
209 pub buffer_delta: Option<Point<i32, Logical>>,
210
211 /// Scale of the contents of the buffer, for higher-resolution contents.
212 ///
213 /// If it matches the one of the output displaying this surface, no change
214 /// is necessary.
215 pub buffer_scale: i32,
216 /// Transform under which interpret the contents of the buffer
217 ///
218 /// If it matches the one of the output displaying this surface, no change
219 /// is necessary.
220 pub buffer_transform: wl_output::Transform,
221 /// Region of the surface that is guaranteed to be opaque
222 ///
223 /// By default the whole surface is potentially transparent
224 pub opaque_region: Option<RegionAttributes>,
225 /// Region of the surface that is sensitive to user input
226 ///
227 /// By default the whole surface should be sensitive
228 pub input_region: Option<RegionAttributes>,
229 /// Damage rectangle
230 ///
231 /// Hint provided by the client to suggest that only this part
232 /// of the surface was changed and needs to be redrawn
233 pub damage: Vec<Damage>,
234 /// The frame callbacks associated with this surface for the commit
235 ///
236 /// The server must send the notifications so that a client
237 /// will not send excessive updates, while still allowing
238 /// the highest possible update rate for clients that wait for the reply
239 /// before drawing again. The server should give some time for the client
240 /// to draw and commit after sending the frame callback events to let it
241 /// hit the next output refresh.
242 ///
243 /// A server should avoid signaling the frame callbacks if the
244 /// surface is not visible in any way, e.g. the surface is off-screen,
245 /// or completely obscured by other opaque surfaces.
246 ///
247 /// An example possibility would be to trigger it once the frame
248 /// associated with this commit has been displayed on the screen.
249 pub frame_callbacks: Vec<wl_callback::WlCallback>,
250
251 pub(crate) client_scale: f64,
252}
253
254impl Default for SurfaceAttributes {
255 fn default() -> SurfaceAttributes {
256 SurfaceAttributes {
257 buffer: None,
258 buffer_delta: None,
259 buffer_scale: 1,
260 buffer_transform: wl_output::Transform::Normal,
261 opaque_region: None,
262 input_region: None,
263 damage: Vec::new(),
264 frame_callbacks: Vec::new(),
265 client_scale: 1.,
266 }
267 }
268}
269
270/// Kind of a rectangle part of a region
271#[derive(Copy, Clone, Debug)]
272pub enum RectangleKind {
273 /// This rectangle should be added to the region
274 Add,
275 /// The intersection of this rectangle with the region should
276 /// be removed from the region
277 Subtract,
278}
279
280/// Description of the contents of a region
281///
282/// A region is defined as an union and difference of rectangle.
283///
284/// This struct contains an ordered `Vec` containing the rectangles defining
285/// a region. They should be added or subtracted in this order to compute the
286/// actual contents of the region.
287#[derive(Clone, Debug, Default)]
288pub struct RegionAttributes {
289 /// List of rectangle part of this region
290 pub rects: Vec<(RectangleKind, Rectangle<i32, Logical>)>,
291}
292
293impl RegionAttributes {
294 /// Checks whether given point is inside the region.
295 pub fn contains<P: Into<Point<i32, Logical>>>(&self, point: P) -> bool {
296 let point: Point<i32, Logical> = point.into();
297 let mut contains = false;
298 for (kind, rect) in &self.rects {
299 if rect.contains(point) {
300 match kind {
301 RectangleKind::Add => contains = true,
302 RectangleKind::Subtract => contains = false,
303 }
304 }
305 }
306 contains
307 }
308}
309
310/// Access the data of a surface tree from bottom to top
311///
312/// You provide three closures, a "filter", a "processor" and a "post filter".
313///
314/// The first closure is initially called on a surface to determine if its children
315/// should be processed as well. It returns a `TraversalAction<T>` reflecting that.
316///
317/// The second closure is supposed to do the actual processing. The processing closure for
318/// a surface may be called after the processing closure of some of its children, depending
319/// on the stack ordering the client requested. Here the surfaces are processed in the same
320/// order as they are supposed to be drawn: from the farthest of the screen to the nearest.
321///
322/// The third closure is called once all the subtree of a node has been processed, and gives
323/// an opportunity for early-stopping. If it returns `true` the processing will continue,
324/// while if it returns `false` it'll stop.
325///
326/// The arguments provided to the closures are, in this order:
327///
328/// - The surface object itself
329/// - a mutable reference to its surface attribute data
330/// - a mutable reference to its role data,
331/// - a custom value that is passed in a fold-like manner, but only from the output of a parent
332/// to its children. See [`TraversalAction`] for details.
333///
334/// If the surface not managed by the `CompositorGlobal` that provided this token, this
335/// will panic (having more than one compositor is not supported).
336pub fn with_surface_tree_upward<F1, F2, F3, T>(
337 surface: &WlSurface,
338 initial: T,
339 filter: F1,
340 processor: F2,
341 post_filter: F3,
342) where
343 F1: FnMut(&WlSurface, &SurfaceData, &T) -> TraversalAction<T>,
344 F2: FnMut(&WlSurface, &SurfaceData, &T),
345 F3: FnMut(&WlSurface, &SurfaceData, &T) -> bool,
346{
347 PrivateSurfaceData::map_tree(surface, &initial, filter, processor, post_filter, false);
348}
349
350/// Access the data of a surface tree from top to bottom
351///
352/// Behavior is the same as [`with_surface_tree_upward`], but the processing is done in the reverse order,
353/// from the nearest of the screen to the deepest.
354///
355/// This would typically be used to find out which surface of a subsurface tree has been clicked for example.
356pub fn with_surface_tree_downward<F1, F2, F3, T>(
357 surface: &WlSurface,
358 initial: T,
359 filter: F1,
360 processor: F2,
361 post_filter: F3,
362) where
363 F1: FnMut(&WlSurface, &SurfaceData, &T) -> TraversalAction<T>,
364 F2: FnMut(&WlSurface, &SurfaceData, &T),
365 F3: FnMut(&WlSurface, &SurfaceData, &T) -> bool,
366{
367 PrivateSurfaceData::map_tree(surface, &initial, filter, processor, post_filter, true);
368}
369
370/// Retrieve the parent of this surface
371///
372/// Returns `None` is this surface is a root surface
373pub fn get_parent(surface: &WlSurface) -> Option<WlSurface> {
374 PrivateSurfaceData::get_parent(surface)
375}
376
377/// Retrieve the children of this surface
378pub fn get_children(surface: &WlSurface) -> Vec<WlSurface> {
379 PrivateSurfaceData::get_children(surface)
380}
381
382/// Check if this subsurface is a synchronized subsurface
383pub fn is_sync_subsurface(surface: &WlSurface) -> bool {
384 self::handlers::is_effectively_sync(surface)
385}
386
387/// Get the current role of this surface
388pub fn get_role(surface: &WlSurface) -> Option<&'static str> {
389 PrivateSurfaceData::get_role(surface)
390}
391
392/// Register that this surface has given role
393///
394/// Fails if the surface already has a role.
395pub fn give_role(surface: &WlSurface, role: &'static str) -> Result<(), AlreadyHasRole> {
396 PrivateSurfaceData::set_role(surface, role)
397}
398
399/// Access the states associated to this surface
400pub fn with_states<F, T>(surface: &WlSurface, f: F) -> T
401where
402 F: FnOnce(&SurfaceData) -> T,
403{
404 PrivateSurfaceData::with_states(surface, f)
405}
406
407/// Send the `scale` and `transform` preferences for the given surface when it supports them.
408///
409/// The new state is only send when it differs from the already cached one on the calling thread.
410pub fn send_surface_state(surface: &WlSurface, data: &SurfaceData, scale: i32, transform: Transform) {
411 if surface.version() < 6 {
412 return;
413 }
414
415 // NOTE we insert default for checks below to work properly.
416 let mut storage = data
417 .data_map
418 .get_or_insert(|| RefCell::new(SuggestedSurfaceState::default()))
419 .borrow_mut();
420
421 if storage.scale != scale {
422 surface.preferred_buffer_scale(scale);
423 storage.scale = scale;
424 }
425
426 let transform = transform.into();
427 if storage.transform != transform {
428 surface.preferred_buffer_transform(transform);
429 storage.transform = transform;
430 }
431}
432
433/// Retrieve the metadata associated with a `wl_region`
434///
435/// If the region is not managed by the `CompositorGlobal` that provided this token, this
436/// will panic (having more than one compositor is not supported).
437pub fn get_region_attributes(region: &wl_region::WlRegion) -> RegionAttributes {
438 match region.data::<RegionUserData>() {
439 Some(data) => data.inner.lock().unwrap().clone(),
440 None => panic!("Accessing the data of foreign regions is not supported."),
441 }
442}
443
444/// Register a pre-commit hook to be invoked on surface commit
445///
446/// It'll be invoked on surface commit, *before* the new state is merged into the current state.
447///
448/// Protocol implementations should use this for error checking, but they should **not** apply
449/// state changes here, since the commit may be further arbitrarily delayed by blockers. Use a
450/// post-commit hook to apply state changes (i.e. copy last acked state to current).
451///
452/// Compositors should use this for adding blockers if needed, e.g. the DMA-BUF readiness blocker.
453pub fn add_pre_commit_hook<D, F>(surface: &WlSurface, hook: F) -> HookId
454where
455 F: Fn(&mut D, &DisplayHandle, &WlSurface) + Send + Sync + 'static,
456 D: 'static,
457{
458 let (user_state_type_id, user_state_type) = surface.data::<SurfaceUserData>().unwrap().user_state_type;
459 assert_eq!(
460 std::any::TypeId::of::<D>(),
461 user_state_type_id,
462 "D has to equal D used in CompositorState::new<D>(), {} != {}",
463 std::any::type_name::<D>(),
464 user_state_type,
465 );
466
467 let hook = move |state: &mut dyn Any, dh: &DisplayHandle, surface: &WlSurface| {
468 let state = state.downcast_mut::<D>().unwrap();
469 hook(state, dh, surface);
470 };
471 PrivateSurfaceData::add_pre_commit_hook(surface, hook)
472}
473
474/// Register a post-commit hook to be invoked on surface commit
475///
476/// It'll be invoked on surface commit, *after* the new state is merged into the current state,
477/// after all commit blockers complete.
478///
479/// Protocol implementations should apply state changes here, i.e. copy last acked state into
480/// current.
481pub fn add_post_commit_hook<D, F>(surface: &WlSurface, hook: F) -> HookId
482where
483 F: Fn(&mut D, &DisplayHandle, &WlSurface) + Send + Sync + 'static,
484 D: 'static,
485{
486 let (user_state_type_id, user_state_type) = surface.data::<SurfaceUserData>().unwrap().user_state_type;
487 assert_eq!(
488 std::any::TypeId::of::<D>(),
489 user_state_type_id,
490 "D has to equal D used in CompositorState::new<D>(), {} != {}",
491 std::any::type_name::<D>(),
492 user_state_type,
493 );
494
495 let hook = move |state: &mut dyn Any, dh: &DisplayHandle, surface: &WlSurface| {
496 let state = state.downcast_mut::<D>().unwrap();
497 hook(state, dh, surface);
498 };
499 PrivateSurfaceData::add_post_commit_hook(surface, hook)
500}
501
502/// Register a destruction hook to be invoked on surface destruction
503///
504/// It'll be invoked when the surface is destroyed (either explicitly by the client or on
505/// client disconnect).
506///
507/// D generic is the compositor state, same as used in `CompositorState::new<D>()`
508pub fn add_destruction_hook<D, F>(surface: &WlSurface, hook: F) -> HookId
509where
510 F: Fn(&mut D, &WlSurface) + Send + Sync + 'static,
511 D: 'static,
512{
513 let (user_state_type_id, user_state_type) = surface.data::<SurfaceUserData>().unwrap().user_state_type;
514 assert_eq!(
515 std::any::TypeId::of::<D>(),
516 user_state_type_id,
517 "D has to equal D used in CompositorState::new<D>(), {} != {}",
518 std::any::type_name::<D>(),
519 user_state_type,
520 );
521
522 let hook = move |state: &mut dyn Any, surface: &WlSurface| {
523 let state = state.downcast_mut::<D>().unwrap();
524 hook(state, surface);
525 };
526 PrivateSurfaceData::add_destruction_hook(surface, hook)
527}
528
529/// Unregister a pre-commit hook
530pub fn remove_pre_commit_hook(surface: &WlSurface, hook_id: &HookId) {
531 PrivateSurfaceData::remove_pre_commit_hook(surface, hook_id)
532}
533
534/// Unregister a post-commit hook
535pub fn remove_post_commit_hook(surface: &WlSurface, hook_id: &HookId) {
536 PrivateSurfaceData::remove_post_commit_hook(surface, hook_id)
537}
538
539/// Unregister a destruction hook
540pub fn remove_destruction_hook(surface: &WlSurface, hook_id: &HookId) {
541 PrivateSurfaceData::remove_destruction_hook(surface, hook_id)
542}
543
544/// Adds a blocker for the currently queued up state changes of the given surface.
545///
546/// Blockers will delay the pending state to be applied on the next commit until
547/// all of them return the state `Released`. Any blocker returning `Cancelled` will
548/// discard all changes.
549///
550/// The module will only evaluate blocker states on commit. If a blocker
551/// becomes ready later, a call to [`CompositorClientState::blocker_cleared`] is necessary
552/// to trigger a re-evaluation.
553pub fn add_blocker(surface: &WlSurface, blocker: impl Blocker + Send + 'static) {
554 PrivateSurfaceData::add_blocker(surface, blocker)
555}
556
557/// Handler trait for compositor
558pub trait CompositorHandler {
559 /// [CompositorState] getter
560 fn compositor_state(&mut self) -> &mut CompositorState;
561 /// [CompositorClientState] getter
562 ///
563 /// The compositor implementation needs some state to be client specific.
564 /// Downstream is expected to store this inside its `ClientData` implementation(s)
565 /// to ensure automatic cleanup of the state, when the client disconnects.
566 fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState;
567
568 /// New surface handler.
569 ///
570 /// This handler can be used to setup hooks (see [`add_pre_commit_hook`]/[`add_post_commit_hook`]/[`add_destruction_hook`]),
571 /// but not much else. The surface has no role or attached data at this point and cannot be rendered.
572 fn new_surface(&mut self, surface: &WlSurface) {
573 let _ = surface;
574 }
575
576 /// New subsurface handler.
577 ///
578 /// This handler can be used to run extra logic when subsurface is getting created. This
579 /// is an addition to [`new_surface`], which will be run for the subsurface surface anyway.
580 ///
581 /// When your compositor knows beforehand where it'll position subsurfaces it can send
582 /// [`send_surface_state`] to them.
583 ///
584 /// [`new_surface`]: Self::new_surface
585 fn new_subsurface(&mut self, surface: &WlSurface, parent: &WlSurface) {
586 let _ = surface;
587 let _ = parent;
588 }
589
590 /// Surface commit handler
591 ///
592 /// This is called when any changed state from a commit actually becomes visible.
593 /// That might be some time after the actual commit has taken place, if the
594 /// state changes are delayed by an added blocker (see [`add_blocker`]).
595 ///
596 /// If you need to handle a commit as soon as it occurs, you might want to consider
597 /// using a pre-commit hook (see [`add_pre_commit_hook`]).
598 fn commit(&mut self, surface: &WlSurface);
599
600 /// The surface was destroyed.
601 ///
602 /// This allows the compositor to clean up any uses of the surface.
603 ///
604 /// Note: Destruction might happen explicitly by the client, or implicitly
605 /// when the client quits. In case of implicit destruction the order the
606 /// callbacks are called in is undefined.
607 fn destroyed(&mut self, _surface: &WlSurface) {}
608}
609
610/// State of a compositor
611#[derive(Debug)]
612pub struct CompositorState {
613 compositor: GlobalId,
614 subcompositor: GlobalId,
615 surfaces: Vec<WlSurface>,
616}
617
618/// Per-client state of a compositor
619#[derive(Debug)]
620pub struct CompositorClientState {
621 queue: Mutex<Option<TransactionQueue>>,
622 scale_override: Arc<AtomicF64>,
623}
624
625impl Default for CompositorClientState {
626 fn default() -> Self {
627 CompositorClientState {
628 queue: Mutex::new(None),
629 scale_override: Arc::new(AtomicF64::new(1.)),
630 }
631 }
632}
633
634impl CompositorClientState {
635 /// To be called, when a previously added blocker (via [`add_blocker`])
636 /// got `Released` or `Cancelled` from being `Pending` previously for any
637 /// surface belonging to this client.
638 pub fn blocker_cleared<D: CompositorHandler + 'static>(&self, state: &mut D, dh: &DisplayHandle) {
639 let transactions = if let Some(queue) = self.queue.lock().unwrap().as_mut() {
640 queue.take_ready()
641 } else {
642 Vec::new()
643 };
644
645 for transaction in transactions {
646 transaction.apply(dh, state)
647 }
648 }
649
650 /// Set an additionally mapping between smithay's `Logical` coordinate space
651 /// and this clients logical coordinate space.
652 ///
653 /// This is used in the same way as if the client was setting the
654 /// surface.buffer_scale on every surface i.e a value of 2.0 will make
655 /// the windows appear smaller on a regular DPI monitor.
656 ///
657 /// Only the minimal set of protocols used by xwayland are guaranteed to be supported.
658 ///
659 /// Buffer sizes are unaffected.
660 pub fn set_client_scale(&self, new_scale: f64) {
661 self.scale_override.store(new_scale, Ordering::Release);
662 }
663
664 /// Get the scale factor of the additional mapping between smithay's `Logical`
665 /// coordinate space and this clients logical coordinate space.
666 ///
667 /// This is mainly intended to support out-of-tree protocol implementations.
668 pub fn client_scale(&self) -> f64 {
669 self.scale_override.load(Ordering::Acquire)
670 }
671
672 pub(crate) fn clone_client_scale(&self) -> Arc<AtomicF64> {
673 self.scale_override.clone()
674 }
675}
676
677impl CompositorState {
678 /// Create new [`wl_compositor`] version 5 and [`wl_subcompositor`] globals.
679 ///
680 /// It returns the two global handles, in case you wish to remove these globals from
681 /// the event loop in the future.
682 ///
683 /// [`wl_compositor`]: wayland_server::protocol::wl_compositor
684 /// [`wl_subcompositor`]: wayland_server::protocol::wl_subcompositor
685 pub fn new<D>(display: &DisplayHandle) -> Self
686 where
687 D: GlobalDispatch<WlCompositor, GlobalData> + GlobalDispatch<WlSubcompositor, GlobalData> + 'static,
688 {
689 Self::new_with_version::<D>(display, 5)
690 }
691
692 /// The same as [`new`], but binds at least version 6 of [`wl_compositor`].
693 ///
694 /// This means that for clients to scale and apply transformation with
695 /// non-default values [`send_surface_state`] must be used.
696 ///
697 /// [`new`]: Self::new
698 /// [`wl_compositor`]: wayland_server::protocol::wl_compositor
699 pub fn new_v6<D>(display: &DisplayHandle) -> Self
700 where
701 D: GlobalDispatch<WlCompositor, GlobalData> + GlobalDispatch<WlSubcompositor, GlobalData> + 'static,
702 {
703 Self::new_with_version::<D>(display, 6)
704 }
705
706 fn new_with_version<D>(display: &DisplayHandle, version: u32) -> Self
707 where
708 D: GlobalDispatch<WlCompositor, GlobalData> + GlobalDispatch<WlSubcompositor, GlobalData> + 'static,
709 {
710 let compositor = display.create_global::<D, WlCompositor, _>(version, GlobalData);
711 let subcompositor = display.create_global::<D, WlSubcompositor, _>(1, GlobalData);
712
713 CompositorState {
714 compositor,
715 subcompositor,
716 surfaces: Vec::new(),
717 }
718 }
719
720 /// Get id of compositor global
721 pub fn compositor_global(&self) -> GlobalId {
722 self.compositor.clone()
723 }
724
725 /// Get id of subcompositor global
726 pub fn subcompositor_global(&self) -> GlobalId {
727 self.subcompositor.clone()
728 }
729}
730
731#[cfg(test)]
732mod tests {
733 use super::*;
734
735 #[test]
736 fn region_attributes_empty() {
737 let region = RegionAttributes { rects: vec![] };
738 assert!(!region.contains((0, 0)));
739 }
740
741 #[test]
742 fn region_attributes_add() {
743 let region = RegionAttributes {
744 rects: vec![(RectangleKind::Add, Rectangle::from_size((10, 10).into()))],
745 };
746
747 assert!(region.contains((0, 0)));
748 }
749
750 #[test]
751 fn region_attributes_add_subtract() {
752 let region = RegionAttributes {
753 rects: vec![
754 (RectangleKind::Add, Rectangle::from_size((10, 10).into())),
755 (RectangleKind::Subtract, Rectangle::from_size((5, 5).into())),
756 ],
757 };
758
759 assert!(!region.contains((0, 0)));
760 assert!(region.contains((5, 5)));
761 }
762
763 #[test]
764 fn region_attributes_add_subtract_add() {
765 let region = RegionAttributes {
766 rects: vec![
767 (RectangleKind::Add, Rectangle::from_size((10, 10).into())),
768 (RectangleKind::Subtract, Rectangle::from_size((5, 5).into())),
769 (RectangleKind::Add, Rectangle::new((2, 2).into(), (2, 2).into())),
770 ],
771 };
772
773 assert!(!region.contains((0, 0)));
774 assert!(region.contains((5, 5)));
775 assert!(region.contains((2, 2)));
776 }
777}