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