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