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