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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
use crate::{
    convert::{winit_key_code_to_code, winit_key_to_key},
    window::Window,
};

#[cfg(feature = "accesskit")]
use accesskit::{Action, NodeBuilder, NodeId, TreeUpdate};
#[cfg(feature = "accesskit")]
use accesskit_winit;
use std::cell::RefCell;
use vizia_core::backend::*;
use vizia_core::context::EventProxy;
use vizia_core::prelude::*;
// use vizia_input::KeyState;
#[cfg(all(
    feature = "clipboard",
    feature = "wayland",
    any(
        target_os = "linux",
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd"
    )
))]
use raw_window_handle::{HasRawDisplayHandle, RawDisplayHandle};
use vizia_window::Position;

use winit::{
    error::EventLoopError, event::ElementState, event_loop::EventLoopBuilder, keyboard::PhysicalKey,
};
use winit::{
    event_loop::{ControlFlow, EventLoop},
    keyboard::NativeKeyCode,
};

use winit::event_loop::EventLoopProxy;

#[derive(Debug)]
pub enum UserEvent {
    Event(Event),
    #[cfg(feature = "accesskit")]
    AccessKitActionRequest(accesskit_winit::ActionRequestEvent),
}

#[cfg(feature = "accesskit")]
impl From<accesskit_winit::ActionRequestEvent> for UserEvent {
    fn from(action_request_event: accesskit_winit::ActionRequestEvent) -> Self {
        UserEvent::AccessKitActionRequest(action_request_event)
    }
}

impl From<vizia_core::events::Event> for UserEvent {
    fn from(event: vizia_core::events::Event) -> Self {
        UserEvent::Event(event)
    }
}

type IdleCallback = Option<Box<dyn Fn(&mut Context)>>;

#[derive(Debug)]
pub enum ApplicationError {
    EventLoopError(EventLoopError),
    LogError,
}

///Creating a new application creates a root `Window` and a `Context`. Views declared within the closure passed to `Application::new()` are added to the context and rendered into the root window.
///
/// # Example
/// ```no_run
/// # use vizia_core::prelude::*;
/// # use vizia_winit::application::Application;
/// Application::new(|cx|{
///    // Content goes here
/// })
/// .run();
///```
/// Calling `run()` on the `Application` causes the program to enter the event loop and for the main window to display.
pub struct Application {
    context: Context,
    event_loop: EventLoop<UserEvent>,
    on_idle: IdleCallback,
    window_description: WindowDescription,
    should_poll: bool,
}
pub struct WinitEventProxy(EventLoopProxy<UserEvent>);

impl EventProxy for WinitEventProxy {
    fn send(&self, event: Event) -> Result<(), ()> {
        self.0.send_event(UserEvent::Event(event)).map_err(|_| ())
    }

    fn make_clone(&self) -> Box<dyn EventProxy> {
        Box::new(WinitEventProxy(self.0.clone()))
    }
}

impl Application {
    pub fn new<F>(content: F) -> Self
    where
        F: 'static + FnOnce(&mut Context),
    {
        // TODO: User scale factors and window resizing has not been implement for winit
        // TODO: Changing the scale factor doesn't work for winit anyways since winit doesn't let
        //       you resize the window, so there's no mutator for that at he moment
        let mut context = Context::new(WindowSize::new(1, 1), 1.0);

        let event_loop =
            EventLoopBuilder::with_user_event().build().expect("Failed to create event loop");

        let mut cx = BackendContext::new(&mut context);
        let event_proxy_obj = event_loop.create_proxy();
        cx.set_event_proxy(Box::new(WinitEventProxy(event_proxy_obj)));

        cx.renegotiate_language();
        cx.0.remove_user_themes();
        (content)(cx.0);

        Self {
            context,
            event_loop,
            on_idle: None,
            window_description: WindowDescription::new(),
            should_poll: false,
        }
    }

    /// Sets the default built-in theming to be ignored.
    pub fn ignore_default_theme(mut self) -> Self {
        self.context.ignore_default_theme = true;
        self
    }

    pub fn set_text_config(mut self, text_config: TextConfig) -> Self {
        BackendContext::new(&mut self.context).set_text_config(text_config);
        self
    }

    pub fn should_poll(mut self) -> Self {
        self.should_poll = true;

        self
    }

