freya_hooks/
use_platform.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
use std::sync::Arc;

use dioxus_core::{
    prelude::{
        consume_context,
        provide_root_context,
        try_consume_context,
        use_hook,
    },
    ScopeId,
};
use dioxus_signals::{
    Readable,
    Signal,
};
use freya_core::{
    accessibility::AccessibilityFocusStrategy,
    event_loop_messages::EventLoopMessage,
    platform::CursorIcon,
};
use tokio::sync::{
    broadcast,
    mpsc::UnboundedSender,
};
use torin::prelude::Area;
#[cfg(feature = "winit")]
pub use winit::{
    event_loop::EventLoopProxy,
    window::{
        Fullscreen,
        Window,
    },
};

#[derive(Clone, Copy, PartialEq)]
pub struct UsePlatform {
    ticker: Signal<Arc<broadcast::Receiver<()>>>,
    #[cfg(feature = "winit")]
    event_loop_proxy: Signal<Option<EventLoopProxy<EventLoopMessage>>>,
    platform_emitter: Signal<Option<UnboundedSender<EventLoopMessage>>>,
}

#[derive(PartialEq, Eq, Debug)]
pub enum UsePlatformError {
    EventLoopProxyFailed,
    PlatformEmitterFailed,
}

impl UsePlatform {
    /// Get the current [UsePlatform].
    pub fn current() -> Self {
        match try_consume_context() {
            Some(p) => p,
            None => provide_root_context(UsePlatform {
                #[cfg(feature = "winit")]
                event_loop_proxy: Signal::new_in_scope(
                    try_consume_context::<EventLoopProxy<EventLoopMessage>>(),
                    ScopeId::ROOT,
                ),
                platform_emitter: Signal::new_in_scope(
                    try_consume_context::<UnboundedSender<EventLoopMessage>>(),
                    ScopeId::ROOT,
                ),
                ticker: Signal::new_in_scope(
                    consume_context::<Arc<broadcast::Receiver<()>>>(),
                    ScopeId::ROOT,
                ),
            }),
        }
    }

    /// You most likely dont want to use this method. Check the other methods in [UsePlatform].
    pub fn send(&self, event: EventLoopMessage) -> Result<(), UsePlatformError> {
        #[cfg(feature = "winit")]
        if let Some(event_loop_proxy) = &*self.event_loop_proxy.peek() {
            return event_loop_proxy
                .send_event(event)
                .map_err(|_| UsePlatformError::EventLoopProxyFailed);
        }
        if let Some(platform_emitter) = &*self.platform_emitter.peek() {
            platform_emitter
                .send(event)
                .map_err(|_| UsePlatformError::PlatformEmitterFailed)?;
        }
        Ok(())
    }

    /// Update the [CursorIcon].
    pub fn set_cursor(&self, cursor_icon: CursorIcon) {
        self.send(EventLoopMessage::SetCursorIcon(cursor_icon)).ok();
    }

    #[cfg(feature = "winit")]
    /// Update the title of the app/window.
    pub fn set_title(&self, title: impl Into<String>) {
        let title = title.into();
        self.with_window(move |window| {
            window.set_title(&title);
        });
    }

    #[cfg(feature = "winit")]
    /// Send a callback that will be called with the [Window] once this is available to get read.
    ///
    /// For a `Sync` + `Send` version of this method you can use [UsePlatform::sender].
    pub fn with_window(&self, cb: impl FnOnce(&Window) + 'static + Send + Sync) {
        self.send(EventLoopMessage::WithWindow(Box::new(cb))).ok();
    }

    #[cfg(feature = "winit")]
    /// Shortcut for [Window::drag_window].
    pub fn drag_window(&self) {
        self.with_window(|window| {
            window.drag_window().ok();
        });
    }

    #[cfg(feature = "winit")]
    /// Shortcut for [Window::set_maximized].
    pub fn set_maximize_window(&self, maximize: bool) {
        self.with_window(move |window| {
            window.set_maximized(maximize);
        });
    }

    #[cfg(feature = "winit")]
    /// Shortcut for [Window::set_maximized].
    ///
    /// Toggles the maximized state of the [Window].
    pub fn toggle_maximize_window(&self) {
        self.with_window(|window| {
            window.set_maximized(!window.is_maximized());
        });
    }

