1use std::{
2 borrow::Cow,
3 path::PathBuf,
4 rc::Rc,
5 sync::Arc,
6 task::Waker,
7};
8
9use accesskit_winit::Adapter;
10use freya_clipboard::copypasta::{
11 ClipboardContext,
12 ClipboardProvider,
13};
14use freya_components::{
15 cache::AssetCacher,
16 integration::integration,
17};
18use freya_core::{
19 integration::*,
20 prelude::Color,
21};
22use freya_engine::prelude::{
23 FontCollection,
24 FontMgr,
25};
26use futures_util::task::{
27 ArcWake,
28 waker,
29};
30use ragnarok::NodesState;
31use raw_window_handle::HasDisplayHandle;
32#[cfg(target_os = "linux")]
33use raw_window_handle::RawDisplayHandle;
34use torin::prelude::{
35 CursorPoint,
36 Size2D,
37};
38use winit::{
39 dpi::LogicalSize,
40 event::ElementState,
41 event_loop::{
42 ActiveEventLoop,
43 EventLoopProxy,
44 },
45 keyboard::ModifiersState,
46 window::{
47 Theme,
48 Window,
49 WindowAttributes,
50 WindowId,
51 },
52};
53
54use crate::{
55 accessibility::AccessibilityTask,
56 config::{
57 OnCloseHook,
58 WindowConfig,
59 },
60 drivers::GraphicsDriver,
61 plugins::{
62 PluginEvent,
63 PluginHandle,
64 PluginsManager,
65 },
66 renderer::{
67 NativeEvent,
68 NativeWindowEvent,
69 NativeWindowEventAction,
70 },
71};
72
73pub struct AppWindow {
74 pub(crate) runner: Runner,
75 pub(crate) tree: Tree,
76 pub(crate) driver: GraphicsDriver,
77 pub(crate) window: Window,
78 pub(crate) nodes_state: NodesState<NodeId>,
79
80 pub(crate) position: CursorPoint,
81 pub(crate) mouse_state: ElementState,
82 pub(crate) modifiers_state: ModifiersState,
83 pub(crate) just_focused: bool,
84
85 pub(crate) events_receiver: futures_channel::mpsc::UnboundedReceiver<EventsChunk>,
86 pub(crate) events_sender: futures_channel::mpsc::UnboundedSender<EventsChunk>,
87
88 pub(crate) accessibility: AccessibilityTree,
89 pub(crate) accessibility_adapter: accesskit_winit::Adapter,
90 pub(crate) accessibility_tasks_for_next_render: AccessibilityTask,
91
92 pub(crate) process_layout_on_next_render: bool,
93
94 pub(crate) waker: Waker,
95
96 pub(crate) ticker_sender: RenderingTickerSender,
97
98 pub(crate) platform: Platform,
99
100 pub(crate) animation_clock: AnimationClock,
101
102 pub(crate) background: Color,
103
104 pub(crate) dropped_file_paths: Vec<PathBuf>,
105
106 pub(crate) on_close: Option<OnCloseHook>,
107
108 pub(crate) window_attributes: WindowAttributes,
109}
110
111impl AppWindow {
112 #[allow(clippy::too_many_arguments)]
113 pub fn new(
114 mut window_config: WindowConfig,
115 active_event_loop: &ActiveEventLoop,
116 event_loop_proxy: &EventLoopProxy<NativeEvent>,
117 plugins: &mut PluginsManager,
118 font_collection: &mut FontCollection,
119 font_manager: &FontMgr,
120 fallback_fonts: &[Cow<'static, str>],
121 screen_reader: ScreenReader,
122 ) -> Self {
123 let mut window_attributes = Window::default_attributes()
124 .with_resizable(window_config.resizable)
125 .with_window_icon(window_config.icon.take())
126 .with_visible(false)
127 .with_title(window_config.title)
128 .with_decorations(window_config.decorations)
129 .with_transparent(window_config.transparent)
130 .with_inner_size(LogicalSize::<f64>::from(window_config.size));
131
132 if let Some(min_size) = window_config.min_size {
133 window_attributes =
134 window_attributes.with_min_inner_size(LogicalSize::<f64>::from(min_size));
135 }
136 if let Some(max_size) = window_config.max_size {
137 window_attributes =
138 window_attributes.with_max_inner_size(LogicalSize::<f64>::from(max_size));
139 }
140 #[cfg(target_os = "linux")]
141 if let Some(app_id) = window_config.app_id.take() {
142 use winit::platform::wayland::WindowAttributesExtWayland;
143 window_attributes = window_attributes.with_name(&app_id, &app_id);
144 }
145 if let Some(window_attributes_hook) = window_config.window_attributes_hook.take() {
146 window_attributes = window_attributes_hook(window_attributes, active_event_loop);
147 }
148 let (driver, mut window) =
149 GraphicsDriver::new(active_event_loop, window_attributes.clone());
150
151 if let Some(window_handle_hook) = window_config.window_handle_hook.take() {
152 window_handle_hook(&mut window);
153 }
154
155 let on_close = window_config.on_close.take();
156
157 let (events_sender, events_receiver) = futures_channel::mpsc::unbounded();
158
159 let app = window_config.app.clone();
160 let mut runner = Runner::new({
161 let plugins = plugins.clone();
162 move || {
163 let el = integration(app.clone()).into_element();
164 plugins.wrap_root(el)
165 }
166 });
167
168 runner.provide_root_context(|| screen_reader);
169
170 let (mut ticker_sender, ticker) = RenderingTicker::new();
171 ticker_sender.set_overflow(true);
172 runner.provide_root_context(|| ticker);
173
174 let animation_clock = AnimationClock::new();
175 runner.provide_root_context(|| animation_clock.clone());
176
177 runner.provide_root_context(AssetCacher::create);
178 let mut tree = Tree::default();
179
180 let window_size = window.inner_size();
181 let platform = runner.provide_root_context({
182 let event_loop_proxy = event_loop_proxy.clone();
183 let window_id = window.id();
184 let theme = match window.theme() {
185 Some(Theme::Dark) => PreferredTheme::Dark,
186 _ => PreferredTheme::Light,
187 };
188 move || Platform {
189 focused_accessibility_id: State::create(ACCESSIBILITY_ROOT_ID),
190 focused_accessibility_node: State::create(accesskit::Node::new(
191 accesskit::Role::Window,
192 )),
193 root_size: State::create(Size2D::new(
194 window_size.width as f32,
195 window_size.height as f32,
196 )),
197 navigation_mode: State::create(NavigationMode::NotKeyboard),
198 preferred_theme: State::create(theme),
199 sender: Rc::new(move |user_event| {
200 event_loop_proxy
201 .send_event(NativeEvent::Window(NativeWindowEvent {
202 window_id,
203 action: NativeWindowEventAction::User(user_event),
204 }))
205 .unwrap();
206 }),
207 }
208 });
209
210 let clipboard = {
211 if let Ok(handle) = window.display_handle() {
212 #[allow(clippy::match_single_binding)]
213 match handle.as_raw() {
214 #[cfg(target_os = "linux")]
215 RawDisplayHandle::Wayland(handle) => {
216 let (_primary, clipboard) = unsafe {
217 use freya_clipboard::copypasta::wayland_clipboard;
218
219 wayland_clipboard::create_clipboards_from_external(
220 handle.display.as_ptr(),
221 )
222 };
223 let clipboard: Box<dyn ClipboardProvider> = Box::new(clipboard);
224 Some(clipboard)
225 }
226 _ => ClipboardContext::new().ok().map(|c| {
227 let clipboard: Box<dyn ClipboardProvider> = Box::new(c);
228 clipboard
229 }),
230 }
231 } else {
232 None
233 }
234 };
235
236 runner.provide_root_context(|| State::create(clipboard));
237
238 runner.provide_root_context(|| tree.accessibility_generator.clone());
239
240 runner.provide_root_context(|| tree.accessibility_generator.clone());
241
242 runner.provide_root_context(|| font_collection.clone());
243
244 plugins.send(
245 PluginEvent::RunnerCreated {
246 runner: &mut runner,
247 },
248 PluginHandle::new(event_loop_proxy),
249 );
250
251 let mutations = runner.sync_and_update();
252 tree.apply_mutations(mutations);
253 tree.measure_layout(
254 (
255 window.inner_size().width as f32,
256 window.inner_size().height as f32,
257 )
258 .into(),
259 font_collection,
260 font_manager,
261 &events_sender,
262 window.scale_factor(),
263 fallback_fonts,
264 );
265
266 let nodes_state = NodesState::default();
267
268 let accessibility_adapter =
269 Adapter::with_event_loop_proxy(active_event_loop, &window, event_loop_proxy.clone());
270
271 window.set_visible(true);
272
273 struct TreeHandle(EventLoopProxy<NativeEvent>, WindowId);
274
275 impl ArcWake for TreeHandle {
276 fn wake_by_ref(arc_self: &Arc<Self>) {
277 _ = arc_self
278 .0
279 .send_event(NativeEvent::Window(NativeWindowEvent {
280 window_id: arc_self.1,
281 action: NativeWindowEventAction::PollRunner,
282 }));
283 }
284 }
285
286 let waker = waker(Arc::new(TreeHandle(event_loop_proxy.clone(), window.id())));
287
288 plugins.send(
289 PluginEvent::WindowCreated {
290 window: &window,
291 font_collection,
292 tree: &tree,
293 animation_clock: &animation_clock,
294 runner: &mut runner,
295 graphics_driver: driver.name(),
296 },
297 PluginHandle::new(event_loop_proxy),
298 );
299
300 AppWindow {
301 runner,
302 tree,
303 driver,
304 window,
305 nodes_state,
306
307 mouse_state: ElementState::Released,
308 position: CursorPoint::default(),
309 modifiers_state: ModifiersState::default(),
310 just_focused: false,
311
312 events_receiver,
313 events_sender,
314
315 accessibility: AccessibilityTree::default(),
316 accessibility_adapter,
317 accessibility_tasks_for_next_render: AccessibilityTask::ProcessUpdate { mode: None },
318
319 process_layout_on_next_render: true,
320
321 waker,
322
323 ticker_sender,
324
325 platform,
326
327 animation_clock,
328
329 background: window_config.background,
330
331 dropped_file_paths: Vec::new(),
332
333 on_close,
334
335 window_attributes,
336 }
337 }
338
339 pub fn window(&self) -> &Window {
340 &self.window
341 }
342
343 pub fn window_mut(&mut self) -> &mut Window {
344 &mut self.window
345 }
346}