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