mod accessibility;
mod build;
mod focus;
mod layout;
mod pipeline;
mod queries;
mod scroll;
mod services;
mod styles;
mod tree;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::rc::{Rc, Weak};
use taffy::TaffyTree;
use crate::a11y::A11yProps;
use crate::app_info::AppInfo;
use crate::backend::{Backend, EventSink, PlatformMetrics};
use crate::command::{Command, UiEvent};
use crate::custom::CustomProps;
use crate::geometry::{Insets, Point, Rect, Size};
use crate::services::Services;
use crate::style::Style;
use crate::task::{Clock, Executor, Sleep, TaskHandle};
use crate::widget::{NodeId, Prop, RowKey, WidgetKind};
fn in_chrome(kind: WidgetKind) -> bool {
matches!(kind, WidgetKind::ToolbarItem | WidgetKind::Sidebar | WidgetKind::Popover)
}
pub(crate) type Handler = Rc<dyn Fn(&UiEvent)>;
type Handler0 = Rc<dyn Fn()>;
type NotificationHandler = Rc<dyn Fn(&str)>;
type ReopenHandler = Rc<dyn Fn(&crate::services::Reopen)>;
struct Node {
kind: WidgetKind,
parent: Option<NodeId>,
children: Vec<NodeId>,
native_children: Vec<NodeId>,
native_parent: Option<NodeId>,
props: Vec<Prop>,
style: Style,
a11y: A11yProps,
test_id: Option<String>,
tab_index: Option<u32>,
handlers: Vec<Handler>,
taffy: Option<taffy::NodeId>,
frame: Rect,
framed: bool,
window_size: Size,
fit: Fit,
heights: Vec<f32>,
scroll_offset: Point,
row_width: Option<f32>,
tree_indent: crate::TreeIndent,
viewport_insets: Insets,
column_widths: Option<Vec<f32>>,
row_heights: BTreeMap<RowKey, f32>,
strip: Size,
insets: Option<crate::Insets>,
drawn_at: Option<Size>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Fit {
None,
Once,
Follow {
until_resized: bool,
},
}
impl Node {
fn in_full_screen(&self) -> bool {
crate::find_prop!(self.props, FullScreen).unwrap_or(false)
}
fn prop(&self, key: &Prop) -> Option<&Prop> {
self.props.iter().find(|p| p.key() == key.key())
}
fn custom(&self) -> Option<&CustomProps> {
self.props.iter().find_map(|p| match p {
Prop::Custom(custom) => Some(custom),
_ => None,
})
}
fn drawn(&self) -> Option<&CustomProps> {
self.custom().filter(|c| c.is_drawn())
}
}
struct Inner {
backend: Box<dyn Backend>,
events: EventSink,
metrics: PlatformMetrics,
nodes: BTreeMap<NodeId, Node>,
taffy: TaffyTree<NodeId>,
next_id: u32,
pending: Vec<Command>,
created: std::collections::HashSet<NodeId>,
pending_focus: Vec<NodeId>,
pending_present: Vec<NodeId>,
pending_selections: Vec<(NodeId, std::ops::Range<usize>)>,
windows: Vec<NodeId>,
destroyed_windows: Vec<NodeId>,
styles_dirty: bool,
resync: BTreeSet<NodeId>,
menu_handlers: BTreeMap<Option<NodeId>, std::collections::HashMap<u32, Handler0>>,
menu_effects: BTreeMap<Option<NodeId>, mitsuami_reactive::Effect>,
next_menu_id: u32,
menu_queue: std::collections::VecDeque<u32>,
quit_items: BTreeMap<Option<NodeId>, u32>,
notification_handlers: BTreeMap<u64, NotificationHandler>,
next_notification_handler: u64,
notification_queue: std::collections::VecDeque<String>,
next_notification: u64,
reopen_handlers: BTreeMap<u64, ReopenHandler>,
next_reopen_handler: u64,
reopen_queue: std::collections::VecDeque<crate::services::Reopen>,
tray_effect: Option<(u64, mitsuami_reactive::Effect)>,
next_tray: u64,
tray_handlers: std::collections::HashMap<u32, Handler0>,
tray_shown: mitsuami_reactive::Signal<bool>,
app_info_changes: mitsuami_reactive::Signal<u64>,
_signals: SignalRoot,
focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
focus_dirty: bool,
focused: BTreeMap<NodeId, NodeId>,
runs_without_windows: bool,
quit_requested: bool,
commit_scheduler: Option<Rc<dyn Fn()>>,
commit_scheduled: bool,
language: Option<crate::l10n::LanguageIdentifier>,
rtl: bool,
observers: BTreeMap<u64, Observer>,
next_observer: u64,
}
struct Observer {
target: Box<dyn Fn() -> Option<NodeId>>,
size: mitsuami_reactive::Signal<Size>,
last: Size,
}
#[derive(Clone)]
pub struct Ui {
inner: Rc<RefCell<Inner>>,
executor: Rc<Executor>,
services: Rc<RefCell<Box<dyn Services>>>,
l10n: Rc<crate::l10n::Localization>,
}
#[derive(Clone)]
pub struct WeakUi {
inner: Weak<RefCell<Inner>>,
executor: Weak<Executor>,
services: Weak<RefCell<Box<dyn Services>>>,
l10n: Weak<crate::l10n::Localization>,
}
impl WeakUi {
pub fn upgrade(&self) -> Option<Ui> {
Some(Ui {
inner: self.inner.upgrade()?,
executor: self.executor.upgrade()?,
services: self.services.upgrade()?,
l10n: self.l10n.upgrade()?,
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct NodeInfo {
pub id: NodeId,
pub kind: WidgetKind,
pub props: Vec<Prop>,
pub test_id: Option<String>,
pub frame: Rect,
pub children: Vec<NodeInfo>,
}
struct SignalRoot(mitsuami_reactive::Owner);
impl Drop for SignalRoot {
fn drop(&mut self) {
self.0.dispose();
}
}
impl Ui {
pub fn new(backend: impl Backend + 'static) -> Ui {
let mut backend: Box<dyn Backend> = Box::new(backend);
let events = EventSink::default();
backend.init(events.clone());
let metrics = backend.metrics();
let services = Rc::new(RefCell::new(backend.services()));
let l10n = crate::l10n::Localization::new(backend.locale());
let signals = SignalRoot(mitsuami_reactive::Owner::new_root());
let ui = Ui {
executor: Rc::default(),
services,
l10n,
inner: Rc::new(RefCell::new(Inner {
backend,
events,
metrics,
nodes: BTreeMap::new(),
taffy: {
let mut taffy = TaffyTree::new();
taffy.disable_rounding();
taffy
},
next_id: 1,
pending: Vec::new(),
created: Default::default(),
pending_focus: Vec::new(),
pending_present: Vec::new(),
pending_selections: Vec::new(),
windows: Vec::new(),
destroyed_windows: Vec::new(),
styles_dirty: true,
resync: BTreeSet::new(),
focus_orders: BTreeMap::new(),
focus_dirty: true,
focused: BTreeMap::new(),
menu_handlers: BTreeMap::new(),
menu_effects: BTreeMap::new(),
next_menu_id: 1,
menu_queue: Default::default(),
quit_items: BTreeMap::new(),
notification_handlers: BTreeMap::new(),
next_notification_handler: 1,
notification_queue: Default::default(),
next_notification: 1,
reopen_handlers: BTreeMap::new(),
next_reopen_handler: 1,
reopen_queue: Default::default(),
tray_effect: None,
next_tray: 1,
tray_handlers: Default::default(),
tray_shown: signals.0.with(|| mitsuami_reactive::signal(false)),
app_info_changes: signals.0.with(|| mitsuami_reactive::signal(0)),
_signals: signals,
runs_without_windows: false,
quit_requested: false,
commit_scheduler: None,
commit_scheduled: false,
language: None,
rtl: false,
observers: BTreeMap::new(),
next_observer: 1,
})),
};
let weak = ui.downgrade();
ui.l10n.set_on_change(move |_, _| {
if let Some(ui) = weak.upgrade() {
ui.changed();
}
});
ui
}
pub fn downgrade(&self) -> WeakUi {
WeakUi {
inner: Rc::downgrade(&self.inner),
executor: Rc::downgrade(&self.executor),
services: Rc::downgrade(&self.services),
l10n: Rc::downgrade(&self.l10n),
}
}
pub(crate) fn executor(&self) -> &Executor {
&self.executor
}
pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
self.spawn_in(future, None)
}
pub(crate) fn spawn_in(
&self,
future: impl std::future::Future<Output = ()> + 'static,
owner: Option<mitsuami_reactive::Owner>,
) -> TaskHandle {
let id = self.executor.spawn(Box::pin(future), owner);
self.changed();
TaskHandle::new(id, self.downgrade())
}
pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
Sleep::new(self.clone(), duration)
}
pub fn set_clock(&self, clock: Rc<dyn Clock>) {
self.executor.set_clock(clock);
}
pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
self.executor.set_wake_ui(wake);
}
pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
let now = self.executor.now();
self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
}
pub fn set_app_info(&self, info: AppInfo) {
let changes = {
let mut inner = self.inner.borrow_mut();
inner.backend.set_app_info(&info);
inner.app_info_changes
};
changes.update(|n| *n += 1);
}
pub fn pending_tasks(&self) -> usize {
self.executor.task_count()
}
pub fn events(&self) -> EventSink {
self.inner.borrow().events.clone()
}
pub fn metrics(&self) -> PlatformMetrics {
self.inner.borrow().metrics.clone()
}
pub fn set_locales(&self, locales: crate::l10n::Locales) {
self.l10n.set_locales(locales);
}
pub fn set_languages(&self, languages: Option<Vec<String>>) {
self.l10n.set_requested(languages);
}
pub fn language(&self) -> crate::l10n::LanguageIdentifier {
self.l10n.current()
}
pub fn take_l10n_errors(&self) -> Vec<String> {
self.l10n.take_errors()
}
pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
}
fn changed(&self) {
let schedule = {
let mut inner = self.inner.borrow_mut();
if inner.commit_scheduled {
return;
}
inner.commit_scheduled = true;
inner.commit_scheduler.clone()
};
if let Some(schedule) = schedule {
schedule();
}
}
}