freya-winit 0.4.1

Winit renderer for Freya
Documentation
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use std::{
    borrow::Cow,
    path::PathBuf,
    rc::Rc,
    sync::Arc,
    task::Waker,
};

use accesskit_winit::Adapter;
use freya_clipboard::copypasta::{
    ClipboardContext,
    ClipboardProvider,
};
use freya_components::{
    cache::AssetCacher,
    integration::integration,
};
use freya_core::{
    integration::*,
    prelude::Color,
};
use freya_engine::prelude::{
    FontCollection,
    FontMgr,
};
use futures_util::task::{
    ArcWake,
    waker,
};
use ragnarok::NodesState;
use raw_window_handle::HasDisplayHandle;
#[cfg(target_os = "linux")]
use raw_window_handle::RawDisplayHandle;
use torin::prelude::{
    CursorPoint,
    Size2D,
};
use winit::{
    dpi::LogicalSize,
    event::ElementState,
    event_loop::{
        ActiveEventLoop,
        EventLoopProxy,
    },
    keyboard::ModifiersState,
    window::{
        Theme,
        Window,
        WindowAttributes,
        WindowId,
    },
};

use crate::{
    accessibility::AccessibilityTask,
    config::{
        OnCloseHook,
        WindowConfig,
    },
    drivers::GraphicsDriver,
    plugins::{
        PluginEvent,
        PluginHandle,
        PluginsManager,
    },
    renderer::{
        NativeEvent,
        NativeWindowEvent,
        NativeWindowEventAction,
    },
};

pub struct AppWindow {
    pub(crate) runner: Runner,
    pub(crate) tree: Tree,
    pub(crate) driver: GraphicsDriver,
    pub(crate) window: Window,
    pub(crate) nodes_state: NodesState<NodeId>,

    pub(crate) position: CursorPoint,
    pub(crate) mouse_state: ElementState,
    pub(crate) modifiers_state: ModifiersState,

    pub(crate) events_receiver: futures_channel::mpsc::UnboundedReceiver<EventsChunk>,
    pub(crate) events_sender: futures_channel::mpsc::UnboundedSender<EventsChunk>,

    pub(crate) accessibility: AccessibilityTree,
    pub(crate) accessibility_adapter: accesskit_winit::Adapter,
    pub(crate) accessibility_tasks_for_next_render: AccessibilityTask,
    pub(crate) screen_reader: ScreenReader,

    pub(crate) process_layout_on_next_render: bool,

    pub(crate) waker: Waker,

    pub(crate) ticker_sender: RenderingTickerSender,

    pub(crate) platform: Platform,

    pub(crate) animation_clock: AnimationClock,

    pub(crate) background: Color,

    pub(crate) dropped_file_paths: Vec<PathBuf>,

    pub(crate) on_close: Option<OnCloseHook>,

    pub(crate) window_attributes: WindowAttributes,

    pub(crate) user_zoom: f32,
    #[cfg(feature = "hotreload")]
    pub(crate) hot_reload_pending: Arc<std::sync::atomic::AtomicBool>,
}

pub(crate) const MIN_USER_ZOOM: f32 = 0.25;
pub(crate) const MAX_USER_ZOOM: f32 = 5.0;

#[cfg(feature = "zoom-shortcuts")]
pub(crate) const ZOOM_STEP: f32 = 0.10;

