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 resize(&mut self, size: Size<Pixels>) {
801 let state = self.borrow();
802 let state_ptr = self.0.clone();
803 let dp_size = size.to_device_pixels(self.scale_factor());
804
805 state.xdg_surface.set_window_geometry(
806 state.bounds.origin.x.0 as i32,
807 state.bounds.origin.y.0 as i32,
808 dp_size.width.0,
809 dp_size.height.0,
810 );
811
812 state
813 .globals
814 .executor
815 .spawn(async move { state_ptr.resize(size) })
816 .detach();
817 }
818
819 fn scale_factor(&self) -> f32 {
820 self.borrow().scale
821 }
822
823 fn appearance(&self) -> WindowAppearance {
824 self.borrow().appearance
825 }
826
827 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
828 let state = self.borrow();
829 state.display.as_ref().map(|(id, display)| {
830 Rc::new(WaylandDisplay {
831 id: id.clone(),
832 name: display.name.clone(),
833 bounds: display.bounds.to_pixels(state.scale),
834 }) as Rc<dyn PlatformDisplay>
835 })
836 }
837
838 fn mouse_position(&self) -> Point<Pixels> {
839 self.borrow()
840 .client
841 .get_client()
842 .borrow()
843 .mouse_location
844 .unwrap_or_default()
845 }
846
847 fn modifiers(&self) -> Modifiers {
848 self.borrow().client.get_client().borrow().modifiers
849 }
850
851 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
852 self.borrow_mut().input_handler = Some(input_handler);
853 }
854
855 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
856 self.borrow_mut().input_handler.take()
857 }
858
859 fn prompt(
860 &self,
861 _level: PromptLevel,
862 _msg: &str,
863 _detail: Option<&str>,
864 _answers: &[&str],
865 ) -> Option<Receiver<usize>> {
866 None
867 }
868
869 fn activate(&self) {
870 // Try to request an activation token. Even though the activation is likely going to be rejected,
871 // KWin and Mutter can use the app_id to visually indicate we're requesting attention.
872 let state = self.borrow();
873 if let (Some(activation), Some(app_id)) = (&state.globals.activation, state.app_id.clone())
874 {
875 state.client.set_pending_activation(state.surface.id());
876 let token = activation.get_activation_token(&state.globals.qh, ());
877 // The serial isn't exactly important here, since the activation is probably going to be rejected anyway.
878 let serial = state.client.get_serial(SerialKind::MousePress);
879 token.set_app_id(app_id);
880 token.set_serial(serial, &state.globals.seat);
881 token.set_surface(&state.surface);
882 token.commit();
883 }
884 }
885
886 fn is_active(&self) -> bool {
887 self.borrow().active
888 }
889
890 fn is_hovered(&self) -> bool {
891 self.borrow().hovered
892 }
893
894 fn set_title(&mut self, title: &str) {
895 self.borrow().toplevel.set_title(title.to_string());
896 }
897
898 fn set_app_id(&mut self, app_id: &str) {
899 let mut state = self.borrow_mut();
900 state.toplevel.set_app_id(app_id.to_owned());
901 state.app_id = Some(app_id.to_owned());
902 }
903
904 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
905 let mut state = self.borrow_mut();
906 state.background_appearance = background_appearance;
907 update_window(state);
908 }
909
910 fn minimize(&self) {
911 self.borrow().toplevel.set_minimized();
912 }
913
914 fn zoom(&self) {
915 let state = self.borrow();
916 if !state.maximized {
917 state.toplevel.set_maximized();
918 } else {
919 state.toplevel.unset_maximized();
920 }
921 }
922
923 fn toggle_fullscreen(&self) {
924 let mut state = self.borrow_mut();
925 if !state.fullscreen {
926 state.toplevel.set_fullscreen(None);
927 } else {
928 state.toplevel.unset_fullscreen();
929 }
930 }
931
932 fn is_fullscreen(&self) -> bool {
933 self.borrow().fullscreen
934 }
935
936 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
937 self.0.callbacks.borrow_mut().request_frame = Some(callback);
938 }
939
940 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
941 self.0.callbacks.borrow_mut().input = Some(callback);
942 }
943
944 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
945 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
946 }
947
948 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
949 self.0.callbacks.borrow_mut().hover_status_change = Some(callback);
950 }
951
952 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
953 self.0.callbacks.borrow_mut().resize = Some(callback);
954 }
955
956 fn on_moved(&self, callback: Box<dyn FnMut()>) {
957 self.0.callbacks.borrow_mut().moved = Some(callback);
958 }
959
960 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
961 self.0.callbacks.borrow_mut().should_close = Some(callback);
962 }
963
964 fn on_close(&self, callback: Box<dyn FnOnce()>) {
965 self.0.callbacks.borrow_mut().close = Some(callback);
966 }
967
968 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
969 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
970 }
971
972 fn draw(&self, scene: &Scene) {
973 let mut state = self.borrow_mut();
974 state.renderer.draw(scene);
975 }
976
977 fn completed_frame(&self) {
978 let state = self.borrow();
979 state.surface.commit();
980 }
981
982 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
983 let state = self.borrow();
984 state.renderer.sprite_atlas().clone()
985 }
986
987 fn show_window_menu(&self, position: Point<Pixels>) {
988 let state = self.borrow();
989 let serial = state.client.get_serial(SerialKind::MousePress);
990 state.toplevel.show_window_menu(
991 &state.globals.seat,
992 serial,
993 position.x.0 as i32,
994 position.y.0 as i32,
995 );
996 }
997
998 fn start_window_move(&self) {
999 let state = self.borrow();
1000 let serial = state.client.get_serial(SerialKind::MousePress);
1001 state.toplevel._move(&state.globals.seat, serial);
1002 }
1003
1004 fn start_window_resize(&self, edge: crate::ResizeEdge) {
1005 let state = self.borrow();
1006 state.toplevel.resize(
1007 &state.globals.seat,
1008 state.client.get_serial(SerialKind::MousePress),
1009 edge.to_xdg(),
1010 )
1011 }
1012
1013 fn window_decorations(&self) -> Decorations {
1014 let state = self.borrow();
1015 match state.decorations {
1016 WindowDecorations::Server => Decorations::Server,
1017 WindowDecorations::Client => Decorations::Client {
1018 tiling: state.tiling,
1019 },
1020 }
1021 }
1022
1023 fn request_decorations(&self, decorations: WindowDecorations) {
1024 let mut state = self.borrow_mut();
1025 state.decorations = decorations;
1026 if let Some(decoration) = state.decoration.as_ref() {
1027 decoration.set_mode(decorations.to_xdg());
1028 update_window(state);
1029 }
1030 }
1031
1032 fn window_controls(&self) -> WindowControls {
1033 self.borrow().window_controls
1034 }
1035
1036 fn set_client_inset(&self, inset: Pixels) {
1037 let mut state = self.borrow_mut();
1038 if Some(inset) != state.inset {
1039 state.inset = Some(inset);
1040 update_window(state);
1041 }
1042 }
1043
1044 fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
1045 let state = self.borrow();
1046 state.client.update_ime_position(bounds);
1047 }
1048
1049 fn gpu_specs(&self) -> Option<GpuSpecs> {
1050 self.borrow().renderer.gpu_specs().into()
1051 }
1052}
1053
1054fn update_window(mut state: RefMut<WaylandWindowState>) {
1055 let opaque = !state.is_transparent();
1056
1057 state.renderer.update_transparency(!opaque);
1058 let mut opaque_area = state.window_bounds.map(|v| v.0 as i32);
1059 if let Some(inset) = state.inset {
1060 opaque_area.inset(inset.0 as i32);
1061 }
1062
1063 let region = state
1064 .globals
1065 .compositor
1066 .create_region(&state.globals.qh, ());
1067 region.add(
1068 opaque_area.origin.x,
1069 opaque_area.origin.y,
1070 opaque_area.size.width,
1071 opaque_area.size.height,
1072 );
1073
1074 // Note that rounded corners make this rectangle API hard to work with.
1075 // As this is common when using CSD, let's just disable this API.
1076 if state.background_appearance == WindowBackgroundAppearance::Opaque
1077 && state.decorations == WindowDecorations::Server
1078 {
1079 // Promise the compositor that this region of the window surface
1080 // contains no transparent pixels. This allows the compositor to skip
1081 // updating whatever is behind the surface for better performance.
1082 state.surface.set_opaque_region(Some(®ion));
1083 } else {
1084 state.surface.set_opaque_region(None);
1085 }
1086
1087 if let Some(ref blur_manager) = state.globals.blur_manager {
1088 if state.background_appearance == WindowBackgroundAppearance::Blurred {
1089 if state.blur.is_none() {
1090 let blur = blur_manager.create(&state.surface, &state.globals.qh, ());
1091 state.blur = Some(blur);
1092 }
1093 state.blur.as_ref().unwrap().commit();
1094 } else {
1095 // It probably doesn't hurt to clear the blur for opaque windows
1096 blur_manager.unset(&state.surface);
1097 if let Some(b) = state.blur.take() {
1098 b.release()
1099 }
1100 }
1101 }
1102
1103 region.destroy();
1104}
1105
1106impl WindowDecorations {
1107 fn to_xdg(&self) -> zxdg_toplevel_decoration_v1::Mode {
1108 match self {
1109 WindowDecorations::Client => zxdg_toplevel_decoration_v1::Mode::ClientSide,
1110 WindowDecorations::Server => zxdg_toplevel_decoration_v1::Mode::ServerSide,
1111 }
1112 }
1113}
1114
1115impl ResizeEdge {
1116 fn to_xdg(&self) -> xdg_toplevel::ResizeEdge {
1117 match self {
1118 ResizeEdge::Top => xdg_toplevel::ResizeEdge::Top,
1119 ResizeEdge::TopRight => xdg_toplevel::ResizeEdge::TopRight,
1120 ResizeEdge::Right => xdg_toplevel::ResizeEdge::Right,
1121 ResizeEdge::BottomRight => xdg_toplevel::ResizeEdge::BottomRight,
1122 ResizeEdge::Bottom => xdg_toplevel::ResizeEdge::Bottom,
1123 ResizeEdge::BottomLeft => xdg_toplevel::ResizeEdge::BottomLeft,
1124 ResizeEdge::Left => xdg_toplevel::ResizeEdge::Left,
1125 ResizeEdge::TopLeft => xdg_toplevel::ResizeEdge::TopLeft,
1126 }
1127 }
1128}
1129
1130/// The configuration event is in terms of the window geometry, which we are constantly
1131/// updating to account for the client decorations. But that's not the area we want to render
1132/// to, due to our intrusize CSD. So, here we calculate the 'actual' size, by adding back in the insets
1133fn compute_outer_size(
1134 inset: Option<Pixels>,
1135 new_size: Option<Size<Pixels>>,
1136 tiling: Tiling,
1137) -> Option<Size<Pixels>> {
1138 let Some(inset) = inset else { return new_size };
1139
1140 new_size.map(|mut new_size| {
1141 if !tiling.top {
1142 new_size.height += inset;
1143 }
1144 if !tiling.bottom {
1145 new_size.height += inset;
1146 }
1147 if !tiling.left {
1148 new_size.width += inset;
1149 }
1150 if !tiling.right {
1151 new_size.width += inset;
1152 }
1153
1154 new_size
1155 })
1156}
1157
1158fn inset_by_tiling(mut bounds: Bounds<Pixels>, inset: Pixels, tiling: Tiling) -> Bounds<Pixels> {
1159 if !tiling.top {
1160 bounds.origin.y += inset;
1161 bounds.size.height -= inset;
1162 }
1163 if !tiling.bottom {
1164 bounds.size.height -= inset;
1165 }
1166 if !tiling.left {
1167 bounds.origin.x += inset;
1168 bounds.size.width -= inset;
1169 }
1170 if !tiling.right {
1171 bounds.size.width -= inset;
1172 }
1173
1174 bounds
1175}