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