    /// Takes a closure which will be called at the end of every loop of the application.
    ///
    /// The callback provides a place to run 'idle' processing and happens at the end of each loop but before drawing.
    /// If the callback pushes events into the queue in state then the event loop will re-run. Care must be taken not to
    /// push events into the queue every time the callback runs unless this is intended.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use vizia_core::prelude::*;
    /// # use vizia_winit::application::Application;
    /// #
    /// Application::new(|cx| {
    ///     // Build application here
    /// })
    /// .on_idle(|cx| {
    ///     // Code here runs at the end of every event loop after OS and vizia events have been handled
    /// })
    /// .run();
    /// ```
    pub fn on_idle<F: 'static + Fn(&mut Context)>(mut self, callback: F) -> Self {
        self.on_idle = Some(Box::new(callback));

        self
    }

    /// Returns a `ContextProxy` which can be used to send events from another thread.
    pub fn get_proxy(&self) -> ContextProxy {
        self.context.get_proxy()
    }

    /// Starts the application and enters the main event loop.
    pub fn run(mut self) -> Result<(), ApplicationError> {
        let mut context = self.context;

        let event_loop = self.event_loop;

        let (window, canvas) = Window::new(&event_loop, &self.window_description);

        // On windows cloak (hide) the window initially, we later reveal it after the first draw.
        // This is a workaround to hide the "white flash" that occurs during application startup.
        #[cfg(target_os = "windows")]
        let mut is_initially_cloaked = window.set_cloak(true);

        #[cfg(feature = "accesskit")]
        let event_loop_proxy = event_loop.create_proxy();

        let mut cx = BackendContext::new(&mut context);

        // update the sys theme if any
        if let Some(theme) = window.window().theme() {
            let theme = match theme {
                winit::window::Theme::Light => ThemeMode::LightMode,
                winit::window::Theme::Dark => ThemeMode::DarkMode,
            };
            cx.emit_origin(WindowEvent::ThemeChanged(theme));
        }

        #[cfg(feature = "accesskit")]
        let root_node = NodeBuilder::new(Role::Window).build(cx.accesskit_node_classes());
        #[cfg(feature = "accesskit")]
        let accesskit = accesskit_winit::Adapter::new(
            window.window(),
            move || {
                // TODO: set a flag to signify that a screen reader has been attached
                use accesskit::Tree;

                let root_id = Entity::root().accesskit_id();

                // Build initial tree here

                TreeUpdate {
                    nodes: vec![(root_id, root_node)],
                    tree: Some(Tree::new(root_id)),
                    focus: Entity::root().accesskit_id(),
                }
            },
            event_loop_proxy,
        );

        // Accesskit requires that the window starts invisible until accesskit has been initialised.
        // At this point we can set the visibility based on the desired visibility from the window description.
        window.window().set_visible(self.window_description.visible);

        #[cfg(all(
            feature = "clipboard",
            feature = "wayland",
            any(
                target_os = "linux",
                target_os = "dragonfly",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "openbsd"
            )
        ))]
        unsafe {
            let display = window.window().raw_display_handle();
            if let RawDisplayHandle::Wayland(display_handle) = display {
                let (_, clipboard) = copypasta::wayland_clipboard::create_clipboards_from_external(
                    display_handle.display,
                );
                cx.set_clipboard_provider(Box::new(clipboard));
            }
        }

        let scale_factor = window.window().scale_factor() as f32;
        cx.add_main_window(&self.window_description, canvas, scale_factor);
        cx.add_window(window);

        cx.0.remove_user_themes();

        let on_idle = self.on_idle.take();

        let event_loop_proxy = event_loop.create_proxy();

        let default_should_poll = self.should_poll;
        let stored_control_flow = RefCell::new(ControlFlow::Poll);

        // #[cfg(feature = "accesskit")]
        // cx.process_tree_updates(|tree_updates| {
        //     for update in tree_updates.iter_mut() {
        //         accesskit.update_if_active(|| update.take().unwrap());
        //     }
        // });

        let mut cursor_moved = false;
        let mut cursor = (0.0f32, 0.0f32);

        // cx.process_events();

        cx.process_data_updates();
        cx.process_style_updates();
        cx.process_visual_updates();

        let mut main_events = false;
        event_loop
            .run(move |event, elwt| {
                let mut cx = BackendContext::new_with_event_manager(&mut context);

                match event {
                    winit::event::Event::NewEvents(_) => {
                        cx.process_timers();
                        cx.emit_scheduled_events();
                    }

                    winit::event::Event::UserEvent(user_event) => match user_event {
                        UserEvent::Event(event) => {
                            cx.send_event(event);
                        }

                        #[cfg(feature = "accesskit")]
                        UserEvent::AccessKitActionRequest(action_request_event) => {
                            let node_id = action_request_event.request.target;

                            if action_request_event.request.action != Action::ScrollIntoView {
                                let entity = Entity::new(node_id.0 as u64, 0);

                                // Handle focus action from screen reader
                                if action_request_event.request.action == Action::Focus {
                                    cx.0.with_current(entity, |cx| {
                                        cx.focus();
                                    });
                                }

                                cx.send_event(
                                    Event::new(WindowEvent::ActionRequest(
                                        action_request_event.request,
                                    ))
                                    .direct(entity),
                                );
                            }
                        }
                    },

                    winit::event::Event::AboutToWait => {
                        main_events = true;

                        *stored_control_flow.borrow_mut() =
                            if default_should_poll { ControlFlow::Poll } else { ControlFlow::Wait };

                        if cursor_moved {
                            cx.emit_origin(WindowEvent::MouseMove(cursor.0, cursor.1));
                            cursor_moved = false;
                        }

                        cx.process_events();

                        cx.process_style_updates();

                        if cx.process_animations() {
                            *stored_control_flow.borrow_mut() = ControlFlow::Poll;

                            event_loop_proxy
                                .send_event(UserEvent::Event(Event::new(WindowEvent::Redraw)))
                                .expect("Failed to send redraw event");

                            cx.mutate_window(|_, window: &Window| {
                                window.window().request_redraw();
                            });
                        }

                        cx.process_visual_updates();

                        #[cfg(feature = "accesskit")]
                        cx.process_tree_updates(|tree_updates| {
                            for update in tree_updates.iter_mut() {
                                accesskit.update_if_active(|| update.take().unwrap());
                            }
                        });

                        cx.mutate_window(|cx, window: &Window| {
                            cx.style().should_redraw(|| {
                                window.window().request_redraw();
                            });
                        });

                        if let Some(idle_callback) = &on_idle {
                            cx.set_current(Entity::root());
                            (idle_callback)(cx.context());
                        }

                        if cx.has_queued_events() {
                            *stored_control_flow.borrow_mut() = ControlFlow::Poll;
                            event_loop_proxy
                                .send_event(UserEvent::Event(Event::new(())))
                                .expect("Failed to send event");
                        }

                        cx.mutate_window(|_, window: &Window| {
                            if window.should_close {
                                elwt.exit();
                            }
                        });
                    }

                    winit::event::Event::WindowEvent { window_id: _, event } => {
                        #[cfg(feature = "accesskit")]
                        cx.mutate_window(|_, window: &Window| {
                            accesskit.process_event(window.window(), &event);
                        });

                        match event {
                            winit::event::WindowEvent::RedrawRequested => {
                                if main_events {
                                    // Redraw
                                    cx.draw();
                                    cx.mutate_window(|_, window: &Window| {
                                        // window.window().pre_present_notify();
                                        window.swap_buffers();
                                    });

                                    // Un-cloak
                                    #[cfg(target_os = "windows")]
                                    if is_initially_cloaked {
                                        is_initially_cloaked = false;
                                        cx.draw();
                                        cx.mutate_window(|_, window: &Window| {
                                            window.swap_buffers();
                                            window.set_cloak(false);
                                        });
                                    }
                                }
                            }

                            winit::event::WindowEvent::CloseRequested => {
                                cx.emit_origin(WindowEvent::WindowClose);
                            }

                            winit::event::WindowEvent::Focused(is_focused) => {
                                cx.0.window_has_focus = is_focused;
                                #[cfg(feature = "accesskit")]
                                accesskit.update_if_active(|| TreeUpdate {
                                    nodes: vec![],
                                    tree: None,
                                    focus: is_focused
                                        .then_some(cx.focused().accesskit_id())
                                        .unwrap_or(NodeId(0)),
                                });
                            }

                            winit::event::WindowEvent::ScaleFactorChanged {
                                scale_factor,
                                inner_size_writer: _,
                            } => {
                                cx.set_scale_factor(scale_factor);
                                // cx.set_window_size(
                                //     new_inner_size.width as f32,
                                //     new_inner_size.height as f32,
                                // );
                                cx.needs_refresh();
                            }

                            winit::event::WindowEvent::DroppedFile(path) => {
                                cx.emit_origin(WindowEvent::Drop(DropData::File(path)));
                            }

                            #[allow(deprecated)]
                            winit::event::WindowEvent::CursorMoved { device_id: _, position } => {
                                // To avoid calling the hover system multiple times in one frame when multiple cursor moved
                                // events are received, instead we set a flag here and emit the MouseMove event during MainEventsCleared.
                                if !cursor_moved {
                                    cursor_moved = true;
                                    cursor.0 = position.x as f32;
                                    cursor.1 = position.y as f32;
                                }
                            }

                            #[allow(deprecated)]
                            winit::event::WindowEvent::MouseInput {
                                device_id: _,
                                button,
                                state,
                            } => {
                                let button = match button {
                                    winit::event::MouseButton::Left => MouseButton::Left,
                                    winit::event::MouseButton::Right => MouseButton::Right,
                                    winit::event::MouseButton::Middle => MouseButton::Middle,
                                    winit::event::MouseButton::Other(val) => {
                                        MouseButton::Other(val)
                                    }
                                    winit::event::MouseButton::Back => MouseButton::Back,
                                    winit::event::MouseButton::Forward => MouseButton::Forward,
                                };

                                let event = match state {
                                    winit::event::ElementState::Pressed => {
                                        WindowEvent::MouseDown(button)
                                    }
                                    winit::event::ElementState::Released => {
                                        WindowEvent::MouseUp(button)
                                    }
                                };

                                cx.emit_origin(event);
                            }

                            winit::event::WindowEvent::MouseWheel { delta, phase: _, .. } => {
                                let out_event = match delta {
                                    winit::event::MouseScrollDelta::LineDelta(x, y) => {
                                        WindowEvent::MouseScroll(x, y)
                                    }
                                    winit::event::MouseScrollDelta::PixelDelta(pos) => {
                                        WindowEvent::MouseScroll(
                                            pos.x as f32 / 20.0,
                                            pos.y as f32 / 20.0, // this number calibrated for wayland
                                        )
                                    }
                                };

                                cx.emit_origin(out_event);
                            }

                            winit::event::WindowEvent::KeyboardInput {
                                device_id: _,
                                event,
                                is_synthetic: _,
                            } => {
                                let code = match event.physical_key {
                                    PhysicalKey::Code(code) => winit_key_code_to_code(code),
                                    PhysicalKey::Unidentified(native) => match native {
                                        NativeKeyCode::Windows(_scancode) => return,
                                        _ => return,
                                    },
                                };

                                let key = match event.logical_key {
                                    winit::keyboard::Key::Named(named_key) => {
                                        winit_key_to_key(named_key)
                                    }
                                    _ => None,
                                };

                                if let winit::keyboard::Key::Character(character) =
                                    event.logical_key
                                {
                                    if event.state == ElementState::Pressed {
                                        cx.emit_origin(WindowEvent::CharInput(
                                            character.as_str().chars().next().unwrap(),
                                        ));
                                    }
                                }

                                let event = match event.state {
                                    winit::event::ElementState::Pressed => {
                                        WindowEvent::KeyDown(code, key)
                                    }
                                    winit::event::ElementState::Released => {
                                        WindowEvent::KeyUp(code, key)
                                    }
                                };

                                cx.emit_origin(event);
                            }

                            winit::event::WindowEvent::Resized(physical_size) => {
                                cx.mutate_window(|_, window: &Window| {
                                    window.resize(physical_size);
                                });

                                cx.set_window_size(
                                    physical_size.width as f32,
                                    physical_size.height as f32,
                                );

                                cx.needs_refresh();

                                #[cfg(target_os = "windows")]
                                {
                                    cx.process_events();

                                    cx.process_style_updates();

                                    if cx.process_animations() {
                                        *stored_control_flow.borrow_mut() = ControlFlow::Poll;

                                        event_loop_proxy
                                            .send_event(UserEvent::Event(Event::new(
                                                WindowEvent::Redraw,
                                            )))
                                            .expect("Failed to send redraw event");

                                        cx.mutate_window(|_, window: &Window| {
                                            window.window().request_redraw();
                                        });
                                    }

                                    cx.process_visual_updates();

                                    #[cfg(feature = "accesskit")]
                                    cx.process_tree_updates(|tree_updates| {
                                        for update in tree_updates.iter_mut() {
                                            accesskit.update_if_active(|| update.take().unwrap());
                                        }
                                    });

                                    cx.mutate_window(|_, window: &Window| {
                                        window.window().request_redraw();
                                    });
                                }
                            }

                            winit::event::WindowEvent::ThemeChanged(theme) => {
                                let theme = match theme {
                                    winit::window::Theme::Light => ThemeMode::LightMode,
                                    winit::window::Theme::Dark => ThemeMode::DarkMode,
                                };
                                cx.emit_origin(WindowEvent::ThemeChanged(theme));
                            }

                            winit::event::WindowEvent::ModifiersChanged(modifiers_state) => {
                                cx.modifiers()
                                    .set(Modifiers::SHIFT, modifiers_state.state().shift_key());

                                cx.modifiers()
                                    .set(Modifiers::ALT, modifiers_state.state().alt_key());

                                cx.modifiers()
                                    .set(Modifiers::CTRL, modifiers_state.state().control_key());

                                cx.modifiers()
                                    .set(Modifiers::SUPER, modifiers_state.state().super_key());
                            }

                            winit::event::WindowEvent::CursorEntered { device_id: _ } => {
                                cx.emit_origin(WindowEvent::MouseEnter);
                            }

                            winit::event::WindowEvent::CursorLeft { device_id: _ } => {
                                cx.emit_origin(WindowEvent::MouseLeave);
                            }

                            _ => {}
                        }
                    }

                    _ => {}
                }

                if let Some(timer_time) = cx.get_next_timer_time() {
                    elwt.set_control_flow(ControlFlow::WaitUntil(timer_time));
                } else {
                    elwt.set_control_flow(*stored_control_flow.borrow());
                }
            })
            .map_err(ApplicationError::EventLoopError)?;

        Ok(())
    }
}

