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