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        match event {
 359            xdg_surface::Event::Configure { serial } => {
 360                {
 361                    let mut state = self.state.borrow_mut();
 362                    if let Some(window_controls) = state.in_progress_window_controls.take() {
 363                        state.window_controls = window_controls;
 364
 365                        drop(state);
 366                        let mut callbacks = self.callbacks.borrow_mut();
 367                        if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
 368                            appearance_changed();
 369                        }
 370                    }
 371                }
 372                {
 373                    let mut state = self.state.borrow_mut();
 374
 375                    if let Some(mut configure) = state.in_progress_configure.take() {
 376                        let got_unmaximized = state.maximized && !configure.maximized;
 377                        state.fullscreen = configure.fullscreen;
 378                        state.maximized = configure.maximized;
 379                        state.tiling = configure.tiling;
 380                        // Limit interactive resizes to once per vblank
 381                        if configure.resizing && state.resize_throttle {
 382                            return;
 383                        } else if configure.resizing {
 384                            state.resize_throttle = true;
 385                        }
 386                        if !configure.fullscreen && !configure.maximized {
 387                            configure.size = if got_unmaximized {
 388                                Some(state.window_bounds.size)
 389                            } else {
 390                                compute_outer_size(state.inset(), configure.size, state.tiling)
 391                            };
 392                            if let Some(size) = configure.size {
 393                                state.window_bounds = Bounds {
 394                                    origin: Point::default(),
 395                                    size,
 396                                };
 397                            }
 398                        }
 399                        drop(state);
 400                        if let Some(size) = configure.size {
 401                            self.resize(size);
 402                        }
 403                    }
 404                }
 405                let mut state = self.state.borrow_mut();
 406                state.xdg_surface.ack_configure(serial);
 407
 408                let window_geometry = inset_by_tiling(
 409                    state.bounds.map_origin(|_| px(0.0)),
 410                    state.inset(),
 411                    state.tiling,
 412                )
 413                .map(|v| v.0 as i32)
 414                .map_size(|v| if v <= 0 { 1 } else { v });
 415
 416                state.xdg_surface.set_window_geometry(
 417                    window_geometry.origin.x,
 418                    window_geometry.origin.y,
 419                    window_geometry.size.width,
 420                    window_geometry.size.height,
 421                );
 422
 423                let request_frame_callback = !state.acknowledged_first_configure;
 424                if request_frame_callback {
 425                    state.acknowledged_first_configure = true;
 426                    drop(state);
 427                    self.frame();
 428                }
 429            }
 430            _ => {}
 431        }
 432    }
 433
 434    pub fn handle_toplevel_decoration_event(&self, event: zxdg_toplevel_decoration_v1::Event) {
 435        match event {
 436            zxdg_toplevel_decoration_v1::Event::Configure { mode } => match mode {
 437                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
 438                    self.state.borrow_mut().decorations = WindowDecorations::Server;
 439                    if let Some(mut appearance_changed) =
 440                        self.callbacks.borrow_mut().appearance_changed.as_mut()
 441                    {
 442                        appearance_changed();
 443                    }
 444                }
 445                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
 446                    self.state.borrow_mut().decorations = WindowDecorations::Client;
 447                    // Update background to be transparent
 448                    if let Some(mut appearance_changed) =
 449                        self.callbacks.borrow_mut().appearance_changed.as_mut()
 450                    {
 451                        appearance_changed();
 452                    }
 453                }
 454                WEnum::Value(_) => {
 455                    log::warn!("Unknown decoration mode");
 456                }
 457                WEnum::Unknown(v) => {
 458                    log::warn!("Unknown decoration mode: {}", v);
 459                }
 460            },
 461            _ => {}
 462        }
 463    }
 464
 465    pub fn handle_fractional_scale_event(&self, event: wp_fractional_scale_v1::Event) {
 466        match event {
 467            wp_fractional_scale_v1::Event::PreferredScale { scale } => {
 468                self.rescale(scale as f32 / 120.0);
 469            }
 470            _ => {}
 471        }
 472    }
 473
 474    pub fn handle_toplevel_event(&self, event: xdg_toplevel::Event) -> bool {
 475        match event {
 476            xdg_toplevel::Event::Configure {
 477                width,
 478                height,
 479                states,
 480            } => {
 481                let mut size = if width == 0 || height == 0 {
 482                    None
 483                } else {
 484                    Some(size(px(width as f32), px(height as f32)))
 485                };
 486
 487                let states = extract_states::<xdg_toplevel::State>(&states);
 488
 489                let mut tiling = Tiling::default();
 490                let mut fullscreen = false;
 491                let mut maximized = false;
 492                let mut resizing = false;
 493
 494                for state in states {
 495                    match state {
 496                        xdg_toplevel::State::Maximized => {
 497                            maximized = true;
 498                        }
 499                        xdg_toplevel::State::Fullscreen => {
 500                            fullscreen = true;
 501                        }
 502                        xdg_toplevel::State::Resizing => resizing = true,
 503                        xdg_toplevel::State::TiledTop => {
 504                            tiling.top = true;
 505                        }
 506                        xdg_toplevel::State::TiledLeft => {
 507                            tiling.left = true;
 508                        }
 509                        xdg_toplevel::State::TiledRight => {
 510                            tiling.right = true;
 511                        }
 512                        xdg_toplevel::State::TiledBottom => {
 513                            tiling.bottom = true;
 514                        }
 515                        _ => {
 516                            // noop
 517                        }
 518                    }
 519                }
 520
 521                if fullscreen || maximized {
 522                    tiling = Tiling::tiled();
 523                }
 524
 525                let mut state = self.state.borrow_mut();
 526                state.in_progress_configure = Some(InProgressConfigure {
 527                    size,
 528                    fullscreen,
 529                    maximized,
 530                    resizing,
 531                    tiling,
 532                });
 533
 534                false
 535            }
 536            xdg_toplevel::Event::Close => {
 537                let mut cb = self.callbacks.borrow_mut();
 538                if let Some(mut should_close) = cb.should_close.take() {
 539                    let result = (should_close)();
 540                    cb.should_close = Some(should_close);
 541                    if result {
 542                        drop(cb);
 543                        self.close();
 544                    }
 545                    result
 546                } else {
 547                    true
 548                }
 549            }
 550            xdg_toplevel::Event::WmCapabilities { capabilities } => {
 551                let mut window_controls = WindowControls::default();
 552
 553                let states = extract_states::<xdg_toplevel::WmCapabilities>(&capabilities);
 554
 555                for state in states {
 556                    match state {
 557                        xdg_toplevel::WmCapabilities::Maximize => {
 558                            window_controls.maximize = true;
 559                        }
 560                        xdg_toplevel::WmCapabilities::Minimize => {
 561                            window_controls.minimize = true;
 562                        }
 563                        xdg_toplevel::WmCapabilities::Fullscreen => {
 564                            window_controls.fullscreen = true;
 565                        }
 566                        xdg_toplevel::WmCapabilities::WindowMenu => {
 567                            window_controls.window_menu = true;
 568                        }
 569                        _ => {}
 570                    }
 571                }
 572
 573                let mut state = self.state.borrow_mut();
 574                state.in_progress_window_controls = Some(window_controls);
 575                false
 576            }
 577            _ => false,
 578        }
 579    }
 580
 581    #[allow(clippy::mutable_key_type)]
 582    pub fn handle_surface_event(
 583        &self,
 584        event: wl_surface::Event,
 585        outputs: HashMap<ObjectId, Output>,
 586    ) {
 587        let mut state = self.state.borrow_mut();
 588
 589        match event {
 590            wl_surface::Event::Enter { output } => {
 591                let id = output.id();
 592
 593                let Some(output) = outputs.get(&id) else {
 594                    return;
 595                };
 596
 597                state.outputs.insert(id, output.clone());
 598
 599                let scale = state.primary_output_scale();
 600
 601                // We use `PreferredBufferScale` instead to set the scale if it's available
 602                if state.surface.version() < wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
 603                    state.surface.set_buffer_scale(scale);
 604                    drop(state);
 605                    self.rescale(scale as f32);
 606                }
 607            }
 608            wl_surface::Event::Leave { output } => {
 609                state.outputs.remove(&output.id());
 610
 611                let scale = state.primary_output_scale();
 612
 613                // We use `PreferredBufferScale` instead to set the scale if it's available
 614                if state.surface.version() < wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
 615                    state.surface.set_buffer_scale(scale);
 616                    drop(state);
 617                    self.rescale(scale as f32);
 618                }
 619            }
 620            wl_surface::Event::PreferredBufferScale { factor } => {
 621                // We use `WpFractionalScale` instead to set the scale if it's available
 622                if state.globals.fractional_scale_manager.is_none() {
 623                    state.surface.set_buffer_scale(factor);
 624                    drop(state);
 625                    self.rescale(factor as f32);
 626                }
 627            }
 628            _ => {}
 629        }
 630    }
 631
 632    pub fn handle_ime(&self, ime: ImeInput) {
 633        let mut state = self.state.borrow_mut();
 634        if let Some(mut input_handler) = state.input_handler.take() {
 635            drop(state);
 636            match ime {
 637                ImeInput::InsertText(text) => {
 638                    input_handler.replace_text_in_range(None, &text);
 639                }
 640                ImeInput::SetMarkedText(text) => {
 641                    input_handler.replace_and_mark_text_in_range(None, &text, None);
 642                }
 643                ImeInput::UnmarkText => {
 644                    input_handler.unmark_text();
 645                }
 646                ImeInput::DeleteText => {
 647                    if let Some(marked) = input_handler.marked_text_range() {
 648                        input_handler.replace_text_in_range(Some(marked), "");
 649                    }
 650                }
 651            }
 652            self.state.borrow_mut().input_handler = Some(input_handler);
 653        }
 654    }
 655
 656    pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
 657        let mut state = self.state.borrow_mut();
 658        let mut bounds: Option<Bounds<Pixels>> = None;
 659        if let Some(mut input_handler) = state.input_handler.take() {
 660            drop(state);
 661            if let Some(selection) = input_handler.marked_text_range() {
 662                bounds = input_handler.bounds_for_range(selection.start..selection.start);
 663            }
 664            self.state.borrow_mut().input_handler = Some(input_handler);
 665        }
 666        bounds
 667    }
 668
 669    pub fn set_size_and_scale(&self, size: Option<Size<Pixels>>, scale: Option<f32>) {
 670        let (size, scale) = {
 671            let mut state = self.state.borrow_mut();
 672            if size.is_none_or(|size| size == state.bounds.size)
 673                && scale.is_none_or(|scale| scale == state.scale)
 674            {
 675                return;
 676            }
 677            if let Some(size) = size {
 678                state.bounds.size = size;
 679            }
 680            if let Some(scale) = scale {
 681                state.scale = scale;
 682            }
 683            let device_bounds = state.bounds.to_device_pixels(state.scale);
 684            state.renderer.update_drawable_size(device_bounds.size);
 685            (state.bounds.size, state.scale)
 686        };
 687
 688        if let Some(ref mut fun) = self.callbacks.borrow_mut().resize {
 689            fun(size, scale);
 690        }
 691
 692        {
 693            let state = self.state.borrow();
 694            if let Some(viewport) = &state.viewport {
 695                viewport.set_destination(size.width.0 as i32, size.height.0 as i32);
 696            }
 697        }
 698    }
 699
 700    pub fn resize(&self, size: Size<Pixels>) {
 701        self.set_size_and_scale(Some(size), None);
 702    }
 703
 704    pub fn rescale(&self, scale: f32) {
 705        self.set_size_and_scale(None, Some(scale));
 706    }
 707
 708    pub fn close(&self) {
 709        let mut callbacks = self.callbacks.borrow_mut();
 710        if let Some(fun) = callbacks.close.take() {
 711            fun()
 712        }
 713    }
 714
 715    pub fn handle_input(&self, input: PlatformInput) {
 716        if let Some(ref mut fun) = self.callbacks.borrow_mut().input
 717            && !fun(input.clone()).propagate
 718        {
 719            return;
 720        }
 721        if let PlatformInput::KeyDown(event) = input
 722            && event.keystroke.modifiers.is_subset_of(&Modifiers::shift())
 723            && let Some(key_char) = &event.keystroke.key_char
 724        {
 725            let mut state = self.state.borrow_mut();
 726            if let Some(mut input_handler) = state.input_handler.take() {
 727                drop(state);
 728                input_handler.replace_text_in_range(None, key_char);
 729                self.state.borrow_mut().input_handler = Some(input_handler);
 730            }
 731        }
 732    }
 733
 734    pub fn set_focused(&self, focus: bool) {
 735        self.state.borrow_mut().active = focus;
 736        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
 737            fun(focus);
 738        }
 739    }
 740
 741    pub fn set_hovered(&self, focus: bool) {
 742        if let Some(ref mut fun) = self.callbacks.borrow_mut().hover_status_change {
 743            fun(focus);
 744        }
 745    }
 746
 747    pub fn set_appearance(&mut self, appearance: WindowAppearance) {
 748        self.state.borrow_mut().appearance = appearance;
 749
 750        let mut callbacks = self.callbacks.borrow_mut();
 751        if let Some(ref mut fun) = callbacks.appearance_changed {
 752            (fun)()
 753        }
 754    }
 755
 756    pub fn primary_output_scale(&self) -> i32 {
 757        self.state.borrow_mut().primary_output_scale()
 758    }
 759}
 760
 761fn extract_states<'a, S: TryFrom<u32> + 'a>(states: &'a [u8]) -> impl Iterator<Item = S> + 'a
 762where
 763    <S as TryFrom<u32>>::Error: 'a,
 764{
 765    states
 766        .chunks_exact(4)
 767        .flat_map(TryInto::<[u8; 4]>::try_into)
 768        .map(u32::from_ne_bytes)
 769        .flat_map(S::try_from)
 770}
 771
 772impl rwh::HasWindowHandle for WaylandWindow {
 773    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 774        let surface = self.0.surface().id().as_ptr() as *mut libc::c_void;
 775        let c_ptr = NonNull::new(surface).ok_or(rwh::HandleError::Unavailable)?;
 776        let handle = rwh::WaylandWindowHandle::new(c_ptr);
 777        let raw_handle = rwh::RawWindowHandle::Wayland(handle);
 778        Ok(unsafe { rwh::WindowHandle::borrow_raw(raw_handle) })
 779    }
 780}
 781
 782impl rwh::HasDisplayHandle for WaylandWindow {
 783    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 784        let display = self
 785            .0
 786            .surface()
 787            .backend()
 788            .upgrade()
 789            .ok_or(rwh::HandleError::Unavailable)?
 790            .display_ptr() as *mut libc::c_void;
 791
 792        let c_ptr = NonNull::new(display).ok_or(rwh::HandleError::Unavailable)?;
 793        let handle = rwh::WaylandDisplayHandle::new(c_ptr);
 794        let raw_handle = rwh::RawDisplayHandle::Wayland(handle);
 795        Ok(unsafe { rwh::DisplayHandle::borrow_raw(raw_handle) })
 796    }
 797}
 798
 799impl PlatformWindow for WaylandWindow {
 800    fn bounds(&self) -> Bounds<Pixels> {
 801        self.borrow().bounds
 802    }
 803
 804    fn is_maximized(&self) -> bool {
 805        self.borrow().maximized
 806    }
 807
 808    fn window_bounds(&self) -> WindowBounds {
 809        let state = self.borrow();
 810        if state.fullscreen {
 811            WindowBounds::Fullscreen(state.window_bounds)
 812        } else if state.maximized {
 813            WindowBounds::Maximized(state.window_bounds)
 814        } else {
 815            drop(state);
 816            WindowBounds::Windowed(self.bounds())
 817        }
 818    }
 819
 820    fn inner_window_bounds(&self) -> WindowBounds {
 821        let state = self.borrow();
 822        if state.fullscreen {
 823            WindowBounds::Fullscreen(state.window_bounds)
 824        } else if state.maximized {
 825            WindowBounds::Maximized(state.window_bounds)
 826        } else {
 827            let inset = state.inset();
 828            drop(state);
 829            WindowBounds::Windowed(self.bounds().inset(inset))
 830        }
 831    }
 832
 833    fn content_size(&self) -> Size<Pixels> {
 834        self.borrow().bounds.size
 835    }
 836
 837    fn resize(&mut self, size: Size<Pixels>) {
 838        let state = self.borrow();
 839        let state_ptr = self.0.clone();
 840        let dp_size = size.to_device_pixels(self.scale_factor());
 841
 842        state.xdg_surface.set_window_geometry(
 843            state.bounds.origin.x.0 as i32,
 844            state.bounds.origin.y.0 as i32,
 845            dp_size.width.0,
 846            dp_size.height.0,
 847        );
 848
 849        state
 850            .globals
 851            .executor
 852            .spawn(async move { state_ptr.resize(size) })
 853            .detach();
 854    }
 855
 856    fn scale_factor(&self) -> f32 {
 857        self.borrow().scale
 858    }
 859
 860    fn appearance(&self) -> WindowAppearance {
 861        self.borrow().appearance
 862    }
 863
 864    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 865        let state = self.borrow();
 866        state.display.as_ref().map(|(id, display)| {
 867            Rc::new(WaylandDisplay {
 868                id: id.clone(),
 869                name: display.name.clone(),
 870                bounds: display.bounds.to_pixels(state.scale),
 871            }) as Rc<dyn PlatformDisplay>
 872        })
 873    }
 874
 875    fn mouse_position(&self) -> Point<Pixels> {
 876        self.borrow()
 877            .client
 878            .get_client()
 879            .borrow()
 880            .mouse_location
 881            .unwrap_or_default()
 882    }
 883
 884    fn modifiers(&self) -> Modifiers {
 885        self.borrow().client.get_client().borrow().modifiers
 886    }
 887
 888    fn capslock(&self) -> Capslock {
 889        self.borrow().client.get_client().borrow().capslock
 890    }
 891
 892    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 893        self.borrow_mut().input_handler = Some(input_handler);
 894    }
 895
 896    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 897        self.borrow_mut().input_handler.take()
 898    }
 899
 900    fn prompt(
 901        &self,
 902        _level: PromptLevel,
 903        _msg: &str,
 904        _detail: Option<&str>,
 905        _answers: &[PromptButton],
 906    ) -> Option<Receiver<usize>> {
 907        None
 908    }
 909
 910    fn activate(&self) {
 911        // Try to request an activation token. Even though the activation is likely going to be rejected,
 912        // KWin and Mutter can use the app_id to visually indicate we're requesting attention.
 913        let state = self.borrow();
 914        if let (Some(activation), Some(app_id)) = (&state.globals.activation, state.app_id.clone())
 915        {
 916            state.client.set_pending_activation(state.surface.id());
 917            let token = activation.get_activation_token(&state.globals.qh, ());
 918            // The serial isn't exactly important here, since the activation is probably going to be rejected anyway.
 919            let serial = state.client.get_serial(SerialKind::MousePress);
 920            token.set_app_id(app_id);
 921            token.set_serial(serial, &state.globals.seat);
 922            token.set_surface(&state.surface);
 923            token.commit();
 924        }
 925    }
 926
 927    fn is_active(&self) -> bool {
 928        self.borrow().active
 929    }
 930
 931    fn is_hovered(&self) -> bool {
 932        self.borrow().hovered
 933    }
 934
 935    fn set_title(&mut self, title: &str) {
 936        self.borrow().toplevel.set_title(title.to_string());
 937    }
 938
 939    fn set_app_id(&mut self, app_id: &str) {
 940        let mut state = self.borrow_mut();
 941        state.toplevel.set_app_id(app_id.to_owned());
 942        state.app_id = Some(app_id.to_owned());
 943    }
 944
 945    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
 946        let mut state = self.borrow_mut();
 947        state.background_appearance = background_appearance;
 948        update_window(state);
 949    }
 950
 951    fn minimize(&self) {
 952        self.borrow().toplevel.set_minimized();
 953    }
 954
 955    fn zoom(&self) {
 956        let state = self.borrow();
 957        if !state.maximized {
 958            state.toplevel.set_maximized();
 959        } else {
 960            state.toplevel.unset_maximized();
 961        }
 962    }
 963
 964    fn toggle_fullscreen(&self) {
 965        let mut state = self.borrow_mut();
 966        if !state.fullscreen {
 967            state.toplevel.set_fullscreen(None);
 968        } else {
 969            state.toplevel.unset_fullscreen();
 970        }
 971    }
 972
 973    fn is_fullscreen(&self) -> bool {
 974        self.borrow().fullscreen
 975    }
 976
 977    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
 978        self.0.callbacks.borrow_mut().request_frame = Some(callback);
 979    }
 980
 981    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
 982        self.0.callbacks.borrow_mut().input = Some(callback);
 983    }
 984
 985    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 986        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
 987    }
 988
 989    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 990        self.0.callbacks.borrow_mut().hover_status_change = Some(callback);
 991    }
 992
 993    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 994        self.0.callbacks.borrow_mut().resize = Some(callback);
 995    }
 996
 997    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 998        self.0.callbacks.borrow_mut().moved = Some(callback);
 999    }