impl WindowModifiers for Application {
    fn title<T: ToString>(mut self, title: impl Res<T>) -> Self {
        title.set_or_bind(&mut self.context, Entity::root(), |cx, title| {
            cx.emit(WindowEvent::SetTitle(title.get(cx).to_string()));
        });

        self
    }

    fn inner_size<S: Into<WindowSize>>(mut self, size: impl Res<S>) -> Self {
        self.window_description.inner_size = size.get(&self.context).into();

        size.set_or_bind(&mut self.context, Entity::root(), |cx, size| {
            cx.emit(WindowEvent::SetSize(size.get(cx).into()));
        });

        self
    }

    fn min_inner_size<S: Into<WindowSize>>(mut self, size: impl Res<Option<S>>) -> Self {
        self.window_description.min_inner_size = size.get(&self.context).map(|s| s.into());

        size.set_or_bind(&mut self.context, Entity::root(), |cx, size| {
            cx.emit(WindowEvent::SetMinSize(size.get(cx).map(|s| s.into())));
        });

        self
    }

    fn max_inner_size<S: Into<WindowSize>>(mut self, size: impl Res<Option<S>>) -> Self {
        self.window_description.max_inner_size = size.get(&self.context).map(|s| s.into());

        size.set_or_bind(&mut self.context, Entity::root(), |cx, size| {
            cx.emit(WindowEvent::SetMaxSize(size.get(cx).map(|s| s.into())));
        });
        self
    }

