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
use std::{sync::Arc, task::Waker};

use dioxus_core::{Template, VirtualDom};
use freya_common::EventMessage;
use freya_core::prelude::*;
use freya_dom::prelude::SafeDOM;
use freya_engine::prelude::*;
use futures::FutureExt;
use futures::{
    pin_mut,
    task::{self, ArcWake},
};
use tokio::sync::broadcast;
use tokio::{
    select,
    sync::{mpsc, watch, Notify},
};
use tracing::info;
use uuid::Uuid;
use winit::event::WindowEvent;
use winit::{dpi::PhysicalSize, event_loop::EventLoopProxy};

use crate::accessibility::NativeAccessibility;
use crate::{FontsConfig, HoveredNode, WindowEnv};

fn winit_waker(proxy: &EventLoopProxy<EventMessage>) -> std::task::Waker {
    struct DomHandle(EventLoopProxy<EventMessage>);

    unsafe impl Send for DomHandle {}
    unsafe impl Sync for DomHandle {}

    impl ArcWake for DomHandle {
        fn wake_by_ref(arc_self: &Arc<Self>) {
            _ = arc_self.0.send_event(EventMessage::PollVDOM);
        }
    }

    task::waker(Arc::new(DomHandle(proxy.clone())))
}

/// Manages the Application lifecycle
pub struct App<State: 'static + Clone> {
    sdom: SafeDOM,
    vdom: VirtualDom,

    events: EventsQueue,

    vdom_waker: Waker,
    proxy: EventLoopProxy<EventMessage>,
    mutations_notifier: Option<Arc<Notify>>,

    event_emitter: EventEmitter,
    event_receiver: EventReceiver,

    window_env: WindowEnv<State>,

    layers: Layers,
    elements_state: ElementsState,
    viewports: Viewports,

    focus_sender: FocusSender,
    focus_receiver: FocusReceiver,

    accessibility: NativeAccessibility,

    font_collection: FontCollection,

    ticker_sender: broadcast::Sender<()>,

    plugins: PluginsManager,
}

