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)>;
47
48struct Node {
49 kind: WidgetKind,
50 parent: Option<NodeId>,
51 children: Vec<NodeId>,
52 native_children: Vec<NodeId>,
54 native_parent: Option<NodeId>,
55 props: Vec<Prop>,
56 style: Style,
57 a11y: A11yProps,
58 test_id: Option<String>,
59 tab_index: Option<u32>,
60 handlers: Vec<Handler>,
61 taffy: Option<taffy::NodeId>,
62 frame: Rect,
64 framed: bool,
67 window_size: Size,
69 fit: Fit,
71 heights: Vec<f32>,
75 scroll_offset: Point,
77 row_width: Option<f32>,
79 tree_indent: crate::TreeIndent,
81 viewport_insets: Insets,
83 column_widths: Option<Vec<f32>>,
85 row_heights: BTreeMap<RowKey, f32>,
88 strip: Size,
91 insets: Option<crate::Insets>,
94 drawn_at: Option<Size>,
97}
98
99#[derive(Clone, Copy, Debug, PartialEq)]
101enum Fit {
102 None,
103 Once,
105 Follow {
106 until_resized: bool,
107 },
108}
109
110impl Node {
111 fn in_full_screen(&self) -> bool {
112 crate::find_prop!(self.props, FullScreen).unwrap_or(false)
113 }
114
115 fn prop(&self, key: &Prop) -> Option<&Prop> {
116 self.props.iter().find(|p| p.key() == key.key())
117 }
118
119 fn custom(&self) -> Option<&CustomProps> {
120 self.props.iter().find_map(|p| match p {
121 Prop::Custom(custom) => Some(custom),
122 _ => None,
123 })
124 }
125
126 fn drawn(&self) -> Option<&CustomProps> {
128 self.custom().filter(|c| c.is_drawn())
129 }
130}
131
132struct Inner {
133 backend: Box<dyn Backend>,
134 events: EventSink,
135 metrics: PlatformMetrics,
136 nodes: BTreeMap<NodeId, Node>,
137 taffy: TaffyTree<NodeId>,
138 next_id: u32,
139 pending: Vec<Command>,
140 created: std::collections::HashSet<NodeId>,
143 pending_focus: Vec<NodeId>,
146 pending_selections: Vec<(NodeId, std::ops::Range<usize>)>,
148 windows: Vec<NodeId>,
149 destroyed_windows: Vec<NodeId>,
152 styles_dirty: bool,
153 resync: BTreeSet<NodeId>,
154 menu_handlers: BTreeMap<Option<NodeId>, std::collections::HashMap<u32, Handler0>>,
156 menu_effects: BTreeMap<Option<NodeId>, mitsuami_reactive::Effect>,
158 next_menu_id: u32,
160 menu_queue: std::collections::VecDeque<u32>,
161 quit_items: BTreeMap<Option<NodeId>, u32>,
164 notification_handlers: BTreeMap<u64, NotificationHandler>,
167 next_notification_handler: u64,
168 notification_queue: std::collections::VecDeque<String>,
170 next_notification: u64,
172 focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
174 focus_dirty: bool,
178 focused: BTreeMap<NodeId, NodeId>,
180 runs_without_windows: bool,
182 quit_requested: bool,
184 commit_scheduler: Option<Rc<dyn Fn()>>,
185 commit_scheduled: bool,
186 language: Option<crate::l10n::LanguageIdentifier>,
188 rtl: bool,
190 observers: BTreeMap<u64, Observer>,
192 next_observer: u64,
193}
194
195struct Observer {
197 target: Box<dyn Fn() -> Option<NodeId>>,
198 size: mitsuami_reactive::Signal<Size>,
199 last: Size,
200}
201
202#[derive(Clone)]
205pub struct Ui {
206 inner: Rc<RefCell<Inner>>,
207 executor: Rc<Executor>,
209 services: Rc<RefCell<Box<dyn Services>>>,
211 l10n: Rc<crate::l10n::Localization>,
214}
215
216#[derive(Clone)]
218pub struct WeakUi {
219 inner: Weak<RefCell<Inner>>,
220 executor: Weak<Executor>,
221 services: Weak<RefCell<Box<dyn Services>>>,
222 l10n: Weak<crate::l10n::Localization>,
223}
224
225impl WeakUi {
226 pub fn upgrade(&self) -> Option<Ui> {
227 Some(Ui {
228 inner: self.inner.upgrade()?,
229 executor: self.executor.upgrade()?,
230 services: self.services.upgrade()?,
231 l10n: self.l10n.upgrade()?,
232 })
233 }
234}
235
236#[derive(Clone, Debug, PartialEq)]
238pub struct NodeInfo {
239 pub id: NodeId,
240 pub kind: WidgetKind,
241 pub props: Vec<Prop>,
242 pub test_id: Option<String>,
243 pub frame: Rect,
245 pub children: Vec<NodeInfo>,
246}
247
248impl Ui {
249 pub fn new(backend: impl Backend + 'static) -> Ui {
250 let mut backend: Box<dyn Backend> = Box::new(backend);
251 let events = EventSink::default();
252 backend.init(events.clone());
253 let metrics = backend.metrics();
254 let services = Rc::new(RefCell::new(backend.services()));
255 let l10n = crate::l10n::Localization::new(backend.locale());
256 let ui = Ui {
257 executor: Rc::default(),
258 services,
259 l10n,
260 inner: Rc::new(RefCell::new(Inner {
261 backend,
262 events,
263 metrics,
264 nodes: BTreeMap::new(),
265 taffy: {
268 let mut taffy = TaffyTree::new();
269 taffy.disable_rounding();
270 taffy
271 },
272 next_id: 1,
273 pending: Vec::new(),
274 created: Default::default(),
275 pending_focus: Vec::new(),
276 pending_selections: Vec::new(),
277 windows: Vec::new(),
278 destroyed_windows: Vec::new(),
279 styles_dirty: true,
280 resync: BTreeSet::new(),
281 focus_orders: BTreeMap::new(),
282 focus_dirty: true,
283 focused: BTreeMap::new(),
284 menu_handlers: BTreeMap::new(),
285 menu_effects: BTreeMap::new(),
286 next_menu_id: 1,
287 menu_queue: Default::default(),
288 quit_items: BTreeMap::new(),
289 notification_handlers: BTreeMap::new(),
290 next_notification_handler: 1,
291 notification_queue: Default::default(),
292 next_notification: 1,
293 runs_without_windows: false,
294 quit_requested: false,
295 commit_scheduler: None,
296 commit_scheduled: false,
297 language: None,
298 rtl: false,
299 observers: BTreeMap::new(),
300 next_observer: 1,
301 })),
302 };
303 let weak = ui.downgrade();
305 ui.l10n.set_on_change(move |_, _| {
306 if let Some(ui) = weak.upgrade() {
307 ui.changed();
308 }
309 });
310 ui
311 }
312
313 pub fn downgrade(&self) -> WeakUi {
314 WeakUi {
315 inner: Rc::downgrade(&self.inner),
316 executor: Rc::downgrade(&self.executor),
317 services: Rc::downgrade(&self.services),
318 l10n: Rc::downgrade(&self.l10n),
319 }
320 }
321
322 pub(crate) fn executor(&self) -> &Executor {
325 &self.executor
326 }
327
328 pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
332 self.spawn_in(future, None)
333 }
334
335 pub(crate) fn spawn_in(
336 &self,
337 future: impl std::future::Future<Output = ()> + 'static,
338 owner: Option<mitsuami_reactive::Owner>,
339 ) -> TaskHandle {
340 let id = self.executor.spawn(Box::pin(future), owner);
341 self.changed();
342 TaskHandle::new(id, self.downgrade())
343 }
344
345 pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
347 Sleep::new(self.clone(), duration)
348 }
349
350 pub fn set_clock(&self, clock: Rc<dyn Clock>) {
352 self.executor.set_clock(clock);
353 }
354
355 pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
358 self.executor.set_wake_ui(wake);
359 }
360
361 pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
364 let now = self.executor.now();
365 self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
366 }
367
368 pub fn set_app_info(&self, info: AppInfo) {
371 self.inner.borrow_mut().backend.set_app_info(&info);
372 }
373
374 pub fn pending_tasks(&self) -> usize {
376 self.executor.task_count()
377 }
378
379 pub fn events(&self) -> EventSink {
380 self.inner.borrow().events.clone()
381 }
382
383 pub fn metrics(&self) -> PlatformMetrics {
384 self.inner.borrow().metrics.clone()
385 }
386
387 pub fn set_locales(&self, locales: crate::l10n::Locales) {
392 self.l10n.set_locales(locales);
393 }
394
395 pub fn set_languages(&self, languages: Option<Vec<String>>) {
399 self.l10n.set_requested(languages);
400 }
401
402 pub fn language(&self) -> crate::l10n::LanguageIdentifier {
405 self.l10n.current()
406 }
407
408 pub fn take_l10n_errors(&self) -> Vec<String> {
411 self.l10n.take_errors()
412 }
413
414 pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
418 self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
419 }
420
421 fn changed(&self) {
422 let schedule = {
423 let mut inner = self.inner.borrow_mut();
424 if inner.commit_scheduled {
425 return;
426 }
427 inner.commit_scheduled = true;
428 inner.commit_scheduler.clone()
429 };
430 if let Some(schedule) = schedule {
431 schedule();
432 }
433 }
434}