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, Globals, Modifiers, Output, Pixels,
  29    PlatformDisplay, PlatformInput, Point, PromptLevel, ResizeEdge, Size, Tiling,
  30    WaylandClientStatePtr, WindowAppearance, WindowBackgroundAppearance, WindowBounds,
  31    WindowControls, WindowDecorations, WindowParams,
  32};
  33
  34#[derive(Default)]
  35pub(crate) struct Callbacks {
  36    request_frame: Option<Box<dyn FnMut()>>,
  37    input: Option<Box<dyn FnMut(crate::PlatformInput) -> crate::DispatchEventResult>>,
  38    active_status_change: Option<Box<dyn FnMut(bool)>>,
  39    resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
  40    moved: Option<Box<dyn FnMut()>>,
  41    should_close: Option<Box<dyn FnMut() -> bool>>,
  42    close: Option<Box<dyn FnOnce()>>,
  43    appearance_changed: Option<Box<dyn FnMut()>>,
  44}
  45
  46struct RawWindow {
  47    window: *mut c_void,
  48    display: *mut c_void,
  49}
  50
  51impl rwh::HasWindowHandle for RawWindow {
  52    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
  53        let window = NonNull::new(self.window).unwrap();
  54        let handle = rwh::WaylandWindowHandle::new(window);
  55        Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
  56    }
  57}
  58impl rwh::HasDisplayHandle for RawWindow {
  59    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
  60        let display = NonNull::new(self.display).unwrap();
  61        let handle = rwh::WaylandDisplayHandle::new(display);
  62        Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
  63    }
  64}
  65
  66#[derive(Debug)]
  67struct InProgressConfigure {
  68    size: Option<Size<Pixels>>,
  69    fullscreen: bool,
  70    maximized: bool,
  71    tiling: Tiling,
  72}
  73
  74pub struct WaylandWindowState {
  75    xdg_surface: xdg_surface::XdgSurface,
  76    acknowledged_first_configure: bool,
  77    pub surface: wl_surface::WlSurface,
  78    decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
  79    app_id: Option<String>,
  80    appearance: WindowAppearance,
  81    blur: Option<org_kde_kwin_blur::OrgKdeKwinBlur>,
  82    toplevel: xdg_toplevel::XdgToplevel,
  83    viewport: Option<wp_viewport::WpViewport>,
  84    outputs: HashMap<ObjectId, Output>,
  85    display: Option<(ObjectId, Output)>,
  86    globals: Globals,
  87    renderer: BladeRenderer,
  88    bounds: Bounds<Pixels>,
  89    scale: f32,
  90    input_handler: Option<PlatformInputHandler>,
  91    decorations: WindowDecorations,
  92    background_appearance: WindowBackgroundAppearance,
  93    fullscreen: bool,
  94    maximized: bool,
  95    tiling: Tiling,
  96    window_bounds: Bounds<Pixels>,
  97    client: WaylandClientStatePtr,
  98    handle: AnyWindowHandle,
  99    active: bool,
 100    in_progress_configure: Option<InProgressConfigure>,
 101    in_progress_window_controls: Option<WindowControls>,
 102    window_controls: WindowControls,
 103    inset: Option<Pixels>,
 104}
 105
 106#[derive(Clone)]
 107pub struct WaylandWindowStatePtr {
 108    state: Rc<RefCell<WaylandWindowState>>,
 109    callbacks: Rc<RefCell<Callbacks>>,
 110}
 111
 112impl WaylandWindowState {
 113    #[allow(clippy::too_many_arguments)]
 114    pub(crate) fn new(
 115        handle: AnyWindowHandle,
 116        surface: wl_surface::WlSurface,
 117        xdg_surface: xdg_surface::XdgSurface,
 118        toplevel: xdg_toplevel::XdgToplevel,
 119        decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
 120        appearance: WindowAppearance,
 121        viewport: Option<wp_viewport::WpViewport>,
 122        client: WaylandClientStatePtr,
 123        globals: Globals,
 124        options: WindowParams,
 125    ) -> anyhow::Result<Self> {
 126        let raw = RawWindow {
 127            window: surface.id().as_ptr().cast::<c_void>(),
 128            display: surface
 129                .backend()
 130                .upgrade()
 131                .unwrap()
 132                .display_ptr()
 133                .cast::<c_void>(),
 134        };
 135        let gpu = Arc::new(
 136            unsafe {
 137                gpu::Context::init_windowed(
 138                    &raw,
 139                    gpu::ContextDesc {
 140                        validation: false,
 141                        capture: false,
 142                        overlay: false,
 143                    },
 144                )
 145            }
 146            .map_err(|e| anyhow::anyhow!("{:?}", e))?,
 147        );
 148        let config = BladeSurfaceConfig {
 149            size: gpu::Extent {
 150                width: options.bounds.size.width.0 as u32,
 151                height: options.bounds.size.height.0 as u32,
 152                depth: 1,
 153            },
 154            transparent: true,
 155        };
 156
 157        Ok(Self {
 158            xdg_surface,
 159            acknowledged_first_configure: false,
 160            surface,
 161            decoration,
 162            app_id: None,
 163            blur: None,
 164            toplevel,
 165            viewport,
 166            globals,
 167            outputs: HashMap::default(),
 168            display: None,
 169            renderer: BladeRenderer::new(gpu, config),
 170            bounds: options.bounds,
 171            scale: 1.0,
 172            input_handler: None,
 173            decorations: WindowDecorations::Client,
 174            background_appearance: WindowBackgroundAppearance::Opaque,
 175            fullscreen: false,
 176            maximized: false,
 177            tiling: Tiling::default(),
 178            window_bounds: options.bounds,
 179            in_progress_configure: None,
 180            client,
 181            appearance,
 182            handle,
 183            active: false,
 184            in_progress_window_controls: None,
 185            // Assume that we can do anything, unless told otherwise
 186            window_controls: WindowControls {
 187                fullscreen: true,
 188                maximize: true,
 189                minimize: true,
 190                window_menu: true,
 191            },
 192            inset: None,
 193        })
 194    }
 195
 196    pub fn is_transparent(&self) -> bool {
 197        self.decorations == WindowDecorations::Client
 198            || self.background_appearance != WindowBackgroundAppearance::Opaque
 199    }
 200}
 201
 202pub(crate) struct WaylandWindow(pub WaylandWindowStatePtr);
 203pub enum ImeInput {
 204    InsertText(String),
 205    SetMarkedText(String),
 206    UnmarkText,
 207    DeleteText,
 208}
 209
 210impl Drop for WaylandWindow {
 211    fn drop(&mut self) {
 212        let mut state = self.0.state.borrow_mut();
 213        let surface_id = state.surface.id();
 214        let client = state.client.clone();
 215
 216        state.renderer.destroy();
 217        if let Some(decoration) = &state.decoration {
 218            decoration.destroy();
 219        }
 220        if let Some(blur) = &state.blur {
 221            blur.release();
 222        }
 223        state.toplevel.destroy();
 224        if let Some(viewport) = &state.viewport {
 225            viewport.destroy();
 226        }
 227        state.xdg_surface.destroy();
 228        state.surface.destroy();
 229
 230        let state_ptr = self.0.clone();
 231        state
 232            .globals
 233            .executor
 234            .spawn(async move {
 235                state_ptr.close();
 236                client.drop_window(&surface_id)
 237            })
 238            .detach();
 239        drop(state);
 240    }
 241}
 242
 243impl WaylandWindow {
 244    fn borrow(&self) -> Ref<WaylandWindowState> {
 245        self.0.state.borrow()
 246    }
 247
 248    fn borrow_mut(&self) -> RefMut<WaylandWindowState> {
 249        self.0.state.borrow_mut()
 250    }
 251
 252    pub fn new(
 253        handle: AnyWindowHandle,
 254        globals: Globals,
 255        client: WaylandClientStatePtr,
 256        params: WindowParams,
 257        appearance: WindowAppearance,
 258    ) -> anyhow::Result<(Self, ObjectId)> {
 259        let surface = globals.compositor.create_surface(&globals.qh, ());
 260        let xdg_surface = globals
 261            .wm_base
 262            .get_xdg_surface(&surface, &globals.qh, surface.id());
 263        let toplevel = xdg_surface.get_toplevel(&globals.qh, surface.id());
 264        toplevel.set_min_size(50, 50);
 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();
 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    pub fn handle_surface_event(
 546        &self,
 547        event: wl_surface::Event,
 548        outputs: HashMap<ObjectId, Output>,
 549    ) {
 550        let mut state = self.state.borrow_mut();
 551
 552        match event {
 553            wl_surface::Event::Enter { output } => {
 554                let id = output.id();
 555
 556                let Some(output) = outputs.get(&id) else {
 557                    return;
 558                };
 559
 560                state.outputs.insert(id, output.clone());
 561
 562                let scale = primary_output_scale(&mut state);
 563
 564                // We use `PreferredBufferScale` instead to set the scale if it's available
 565                if state.surface.version() < wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
 566                    state.surface.set_buffer_scale(scale);
 567                    drop(state);
 568                    self.rescale(scale as f32);
 569                }
 570            }
 571            wl_surface::Event::Leave { output } => {
 572                state.outputs.remove(&output.id());
 573
 574                let scale = primary_output_scale(&mut state);
 575
 576                // We use `PreferredBufferScale` instead to set the scale if it's available
 577                if state.surface.version() < wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
 578                    state.surface.set_buffer_scale(scale);
 579                    drop(state);
 580                    self.rescale(scale as f32);
 581                }
 582            }
 583            wl_surface::Event::PreferredBufferScale { factor } => {
 584                // We use `WpFractionalScale` instead to set the scale if it's available
 585                if state.globals.fractional_scale_manager.is_none() {
 586                    state.surface.set_buffer_scale(factor);
 587                    drop(state);
 588                    self.rescale(factor as f32);
 589                }
 590            }
 591            _ => {}
 592        }
 593    }
 594
 595    pub fn handle_ime(&self, ime: ImeInput) {
 596        let mut state = self.state.borrow_mut();
 597        if let Some(mut input_handler) = state.input_handler.take() {
 598            drop(state);
 599            match ime {
 600                ImeInput::InsertText(text) => {
 601                    input_handler.replace_text_in_range(None, &text);
 602                }
 603                ImeInput::SetMarkedText(text) => {
 604                    input_handler.replace_and_mark_text_in_range(None, &text, None);
 605                }
 606                ImeInput::UnmarkText => {
 607                    input_handler.unmark_text();
 608                }
 609                ImeInput::DeleteText => {
 610                    if let Some(marked) = input_handler.marked_text_range() {
 611                        input_handler.replace_text_in_range(Some(marked), "");
 612                    }
 613                }
 614            }
 615            self.state.borrow_mut().input_handler = Some(input_handler);
 616        }
 617    }
 618
 619    pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
 620        let mut state = self.state.borrow_mut();
 621        let mut bounds: Option<Bounds<Pixels>> = None;
 622        if let Some(mut input_handler) = state.input_handler.take() {
 623            drop(state);
 624            if let Some(range) = input_handler.selected_text_range() {
 625                bounds = input_handler.bounds_for_range(range);
 626            }
 627            self.state.borrow_mut().input_handler = Some(input_handler);
 628        }
 629        bounds
 630    }
 631
 632    pub fn set_size_and_scale(&self, size: Option<Size<Pixels>>, scale: Option<f32>) {
 633        let (size, scale) = {
 634            let mut state = self.state.borrow_mut();
 635            if size.map_or(true, |size| size == state.bounds.size)
 636                && scale.map_or(true, |scale| scale == state.scale)
 637            {
 638                return;
 639            }
 640            if let Some(size) = size {
 641                state.bounds.size = size;
 642            }
 643            if let Some(scale) = scale {
 644                state.scale = scale;
 645            }
 646            let device_bounds = state.bounds.to_device_pixels(state.scale);
 647            state.renderer.update_drawable_size(device_bounds.size);
 648            (state.bounds.size, state.scale)
 649        };
 650
 651        if let Some(ref mut fun) = self.callbacks.borrow_mut().resize {
 652            fun(size, scale);
 653        }
 654
 655        {
 656            let state = self.state.borrow();
 657            if let Some(viewport) = &state.viewport {
 658                viewport.set_destination(size.width.0 as i32, size.height.0 as i32);
 659            }
 660        }
 661    }
 662
 663    pub fn resize(&self, size: Size<Pixels>) {
 664        self.set_size_and_scale(Some(size), None);
 665    }
 666
 667    pub fn rescale(&self, scale: f32) {
 668        self.set_size_and_scale(None, Some(scale));
 669    }
 670
 671    pub fn close(&self) {
 672        let mut callbacks = self.callbacks.borrow_mut();
 673        if let Some(fun) = callbacks.close.take() {
 674            fun()
 675        }
 676    }
 677
 678    pub fn handle_input(&self, input: PlatformInput) {
 679        if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
 680            if !fun(input.clone()).propagate {
 681                return;
 682            }
 683        }
 684        if let PlatformInput::KeyDown(event) = input {
 685            if let Some(ime_key) = &event.keystroke.ime_key {
 686                let mut state = self.state.borrow_mut();
 687                if let Some(mut input_handler) = state.input_handler.take() {
 688                    drop(state);
 689                    input_handler.replace_text_in_range(None, ime_key);
 690                    self.state.borrow_mut().input_handler = Some(input_handler);
 691                }
 692            }
 693        }
 694    }
 695
 696    pub fn set_focused(&self, focus: bool) {
 697        self.state.borrow_mut().active = focus;
 698        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
 699            fun(focus);
 700        }
 701    }
 702
 703    pub fn set_appearance(&mut self, appearance: WindowAppearance) {
 704        self.state.borrow_mut().appearance = appearance;
 705
 706        let mut callbacks = self.callbacks.borrow_mut();
 707        if let Some(ref mut fun) = callbacks.appearance_changed {
 708            (fun)()
 709        }
 710    }
 711}
 712
 713fn extract_states<'a, S: TryFrom<u32> + 'a>(states: &'a [u8]) -> impl Iterator<Item = S> + 'a
 714where
 715    <S as TryFrom<u32>>::Error: 'a,
 716{
 717    states
 718        .chunks_exact(4)
 719        .flat_map(TryInto::<[u8; 4]>::try_into)
 720        .map(u32::from_ne_bytes)
 721        .flat_map(S::try_from)
 722}
 723
 724fn primary_output_scale(state: &mut RefMut<WaylandWindowState>) -> i32 {
 725    let mut scale = 1;
 726    let mut current_output = state.display.take();
 727    for (id, output) in state.outputs.iter() {
 728        if let Some((_, output_data)) = &current_output {
 729            if output.scale > output_data.scale {
 730                current_output = Some((id.clone(), output.clone()));
 731            }
 732        } else {
 733            current_output = Some((id.clone(), output.clone()));
 734        }
 735        scale = scale.max(output.scale);
 736    }
 737    state.display = current_output;
 738    scale
 739}
 740
 741impl rwh::HasWindowHandle for WaylandWindow {
 742    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 743        unimplemented!()
 744    }
 745}
 746impl rwh::HasDisplayHandle for WaylandWindow {
 747    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 748        unimplemented!()
 749    }
 750}
 751
 752impl PlatformWindow for WaylandWindow {
 753    fn bounds(&self) -> Bounds<Pixels> {
 754        self.borrow().bounds
 755    }
 756
 757    fn is_maximized(&self) -> bool {
 758        self.borrow().maximized
 759    }
 760
 761    fn window_bounds(&self) -> WindowBounds {
 762        let state = self.borrow();
 763        if state.fullscreen {
 764            WindowBounds::Fullscreen(state.window_bounds)
 765        } else if state.maximized {
 766            WindowBounds::Maximized(state.window_bounds)
 767        } else {
 768            drop(state);
 769            WindowBounds::Windowed(self.bounds())
 770        }
 771    }
 772
 773    fn content_size(&self) -> Size<Pixels> {
 774        self.borrow().bounds.size
 775    }
 776
 777    fn scale_factor(&self) -> f32 {
 778        self.borrow().scale
 779    }
 780
 781    fn appearance(&self) -> WindowAppearance {
 782        self.borrow().appearance
 783    }
 784
 785    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 786        let state = self.borrow();
 787        state.display.as_ref().map(|(id, display)| {
 788            Rc::new(WaylandDisplay {
 789                id: id.clone(),
 790                name: display.name.clone(),
 791                bounds: display.bounds.to_pixels(state.scale),
 792            }) as Rc<dyn PlatformDisplay>
 793        })
 794    }
 795
 796    fn mouse_position(&self) -> Point<Pixels> {
 797        self.borrow()
 798            .client
 799            .get_client()
 800            .borrow()
 801            .mouse_location
 802            .unwrap_or_default()
 803    }
 804
 805    fn modifiers(&self) -> Modifiers {
 806        self.borrow().client.get_client().borrow().modifiers
 807    }
 808
 809    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 810        self.borrow_mut().input_handler = Some(input_handler);
 811    }
 812
 813    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 814        self.borrow_mut().input_handler.take()
 815    }
 816
 817    fn prompt(
 818        &self,
 819        _level: PromptLevel,
 820        _msg: &str,
 821        _detail: Option<&str>,
 822        _answers: &[&str],
 823    ) -> Option<Receiver<usize>> {
 824        None
 825    }
 826
 827    fn activate(&self) {
 828        // Try to request an activation token. Even though the activation is likely going to be rejected,
 829        // KWin and Mutter can use the app_id to visually indicate we're requesting attention.
 830        let state = self.borrow();
 831        if let (Some(activation), Some(app_id)) = (&state.globals.activation, state.app_id.clone())
 832        {
 833            state.client.set_pending_activation(state.surface.id());
 834            let token = activation.get_activation_token(&state.globals.qh, ());
 835            // The serial isn't exactly important here, since the activation is probably going to be rejected anyway.
 836            let serial = state.client.get_serial(SerialKind::MousePress);
 837            token.set_app_id(app_id);
 838            token.set_serial(serial, &state.globals.seat);
 839            token.set_surface(&state.surface);
 840            token.commit();
 841        }
 842    }
 843
 844    fn is_active(&self) -> bool {
 845        self.borrow().active
 846    }
 847
 848    fn set_title(&mut self, title: &str) {
 849        self.borrow().toplevel.set_title(title.to_string());
 850    }
 851
 852    fn set_app_id(&mut self, app_id: &str) {
 853        let mut state = self.borrow_mut();
 854        state.toplevel.set_app_id(app_id.to_owned());
 855        state.app_id = Some(app_id.to_owned());
 856    }
 857
 858    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
 859        let mut state = self.borrow_mut();
 860        state.background_appearance = background_appearance;
 861        update_window(state);
 862    }
 863
 864    fn minimize(&self) {
 865        self.borrow().toplevel.set_minimized();
 866    }
 867
 868    fn zoom(&self) {
 869        let state = self.borrow();
 870        if !state.maximized {
 871            state.toplevel.set_maximized();
 872        } else {
 873            state.toplevel.unset_maximized();
 874        }
 875    }
 876
 877    fn toggle_fullscreen(&self) {
 878        let mut state = self.borrow_mut();
 879        if !state.fullscreen {
 880            state.toplevel.set_fullscreen(None);
 881        } else {
 882            state.toplevel.unset_fullscreen();
 883        }
 884    }
 885
 886    fn is_fullscreen(&self) -> bool {
 887        self.borrow().fullscreen
 888    }
 889
 890    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
 891        self.0.callbacks.borrow_mut().request_frame = Some(callback);
 892    }
 893
 894    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
 895        self.0.callbacks.borrow_mut().input = Some(callback);
 896    }
 897
 898    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 899        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
 900    }
 901
 902    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 903        self.0.callbacks.borrow_mut().resize = Some(callback);
 904    }
 905
 906    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 907        self.0.callbacks.borrow_mut().moved = Some(callback);
 908    }
 909
 910    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 911        self.0.callbacks.borrow_mut().should_close = Some(callback);
 912    }
 913
 914    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 915        self.0.callbacks.borrow_mut().close = Some(callback);
 916    }
 917
 918    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 919        self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
 920    }
 921
 922    fn draw(&self, scene: &Scene) {
 923        let mut state = self.borrow_mut();
 924        state.renderer.draw(scene);
 925    }
 926
 927    fn completed_frame(&self) {
 928        let state = self.borrow();
 929        state.surface.commit();
 930    }
 931
 932    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 933        let state = self.borrow();
 934        state.renderer.sprite_atlas().clone()
 935    }
 936
 937    fn show_window_menu(&self, position: Point<Pixels>) {
 938        let state = self.borrow();
 939        let serial = state.client.get_serial(SerialKind::MousePress);
 940        state.toplevel.show_window_menu(
 941            &state.globals.seat,
 942            serial,
 943            position.x.0 as i32,
 944            position.y.0 as i32,
 945        );
 946    }
 947
 948    fn start_window_move(&self) {
 949        let state = self.borrow();
 950        let serial = state.client.get_serial(SerialKind::MousePress);
 951        state.toplevel._move(&state.globals.seat, serial);
 952    }
 953
 954    fn start_window_resize(&self, edge: crate::ResizeEdge) {
 955        let state = self.borrow();
 956        state.toplevel.resize(
 957            &state.globals.seat,
 958            state.client.get_serial(SerialKind::MousePress),
 959            edge.to_xdg(),
 960        )
 961    }
 962
 963    fn window_decorations(&self) -> Decorations {
 964        let state = self.borrow();
 965        match state.decorations {
 966            WindowDecorations::Server => Decorations::Server,
 967            WindowDecorations::Client => Decorations::Client {
 968                tiling: state.tiling,
 969            },
 970        }
 971    }
 972
 973    fn request_decorations(&self, decorations: WindowDecorations) {
 974        let mut state = self.borrow_mut();
 975        state.decorations = decorations;
 976        if let Some(decoration) = state.decoration.as_ref() {
 977            decoration.set_mode(decorations.to_xdg());
 978            update_window(state);
 979        }
 980    }
 981
 982    fn window_controls(&self) -> WindowControls {
 983        self.borrow().window_controls
 984    }
 985
 986    fn set_client_inset(&self, inset: Pixels) {
 987        let mut state = self.borrow_mut();
 988        if Some(inset) != state.inset {
 989            state.inset = Some(inset);
 990            update_window(state);
 991        }
 992    }
 993}
 994
 995fn update_window(mut state: RefMut<WaylandWindowState>) {
 996    let opaque = !state.is_transparent();
 997
 998    state.renderer.update_transparency(!opaque);
 999    let mut opaque_area = state.window_bounds.map(|v| v.0 as i32);
1000    if let Some(inset) = state.inset {
1001        opaque_area.inset(inset.0 as i32);
1002    }
1003
1004    let region = state
1005        .globals
1006        .compositor
1007        .create_region(&state.globals.qh, ());
1008    region.add(
1009        opaque_area.origin.x,
1010        opaque_area.origin.y,
1011        opaque_area.size.width,
1012        opaque_area.size.height,
1013    );
1014
1015    // Note that rounded corners make this rectangle API hard to work with.
1016    // As this is common when using CSD, let's just disable this API.
1017    if state.background_appearance == WindowBackgroundAppearance::Opaque
1018        && state.decorations == WindowDecorations::Server
1019    {
1020        // Promise the compositor that this region of the window surface
1021        // contains no transparent pixels. This allows the compositor to
1022        // do skip whatever is behind the surface for better performance.
1023        state.surface.set_opaque_region(Some(&region));
1024    } else {
1025        state.surface.set_opaque_region(None);
1026    }
1027
1028    if let Some(ref blur_manager) = state.globals.blur_manager {
1029        if state.background_appearance == WindowBackgroundAppearance::Blurred {
1030            if state.blur.is_none() {
1031                let blur = blur_manager.create(&state.surface, &state.globals.qh, ());
1032                blur.set_region(Some(&region));
1033                state.blur = Some(blur);
1034            }
1035            state.blur.as_ref().unwrap().commit();
1036        } else {
1037            // It probably doesn't hurt to clear the blur for opaque windows
1038            blur_manager.unset(&state.surface);
1039            if let Some(b) = state.blur.take() {
1040                b.release()
1041            }
1042        }
1043    }
1044
1045    region.destroy();
1046}
1047
1048impl WindowDecorations {
1049    fn to_xdg(&self) -> zxdg_toplevel_decoration_v1::Mode {
1050        match self {
1051            WindowDecorations::Client => zxdg_toplevel_decoration_v1::Mode::ClientSide,
1052            WindowDecorations::Server => zxdg_toplevel_decoration_v1::Mode::ServerSide,
1053        }
1054    }
1055}
1056
1057impl ResizeEdge {
1058    fn to_xdg(&self) -> xdg_toplevel::ResizeEdge {
1059        match self {
1060            ResizeEdge::Top => xdg_toplevel::ResizeEdge::Top,
1061            ResizeEdge::TopRight => xdg_toplevel::ResizeEdge::TopRight,
1062            ResizeEdge::Right => xdg_toplevel::ResizeEdge::Right,
1063            ResizeEdge::BottomRight => xdg_toplevel::ResizeEdge::BottomRight,
1064            ResizeEdge::Bottom => xdg_toplevel::ResizeEdge::Bottom,
1065            ResizeEdge::BottomLeft => xdg_toplevel::ResizeEdge::BottomLeft,
1066            ResizeEdge::Left => xdg_toplevel::ResizeEdge::Left,
1067            ResizeEdge::TopLeft => xdg_toplevel::ResizeEdge::TopLeft,
1068        }
1069    }
1070}
1071
1072/// The configuration event is in terms of the window geometry, which we are constantly
1073/// updating to account for the client decorations. But that's not the area we want to render
1074/// to, due to our intrusize CSD. So, here we calculate the 'actual' size, by adding back in the insets
1075fn compute_outer_size(
1076    inset: Option<Pixels>,
1077    new_size: Option<Size<Pixels>>,
1078    tiling: Tiling,
1079) -> Option<Size<Pixels>> {
1080    let Some(inset) = inset else { return new_size };
1081
1082    new_size.map(|mut new_size| {
1083        if !tiling.top {
1084            new_size.height += inset;
1085        }
1086        if !tiling.bottom {
1087            new_size.height += inset;
1088        }
1089        if !tiling.left {
1090            new_size.width += inset;
1091        }
1092        if !tiling.right {
1093            new_size.width += inset;
1094        }
1095
1096        new_size
1097    })
1098}
1099
1100fn inset_by_tiling(mut bounds: Bounds<Pixels>, inset: Pixels, tiling: Tiling) -> Bounds<Pixels> {
1101    if !tiling.top {
1102        bounds.origin.y += inset;
1103        bounds.size.height -= inset;
1104    }
1105    if !tiling.bottom {
1106        bounds.size.height -= inset;
1107    }
1108    if !tiling.left {
1109        bounds.origin.x += inset;
1110        bounds.size.width -= inset;
1111    }
1112    if !tiling.right {
1113        bounds.size.width -= inset;
1114    }
1115
1116    bounds
1117}