window.rs

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