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