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 if let xdg_surface::Event::Configure { serial } = event {
359 {
360 let mut state = self.state.borrow_mut();
361 if let Some(window_controls) = state.in_progress_window_controls.take() {
362 state.window_controls = window_controls;
363
364 drop(state);
365 let mut callbacks = self.callbacks.borrow_mut();
366 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
367 appearance_changed();
368 }
369 }
370 }
371 {
372 let mut state = self.state.borrow_mut();
373
374 if let Some(mut configure) = state.in_progress_configure.take() {
375 let got_unmaximized = state.maximized && !configure.maximized;
376 state.fullscreen = configure.fullscreen;
377 state.maximized = configure.maximized;
378 state.tiling = configure.tiling;
379 // Limit interactive resizes to once per vblank
380 if configure.resizing && state.resize_throttle {
381 return;
382 } else if configure.resizing {
383 state.resize_throttle = true;
384 }
385 if !configure.fullscreen && !configure.maximized {
386 configure.size = if got_unmaximized {
387 Some(state.window_bounds.size)
388 } else {
389 compute_outer_size(state.inset(), configure.size, state.tiling)
390 };
391 if let Some(size) = configure.size {
392 state.window_bounds = Bounds {
393 origin: Point::default(),
394 size,
395 };
396 }
397 }
398 drop(state);
399 if let Some(size) = configure.size {
400 self.resize(size);
401 }
402 }
403 }
404 let mut state = self.state.borrow_mut();
405 state.xdg_surface.ack_configure(serial);
406
407 let window_geometry = inset_by_tiling(
408 state.bounds.map_origin(|_| px(0.0)),
409 state.inset(),
410 state.tiling,
411 )
412 .map(|v| v.0 as i32)
413 .map_size(|v| if v <= 0 { 1 } else { v });
414
415 state.xdg_surface.set_window_geometry(
416 window_geometry.origin.x,
417 window_geometry.origin.y,
418 window_geometry.size.width,
419 window_geometry.size.height,
420 );
421
422 let request_frame_callback = !state.acknowledged_first_configure;
423 if request_frame_callback {
424 state.acknowledged_first_configure = true;
425 drop(state);
426 self.frame();
427 }
428 }
429 }
430
431 pub fn handle_toplevel_decoration_event(&self, event: zxdg_toplevel_decoration_v1::Event) {
432 if let zxdg_toplevel_decoration_v1::Event::Configure { mode } = event {
433 match mode {
434 WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
435 self.state.borrow_mut().decorations = WindowDecorations::Server;
436 if let Some(mut appearance_changed) =
437 self.callbacks.borrow_mut().appearance_changed.as_mut()
438 {
439 appearance_changed();
440 }
441 }
442 WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
443 self.state.borrow_mut().decorations = WindowDecorations::Client;
444 // Update background to be transparent
445 if let Some(mut appearance_changed) =
446 self.callbacks.borrow_mut().appearance_changed.as_mut()
447 {
448 appearance_changed();
449 }
450 }
451 WEnum::Value(_) => {
452 log::warn!("Unknown decoration mode");
453 }
454 WEnum::Unknown(v) => {
455 log::warn!("Unknown decoration mode: {}", v);
456 }
457 }
458 }
459 }
460
461 pub fn handle_fractional_scale_event(&self, event: wp_fractional_scale_v1::Event) {
462 if let wp_fractional_scale_v1::Event::PreferredScale { scale } = event {
463 self.rescale(scale as f32 / 120.0);
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.is_none_or(|size| size == state.bounds.size)
666 && scale.is_none_or(|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 && !fun(input.clone()).propagate
711 {
712 return;
713 }
714 if let PlatformInput::KeyDown(event) = input
715 && event.keystroke.modifiers.is_subset_of(&Modifiers::shift())
716 && let Some(key_char) = &event.keystroke.key_char
717 {
718 let mut state = self.state.borrow_mut();
719 if let Some(mut input_handler) = state.input_handler.take() {
720 drop(state);
721 input_handler.replace_text_in_range(None, key_char);
722 self.state.borrow_mut().input_handler = Some(input_handler);
723 }
724 }
725 }
726
727 pub fn set_focused(&self, focus: bool) {
728 self.state.borrow_mut().active = focus;
729 if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
730 fun(focus);
731 }
732 }
733
734 pub fn set_hovered(&self, focus: bool) {
735 if let Some(ref mut fun) = self.callbacks.borrow_mut().hover_status_change {
736 fun(focus);
737 }
738 }
739
740 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
741 self.state.borrow_mut().appearance = appearance;
742
743 let mut callbacks = self.callbacks.borrow_mut();
744 if let Some(ref mut fun) = callbacks.appearance_changed {
745 (fun)()
746 }
747 }
748
749 pub fn primary_output_scale(&self) -> i32 {
750 self.state.borrow_mut().primary_output_scale()
751 }
752}
753
754fn extract_states<'a, S: TryFrom<u32> + 'a>(states: &'a [u8]) -> impl Iterator<Item = S> + 'a
755where
756 <S as TryFrom<u32>>::Error: 'a,
757{
758 states
759 .chunks_exact(4)
760 .flat_map(TryInto::<[u8; 4]>::try_into)
761 .map(u32::from_ne_bytes)
762 .flat_map(S::try_from)
763}
764
765impl rwh::HasWindowHandle for WaylandWindow {
766 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
767 let surface = self.0.surface().id().as_ptr() as *mut libc::c_void;
768 let c_ptr = NonNull::new(surface).ok_or(rwh::HandleError::Unavailable)?;
769 let handle = rwh::WaylandWindowHandle::new(c_ptr);
770 let raw_handle = rwh::RawWindowHandle::Wayland(handle);
771 Ok(unsafe { rwh::WindowHandle::borrow_raw(raw_handle) })
772 }
773}
774
775impl rwh::HasDisplayHandle for WaylandWindow {
776 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
777 let display = self
778 .0
779 .surface()
780 .backend()
781 .upgrade()
782 .ok_or(rwh::HandleError::Unavailable)?
783 .display_ptr() as *mut libc::c_void;
784
785 let c_ptr = NonNull::new(display).ok_or(rwh::HandleError::Unavailable)?;
786 let handle = rwh::WaylandDisplayHandle::new(c_ptr);
787 let raw_handle = rwh::RawDisplayHandle::Wayland(handle);
788 Ok(unsafe { rwh::DisplayHandle::borrow_raw(raw_handle) })
789 }
790}
791
792impl PlatformWindow for WaylandWindow {
793 fn bounds(&self) -> Bounds<Pixels> {
794 self.borrow().bounds
795 }
796
797 fn is_maximized(&self) -> bool {
798 self.borrow().maximized
799 }
800
801 fn window_bounds(&self) -> WindowBounds {
802 let state = self.borrow();
803 if state.fullscreen {
804 WindowBounds::Fullscreen(state.window_bounds)
805 } else if state.maximized {
806 WindowBounds::Maximized(state.window_bounds)
807 } else {
808 drop(state);
809 WindowBounds::Windowed(self.bounds())
810 }
811 }
812
813 fn inner_window_bounds(&self) -> WindowBounds {
814 let state = self.borrow();
815 if state.fullscreen {
816 WindowBounds::Fullscreen(state.window_bounds)
817 } else if state.maximized {
818 WindowBounds::Maximized(state.window_bounds)
819 } else {
820 let inset = state.inset();
821 drop(state);
822 WindowBounds::Windowed(self.bounds().inset(inset))
823 }
824 }
825
826 fn content_size(&self) -> Size<Pixels> {
827 self.borrow().bounds.size
828 }
829
830 fn resize(&mut self, size: Size<Pixels>) {
831 let state = self.borrow();
832 let state_ptr = self.0.clone();
833 let dp_size = size.to_device_pixels(self.scale_factor());
834
835 state.xdg_surface.set_window_geometry(
836 state.bounds.origin.x.0 as i32,
837 state.bounds.origin.y.0 as i32,
838 dp_size.width.0,
839 dp_size.height.0,
840 );
841
842 state
843 .globals
844 .executor
845 .spawn(async move { state_ptr.resize(size) })
846 .detach();
847 }
848
849 fn scale_factor(&self) -> f32 {
850 self.borrow().scale
851 }
852
853 fn appearance(&self) -> WindowAppearance {
854 self.borrow().appearance
855 }
856
857 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
858 let state = self.borrow();
859 state.display.as_ref().map(|(id, display)| {
860 Rc::new(WaylandDisplay {
861 id: id.clone(),
862 name: display.name.clone(),
863 bounds: display.bounds.to_pixels(state.scale),
864 }) as Rc<dyn PlatformDisplay>
865 })
866 }
867
868 fn mouse_position(&self) -> Point<Pixels> {
869 self.borrow()
870 .client
871 .get_client()
872 .borrow()
873 .mouse_location
874 .unwrap_or_default()
875 }
876
877 fn modifiers(&self) -> Modifiers {
878 self.borrow().client.get_client().borrow().modifiers
879 }
880
881 fn capslock(&self) -> Capslock {
882 self.borrow().client.get_client().borrow().capslock
883 }
884
885 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
886 self.borrow_mut().input_handler = Some(input_handler);
887 }
888
889 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
890 self.borrow_mut().input_handler.take()
891 }
892
893 fn prompt(
894 &self,
895 _level: PromptLevel,
896 _msg: &str,
897 _detail: Option<&str>,
898 _answers: &[PromptButton],
899 ) -> Option<Receiver<usize>> {
900 None
901 }
902
903 fn activate(&self) {
904 // Try to request an activation token. Even though the activation is likely going to be rejected,
905 // KWin and Mutter can use the app_id to visually indicate we're requesting attention.
906 let state = self.borrow();
907 if let (Some(activation), Some(app_id)) = (&state.globals.activation, state.app_id.clone())
908 {
909 state.client.set_pending_activation(state.surface.id());
910 let token = activation.get_activation_token(&state.globals.qh, ());
911 // The serial isn't exactly important here, since the activation is probably going to be rejected anyway.
912 let serial = state.client.get_serial(SerialKind::MousePress);
913 token.set_app_id(app_id);
914 token.set_serial(serial, &state.globals.seat);
915 token.set_surface(&state.surface);
916 token.commit();
917 }
918 }
919
920 fn is_active(&self) -> bool {
921 self.borrow().active
922 }
923
924 fn is_hovered(&self) -> bool {
925 self.borrow().hovered
926 }
927
928 fn set_title(&mut self, title: &str) {
929 self.borrow().toplevel.set_title(title.to_string());
930 }
931
932 fn set_app_id(&mut self, app_id: &str) {
933 let mut state = self.borrow_mut();
934 state.toplevel.set_app_id(app_id.to_owned());
935 state.app_id = Some(app_id.to_owned());
936 }
937
938 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
939 let mut state = self.borrow_mut();
940 state.background_appearance = background_appearance;
941 update_window(state);
942 }
943
944 fn minimize(&self) {
945 self.borrow().toplevel.set_minimized();
946 }
947
948 fn zoom(&self) {
949 let state = self.borrow();
950 if !state.maximized {
951 state.toplevel.set_maximized();
952 } else {
953 state.toplevel.unset_maximized();
954 }
955 }
956
957 fn toggle_fullscreen(&self) {
958 let mut state = self.borrow_mut();
959 if !state.fullscreen {
960 state.toplevel.set_fullscreen(None);
961 } else {
962 state.toplevel.unset_fullscreen();
963 }
964 }
965
966 fn is_fullscreen(&self) -> bool {
967 self.borrow().fullscreen
968 }
969
970 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
971 self.0.callbacks.borrow_mut().request_frame = Some(callback);
972 }
973
974 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
975 self.0.callbacks.borrow_mut().input = Some(callback);
976 }
977
978 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
979 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
980 }
981
982 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
983 self.0.callbacks.borrow_mut().hover_status_change = Some(callback);
984 }
985
986 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
987 self.0.callbacks.borrow_mut().resize = Some(callback);
988 }
989
990 fn on_moved(&self, callback: Box<dyn FnMut()>) {
991 self.0.callbacks.borrow_mut().moved = Some(callback);
992 }
993
994 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
995 self.0.callbacks.borrow_mut().should_close = Some(callback);
996 }
997
998 fn on_close(&self, callback: Box<dyn FnOnce()>) {
999 self.0.callbacks.borrow_mut().close = Some(callback);
1000 }
1001
1002 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1003 }
1004
1005 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1006 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1007 }
1008
1009 fn draw(&self, scene: &Scene) {
1010 let mut state = self.borrow_mut();
1011 state.renderer.draw(scene);
1012 }
1013
1014 fn completed_frame(&self) {
1015 let state = self.borrow();
1016 state.surface.commit();
1017 }
1018
1019 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1020 let state = self.borrow();
1021 state.renderer.sprite_atlas().clone()
1022 }
1023
1024 fn show_window_menu(&self, position: Point<Pixels>) {
1025 let state = self.borrow();
1026 let serial = state.client.get_serial(SerialKind::MousePress);
1027 state.toplevel.show_window_menu(
1028 &state.globals.seat,
1029 serial,
1030 position.x.0 as i32,
1031 position.y.0 as i32,
1032 );
1033 }
1034
1035 fn start_window_move(&self) {
1036 let state = self.borrow();
1037 let serial = state.client.get_serial(SerialKind::MousePress);
1038 state.toplevel._move(&state.globals.seat, serial);
1039 }
1040
1041 fn start_window_resize(&self, edge: crate::ResizeEdge) {
1042 let state = self.borrow();
1043 state.toplevel.resize(
1044 &state.globals.seat,
1045 state.client.get_serial(SerialKind::MousePress),
1046 edge.to_xdg(),
1047 )
1048 }
1049
1050 fn window_decorations(&self) -> Decorations {
1051 let state = self.borrow();
1052 match state.decorations {
1053 WindowDecorations::Server => Decorations::Server,
1054 WindowDecorations::Client => Decorations::Client {
1055 tiling: state.tiling,
1056 },
1057 }
1058 }
1059
1060 fn request_decorations(&self, decorations: WindowDecorations) {
1061 let mut state = self.borrow_mut();
1062 state.decorations = decorations;
1063 if let Some(decoration) = state.decoration.as_ref() {
1064 decoration.set_mode(decorations.to_xdg());
1065 update_window(state);
1066 }
1067 }
1068
1069 fn window_controls(&self) -> WindowControls {
1070 self.borrow().window_controls
1071 }
1072
1073 fn set_client_inset(&self, inset: Pixels) {
1074 let mut state = self.borrow_mut();
1075 if Some(inset) != state.client_inset {
1076 state.client_inset = Some(inset);
1077 update_window(state);
1078 }
1079 }
1080
1081 fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
1082 let state = self.borrow();
1083 state.client.update_ime_position(bounds);
1084 }
1085
1086 fn gpu_specs(&self) -> Option<GpuSpecs> {
1087 self.borrow().renderer.gpu_specs().into()
1088 }
1089}
1090
1091fn update_window(mut state: RefMut<WaylandWindowState>) {
1092 let opaque = !state.is_transparent();
1093
1094 state.renderer.update_transparency(!opaque);
1095 let mut opaque_area = state.window_bounds.map(|v| v.0 as i32);
1096 opaque_area.inset(state.inset().0 as i32);
1097
1098 let region = state
1099 .globals
1100 .compositor
1101 .create_region(&state.globals.qh, ());
1102 region.add(
1103 opaque_area.origin.x,
1104 opaque_area.origin.y,
1105 opaque_area.size.width,
1106 opaque_area.size.height,
1107 );
1108
1109 // Note that rounded corners make this rectangle API hard to work with.
1110 // As this is common when using CSD, let's just disable this API.
1111 if state.background_appearance == WindowBackgroundAppearance::Opaque
1112 && state.decorations == WindowDecorations::Server
1113 {
1114 // Promise the compositor that this region of the window surface
1115 // contains no transparent pixels. This allows the compositor to skip
1116 // updating whatever is behind the surface for better performance.
1117 state.surface.set_opaque_region(Some(®ion));
1118 } else {
1119 state.surface.set_opaque_region(None);
1120 }
1121
1122 if let Some(ref blur_manager) = state.globals.blur_manager {
1123 if state.background_appearance == WindowBackgroundAppearance::Blurred {
1124 if state.blur.is_none() {
1125 let blur = blur_manager.create(&state.surface, &state.globals.qh, ());
1126 state.blur = Some(blur);
1127 }
1128 state.blur.as_ref().unwrap().commit();
1129 } else {
1130 // It probably doesn't hurt to clear the blur for opaque windows
1131 blur_manager.unset(&state.surface);
1132 if let Some(b) = state.blur.take() {
1133 b.release()
1134 }
1135 }
1136 }
1137
1138 region.destroy();
1139}
1140
1141impl WindowDecorations {
1142 fn to_xdg(self) -> zxdg_toplevel_decoration_v1::Mode {
1143 match self {
1144 WindowDecorations::Client => zxdg_toplevel_decoration_v1::Mode::ClientSide,
1145 WindowDecorations::Server => zxdg_toplevel_decoration_v1::Mode::ServerSide,
1146 }
1147 }
1148}
1149
1150impl ResizeEdge {
1151 fn to_xdg(self) -> xdg_toplevel::ResizeEdge {
1152 match self {
1153 ResizeEdge::Top => xdg_toplevel::ResizeEdge::Top,
1154 ResizeEdge::TopRight => xdg_toplevel::ResizeEdge::TopRight,
1155 ResizeEdge::Right => xdg_toplevel::ResizeEdge::Right,
1156 ResizeEdge::BottomRight => xdg_toplevel::ResizeEdge::BottomRight,
1157 ResizeEdge::Bottom => xdg_toplevel::ResizeEdge::Bottom,
1158 ResizeEdge::BottomLeft => xdg_toplevel::ResizeEdge::BottomLeft,
1159 ResizeEdge::Left => xdg_toplevel::ResizeEdge::Left,
1160 ResizeEdge::TopLeft => xdg_toplevel::ResizeEdge::TopLeft,
1161 }
1162 }
1163}
1164
1165/// The configuration event is in terms of the window geometry, which we are constantly
1166/// updating to account for the client decorations. But that's not the area we want to render
1167/// to, due to our intrusize CSD. So, here we calculate the 'actual' size, by adding back in the insets
1168fn compute_outer_size(
1169 inset: Pixels,
1170 new_size: Option<Size<Pixels>>,
1171 tiling: Tiling,
1172) -> Option<Size<Pixels>> {
1173 new_size.map(|mut new_size| {
1174 if !tiling.top {
1175 new_size.height += inset;
1176 }
1177 if !tiling.bottom {
1178 new_size.height += inset;
1179 }
1180 if !tiling.left {
1181 new_size.width += inset;
1182 }
1183 if !tiling.right {
1184 new_size.width += inset;
1185 }
1186
1187 new_size
1188 })
1189}
1190
1191fn inset_by_tiling(mut bounds: Bounds<Pixels>, inset: Pixels, tiling: Tiling) -> Bounds<Pixels> {
1192 if !tiling.top {
1193 bounds.origin.y += inset;
1194 bounds.size.height -= inset;
1195 }
1196 if !tiling.bottom {
1197 bounds.size.height -= inset;
1198 }
1199 if !tiling.left {
1200 bounds.origin.x += inset;
1201 bounds.size.width -= inset;
1202 }
1203 if !tiling.right {
1204 bounds.size.width -= inset;
1205 }
1206
1207 bounds
1208}