1000
1001    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1002        self.0.callbacks.borrow_mut().should_close = Some(callback);
1003    }
1004
1005    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1006        self.0.callbacks.borrow_mut().close = Some(callback);
1007    }
1008
1009    fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1010    }
1011
1012    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1013        self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1014    }
1015
1016    fn draw(&self, scene: &Scene) {
1017        let mut state = self.borrow_mut();
1018        state.renderer.draw(scene);
1019    }
1020
1021    fn completed_frame(&self) {
1022        let state = self.borrow();
1023        state.surface.commit();
1024    }
1025
1026    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1027        let state = self.borrow();
1028        state.renderer.sprite_atlas().clone()
1029    }
1030
1031    fn show_window_menu(&self, position: Point<Pixels>) {
1032        let state = self.borrow();
1033        let serial = state.client.get_serial(SerialKind::MousePress);
1034        state.toplevel.show_window_menu(
1035            &state.globals.seat,
1036            serial,
1037            position.x.0 as i32,
1038            position.y.0 as i32,
1039        );
1040    }
1041
1042    fn start_window_move(&self) {
1043        let state = self.borrow();
1044        let serial = state.client.get_serial(SerialKind::MousePress);
1045        state.toplevel._move(&state.globals.seat, serial);
1046    }
1047
1048    fn start_window_resize(&self, edge: crate::ResizeEdge) {
1049        let state = self.borrow();
1050        state.toplevel.resize(
1051            &state.globals.seat,
1052            state.client.get_serial(SerialKind::MousePress),
1053            edge.to_xdg(),
1054        )
1055    }
1056
1057    fn window_decorations(&self) -> Decorations {
1058        let state = self.borrow();
1059        match state.decorations {
1060            WindowDecorations::Server => Decorations::Server,
1061            WindowDecorations::Client => Decorations::Client {
1062                tiling: state.tiling,
1063            },
1064        }
1065    }
1066
1067    fn request_decorations(&self, decorations: WindowDecorations) {
1068        let mut state = self.borrow_mut();
1069        state.decorations = decorations;
1070        if let Some(decoration) = state.decoration.as_ref() {
1071            decoration.set_mode(decorations.to_xdg());
1072            update_window(state);
1073        }
1074    }
1075
1076    fn window_controls(&self) -> WindowControls {
1077        self.borrow().window_controls
1078    }
1079
1080    fn set_client_inset(&self, inset: Pixels) {
1081        let mut state = self.borrow_mut();
1082        if Some(inset) != state.client_inset {
1083            state.client_inset = Some(inset);
1084            update_window(state);
1085        }
1086    }
1087
1088    fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
1089        let state = self.borrow();
1090        state.client.update_ime_position(bounds);
1091    }
1092
1093    fn gpu_specs(&self) -> Option<GpuSpecs> {
1094        self.borrow().renderer.gpu_specs().into()
1095    }
1096}
1097
1098fn update_window(mut state: RefMut<WaylandWindowState>) {
1099    let opaque = !state.is_transparent();
1100
1101    state.renderer.update_transparency(!opaque);
1102    let mut opaque_area = state.window_bounds.map(|v| v.0 as i32);
1103    opaque_area.inset(state.inset().0 as i32);
1104
1105    let region = state
1106        .globals
1107        .compositor
1108        .create_region(&state.globals.qh, ());
1109    region.add(
1110        opaque_area.origin.x,
1111        opaque_area.origin.y,
1112        opaque_area.size.width,
1113        opaque_area.size.height,
1114    );
1115
1116    // Note that rounded corners make this rectangle API hard to work with.
1117    // As this is common when using CSD, let's just disable this API.
1118    if state.background_appearance == WindowBackgroundAppearance::Opaque
1119        && state.decorations == WindowDecorations::Server
1120    {
1121        // Promise the compositor that this region of the window surface
1122        // contains no transparent pixels. This allows the compositor to skip
1123        // updating whatever is behind the surface for better performance.
1124        state.surface.set_opaque_region(Some(&region));
1125    } else {
1126        state.surface.set_opaque_region(None);
1127    }
1128
1129    if let Some(ref blur_manager) = state.globals.blur_manager {
1130        if state.background_appearance == WindowBackgroundAppearance::Blurred {
1131            if state.blur.is_none() {
1132                let blur = blur_manager.create(&state.surface, &state.globals.qh, ());
1133                state.blur = Some(blur);
1134            }
1135            state.blur.as_ref().unwrap().commit();
1136        } else {
1137            // It probably doesn't hurt to clear the blur for opaque windows
1138            blur_manager.unset(&state.surface);
1139            if let Some(b) = state.blur.take() {
1140                b.release()
1141            }
1142        }
1143    }
1144
1145    region.destroy();
1146}
1147
1148impl WindowDecorations {
1149    fn to_xdg(&self) -> zxdg_toplevel_decoration_v1::Mode {
1150        match self {
1151            WindowDecorations::Client => zxdg_toplevel_decoration_v1::Mode::ClientSide,
1152            WindowDecorations::Server => zxdg_toplevel_decoration_v1::Mode::ServerSide,
1153        }
1154    }
1155}
1156
1157impl ResizeEdge {
1158    fn to_xdg(&self) -> xdg_toplevel::ResizeEdge {
1159        match self {
1160            ResizeEdge::Top => xdg_toplevel::ResizeEdge::Top,
1161            ResizeEdge::TopRight => xdg_toplevel::ResizeEdge::TopRight,
1162            ResizeEdge::Right => xdg_toplevel::ResizeEdge::Right,
1163            ResizeEdge::BottomRight => xdg_toplevel::ResizeEdge::BottomRight,
1164            ResizeEdge::Bottom => xdg_toplevel::ResizeEdge::Bottom,
1165            ResizeEdge::BottomLeft => xdg_toplevel::ResizeEdge::BottomLeft,
1166            ResizeEdge::Left => xdg_toplevel::ResizeEdge::Left,
1167            ResizeEdge::TopLeft => xdg_toplevel::ResizeEdge::TopLeft,
1168        }
1169    }
1170}
1171
1172/// The configuration event is in terms of the window geometry, which we are constantly
1173/// updating to account for the client decorations. But that's not the area we want to render
1174/// to, due to our intrusize CSD. So, here we calculate the 'actual' size, by adding back in the insets
1175fn compute_outer_size(
1176    inset: Pixels,
1177    new_size: Option<Size<Pixels>>,
1178    tiling: Tiling,
1179) -> Option<Size<Pixels>> {
1180    new_size.map(|mut new_size| {
1181        if !tiling.top {
1182            new_size.height += inset;
1183        }
1184        if !tiling.bottom {
1185            new_size.height += inset;
1186        }
1187        if !tiling.left {
1188            new_size.width += inset;
1189        }
1190        if !tiling.right {
1191            new_size.width += inset;
1192        }
1193
1194        new_size
1195    })
1196}
1197
1198fn inset_by_tiling(mut bounds: Bounds<Pixels>, inset: Pixels, tiling: Tiling) -> Bounds<Pixels> {
1199    if !tiling.top {
1200        bounds.origin.y += inset;
1201        bounds.size.height -= inset;
1202    }
1203    if !tiling.bottom {
1204        bounds.size.height -= inset;
1205    }
1206    if !tiling.left {
1207        bounds.origin.x += inset;
1208        bounds.size.width -= inset;
1209    }
1210    if !tiling.right {
1211        bounds.size.width -= inset;
1212    }
1213
1214    bounds
1215}