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