impl AppWindow {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        mut window_config: WindowConfig,
        active_event_loop: &ActiveEventLoop,
        event_loop_proxy: &EventLoopProxy<NativeEvent>,
        plugins: &mut PluginsManager,
        font_collection: &mut FontCollection,
        font_manager: &FontMgr,
        fallback_fonts: &[Cow<'static, str>],
        gpu_resource_cache_limit: usize,
    ) -> Self {
        #[cfg(feature = "hotreload")]
        let hot_reload_pending = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let mut window_attributes = Window::default_attributes()
            .with_resizable(window_config.resizable)
            .with_window_icon(window_config.icon.take())
            .with_visible(false)
            .with_title(window_config.title)
            .with_decorations(window_config.decorations)
            .with_transparent(window_config.transparent)
            .with_inner_size(LogicalSize::<f64>::from(window_config.size));

        if let Some(min_size) = window_config.min_size {
            window_attributes =
                window_attributes.with_min_inner_size(LogicalSize::<f64>::from(min_size));
        }
        if let Some(max_size) = window_config.max_size {
            window_attributes =
                window_attributes.with_max_inner_size(LogicalSize::<f64>::from(max_size));
        }
        #[cfg(target_os = "linux")]
        if let Some(app_id) = window_config.app_id.take() {
            use winit::platform::wayland::WindowAttributesExtWayland;
            window_attributes = window_attributes.with_name(&app_id, &app_id);
        }
        if let Some(window_attributes_hook) = window_config.window_attributes_hook.take() {
            window_attributes = window_attributes_hook(window_attributes, active_event_loop);
        }
        let (driver, mut window) = GraphicsDriver::new(
            active_event_loop,
            window_attributes.clone(),
            gpu_resource_cache_limit,
        );

        if let Some(window_handle_hook) = window_config.window_handle_hook.take() {
            window_handle_hook(&mut window);
        }

        let on_close = window_config.on_close.take();

        let (events_sender, events_receiver) = futures_channel::mpsc::unbounded();

        let app = window_config.app.clone();
        let mut runner = Runner::new({
            let plugins = plugins.clone();
            move || {
                let el = integration(app.clone()).into_element();
                plugins.wrap_root(el)
            }
        });

        let screen_reader = ScreenReader::new();
        runner.provide_root_context(|| screen_reader.clone());

        let (ticker_sender, ticker) = RenderingTicker::new();
        runner.provide_root_context(|| ticker);

        let animation_clock = AnimationClock::new();
        runner.provide_root_context(|| animation_clock.clone());

        runner.provide_root_context(AssetCacher::create);
        let mut tree = Tree::default();

        let window_size = window.inner_size();
        let accent_color_preference = accent_color_preference();
        let platform = runner.provide_root_context({
            let event_loop_proxy = event_loop_proxy.clone();
            let window_id = window.id();
            let theme = match window.theme() {
                Some(Theme::Dark) => PreferredTheme::Dark,
                _ => PreferredTheme::Light,
            };
            let is_app_focused = window.has_focus();
            let scale_factor = window.scale_factor();
            move || Platform {
                focused_accessibility_id: State::create(ACCESSIBILITY_ROOT_ID),
                focused_accessibility_node: State::create(accesskit::Node::new(
                    accesskit::Role::Window,
                )),
                root_size: State::create(Size2D::new(
                    window_size.width as f32,
                    window_size.height as f32,
                )),
                scale_factor: State::create(scale_factor),
                navigation_mode: State::create(NavigationMode::NotKeyboard),
                preferred_theme: State::create(theme),
                is_app_focused: State::create(is_app_focused),
                accent_color: State::create(accent_color_preference.accent_color),
                sender: Rc::new(move |user_event| {
                    event_loop_proxy
                        .send_event(NativeEvent::Window(NativeWindowEvent {
                            window_id,
                            action: NativeWindowEventAction::User(user_event),
                        }))
                        .unwrap();
                }),
            }
        });

        let clipboard = {
            if let Ok(handle) = window.display_handle() {
                #[allow(clippy::match_single_binding)]
                match handle.as_raw() {
                    #[cfg(target_os = "linux")]
                    RawDisplayHandle::Wayland(handle) => {
                        let (_primary, clipboard) = unsafe {
                            use freya_clipboard::copypasta::wayland_clipboard;

                            wayland_clipboard::create_clipboards_from_external(
                                handle.display.as_ptr(),
                            )
                        };
                        let clipboard: Box<dyn ClipboardProvider> = Box::new(clipboard);
                        Some(clipboard)
                    }
                    _ => ClipboardContext::new().ok().map(|c| {
                        let clipboard: Box<dyn ClipboardProvider> = Box::new(c);
                        clipboard
                    }),
                }
            } else {
                None
            }
        };

        runner.provide_root_context(|| State::create(clipboard));

        runner.provide_root_context(|| tree.accessibility_generator.clone());

        runner.provide_root_context(|| tree.accessibility_generator.clone());

        runner.provide_root_context(|| font_collection.clone());

        plugins.send(
            PluginEvent::RunnerCreated {
                runner: &mut runner,
            },
            PluginHandle::new(event_loop_proxy),
        );

        let mutations = runner.sync_and_update();
        tree.apply_mutations(mutations);
        tree.measure_layout(
            (
                window.inner_size().width as f32,
                window.inner_size().height as f32,
            )
                .into(),
            font_collection,
            font_manager,
            &events_sender,
            window.scale_factor(),
            fallback_fonts,
        );

        let nodes_state = NodesState::default();

        let accessibility_adapter =
            Adapter::with_event_loop_proxy(active_event_loop, &window, event_loop_proxy.clone());

        window.set_visible(true);

        struct TreeHandle(EventLoopProxy<NativeEvent>, WindowId);

        impl ArcWake for TreeHandle {
            fn wake_by_ref(arc_self: &Arc<Self>) {
                _ = arc_self
                    .0
                    .send_event(NativeEvent::Window(NativeWindowEvent {
                        window_id: arc_self.1,
                        action: NativeWindowEventAction::PollRunner,
                    }));
            }
        }

        let waker = waker(Arc::new(TreeHandle(event_loop_proxy.clone(), window.id())));

        #[cfg(feature = "hotreload")]
        {
            let event_loop_proxy = event_loop_proxy.clone();
            let window_id = window.id();
            let hot_reload_pending_handler = hot_reload_pending.clone();
            freya_core::hotreload::subsecond::register_handler(Arc::new(move || {
                hot_reload_pending_handler.store(true, std::sync::atomic::Ordering::Release);
                let _ = event_loop_proxy.send_event(NativeEvent::Window(NativeWindowEvent {
                    window_id,
                    action: NativeWindowEventAction::PollRunner,
                }));
            }));
        }

        plugins.send(
            PluginEvent::WindowCreated {
                window: &window,
                font_collection,
                tree: &tree,
                animation_clock: &animation_clock,
                runner: &mut runner,
                graphics_driver: driver.name(),
            },
            PluginHandle::new(event_loop_proxy),
        );

        AppWindow {
            runner,
            tree,
            driver,
            window,
            nodes_state,

            mouse_state: ElementState::Released,
            position: CursorPoint::default(),
            modifiers_state: ModifiersState::default(),

            events_receiver,
            events_sender,

            accessibility: AccessibilityTree::default(),
            accessibility_adapter,
            accessibility_tasks_for_next_render: AccessibilityTask::ProcessUpdate { mode: None },
            screen_reader,

            process_layout_on_next_render: true,

            waker,

            ticker_sender,

            platform,

            animation_clock,

            background: window_config.background,

            dropped_file_paths: Vec::new(),

            on_close,

            window_attributes,

            user_zoom: 1.0,

            #[cfg(feature = "hotreload")]
            hot_reload_pending,
        }
    }

