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