1mod accessibility;
9mod build;
10mod focus;
11mod layout;
12mod pipeline;
13mod queries;
14mod scroll;
15mod services;
16mod styles;
17mod tree;
18
19use std::cell::RefCell;
20use std::collections::{BTreeMap, BTreeSet};
21use std::rc::{Rc, Weak};
22
23use taffy::TaffyTree;
24
25use crate::a11y::A11yProps;
26use crate::app_info::AppInfo;
27use crate::backend::{Backend, EventSink, PlatformMetrics};
28use crate::command::{Command, UiEvent};
29use crate::custom::CustomProps;
30use crate::geometry::{Insets, Point, Rect, Size};
31use crate::services::Services;
32use crate::style::Style;
33use crate::task::{Clock, Executor, Sleep, TaskHandle};
34use crate::widget::{NodeId, Prop, RowKey, WidgetKind};
35
36fn in_chrome(kind: WidgetKind) -> bool {
40 matches!(kind, WidgetKind::ToolbarItem | WidgetKind::Sidebar | WidgetKind::Popover)
41}
42
43pub(crate) type Handler = Rc<dyn Fn(&UiEvent)>;
44type Handler0 = Rc<dyn Fn()>;
45type NotificationHandler = Rc<dyn Fn(&str)>;
47type ReopenHandler = Rc<dyn Fn(&crate::services::Reopen)>;
49
50struct Node {
51 kind: WidgetKind,
52 parent: Option<NodeId>,
53 children: Vec<NodeId>,
54 native_children: Vec<NodeId>,
56 native_parent: Option<NodeId>,
57 props: Vec<Prop>,
58 style: Style,
59 a11y: A11yProps,
60 test_id: Option<String>,
61 tab_index: Option<u32>,
62 handlers: Vec<Handler>,
63 taffy: Option<taffy::NodeId>,
64 frame: Rect,
66 framed: bool,
69 window_size: Size,
71 fit: Fit,
73 heights: Vec<f32>,
77 scroll_offset: Point,
79 row_width: Option<f32>,
81 tree_indent: crate::TreeIndent,
83 viewport_insets: Insets,
85 column_widths: Option<Vec<f32>>,
87 row_heights: BTreeMap<RowKey, f32>,
90 strip: Size,
93 insets: Option<crate::Insets>,
96 drawn_at: Option<Size>,
99}
100
101#[derive(Clone, Copy, Debug, PartialEq)]
103enum Fit {
104 None,
105 Once,
107 Follow {
108 until_resized: bool,
109 },
110}
111
112impl Node {
113 fn in_full_screen(&self) -> bool {
114 crate::find_prop!(self.props, FullScreen).unwrap_or(false)
115 }
116
117 fn prop(&self, key: &Prop) -> Option<&Prop> {
118 self.props.iter().find(|p| p.key() == key.key())
119 }
120
121 fn custom(&self) -> Option<&CustomProps> {
122 self.props.iter().find_map(|p| match p {
123 Prop::Custom(custom) => Some(custom),
124 _ => None,
125 })
126 }
127
128 fn drawn(&self) -> Option<&CustomProps> {
130 self.custom().filter(|c| c.is_drawn())
131 }
132}
133
134struct Inner {
135 backend: Box<dyn Backend>,
136 events: EventSink,
137 metrics: PlatformMetrics,
138 nodes: BTreeMap<NodeId, Node>,
139 taffy: TaffyTree<NodeId>,
140 next_id: u32,
141 pending: Vec<Command>,
142 created: std::collections::HashSet<NodeId>,
145 pending_focus: Vec<NodeId>,
148 pending_present: Vec<NodeId>,
150 pending_selections: Vec<(NodeId, std::ops::Range<usize>)>,
152 windows: Vec<NodeId>,
153 destroyed_windows: Vec<NodeId>,
156 styles_dirty: bool,
157 resync: BTreeSet<NodeId>,
158 menu_handlers: BTreeMap<Option<NodeId>, std::collections::HashMap<u32, Handler0>>,
160 menu_effects: BTreeMap<Option<NodeId>, mitsuami_reactive::Effect>,
162 next_menu_id: u32,
164 menu_queue: std::collections::VecDeque<u32>,
165 quit_items: BTreeMap<Option<NodeId>, u32>,
168 notification_handlers: BTreeMap<u64, NotificationHandler>,
171 next_notification_handler: u64,
172 notification_queue: std::collections::VecDeque<String>,
174 next_notification: u64,
176 reopen_handlers: BTreeMap<u64, ReopenHandler>,
179 next_reopen_handler: u64,
180 reopen_queue: std::collections::VecDeque<crate::services::Reopen>,
182 tray_effect: Option<(u64, mitsuami_reactive::Effect)>,
185 next_tray: u64,
186 tray_handlers: std::collections::HashMap<u32, Handler0>,
188 tray_shown: mitsuami_reactive::Signal<bool>,
190 app_info_changes: mitsuami_reactive::Signal<u64>,
193 _signals: SignalRoot,
195 focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
197 focus_dirty: bool,
201 focused: BTreeMap<NodeId, NodeId>,
203 runs_without_windows: bool,
205 quit_requested: bool,
207 commit_scheduler: Option<Rc<dyn Fn()>>,
208 commit_scheduled: bool,
209 language: Option<crate::l10n::LanguageIdentifier>,
211 rtl: bool,
213 observers: BTreeMap<u64, Observer>,
215 next_observer: u64,
216}
217
218struct Observer {
220 target: Box<dyn Fn() -> Option<NodeId>>,
221 size: mitsuami_reactive::Signal<Size>,
222 last: Size,
223}
224
225#[derive(Clone)]
228pub struct Ui {
229 inner: Rc<RefCell<Inner>>,
230 executor: Rc<Executor>,
232 services: Rc<RefCell<Box<dyn Services>>>,
234 l10n: Rc<crate::l10n::Localization>,
237}
238
239#[derive(Clone)]
241pub struct WeakUi {
242 inner: Weak<RefCell<Inner>>,
243 executor: Weak<Executor>,
244 services: Weak<RefCell<Box<dyn Services>>>,
245 l10n: Weak<crate::l10n::Localization>,
246}
247
248impl WeakUi {
249 pub fn upgrade(&self) -> Option<Ui> {
250 Some(Ui {
251 inner: self.inner.upgrade()?,
252 executor: self.executor.upgrade()?,
253 services: self.services.upgrade()?,
254 l10n: self.l10n.upgrade()?,
255 })
256 }
257}
258
259#[derive(Clone, Debug, PartialEq)]
261pub struct NodeInfo {
262 pub id: NodeId,
263 pub kind: WidgetKind,
264 pub props: Vec<Prop>,
265 pub test_id: Option<String>,
266 pub frame: Rect,
268 pub children: Vec<NodeInfo>,
269}
270
271struct SignalRoot(mitsuami_reactive::Owner);
275
276impl Drop for SignalRoot {
277 fn drop(&mut self) {
278 self.0.dispose();
279 }
280}
281
282impl Ui {
283 pub fn new(backend: impl Backend + 'static) -> Ui {
284 let mut backend: Box<dyn Backend> = Box::new(backend);
285 let events = EventSink::default();
286 backend.init(events.clone());
287 let metrics = backend.metrics();
288 let services = Rc::new(RefCell::new(backend.services()));
289 let l10n = crate::l10n::Localization::new(backend.locale());
290 let signals = SignalRoot(mitsuami_reactive::Owner::new_root());
293 let ui = Ui {
294 executor: Rc::default(),
295 services,
296 l10n,
297 inner: Rc::new(RefCell::new(Inner {
298 backend,
299 events,
300 metrics,
301 nodes: BTreeMap::new(),
302 taffy: {
305 let mut taffy = TaffyTree::new();
306 taffy.disable_rounding();
307 taffy
308 },
309 next_id: 1,
310 pending: Vec::new(),
311 created: Default::default(),
312 pending_focus: Vec::new(),
313 pending_present: Vec::new(),
314 pending_selections: Vec::new(),
315 windows: Vec::new(),
316 destroyed_windows: Vec::new(),
317 styles_dirty: true,
318 resync: BTreeSet::new(),
319 focus_orders: BTreeMap::new(),
320 focus_dirty: true,
321 focused: BTreeMap::new(),
322 menu_handlers: BTreeMap::new(),
323 menu_effects: BTreeMap::new(),
324 next_menu_id: 1,
325 menu_queue: Default::default(),
326 quit_items: BTreeMap::new(),
327 notification_handlers: BTreeMap::new(),
328 next_notification_handler: 1,
329 notification_queue: Default::default(),
330 next_notification: 1,
331 reopen_handlers: BTreeMap::new(),
332 next_reopen_handler: 1,
333 reopen_queue: Default::default(),
334 tray_effect: None,
335 next_tray: 1,
336 tray_handlers: Default::default(),
337 tray_shown: signals.0.with(|| mitsuami_reactive::signal(false)),
338 app_info_changes: signals.0.with(|| mitsuami_reactive::signal(0)),
339 _signals: signals,
340 runs_without_windows: false,
341 quit_requested: false,
342 commit_scheduler: None,
343 commit_scheduled: false,
344 language: None,
345 rtl: false,
346 observers: BTreeMap::new(),
347 next_observer: 1,
348 })),
349 };
350 let weak = ui.downgrade();
352 ui.l10n.set_on_change(move |_, _| {
353 if let Some(ui) = weak.upgrade() {
354 ui.changed();
355 }
356 });
357 ui
358 }
359
360 pub fn downgrade(&self) -> WeakUi {
361 WeakUi {
362 inner: Rc::downgrade(&self.inner),
363 executor: Rc::downgrade(&self.executor),
364 services: Rc::downgrade(&self.services),
365 l10n: Rc::downgrade(&self.l10n),
366 }
367 }
368
369 pub(crate) fn executor(&self) -> &Executor {
372 &self.executor
373 }
374
375 pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
379 self.spawn_in(future, None)
380 }
381
382 pub(crate) fn spawn_in(
383 &self,
384 future: impl std::future::Future<Output = ()> + 'static,
385 owner: Option<mitsuami_reactive::Owner>,
386 ) -> TaskHandle {
387 let id = self.executor.spawn(Box::pin(future), owner);
388 self.changed();
389 TaskHandle::new(id, self.downgrade())
390 }
391
392 pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
394 Sleep::new(self.clone(), duration)
395 }
396
397 pub fn set_clock(&self, clock: Rc<dyn Clock>) {
399 self.executor.set_clock(clock);
400 }
401
402 pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
405 self.executor.set_wake_ui(wake);
406 }
407
408 pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
411 let now = self.executor.now();
412 self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
413 }
414
415 pub fn set_app_info(&self, info: AppInfo) {
418 let changes = {
419 let mut inner = self.inner.borrow_mut();
420 inner.backend.set_app_info(&info);
421 inner.app_info_changes
422 };
423 changes.update(|n| *n += 1);
424 }
425
426 pub fn pending_tasks(&self) -> usize {
428 self.executor.task_count()
429 }
430
431 pub fn events(&self) -> EventSink {
432 self.inner.borrow().events.clone()
433 }
434
435 pub fn metrics(&self) -> PlatformMetrics {
436 self.inner.borrow().metrics.clone()
437 }
438
439 pub fn set_locales(&self, locales: crate::l10n::Locales) {
444 self.l10n.set_locales(locales);
445 }
446
447 pub fn set_languages(&self, languages: Option<Vec<String>>) {
451 self.l10n.set_requested(languages);
452 }
453
454 pub fn language(&self) -> crate::l10n::LanguageIdentifier {
457 self.l10n.current()
458 }
459
460 pub fn take_l10n_errors(&self) -> Vec<String> {
463 self.l10n.take_errors()
464 }
465
466 pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
470 self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
471 }
472
473 fn changed(&self) {
474 let schedule = {
475 let mut inner = self.inner.borrow_mut();
476 if inner.commit_scheduled {
477 return;
478 }
479 inner.commit_scheduled = true;
480 inner.commit_scheduler.clone()
481 };
482 if let Some(schedule) = schedule {
483 schedule();
484 }
485 }
486}