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()>;
45
46struct Node {
47 kind: WidgetKind,
48 parent: Option<NodeId>,
49 children: Vec<NodeId>,
50 native_children: Vec<NodeId>,
52 native_parent: Option<NodeId>,
53 props: Vec<Prop>,
54 style: Style,
55 a11y: A11yProps,
56 test_id: Option<String>,
57 tab_index: Option<u32>,
58 handlers: Vec<Handler>,
59 taffy: Option<taffy::NodeId>,
60 frame: Rect,
62 framed: bool,
65 window_size: Size,
67 fit: Fit,
69 heights: Vec<f32>,
73 scroll_offset: Point,
75 row_width: Option<f32>,
77 tree_indent: crate::TreeIndent,
79 viewport_insets: Insets,
81 column_widths: Option<Vec<f32>>,
83 row_heights: BTreeMap<RowKey, f32>,
86 strip: Size,
89 insets: Option<crate::Insets>,
92 drawn_at: Option<Size>,
95}
96
97#[derive(Clone, Copy, Debug, PartialEq)]
99enum Fit {
100 None,
101 Once,
103 Follow {
104 until_resized: bool,
105 },
106}
107
108impl Node {
109 fn in_full_screen(&self) -> bool {
110 crate::find_prop!(self.props, FullScreen).unwrap_or(false)
111 }
112
113 fn prop(&self, key: &Prop) -> Option<&Prop> {
114 self.props.iter().find(|p| p.key() == key.key())
115 }
116
117 fn custom(&self) -> Option<&CustomProps> {
118 self.props.iter().find_map(|p| match p {
119 Prop::Custom(custom) => Some(custom),
120 _ => None,
121 })
122 }
123
124 fn drawn(&self) -> Option<&CustomProps> {
126 self.custom().filter(|c| c.is_drawn())
127 }
128}
129
130struct Inner {
131 backend: Box<dyn Backend>,
132 events: EventSink,
133 metrics: PlatformMetrics,
134 nodes: BTreeMap<NodeId, Node>,
135 taffy: TaffyTree<NodeId>,
136 next_id: u32,
137 pending: Vec<Command>,
138 created: std::collections::HashSet<NodeId>,
141 pending_focus: Vec<NodeId>,
144 pending_selections: Vec<(NodeId, std::ops::Range<usize>)>,
146 windows: Vec<NodeId>,
147 destroyed_windows: Vec<NodeId>,
150 styles_dirty: bool,
151 resync: BTreeSet<NodeId>,
152 menu_handlers: BTreeMap<Option<NodeId>, std::collections::HashMap<u32, Handler0>>,
154 menu_effects: BTreeMap<Option<NodeId>, mitsuami_reactive::Effect>,
156 next_menu_id: u32,
158 menu_queue: std::collections::VecDeque<u32>,
159 quit_items: BTreeMap<Option<NodeId>, u32>,
162 focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
164 focus_dirty: bool,
168 focused: BTreeMap<NodeId, NodeId>,
170 commit_scheduler: Option<Rc<dyn Fn()>>,
171 commit_scheduled: bool,
172 language: Option<crate::l10n::LanguageIdentifier>,
174 rtl: bool,
176 observers: BTreeMap<u64, Observer>,
178 next_observer: u64,
179}
180
181struct Observer {
183 target: Box<dyn Fn() -> Option<NodeId>>,
184 size: mitsuami_reactive::Signal<Size>,
185 last: Size,
186}
187
188#[derive(Clone)]
191pub struct Ui {
192 inner: Rc<RefCell<Inner>>,
193 executor: Rc<Executor>,
195 services: Rc<RefCell<Box<dyn Services>>>,
197 l10n: Rc<crate::l10n::Localization>,
200}
201
202#[derive(Clone)]
204pub struct WeakUi {
205 inner: Weak<RefCell<Inner>>,
206 executor: Weak<Executor>,
207 services: Weak<RefCell<Box<dyn Services>>>,
208 l10n: Weak<crate::l10n::Localization>,
209}
210
211impl WeakUi {
212 pub fn upgrade(&self) -> Option<Ui> {
213 Some(Ui {
214 inner: self.inner.upgrade()?,
215 executor: self.executor.upgrade()?,
216 services: self.services.upgrade()?,
217 l10n: self.l10n.upgrade()?,
218 })
219 }
220}
221
222#[derive(Clone, Debug, PartialEq)]
224pub struct NodeInfo {
225 pub id: NodeId,
226 pub kind: WidgetKind,
227 pub props: Vec<Prop>,
228 pub test_id: Option<String>,
229 pub frame: Rect,
231 pub children: Vec<NodeInfo>,
232}
233
234impl Ui {
235 pub fn new(backend: impl Backend + 'static) -> Ui {
236 let mut backend: Box<dyn Backend> = Box::new(backend);
237 let events = EventSink::default();
238 backend.init(events.clone());
239 let metrics = backend.metrics();
240 let services = Rc::new(RefCell::new(backend.services()));
241 let l10n = crate::l10n::Localization::new(backend.locale());
242 let ui = Ui {
243 executor: Rc::default(),
244 services,
245 l10n,
246 inner: Rc::new(RefCell::new(Inner {
247 backend,
248 events,
249 metrics,
250 nodes: BTreeMap::new(),
251 taffy: {
254 let mut taffy = TaffyTree::new();
255 taffy.disable_rounding();
256 taffy
257 },
258 next_id: 1,
259 pending: Vec::new(),
260 created: Default::default(),
261 pending_focus: Vec::new(),
262 pending_selections: Vec::new(),
263 windows: Vec::new(),
264 destroyed_windows: Vec::new(),
265 styles_dirty: true,
266 resync: BTreeSet::new(),
267 focus_orders: BTreeMap::new(),
268 focus_dirty: true,
269 focused: BTreeMap::new(),
270 menu_handlers: BTreeMap::new(),
271 menu_effects: BTreeMap::new(),
272 next_menu_id: 1,
273 menu_queue: Default::default(),
274 quit_items: BTreeMap::new(),
275 commit_scheduler: None,
276 commit_scheduled: false,
277 language: None,
278 rtl: false,
279 observers: BTreeMap::new(),
280 next_observer: 1,
281 })),
282 };
283 let weak = ui.downgrade();
285 ui.l10n.set_on_change(move |_, _| {
286 if let Some(ui) = weak.upgrade() {
287 ui.changed();
288 }
289 });
290 ui
291 }
292
293 pub fn downgrade(&self) -> WeakUi {
294 WeakUi {
295 inner: Rc::downgrade(&self.inner),
296 executor: Rc::downgrade(&self.executor),
297 services: Rc::downgrade(&self.services),
298 l10n: Rc::downgrade(&self.l10n),
299 }
300 }
301
302 pub(crate) fn executor(&self) -> &Executor {
305 &self.executor
306 }
307
308 pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
312 self.spawn_in(future, None)
313 }
314
315 pub(crate) fn spawn_in(
316 &self,
317 future: impl std::future::Future<Output = ()> + 'static,
318 owner: Option<mitsuami_reactive::Owner>,
319 ) -> TaskHandle {
320 let id = self.executor.spawn(Box::pin(future), owner);
321 self.changed();
322 TaskHandle::new(id, self.downgrade())
323 }
324
325 pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
327 Sleep::new(self.clone(), duration)
328 }
329
330 pub fn set_clock(&self, clock: Rc<dyn Clock>) {
332 self.executor.set_clock(clock);
333 }
334
335 pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
338 self.executor.set_wake_ui(wake);
339 }
340
341 pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
344 let now = self.executor.now();
345 self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
346 }
347
348 pub fn set_app_info(&self, info: AppInfo) {
351 self.inner.borrow_mut().backend.set_app_info(&info);
352 }
353
354 pub fn pending_tasks(&self) -> usize {
356 self.executor.task_count()
357 }
358
359 pub fn events(&self) -> EventSink {
360 self.inner.borrow().events.clone()
361 }
362
363 pub fn metrics(&self) -> PlatformMetrics {
364 self.inner.borrow().metrics.clone()
365 }
366
367 pub fn set_locales(&self, locales: crate::l10n::Locales) {
372 self.l10n.set_locales(locales);
373 }
374
375 pub fn set_languages(&self, languages: Option<Vec<String>>) {
379 self.l10n.set_requested(languages);
380 }
381
382 pub fn language(&self) -> crate::l10n::LanguageIdentifier {
385 self.l10n.current()
386 }
387
388 pub fn take_l10n_errors(&self) -> Vec<String> {
391 self.l10n.take_errors()
392 }
393
394 pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
398 self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
399 }
400
401 fn changed(&self) {
402 let schedule = {
403 let mut inner = self.inner.borrow_mut();
404 if inner.commit_scheduled {
405 return;
406 }
407 inner.commit_scheduled = true;
408 inner.commit_scheduler.clone()
409 };
410 if let Some(schedule) = schedule {
411 schedule();
412 }
413 }
414}