window.rs

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