impl<State: 'static + Clone> App<State> {
    pub fn new(
        sdom: SafeDOM,
        vdom: VirtualDom,
        proxy: &EventLoopProxy<EventMessage>,
        mutations_notifier: Option<Arc<Notify>>,
        mut window_env: WindowEnv<State>,
        fonts_config: FontsConfig,
        mut plugins: PluginsManager,
    ) -> Self {
        let accessibility = NativeAccessibility::new(&window_env.window, proxy.clone());

        window_env.window_mut().set_visible(true);

        let mut font_collection = FontCollection::new();
        let def_mgr = FontMgr::default();

        let mut provider = TypefaceFontProvider::new();

        for (font_name, font_data) in fonts_config {
            let ft_type = def_mgr.new_from_data(font_data, None).unwrap();
            provider.register_typeface(ft_type, Some(font_name));
        }

        let mgr: FontMgr = provider.into();
        font_collection.set_default_font_manager(def_mgr, "Fira Sans");
        font_collection.set_dynamic_font_manager(mgr);

        let (event_emitter, event_receiver) = mpsc::unbounded_channel::<DomEvent>();
        let (focus_sender, focus_receiver) = watch::channel(ACCESSIBILITY_ROOT_ID);

        plugins.send(PluginEvent::WindowCreated(window_env.window_mut()));

        Self {
            sdom,
            vdom,
            events: EventsQueue::new(),
            vdom_waker: winit_waker(proxy),
            proxy: proxy.clone(),
            mutations_notifier,
            event_emitter,
            event_receiver,
            window_env,
            layers: Layers::default(),
            elements_state: ElementsState::default(),
            viewports: Viewports::default(),
            accessibility,
            focus_sender,
            focus_receiver,
            font_collection,
            ticker_sender: broadcast::channel(5).0,
            plugins,
        }
    }

    /// Provide the launch state and few other utilities like the EventLoopProxy
    pub fn provide_vdom_contexts(&self) {
        if let Some(state) = self.window_env.window_config.state.clone() {
            self.vdom.base_scope().provide_context(state);
        }
        self.vdom.base_scope().provide_context(self.proxy.clone());
        self.vdom
            .base_scope()
            .provide_context(self.focus_receiver.clone());
        self.vdom
            .base_scope()
            .provide_context(Arc::new(self.ticker_sender.subscribe()));
    }

    /// Make the first build of the VirtualDOM.
    pub fn init_vdom(&mut self) {
        let scale_factor = self.window_env.window.scale_factor() as f32;
        self.provide_vdom_contexts();

        let mutations = self.vdom.rebuild();

        self.sdom.get_mut().init_dom(mutations, scale_factor);

        if let Some(mutations_notifier) = &self.mutations_notifier {
            mutations_notifier.notify_one();
        }
    }

    /// Update the DOM with the mutations from the VirtualDOM.
    pub fn apply_vdom_changes(&mut self) -> (bool, bool) {
        let scale_factor = self.window_env.window.scale_factor() as f32;
        let mutations = self.vdom.render_immediate();

        let is_empty = mutations.dirty_scopes.is_empty()
            && mutations.edits.is_empty()
            && mutations.templates.is_empty();

        let (repaint, relayout) = if !is_empty {
            self.sdom.get_mut().apply_mutations(mutations, scale_factor)
        } else {
            (false, false)
        };

        if repaint {
            if let Some(mutations_notifier) = &self.mutations_notifier {
                mutations_notifier.notify_one();
            }
        }

        (repaint, relayout)
    }

    /// Poll the VirtualDOM for any new change
    pub fn poll_vdom(&mut self) {
        let waker = &self.vdom_waker.clone();
        let mut cx = std::task::Context::from_waker(waker);

        loop {
            {
                let fut = async {
                    select! {
                        ev = self.event_receiver.recv() => {
                            if let Some(ev) = ev {
                                let data = ev.data.any();
                                self.vdom.handle_event(&ev.name, data, ev.element_id, false);

                                self.vdom.process_events();
                            }
                        },
                        _ = self.vdom.wait_for_work() => {},
                    }
                };
                pin_mut!(fut);

                match fut.poll_unpin(&mut cx) {
                    std::task::Poll::Ready(_) => {}
                    std::task::Poll::Pending => break,
                }
            }

            let (must_repaint, must_relayout) = self.apply_vdom_changes();

            if must_relayout {
                self.window_env.window.request_redraw();
            } else if must_repaint {
                self.proxy.send_event(EventMessage::RequestRedraw).unwrap();
            }
        }
    }

    /// Process the events queue
    pub fn process_events(&mut self) {
        let scale_factor = self.window_env.window.scale_factor();
        process_events(
            &self.sdom.get(),
            &self.layers,
            &mut self.events,
            &self.event_emitter,
            &mut self.elements_state,
            &self.viewports,
            scale_factor,
        )
    }

    /// Measure the layout
    pub fn process_layout(&mut self) {
        self.accessibility.clear_accessibility();

        {
            let dom = self.sdom.get();

            self.plugins.send(PluginEvent::StartedLayout(&dom.layout()));

            let (layers, viewports) = self
                .window_env
                .process_layout(&dom, &mut self.font_collection);
            self.layers = layers;
            self.viewports = viewports;

            self.plugins
                .send(PluginEvent::FinishedLayout(&dom.layout()));
        }

        info!(
            "Processed {} layers and {} group of paragraph elements",
            self.layers.len_layers(),
            self.layers.len_paragraph_elements()
        );
        info!("Processed {} viewports", self.viewports.size());

        if let Some(mutations_notifier) = &self.mutations_notifier {
            mutations_notifier.notify_one();
        }

        self.process_accessibility();
    }

    /// Create the Accessibility tree
    /// This will iterater the DOM ordered by layers (top to bottom)
    /// and add every element with an accessibility ID to the Accessibility Tree
    pub fn process_accessibility(&mut self) {
        let fdom = &self.sdom.get();
        let layout = fdom.layout();
        let rdom = fdom.rdom();
        let layers = &self.layers;

        process_accessibility(
            layers,
            &layout,
            rdom,
            &mut *self.accessibility.accessibility_state().lock().unwrap(),
        );
    }

    /// Send an event
    pub fn send_event(&mut self, event: FreyaEvent) {
        self.events.push(event);
        self.process_events();
    }

    /// Replace a VirtualDOM Template
    pub fn vdom_replace_template(&mut self, template: Template<'static>) {
        self.vdom.replace_template(template);
    }

    /// Render the RealDOM into the Window
    pub fn render(&mut self, hovered_node: &HoveredNode) {
        self.plugins.send(PluginEvent::BeforeRender {
            canvas: self.window_env.canvas(),
            font_collection: &self.font_collection,
            freya_dom: &self.sdom.get(),
            viewports: &self.viewports,
        });

        self.window_env.start_render(
            &self.layers,
            &self.viewports,
            &mut self.font_collection,
            hovered_node,
            &self.sdom.get(),
        );

        self.accessibility
            .render_accessibility(self.window_env.window.title().as_str());

        self.plugins.send(PluginEvent::AfterRender {
            canvas: self.window_env.canvas(),
            font_collection: &self.font_collection,
            freya_dom: &self.sdom.get(),
            viewports: &self.viewports,
        });

        self.window_env.finish_render();
    }

    /// Resize the Window
    pub fn resize(&mut self, size: PhysicalSize<u32>) {
        self.sdom.get().layout().reset();
        self.window_env.resize(size);
    }

    pub fn measure_text_group(&self, text_id: &Uuid) {
        let scale_factor = self.window_env.window.scale_factor() as f32;
        self.layers.measure_paragraph_elements(
            text_id,
            &self.sdom.get(),
            &self.font_collection,
            scale_factor,
        );
    }

    pub fn window_env(&mut self) -> &mut WindowEnv<State> {
        &mut self.window_env
    }

    pub fn accessibility(&mut self) -> &mut NativeAccessibility {
        &mut self.accessibility
    }

    pub fn process_accessibility_event(&mut self, event: &WindowEvent) {
        self.accessibility
            .process_accessibility_event(&self.window_env.window, event)
    }

    pub fn focus_next_node(&mut self, direction: AccessibilityFocusDirection) {
        self.accessibility
            .focus_next_node(direction, &self.focus_sender)
    }

    pub fn tick(&self) {
        self.ticker_sender.send(()).unwrap();
    }
}