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