    pub fn window(&self) -> &Window {
        &self.window
    }

    pub fn window_mut(&mut self) -> &mut Window {
        &mut self.window
    }

    pub fn effective_scale_factor(&self) -> f64 {
        self.window.scale_factor() * self.user_zoom as f64
    }

    /// Syncs the effective scale factor on [`Platform`].
    pub fn sync_scale_factor(&mut self) {
        self.platform
            .scale_factor
            .set(self.effective_scale_factor());
    }

    /// Sets `user_zoom`, clamped to `[MIN_USER_ZOOM, MAX_USER_ZOOM]`. On change,
    /// resets layout/text caches and requests a redraw, mirroring `ScaleFactorChanged`.
    pub fn set_user_zoom(&mut self, zoom: f32) {
        let clamped = zoom.clamp(MIN_USER_ZOOM, MAX_USER_ZOOM);
        if (clamped - self.user_zoom).abs() < f32::EPSILON {
            return;
        }
        self.user_zoom = clamped;
        self.sync_scale_factor();
        self.process_layout_on_next_render = true;
        self.tree.layout.reset();
        self.tree.text_cache.reset();
        self.window.request_redraw();
    }

    /// Returns `true` when the combo matched. Releases are also consumed so
    /// press/release pairs stay symmetrical for upstream listeners.
    #[cfg(feature = "zoom-shortcuts")]
    pub fn try_handle_zoom_shortcut(
        &mut self,
        key: &keyboard_types::Key,
        modifiers: keyboard_types::Modifiers,
        is_pressed: bool,
    ) -> bool {
        use keyboard_types::{
            Key,
            Modifiers,
        };
        if !modifiers.contains(Modifiers::ctrl_or_meta()) {
            return false;
        }
        let new_zoom = match key {
            Key::Character(c) if c == "+" || c == "=" => self.user_zoom + ZOOM_STEP,
            Key::Character(c) if c == "-" => self.user_zoom - ZOOM_STEP,
            Key::Character(c) if c == "0" => 1.0,
            _ => return false,
        };
        if is_pressed {
            self.set_user_zoom(new_zoom);
        }
        true
    }
}

fn accent_color_preference() -> mundy::Preferences {
    use std::sync::OnceLock;
    static PREFERENCE: OnceLock<mundy::Preferences> = OnceLock::new();
    *PREFERENCE.get_or_init(|| {
        mundy::Preferences::once_blocking(
            mundy::Interest::AccentColor,
            std::time::Duration::from_millis(200),
        )
        .unwrap_or_default()
    })
}