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