    #[cfg(feature = "winit")]
    /// Shortcut for [Window::set_minimized].
    pub fn set_minimize_window(&self, minimize: bool) {
        self.with_window(move |window| {
            window.set_minimized(minimize);
        });
    }

    #[cfg(feature = "winit")]
    /// Shortcut for [Window::set_minimized].
    ///
    /// Toggles the minimized state of the [Window].
    pub fn toggle_minimize_window(&self) {
        self.with_window(|window| {
            window.set_minimized(window.is_minimized().map(|v| !v).unwrap_or_default());
        });
    }

    #[cfg(feature = "winit")]
    /// Shortcut for [Window::set_fullscreen].
    pub fn set_fullscreen_window(&self, fullscreen: bool) {
        self.with_window(move |window| {
            if fullscreen {
                window.set_fullscreen(Some(Fullscreen::Borderless(None)))
            } else {
                window.set_fullscreen(None)
            }
        });
    }

    #[cfg(feature = "winit")]
    /// Shortcut for [Window::set_fullscreen].
    ///
    /// Toggles the fullscreen state of the [Window].
    pub fn toggle_fullscreen_window(&self) {
        self.with_window(|window| match window.fullscreen() {
            Some(_) => window.set_fullscreen(None),
            None => window.set_fullscreen(Some(Fullscreen::Borderless(None))),
        });
    }

    /// Invalidates a drawing area.
    ///
    /// You most likely dont want to use this unless you are dealing with advanced images/canvas rendering.
    pub fn invalidate_drawing_area(&self, area: Area) {
        self.send(EventLoopMessage::InvalidateArea(area)).ok();
    }

    /// Requests a new animation frame.
    ///
    /// You most likely dont want to use this unless you are dealing animations or canvas rendering.
    pub fn request_animation_frame(&self) {
        self.send(EventLoopMessage::RequestRerender).ok();
    }

    /// Request focus with a given [AccessibilityFocusStrategy].
    pub fn request_focus(&self, strategy: AccessibilityFocusStrategy) {
        self.send(EventLoopMessage::FocusAccessibilityNode(strategy))
            .ok();
    }

    /// Create a new frame [Ticker].
    ///
    /// You most likely dont want to use this unless you are dealing animations or canvas rendering.
    pub fn new_ticker(&self) -> Ticker {
        Ticker {
            inner: self.ticker.peek().resubscribe(),
        }
    }

    /// Closes the whole app.
    pub fn exit(&self) {
        self.send(EventLoopMessage::ExitApp).ok();
    }

    /// Get a [PlatformSender] that you can use to send events from other threads.
    pub fn sender(&self) -> PlatformSender {
        PlatformSender {
            event_loop_proxy: self.event_loop_proxy.read().clone(),
            platform_emitter: self.platform_emitter.read().clone(),
        }
    }
}

#[derive(Clone)]
pub struct PlatformSender {
    event_loop_proxy: Option<EventLoopProxy<EventLoopMessage>>,
    platform_emitter: Option<UnboundedSender<EventLoopMessage>>,
}

impl PlatformSender {
    pub fn send(&self, event: EventLoopMessage) -> Result<(), UsePlatformError> {
        if let Some(event_loop_proxy) = &self.event_loop_proxy {
            event_loop_proxy
                .send_event(event)
                .map_err(|_| UsePlatformError::EventLoopProxyFailed)?;
        } else if let Some(platform_emitter) = &self.platform_emitter {
            platform_emitter
                .send(event)
                .map_err(|_| UsePlatformError::PlatformEmitterFailed)?;
        }
        Ok(())
    }

    /// Send a callback that will be called with the [Window] once this is available to get read.
    pub fn with_window(&self, cb: impl FnOnce(&Window) + 'static + Send + Sync) {
        self.send(EventLoopMessage::WithWindow(Box::new(cb))).ok();
    }
}

/// Get access to information and features of the platform.
pub fn use_platform() -> UsePlatform {
    use_hook(UsePlatform::current)
}

pub struct Ticker {
    inner: broadcast::Receiver<()>,
}

impl Ticker {
    pub async fn tick(&mut self) {
        self.inner.recv().await.ok();
    }
}