window.rs

   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::{WgpuContext, 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) = &params.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: &mut Option<WgpuContext>,
 321        options: WindowParams,
 322        parent: Option<WaylandWindowStatePtr>,
 323    ) -> anyhow::Result<Self> {
 324        let renderer = {
 325            let raw_window = RawWindow {
 326                window: surface.id().as_ptr().cast::<c_void>(),
 327                display: surface
 328                    .backend()
 329                    .upgrade()
 330                    .unwrap()
 331                    .display_ptr()
 332                    .cast::<c_void>(),
 333            };
 334            let config = WgpuSurfaceConfig {
 335                size: Size {
 336                    width: DevicePixels(f32::from(options.bounds.size.width) as i32),
 337                    height: DevicePixels(f32::from(options.bounds.size.height) as i32),
 338                },
 339                transparent: true,
 340            };
 341            WgpuRenderer::new(gpu_context, &raw_window, config)?
 342        };
 343
 344        if let WaylandSurfaceState::Xdg(ref xdg_state) = surface_state {
 345            if let Some(title) = options.titlebar.and_then(|titlebar| titlebar.title) {
 346                xdg_state.toplevel.set_title(title.to_string());
 347            }
 348        }
 349
 350        Ok(Self {
 351            surface_state,
 352            acknowledged_first_configure: false,
 353            parent,
 354            children: FxHashSet::default(),
 355            surface,
 356            app_id: None,
 357            blur: None,
 358            viewport,
 359            globals,
 360            outputs: HashMap::default(),
 361            display: None,
 362            renderer,
 363            bounds: options.bounds,
 364            scale: 1.0,
 365            input_handler: None,
 366            decorations: WindowDecorations::Client,
 367            background_appearance: WindowBackgroundAppearance::Opaque,
 368            fullscreen: false,
 369            maximized: false,
 370            tiling: Tiling::default(),
 371            window_bounds: options.bounds,
 372            in_progress_configure: None,
 373            resize_throttle: false,
 374            client,
 375            appearance,
 376            handle,
 377            active: false,
 378            hovered: false,
 379            in_progress_window_controls: None,
 380            window_controls: WindowControls::default(),
 381            client_inset: None,
 382        })
 383    }
 384
 385    pub fn is_transparent(&self) -> bool {
 386        self.decorations == WindowDecorations::Client
 387            || self.background_appearance != WindowBackgroundAppearance::Opaque
 388    }
 389
 390    pub fn primary_output_scale(&mut self) -> i32 {
 391        let mut scale = 1;
 392        let mut current_output = self.display.take();
 393        for (id, output) in self.outputs.iter() {
 394            if let Some((_, output_data)) = &current_output {
 395                if output.scale > output_data.scale {
 396                    current_output = Some((id.clone(), output.clone()));
 397                }
 398            } else {
 399                current_output = Some((id.clone(), output.clone()));
 400            }
 401            scale = scale.max(output.scale);
 402        }
 403        self.display = current_output;
 404        scale
 405    }
 406
 407    pub fn inset(&self) -> Pixels {
 408        match self.decorations {
 409            WindowDecorations::Server => px(0.0),
 410            WindowDecorations::Client => self.client_inset.unwrap_or(px(0.0)),
 411        }
 412    }
 413}
 414
 415pub(crate) struct WaylandWindow(pub WaylandWindowStatePtr);
 416pub enum ImeInput {
 417    InsertText(String),
 418    SetMarkedText(String),
 419    UnmarkText,
 420    DeleteText,
 421}
 422
 423impl Drop for WaylandWindow {
 424    fn drop(&mut self) {
 425        let mut state = self.0.state.borrow_mut();
 426        let surface_id = state.surface.id();
 427        if let Some(parent) = state.parent.as_ref() {
 428            parent.state.borrow_mut().children.remove(&surface_id);
 429        }
 430
 431        let client = state.client.clone();
 432
 433        state.renderer.destroy();
 434
 435        // Destroy blur first, this has no dependencies.
 436        if let Some(blur) = &state.blur {
 437            blur.release();
 438        }
 439
 440        // Decorations must be destroyed before the xdg state.
 441        // See https://wayland.app/protocols/xdg-decoration-unstable-v1#zxdg_toplevel_decoration_v1
 442        if let Some(decoration) = &state.surface_state.decoration() {
 443            decoration.destroy();
 444        }
 445
 446        // Surface state might contain xdg_toplevel/xdg_surface which can be destroyed now that
 447        // decorations are gone. layer_surface has no dependencies.
 448        state.surface_state.destroy();
 449
 450        // Viewport must be destroyed before the wl_surface.
 451        // See https://wayland.app/protocols/viewporter#wp_viewport
 452        if let Some(viewport) = &state.viewport {
 453            viewport.destroy();
 454        }
 455
 456        // The wl_surface itself should always be destroyed last.
 457        state.surface.destroy();
 458
 459        let state_ptr = self.0.clone();
 460        state
 461            .globals
 462            .executor
 463            .spawn(async move {
 464                state_ptr.close();
 465                client.drop_window(&surface_id)
 466            })
 467            .detach();
 468        drop(state);
 469    }
 470}
 471
 472impl WaylandWindow {
 473    fn borrow(&self) -> Ref<'_, WaylandWindowState> {
 474        self.0.state.borrow()
 475    }
 476
 477    fn borrow_mut(&self) -> RefMut<'_, WaylandWindowState> {
 478        self.0.state.borrow_mut()
 479    }
 480
 481    pub fn new(
 482        handle: AnyWindowHandle,
 483        globals: Globals,
 484        gpu_context: &mut Option<WgpuContext>,
 485        client: WaylandClientStatePtr,
 486        params: WindowParams,
 487        appearance: WindowAppearance,
 488        parent: Option<WaylandWindowStatePtr>,
 489    ) -> anyhow::Result<(Self, ObjectId)> {
 490        let surface = globals.compositor.create_surface(&globals.qh, ());
 491        let surface_state = WaylandSurfaceState::new(&surface, &globals, &params, parent.clone())?;
 492
 493        if let Some(fractional_scale_manager) = globals.fractional_scale_manager.as_ref() {
 494            fractional_scale_manager.get_fractional_scale(&surface, &globals.qh, surface.id());
 495        }
 496
 497        let viewport = globals
 498            .viewporter
 499            .as_ref()
 500            .map(|viewporter| viewporter.get_viewport(&surface, &globals.qh, ()));
 501
 502        let this = Self(WaylandWindowStatePtr {
 503            state: Rc::new(RefCell::new(WaylandWindowState::new(
 504                handle,
 505                surface.clone(),
 506                surface_state,
 507                appearance,
 508                viewport,
 509                client,
 510                globals,
 511                gpu_context,
 512                params,
 513                parent,
 514            )?)),
 515            callbacks: Rc::new(RefCell::new(Callbacks::default())),
 516        });
 517
 518        // Kick things off
 519        surface.commit();
 520
 521        Ok((this, surface.id()))
 522    }
 523}
 524
 525impl WaylandWindowStatePtr {
 526    pub fn handle(&self) -> AnyWindowHandle {
 527        self.state.borrow().handle
 528    }
 529
 530    pub fn surface(&self) -> wl_surface::WlSurface {
 531        self.state.borrow().surface.clone()
 532    }
 533
 534    pub fn toplevel(&self) -> Option<xdg_toplevel::XdgToplevel> {
 535        self.state.borrow().surface_state.toplevel().cloned()
 536    }
 537
 538    pub fn ptr_eq(&self, other: &Self) -> bool {
 539        Rc::ptr_eq(&self.state, &other.state)
 540    }
 541
 542    pub fn add_child(&self, child: ObjectId) {
 543        let mut state = self.state.borrow_mut();
 544        state.children.insert(child);
 545    }
 546
 547    pub fn is_blocked(&self) -> bool {
 548        let state = self.state.borrow();
 549        !state.children.is_empty()
 550    }
 551
 552    pub fn frame(&self) {
 553        let mut state = self.state.borrow_mut();
 554        state.surface.frame(&state.globals.qh, state.surface.id());
 555        state.resize_throttle = false;
 556        drop(state);
 557
 558        let mut cb = self.callbacks.borrow_mut();
 559        if let Some(fun) = cb.request_frame.as_mut() {
 560            fun(Default::default());
 561        }
 562    }
 563
 564    pub fn handle_xdg_surface_event(&self, event: xdg_surface::Event) {
 565        if let xdg_surface::Event::Configure { serial } = event {
 566            {
 567                let mut state = self.state.borrow_mut();
 568                if let Some(window_controls) = state.in_progress_window_controls.take() {
 569                    state.window_controls = window_controls;
 570
 571                    drop(state);
 572                    let mut callbacks = self.callbacks.borrow_mut();
 573                    if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
 574                        appearance_changed();
 575                    }
 576                }
 577            }
 578            {
 579                let mut state = self.state.borrow_mut();
 580
 581                if let Some(mut configure) = state.in_progress_configure.take() {
 582                    let got_unmaximized = state.maximized && !configure.maximized;
 583                    state.fullscreen = configure.fullscreen;
 584                    state.maximized = configure.maximized;
 585                    state.tiling = configure.tiling;
 586                    // Limit interactive resizes to once per vblank
 587                    if configure.resizing && state.resize_throttle {
 588                        return;
 589                    } else if configure.resizing {
 590                        state.resize_throttle = true;
 591                    }
 592                    if !configure.fullscreen && !configure.maximized {
 593                        configure.size = if got_unmaximized {
 594                            Some(state.window_bounds.size)
 595                        } else {
 596                            compute_outer_size(state.inset(), configure.size, state.tiling)
 597                        };
 598                        if let Some(size) = configure.size {
 599                            state.window_bounds = Bounds {
 600                                origin: Point::default(),
 601                                size,
 602                            };
 603                        }
 604                    }
 605                    drop(state);
 606                    if let Some(size) = configure.size {
 607                        self.resize(size);
 608                    }
 609                }
 610            }
 611            let mut state = self.state.borrow_mut();
 612            state.surface_state.ack_configure(serial);
 613
 614            let window_geometry = inset_by_tiling(
 615                state.bounds.map_origin(|_| px(0.0)),
 616                state.inset(),
 617                state.tiling,
 618            )
 619            .map(|v| f32::from(v) as i32)
 620            .map_size(|v| if v <= 0 { 1 } else { v });
 621
 622            state.surface_state.set_geometry(
 623                window_geometry.origin.x,
 624                window_geometry.origin.y,
 625                window_geometry.size.width,
 626                window_geometry.size.height,
 627            );
 628
 629            let request_frame_callback = !state.acknowledged_first_configure;
 630            if request_frame_callback {
 631                state.acknowledged_first_configure = true;
 632                drop(state);
 633                self.frame();
 634            }
 635        }
 636    }
 637
 638    pub fn handle_toplevel_decoration_event(&self, event: zxdg_toplevel_decoration_v1::Event) {
 639        if let zxdg_toplevel_decoration_v1::Event::Configure { mode } = event {
 640            match mode {
 641                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
 642                    self.state.borrow_mut().decorations = WindowDecorations::Server;
 643                    let callback = self.callbacks.borrow_mut().appearance_changed.take();
 644                    if let Some(mut fun) = callback {
 645                        fun();
 646                        self.callbacks.borrow_mut().appearance_changed = Some(fun);
 647                    }
 648                }
 649                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
 650                    self.state.borrow_mut().decorations = WindowDecorations::Client;
 651                    // Update background to be transparent
 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(_) => {
 659                    log::warn!("Unknown decoration mode");
 660                }
 661                WEnum::Unknown(v) => {
 662                    log::warn!("Unknown decoration mode: {}", v);
 663                }
 664            }
 665        }
 666    }
 667
 668    pub fn handle_fractional_scale_event(&self, event: wp_fractional_scale_v1::Event) {
 669        if let wp_fractional_scale_v1::Event::PreferredScale { scale } = event {
 670            self.rescale(scale as f32 / 120.0);
 671        }
 672    }
 673
 674    pub fn handle_toplevel_event(&self, event: xdg_toplevel::Event) -> bool {
 675        match event {
 676            xdg_toplevel::Event::Configure {
 677                width,
 678                height,
 679                states,
 680            } => {
 681                let size = if width == 0 || height == 0 {
 682                    None
 683                } else {
 684                    Some(size(px(width as f32), px(height as f32)))
 685                };
 686
 687                let states = extract_states::<xdg_toplevel::State>(&states);
 688
 689                let mut tiling = Tiling::default();
 690                let mut fullscreen = false;
 691                let mut maximized = false;
 692                let mut resizing = false;
 693
 694                for state in states {
 695                    match state {
 696                        xdg_toplevel::State::Maximized => {
 697                            maximized = true;
 698                        }
 699                        xdg_toplevel::State::Fullscreen => {
 700                            fullscreen = true;
 701                        }
 702                        xdg_toplevel::State::Resizing => resizing = true,
 703                        xdg_toplevel::State::TiledTop => {
 704                            tiling.top = true;
 705                        }
 706                        xdg_toplevel::State::TiledLeft => {
 707                            tiling.left = true;
 708                        }
 709                        xdg_toplevel::State::TiledRight => {
 710                            tiling.right = true;
 711                        }
 712                        xdg_toplevel::State::TiledBottom => {
 713                            tiling.bottom = true;
 714                        }
 715                        _ => {
 716                            // noop
 717                        }
 718                    }
 719                }
 720
 721                if fullscreen || maximized {
 722                    tiling = Tiling::tiled();
 723                }
 724
 725                let mut state = self.state.borrow_mut();
 726                state.in_progress_configure = Some(InProgressConfigure {
 727                    size,
 728                    fullscreen,
 729                    maximized,
 730                    resizing,
 731                    tiling,
 732                });
 733
 734                false
 735            }
 736            xdg_toplevel::Event::Close => {
 737                let mut cb = self.callbacks.borrow_mut();
 738                if let Some(mut should_close) = cb.should_close.take() {
 739                    let result = (should_close)();
 740                    cb.should_close = Some(should_close);
 741                    if result {
 742                        drop(cb);
 743                        self.close();
 744                    }
 745                    result
 746                } else {
 747                    true
 748                }
 749            }
 750            xdg_toplevel::Event::WmCapabilities { capabilities } => {
 751                let mut window_controls = WindowControls::default();
 752
 753                let states = extract_states::<xdg_toplevel::WmCapabilities>(&capabilities);
 754
 755                for state in states {
 756                    match state {
 757                        xdg_toplevel::WmCapabilities::Maximize => {
 758                            window_controls.maximize = true;
 759                        }
 760                        xdg_toplevel::WmCapabilities::Minimize => {
 761                            window_controls.minimize = true;
 762                        }
 763                        xdg_toplevel::WmCapabilities::Fullscreen => {
 764                            window_controls.fullscreen = true;
 765                        }
 766                        xdg_toplevel::WmCapabilities::WindowMenu => {
 767                            window_controls.window_menu = true;
 768                        }
 769                        _ => {}
 770                    }
 771                }
 772
 773                let mut state = self.state.borrow_mut();
 774                state.in_progress_window_controls = Some(window_controls);
 775                false
 776            }
 777            _ => false,
 778        }
 779    }
 780
 781    pub fn handle_layersurface_event(&self, event: zwlr_layer_surface_v1::Event) -> bool {
 782        match event {
 783            zwlr_layer_surface_v1::Event::Configure {
 784                width,
 785                height,
 786                serial,
 787            } => {
 788                let size = if width == 0 || height == 0 {
 789                    None
 790                } else {
 791                    Some(size(px(width as f32), px(height as f32)))
 792                };
 793
 794                let mut state = self.state.borrow_mut();
 795                state.in_progress_configure = Some(InProgressConfigure {
 796                    size,
 797                    fullscreen: false,
 798                    maximized: false,
 799                    resizing: false,
 800                    tiling: Tiling::default(),
 801                });
 802                drop(state);
 803
 804                // just do the same thing we'd do as an xdg_surface
 805                self.handle_xdg_surface_event(xdg_surface::Event::Configure { serial });
 806
 807                false
 808            }
 809            zwlr_layer_surface_v1::Event::Closed => {
 810                // unlike xdg, we don't have a choice here: the surface is closing.
 811                true
 812            }
 813            _ => false,
 814        }
 815    }
 816
 817    #[allow(clippy::mutable_key_type)]
 818    pub fn handle_surface_event(
 819        &self,
 820        event: wl_surface::Event,
 821        outputs: HashMap<ObjectId, Output>,
 822    ) {
 823        let mut state = self.state.borrow_mut();
 824
 825        match event {
 826            wl_surface::Event::Enter { output } => {
 827                let id = output.id();
 828
 829                let Some(output) = outputs.get(&id) else {
 830                    return;
 831                };
 832
 833                state.outputs.insert(id, output.clone());
 834
 835                let scale = state.primary_output_scale();
 836
 837                // We use `PreferredBufferScale` instead to set the scale if it's available
 838                if state.surface.version() < wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
 839                    state.surface.set_buffer_scale(scale);
 840                    drop(state);
 841                    self.rescale(scale as f32);
 842                }
 843            }
 844            wl_surface::Event::Leave { output } => {
 845                state.outputs.remove(&output.id());
 846
 847                let scale = state.primary_output_scale();
 848
 849                // We use `PreferredBufferScale` instead to set the scale if it's available
 850                if state.surface.version() < wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
 851                    state.surface.set_buffer_scale(scale);
 852                    drop(state);
 853                    self.rescale(scale as f32);
 854                }
 855            }
 856            wl_surface::Event::PreferredBufferScale { factor } => {
 857                // We use `WpFractionalScale` instead to set the scale if it's available
 858                if state.globals.fractional_scale_manager.is_none() {
 859                    state.surface.set_buffer_scale(factor);
 860                    drop(state);
 861                    self.rescale(factor as f32);
 862                }
 863            }
 864            _ => {}
 865        }
 866    }
 867
 868    pub fn handle_ime(&self, ime: ImeInput) {
 869        if self.is_blocked() {
 870            return;
 871        }
 872        let mut state = self.state.borrow_mut();
 873        if let Some(mut input_handler) = state.input_handler.take() {
 874            drop(state);
 875            match ime {
 876                ImeInput::InsertText(text) => {
 877                    input_handler.replace_text_in_range(None, &text);
 878                }
 879                ImeInput::SetMarkedText(text) => {
 880                    input_handler.replace_and_mark_text_in_range(None, &text, None);
 881                }
 882                ImeInput::UnmarkText => {
 883                    input_handler.unmark_text();
 884                }
 885                ImeInput::DeleteText => {
 886                    if let Some(marked) = input_handler.marked_text_range() {
 887                        input_handler.replace_text_in_range(Some(marked), "");
 888                    }
 889                }
 890            }
 891            self.state.borrow_mut().input_handler = Some(input_handler);
 892        }
 893    }
 894
 895    pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
 896        let mut state = self.state.borrow_mut();
 897        let mut bounds: Option<Bounds<Pixels>> = None;
 898        if let Some(mut input_handler) = state.input_handler.take() {
 899            drop(state);
 900            if let Some(selection) = input_handler.marked_text_range() {
 901                bounds = input_handler.bounds_for_range(selection.start..selection.start);
 902            }
 903            self.state.borrow_mut().input_handler = Some(input_handler);
 904        }
 905        bounds
 906    }
 907
 908    pub fn set_size_and_scale(&self, size: Option<Size<Pixels>>, scale: Option<f32>) {
 909        let (size, scale) = {
 910            let mut state = self.state.borrow_mut();
 911            if size.is_none_or(|size| size == state.bounds.size)
 912                && scale.is_none_or(|scale| scale == state.scale)
 913            {
 914                return;
 915            }
 916            if let Some(size) = size {
 917                state.bounds.size = size;
 918            }
 919            if let Some(scale) = scale {
 920                state.scale = scale;
 921            }
 922            let device_bounds = state.bounds.to_device_pixels(state.scale);
 923            state.renderer.update_drawable_size(device_bounds.size);
 924            (state.bounds.size, state.scale)
 925        };
 926
 927        let callback = self.callbacks.borrow_mut().resize.take();
 928        if let Some(mut fun) = callback {
 929            fun(size, scale);
 930            self.callbacks.borrow_mut().resize = Some(fun);
 931        }
 932
 933        {
 934            let state = self.state.borrow();
 935            if let Some(viewport) = &state.viewport {
 936                viewport
 937                    .set_destination(f32::from(size.width) as i32, f32::from(size.height) as i32);
 938            }
 939        }
 940    }
 941
 942    pub fn resize(&self, size: Size<Pixels>) {
 943        self.set_size_and_scale(Some(size), None);
 944    }
 945
 946    pub fn rescale(&self, scale: f32) {
 947        self.set_size_and_scale(None, Some(scale));
 948    }
 949
 950    pub fn close(&self) {
 951        let state = self.state.borrow();
 952        let client = state.client.get_client();
 953        #[allow(clippy::mutable_key_type)]
 954        let children = state.children.clone();
 955        drop(state);
 956
 957        for child in children {
 958            let mut client_state = client.borrow_mut();
 959            let window = get_window(&mut client_state, &child);
 960            drop(client_state);
 961
 962            if let Some(child) = window {
 963                child.close();
 964            }
 965        }
 966        let mut callbacks = self.callbacks.borrow_mut();
 967        if let Some(fun) = callbacks.close.take() {
 968            fun()
 969        }
 970    }
 971
 972    pub fn handle_input(&self, input: PlatformInput) {
 973        if self.is_blocked() {
 974            return;
 975        }
 976        let callback = self.callbacks.borrow_mut().input.take();
 977        if let Some(mut fun) = callback {
 978            let result = fun(input.clone());
 979            self.callbacks.borrow_mut().input = Some(fun);
 980            if !result.propagate {
 981                return;
 982            }
 983        }
 984        if let PlatformInput::KeyDown(event) = input
 985            && event.keystroke.modifiers.is_subset_of(&Modifiers::shift())
 986            && let Some(key_char) = &event.keystroke.key_char
 987        {
 988            let mut state = self.state.borrow_mut();
 989            if let Some(mut input_handler) = state.input_handler.take() {
 990                drop(state);
 991                input_handler.replace_text_in_range(None, key_char);
 992                self.state.borrow_mut().input_handler = Some(input_handler);
 993            }
 994        }
 995    }
 996
 997    pub fn set_focused(&self, focus: bool) {
 998        self.state.borrow_mut().active = focus;
 999        let callback = self.callbacks.borrow_mut().active_status_change.take();
1000        if let Some(mut fun) = callback {
1001            fun(focus);
1002            self.callbacks.borrow_mut().active_status_change = Some(fun);
1003        }
1004    }
1005
1006    pub fn set_hovered(&self, focus: bool) {
1007        let callback = self.callbacks.borrow_mut().hover_status_change.take();
1008        if let Some(mut fun) = callback {
1009            fun(focus);
1010            self.callbacks.borrow_mut().hover_status_change = Some(fun);
1011        }
1012    }
1013
1014    pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1015        self.state.borrow_mut().appearance = appearance;
1016
1017        let callback = self.callbacks.borrow_mut().appearance_changed.take();
1018        if let Some(mut fun) = callback {
1019            fun();
1020            self.callbacks.borrow_mut().appearance_changed = Some(fun);
1021        }
1022    }
1023
1024    pub fn primary_output_scale(&self) -> i32 {
1025        self.state.borrow_mut().primary_output_scale()
1026    }
1027}
1028
1029fn extract_states<'a, S: TryFrom<u32> + 'a>(states: &'a [u8]) -> impl Iterator<Item = S> + 'a
1030where
1031    <S as TryFrom<u32>>::Error: 'a,
1032{
1033    states
1034        .chunks_exact(4)
1035        .flat_map(TryInto::<[u8; 4]>::try_into)
1036        .map(u32::from_ne_bytes)
1037        .flat_map(S::try_from)
1038}
1039
1040impl rwh::HasWindowHandle for WaylandWindow {
1041    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1042        let surface = self.0.surface().id().as_ptr() as *mut libc::c_void;
1043        let c_ptr = NonNull::new(surface).ok_or(rwh::HandleError::Unavailable)?;
1044        let handle = rwh::WaylandWindowHandle::new(c_ptr);
1045        let raw_handle = rwh::RawWindowHandle::Wayland(handle);
1046        Ok(unsafe { rwh::WindowHandle::borrow_raw(raw_handle) })
1047    }
1048}
1049
1050impl rwh::HasDisplayHandle for WaylandWindow {
1051    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1052        let display = self
1053            .0
1054            .surface()
1055            .backend()
1056            .upgrade()
1057            .ok_or(rwh::HandleError::Unavailable)?
1058            .display_ptr() as *mut libc::c_void;
1059
1060        let c_ptr = NonNull::new(display).ok_or(rwh::HandleError::Unavailable)?;
1061        let handle = rwh::WaylandDisplayHandle::new(c_ptr);
1062        let raw_handle = rwh::RawDisplayHandle::Wayland(handle);
1063        Ok(unsafe { rwh::DisplayHandle::borrow_raw(raw_handle) })
1064    }
1065}
1066
1067impl PlatformWindow for WaylandWindow {
1068    fn bounds(&self) -> Bounds<Pixels> {
1069        self.borrow().bounds
1070    }
1071
1072    fn is_maximized(&self) -> bool {
1073        self.borrow().maximized
1074    }
1075
1076    fn window_bounds(&self) -> WindowBounds {
1077        let state = self.borrow();
1078        if state.fullscreen {
1079            WindowBounds::Fullscreen(state.window_bounds)
1080        } else if state.maximized {
1081            WindowBounds::Maximized(state.window_bounds)
1082        } else {
1083            drop(state);
1084            WindowBounds::Windowed(self.bounds())
1085        }
1086    }
1087
1088    fn inner_window_bounds(&self) -> WindowBounds {
1089        let state = self.borrow();
1090        if state.fullscreen {
1091            WindowBounds::Fullscreen(state.window_bounds)
1092        } else if state.maximized {
1093            WindowBounds::Maximized(state.window_bounds)
1094        } else {
1095            let inset = state.inset();
1096            drop(state);
1097            WindowBounds::Windowed(self.bounds().inset(inset))
1098        }
1099    }
1100
1101    fn content_size(&self) -> Size<Pixels> {
1102        self.borrow().bounds.size
1103    }
1104
1105    fn resize(&mut self, size: Size<Pixels>) {
1106        let state = self.borrow();
1107        let state_ptr = self.0.clone();
1108
1109        // Keep window geometry consistent with configure handling. On Wayland, window geometry is
1110        // surface-local: resizing should not attempt to translate the window; the compositor
1111        // controls placement. We also account for client-side decoration insets and tiling.
1112        let window_geometry = inset_by_tiling(
1113            Bounds {
1114                origin: Point::default(),
1115                size,
1116            },
1117            state.inset(),
1118            state.tiling,
1119        )
1120        .map(|v| f32::from(v) as i32)
1121        .map_size(|v| if v <= 0 { 1 } else { v });
1122
1123        state.surface_state.set_geometry(
1124            window_geometry.origin.x,
1125            window_geometry.origin.y,
1126            window_geometry.size.width,
1127            window_geometry.size.height,
1128        );
1129
1130        state
1131            .globals
1132            .executor
1133            .spawn(async move { state_ptr.resize(size) })
1134            .detach();
1135    }
1136
1137    fn scale_factor(&self) -> f32 {
1138        self.borrow().scale
1139    }
1140
1141    fn appearance(&self) -> WindowAppearance {
1142        self.borrow().appearance
1143    }
1144
1145    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1146        let state = self.borrow();
1147        state.display.as_ref().map(|(id, display)| {
1148            Rc::new(WaylandDisplay {
1149                id: id.clone(),
1150                name: display.name.clone(),
1151                bounds: display.bounds.to_pixels(state.scale),
1152            }) as Rc<dyn PlatformDisplay>
1153        })
1154    }
1155
1156    fn mouse_position(&self) -> Point<Pixels> {
1157        self.borrow()
1158            .client
1159            .get_client()
1160            .borrow()
1161            .mouse_location
1162            .unwrap_or_default()
1163    }
1164
1165    fn modifiers(&self) -> Modifiers {
1166        self.borrow().client.get_client().borrow().modifiers
1167    }
1168
1169    fn capslock(&self) -> Capslock {
1170        self.borrow().client.get_client().borrow().capslock
1171    }
1172
1173    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1174        self.borrow_mut().input_handler = Some(input_handler);
1175    }
1176
1177    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1178        self.borrow_mut().input_handler.take()
1179    }
1180
1181    fn prompt(
1182        &self,
1183        _level: PromptLevel,
1184        _msg: &str,
1185        _detail: Option<&str>,
1186        _answers: &[PromptButton],
1187    ) -> Option<Receiver<usize>> {
1188        None
1189    }
1190
1191    fn activate(&self) {
1192        // Try to request an activation token. Even though the activation is likely going to be rejected,
1193        // KWin and Mutter can use the app_id to visually indicate we're requesting attention.
1194        let state = self.borrow();
1195        if let (Some(activation), Some(app_id)) = (&state.globals.activation, state.app_id.clone())
1196        {
1197            state.client.set_pending_activation(state.surface.id());
1198            let token = activation.get_activation_token(&state.globals.qh, ());
1199            // The serial isn't exactly important here, since the activation is probably going to be rejected anyway.
1200            let serial = state.client.get_serial(SerialKind::MousePress);
1201            token.set_app_id(app_id);
1202            token.set_serial(serial, &state.globals.seat);
1203            token.set_surface(&state.surface);
1204            token.commit();
1205        }
1206    }
1207
1208    fn is_active(&self) -> bool {
1209        self.borrow().active
1210    }
1211
1212    fn is_hovered(&self) -> bool {
1213        self.borrow().hovered
1214    }
1215
1216    fn set_title(&mut self, title: &str) {
1217        if let Some(toplevel) = self.borrow().surface_state.toplevel() {
1218            toplevel.set_title(title.to_string());
1219        }
1220    }
1221
1222    fn set_app_id(&mut self, app_id: &str) {
1223        let mut state = self.borrow_mut();
1224        if let Some(toplevel) = state.surface_state.toplevel() {
1225            toplevel.set_app_id(app_id.to_owned());
1226        }
1227        state.app_id = Some(app_id.to_owned());
1228    }
1229
1230    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1231        let mut state = self.borrow_mut();
1232        state.background_appearance = background_appearance;
1233        update_window(state);
1234    }
1235
1236    fn background_appearance(&self) -> WindowBackgroundAppearance {
1237        self.borrow().background_appearance
1238    }
1239
1240    fn is_subpixel_rendering_supported(&self) -> bool {
1241        let client = self.borrow().client.get_client();
1242        let state = client.borrow();
1243        state
1244            .gpu_context
1245            .as_ref()
1246            .is_some_and(|ctx| ctx.supports_dual_source_blending())
1247    }
1248
1249    fn minimize(&self) {
1250        if let Some(toplevel) = self.borrow().surface_state.toplevel() {
1251            toplevel.set_minimized();
1252        }
1253    }
1254
1255    fn zoom(&self) {
1256        let state = self.borrow();
1257        if let Some(toplevel) = state.surface_state.toplevel() {
1258            if !state.maximized {
1259                toplevel.set_maximized();
1260            } else {
1261                toplevel.unset_maximized();
1262            }
1263        }
1264    }
1265
1266    fn toggle_fullscreen(&self) {
1267        let state = self.borrow();
1268        if let Some(toplevel) = state.surface_state.toplevel() {
1269            if !state.fullscreen {
1270                toplevel.set_fullscreen(None);
1271            } else {
1272                toplevel.unset_fullscreen();
1273            }
1274        }
1275    }
1276
1277    fn is_fullscreen(&self) -> bool {
1278        self.borrow().fullscreen
1279    }
1280
1281    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1282        self.0.callbacks.borrow_mut().request_frame = Some(callback);
1283    }
1284
1285    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>) {
1286        self.0.callbacks.borrow_mut().input = Some(callback);
1287    }
1288
1289    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1290        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1291    }
1292
1293    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1294        self.0.callbacks.borrow_mut().hover_status_change = Some(callback);
1295    }
1296
1297    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1298        self.0.callbacks.borrow_mut().resize = Some(callback);
1299    }
1300
1301    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1302        self.0.callbacks.borrow_mut().moved = Some(callback);
1303    }
1304
1305    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1306        self.0.callbacks.borrow_mut().should_close = Some(callback);
1307    }
1308
1309    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1310        self.0.callbacks.borrow_mut().close = Some(callback);
1311    }
1312
1313    fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1314    }
1315
1316    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1317        self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1318    }
1319
1320    fn draw(&self, scene: &Scene) {
1321        let mut state = self.borrow_mut();
1322        state.renderer.draw(scene);
1323    }
1324
1325    fn completed_frame(&self) {
1326        let state = self.borrow();
1327        state.surface.commit();
1328    }
1329
1330    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1331        let state = self.borrow();
1332        state.renderer.sprite_atlas().clone()
1333    }
1334
1335    fn show_window_menu(&self, position: Point<Pixels>) {
1336        let state = self.borrow();
1337        let serial = state.client.get_serial(SerialKind::MousePress);
1338        if let Some(toplevel) = state.surface_state.toplevel() {
1339            toplevel.show_window_menu(
1340                &state.globals.seat,
1341                serial,
1342                f32::from(position.x) as i32,
1343                f32::from(position.y) as i32,
1344            );
1345        }
1346    }
1347
1348    fn start_window_move(&self) {
1349        let state = self.borrow();
1350        let serial = state.client.get_serial(SerialKind::MousePress);
1351        if let Some(toplevel) = state.surface_state.toplevel() {
1352            toplevel._move(&state.globals.seat, serial);
1353        }
1354    }
1355
1356    fn start_window_resize(&self, edge: gpui::ResizeEdge) {
1357        let state = self.borrow();
1358        if let Some(toplevel) = state.surface_state.toplevel() {
1359            toplevel.resize(
1360                &state.globals.seat,
1361                state.client.get_serial(SerialKind::MousePress),
1362                edge.to_xdg(),
1363            )
1364        }
1365    }
1366
1367    fn window_decorations(&self) -> Decorations {
1368        let state = self.borrow();
1369        match state.decorations {
1370            WindowDecorations::Server => Decorations::Server,
1371            WindowDecorations::Client => Decorations::Client {
1372                tiling: state.tiling,
1373            },
1374        }
1375    }
1376
1377    fn request_decorations(&self, decorations: WindowDecorations) {
1378        let mut state = self.borrow_mut();
1379        match state.surface_state.decoration().as_ref() {
1380            Some(decoration) => {
1381                decoration.set_mode(decorations.to_xdg());
1382                state.decorations = decorations;
1383                update_window(state);
1384            }
1385            None => {
1386                if matches!(decorations, WindowDecorations::Server) {
1387                    log::info!(
1388                        "Server-side decorations requested, but the Wayland server does not support them. Falling back to client-side decorations."
1389                    );
1390                }
1391                state.decorations = WindowDecorations::Client;
1392                update_window(state);
1393            }
1394        }
1395    }
1396
1397    fn window_controls(&self) -> WindowControls {
1398        self.borrow().window_controls
1399    }
1400
1401    fn set_client_inset(&self, inset: Pixels) {
1402        let mut state = self.borrow_mut();
1403        if Some(inset) != state.client_inset {
1404            state.client_inset = Some(inset);
1405            update_window(state);
1406        }
1407    }
1408
1409    fn update_ime_position(&self, bounds: Bounds<Pixels>) {
1410        let state = self.borrow();
1411        state.client.update_ime_position(bounds);
1412    }
1413
1414    fn gpu_specs(&self) -> Option<GpuSpecs> {
1415        self.borrow().renderer.gpu_specs().into()
1416    }
1417}
1418
1419fn update_window(mut state: RefMut<WaylandWindowState>) {
1420    let opaque = !state.is_transparent();
1421
1422    state.renderer.update_transparency(!opaque);
1423    let opaque_area = state.window_bounds.map(|v| f32::from(v) as i32);
1424    opaque_area.inset(f32::from(state.inset()) as i32);
1425
1426    let region = state
1427        .globals
1428        .compositor
1429        .create_region(&state.globals.qh, ());
1430    region.add(
1431        opaque_area.origin.x,
1432        opaque_area.origin.y,
1433        opaque_area.size.width,
1434        opaque_area.size.height,
1435    );
1436
1437    // Note that rounded corners make this rectangle API hard to work with.
1438    // As this is common when using CSD, let's just disable this API.
1439    if state.background_appearance == WindowBackgroundAppearance::Opaque
1440        && state.decorations == WindowDecorations::Server
1441    {
1442        // Promise the compositor that this region of the window surface
1443        // contains no transparent pixels. This allows the compositor to skip
1444        // updating whatever is behind the surface for better performance.
1445        state.surface.set_opaque_region(Some(&region));
1446    } else {
1447        state.surface.set_opaque_region(None);
1448    }
1449
1450    if let Some(ref blur_manager) = state.globals.blur_manager {
1451        if state.background_appearance == WindowBackgroundAppearance::Blurred {
1452            if state.blur.is_none() {
1453                let blur = blur_manager.create(&state.surface, &state.globals.qh, ());
1454                state.blur = Some(blur);
1455            }
1456            state.blur.as_ref().unwrap().commit();
1457        } else {
1458            // It probably doesn't hurt to clear the blur for opaque windows
1459            blur_manager.unset(&state.surface);
1460            if let Some(b) = state.blur.take() {
1461                b.release()
1462            }
1463        }
1464    }
1465
1466    region.destroy();
1467}
1468
1469pub(crate) trait WindowDecorationsExt {
1470    fn to_xdg(self) -> zxdg_toplevel_decoration_v1::Mode;
1471}
1472
1473impl WindowDecorationsExt for WindowDecorations {
1474    fn to_xdg(self) -> zxdg_toplevel_decoration_v1::Mode {
1475        match self {
1476            WindowDecorations::Client => zxdg_toplevel_decoration_v1::Mode::ClientSide,
1477            WindowDecorations::Server => zxdg_toplevel_decoration_v1::Mode::ServerSide,
1478        }
1479    }
1480}
1481
1482pub(crate) trait ResizeEdgeWaylandExt {
1483    fn to_xdg(self) -> xdg_toplevel::ResizeEdge;
1484}
1485
1486impl ResizeEdgeWaylandExt for ResizeEdge {
1487    fn to_xdg(self) -> xdg_toplevel::ResizeEdge {
1488        match self {
1489            ResizeEdge::Top => xdg_toplevel::ResizeEdge::Top,
1490            ResizeEdge::TopRight => xdg_toplevel::ResizeEdge::TopRight,
1491            ResizeEdge::Right => xdg_toplevel::ResizeEdge::Right,
1492            ResizeEdge::BottomRight => xdg_toplevel::ResizeEdge::BottomRight,
1493            ResizeEdge::Bottom => xdg_toplevel::ResizeEdge::Bottom,
1494            ResizeEdge::BottomLeft => xdg_toplevel::ResizeEdge::BottomLeft,
1495            ResizeEdge::Left => xdg_toplevel::ResizeEdge::Left,
1496            ResizeEdge::TopLeft => xdg_toplevel::ResizeEdge::TopLeft,
1497        }
1498    }
1499}
1500
1501/// The configuration event is in terms of the window geometry, which we are constantly
1502/// updating to account for the client decorations. But that's not the area we want to render
1503/// to, due to our intrusize CSD. So, here we calculate the 'actual' size, by adding back in the insets
1504fn compute_outer_size(
1505    inset: Pixels,
1506    new_size: Option<Size<Pixels>>,
1507    tiling: Tiling,
1508) -> Option<Size<Pixels>> {
1509    new_size.map(|mut new_size| {
1510        if !tiling.top {
1511            new_size.height += inset;
1512        }
1513        if !tiling.bottom {
1514            new_size.height += inset;
1515        }
1516        if !tiling.left {
1517            new_size.width += inset;
1518        }
1519        if !tiling.right {
1520            new_size.width += inset;
1521        }
1522
1523        new_size
1524    })
1525}
1526
1527fn inset_by_tiling(mut bounds: Bounds<Pixels>, inset: Pixels, tiling: Tiling) -> Bounds<Pixels> {
1528    if !tiling.top {
1529        bounds.origin.y += inset;
1530        bounds.size.height -= inset;
1531    }
1532    if !tiling.bottom {
1533        bounds.size.height -= inset;
1534    }
1535    if !tiling.left {
1536        bounds.origin.x += inset;
1537        bounds.size.width -= inset;
1538    }
1539    if !tiling.right {
1540        bounds.size.width -= inset;
1541    }
1542
1543    bounds
1544}