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