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 commit_scheduler: Option<Rc<dyn Fn()>>,
181 commit_scheduled: bool,
182 language: Option<crate::l10n::LanguageIdentifier>,
184 rtl: bool,
186 observers: BTreeMap<u64, Observer>,
188 next_observer: u64,
189}
190
191struct Observer {
193 target: Box<dyn Fn() -> Option<NodeId>>,
194 size: mitsuami_reactive::Signal<Size>,
195 last: Size,
196}
197
198#[derive(Clone)]
201pub struct Ui {
202 inner: Rc<RefCell<Inner>>,
203 executor: Rc<Executor>,
205 services: Rc<RefCell<Box<dyn Services>>>,
207 l10n: Rc<crate::l10n::Localization>,
210}
211
212#[derive(Clone)]
214pub struct WeakUi {
215 inner: Weak<RefCell<Inner>>,
216 executor: Weak<Executor>,
217 services: Weak<RefCell<Box<dyn Services>>>,
218 l10n: Weak<crate::l10n::Localization>,
219}
220
221impl WeakUi {
222 pub fn upgrade(&self) -> Option<Ui> {
223 Some(Ui {
224 inner: self.inner.upgrade()?,
225 executor: self.executor.upgrade()?,
226 services: self.services.upgrade()?,
227 l10n: self.l10n.upgrade()?,
228 })
229 }
230}
231
232#[derive(Clone, Debug, PartialEq)]
234pub struct NodeInfo {
235 pub id: NodeId,
236 pub kind: WidgetKind,
237 pub props: Vec<Prop>,
238 pub test_id: Option<String>,
239 pub frame: Rect,
241 pub children: Vec<NodeInfo>,
242}
243
244impl Ui {
245 pub fn new(backend: impl Backend + 'static) -> Ui {
246 let mut backend: Box<dyn Backend> = Box::new(backend);
247 let events = EventSink::default();
248 backend.init(events.clone());
249 let metrics = backend.metrics();
250 let services = Rc::new(RefCell::new(backend.services()));
251 let l10n = crate::l10n::Localization::new(backend.locale());
252 let ui = Ui {
253 executor: Rc::default(),
254 services,
255 l10n,
256 inner: Rc::new(RefCell::new(Inner {
257 backend,
258 events,
259 metrics,
260 nodes: BTreeMap::new(),
261 taffy: {
264 let mut taffy = TaffyTree::new();
265 taffy.disable_rounding();
266 taffy
267 },
268 next_id: 1,
269 pending: Vec::new(),
270 created: Default::default(),
271 pending_focus: Vec::new(),
272 pending_selections: Vec::new(),
273 windows: Vec::new(),
274 destroyed_windows: Vec::new(),
275 styles_dirty: true,
276 resync: BTreeSet::new(),
277 focus_orders: BTreeMap::new(),
278 focus_dirty: true,
279 focused: BTreeMap::new(),
280 menu_handlers: BTreeMap::new(),
281 menu_effects: BTreeMap::new(),
282 next_menu_id: 1,
283 menu_queue: Default::default(),
284 quit_items: BTreeMap::new(),
285 notification_handlers: BTreeMap::new(),
286 next_notification_handler: 1,
287 notification_queue: Default::default(),
288 next_notification: 1,
289 commit_scheduler: None,
290 commit_scheduled: false,
291 language: None,
292 rtl: false,
293 observers: BTreeMap::new(),
294 next_observer: 1,
295 })),
296 };
297 let weak = ui.downgrade();
299 ui.l10n.set_on_change(move |_, _| {
300 if let Some(ui) = weak.upgrade() {
301 ui.changed();
302 }
303 });
304 ui
305 }
306
307 pub fn downgrade(&self) -> WeakUi {
308 WeakUi {
309 inner: Rc::downgrade(&self.inner),
310 executor: Rc::downgrade(&self.executor),
311 services: Rc::downgrade(&self.services),
312 l10n: Rc::downgrade(&self.l10n),
313 }
314 }
315
316 pub(crate) fn executor(&self) -> &Executor {
319 &self.executor
320 }
321
322 pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
326 self.spawn_in(future, None)
327 }
328
329 pub(crate) fn spawn_in(
330 &self,
331 future: impl std::future::Future<Output = ()> + 'static,
332 owner: Option<mitsuami_reactive::Owner>,
333 ) -> TaskHandle {
334 let id = self.executor.spawn(Box::pin(future), owner);
335 self.changed();
336 TaskHandle::new(id, self.downgrade())
337 }
338
339 pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
341 Sleep::new(self.clone(), duration)
342 }
343
344 pub fn set_clock(&self, clock: Rc<dyn Clock>) {
346 self.executor.set_clock(clock);
347 }
348
349 pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
352 self.executor.set_wake_ui(wake);
353 }
354
355 pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
358 let now = self.executor.now();
359 self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
360 }
361
362 pub fn set_app_info(&self, info: AppInfo) {
365 self.inner.borrow_mut().backend.set_app_info(&info);
366 }
367
368 pub fn pending_tasks(&self) -> usize {
370 self.executor.task_count()
371 }
372
373 pub fn events(&self) -> EventSink {
374 self.inner.borrow().events.clone()
375 }
376
377 pub fn metrics(&self) -> PlatformMetrics {
378 self.inner.borrow().metrics.clone()
379 }
380
381 pub fn set_locales(&self, locales: crate::l10n::Locales) {
386 self.l10n.set_locales(locales);
387 }
388
389 pub fn set_languages(&self, languages: Option<Vec<String>>) {
393 self.l10n.set_requested(languages);
394 }
395
396 pub fn language(&self) -> crate::l10n::LanguageIdentifier {
399 self.l10n.current()
400 }
401
402 pub fn take_l10n_errors(&self) -> Vec<String> {
405 self.l10n.take_errors()
406 }
407
408 pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
412 self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
413 }
414
415 fn changed(&self) {
416 let schedule = {
417 let mut inner = self.inner.borrow_mut();
418 if inner.commit_scheduled {
419 return;
420 }
421 inner.commit_scheduled = true;
422 inner.commit_scheduler.clone()
423 };
424 if let Some(schedule) = schedule {
425 schedule();
426 }
427 }
428}