1use std::any::Any;
2use std::cell::{Ref, RefCell, RefMut};
3use std::ffi::c_void;
4use std::num::NonZeroU32;
5use std::ptr::NonNull;
6use std::rc::{Rc, Weak};
7use std::sync::Arc;
8
9use blade_graphics as gpu;
10use collections::{HashMap, HashSet};
11use futures::channel::oneshot::Receiver;
12use raw_window_handle as rwh;
13use wayland_backend::client::ObjectId;
14use wayland_client::WEnum;
15use wayland_client::{protocol::wl_surface, Proxy};
16use wayland_protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1;
17use wayland_protocols::wp::viewporter::client::wp_viewport;
18use wayland_protocols::xdg::decoration::zv1::client::zxdg_toplevel_decoration_v1;
19use wayland_protocols::xdg::shell::client::xdg_surface;
20use wayland_protocols::xdg::shell::client::xdg_toplevel::{self, WmCapabilities};
21
22use crate::platform::blade::BladeRenderer;
23use crate::platform::linux::wayland::display::WaylandDisplay;
24use crate::platform::{PlatformAtlas, PlatformInputHandler, PlatformWindow};
25use crate::scene::Scene;
26use crate::{
27 px, size, Bounds, DevicePixels, Globals, Modifiers, Pixels, PlatformDisplay, PlatformInput,
28 Point, PromptLevel, Size, WaylandClientState, WaylandClientStatePtr, WindowAppearance,
29 WindowBackgroundAppearance, WindowParams,
30};
31
32#[derive(Default)]
33pub(crate) struct Callbacks {
34 request_frame: Option<Box<dyn FnMut()>>,
35 input: Option<Box<dyn FnMut(crate::PlatformInput) -> crate::DispatchEventResult>>,
36 active_status_change: Option<Box<dyn FnMut(bool)>>,
37 resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
38 fullscreen: Option<Box<dyn FnMut(bool)>>,
39 moved: Option<Box<dyn FnMut()>>,
40 should_close: Option<Box<dyn FnMut() -> bool>>,
41 close: Option<Box<dyn FnOnce()>>,
42 appearance_changed: Option<Box<dyn FnMut()>>,
43}
44
45struct RawWindow {
46 window: *mut c_void,
47 display: *mut c_void,
48}
49
50impl rwh::HasWindowHandle for RawWindow {
51 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
52 let window = NonNull::new(self.window).unwrap();
53 let handle = rwh::WaylandWindowHandle::new(window);
54 Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
55 }
56}
57impl rwh::HasDisplayHandle for RawWindow {
58 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
59 let display = NonNull::new(self.display).unwrap();
60 let handle = rwh::WaylandDisplayHandle::new(display);
61 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
62 }
63}
64
65pub struct WaylandWindowState {
66 xdg_surface: xdg_surface::XdgSurface,
67 pub surface: wl_surface::WlSurface,
68 decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
69 toplevel: xdg_toplevel::XdgToplevel,
70 viewport: Option<wp_viewport::WpViewport>,
71 outputs: HashSet<ObjectId>,
72 globals: Globals,
73 renderer: BladeRenderer,
74 bounds: Bounds<u32>,
75 scale: f32,
76 input_handler: Option<PlatformInputHandler>,
77 decoration_state: WaylandDecorationState,
78 fullscreen: bool,
79 maximized: bool,
80 client: WaylandClientStatePtr,
81 callbacks: Callbacks,
82}
83
84#[derive(Clone)]
85pub struct WaylandWindowStatePtr {
86 state: Rc<RefCell<WaylandWindowState>>,
87 callbacks: Rc<RefCell<Callbacks>>,
88}
89
90impl WaylandWindowState {
91 #[allow(clippy::too_many_arguments)]
92 pub(crate) fn new(
93 surface: wl_surface::WlSurface,
94 xdg_surface: xdg_surface::XdgSurface,
95 toplevel: xdg_toplevel::XdgToplevel,
96 decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
97 viewport: Option<wp_viewport::WpViewport>,
98 client: WaylandClientStatePtr,
99 globals: Globals,
100 options: WindowParams,
101 ) -> Self {
102 let bounds = options.bounds.map(|p| p.0 as u32);
103
104 let raw = RawWindow {
105 window: surface.id().as_ptr().cast::<c_void>(),
106 display: surface
107 .backend()
108 .upgrade()
109 .unwrap()
110 .display_ptr()
111 .cast::<c_void>(),
112 };
113 let gpu = Arc::new(
114 unsafe {
115 gpu::Context::init_windowed(
116 &raw,
117 gpu::ContextDesc {
118 validation: false,
119 capture: false,
120 overlay: false,
121 },
122 )
123 }
124 .unwrap(),
125 );
126 let extent = gpu::Extent {
127 width: bounds.size.width,
128 height: bounds.size.height,
129 depth: 1,
130 };
131
132 Self {
133 xdg_surface,
134 surface,
135 decoration,
136 toplevel,
137 viewport,
138 globals,
139
140 outputs: HashSet::default(),
141
142 renderer: BladeRenderer::new(gpu, extent),
143 bounds,
144 scale: 1.0,
145 input_handler: None,
146 decoration_state: WaylandDecorationState::Client,
147 fullscreen: false,
148 maximized: false,
149 callbacks: Callbacks::default(),
150 client,
151 }
152 }
153}
154
155pub(crate) struct WaylandWindow(pub WaylandWindowStatePtr);
156
157impl Drop for WaylandWindow {
158 fn drop(&mut self) {
159 let mut state = self.0.state.borrow_mut();
160 let surface_id = state.surface.id();
161 let client = state.client.clone();
162
163 state.renderer.destroy();
164 if let Some(decoration) = &state.decoration {
165 decoration.destroy();
166 }
167 state.toplevel.destroy();
168 if let Some(viewport) = &state.viewport {
169 viewport.destroy();
170 }
171 state.xdg_surface.destroy();
172 state.surface.destroy();
173
174 let state_ptr = self.0.clone();
175 state
176 .globals
177 .executor
178 .spawn(async move {
179 state_ptr.close();
180 client.drop_window(&surface_id)
181 })
182 .detach();
183 drop(state);
184 }
185}
186
187impl WaylandWindow {
188 fn borrow(&self) -> Ref<WaylandWindowState> {
189 self.0.state.borrow()
190 }
191
192 fn borrow_mut(&self) -> RefMut<WaylandWindowState> {
193 self.0.state.borrow_mut()
194 }
195
196 pub fn new(
197 globals: Globals,
198 client: WaylandClientStatePtr,
199 params: WindowParams,
200 ) -> (Self, ObjectId) {
201 let surface = globals.compositor.create_surface(&globals.qh, ());
202 let xdg_surface = globals
203 .wm_base
204 .get_xdg_surface(&surface, &globals.qh, surface.id());
205 let toplevel = xdg_surface.get_toplevel(&globals.qh, surface.id());
206
207 if let Some(fractional_scale_manager) = globals.fractional_scale_manager.as_ref() {
208 fractional_scale_manager.get_fractional_scale(&surface, &globals.qh, surface.id());
209 }
210
211 // Attempt to set up window decorations based on the requested configuration
212 let decoration = globals
213 .decoration_manager
214 .as_ref()
215 .map(|decoration_manager| {
216 let decoration = decoration_manager.get_toplevel_decoration(
217 &toplevel,
218 &globals.qh,
219 surface.id(),
220 );
221 decoration.set_mode(zxdg_toplevel_decoration_v1::Mode::ClientSide);
222 decoration
223 });
224
225 let viewport = globals
226 .viewporter
227 .as_ref()
228 .map(|viewporter| viewporter.get_viewport(&surface, &globals.qh, ()));
229
230 surface.frame(&globals.qh, surface.id());
231
232 let this = Self(WaylandWindowStatePtr {
233 state: Rc::new(RefCell::new(WaylandWindowState::new(
234 surface.clone(),
235 xdg_surface,
236 toplevel,
237 decoration,
238 viewport,
239 client,
240 globals,
241 params,
242 ))),
243 callbacks: Rc::new(RefCell::new(Callbacks::default())),
244 });
245
246 // Kick things off
247 surface.commit();
248
249 (this, surface.id())
250 }
251}
252
253impl WaylandWindowStatePtr {
254 pub fn ptr_eq(&self, other: &Self) -> bool {
255 Rc::ptr_eq(&self.state, &other.state)
256 }
257
258 pub fn frame(&self, from_frame_callback: bool) {
259 if from_frame_callback {
260 let state = self.state.borrow_mut();
261 state.surface.frame(&state.globals.qh, state.surface.id());
262 drop(state);
263 }
264 let mut cb = self.callbacks.borrow_mut();
265 if let Some(fun) = cb.request_frame.as_mut() {
266 fun();
267 }
268 }
269
270 pub fn handle_xdg_surface_event(&self, event: xdg_surface::Event) {
271 match event {
272 xdg_surface::Event::Configure { serial } => {
273 let state = self.state.borrow();
274 state.xdg_surface.ack_configure(serial);
275 drop(state);
276 self.frame(false);
277 }
278 _ => {}
279 }
280 }
281
282 pub fn handle_toplevel_decoration_event(&self, event: zxdg_toplevel_decoration_v1::Event) {
283 match event {
284 zxdg_toplevel_decoration_v1::Event::Configure { mode } => match mode {
285 WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
286 self.set_decoration_state(WaylandDecorationState::Server)
287 }
288 WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
289 self.set_decoration_state(WaylandDecorationState::Server)
290 }
291 WEnum::Value(_) => {
292 log::warn!("Unknown decoration mode");
293 }
294 WEnum::Unknown(v) => {
295 log::warn!("Unknown decoration mode: {}", v);
296 }
297 },
298 _ => {}
299 }
300 }
301
302 pub fn handle_fractional_scale_event(&self, event: wp_fractional_scale_v1::Event) {
303 match event {
304 wp_fractional_scale_v1::Event::PreferredScale { scale } => {
305 self.rescale(scale as f32 / 120.0);
306 }
307 _ => {}
308 }
309 }
310
311 pub fn handle_toplevel_event(&self, event: xdg_toplevel::Event) -> bool {
312 match event {
313 xdg_toplevel::Event::Configure {
314 width,
315 height,
316 states,
317 } => {
318 let width = NonZeroU32::new(width as u32);
319 let height = NonZeroU32::new(height as u32);
320 let fullscreen = states.contains(&(xdg_toplevel::State::Fullscreen as u8));
321 let maximized = states.contains(&(xdg_toplevel::State::Maximized as u8));
322 self.resize(width, height);
323 self.set_fullscreen(fullscreen);
324 let mut state = self.state.borrow_mut();
325 state.maximized = true;
326
327 false
328 }
329 xdg_toplevel::Event::Close => {
330 let mut cb = self.callbacks.borrow_mut();
331 if let Some(mut should_close) = cb.should_close.take() {
332 let result = (should_close)();
333 cb.should_close = Some(should_close);
334 if result {
335 drop(cb);
336 self.close();
337 }
338 result
339 } else {
340 true
341 }
342 }
343 _ => false,
344 }
345 }
346
347 pub fn handle_surface_event(
348 &self,
349 event: wl_surface::Event,
350 output_scales: HashMap<ObjectId, i32>,
351 ) {
352 let mut state = self.state.borrow_mut();
353
354 // We use `WpFractionalScale` instead to set the scale if it's available
355 if state.globals.fractional_scale_manager.is_some() {
356 return;
357 }
358
359 match event {
360 wl_surface::Event::Enter { output } => {
361 // We use `PreferredBufferScale` instead to set the scale if it's available
362 if state.surface.version() >= wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
363 return;
364 }
365
366 state.outputs.insert(output.id());
367
368 let mut scale = 1;
369 for output in state.outputs.iter() {
370 if let Some(s) = output_scales.get(output) {
371 scale = scale.max(*s)
372 }
373 }
374
375 state.surface.set_buffer_scale(scale);
376 drop(state);
377 self.rescale(scale as f32);
378 }
379 wl_surface::Event::Leave { output } => {
380 // We use `PreferredBufferScale` instead to set the scale if it's available
381 if state.surface.version() >= wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
382 return;
383 }
384
385 state.outputs.remove(&output.id());
386
387 let mut scale = 1;
388 for output in state.outputs.iter() {
389 if let Some(s) = output_scales.get(output) {
390 scale = scale.max(*s)
391 }
392 }
393
394 state.surface.set_buffer_scale(scale);
395 drop(state);
396 self.rescale(scale as f32);
397 }
398 wl_surface::Event::PreferredBufferScale { factor } => {
399 state.surface.set_buffer_scale(factor);
400 drop(state);
401 self.rescale(factor as f32);
402 }
403 _ => {}
404 }
405 }
406
407 pub fn set_size_and_scale(
408 &self,
409 width: Option<NonZeroU32>,
410 height: Option<NonZeroU32>,
411 scale: Option<f32>,
412 ) {
413 let (width, height, scale) = {
414 let mut state = self.state.borrow_mut();
415 if width.map_or(true, |width| width.get() == state.bounds.size.width)
416 && height.map_or(true, |height| height.get() == state.bounds.size.height)
417 && scale.map_or(true, |scale| scale == state.scale)
418 {
419 return;
420 }
421 if let Some(width) = width {
422 state.bounds.size.width = width.get();
423 }
424 if let Some(height) = height {
425 state.bounds.size.height = height.get();
426 }
427 if let Some(scale) = scale {
428 state.scale = scale;
429 }
430 let width = state.bounds.size.width;
431 let height = state.bounds.size.height;
432 let scale = state.scale;
433 state.renderer.update_drawable_size(size(
434 width as f64 * scale as f64,
435 height as f64 * scale as f64,
436 ));
437 (width, height, scale)
438 };
439
440 if let Some(ref mut fun) = self.callbacks.borrow_mut().resize {
441 fun(
442 Size {
443 width: px(width as f32),
444 height: px(height as f32),
445 },
446 scale,
447 );
448 }
449
450 {
451 let state = self.state.borrow();
452 if let Some(viewport) = &state.viewport {
453 viewport.set_destination(width as i32, height as i32);
454 }
455 }
456 }
457
458 pub fn resize(&self, width: Option<NonZeroU32>, height: Option<NonZeroU32>) {
459 self.set_size_and_scale(width, height, None);
460 }
461
462 pub fn rescale(&self, scale: f32) {
463 self.set_size_and_scale(None, None, Some(scale));
464 }
465
466 pub fn set_fullscreen(&self, fullscreen: bool) {
467 let mut state = self.state.borrow_mut();
468 state.fullscreen = fullscreen;
469
470 let mut callbacks = self.callbacks.borrow_mut();
471 if let Some(ref mut fun) = callbacks.fullscreen {
472 fun(fullscreen)
473 }
474 }
475
476 /// Notifies the window of the state of the decorations.
477 ///
478 /// # Note
479 ///
480 /// This API is indirectly called by the wayland compositor and
481 /// not meant to be called by a user who wishes to change the state
482 /// of the decorations. This is because the state of the decorations
483 /// is managed by the compositor and not the client.
484 pub fn set_decoration_state(&self, state: WaylandDecorationState) {
485 self.state.borrow_mut().decoration_state = state;
486 }
487
488 pub fn close(&self) {
489 let mut callbacks = self.callbacks.borrow_mut();
490 if let Some(fun) = callbacks.close.take() {
491 fun()
492 }
493 }
494
495 pub fn handle_input(&self, input: PlatformInput) {
496 if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
497 if !fun(input.clone()).propagate {
498 return;
499 }
500 }
501 if let PlatformInput::KeyDown(event) = input {
502 if let Some(ime_key) = &event.keystroke.ime_key {
503 let mut state = self.state.borrow_mut();
504 if let Some(mut input_handler) = state.input_handler.take() {
505 drop(state);
506 input_handler.replace_text_in_range(None, ime_key);
507 self.state.borrow_mut().input_handler = Some(input_handler);
508 }
509 }
510 }
511 }
512
513 pub fn set_focused(&self, focus: bool) {
514 if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
515 fun(focus);
516 }
517 }
518}
519
520impl rwh::HasWindowHandle for WaylandWindow {
521 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
522 unimplemented!()
523 }
524}
525impl rwh::HasDisplayHandle for WaylandWindow {
526 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
527 unimplemented!()
528 }
529}
530
531impl PlatformWindow for WaylandWindow {
532 fn bounds(&self) -> Bounds<DevicePixels> {
533 self.borrow().bounds.map(|p| DevicePixels(p as i32))
534 }
535
536 fn is_maximized(&self) -> bool {
537 self.borrow().maximized
538 }
539
540 fn is_minimized(&self) -> bool {
541 // This cannot be determined by the client
542 false
543 }
544
545 fn content_size(&self) -> Size<Pixels> {
546 let state = self.borrow();
547 Size {
548 width: Pixels(state.bounds.size.width as f32),
549 height: Pixels(state.bounds.size.height as f32),
550 }
551 }
552
553 fn scale_factor(&self) -> f32 {
554 self.borrow().scale
555 }
556
557 // todo(linux)
558 fn appearance(&self) -> WindowAppearance {
559 WindowAppearance::Light
560 }
561
562 // todo(linux)
563 fn display(&self) -> Rc<dyn PlatformDisplay> {
564 Rc::new(WaylandDisplay {})
565 }
566
567 // todo(linux)
568 fn mouse_position(&self) -> Point<Pixels> {
569 Point::default()
570 }
571
572 // todo(linux)
573 fn modifiers(&self) -> Modifiers {
574 crate::Modifiers::default()
575 }
576
577 fn as_any_mut(&mut self) -> &mut dyn Any {
578 self
579 }
580
581 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
582 self.borrow_mut().input_handler = Some(input_handler);
583 }
584
585 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
586 self.borrow_mut().input_handler.take()
587 }
588
589 fn prompt(
590 &self,
591 level: PromptLevel,
592 msg: &str,
593 detail: Option<&str>,
594 answers: &[&str],
595 ) -> Option<Receiver<usize>> {
596 None
597 }
598
599 fn activate(&self) {
600 // todo(linux)
601 }
602
603 // todo(linux)
604 fn is_active(&self) -> bool {
605 false
606 }
607
608 fn set_title(&mut self, title: &str) {
609 self.borrow_mut().toplevel.set_title(title.to_string());
610 }
611
612 fn set_background_appearance(&mut self, _background_appearance: WindowBackgroundAppearance) {
613 // todo(linux)
614 }
615
616 fn set_edited(&mut self, edited: bool) {
617 // todo(linux)
618 }
619
620 fn show_character_palette(&self) {
621 // todo(linux)
622 }
623
624 fn minimize(&self) {
625 self.borrow_mut().toplevel.set_minimized();
626 }
627
628 fn zoom(&self) {
629 // todo(linux)
630 }
631
632 fn toggle_fullscreen(&self) {
633 let state = self.borrow_mut();
634 if !state.fullscreen {
635 state.toplevel.set_fullscreen(None);
636 } else {
637 state.toplevel.unset_fullscreen();
638 }
639 }
640
641 fn is_fullscreen(&self) -> bool {
642 self.borrow().fullscreen
643 }
644
645 fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
646 self.0.callbacks.borrow_mut().request_frame = Some(callback);
647 }
648
649 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
650 self.0.callbacks.borrow_mut().input = Some(callback);
651 }
652
653 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
654 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
655 }
656
657 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
658 self.0.callbacks.borrow_mut().resize = Some(callback);
659 }
660
661 fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
662 self.0.callbacks.borrow_mut().fullscreen = Some(callback);
663 }
664
665 fn on_moved(&self, callback: Box<dyn FnMut()>) {
666 self.0.callbacks.borrow_mut().moved = Some(callback);
667 }
668
669 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
670 self.0.callbacks.borrow_mut().should_close = Some(callback);
671 }
672
673 fn on_close(&self, callback: Box<dyn FnOnce()>) {
674 self.0.callbacks.borrow_mut().close = Some(callback);
675 }
676
677 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
678 // todo(linux)
679 }
680
681 // todo(linux)
682 fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
683 false
684 }
685
686 fn draw(&self, scene: &Scene) {
687 let mut state = self.borrow_mut();
688 state.renderer.draw(scene);
689 }
690
691 fn completed_frame(&self) {
692 let mut state = self.borrow_mut();
693 state.surface.commit();
694 }
695
696 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
697 let state = self.borrow();
698 state.renderer.sprite_atlas().clone()
699 }
700}
701
702#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
703pub enum WaylandDecorationState {
704 /// Decorations are to be provided by the client
705 Client,
706
707 /// Decorations are provided by the server
708 Server,
709}