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