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