1use std::{
2 cell::{Ref, RefCell, RefMut},
3 ffi::c_void,
4 ptr::NonNull,
5 rc::Rc,
6 sync::Arc,
7};
8
9use collections::{FxHashSet, HashMap};
10use futures::channel::oneshot::Receiver;
11
12use raw_window_handle as rwh;
13use wayland_backend::client::ObjectId;
14use wayland_client::WEnum;
15use wayland_client::{
16 Proxy,
17 protocol::{wl_output, wl_surface},
18};
19use wayland_protocols::wp::viewporter::client::wp_viewport;
20use wayland_protocols::xdg::decoration::zv1::client::zxdg_toplevel_decoration_v1;
21use wayland_protocols::xdg::shell::client::xdg_surface;
22use wayland_protocols::xdg::shell::client::xdg_toplevel::{self};
23use wayland_protocols::{
24 wp::fractional_scale::v1::client::wp_fractional_scale_v1,
25 xdg::dialog::v1::client::xdg_dialog_v1::XdgDialogV1,
26};
27use wayland_protocols_plasma::blur::client::org_kde_kwin_blur;
28use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_surface_v1;
29
30use crate::linux::wayland::{display::WaylandDisplay, serial::SerialKind};
31use crate::linux::{Globals, Output, WaylandClientStatePtr, get_window};
32use gpui::{
33 AnyWindowHandle, Bounds, Capslock, Decorations, DevicePixels, GpuSpecs, Modifiers, Pixels,
34 PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
35 PromptButton, PromptLevel, RequestFrameOptions, ResizeEdge, Scene, Size, Tiling,
36 WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowControls,
37 WindowDecorations, WindowKind, WindowParams, layer_shell::LayerShellNotSupportedError, px,
38 size,
39};
40use gpui_wgpu::{CompositorGpuHint, WgpuRenderer, WgpuSurfaceConfig};
41
42#[derive(Default)]
43pub(crate) struct Callbacks {
44 request_frame: Option<Box<dyn FnMut(RequestFrameOptions)>>,
45 input: Option<Box<dyn FnMut(gpui::PlatformInput) -> gpui::DispatchEventResult>>,
46 active_status_change: Option<Box<dyn FnMut(bool)>>,
47 hover_status_change: Option<Box<dyn FnMut(bool)>>,
48 resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
49 moved: Option<Box<dyn FnMut()>>,
50 should_close: Option<Box<dyn FnMut() -> bool>>,
51 close: Option<Box<dyn FnOnce()>>,
52 appearance_changed: Option<Box<dyn FnMut()>>,
53}
54
55#[derive(Debug, Clone, Copy)]
56struct RawWindow {
57 window: *mut c_void,
58 display: *mut c_void,
59}
60
61// Safety: The raw pointers in RawWindow point to Wayland surface/display
62// which are valid for the window's lifetime. These are used only for
63// passing to wgpu which needs Send+Sync for surface creation.
64unsafe impl Send for RawWindow {}
65unsafe impl Sync for RawWindow {}
66
67impl rwh::HasWindowHandle for RawWindow {
68 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
69 let window = NonNull::new(self.window).unwrap();
70 let handle = rwh::WaylandWindowHandle::new(window);
71 Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
72 }
73}
74impl rwh::HasDisplayHandle for RawWindow {
75 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
76 let display = NonNull::new(self.display).unwrap();
77 let handle = rwh::WaylandDisplayHandle::new(display);
78 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
79 }
80}
81
82#[derive(Debug)]
83struct InProgressConfigure {
84 size: Option<Size<Pixels>>,
85 fullscreen: bool,
86 maximized: bool,
87 resizing: bool,
88 tiling: Tiling,
89}
90
91pub struct WaylandWindowState {
92 surface_state: WaylandSurfaceState,
93 acknowledged_first_configure: bool,
94 parent: Option<WaylandWindowStatePtr>,
95 children: FxHashSet<ObjectId>,
96 pub surface: wl_surface::WlSurface,
97 app_id: Option<String>,
98 appearance: WindowAppearance,
99 blur: Option<org_kde_kwin_blur::OrgKdeKwinBlur>,
100 viewport: Option<wp_viewport::WpViewport>,
101 outputs: HashMap<ObjectId, Output>,
102 display: Option<(ObjectId, Output)>,
103 globals: Globals,
104 renderer: WgpuRenderer,
105 bounds: Bounds<Pixels>,
106 scale: f32,
107 input_handler: Option<PlatformInputHandler>,
108 decorations: WindowDecorations,
109 background_appearance: WindowBackgroundAppearance,
110 fullscreen: bool,
111 maximized: bool,
112 tiling: Tiling,
113 window_bounds: Bounds<Pixels>,
114 client: WaylandClientStatePtr,
115 handle: AnyWindowHandle,
116 active: bool,
117 hovered: bool,
118 in_progress_configure: Option<InProgressConfigure>,
119 resize_throttle: bool,
120 in_progress_window_controls: Option<WindowControls>,
121 window_controls: WindowControls,
122 client_inset: Option<Pixels>,
123}
124
125pub enum WaylandSurfaceState {
126 Xdg(WaylandXdgSurfaceState),
127 LayerShell(WaylandLayerSurfaceState),
128}
129
130impl WaylandSurfaceState {
131 fn new(
132 surface: &wl_surface::WlSurface,
133 globals: &Globals,
134 params: &WindowParams,
135 parent: Option<WaylandWindowStatePtr>,
136 target_output: Option<wl_output::WlOutput>,
137 ) -> anyhow::Result<Self> {
138 // For layer_shell windows, create a layer surface instead of an xdg surface
139 if let WindowKind::LayerShell(options) = ¶ms.kind {
140 let Some(layer_shell) = globals.layer_shell.as_ref() else {
141 return Err(LayerShellNotSupportedError.into());
142 };
143
144 let layer_surface = layer_shell.get_layer_surface(
145 &surface,
146 target_output.as_ref(),
147 super::layer_shell::wayland_layer(options.layer),
148 options.namespace.clone(),
149 &globals.qh,
150 surface.id(),
151 );
152
153 let width = f32::from(params.bounds.size.width);
154 let height = f32::from(params.bounds.size.height);
155 layer_surface.set_size(width as u32, height as u32);
156
157 layer_surface.set_anchor(super::layer_shell::wayland_anchor(options.anchor));
158 layer_surface.set_keyboard_interactivity(
159 super::layer_shell::wayland_keyboard_interactivity(options.keyboard_interactivity),
160 );
161
162 if let Some(margin) = options.margin {
163 layer_surface.set_margin(
164 f32::from(margin.0) as i32,
165 f32::from(margin.1) as i32,
166 f32::from(margin.2) as i32,
167 f32::from(margin.3) as i32,
168 )
169 }
170
171 if let Some(exclusive_zone) = options.exclusive_zone {
172 layer_surface.set_exclusive_zone(f32::from(exclusive_zone) as i32);
173 }
174
175 if let Some(exclusive_edge) = options.exclusive_edge {
176 layer_surface
177 .set_exclusive_edge(super::layer_shell::wayland_anchor(exclusive_edge));
178 }
179
180 return Ok(WaylandSurfaceState::LayerShell(WaylandLayerSurfaceState {
181 layer_surface,
182 }));
183 }
184
185 // All other WindowKinds result in a regular xdg surface
186 let xdg_surface = globals
187 .wm_base
188 .get_xdg_surface(&surface, &globals.qh, surface.id());
189
190 let toplevel = xdg_surface.get_toplevel(&globals.qh, surface.id());
191 let xdg_parent = parent.as_ref().and_then(|w| w.toplevel());
192
193 if params.kind == WindowKind::Floating || params.kind == WindowKind::Dialog {
194 toplevel.set_parent(xdg_parent.as_ref());
195 }
196
197 let dialog = if params.kind == WindowKind::Dialog {
198 let dialog = globals.dialog.as_ref().map(|dialog| {
199 let xdg_dialog = dialog.get_xdg_dialog(&toplevel, &globals.qh, ());
200 xdg_dialog.set_modal();
201 xdg_dialog
202 });
203
204 if let Some(parent) = parent.as_ref() {
205 parent.add_child(surface.id());
206 }
207
208 dialog
209 } else {
210 None
211 };
212
213 if let Some(size) = params.window_min_size {
214 toplevel.set_min_size(f32::from(size.width) as i32, f32::from(size.height) as i32);
215 }
216
217 // Attempt to set up window decorations based on the requested configuration
218 let decoration = globals
219 .decoration_manager
220 .as_ref()
221 .map(|decoration_manager| {
222 decoration_manager.get_toplevel_decoration(&toplevel, &globals.qh, surface.id())
223 });
224
225 Ok(WaylandSurfaceState::Xdg(WaylandXdgSurfaceState {
226 xdg_surface,
227 toplevel,
228 decoration,
229 dialog,
230 }))
231 }
232}
233
234pub struct WaylandXdgSurfaceState {
235 xdg_surface: xdg_surface::XdgSurface,
236 toplevel: xdg_toplevel::XdgToplevel,
237 decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
238 dialog: Option<XdgDialogV1>,
239}
240
241pub struct WaylandLayerSurfaceState {
242 layer_surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1,
243}
244
245impl WaylandSurfaceState {
246 fn ack_configure(&self, serial: u32) {
247 match self {
248 WaylandSurfaceState::Xdg(WaylandXdgSurfaceState { xdg_surface, .. }) => {
249 xdg_surface.ack_configure(serial);
250 }
251 WaylandSurfaceState::LayerShell(WaylandLayerSurfaceState { layer_surface, .. }) => {
252 layer_surface.ack_configure(serial);
253 }
254 }
255 }
256
257 fn decoration(&self) -> Option<&zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1> {
258 if let WaylandSurfaceState::Xdg(WaylandXdgSurfaceState { decoration, .. }) = self {
259 decoration.as_ref()
260 } else {
261 None
262 }
263 }
264
265 fn toplevel(&self) -> Option<&xdg_toplevel::XdgToplevel> {
266 if let WaylandSurfaceState::Xdg(WaylandXdgSurfaceState { toplevel, .. }) = self {
267 Some(toplevel)
268 } else {
269 None
270 }
271 }
272
273 fn set_geometry(&self, x: i32, y: i32, width: i32, height: i32) {
274 match self {
275 WaylandSurfaceState::Xdg(WaylandXdgSurfaceState { xdg_surface, .. }) => {
276 xdg_surface.set_window_geometry(x, y, width, height);
277 }
278 WaylandSurfaceState::LayerShell(WaylandLayerSurfaceState { layer_surface, .. }) => {
279 // cannot set window position of a layer surface
280 layer_surface.set_size(width as u32, height as u32);
281 }
282 }
283 }
284
285 fn destroy(&mut self) {
286 match self {
287 WaylandSurfaceState::Xdg(WaylandXdgSurfaceState {
288 xdg_surface,
289 toplevel,
290 decoration: _decoration,
291 dialog,
292 }) => {
293 // drop the dialog before toplevel so compositor can explicitly unapply it's effects
294 if let Some(dialog) = dialog {
295 dialog.destroy();
296 }
297
298 // The role object (toplevel) must always be destroyed before the xdg_surface.
299 // See https://wayland.app/protocols/xdg-shell#xdg_surface:request:destroy
300 toplevel.destroy();
301 xdg_surface.destroy();
302 }
303 WaylandSurfaceState::LayerShell(WaylandLayerSurfaceState { layer_surface }) => {
304 layer_surface.destroy();
305 }
306 }
307 }
308}
309
310#[derive(Clone)]
311pub struct WaylandWindowStatePtr {
312 state: Rc<RefCell<WaylandWindowState>>,
313 callbacks: Rc<RefCell<Callbacks>>,
314}
315
316impl WaylandWindowState {
317 pub(crate) fn new(
318 handle: AnyWindowHandle,
319 surface: wl_surface::WlSurface,
320 surface_state: WaylandSurfaceState,
321 appearance: WindowAppearance,
322 viewport: Option<wp_viewport::WpViewport>,
323 client: WaylandClientStatePtr,
324 globals: Globals,
325 gpu_context: gpui_wgpu::GpuContext,
326 compositor_gpu: Option<CompositorGpuHint>,
327 options: WindowParams,
328 parent: Option<WaylandWindowStatePtr>,
329 ) -> anyhow::Result<Self> {
330 let renderer = {
331 let raw_window = RawWindow {
332 window: surface.id().as_ptr().cast::<c_void>(),
333 display: surface
334 .backend()
335 .upgrade()
336 .unwrap()
337 .display_ptr()
338 .cast::<c_void>(),
339 };
340 let config = WgpuSurfaceConfig {
341 size: Size {
342 width: DevicePixels(f32::from(options.bounds.size.width) as i32),
343 height: DevicePixels(f32::from(options.bounds.size.height) as i32),
344 },
345 transparent: true,
346 };
347 WgpuRenderer::new(gpu_context, &raw_window, config, compositor_gpu)?
348 };
349
350 if let WaylandSurfaceState::Xdg(ref xdg_state) = surface_state {
351 if let Some(title) = options.titlebar.and_then(|titlebar| titlebar.title) {
352 xdg_state.toplevel.set_title(title.to_string());
353 }
354 // Set max window size based on the GPU's maximum texture dimension.
355 // This prevents the window from being resized larger than what the GPU can render.
356 let max_texture_size = renderer.max_texture_size() as i32;
357 xdg_state
358 .toplevel
359 .set_max_size(max_texture_size, max_texture_size);
360 }
361
362 Ok(Self {
363 surface_state,
364 acknowledged_first_configure: false,
365 parent,
366 children: FxHashSet::default(),
367 surface,
368 app_id: None,
369 blur: None,
370 viewport,
371 globals,
372 outputs: HashMap::default(),
373 display: None,
374 renderer,
375 bounds: options.bounds,
376 scale: 1.0,
377 input_handler: None,
378 decorations: WindowDecorations::Client,
379 background_appearance: WindowBackgroundAppearance::Opaque,
380 fullscreen: false,
381 maximized: false,
382 tiling: Tiling::default(),
383 window_bounds: options.bounds,
384 in_progress_configure: None,
385 resize_throttle: false,
386 client,
387 appearance,
388 handle,
389 active: false,
390 hovered: false,
391 in_progress_window_controls: None,
392 window_controls: WindowControls::default(),
393 client_inset: None,
394 })
395 }
396
397 pub fn is_transparent(&self) -> bool {
398 self.decorations == WindowDecorations::Client
399 || self.background_appearance != WindowBackgroundAppearance::Opaque
400 }
401
402 pub fn primary_output_scale(&mut self) -> i32 {
403 let mut scale = 1;
404 let mut current_output = self.display.take();
405 for (id, output) in self.outputs.iter() {
406 if let Some((_, output_data)) = ¤t_output {
407 if output.scale > output_data.scale {
408 current_output = Some((id.clone(), output.clone()));
409 }
410 } else {
411 current_output = Some((id.clone(), output.clone()));
412 }
413 scale = scale.max(output.scale);
414 }
415 self.display = current_output;
416 scale
417 }
418
419 pub fn inset(&self) -> Pixels {
420 match self.decorations {
421 WindowDecorations::Server => px(0.0),
422 WindowDecorations::Client => self.client_inset.unwrap_or(px(0.0)),
423 }
424 }
425}
426
427pub(crate) struct WaylandWindow(pub WaylandWindowStatePtr);
428pub enum ImeInput {
429 InsertText(String),
430 SetMarkedText(String),
431 UnmarkText,
432 DeleteText,
433}
434
435impl Drop for WaylandWindow {
436 fn drop(&mut self) {
437 let mut state = self.0.state.borrow_mut();
438 let surface_id = state.surface.id();
439 if let Some(parent) = state.parent.as_ref() {
440 parent.state.borrow_mut().children.remove(&surface_id);
441 }
442
443 let client = state.client.clone();
444
445 state.renderer.destroy();
446
447 // Destroy blur first, this has no dependencies.
448 if let Some(blur) = &state.blur {
449 blur.release();
450 }
451
452 // Decorations must be destroyed before the xdg state.
453 // See https://wayland.app/protocols/xdg-decoration-unstable-v1#zxdg_toplevel_decoration_v1
454 if let Some(decoration) = &state.surface_state.decoration() {
455 decoration.destroy();
456 }
457
458 // Surface state might contain xdg_toplevel/xdg_surface which can be destroyed now that
459 // decorations are gone. layer_surface has no dependencies.
460 state.surface_state.destroy();
461
462 // Viewport must be destroyed before the wl_surface.
463 // See https://wayland.app/protocols/viewporter#wp_viewport
464 if let Some(viewport) = &state.viewport {
465 viewport.destroy();
466 }
467
468 // The wl_surface itself should always be destroyed last.
469 state.surface.destroy();
470
471 let state_ptr = self.0.clone();
472 state
473 .globals
474 .executor
475 .spawn(async move {
476 state_ptr.close();
477 client.drop_window(&surface_id)
478 })
479 .detach();
480 drop(state);
481 }
482}
483
484impl WaylandWindow {
485 fn borrow(&self) -> Ref<'_, WaylandWindowState> {
486 self.0.state.borrow()
487 }
488
489 fn borrow_mut(&self) -> RefMut<'_, WaylandWindowState> {
490 self.0.state.borrow_mut()
491 }
492
493 pub fn new(
494 handle: AnyWindowHandle,
495 globals: Globals,
496 gpu_context: gpui_wgpu::GpuContext,
497 compositor_gpu: Option<CompositorGpuHint>,
498 client: WaylandClientStatePtr,
499 params: WindowParams,
500 appearance: WindowAppearance,
501 parent: Option<WaylandWindowStatePtr>,
502 target_output: Option<wl_output::WlOutput>,
503 ) -> anyhow::Result<(Self, ObjectId)> {
504 let surface = globals.compositor.create_surface(&globals.qh, ());
505 let surface_state =
506 WaylandSurfaceState::new(&surface, &globals, ¶ms, parent.clone(), target_output)?;
507
508 if let Some(fractional_scale_manager) = globals.fractional_scale_manager.as_ref() {
509 fractional_scale_manager.get_fractional_scale(&surface, &globals.qh, surface.id());
510 }
511
512 let viewport = globals
513 .viewporter
514 .as_ref()
515 .map(|viewporter| viewporter.get_viewport(&surface, &globals.qh, ()));
516
517 let this = Self(WaylandWindowStatePtr {
518 state: Rc::new(RefCell::new(WaylandWindowState::new(
519 handle,
520 surface.clone(),
521 surface_state,
522 appearance,
523 viewport,
524 client,
525 globals,
526 gpu_context,
527 compositor_gpu,
528 params,
529 parent,
530 )?)),
531 callbacks: Rc::new(RefCell::new(Callbacks::default())),
532 });
533
534 // Kick things off
535 surface.commit();
536
537 Ok((this, surface.id()))
538 }
539}
540
541impl WaylandWindowStatePtr {
542 pub fn handle(&self) -> AnyWindowHandle {
543 self.state.borrow().handle
544 }
545
546 pub fn surface(&self) -> wl_surface::WlSurface {
547 self.state.borrow().surface.clone()
548 }
549
550 pub fn toplevel(&self) -> Option<xdg_toplevel::XdgToplevel> {
551 self.state.borrow().surface_state.toplevel().cloned()
552 }
553
554 pub fn ptr_eq(&self, other: &Self) -> bool {
555 Rc::ptr_eq(&self.state, &other.state)
556 }
557
558 pub fn add_child(&self, child: ObjectId) {
559 let mut state = self.state.borrow_mut();
560 state.children.insert(child);
561 }
562
563 pub fn is_blocked(&self) -> bool {
564 let state = self.state.borrow();
565 !state.children.is_empty()
566 }
567
568 pub fn frame(&self) {
569 let mut state = self.state.borrow_mut();
570 state.surface.frame(&state.globals.qh, state.surface.id());
571 state.resize_throttle = false;
572 drop(state);
573
574 let mut cb = self.callbacks.borrow_mut();
575 if let Some(fun) = cb.request_frame.as_mut() {
576 fun(Default::default());
577 }
578 }
579
580 pub fn handle_xdg_surface_event(&self, event: xdg_surface::Event) {
581 if let xdg_surface::Event::Configure { serial } = event {
582 {
583 let mut state = self.state.borrow_mut();
584 if let Some(window_controls) = state.in_progress_window_controls.take() {
585 state.window_controls = window_controls;
586
587 drop(state);
588 let mut callbacks = self.callbacks.borrow_mut();
589 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
590 appearance_changed();
591 }
592 }
593 }
594 {
595 let mut state = self.state.borrow_mut();
596
597 if let Some(mut configure) = state.in_progress_configure.take() {
598 let got_unmaximized = state.maximized && !configure.maximized;
599 state.fullscreen = configure.fullscreen;
600 state.maximized = configure.maximized;
601 state.tiling = configure.tiling;
602 // Limit interactive resizes to once per vblank
603 if configure.resizing && state.resize_throttle {
604 state.surface_state.ack_configure(serial);
605 return;
606 } else if configure.resizing {
607 state.resize_throttle = true;
608 }
609 if !configure.fullscreen && !configure.maximized {
610 configure.size = if got_unmaximized {
611 Some(state.window_bounds.size)
612 } else {
613 compute_outer_size(state.inset(), configure.size, state.tiling)
614 };
615 if let Some(size) = configure.size {
616 state.window_bounds = Bounds {
617 origin: Point::default(),
618 size,
619 };
620 }
621 }
622 drop(state);
623 if let Some(size) = configure.size {
624 self.resize(size);
625 }
626 }
627 }
628 let mut state = self.state.borrow_mut();
629 state.surface_state.ack_configure(serial);
630
631 let window_geometry = inset_by_tiling(
632 state.bounds.map_origin(|_| px(0.0)),
633 state.inset(),
634 state.tiling,
635 )
636 .map(|v| f32::from(v) as i32)
637 .map_size(|v| if v <= 0 { 1 } else { v });
638
639 state.surface_state.set_geometry(
640 window_geometry.origin.x,
641 window_geometry.origin.y,
642 window_geometry.size.width,
643 window_geometry.size.height,
644 );
645
646 let request_frame_callback = !state.acknowledged_first_configure;
647 if request_frame_callback {
648 state.acknowledged_first_configure = true;
649 drop(state);
650 self.frame();
651 }
652 }
653 }
654
655 pub fn handle_toplevel_decoration_event(&self, event: zxdg_toplevel_decoration_v1::Event) {
656 if let zxdg_toplevel_decoration_v1::Event::Configure { mode } = event {
657 match mode {
658 WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
659 self.state.borrow_mut().decorations = WindowDecorations::Server;
660 let callback = self.callbacks.borrow_mut().appearance_changed.take();
661 if let Some(mut fun) = callback {
662 fun();
663 self.callbacks.borrow_mut().appearance_changed = Some(fun);
664 }
665 }
666 WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
667 self.state.borrow_mut().decorations = WindowDecorations::Client;
668 // Update background to be transparent
669 let callback = self.callbacks.borrow_mut().appearance_changed.take();
670 if let Some(mut fun) = callback {
671 fun();
672 self.callbacks.borrow_mut().appearance_changed = Some(fun);
673 }
674 }
675 WEnum::Value(_) => {
676 log::warn!("Unknown decoration mode");
677 }
678 WEnum::Unknown(v) => {
679 log::warn!("Unknown decoration mode: {}", v);
680 }
681 }
682 }
683 }
684
685 pub fn handle_fractional_scale_event(&self, event: wp_fractional_scale_v1::Event) {
686 if let wp_fractional_scale_v1::Event::PreferredScale { scale } = event {
687 self.rescale(scale as f32 / 120.0);
688 }
689 }
690
691 pub fn handle_toplevel_event(&self, event: xdg_toplevel::Event) -> bool {
692 match event {
693 xdg_toplevel::Event::Configure {
694 width,
695 height,
696 states,
697 } => {
698 let size = if width == 0 || height == 0 {
699 None
700 } else {
701 Some(size(px(width as f32), px(height as f32)))
702 };
703
704 let states = extract_states::<xdg_toplevel::State>(&states);
705
706 let mut tiling = Tiling::default();
707 let mut fullscreen = false;
708 let mut maximized = false;
709 let mut resizing = false;
710
711 for state in states {
712 match state {
713 xdg_toplevel::State::Maximized => {
714 maximized = true;
715 }
716 xdg_toplevel::State::Fullscreen => {
717 fullscreen = true;
718 }
719 xdg_toplevel::State::Resizing => resizing = true,
720 xdg_toplevel::State::TiledTop => {
721 tiling.top = true;
722 }
723 xdg_toplevel::State::TiledLeft => {
724 tiling.left = true;
725 }
726 xdg_toplevel::State::TiledRight => {
727 tiling.right = true;
728 }
729 xdg_toplevel::State::TiledBottom => {
730 tiling.bottom = true;
731 }
732 _ => {
733 // noop
734 }
735 }
736 }
737
738 if fullscreen || maximized {
739 tiling = Tiling::tiled();
740 }
741
742 let mut state = self.state.borrow_mut();
743 state.in_progress_configure = Some(InProgressConfigure {
744 size,
745 fullscreen,
746 maximized,
747 resizing,
748 tiling,
749 });
750
751 false
752 }
753 xdg_toplevel::Event::Close => {
754 let mut cb = self.callbacks.borrow_mut();
755 if let Some(mut should_close) = cb.should_close.take() {
756 let result = (should_close)();
757 cb.should_close = Some(should_close);
758 if result {
759 drop(cb);
760 self.close();
761 }
762 result
763 } else {
764 true
765 }
766 }
767 xdg_toplevel::Event::WmCapabilities { capabilities } => {
768 let mut window_controls = WindowControls::default();
769
770 let states = extract_states::<xdg_toplevel::WmCapabilities>(&capabilities);
771
772 for state in states {
773 match state {
774 xdg_toplevel::WmCapabilities::Maximize => {
775 window_controls.maximize = true;
776 }
777 xdg_toplevel::WmCapabilities::Minimize => {
778 window_controls.minimize = true;
779 }
780 xdg_toplevel::WmCapabilities::Fullscreen => {
781 window_controls.fullscreen = true;
782 }
783 xdg_toplevel::WmCapabilities::WindowMenu => {
784 window_controls.window_menu = true;
785 }
786 _ => {}
787 }
788 }
789
790 let mut state = self.state.borrow_mut();
791 state.in_progress_window_controls = Some(window_controls);
792 false
793 }
794 _ => false,
795 }
796 }
797
798 pub fn handle_layersurface_event(&self, event: zwlr_layer_surface_v1::Event) -> bool {
799 match event {
800 zwlr_layer_surface_v1::Event::Configure {
801 width,
802 height,
803 serial,
804 } => {
805 let size = if width == 0 || height == 0 {
806 None
807 } else {
808 Some(size(px(width as f32), px(height as f32)))
809 };
810
811 let mut state = self.state.borrow_mut();
812 state.in_progress_configure = Some(InProgressConfigure {
813 size,
814 fullscreen: false,
815 maximized: false,
816 resizing: false,
817 tiling: Tiling::default(),
818 });
819 drop(state);
820
821 // just do the same thing we'd do as an xdg_surface
822 self.handle_xdg_surface_event(xdg_surface::Event::Configure { serial });
823
824 false
825 }
826 zwlr_layer_surface_v1::Event::Closed => {
827 // unlike xdg, we don't have a choice here: the surface is closing.
828 true
829 }
830 _ => false,
831 }
832 }
833
834 #[allow(clippy::mutable_key_type)]
835 pub fn handle_surface_event(
836 &self,
837 event: wl_surface::Event,
838 outputs: HashMap<ObjectId, Output>,
839 ) {
840 let mut state = self.state.borrow_mut();
841
842 match event {
843 wl_surface::Event::Enter { output } => {
844 let id = output.id();
845
846 let Some(output) = outputs.get(&id) else {
847 return;
848 };
849
850 state.outputs.insert(id, output.clone());
851
852 let scale = state.primary_output_scale();
853
854 // We use `PreferredBufferScale` instead to set the scale if it's available
855 if state.surface.version() < wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
856 state.surface.set_buffer_scale(scale);
857 drop(state);
858 self.rescale(scale as f32);
859 }
860 }
861 wl_surface::Event::Leave { output } => {
862 state.outputs.remove(&output.id());
863
864 let scale = state.primary_output_scale();
865
866 // We use `PreferredBufferScale` instead to set the scale if it's available
867 if state.surface.version() < wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
868 state.surface.set_buffer_scale(scale);
869 drop(state);
870 self.rescale(scale as f32);
871 }
872 }
873 wl_surface::Event::PreferredBufferScale { factor } => {
874 // We use `WpFractionalScale` instead to set the scale if it's available
875 if state.globals.fractional_scale_manager.is_none() {
876 state.surface.set_buffer_scale(factor);
877 drop(state);
878 self.rescale(factor as f32);
879 }
880 }
881 _ => {}
882 }
883 }
884
885 pub fn handle_ime(&self, ime: ImeInput) {
886 if self.is_blocked() {
887 return;
888 }
889 let mut state = self.state.borrow_mut();
890 if let Some(mut input_handler) = state.input_handler.take() {
891 drop(state);
892 match ime {
893 ImeInput::InsertText(text) => {
894 input_handler.replace_text_in_range(None, &text);
895 }
896 ImeInput::SetMarkedText(text) => {
897 input_handler.replace_and_mark_text_in_range(None, &text, None);
898 }
899 ImeInput::UnmarkText => {
900 input_handler.unmark_text();
901 }
902 ImeInput::DeleteText => {
903 if let Some(marked) = input_handler.marked_text_range() {
904 input_handler.replace_text_in_range(Some(marked), "");
905 }
906 }
907 }
908 self.state.borrow_mut().input_handler = Some(input_handler);
909 }
910 }
911
912 pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
913 let mut state = self.state.borrow_mut();
914 let mut bounds: Option<Bounds<Pixels>> = None;
915 if let Some(mut input_handler) = state.input_handler.take() {
916 drop(state);
917 if let Some(selection) = input_handler.marked_text_range() {
918 bounds = input_handler.bounds_for_range(selection.start..selection.start);
919 }
920 self.state.borrow_mut().input_handler = Some(input_handler);
921 }
922 bounds
923 }
924
925 pub fn set_size_and_scale(&self, size: Option<Size<Pixels>>, scale: Option<f32>) {
926 let (size, scale) = {
927 let mut state = self.state.borrow_mut();
928 if size.is_none_or(|size| size == state.bounds.size)
929 && scale.is_none_or(|scale| scale == state.scale)
930 {
931 return;
932 }
933 if let Some(size) = size {
934 state.bounds.size = size;
935 }
936 if let Some(scale) = scale {
937 state.scale = scale;
938 }
939 let device_bounds = state.bounds.to_device_pixels(state.scale);
940 state.renderer.update_drawable_size(device_bounds.size);
941 (state.bounds.size, state.scale)
942 };
943
944 let callback = self.callbacks.borrow_mut().resize.take();
945 if let Some(mut fun) = callback {
946 fun(size, scale);
947 self.callbacks.borrow_mut().resize = Some(fun);
948 }
949
950 {
951 let state = self.state.borrow();
952 if let Some(viewport) = &state.viewport {
953 viewport
954 .set_destination(f32::from(size.width) as i32, f32::from(size.height) as i32);
955 }
956 }
957 }
958
959 pub fn resize(&self, size: Size<Pixels>) {
960 self.set_size_and_scale(Some(size), None);
961 }
962
963 pub fn rescale(&self, scale: f32) {
964 self.set_size_and_scale(None, Some(scale));
965 }
966
967 pub fn close(&self) {
968 let state = self.state.borrow();
969 let client = state.client.get_client();
970 #[allow(clippy::mutable_key_type)]
971 let children = state.children.clone();
972 drop(state);
973
974 for child in children {
975 let mut client_state = client.borrow_mut();
976 let window = get_window(&mut client_state, &child);
977 drop(client_state);
978
979 if let Some(child) = window {
980 child.close();
981 }
982 }
983 let mut callbacks = self.callbacks.borrow_mut();
984 if let Some(fun) = callbacks.close.take() {
985 fun()
986 }
987 }
988
989 pub fn handle_input(&self, input: PlatformInput) {
990 if self.is_blocked() {
991 return;
992 }
993 let callback = self.callbacks.borrow_mut().input.take();
994 if let Some(mut fun) = callback {
995 let result = fun(input.clone());
996 self.callbacks.borrow_mut().input = Some(fun);
997 if !result.propagate {
998 return;
999 }
1000 }
1001 if let PlatformInput::KeyDown(event) = input
1002 && event.keystroke.modifiers.is_subset_of(&Modifiers::shift())
1003 && let Some(key_char) = &event.keystroke.key_char
1004 {
1005 let mut state = self.state.borrow_mut();
1006 if let Some(mut input_handler) = state.input_handler.take() {
1007 drop(state);
1008 input_handler.replace_text_in_range(None, key_char);
1009 self.state.borrow_mut().input_handler = Some(input_handler);
1010 }
1011 }
1012 }
1013
1014 pub fn set_focused(&self, focus: bool) {
1015 self.state.borrow_mut().active = focus;
1016 let callback = self.callbacks.borrow_mut().active_status_change.take();
1017 if let Some(mut fun) = callback {
1018 fun(focus);
1019 self.callbacks.borrow_mut().active_status_change = Some(fun);
1020 }
1021 }
1022
1023 pub fn set_hovered(&self, focus: bool) {
1024 let callback = self.callbacks.borrow_mut().hover_status_change.take();
1025 if let Some(mut fun) = callback {
1026 fun(focus);
1027 self.callbacks.borrow_mut().hover_status_change = Some(fun);
1028 }
1029 }
1030
1031 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1032 self.state.borrow_mut().appearance = appearance;
1033
1034 let callback = self.callbacks.borrow_mut().appearance_changed.take();
1035 if let Some(mut fun) = callback {
1036 fun();
1037 self.callbacks.borrow_mut().appearance_changed = Some(fun);
1038 }
1039 }
1040
1041 pub fn primary_output_scale(&self) -> i32 {
1042 self.state.borrow_mut().primary_output_scale()
1043 }
1044}
1045
1046fn extract_states<'a, S: TryFrom<u32> + 'a>(states: &'a [u8]) -> impl Iterator<Item = S> + 'a
1047where
1048 <S as TryFrom<u32>>::Error: 'a,
1049{
1050 states
1051 .chunks_exact(4)
1052 .flat_map(TryInto::<[u8; 4]>::try_into)
1053 .map(u32::from_ne_bytes)
1054 .flat_map(S::try_from)
1055}
1056
1057impl rwh::HasWindowHandle for WaylandWindow {
1058 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1059 let surface = self.0.surface().id().as_ptr() as *mut libc::c_void;
1060 let c_ptr = NonNull::new(surface).ok_or(rwh::HandleError::Unavailable)?;
1061 let handle = rwh::WaylandWindowHandle::new(c_ptr);
1062 let raw_handle = rwh::RawWindowHandle::Wayland(handle);
1063 Ok(unsafe { rwh::WindowHandle::borrow_raw(raw_handle) })
1064 }
1065}
1066
1067impl rwh::HasDisplayHandle for WaylandWindow {
1068 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1069 let display = self
1070 .0
1071 .surface()
1072 .backend()
1073 .upgrade()
1074 .ok_or(rwh::HandleError::Unavailable)?
1075 .display_ptr() as *mut libc::c_void;
1076
1077 let c_ptr = NonNull::new(display).ok_or(rwh::HandleError::Unavailable)?;
1078 let handle = rwh::WaylandDisplayHandle::new(c_ptr);
1079 let raw_handle = rwh::RawDisplayHandle::Wayland(handle);
1080 Ok(unsafe { rwh::DisplayHandle::borrow_raw(raw_handle) })
1081 }
1082}
1083
1084impl PlatformWindow for WaylandWindow {
1085 fn bounds(&self) -> Bounds<Pixels> {
1086 self.borrow().bounds
1087 }
1088
1089 fn is_maximized(&self) -> bool {
1090 self.borrow().maximized
1091 }
1092
1093 fn window_bounds(&self) -> WindowBounds {
1094 let state = self.borrow();
1095 if state.fullscreen {
1096 WindowBounds::Fullscreen(state.window_bounds)
1097 } else if state.maximized {
1098 WindowBounds::Maximized(state.window_bounds)
1099 } else {
1100 drop(state);
1101 WindowBounds::Windowed(self.bounds())
1102 }
1103 }
1104
1105 fn inner_window_bounds(&self) -> WindowBounds {
1106 let state = self.borrow();
1107 if state.fullscreen {
1108 WindowBounds::Fullscreen(state.window_bounds)
1109 } else if state.maximized {
1110 WindowBounds::Maximized(state.window_bounds)
1111 } else {
1112 let inset = state.inset();
1113 drop(state);
1114 WindowBounds::Windowed(self.bounds().inset(inset))
1115 }
1116 }
1117
1118 fn content_size(&self) -> Size<Pixels> {
1119 self.borrow().bounds.size
1120 }
1121
1122 fn resize(&mut self, size: Size<Pixels>) {
1123 let state = self.borrow();
1124 let state_ptr = self.0.clone();
1125
1126 // Keep window geometry consistent with configure handling. On Wayland, window geometry is
1127 // surface-local: resizing should not attempt to translate the window; the compositor
1128 // controls placement. We also account for client-side decoration insets and tiling.
1129 let window_geometry = inset_by_tiling(
1130 Bounds {
1131 origin: Point::default(),
1132 size,
1133 },
1134 state.inset(),
1135 state.tiling,
1136 )
1137 .map(|v| f32::from(v) as i32)
1138 .map_size(|v| if v <= 0 { 1 } else { v });
1139
1140 state.surface_state.set_geometry(
1141 window_geometry.origin.x,
1142 window_geometry.origin.y,
1143 window_geometry.size.width,
1144 window_geometry.size.height,
1145 );
1146
1147 state
1148 .globals
1149 .executor
1150 .spawn(async move { state_ptr.resize(size) })
1151 .detach();
1152 }
1153
1154 fn scale_factor(&self) -> f32 {
1155 self.borrow().scale
1156 }
1157
1158 fn appearance(&self) -> WindowAppearance {
1159 self.borrow().appearance
1160 }
1161
1162 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1163 let state = self.borrow();
1164 state.display.as_ref().map(|(id, display)| {
1165 Rc::new(WaylandDisplay {
1166 id: id.clone(),
1167 name: display.name.clone(),
1168 bounds: display.bounds.to_pixels(state.scale),
1169 }) as Rc<dyn PlatformDisplay>
1170 })
1171 }
1172
1173 fn mouse_position(&self) -> Point<Pixels> {
1174 self.borrow()
1175 .client
1176 .get_client()
1177 .borrow()
1178 .mouse_location
1179 .unwrap_or_default()
1180 }
1181
1182 fn modifiers(&self) -> Modifiers {
1183 self.borrow().client.get_client().borrow().modifiers
1184 }
1185
1186 fn capslock(&self) -> Capslock {
1187 self.borrow().client.get_client().borrow().capslock
1188 }
1189
1190 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1191 self.borrow_mut().input_handler = Some(input_handler);
1192 }
1193
1194 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1195 self.borrow_mut().input_handler.take()
1196 }
1197
1198 fn prompt(
1199 &self,
1200 _level: PromptLevel,
1201 _msg: &str,
1202 _detail: Option<&str>,
1203 _answers: &[PromptButton],
1204 ) -> Option<Receiver<usize>> {
1205 None
1206 }
1207
1208 fn activate(&self) {
1209 // Try to request an activation token. Even though the activation is likely going to be rejected,
1210 // KWin and Mutter can use the app_id to visually indicate we're requesting attention.
1211 let state = self.borrow();
1212 if let (Some(activation), Some(app_id)) = (&state.globals.activation, state.app_id.clone())
1213 {
1214 state.client.set_pending_activation(state.surface.id());
1215 let token = activation.get_activation_token(&state.globals.qh, ());
1216 // The serial isn't exactly important here, since the activation is probably going to be rejected anyway.
1217 let serial = state.client.get_serial(SerialKind::MousePress);
1218 token.set_app_id(app_id);
1219 token.set_serial(serial, &state.globals.seat);
1220 token.set_surface(&state.surface);
1221 token.commit();
1222 }
1223 }
1224
1225 fn is_active(&self) -> bool {
1226 self.borrow().active
1227 }
1228
1229 fn is_hovered(&self) -> bool {
1230 self.borrow().hovered
1231 }
1232
1233 fn set_title(&mut self, title: &str) {
1234 if let Some(toplevel) = self.borrow().surface_state.toplevel() {
1235 toplevel.set_title(title.to_string());
1236 }
1237 }
1238
1239 fn set_app_id(&mut self, app_id: &str) {
1240 let mut state = self.borrow_mut();
1241 if let Some(toplevel) = state.surface_state.toplevel() {
1242 toplevel.set_app_id(app_id.to_owned());
1243 }
1244 state.app_id = Some(app_id.to_owned());
1245 }
1246
1247 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1248 let mut state = self.borrow_mut();
1249 state.background_appearance = background_appearance;
1250 update_window(state);
1251 }
1252
1253 fn background_appearance(&self) -> WindowBackgroundAppearance {
1254 self.borrow().background_appearance
1255 }
1256
1257 fn is_subpixel_rendering_supported(&self) -> bool {
1258 let client = self.borrow().client.get_client();
1259 let state = client.borrow();
1260 state
1261 .gpu_context
1262 .borrow()
1263 .as_ref()
1264 .is_some_and(|ctx| ctx.supports_dual_source_blending())
1265 }
1266
1267 fn minimize(&self) {
1268 if let Some(toplevel) = self.borrow().surface_state.toplevel() {
1269 toplevel.set_minimized();
1270 }
1271 }
1272
1273 fn zoom(&self) {
1274 let state = self.borrow();
1275 if let Some(toplevel) = state.surface_state.toplevel() {
1276 if !state.maximized {
1277 toplevel.set_maximized();
1278 } else {
1279 toplevel.unset_maximized();
1280 }
1281 }
1282 }
1283
1284 fn toggle_fullscreen(&self) {
1285 let state = self.borrow();
1286 if let Some(toplevel) = state.surface_state.toplevel() {
1287 if !state.fullscreen {
1288 toplevel.set_fullscreen(None);
1289 } else {
1290 toplevel.unset_fullscreen();
1291 }
1292 }
1293 }
1294
1295 fn is_fullscreen(&self) -> bool {
1296 self.borrow().fullscreen
1297 }
1298
1299 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1300 self.0.callbacks.borrow_mut().request_frame = Some(callback);
1301 }
1302
1303 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>) {
1304 self.0.callbacks.borrow_mut().input = Some(callback);
1305 }
1306
1307 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1308 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1309 }
1310
1311 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1312 self.0.callbacks.borrow_mut().hover_status_change = Some(callback);
1313 }
1314
1315 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1316 self.0.callbacks.borrow_mut().resize = Some(callback);
1317 }
1318
1319 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1320 self.0.callbacks.borrow_mut().moved = Some(callback);
1321 }
1322
1323 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1324 self.0.callbacks.borrow_mut().should_close = Some(callback);
1325 }
1326
1327 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1328 self.0.callbacks.borrow_mut().close = Some(callback);
1329 }
1330
1331 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1332 }
1333
1334 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1335 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1336 }
1337
1338 fn draw(&self, scene: &Scene) {
1339 let mut state = self.borrow_mut();
1340
1341 if state.renderer.device_lost() {
1342 let raw_window = RawWindow {
1343 window: state.surface.id().as_ptr().cast::<std::ffi::c_void>(),
1344 display: state
1345 .surface
1346 .backend()
1347 .upgrade()
1348 .unwrap()
1349 .display_ptr()
1350 .cast::<std::ffi::c_void>(),
1351 };
1352 state.renderer.recover(&raw_window).unwrap_or_else(|err| {
1353 panic!(
1354 "GPU device lost and recovery failed. \
1355 This may happen after system suspend/resume. \
1356 Please restart the application.\n\nError: {err}"
1357 )
1358 });
1359
1360 // The current scene references atlas textures that were cleared during recovery.
1361 // Skip this frame and let the next frame rebuild the scene with fresh textures.
1362 return;
1363 }
1364
1365 state.renderer.draw(scene);
1366 }
1367
1368 fn completed_frame(&self) {
1369 let state = self.borrow();
1370 state.surface.commit();
1371 }
1372
1373 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1374 let state = self.borrow();
1375 state.renderer.sprite_atlas().clone()
1376 }
1377
1378 fn show_window_menu(&self, position: Point<Pixels>) {
1379 let state = self.borrow();
1380 let serial = state.client.get_serial(SerialKind::MousePress);
1381 if let Some(toplevel) = state.surface_state.toplevel() {
1382 toplevel.show_window_menu(
1383 &state.globals.seat,
1384 serial,
1385 f32::from(position.x) as i32,
1386 f32::from(position.y) as i32,
1387 );
1388 }
1389 }
1390
1391 fn start_window_move(&self) {
1392 let state = self.borrow();
1393 let serial = state.client.get_serial(SerialKind::MousePress);
1394 if let Some(toplevel) = state.surface_state.toplevel() {
1395 toplevel._move(&state.globals.seat, serial);
1396 }
1397 }
1398
1399 fn start_window_resize(&self, edge: gpui::ResizeEdge) {
1400 let state = self.borrow();
1401 if let Some(toplevel) = state.surface_state.toplevel() {
1402 toplevel.resize(
1403 &state.globals.seat,
1404 state.client.get_serial(SerialKind::MousePress),
1405 edge.to_xdg(),
1406 )
1407 }
1408 }
1409
1410 fn window_decorations(&self) -> Decorations {
1411 let state = self.borrow();
1412 match state.decorations {
1413 WindowDecorations::Server => Decorations::Server,
1414 WindowDecorations::Client => Decorations::Client {
1415 tiling: state.tiling,
1416 },
1417 }
1418 }
1419
1420 fn request_decorations(&self, decorations: WindowDecorations) {
1421 let mut state = self.borrow_mut();
1422 match state.surface_state.decoration().as_ref() {
1423 Some(decoration) => {
1424 decoration.set_mode(decorations.to_xdg());
1425 state.decorations = decorations;
1426 update_window(state);
1427 }
1428 None => {
1429 if matches!(decorations, WindowDecorations::Server) {
1430 log::info!(
1431 "Server-side decorations requested, but the Wayland server does not support them. Falling back to client-side decorations."
1432 );
1433 }
1434 state.decorations = WindowDecorations::Client;
1435 update_window(state);
1436 }
1437 }
1438 }
1439
1440 fn window_controls(&self) -> WindowControls {
1441 self.borrow().window_controls
1442 }
1443
1444 fn set_client_inset(&self, inset: Pixels) {
1445 let mut state = self.borrow_mut();
1446 if Some(inset) != state.client_inset {
1447 state.client_inset = Some(inset);
1448 update_window(state);
1449 }
1450 }
1451
1452 fn update_ime_position(&self, bounds: Bounds<Pixels>) {
1453 let state = self.borrow();
1454 state.client.update_ime_position(bounds);
1455 }
1456
1457 fn gpu_specs(&self) -> Option<GpuSpecs> {
1458 self.borrow().renderer.gpu_specs().into()
1459 }
1460}
1461
1462fn update_window(mut state: RefMut<WaylandWindowState>) {
1463 let opaque = !state.is_transparent();
1464
1465 state.renderer.update_transparency(!opaque);
1466 let opaque_area = state.window_bounds.map(|v| f32::from(v) as i32);
1467 opaque_area.inset(f32::from(state.inset()) as i32);
1468
1469 let region = state
1470 .globals
1471 .compositor
1472 .create_region(&state.globals.qh, ());
1473 region.add(
1474 opaque_area.origin.x,
1475 opaque_area.origin.y,
1476 opaque_area.size.width,
1477 opaque_area.size.height,
1478 );
1479
1480 // Note that rounded corners make this rectangle API hard to work with.
1481 // As this is common when using CSD, let's just disable this API.
1482 if state.background_appearance == WindowBackgroundAppearance::Opaque
1483 && state.decorations == WindowDecorations::Server
1484 {
1485 // Promise the compositor that this region of the window surface
1486 // contains no transparent pixels. This allows the compositor to skip
1487 // updating whatever is behind the surface for better performance.
1488 state.surface.set_opaque_region(Some(®ion));
1489 } else {
1490 state.surface.set_opaque_region(None);
1491 }
1492
1493 if let Some(ref blur_manager) = state.globals.blur_manager {
1494 if state.background_appearance == WindowBackgroundAppearance::Blurred {
1495 if state.blur.is_none() {
1496 let blur = blur_manager.create(&state.surface, &state.globals.qh, ());
1497 state.blur = Some(blur);
1498 }
1499 state.blur.as_ref().unwrap().commit();
1500 } else {
1501 // It probably doesn't hurt to clear the blur for opaque windows
1502 blur_manager.unset(&state.surface);
1503 if let Some(b) = state.blur.take() {
1504 b.release()
1505 }
1506 }
1507 }
1508
1509 region.destroy();
1510}
1511
1512pub(crate) trait WindowDecorationsExt {
1513 fn to_xdg(self) -> zxdg_toplevel_decoration_v1::Mode;
1514}
1515
1516impl WindowDecorationsExt for WindowDecorations {
1517 fn to_xdg(self) -> zxdg_toplevel_decoration_v1::Mode {
1518 match self {
1519 WindowDecorations::Client => zxdg_toplevel_decoration_v1::Mode::ClientSide,
1520 WindowDecorations::Server => zxdg_toplevel_decoration_v1::Mode::ServerSide,
1521 }
1522 }
1523}
1524
1525pub(crate) trait ResizeEdgeWaylandExt {
1526 fn to_xdg(self) -> xdg_toplevel::ResizeEdge;
1527}
1528
1529impl ResizeEdgeWaylandExt for ResizeEdge {
1530 fn to_xdg(self) -> xdg_toplevel::ResizeEdge {
1531 match self {
1532 ResizeEdge::Top => xdg_toplevel::ResizeEdge::Top,
1533 ResizeEdge::TopRight => xdg_toplevel::ResizeEdge::TopRight,
1534 ResizeEdge::Right => xdg_toplevel::ResizeEdge::Right,
1535 ResizeEdge::BottomRight => xdg_toplevel::ResizeEdge::BottomRight,
1536 ResizeEdge::Bottom => xdg_toplevel::ResizeEdge::Bottom,
1537 ResizeEdge::BottomLeft => xdg_toplevel::ResizeEdge::BottomLeft,
1538 ResizeEdge::Left => xdg_toplevel::ResizeEdge::Left,
1539 ResizeEdge::TopLeft => xdg_toplevel::ResizeEdge::TopLeft,
1540 }
1541 }
1542}
1543
1544/// The configuration event is in terms of the window geometry, which we are constantly
1545/// updating to account for the client decorations. But that's not the area we want to render
1546/// to, due to our intrusize CSD. So, here we calculate the 'actual' size, by adding back in the insets
1547fn compute_outer_size(
1548 inset: Pixels,
1549 new_size: Option<Size<Pixels>>,
1550 tiling: Tiling,
1551) -> Option<Size<Pixels>> {
1552 new_size.map(|mut new_size| {
1553 if !tiling.top {
1554 new_size.height += inset;
1555 }
1556 if !tiling.bottom {
1557 new_size.height += inset;
1558 }
1559 if !tiling.left {
1560 new_size.width += inset;
1561 }
1562 if !tiling.right {
1563 new_size.width += inset;
1564 }
1565
1566 new_size
1567 })
1568}
1569
1570fn inset_by_tiling(mut bounds: Bounds<Pixels>, inset: Pixels, tiling: Tiling) -> Bounds<Pixels> {
1571 if !tiling.top {
1572 bounds.origin.y += inset;
1573 bounds.size.height -= inset;
1574 }
1575 if !tiling.bottom {
1576 bounds.size.height -= inset;
1577 }
1578 if !tiling.left {
1579 bounds.origin.x += inset;
1580 bounds.size.width -= inset;
1581 }
1582 if !tiling.right {
1583 bounds.size.width -= inset;
1584 }
1585
1586 bounds
1587}