1use std::any::Any;
2use std::ffi::c_void;
3use std::rc::Rc;
4use std::sync::Arc;
5
6use blade_graphics as gpu;
7use blade_rwh::{HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle};
8use futures::channel::oneshot::Receiver;
9use parking_lot::Mutex;
10use raw_window_handle::{
11 DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle,
12};
13use wayland_client::{protocol::wl_surface, Proxy};
14use wayland_protocols::wp::viewporter::client::wp_viewport;
15use wayland_protocols::xdg::shell::client::xdg_toplevel;
16
17use crate::platform::blade::BladeRenderer;
18use crate::platform::linux::wayland::display::WaylandDisplay;
19use crate::platform::{PlatformAtlas, PlatformInputHandler, PlatformWindow};
20use crate::scene::Scene;
21use crate::{
22 px, size, Bounds, Modifiers, Pixels, PlatformDisplay, PlatformInput, Point, PromptLevel, Size,
23 WindowAppearance, WindowBounds, WindowOptions,
24};
25
26#[derive(Default)]
27pub(crate) struct Callbacks {
28 request_frame: Option<Box<dyn FnMut()>>,
29 input: Option<Box<dyn FnMut(crate::PlatformInput) -> bool>>,
30 active_status_change: Option<Box<dyn FnMut(bool)>>,
31 resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
32 fullscreen: Option<Box<dyn FnMut(bool)>>,
33 moved: Option<Box<dyn FnMut()>>,
34 should_close: Option<Box<dyn FnMut() -> bool>>,
35 close: Option<Box<dyn FnOnce()>>,
36 appearance_changed: Option<Box<dyn FnMut()>>,
37}
38
39struct WaylandWindowInner {
40 renderer: BladeRenderer,
41 bounds: Bounds<i32>,
42 scale: f32,
43 input_handler: Option<PlatformInputHandler>,
44 decoration_state: WaylandDecorationState,
45}
46
47struct RawWindow {
48 window: *mut c_void,
49 display: *mut c_void,
50}
51
52unsafe impl HasRawWindowHandle for RawWindow {
53 fn raw_window_handle(&self) -> RawWindowHandle {
54 let mut wh = blade_rwh::WaylandWindowHandle::empty();
55 wh.surface = self.window;
56 wh.into()
57 }
58}
59
60unsafe impl HasRawDisplayHandle for RawWindow {
61 fn raw_display_handle(&self) -> RawDisplayHandle {
62 let mut dh = blade_rwh::WaylandDisplayHandle::empty();
63 dh.display = self.display;
64 dh.into()
65 }
66}
67
68impl WaylandWindowInner {
69 fn new(
70 conn: &Arc<wayland_client::Connection>,
71 wl_surf: &Arc<wl_surface::WlSurface>,
72 bounds: Bounds<i32>,
73 ) -> Self {
74 let raw = RawWindow {
75 window: wl_surf.id().as_ptr().cast::<c_void>(),
76 display: conn.backend().display_ptr().cast::<c_void>(),
77 };
78 let gpu = Arc::new(
79 unsafe {
80 gpu::Context::init_windowed(
81 &raw,
82 gpu::ContextDesc {
83 validation: false,
84 capture: false,
85 },
86 )
87 }
88 .unwrap(),
89 );
90 let extent = gpu::Extent {
91 width: bounds.size.width as u32,
92 height: bounds.size.height as u32,
93 depth: 1,
94 };
95 Self {
96 renderer: BladeRenderer::new(gpu, extent),
97 bounds,
98 scale: 1.0,
99 input_handler: None,
100
101 // On wayland, decorations are by default provided by the client
102 decoration_state: WaylandDecorationState::Client,
103 }
104 }
105}
106
107pub(crate) struct WaylandWindowState {
108 conn: Arc<wayland_client::Connection>,
109 inner: Mutex<WaylandWindowInner>,
110 pub(crate) callbacks: Mutex<Callbacks>,
111 pub(crate) surface: Arc<wl_surface::WlSurface>,
112 pub(crate) toplevel: Arc<xdg_toplevel::XdgToplevel>,
113 viewport: Option<wp_viewport::WpViewport>,
114}
115
116impl WaylandWindowState {
117 pub(crate) fn new(
118 conn: &Arc<wayland_client::Connection>,
119 wl_surf: Arc<wl_surface::WlSurface>,
120 viewport: Option<wp_viewport::WpViewport>,
121 toplevel: Arc<xdg_toplevel::XdgToplevel>,
122 options: WindowOptions,
123 ) -> Self {
124 if options.bounds == WindowBounds::Maximized {
125 toplevel.set_maximized();
126 } else if options.bounds == WindowBounds::Fullscreen {
127 toplevel.set_fullscreen(None);
128 }
129
130 let bounds: Bounds<i32> = match options.bounds {
131 WindowBounds::Fullscreen | WindowBounds::Maximized => Bounds {
132 origin: Point::default(),
133 size: Size {
134 width: 500,
135 height: 500,
136 }, //todo!(implement)
137 },
138 WindowBounds::Fixed(bounds) => bounds.map(|p| p.0 as i32),
139 };
140
141 Self {
142 conn: Arc::clone(conn),
143 surface: Arc::clone(&wl_surf),
144 inner: Mutex::new(WaylandWindowInner::new(&Arc::clone(conn), &wl_surf, bounds)),
145 callbacks: Mutex::new(Callbacks::default()),
146 toplevel,
147 viewport,
148 }
149 }
150
151 pub fn update(&self) {
152 let mut cb = self.callbacks.lock();
153 if let Some(mut fun) = cb.request_frame.take() {
154 drop(cb);
155 fun();
156 self.callbacks.lock().request_frame = Some(fun);
157 }
158 }
159
160 pub fn set_size_and_scale(&self, width: i32, height: i32, scale: f32) {
161 self.inner.lock().scale = scale;
162 self.inner.lock().bounds.size.width = width;
163 self.inner.lock().bounds.size.height = height;
164 self.inner.lock().renderer.update_drawable_size(size(
165 width as f64 * scale as f64,
166 height as f64 * scale as f64,
167 ));
168
169 if let Some(ref mut fun) = self.callbacks.lock().resize {
170 fun(
171 Size {
172 width: px(width as f32),
173 height: px(height as f32),
174 },
175 scale,
176 );
177 }
178
179 if let Some(viewport) = &self.viewport {
180 viewport.set_destination(width, height);
181 }
182 }
183
184 pub fn resize(&self, width: i32, height: i32) {
185 let scale = self.inner.lock().scale;
186 self.set_size_and_scale(width, height, scale);
187 }
188
189 pub fn rescale(&self, scale: f32) {
190 let bounds = self.inner.lock().bounds;
191 self.set_size_and_scale(bounds.size.width, bounds.size.height, scale)
192 }
193
194 /// Notifies the window of the state of the decorations.
195 ///
196 /// # Note
197 ///
198 /// This API is indirectly called by the wayland compositor and
199 /// not meant to be called by a user who wishes to change the state
200 /// of the decorations. This is because the state of the decorations
201 /// is managed by the compositor and not the client.
202 pub fn set_decoration_state(&self, state: WaylandDecorationState) {
203 self.inner.lock().decoration_state = state;
204 log::trace!("Window decorations are now handled by {:?}", state);
205 // todo!(linux) - Handle this properly
206 }
207
208 pub fn close(&self) {
209 let mut callbacks = self.callbacks.lock();
210 if let Some(fun) = callbacks.close.take() {
211 fun()
212 }
213 self.toplevel.destroy();
214 }
215
216 pub fn handle_input(&self, input: PlatformInput) {
217 if let Some(ref mut fun) = self.callbacks.lock().input {
218 if fun(input.clone()) {
219 return;
220 }
221 }
222 if let PlatformInput::KeyDown(event) = input {
223 let mut inner = self.inner.lock();
224 if let Some(ref mut input_handler) = inner.input_handler {
225 if let Some(ime_key) = &event.keystroke.ime_key {
226 input_handler.replace_text_in_range(None, ime_key);
227 }
228 }
229 }
230 }
231
232 pub fn set_focused(&self, focus: bool) {
233 if let Some(ref mut fun) = self.callbacks.lock().active_status_change {
234 fun(focus);
235 }
236 }
237}
238
239#[derive(Clone)]
240pub(crate) struct WaylandWindow(pub(crate) Rc<WaylandWindowState>);
241
242impl HasWindowHandle for WaylandWindow {
243 fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
244 unimplemented!()
245 }
246}
247
248impl HasDisplayHandle for WaylandWindow {
249 fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
250 unimplemented!()
251 }
252}
253
254impl PlatformWindow for WaylandWindow {
255 //todo!(linux)
256 fn bounds(&self) -> WindowBounds {
257 WindowBounds::Maximized
258 }
259
260 fn content_size(&self) -> Size<Pixels> {
261 let inner = self.0.inner.lock();
262 Size {
263 width: Pixels(inner.bounds.size.width as f32),
264 height: Pixels(inner.bounds.size.height as f32),
265 }
266 }
267
268 fn scale_factor(&self) -> f32 {
269 self.0.inner.lock().scale
270 }
271
272 //todo!(linux)
273 fn titlebar_height(&self) -> Pixels {
274 unimplemented!()
275 }
276
277 // todo!(linux)
278 fn appearance(&self) -> WindowAppearance {
279 WindowAppearance::Light
280 }
281
282 // todo!(linux)
283 fn display(&self) -> Rc<dyn PlatformDisplay> {
284 Rc::new(WaylandDisplay {})
285 }
286
287 // todo!(linux)
288 fn mouse_position(&self) -> Point<Pixels> {
289 Point::default()
290 }
291
292 //todo!(linux)
293 fn modifiers(&self) -> Modifiers {
294 crate::Modifiers::default()
295 }
296
297 //todo!(linux)
298 fn as_any_mut(&mut self) -> &mut dyn Any {
299 unimplemented!()
300 }
301
302 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
303 self.0.inner.lock().input_handler = Some(input_handler);
304 }
305
306 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
307 self.0.inner.lock().input_handler.take()
308 }
309
310 //todo!(linux)
311 fn prompt(
312 &self,
313 level: PromptLevel,
314 msg: &str,
315 detail: Option<&str>,
316 answers: &[&str],
317 ) -> Receiver<usize> {
318 unimplemented!()
319 }
320
321 fn activate(&self) {
322 //todo!(linux)
323 }
324
325 fn set_title(&mut self, title: &str) {
326 self.0.toplevel.set_title(title.to_string());
327 }
328
329 fn set_edited(&mut self, edited: bool) {
330 //todo!(linux)
331 }
332
333 fn show_character_palette(&self) {
334 //todo!(linux)
335 }
336
337 fn minimize(&self) {
338 //todo!(linux)
339 }
340
341 fn zoom(&self) {
342 //todo!(linux)
343 }
344
345 fn toggle_full_screen(&self) {
346 //todo!(linux)
347 }
348
349 fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
350 self.0.callbacks.lock().request_frame = Some(callback);
351 }
352
353 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
354 self.0.callbacks.lock().input = Some(callback);
355 }
356
357 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
358 self.0.callbacks.lock().active_status_change = Some(callback);
359 }
360
361 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
362 self.0.callbacks.lock().resize = Some(callback);
363 }
364
365 fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
366 //todo!(linux)
367 }
368
369 fn on_moved(&self, callback: Box<dyn FnMut()>) {
370 self.0.callbacks.lock().moved = Some(callback);
371 }
372
373 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
374 self.0.callbacks.lock().should_close = Some(callback);
375 }
376
377 fn on_close(&self, callback: Box<dyn FnOnce()>) {
378 self.0.callbacks.lock().close = Some(callback);
379 }
380
381 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
382 //todo!(linux)
383 }
384
385 // todo!(linux)
386 fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
387 false
388 }
389
390 fn draw(&self, scene: &Scene) {
391 let mut inner = self.0.inner.lock();
392 inner.renderer.draw(scene);
393 }
394
395 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
396 let inner = self.0.inner.lock();
397 inner.renderer.sprite_atlas().clone()
398 }
399
400 fn set_graphics_profiler_enabled(&self, enabled: bool) {
401 //todo!(linux)
402 }
403}
404
405#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
406pub enum WaylandDecorationState {
407 /// Decorations are to be provided by the client
408 Client,
409
410 /// Decorations are provided by the server
411 Server,
412}