    fn position<P: Into<Position>>(mut self, position: impl Res<P>) -> Self {
        self.window_description.position = Some(position.get(&self.context).into());

        position.set_or_bind(&mut self.context, Entity::root(), |cx, size| {
            cx.emit(WindowEvent::SetPosition(size.get(cx).into()));
        });

        self
    }

    fn resizable(mut self, flag: impl Res<bool>) -> Self {
        self.window_description.resizable = flag.get(&self.context);

        flag.set_or_bind(&mut self.context, Entity::root(), |cx, flag| {
            cx.emit(WindowEvent::SetResizable(flag.get(cx)));
        });

        self
    }

    fn minimized(mut self, flag: impl Res<bool>) -> Self {
        self.window_description.minimized = flag.get(&self.context);

        flag.set_or_bind(&mut self.context, Entity::root(), |cx, flag| {
            cx.emit(WindowEvent::SetMinimized(flag.get(cx)));
        });
        self
    }

    fn maximized(mut self, flag: impl Res<bool>) -> Self {
        self.window_description.maximized = flag.get(&self.context);

        flag.set_or_bind(&mut self.context, Entity::root(), |cx, flag| {
            cx.emit(WindowEvent::SetMaximized(flag.get(cx)));
        });

        self
    }

    fn visible(mut self, flag: bool) -> Self {
        self.window_description.visible = flag;

        self
    }

    fn transparent(mut self, flag: bool) -> Self {
        self.window_description.transparent = flag;

        self
    }

    fn decorations(mut self, flag: bool) -> Self {
        self.window_description.decorations = flag;

        self
    }

    fn always_on_top(mut self, flag: bool) -> Self {
        self.window_description.always_on_top = flag;
        self
    }

    fn vsync(mut self, flag: bool) -> Self {
        self.window_description.vsync = flag;

        self
    }

    fn icon(mut self, width: u32, height: u32, image: Vec<u8>) -> Self {
        self.window_description.icon = Some(image);
        self.window_description.icon_width = width;
        self.window_description.icon_height = height;

        self
    }
}