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