Skip to main content

freya_winit/
extensions.rs

1use freya_core::{
2    elements::rect::Rect,
3    prelude::{
4        Event,
5        EventHandlersExt,
6        EventsCombos,
7        GlobalUserEvent,
8        MouseButton,
9        Platform,
10        PlatformWindow,
11        PointerEventData,
12    },
13    user_event::SingleThreadErasedEvent,
14};
15use freya_engine::prelude::Surface as SkiaSurface;
16use winit::window::{
17    Window,
18    WindowId,
19};
20
21use crate::{
22    config::WindowConfig,
23    renderer::{
24        NativePlatformErasedEventAction,
25        RendererContext,
26    },
27};
28
29/// Extension trait that adds winit-specific window management capabilities to [`Platform`].
30pub trait WinitPlatformExt {
31    /// Get the [`WindowId`] of the current window.
32    ///
33    /// # Example
34    ///
35    /// ```rust,no_run
36    /// use freya::prelude::*;
37    ///
38    /// fn close_current_window() {
39    ///     Platform::get().close_window(Platform::window_id());
40    /// }
41    /// ```
42    fn window_id() -> WindowId;
43
44    /// Dynamically launch a new window at runtime with the given configuration.
45    ///
46    /// This is meant to create windows on the fly after the application has started,
47    /// as opposed to the initial windows registered via [`crate::config::LaunchConfig`].
48    ///
49    /// Returns the [`WindowId`] of the newly created window once it has been created.
50    ///
51    /// # Example
52    ///
53    /// ```rust,no_run
54    /// use freya::prelude::*;
55    ///
56    /// async fn open_new_window() {
57    ///     let window_id = Platform::get()
58    ///         .launch_window(WindowConfig::new(my_app).with_title("New Window"))
59    ///         .await;
60    /// }
61    /// # fn my_app() -> impl IntoElement { rect() }
62    /// ```
63    fn launch_window(&self, window_config: WindowConfig) -> impl Future<Output = WindowId>;
64
65    /// Close an existing window by its [`WindowId`].
66    ///
67    /// # Example
68    ///
69    /// ```rust,no_run
70    /// use freya::{
71    ///     prelude::*,
72    ///     winit::window::WindowId,
73    /// };
74    ///
75    /// fn close_window(window_id: WindowId) {
76    ///     Platform::get().close_window(window_id);
77    /// }
78    /// ```
79    fn close_window(&self, window_id: WindowId);
80
81    /// Focus a window by its [`WindowId`].
82    ///
83    /// # Example
84    ///
85    /// ```rust,no_run
86    /// use freya::prelude::*;
87    ///
88    /// fn focus_current_window() {
89    ///     Platform::get().focus_window(Platform::window_id());
90    /// }
91    /// ```
92    fn focus_window(&self, window_id: WindowId);
93
94    /// Set the title of a window, also updating its accessibility label.
95    ///
96    /// # Example
97    ///
98    /// ```rust,no_run
99    /// use freya::prelude::*;
100    ///
101    /// fn rename_current_window() {
102    ///     Platform::get().set_window_title(Platform::window_id(), "New Title");
103    /// }
104    /// ```
105    fn set_window_title(&self, window_id: WindowId, title: impl Into<String>);
106
107    /// Execute a callback with mutable access to a [`Window`].
108    ///
109    /// This allows direct manipulation of the underlying winit [`Window`] for advanced use cases.
110    ///
111    /// To create new windows dynamically, see [`WinitPlatformExt::launch_window()`].
112    ///
113    /// # Example
114    ///
115    /// ```rust,no_run
116    /// use freya::prelude::*;
117    ///
118    /// fn minimize_current_window() {
119    ///     Platform::get().with_window(Platform::window_id(), |window| {
120    ///         window.set_minimized(true);
121    ///     });
122    /// }
123    /// ```
124    fn with_window(&self, window_id: WindowId, callback: impl FnOnce(&mut Window) + 'static);
125
126    /// Queue a renderer callback without an originating window.
127    /// The returned receiver can be awaited for its result or dropped.
128    fn post_callback<F, T: 'static>(&self, callback: F) -> futures_channel::oneshot::Receiver<T>
129    where
130        F: FnOnce(&mut RendererContext) -> T + 'static;
131}
132
133/// Winit APIs for the selected window, not necessarily the focused window.
134pub trait WinitPlatformWindowExt {
135    /// Queue a callback on this window's next render pass, after rendering and before presenting.
136    ///
137    /// # Example
138    ///
139    /// ```rust,no_run
140    /// use freya::prelude::*;
141    ///
142    /// async fn take_screenshot() {
143    ///     let image = Platform::get()
144    ///         .current_window()
145    ///         .post_render_callback(|surface| surface.image_snapshot())
146    ///         .await;
147    /// }
148    /// ```
149    fn post_render_callback<F, T: 'static>(
150        &self,
151        callback: F,
152    ) -> futures_channel::oneshot::Receiver<T>
153    where
154        F: FnOnce(&mut SkiaSurface) -> T + 'static;
155}
156
157#[derive(Clone, Copy, PartialEq)]
158struct WindowDragGesture;
159
160pub trait WindowDragExt {
161    /// Drag on left press and move, or toggle maximize on a double press.
162    fn window_drag(self) -> Self;
163}
164
165impl WindowDragExt for Rect {
166    fn window_drag(self) -> Self {
167        self.on_pointer_down(|event: Event<PointerEventData>| {
168            if event.button() != Some(MouseButton::Left) {
169                return;
170            }
171            if EventsCombos::<WindowDragGesture>::pressed(event.global_location()).is_double() {
172                Platform::get().with_window(Platform::window_id(), |window| {
173                    window.set_maximized(!window.is_maximized())
174                });
175            }
176        })
177        .on_global_pointer_move(|event: Event<PointerEventData>| {
178            if EventsCombos::<WindowDragGesture>::moved(event.global_location()) {
179                Platform::get().with_window(Platform::window_id(), |window| {
180                    let _ = window.drag_window();
181                });
182            }
183        })
184        .on_global_pointer_up(|_: Event<PointerEventData>| {
185            EventsCombos::<WindowDragGesture>::released();
186        })
187    }
188}
189
190impl WinitPlatformExt for Platform {
191    fn window_id() -> WindowId {
192        Platform::get().current_window().id.into()
193    }
194
195    async fn launch_window(&self, window_config: WindowConfig) -> WindowId {
196        let (sender, receiver) = futures_channel::oneshot::channel();
197        self.send(GlobalUserEvent::Erased(SingleThreadErasedEvent(Box::new(
198            NativePlatformErasedEventAction::LaunchWindow {
199                window_config: Box::new(window_config),
200                ack: sender,
201            },
202        ))));
203        receiver.await.expect("Failed to create window")
204    }
205
206    fn close_window(&self, window_id: WindowId) {
207        self.send(GlobalUserEvent::Erased(SingleThreadErasedEvent(Box::new(
208            NativePlatformErasedEventAction::CloseWindow(window_id),
209        ))));
210    }
211
212    fn focus_window(&self, window_id: WindowId) {
213        self.with_window(window_id, |window| window.focus_window());
214    }
215
216    fn set_window_title(&self, window_id: WindowId, title: impl Into<String>) {
217        let title = title.into();
218        self.send(GlobalUserEvent::Erased(SingleThreadErasedEvent(Box::new(
219            NativePlatformErasedEventAction::RendererCallback(Box::new(move |context| {
220                if let Some(app) = context.windows.get_mut(&window_id) {
221                    app.set_title(&title);
222                }
223            })),
224        ))));
225    }
226
227    fn with_window(&self, window_id: WindowId, callback: impl FnOnce(&mut Window) + 'static) {
228        self.send(GlobalUserEvent::Erased(SingleThreadErasedEvent(Box::new(
229            NativePlatformErasedEventAction::RendererCallback(Box::new(move |context| {
230                if let Some(app) = context.windows.get_mut(&window_id) {
231                    callback(&mut app.window);
232                }
233            })),
234        ))));
235    }
236
237    fn post_callback<F, T: 'static>(&self, callback: F) -> futures_channel::oneshot::Receiver<T>
238    where
239        F: FnOnce(&mut RendererContext) -> T + 'static,
240    {
241        let (sender, receiver) = futures_channel::oneshot::channel();
242        self.send(GlobalUserEvent::Erased(SingleThreadErasedEvent(Box::new(
243            NativePlatformErasedEventAction::RendererCallback(Box::new(move |context| {
244                let _ = sender.send(callback(context));
245            })),
246        ))));
247        receiver
248    }
249}
250
251impl WinitPlatformWindowExt for PlatformWindow {
252    fn post_render_callback<F, T: 'static>(
253        &self,
254        callback: F,
255    ) -> futures_channel::oneshot::Receiver<T>
256    where
257        F: FnOnce(&mut SkiaSurface) -> T + 'static,
258    {
259        let window_id = self.id.into();
260        let (sender, receiver) = futures_channel::oneshot::channel();
261        Platform::get().send(GlobalUserEvent::Erased(SingleThreadErasedEvent(Box::new(
262            NativePlatformErasedEventAction::RendererCallback(Box::new(move |context| {
263                if let Some(app) = context.windows.get_mut(&window_id) {
264                    app.render_callbacks.push(Box::new(move |surface| {
265                        let _ = sender.send(callback(surface));
266                    }));
267                    app.window.request_redraw();
268                }
269            })),
270        ))));
271        receiver
272    }
273}