window.rs

  1use std::cell::{Ref, RefCell, RefMut};
  2use std::ffi::c_void;
  3use std::num::NonZeroU32;
  4use std::ptr::NonNull;
  5use std::rc::Rc;
  6use std::sync::Arc;
  7
  8use blade_graphics as gpu;
  9use collections::HashMap;
 10use futures::channel::oneshot::Receiver;
 11
 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};
 21use wayland_protocols_plasma::blur::client::org_kde_kwin_blur;
 22
 23use crate::platform::blade::{BladeRenderer, BladeSurfaceConfig};
 24use crate::platform::linux::wayland::display::WaylandDisplay;
 25use crate::platform::linux::wayland::serial::SerialKind;
 26use crate::platform::{PlatformAtlas, PlatformInputHandler, PlatformWindow};
 27use crate::scene::Scene;
 28use crate::{
 29    px, size, AnyWindowHandle, Bounds, DevicePixels, Globals, Modifiers, Output, Pixels,
 30    PlatformDisplay, PlatformInput, Point, PromptLevel, Size, WaylandClientStatePtr,
 31    WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowParams,
 32};
 33
 34#[derive(Default)]
 35pub(crate) struct Callbacks {
 36    request_frame: Option<Box<dyn FnMut()>>,
 37    input: Option<Box<dyn FnMut(crate::PlatformInput) -> crate::DispatchEventResult>>,
 38    active_status_change: Option<Box<dyn FnMut(bool)>>,
 39    resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 40    moved: Option<Box<dyn FnMut()>>,
 41    should_close: Option<Box<dyn FnMut() -> bool>>,
 42    close: Option<Box<dyn FnOnce()>>,
 43    appearance_changed: Option<Box<dyn FnMut()>>,
 44}
 45
 46struct RawWindow {
 47    window: *mut c_void,
 48    display: *mut c_void,
 49}
 50
 51impl rwh::HasWindowHandle for RawWindow {
 52    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 53        let window = NonNull::new(self.window).unwrap();
 54        let handle = rwh::WaylandWindowHandle::new(window);
 55        Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
 56    }
 57}
 58impl rwh::HasDisplayHandle for RawWindow {
 59    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 60        let display = NonNull::new(self.display).unwrap();
 61        let handle = rwh::WaylandDisplayHandle::new(display);
 62        Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
 63    }
 64}
 65
 66pub struct WaylandWindowState {
 67    xdg_surface: xdg_surface::XdgSurface,
 68    acknowledged_first_configure: bool,
 69    pub surface: wl_surface::WlSurface,
 70    decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
 71    appearance: WindowAppearance,
 72    blur: Option<org_kde_kwin_blur::OrgKdeKwinBlur>,
 73    toplevel: xdg_toplevel::XdgToplevel,
 74    viewport: Option<wp_viewport::WpViewport>,
 75    outputs: HashMap<ObjectId, Output>,
 76    display: Option<(ObjectId, Output)>,
 77    globals: Globals,
 78    renderer: BladeRenderer,
 79    bounds: Bounds<u32>,
 80    scale: f32,
 81    input_handler: Option<PlatformInputHandler>,
 82    decoration_state: WaylandDecorationState,
 83    fullscreen: bool,
 84    restore_bounds: Bounds<DevicePixels>,
 85    maximized: bool,
 86    client: WaylandClientStatePtr,
 87    handle: AnyWindowHandle,
 88    active: bool,
 89}
 90
 91#[derive(Clone)]
 92pub struct WaylandWindowStatePtr {
 93    state: Rc<RefCell<WaylandWindowState>>,
 94    callbacks: Rc<RefCell<Callbacks>>,
 95}
 96
 97impl WaylandWindowState {
 98    #[allow(clippy::too_many_arguments)]
 99    pub(crate) fn new(
100        handle: AnyWindowHandle,
101        surface: wl_surface::WlSurface,
102        xdg_surface: xdg_surface::XdgSurface,
103        toplevel: xdg_toplevel::XdgToplevel,
104        decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
105        appearance: WindowAppearance,
106        viewport: Option<wp_viewport::WpViewport>,
107        client: WaylandClientStatePtr,
108        globals: Globals,
109        options: WindowParams,
110    ) -> Self {
111        let bounds = options.bounds.map(|p| p.0 as u32);
112
113        let raw = RawWindow {
114            window: surface.id().as_ptr().cast::<c_void>(),
115            display: surface
116                .backend()
117                .upgrade()
118                .unwrap()
119                .display_ptr()
120                .cast::<c_void>(),
121        };
122        let gpu = Arc::new(
123            unsafe {
124                gpu::Context::init_windowed(
125                    &raw,
126                    gpu::ContextDesc {
127                        validation: false,
128                        capture: false,
129                        overlay: false,
130                    },
131                )
132            }
133            .unwrap(),
134        );
135        let config = BladeSurfaceConfig {
136            size: gpu::Extent {
137                width: bounds.size.width,
138                height: bounds.size.height,
139                depth: 1,
140            },
141            transparent: options.window_background != WindowBackgroundAppearance::Opaque,
142        };
143
144        Self {
145            xdg_surface,
146            acknowledged_first_configure: false,
147            surface,
148            decoration,
149            blur: None,
150            toplevel,
151            viewport,
152            globals,
153            outputs: HashMap::default(),
154            display: None,
155            renderer: BladeRenderer::new(gpu, config),
156            bounds,
157            scale: 1.0,
158            input_handler: None,
159            decoration_state: WaylandDecorationState::Client,
160            fullscreen: false,
161            restore_bounds: Bounds::default(),
162            maximized: false,
163            client,
164            appearance,
165            handle,
166            active: false,
167        }
168    }
169}
170
171pub(crate) struct WaylandWindow(pub WaylandWindowStatePtr);
172pub enum ImeInput {
173    InsertText(String),
174    SetMarkedText(String),
175    UnmarkText,
176    DeleteText,
177}
178
179impl Drop for WaylandWindow {
180    fn drop(&mut self) {
181        let mut state = self.0.state.borrow_mut();
182        let surface_id = state.surface.id();
183        let client = state.client.clone();
184
185        state.renderer.destroy();
186        if let Some(decoration) = &state.decoration {
187            decoration.destroy();
188        }
189        if let Some(blur) = &state.blur {
190            blur.release();
191        }
192        state.toplevel.destroy();
193        if let Some(viewport) = &state.viewport {
194            viewport.destroy();
195        }
196        state.xdg_surface.destroy();
197        state.surface.destroy();
198
199        let state_ptr = self.0.clone();
200        state
201            .globals
202            .executor
203            .spawn(async move {
204                state_ptr.close();
205                client.drop_window(&surface_id)
206            })
207            .detach();
208        drop(state);
209    }
210}
211
212impl WaylandWindow {
213    fn borrow(&self) -> Ref<WaylandWindowState> {
214        self.0.state.borrow()
215    }
216
217    fn borrow_mut(&self) -> RefMut<WaylandWindowState> {
218        self.0.state.borrow_mut()
219    }
220
221    pub fn new(
222        handle: AnyWindowHandle,
223        globals: Globals,
224        client: WaylandClientStatePtr,
225        params: WindowParams,
226        appearance: WindowAppearance,
227    ) -> (Self, ObjectId) {
228        let surface = globals.compositor.create_surface(&globals.qh, ());
229        let xdg_surface = globals
230            .wm_base
231            .get_xdg_surface(&surface, &globals.qh, surface.id());
232        let toplevel = xdg_surface.get_toplevel(&globals.qh, surface.id());
233
234        if let Some(fractional_scale_manager) = globals.fractional_scale_manager.as_ref() {
235            fractional_scale_manager.get_fractional_scale(&surface, &globals.qh, surface.id());
236        }
237
238        // Attempt to set up window decorations based on the requested configuration
239        let decoration = globals
240            .decoration_manager
241            .as_ref()
242            .map(|decoration_manager| {
243                let decoration = decoration_manager.get_toplevel_decoration(
244                    &toplevel,
245                    &globals.qh,
246                    surface.id(),
247                );
248                decoration.set_mode(zxdg_toplevel_decoration_v1::Mode::ClientSide);
249                decoration
250            });
251
252        let viewport = globals
253            .viewporter
254            .as_ref()
255            .map(|viewporter| viewporter.get_viewport(&surface, &globals.qh, ()));
256
257        let this = Self(WaylandWindowStatePtr {
258            state: Rc::new(RefCell::new(WaylandWindowState::new(
259                handle,
260                surface.clone(),
261                xdg_surface,
262                toplevel,
263                decoration,
264                appearance,
265                viewport,
266                client,
267                globals,
268                params,
269            ))),
270            callbacks: Rc::new(RefCell::new(Callbacks::default())),
271        });
272
273        // Kick things off
274        surface.commit();
275
276        (this, surface.id())
277    }
278}
279
280impl WaylandWindowStatePtr {
281    pub fn handle(&self) -> AnyWindowHandle {
282        self.state.borrow().handle
283    }
284
285    pub fn surface(&self) -> wl_surface::WlSurface {
286        self.state.borrow().surface.clone()
287    }
288
289    pub fn ptr_eq(&self, other: &Self) -> bool {
290        Rc::ptr_eq(&self.state, &other.state)
291    }
292
293    pub fn frame(&self, request_frame_callback: bool) {
294        if request_frame_callback {
295            let state = self.state.borrow_mut();
296            state.surface.frame(&state.globals.qh, state.surface.id());
297            drop(state);
298        }
299        let mut cb = self.callbacks.borrow_mut();
300        if let Some(fun) = cb.request_frame.as_mut() {
301            fun();
302        }
303    }
304
305    pub fn handle_xdg_surface_event(&self, event: xdg_surface::Event) {
306        match event {
307            xdg_surface::Event::Configure { serial } => {
308                let mut state = self.state.borrow_mut();
309                state.xdg_surface.ack_configure(serial);
310                let request_frame_callback = !state.acknowledged_first_configure;
311                state.acknowledged_first_configure = true;
312                drop(state);
313                self.frame(request_frame_callback);
314            }
315            _ => {}
316        }
317    }
318
319    pub fn handle_toplevel_decoration_event(&self, event: zxdg_toplevel_decoration_v1::Event) {
320        match event {
321            zxdg_toplevel_decoration_v1::Event::Configure { mode } => match mode {
322                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
323                    self.set_decoration_state(WaylandDecorationState::Server)
324                }
325                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
326                    self.set_decoration_state(WaylandDecorationState::Client)
327                }
328                WEnum::Value(_) => {
329                    log::warn!("Unknown decoration mode");
330                }
331                WEnum::Unknown(v) => {
332                    log::warn!("Unknown decoration mode: {}", v);
333                }
334            },
335            _ => {}
336        }
337    }
338
339    pub fn handle_fractional_scale_event(&self, event: wp_fractional_scale_v1::Event) {
340        match event {
341            wp_fractional_scale_v1::Event::PreferredScale { scale } => {
342                self.rescale(scale as f32 / 120.0);
343            }
344            _ => {}
345        }
346    }
347
348    pub fn handle_toplevel_event(&self, event: xdg_toplevel::Event) -> bool {
349        match event {
350            xdg_toplevel::Event::Configure {
351                width,
352                height,
353                states,
354            } => {
355                let width = NonZeroU32::new(width as u32);
356                let height = NonZeroU32::new(height as u32);
357                let fullscreen = states.contains(&(xdg_toplevel::State::Fullscreen as u8));
358                let maximized = states.contains(&(xdg_toplevel::State::Maximized as u8));
359                let mut state = self.state.borrow_mut();
360                state.maximized = maximized;
361                state.fullscreen = fullscreen;
362                if fullscreen || maximized {
363                    state.restore_bounds = state.bounds.map(|p| DevicePixels(p as i32));
364                }
365                drop(state);
366                self.resize(width, height);
367                self.set_fullscreen(fullscreen);
368
369                false
370            }
371            xdg_toplevel::Event::Close => {
372                let mut cb = self.callbacks.borrow_mut();
373                if let Some(mut should_close) = cb.should_close.take() {
374                    let result = (should_close)();
375                    cb.should_close = Some(should_close);
376                    if result {
377                        drop(cb);
378                        self.close();
379                    }
380                    result
381                } else {
382                    true
383                }
384            }
385            _ => false,
386        }
387    }
388
389    pub fn handle_surface_event(
390        &self,
391        event: wl_surface::Event,
392        outputs: HashMap<ObjectId, Output>,
393    ) {
394        let mut state = self.state.borrow_mut();
395
396        // We use `WpFractionalScale` instead to set the scale if it's available
397        if state.globals.fractional_scale_manager.is_some() {
398            return;
399        }
400
401        match event {
402            wl_surface::Event::Enter { output } => {
403                // We use `PreferredBufferScale` instead to set the scale if it's available
404                if state.surface.version() >= wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
405                    return;
406                }
407                let id = output.id();
408
409                let Some(output) = outputs.get(&id) else {
410                    return;
411                };
412
413                state.outputs.insert(id, *output);
414
415                let scale = primary_output_scale(&mut state);
416
417                state.surface.set_buffer_scale(scale);
418                drop(state);
419                self.rescale(scale as f32);
420            }
421            wl_surface::Event::Leave { output } => {
422                // We use `PreferredBufferScale` instead to set the scale if it's available
423                if state.surface.version() >= wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
424                    return;
425                }
426
427                state.outputs.remove(&output.id());
428
429                let scale = primary_output_scale(&mut state);
430
431                state.surface.set_buffer_scale(scale);
432                drop(state);
433                self.rescale(scale as f32);
434            }
435            wl_surface::Event::PreferredBufferScale { factor } => {
436                state.surface.set_buffer_scale(factor);
437                drop(state);
438                self.rescale(factor as f32);
439            }
440            _ => {}
441        }
442    }
443
444    pub fn handle_ime(&self, ime: ImeInput) {
445        let mut state = self.state.borrow_mut();
446        if let Some(mut input_handler) = state.input_handler.take() {
447            drop(state);
448            match ime {
449                ImeInput::InsertText(text) => {
450                    input_handler.replace_text_in_range(None, &text);
451                }
452                ImeInput::SetMarkedText(text) => {
453                    input_handler.replace_and_mark_text_in_range(None, &text, None);
454                }
455                ImeInput::UnmarkText => {
456                    input_handler.unmark_text();
457                }
458                ImeInput::DeleteText => {
459                    if let Some(marked) = input_handler.marked_text_range() {
460                        input_handler.replace_text_in_range(Some(marked), "");
461                    }
462                }
463            }
464            self.state.borrow_mut().input_handler = Some(input_handler);
465        }
466    }
467
468    pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
469        let mut state = self.state.borrow_mut();
470        let mut bounds: Option<Bounds<Pixels>> = None;
471        if let Some(mut input_handler) = state.input_handler.take() {
472            drop(state);
473            if let Some(range) = input_handler.selected_text_range() {
474                bounds = input_handler.bounds_for_range(range);
475            }
476            self.state.borrow_mut().input_handler = Some(input_handler);
477        }
478        bounds
479    }
480
481    pub fn set_size_and_scale(
482        &self,
483        width: Option<NonZeroU32>,
484        height: Option<NonZeroU32>,
485        scale: Option<f32>,
486    ) {
487        let (width, height, scale) = {
488            let mut state = self.state.borrow_mut();
489            if width.map_or(true, |width| width.get() == state.bounds.size.width)
490                && height.map_or(true, |height| height.get() == state.bounds.size.height)
491                && scale.map_or(true, |scale| scale == state.scale)
492            {
493                return;
494            }
495            if let Some(width) = width {
496                state.bounds.size.width = width.get();
497            }
498            if let Some(height) = height {
499                state.bounds.size.height = height.get();
500            }
501            if let Some(scale) = scale {
502                state.scale = scale;
503            }
504            let width = state.bounds.size.width;
505            let height = state.bounds.size.height;
506            let scale = state.scale;
507            state.renderer.update_drawable_size(size(
508                width as f64 * scale as f64,
509                height as f64 * scale as f64,
510            ));
511            (width, height, scale)
512        };
513
514        if let Some(ref mut fun) = self.callbacks.borrow_mut().resize {
515            fun(
516                Size {
517                    width: px(width as f32),
518                    height: px(height as f32),
519                },
520                scale,
521            );
522        }
523
524        {
525            let state = self.state.borrow();
526            if let Some(viewport) = &state.viewport {
527                viewport.set_destination(width as i32, height as i32);
528            }
529        }
530    }
531
532    pub fn resize(&self, width: Option<NonZeroU32>, height: Option<NonZeroU32>) {
533        self.set_size_and_scale(width, height, None);
534    }
535
536    pub fn rescale(&self, scale: f32) {
537        self.set_size_and_scale(None, None, Some(scale));
538    }
539
540    pub fn set_fullscreen(&self, fullscreen: bool) {
541        let mut state = self.state.borrow_mut();
542        state.fullscreen = fullscreen;
543    }
544
545    /// Notifies the window of the state of the decorations.
546    ///
547    /// # Note
548    ///
549    /// This API is indirectly called by the wayland compositor and
550    /// not meant to be called by a user who wishes to change the state
551    /// of the decorations. This is because the state of the decorations
552    /// is managed by the compositor and not the client.
553    pub fn set_decoration_state(&self, state: WaylandDecorationState) {
554        self.state.borrow_mut().decoration_state = state;
555    }
556
557    pub fn close(&self) {
558        let mut callbacks = self.callbacks.borrow_mut();
559        if let Some(fun) = callbacks.close.take() {
560            fun()
561        }
562    }
563
564    pub fn handle_input(&self, input: PlatformInput) {
565        if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
566            if !fun(input.clone()).propagate {
567                return;
568            }
569        }
570        if let PlatformInput::KeyDown(event) = input {
571            if let Some(ime_key) = &event.keystroke.ime_key {
572                let mut state = self.state.borrow_mut();
573                if let Some(mut input_handler) = state.input_handler.take() {
574                    drop(state);
575                    input_handler.replace_text_in_range(None, ime_key);
576                    self.state.borrow_mut().input_handler = Some(input_handler);
577                }
578            }
579        }
580    }
581
582    pub fn set_focused(&self, focus: bool) {
583        self.state.borrow_mut().active = focus;
584        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
585            fun(focus);
586        }
587    }
588
589    pub fn set_appearance(&mut self, appearance: WindowAppearance) {
590        self.state.borrow_mut().appearance = appearance;
591
592        let mut callbacks = self.callbacks.borrow_mut();
593        if let Some(ref mut fun) = callbacks.appearance_changed {
594            (fun)()
595        }
596    }
597}
598
599fn primary_output_scale(state: &mut RefMut<WaylandWindowState>) -> i32 {
600    let mut scale = 1;
601    let mut current_output = state.display.take();
602    for (id, output) in state.outputs.iter() {
603        if let Some((_, output_data)) = &current_output {
604            if output.scale > output_data.scale {
605                current_output = Some((id.clone(), *output));
606            }
607        } else {
608            current_output = Some((id.clone(), *output));
609        }
610        scale = scale.max(output.scale);
611    }
612    state.display = current_output;
613    scale
614}
615
616impl rwh::HasWindowHandle for WaylandWindow {
617    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
618        unimplemented!()
619    }
620}
621impl rwh::HasDisplayHandle for WaylandWindow {
622    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
623        unimplemented!()
624    }
625}
626
627impl PlatformWindow for WaylandWindow {
628    fn bounds(&self) -> Bounds<DevicePixels> {
629        self.borrow().bounds.map(|p| DevicePixels(p as i32))
630    }
631
632    fn is_maximized(&self) -> bool {
633        self.borrow().maximized
634    }
635
636    fn window_bounds(&self) -> WindowBounds {
637        let state = self.borrow();
638        if state.fullscreen {
639            WindowBounds::Fullscreen(state.restore_bounds)
640        } else if state.maximized {
641            WindowBounds::Maximized(state.restore_bounds)
642        } else {
643            WindowBounds::Windowed(state.bounds.map(|p| DevicePixels(p as i32)))
644        }
645    }
646
647    fn content_size(&self) -> Size<Pixels> {
648        let state = self.borrow();
649        Size {
650            width: Pixels(state.bounds.size.width as f32),
651            height: Pixels(state.bounds.size.height as f32),
652        }
653    }
654
655    fn scale_factor(&self) -> f32 {
656        self.borrow().scale
657    }
658
659    fn appearance(&self) -> WindowAppearance {
660        self.borrow().appearance
661    }
662
663    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
664        self.borrow().display.as_ref().map(|(id, display)| {
665            Rc::new(WaylandDisplay {
666                id: id.clone(),
667                bounds: display.bounds,
668            }) as Rc<dyn PlatformDisplay>
669        })
670    }
671
672    fn mouse_position(&self) -> Point<Pixels> {
673        self.borrow()
674            .client
675            .get_client()
676            .borrow()
677            .mouse_location
678            .unwrap_or_default()
679    }
680
681    fn modifiers(&self) -> Modifiers {
682        self.borrow().client.get_client().borrow().modifiers
683    }
684
685    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
686        self.borrow_mut().input_handler = Some(input_handler);
687    }
688
689    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
690        self.borrow_mut().input_handler.take()
691    }
692
693    fn prompt(
694        &self,
695        _level: PromptLevel,
696        _msg: &str,
697        _detail: Option<&str>,
698        _answers: &[&str],
699    ) -> Option<Receiver<usize>> {
700        None
701    }
702
703    fn activate(&self) {
704        log::info!("Wayland does not support this API");
705    }
706
707    fn is_active(&self) -> bool {
708        self.borrow().active
709    }
710
711    fn set_title(&mut self, title: &str) {
712        self.borrow().toplevel.set_title(title.to_string());
713    }
714
715    fn set_app_id(&mut self, app_id: &str) {
716        self.borrow().toplevel.set_app_id(app_id.to_owned());
717    }
718
719    fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
720        let opaque = background_appearance == WindowBackgroundAppearance::Opaque;
721        let mut state = self.borrow_mut();
722        state.renderer.update_transparency(!opaque);
723
724        let region = state
725            .globals
726            .compositor
727            .create_region(&state.globals.qh, ());
728        region.add(0, 0, i32::MAX, i32::MAX);
729
730        if opaque {
731            // Promise the compositor that this region of the window surface
732            // contains no transparent pixels. This allows the compositor to
733            // do skip whatever is behind the surface for better performance.
734            state.surface.set_opaque_region(Some(&region));
735        } else {
736            state.surface.set_opaque_region(None);
737        }
738
739        if let Some(ref blur_manager) = state.globals.blur_manager {
740            if background_appearance == WindowBackgroundAppearance::Blurred {
741                if state.blur.is_none() {
742                    let blur = blur_manager.create(&state.surface, &state.globals.qh, ());
743                    blur.set_region(Some(&region));
744                    state.blur = Some(blur);
745                }
746                state.blur.as_ref().unwrap().commit();
747            } else {
748                // It probably doesn't hurt to clear the blur for opaque windows
749                blur_manager.unset(&state.surface);
750                if let Some(b) = state.blur.take() {
751                    b.release()
752                }
753            }
754        }
755
756        region.destroy();
757    }
758
759    fn set_edited(&mut self, _edited: bool) {
760        log::info!("ignoring macOS specific set_edited");
761    }
762
763    fn show_character_palette(&self) {
764        log::info!("ignoring macOS specific show_character_palette");
765    }
766
767    fn minimize(&self) {
768        self.borrow().toplevel.set_minimized();
769    }
770
771    fn zoom(&self) {
772        let state = self.borrow();
773        if !state.maximized {
774            state.toplevel.set_maximized();
775        } else {
776            state.toplevel.unset_maximized();
777        }
778    }
779
780    fn toggle_fullscreen(&self) {
781        let mut state = self.borrow_mut();
782        state.restore_bounds = state.bounds.map(|p| DevicePixels(p as i32));
783        if !state.fullscreen {
784            state.toplevel.set_fullscreen(None);
785        } else {
786            state.toplevel.unset_fullscreen();
787        }
788    }
789
790    fn is_fullscreen(&self) -> bool {
791        self.borrow().fullscreen
792    }
793
794    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
795        self.0.callbacks.borrow_mut().request_frame = Some(callback);
796    }
797
798    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
799        self.0.callbacks.borrow_mut().input = Some(callback);
800    }
801
802    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
803        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
804    }
805
806    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
807        self.0.callbacks.borrow_mut().resize = Some(callback);
808    }
809
810    fn on_moved(&self, callback: Box<dyn FnMut()>) {
811        self.0.callbacks.borrow_mut().moved = Some(callback);
812    }
813
814    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
815        self.0.callbacks.borrow_mut().should_close = Some(callback);
816    }
817
818    fn on_close(&self, callback: Box<dyn FnOnce()>) {
819        self.0.callbacks.borrow_mut().close = Some(callback);
820    }
821
822    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
823        self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
824    }
825
826    fn draw(&self, scene: &Scene) {
827        let mut state = self.borrow_mut();
828        state.renderer.draw(scene);
829    }
830
831    fn completed_frame(&self) {
832        let mut state = self.borrow_mut();
833        state.surface.commit();
834    }
835
836    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
837        let state = self.borrow();
838        state.renderer.sprite_atlas().clone()
839    }
840
841    fn show_window_menu(&self, position: Point<Pixels>) {
842        let state = self.borrow();
843        let serial = state.client.get_serial(SerialKind::MousePress);
844        state.toplevel.show_window_menu(
845            &state.globals.seat,
846            serial,
847            position.x.0 as i32,
848            position.y.0 as i32,
849        );
850    }
851
852    fn start_system_move(&self) {
853        let state = self.borrow();
854        let serial = state.client.get_serial(SerialKind::MousePress);
855        state.toplevel._move(&state.globals.seat, serial);
856    }
857
858    fn should_render_window_controls(&self) -> bool {
859        self.borrow().decoration_state == WaylandDecorationState::Client
860    }
861}
862
863#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
864pub enum WaylandDecorationState {
865    /// Decorations are to be provided by the client
866    Client,
867
868    /// Decorations are provided by the server
869    Server,
870}