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