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