1use std::cell::{Cell, RefCell};
2use std::collections::{BTreeMap, BTreeSet};
3use std::rc::Rc;
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::time::Duration;
6
7use rhai::{
8 Array, CustomType, Dynamic, Engine, EvalAltResult, FLOAT, FnPtr, INT, ImmutableString, Map,
9 NativeCallContext, Position, TypeBuilder,
10};
11use thiserror::Error;
12
13use crate::{
14 ActionError, ActionId, ActionInvocation, ActionRegistry, AssetError, AssetId, AssetRegistry,
15 AsyncRuntimeError, AsyncScope, CalendarClock, CapabilityError, CapabilityId,
16 CapabilityRegistry, ComponentInstancePath, DateStyle, EventSchema, ImageDecodeHandle,
17 LocaleError, LocaleManager, MotionKey, MotionRuntime, NumberFormatOptions, OpaqueHandle,
18 ResponsiveError, ResponsiveRuntime, ScriptCallback, ScriptGeneration, ScriptWindowSpec,
19 StateError, StateStore, StoreError, StoreId, StoreRegistry, SubscriptionCloseReason,
20 SubscriptionDeliveryPolicy, SubscriptionHandle, SubscriptionOptions, SubscriptionRegistration,
21 SubscriptionRegistry, TaskHandle, TaskRegistry, TextDirection, ThemeError, ThemeManager,
22 ThemePreference, ThemeSelection, UiEvent, UiValue, UiValueError, UiValuePath, UiValuePathError,
23 UiValuePathSegment, WindowCommandError, WindowCommandRegistry,
24};
25
26fn domain_is_within(domain: &str, scope: &str) -> bool {
27 domain == scope
28 || domain
29 .strip_prefix(scope)
30 .is_some_and(|suffix| suffix.starts_with('/'))
31}
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub enum ExecutionPhase {
35 Init,
36 Render,
37 Event,
38 Suspend,
39 Resume,
40 Dispose,
41}
42
43#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
46pub struct ComponentIncarnation(u64);
47
48impl ComponentIncarnation {
49 pub(crate) const fn unscoped() -> Self {
50 Self(0)
51 }
52
53 #[must_use]
54 pub const fn get(self) -> u64 {
55 self.0
56 }
57}
58
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60struct RuntimeStateId(u64);
61
62impl Default for RuntimeStateId {
63 fn default() -> Self {
64 static NEXT_ID: AtomicU64 = AtomicU64::new(1);
65 Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
66 }
67}
68
69enum ThemeTarget {
70 App,
71 Window(String),
72 Local,
73}
74
75impl ExecutionPhase {
76 const fn allows_mutation(self) -> bool {
77 matches!(
78 self,
79 Self::Init | Self::Event | Self::Suspend | Self::Resume | Self::Dispose
80 )
81 }
82
83 const fn allows_async_start(self) -> bool {
84 matches!(self, Self::Init | Self::Event | Self::Resume)
85 }
86}
87
88#[derive(Debug, Default)]
89pub struct UiRuntimeState {
90 runtime_id: RuntimeStateId,
91 transaction_depth: usize,
92 pub component_state: StateStore,
93 pub stores: StoreRegistry,
94 pub native_collections: crate::NativeCollectionRegistry,
95 pub native_documents: crate::NativeTextDocumentRegistry,
96 #[cfg(feature = "charts")]
97 pub native_chart_data: BTreeMap<String, crate::NativeChartData>,
98 pub actions: ActionRegistry,
99 pub key_bindings: Vec<crate::KeyBindingSpec>,
101 pub audit_rules: crate::AuditRules,
103 pub capabilities: CapabilityRegistry,
104 pub dropped_files: crate::DroppedFiles,
107 pub tasks: TaskRegistry,
108 pub subscriptions: SubscriptionRegistry,
109 pub timers: crate::TimerRegistry,
110 pub locale: Option<LocaleManager>,
111 pub calendar_clock: CalendarClock,
112 pub wall_clock: crate::WallClock,
113 pub clock: crate::RuntimeClock,
114 pub theme: Option<ThemeManager>,
115 component_styles: crate::ComponentStyleSheet,
116 pub assets: AssetRegistry,
117 pub motions: MotionRuntime,
118 pub(crate) page_visibility: crate::retained_page::PageVisibility,
119 pub effects: crate::EffectRegistry,
120 pub(crate) effect_cascades: crate::effect::EffectCascadeBudget,
121 pub signals: crate::SignalRegistry,
122 pub element_refs: crate::ElementRefRegistry,
123 pub(crate) geometry: crate::GeometryRegistry,
124 pub(crate) pointer_capture: crate::PointerCaptureRegistry,
125 presentations: BTreeMap<String, ViewPresentationState>,
126 pub budgets: crate::RuntimeBudgets,
127 pub virtual_requests: crate::VirtualRequestRegistry,
128 pub windows: WindowCommandRegistry,
129 pub responsive: ResponsiveRuntime,
130 pub(crate) environment_dependencies:
131 crate::environment_dependency::EnvironmentDependencyRegistry,
132 pub motion_values: BTreeMap<MotionKey, f64>,
133 pub(crate) motion_ghosts: Vec<crate::motion::MotionGhost>,
134 pub(crate) window_appearances: BTreeMap<String, crate::SystemAppearance>,
135 pub traces: crate::TraceBuffer,
136 component_event_handlers: BTreeMap<(ComponentInstancePath, String), ScriptCallback>,
137 component_incarnations: BTreeMap<ComponentInstancePath, ComponentIncarnation>,
138 next_component_incarnation: u64,
139 dirty: BTreeSet<ComponentInstancePath>,
140 pending_events: Vec<PendingEvent>,
141 pending_actions: Vec<ActionInvocation>,
142 pending_async: Vec<crate::AsyncDelivery>,
143 pending_element_commands: Vec<crate::element_ref::ElementCommand>,
144 repaint_windows: BTreeSet<String>,
145 component_style_generation: u64,
146 origin: crate::InvocationOrigin,
148 pub(crate) dispatch_owner: Option<SemanticDispatchOwner>,
150 dispatch_leases: Vec<Rc<SemanticDispatchSource>>,
152}
153
154impl UiRuntimeState {
155 pub(crate) fn reconcile_page_visibility(
156 &mut self,
157 tree: &crate::RetainedUiTree,
158 root: &ComponentInstancePath,
159 domain: &str,
160 ) {
161 let dirty =
162 self.page_visibility
163 .reconcile(tree, root, domain, &mut self.motions, self.clock.now());
164 self.mark_dirty(dirty);
165 }
166
167 #[must_use]
169 pub fn invocation_origin(&self) -> &crate::InvocationOrigin {
170 &self.origin
171 }
172
173 pub(crate) fn replace_origin(
176 &mut self,
177 origin: crate::InvocationOrigin,
178 ) -> crate::InvocationOrigin {
179 self.tasks.set_origin_root(&origin);
180 self.timers.set_origin_root(&origin);
181 std::mem::replace(&mut self.origin, origin)
182 }
183
184 pub(crate) fn update_window_appearance(
185 &mut self,
186 window: &str,
187 appearance: crate::SystemAppearance,
188 ) -> bool {
189 let previous = self
190 .window_appearances
191 .insert(window.to_owned(), appearance)
192 .unwrap_or(crate::SystemAppearance::Dark);
193 let changed = previous != appearance;
194 if changed {
195 let invalidated = self
196 .environment_dependencies
197 .invalidate_theme_window(window);
198 self.mark_dirty(invalidated);
199 }
200 changed
201 }
202 const SUSPENDED_DELIVERY_CAPACITY: usize = 256;
203 #[must_use]
204 pub fn new() -> Self {
205 Self::default()
206 }
207
208 pub(crate) fn ensure_component_incarnation(
209 &mut self,
210 component: &ComponentInstancePath,
211 ) -> ComponentIncarnation {
212 if let Some(incarnation) = self.component_incarnations.get(component) {
213 return *incarnation;
214 }
215 let next = self.next_component_incarnation.max(1);
216 let incarnation = ComponentIncarnation(next);
217 self.next_component_incarnation = next.saturating_add(1);
218 self.component_incarnations
219 .insert(component.clone(), incarnation);
220 incarnation
221 }
222
223 pub(crate) fn component_incarnation(
224 &self,
225 component: &ComponentInstancePath,
226 ) -> Option<ComponentIncarnation> {
227 self.component_incarnations.get(component).copied()
228 }
229
230 pub(crate) fn component_incarnations_snapshot(
231 &self,
232 ) -> BTreeMap<ComponentInstancePath, ComponentIncarnation> {
233 self.component_incarnations.clone()
234 }
235
236 pub(crate) fn ensure_presentation(&mut self, view: &str) {
237 self.presentations.entry(view.to_owned()).or_default();
238 }
239
240 pub fn presentation_geometry(&mut self, view: &str) -> crate::GeometryRegistry {
242 self.ensure_presentation(view);
243 self.geometry_for(Some(view))
244 }
245
246 pub fn presentation_pointer_capture(&mut self, view: &str) -> crate::PointerCaptureRegistry {
248 self.ensure_presentation(view);
249 self.pointer_capture_for(Some(view))
250 }
251
252 pub(crate) fn geometry_for(&self, view: Option<&str>) -> crate::GeometryRegistry {
253 view.and_then(|view| self.presentations.get(view))
254 .map_or_else(|| self.geometry.clone(), |state| state.geometry.clone())
255 }
256
257 pub(crate) fn pointer_capture_for(&self, view: Option<&str>) -> crate::PointerCaptureRegistry {
258 view.and_then(|view| self.presentations.get(view))
259 .map_or_else(
260 || self.pointer_capture.clone(),
261 |state| state.pointer_capture.clone(),
262 )
263 }
264
265 pub(crate) fn remove_presentation(&mut self, view: &str) {
266 self.presentations.remove(view);
267 }
268
269 pub fn set_component_state_from_host(
276 &mut self,
277 component: &ComponentInstancePath,
278 field: &str,
279 value: UiValue,
280 ) -> Result<bool, crate::StateError> {
281 let changed = self.component_state.set(component, field, value)?;
282 if changed {
283 self.mark_dirty_from_host([component.clone()]);
284 }
285 Ok(changed)
286 }
287
288 pub fn replace_native_collection_from_host(
294 &mut self,
295 name: &str,
296 collection: crate::NativeCollection,
297 ) -> Result<bool, crate::NativeCollectionError> {
298 let invalidated = self.native_collections.replace(name, collection)?;
299 let changed = !invalidated.is_empty();
300 self.mark_dirty_from_host(invalidated);
301 Ok(changed)
302 }
303
304 pub fn register_native_collection_from_host(
311 &mut self,
312 _root: &ComponentInstancePath,
313 name: &str,
314 collection: crate::NativeCollection,
315 ) -> Result<(), crate::NativeCollectionError> {
316 let invalidated = self
317 .native_collections
318 .register_with_invalidated(name.to_owned(), collection)?;
319 self.mark_dirty_from_host(invalidated);
320 Ok(())
321 }
322
323 pub fn register_native_text_document_from_host(
328 &mut self,
329 name: &str,
330 document: crate::NativeTextDocument,
331 ) -> Result<(), crate::DocumentError> {
332 let invalidated = self
333 .native_documents
334 .register_with_invalidated(name.to_owned(), document)?;
335 self.mark_dirty_from_host(invalidated);
336 Ok(())
337 }
338
339 pub fn release_native_text_document_from_host(
344 &mut self,
345 name: &str,
346 ) -> Result<bool, crate::DocumentError> {
347 let invalidated = self.native_documents.release(name)?;
348 let changed = !invalidated.is_empty();
349 self.mark_dirty_from_host(invalidated);
350 Ok(changed)
351 }
352
353 pub fn replace_native_text_document_from_host(
359 &mut self,
360 name: &str,
361 document: crate::NativeTextDocument,
362 ) -> Result<bool, crate::DocumentError> {
363 let invalidated = self.native_documents.replace(name, document)?;
364 let changed = !invalidated.is_empty();
365 self.mark_dirty_from_host(invalidated);
366 Ok(changed)
367 }
368
369 pub fn append_native_text_document_from_host(
377 &mut self,
378 name: &str,
379 text: &str,
380 ) -> Result<bool, crate::DocumentError> {
381 let invalidated = self.native_documents.append(name, text)?;
382 let changed = !invalidated.is_empty();
383 self.mark_dirty_from_host(invalidated);
384 Ok(changed)
385 }
386
387 #[cfg(feature = "charts")]
393 pub fn register_native_chart_data(
394 &mut self,
395 name: impl Into<String>,
396 data: crate::NativeChartData,
397 ) -> Result<(), UiContextError> {
398 let name = name.into();
399 if name.is_empty()
400 || name.len() > 128
401 || !name
402 .chars()
403 .next()
404 .is_some_and(|character| character.is_ascii_alphabetic())
405 || !name
406 .chars()
407 .all(|character| character.is_ascii_alphanumeric() || character == '_')
408 {
409 return Err(UiContextError::InvalidChartDataName(name));
410 }
411 self.native_chart_data.insert(name, data);
412 Ok(())
413 }
414
415 pub fn replace_theme_variant_from_host(
422 &mut self,
423 variant: crate::ThemeVariant,
424 ) -> Result<(), crate::ThemeError> {
425 self.theme
426 .as_mut()
427 .ok_or(crate::ThemeError::NoVariants)?
428 .replace_variant(variant)?;
429 self.mark_dirty_from_host(self.component_state.paths());
430 Ok(())
431 }
432
433 pub fn select_theme_from_host(
439 &mut self,
440 family: &str,
441 variant: &str,
442 ) -> Result<bool, crate::ThemeError> {
443 let theme = self.theme.as_mut().ok_or(crate::ThemeError::NoVariants)?;
444 let previous = theme.generation();
445 theme.set_app(ThemePreference::Fixed {
446 selection: ThemeSelection::new(family, variant),
447 })?;
448 let changed = theme.generation() != previous;
449 if changed {
450 let invalidated = self.environment_dependencies.invalidate_theme_app();
451 self.mark_dirty_from_host(invalidated);
452 self.mark_all_windows_dirty();
453 }
454 Ok(changed)
455 }
456
457 pub fn select_locale_from_host(&mut self, locale: &str) -> Result<bool, crate::LocaleError> {
463 let locales = self
464 .locale
465 .as_mut()
466 .ok_or_else(|| crate::LocaleError::UnknownLocale(locale.to_owned()))?;
467 let previous = locales.generation();
468 locales.set_app(locale)?;
469 let changed = locales.generation() != previous;
470 if changed {
471 let invalidated = self.environment_dependencies.invalidate_locale_app();
472 self.mark_dirty_from_host(invalidated);
473 self.mark_all_windows_repaint();
474 }
475 Ok(changed)
476 }
477
478 pub fn set_motion_preference_from_host(&mut self, preference: crate::MotionPreference) -> bool {
484 let previous = self.motions.preference();
485 self.motions.set_preference(preference);
486 let changed = self.motions.preference() != previous;
487 if changed {
488 let now = self.clock.now();
489 self.motion_values = self.motions.snapshot(now);
490 self.mark_dirty_from_host(self.component_state.paths());
491 self.mark_all_windows_dirty();
492 }
493 changed
494 }
495
496 pub fn replace_component_styles_from_host(
501 &mut self,
502 styles: crate::ComponentStyleSheet,
503 ) -> bool {
504 if self.component_styles == styles {
505 return false;
506 }
507 self.component_styles = styles;
508 self.component_style_generation = self.component_style_generation.saturating_add(1);
509 self.mark_dirty_from_host(self.component_state.paths());
510 true
511 }
512
513 pub(crate) const fn component_style_generation(&self) -> u64 {
514 self.component_style_generation
515 }
516
517 pub(crate) const fn component_styles(&self) -> &crate::ComponentStyleSheet {
518 &self.component_styles
519 }
520
521 pub(crate) fn trace_subscription_closures(&mut self) {
522 for closure in self.subscriptions.take_closures() {
523 let scope = match closure.scope {
524 AsyncScope::App => "/App".to_owned(),
525 AsyncScope::Window(window) => format!("window:{window}"),
526 AsyncScope::Component(component) => component.to_string(),
527 AsyncScope::Effect {
528 component,
529 key,
530 activation,
531 } => format!("{component}/effect[{key}]#{activation}"),
532 };
533 self.traces.push(
534 crate::RuntimeTraceKind::Subscription,
535 scope,
536 format!("close {}: {}", closure.label, closure.reason),
537 None,
538 false,
539 );
540 }
541 }
542
543 pub fn release_window(
549 &mut self,
550 window: &str,
551 root: &ComponentInstancePath,
552 ) -> Result<(), AssetError> {
553 self.tasks
554 .cancel_scope(&AsyncScope::Window(window.to_owned()));
555 self.tasks.cancel_component_scope(root);
556 self.timers.cancel_component_scope(root);
557 self.subscriptions
558 .cancel_scope(&AsyncScope::Window(window.to_owned()));
559 self.subscriptions.cancel_component_scope(root);
560 self.assets.cancel_window_scope(window, root)?;
561 self.stores.remove_window(window);
562 self.native_collections.remove_reader_scope(root);
563 self.native_documents.remove_reader_scope(root);
564 self.virtual_requests.release_scope(root);
565 self.component_state.remove_scope(root);
566 self.effect_cascades.remove_scope(root);
567 self.component_event_handlers
568 .retain(|(path, _), _| !path.is_within(root));
569 self.component_incarnations
570 .retain(|path, _| !path.is_within(root));
571 self.actions.remove_component_scope(root);
572 self.dirty.retain(|path| !path.is_within(root));
573 self.pending_events
574 .retain(|event| !event.target.is_within(root));
575 self.pending_actions.retain(|action| {
576 !action
577 .callback
578 .component()
579 .is_some_and(|path| path.is_within(root))
580 });
581 self.pending_async.retain(|delivery| match &delivery.scope {
582 AsyncScope::App => true,
583 AsyncScope::Window(id) => id != window,
584 AsyncScope::Component(_) | AsyncScope::Effect { .. } => {
585 !delivery.scope.is_within_component(root)
586 }
587 });
588 self.pending_element_commands
589 .retain(|command| command.window() != window);
590 self.environment_dependencies.remove_window(window);
591 self.environment_dependencies.remove_scope(root);
592 self.repaint_windows.remove(window);
593 self.window_appearances.remove(window);
594 if let Some(theme) = self.theme.as_mut() {
595 theme.remove_window(window);
596 theme.remove_scope(root);
597 }
598 if let Some(locale) = self.locale.as_mut() {
599 locale.remove_window(window);
600 locale.remove_scope(root);
601 }
602 let window_scope = format!("window:{window}");
603 self.page_visibility
604 .remove_scope(root, &format!("{window_scope}/"));
605 self.motions.release_node_scope(&window_scope);
606 let removed_ghosts = self
607 .motion_ghosts
608 .iter()
609 .filter(|ghost| domain_is_within(&ghost.domain, &window_scope))
610 .map(|ghost| ghost.path.clone())
611 .collect::<Vec<_>>();
612 self.motion_ghosts
613 .retain(|ghost| !domain_is_within(&ghost.domain, &window_scope));
614 for path in removed_ghosts {
615 self.motions.cancel_node_scope(&path);
616 }
617 self.motions.discard_timeline_events_in_scope(&window_scope);
618 self.motion_values = self.motions.snapshot(self.clock.now());
619 self.effects.remove_scope(root);
620 self.signals.remove_scope(root);
621 self.element_refs.remove_scope(root);
622 self.geometry.remove_scope(root);
623 for presentation in self.presentations.values() {
624 presentation.geometry.remove_scope(root);
625 }
626 self.windows.remove(window);
627 self.responsive.remove_window(window);
628 Ok(())
629 }
630
631 pub(crate) fn queue_async(
632 &mut self,
633 deliveries: impl IntoIterator<Item = crate::AsyncDelivery>,
634 ) {
635 self.pending_async.extend(deliveries);
636 }
637
638 pub(crate) fn queue_suspended_async(
639 &mut self,
640 deliveries: impl IntoIterator<Item = crate::AsyncDelivery>,
641 ) -> Result<(), AsyncRuntimeError> {
642 for delivery in deliveries {
643 if self.pending_async.len() >= Self::SUSPENDED_DELIVERY_CAPACITY {
644 return Err(AsyncRuntimeError::SuspendedBackpressure {
645 capacity: Self::SUSPENDED_DELIVERY_CAPACITY,
646 });
647 }
648 self.pending_async.push(delivery);
649 }
650 Ok(())
651 }
652
653 pub(crate) fn suspended_delivery_capacity_remaining(&self) -> usize {
654 Self::SUSPENDED_DELIVERY_CAPACITY.saturating_sub(self.pending_async.len())
655 }
656
657 pub(crate) fn cancel_async_scope(&mut self, scope: &AsyncScope) -> Result<(), AssetError> {
658 self.assets.cancel_scope(scope)?;
659 self.tasks.cancel_scope(scope);
660 self.subscriptions.cancel_scope(scope);
661 self.pending_async
662 .retain(|delivery| &delivery.scope != scope);
663 self.pending_actions.retain(|pending| {
664 pending
665 .owner
666 .as_ref()
667 .is_none_or(|owner| owner.source.effect.as_ref() != Some(scope))
668 });
669 self.pending_events.retain(|pending| {
670 pending
671 .owner
672 .as_ref()
673 .is_none_or(|owner| owner.source.effect.as_ref() != Some(scope))
674 });
675 self.trace_subscription_closures();
676 Ok(())
677 }
678
679 pub(crate) fn take_window_async(
680 &mut self,
681 window: &str,
682 root: &ComponentInstancePath,
683 ) -> Vec<crate::AsyncDelivery> {
684 let app_owner = self.windows.open_ids().into_iter().next();
685 let pending = std::mem::take(&mut self.pending_async);
686 let (accepted, retained) =
687 pending
688 .into_iter()
689 .partition(|delivery| match &delivery.scope {
690 AsyncScope::App => app_owner.as_deref() == Some(window),
691 AsyncScope::Window(id) => id == window,
692 AsyncScope::Component(_) | AsyncScope::Effect { .. } => {
693 delivery.scope.is_within_component(root)
694 }
695 });
696 self.pending_async = retained;
697 accepted
698 }
699
700 pub(crate) fn discard_component_async_before_generation(
701 &mut self,
702 root: &ComponentInstancePath,
703 generation: crate::ScriptGeneration,
704 ) {
705 self.pending_async.retain(|delivery| {
706 !delivery.scope.is_within_component(root)
707 || delivery.callback.generation() == generation
708 });
709 }
710
711 pub(crate) fn requeue_element_commands(
713 &mut self,
714 commands: Vec<crate::element_ref::ElementCommand>,
715 ) {
716 self.pending_element_commands.extend(commands);
717 }
718
719 pub(crate) fn take_window_element_commands(
720 &mut self,
721 window: &str,
722 ) -> Vec<crate::element_ref::ElementCommand> {
723 let commands = std::mem::take(&mut self.pending_element_commands);
724 let (selected, retained) = commands
725 .into_iter()
726 .partition(|command| command.window() == window);
727 self.pending_element_commands = retained;
728 selected
729 }
730
731 pub(crate) fn has_window_dirty(&self, root: &ComponentInstancePath) -> bool {
732 self.dirty
733 .iter()
734 .any(|path| path.is_within(root) && !self.effect_cascades.blocked_component(path))
735 }
736
737 pub(crate) fn flush_geometry_dependencies(&mut self) {
738 self.dirty.extend(self.element_refs.take_dirty());
739 self.dirty.extend(self.geometry.take_dirty());
740 for presentation in self.presentations.values() {
741 self.dirty.extend(presentation.geometry.take_dirty());
742 }
743 }
744
745 pub(crate) fn take_window_dirty_components(
746 &mut self,
747 root: &ComponentInstancePath,
748 ) -> BTreeSet<ComponentInstancePath> {
749 let all = std::mem::take(&mut self.dirty);
750 let (selected, retained) = all.into_iter().partition(|path| path.is_within(root));
751 self.dirty = retained;
752 selected
753 }
754
755 pub(crate) fn has_pending_dispatch(&self) -> bool {
756 self.pending_actions
757 .iter()
758 .any(|pending| self.dispatch_owner_active(pending.owner.as_ref()))
759 || self
760 .pending_events
761 .iter()
762 .any(|pending| self.dispatch_owner_active(pending.owner.as_ref()))
763 }
764
765 pub(crate) fn has_window_pending_dispatch(&self, root: &ComponentInstancePath) -> bool {
766 self.pending_actions.iter().any(|pending| {
767 pending
768 .callback
769 .component()
770 .is_none_or(|path| path.is_within(root))
771 && self.dispatch_owner_active(pending.owner.as_ref())
772 }) || self.pending_events.iter().any(|pending| {
773 pending.target.is_within(root) && self.dispatch_owner_active(pending.owner.as_ref())
774 })
775 }
776
777 pub(crate) fn drain_window_dispatch(
778 &mut self,
779 root: &ComponentInstancePath,
780 ) -> (Vec<ActionInvocation>, Vec<PendingEvent>) {
781 self.prune_pending_dispatch();
782 let (actions, retained) = std::mem::take(&mut self.pending_actions)
783 .into_iter()
784 .partition(|pending| {
785 pending
786 .callback
787 .component()
788 .is_none_or(|path| path.is_within(root))
789 });
790 self.pending_actions = retained;
791 let (events, retained) = std::mem::take(&mut self.pending_events)
792 .into_iter()
793 .partition(|pending| pending.target.is_within(root));
794 self.pending_events = retained;
795 (actions, events)
796 }
797
798 pub(crate) fn dispatch_owner_active(&self, owner: Option<&SemanticDispatchOwner>) -> bool {
799 owner.is_none_or(|owner| {
800 owner.source.runtime_id == self.runtime_id
801 && owner.source.active(
802 &self.component_incarnations,
803 &self.effects,
804 &self.effect_cascades,
805 )
806 })
807 }
808
809 pub(crate) fn prune_pending_dispatch(&mut self) {
810 let incarnations = &self.component_incarnations;
811 let effects = &self.effects;
812 let cascades = &self.effect_cascades;
813 let runtime_id = self.runtime_id;
814 let active = |owner: &SemanticDispatchOwner| {
815 owner.source.runtime_id == runtime_id
816 && owner.source.active(incarnations, effects, cascades)
817 };
818 self.pending_actions
819 .retain(|pending| pending.owner.as_ref().is_none_or(active));
820 self.pending_events
821 .retain(|pending| pending.owner.as_ref().is_none_or(active));
822 self.effect_cascades.prune_dispatches(incarnations, effects);
823 }
824
825 pub(crate) fn has_virtual_requests(&self) -> bool {
826 !self.virtual_requests.is_empty()
827 }
828
829 pub(crate) fn component_event_handler(
830 &self,
831 component: &ComponentInstancePath,
832 event: &str,
833 ) -> Option<ScriptCallback> {
834 self.component_event_handlers
835 .get(&(component.clone(), event.to_owned()))
836 .cloned()
837 }
838
839 pub(crate) fn reset_component_readers(&mut self, component: &ComponentInstancePath) {
840 self.page_visibility.reset_reader(component);
841 self.stores.reset_reader(component);
842 self.native_collections.reset_reader(component);
843 self.native_documents.reset_reader(component);
844 self.environment_dependencies.reset_reader(component);
845 self.reset_geometry_read_contribution(&crate::read_dependency::ReadDependency::component(
846 component,
847 ));
848 }
849
850 pub(crate) fn retain_virtual_read_contributions(
851 &mut self,
852 scope: &ComponentInstancePath,
853 active: &BTreeSet<crate::read_dependency::ReadContribution>,
854 ) {
855 self.native_collections.retain_contributions(scope, active);
856 self.native_documents.retain_contributions(scope, active);
857 self.stores.retain_contributions(scope, active);
858 self.environment_dependencies
859 .retain_contributions(scope, active);
860 self.element_refs.retain_contributions(scope, active);
861 self.geometry.retain_contributions(scope, active);
862 for presentation in self.presentations.values() {
863 presentation.geometry.retain_contributions(scope, active);
864 }
865 }
866
867 fn reset_geometry_read_contribution(
868 &mut self,
869 reader: &crate::read_dependency::ReadDependency,
870 ) {
871 self.element_refs.reset_contribution(reader);
872 self.geometry.reset_contribution(reader);
873 for presentation in self.presentations.values() {
874 presentation.geometry.reset_contribution(reader);
875 }
876 }
877
878 pub(crate) fn component_event_handlers_in_scope(
879 &self,
880 root: &ComponentInstancePath,
881 ) -> BTreeMap<(ComponentInstancePath, String), ScriptCallback> {
882 self.component_event_handlers
883 .iter()
884 .filter(|((path, _), _)| path.is_within(root))
885 .map(|(id, callback)| (id.clone(), callback.clone()))
886 .collect()
887 }
888
889 pub(crate) fn replace_component_event_handlers(
890 &mut self,
891 root: &ComponentInstancePath,
892 handlers: BTreeMap<(ComponentInstancePath, String), ScriptCallback>,
893 ) {
894 self.component_event_handlers
895 .retain(|(path, _), _| !path.is_within(root));
896 self.component_event_handlers.extend(handlers);
897 }
898
899 pub(crate) fn mark_all_windows_dirty(&mut self) {
900 self.mark_dirty(
901 self.windows
902 .open_ids()
903 .into_iter()
904 .map(|window| ComponentInstancePath::root("App", window)),
905 );
906 }
907
908 pub(crate) fn mark_dirty(
909 &mut self,
910 components: impl IntoIterator<Item = ComponentInstancePath>,
911 ) {
912 let mut invalidated = false;
913 for component in components {
914 self.dirty.insert(component);
915 invalidated = true;
916 }
917 if invalidated {
918 self.publish_committed_work();
919 }
920 }
921
922 fn mark_dirty_from_host(
923 &mut self,
924 components: impl IntoIterator<Item = ComponentInstancePath>,
925 ) {
926 let components = components.into_iter().collect::<Vec<_>>();
927 if self.origin != crate::InvocationOrigin::Effect {
928 for component in &components {
929 self.effect_cascades.restart_containing(component);
930 }
931 }
932 self.mark_dirty(components);
933 }
934
935 fn publish_committed_work(&mut self) {
938 if self.transaction_depth != 0 {
939 return;
940 }
941 self.prune_pending_dispatch();
942 let pending_effect_scopes = self
943 .pending_events
944 .iter()
945 .filter(|pending| pending.origin == crate::InvocationOrigin::Effect)
946 .map(|pending| {
947 pending
948 .owner
949 .as_ref()
950 .map_or(&pending.target, |owner| &owner.source.component)
951 })
952 .chain(
953 self.pending_actions
954 .iter()
955 .filter(|pending| pending.origin == crate::InvocationOrigin::Effect)
956 .filter_map(|pending| {
957 pending
958 .owner
959 .as_ref()
960 .map(|owner| &owner.source.component)
961 .or_else(|| pending.callback.component())
962 }),
963 );
964 self.effect_cascades
965 .settle(&self.dirty, pending_effect_scopes);
966 if self
967 .dirty
968 .iter()
969 .any(|path| !self.effect_cascades.blocked_component(path))
970 || self.has_pending_dispatch()
971 || !self.repaint_windows.is_empty()
972 {
973 self.tasks.wake().notify();
977 }
978 }
979
980 pub(crate) fn mark_all_windows_repaint(&mut self) {
981 self.repaint_windows.extend(self.windows.open_ids());
982 self.publish_committed_work();
983 }
984
985 pub(crate) fn mark_window_repaint(&mut self, window: impl Into<String>) {
986 self.repaint_windows.insert(window.into());
987 self.publish_committed_work();
988 }
989
990 pub(crate) fn take_window_repaint(&mut self, window: &str) -> bool {
991 self.repaint_windows.remove(window)
992 }
993
994 pub(crate) fn reconcile_component_lifetimes(
995 &mut self,
996 root: &ComponentInstancePath,
997 active: &BTreeSet<ComponentInstancePath>,
998 previous: &BTreeSet<ComponentInstancePath>,
999 ) -> Result<(), AssetError> {
1000 for removed in previous
1001 .iter()
1002 .filter(|path| path.is_within(root) && *path != root && !active.contains(*path))
1003 {
1004 self.tasks.cancel_component_scope(removed);
1005 self.subscriptions.cancel_component_scope(removed);
1006 self.timers.cancel_component_scope(removed);
1007 self.assets.cancel_component_scope(removed)?;
1008 self.actions.remove_component_scope(removed);
1009 }
1010 self.pending_async.retain(|delivery| {
1011 delivery
1012 .scope
1013 .component()
1014 .is_none_or(|path| !path.is_within(root) || active.contains(path))
1015 });
1016 self.pending_actions.retain(|action| {
1017 !action
1018 .callback
1019 .component()
1020 .is_some_and(|path| path.is_within(root) && !active.contains(path))
1021 });
1022 self.pending_events.retain(|event| {
1023 !event.target.is_within(root) || active.contains(&event.target) || event.target == *root
1024 });
1025 self.stores.retain_reader_scope(root, active);
1026 self.component_event_handlers
1027 .retain(|(path, _), _| !path.is_within(root) || path == root || active.contains(path));
1028 self.native_collections.retain_reader_scope(root, active);
1029 self.native_documents.retain_reader_scope(root, active);
1030 self.element_refs.retain_scope(root, active);
1031 self.geometry.retain_reader_scope(root, active);
1032 for presentation in self.presentations.values() {
1033 presentation.geometry.retain_reader_scope(root, active);
1034 }
1035 self.environment_dependencies.retain_scope(root, active);
1036 self.page_visibility.retain_scope(root, active);
1037 self.dirty
1038 .retain(|path| !path.is_within(root) || path == root || active.contains(path));
1039 self.component_incarnations
1040 .retain(|path, _| !path.is_within(root) || path == root || active.contains(path));
1041 Ok(())
1042 }
1043
1044 #[must_use]
1045 pub fn drain_batch(&mut self) -> UiMutationBatch {
1046 self.prune_pending_dispatch();
1047 UiMutationBatch {
1048 dirty: std::mem::take(&mut self.dirty),
1049 events: std::mem::take(&mut self.pending_events),
1050 actions: std::mem::take(&mut self.pending_actions),
1051 }
1052 }
1053
1054 #[must_use]
1055 pub fn dirty_components(&self) -> &BTreeSet<ComponentInstancePath> {
1056 &self.dirty
1057 }
1058
1059 pub(crate) fn snapshot(&self) -> Result<UiStateSnapshot, AssetError> {
1060 Ok(UiStateSnapshot {
1061 runtime_id: self.runtime_id,
1062 transaction_depth: self.transaction_depth,
1063 dispatch_lease_checkpoint: self.dispatch_leases.len(),
1064 component_state: self.component_state.clone(),
1065 stores: self.stores.clone(),
1066 native_collections: self.native_collections.clone(),
1067 native_documents: self.native_documents.clone(),
1068 actions: self.actions.clone(),
1069 component_event_handlers: self.component_event_handlers.clone(),
1070 component_incarnations: self.component_incarnations.clone(),
1071 next_component_incarnation: self.next_component_incarnation,
1072 dirty: self.dirty.clone(),
1073 pending_events: self.pending_events.clone(),
1074 pending_actions: self.pending_actions.clone(),
1075 pending_async: self.pending_async.clone(),
1076 pending_element_commands: self.pending_element_commands.clone(),
1077 locale: self.locale.clone(),
1078 theme: self.theme.clone(),
1079 component_styles: self.component_styles.clone(),
1080 component_style_generation: self.component_style_generation,
1081 motions: self.motions.transaction_snapshot(),
1082 page_visibility: self.page_visibility.clone(),
1083 effects: self.effects.clone(),
1084 effect_cascades: self.effect_cascades.checkpoint(),
1085 signals: self.signals.clone(),
1086 element_refs: self.element_refs.clone(),
1087 geometry: self.geometry.snapshot(),
1088 pointer_capture: self.pointer_capture.snapshot(),
1089 presentations: self
1090 .presentations
1091 .iter()
1092 .map(|(view, state)| (view.clone(), state.snapshot()))
1093 .collect(),
1094 budgets: self.budgets.clone(),
1095 virtual_requests: self.virtual_requests.snapshot(),
1096 motion_values: self.motion_values.clone(),
1097 motion_ghosts: self.motion_ghosts.clone(),
1098 windows: self.windows.clone(),
1099 responsive: self.responsive.clone(),
1100 environment_dependencies: self.environment_dependencies.clone(),
1101 repaint_windows: self.repaint_windows.clone(),
1102 tasks: self.tasks.snapshot(),
1103 subscriptions: self.subscriptions.snapshot(),
1104 timers: self.timers.clone(),
1105 image_decodes: self.assets.decode_snapshot()?,
1106 })
1107 }
1108
1109 pub(crate) fn restore(&mut self, snapshot: UiStateSnapshot) -> Result<(), UiTransactionError> {
1110 if self.runtime_id != snapshot.runtime_id {
1111 return Err(UiTransactionError::ForeignSnapshot);
1112 }
1113 let expected_depth = snapshot.transaction_depth.saturating_add(1);
1114 if self.transaction_depth != expected_depth {
1115 return Err(UiTransactionError::Unbalanced {
1116 expected: expected_depth,
1117 actual: self.transaction_depth,
1118 });
1119 }
1120 for lease in self
1121 .dispatch_leases
1122 .drain(snapshot.dispatch_lease_checkpoint..)
1123 {
1124 lease.publication_valid.set(false);
1125 }
1126 self.tasks.restore(snapshot.tasks);
1127 self.subscriptions.restore(snapshot.subscriptions);
1128 self.timers = snapshot.timers;
1129 let decode_result = self.assets.restore_decode_snapshot(snapshot.image_decodes);
1130 self.component_state = snapshot.component_state;
1131 self.stores = snapshot.stores;
1132 self.native_collections = snapshot.native_collections;
1133 self.native_documents = snapshot.native_documents;
1134 self.actions = snapshot.actions;
1135 self.component_event_handlers = snapshot.component_event_handlers;
1136 self.component_incarnations = snapshot.component_incarnations;
1137 self.next_component_incarnation = snapshot.next_component_incarnation;
1138 self.dirty = snapshot.dirty;
1139 self.pending_events = snapshot.pending_events;
1140 self.pending_actions = snapshot.pending_actions;
1141 self.pending_async = snapshot.pending_async;
1142 self.pending_element_commands = snapshot.pending_element_commands;
1143 self.locale = snapshot.locale;
1144 self.theme = snapshot.theme;
1145 self.component_styles = snapshot.component_styles;
1146 self.component_style_generation = snapshot.component_style_generation;
1147 self.motions = snapshot.motions;
1148 self.page_visibility = snapshot.page_visibility;
1149 self.effects = snapshot.effects;
1150 self.effect_cascades.restore(snapshot.effect_cascades);
1151 self.prune_pending_dispatch();
1152 self.signals = snapshot.signals;
1153 self.element_refs = snapshot.element_refs;
1154 self.geometry.restore(snapshot.geometry);
1155 self.pointer_capture.restore(snapshot.pointer_capture);
1156 self.presentations
1157 .retain(|view, _| snapshot.presentations.contains_key(view));
1158 for (view, presentation) in snapshot.presentations {
1159 let state = self.presentations.entry(view).or_default();
1160 state.geometry.restore(presentation.geometry);
1161 state.pointer_capture.restore(presentation.pointer_capture);
1162 }
1163 self.budgets = snapshot.budgets;
1164 self.virtual_requests.restore(snapshot.virtual_requests);
1165 self.motion_values = snapshot.motion_values;
1166 self.motion_ghosts = snapshot.motion_ghosts;
1167 self.windows = snapshot.windows;
1168 self.responsive = snapshot.responsive;
1169 self.environment_dependencies = snapshot.environment_dependencies;
1170 self.repaint_windows = snapshot.repaint_windows;
1171 self.transaction_depth = snapshot.transaction_depth;
1172 decode_result.map_err(UiTransactionError::from)?;
1173 if self.transaction_depth == 0 {
1174 self.effect_cascades.collect_retired_rejections();
1175 }
1176 Ok(())
1177 }
1178
1179 pub fn begin_transaction(&mut self) -> Result<UiStateSnapshot, UiTransactionError> {
1188 let snapshot = self.snapshot()?;
1189 let _ = self.assets.begin_transaction()?;
1190 self.tasks.begin_transaction();
1191 self.subscriptions.begin_transaction();
1192 self.transaction_depth = self.transaction_depth.saturating_add(1);
1193 Ok(snapshot)
1194 }
1195
1196 pub fn commit_transaction(&mut self) -> Result<(), UiTransactionError> {
1203 if self.transaction_depth == 0 {
1204 return Err(UiTransactionError::Unbalanced {
1205 expected: 1,
1206 actual: 0,
1207 });
1208 }
1209 self.assets.commit_transaction()?;
1210 self.tasks.commit_transaction();
1211 self.subscriptions.commit_transaction();
1212 self.transaction_depth -= 1;
1213 if self.transaction_depth == 0 {
1214 self.dispatch_leases.clear();
1215 self.effect_cascades.collect_retired_rejections();
1216 }
1217 self.publish_committed_work();
1218 Ok(())
1219 }
1220
1221 pub fn rollback_transaction(
1228 &mut self,
1229 snapshot: UiStateSnapshot,
1230 ) -> Result<(), UiTransactionError> {
1231 self.restore(snapshot)
1232 }
1233}
1234
1235#[derive(Debug, Default)]
1236struct ViewPresentationState {
1237 geometry: crate::GeometryRegistry,
1238 pointer_capture: crate::PointerCaptureRegistry,
1239}
1240
1241impl ViewPresentationState {
1242 fn snapshot(&self) -> ViewPresentationSnapshot {
1243 ViewPresentationSnapshot {
1244 geometry: self.geometry.snapshot(),
1245 pointer_capture: self.pointer_capture.snapshot(),
1246 }
1247 }
1248}
1249
1250#[derive(Clone, Debug)]
1251struct ViewPresentationSnapshot {
1252 geometry: crate::geometry::GeometrySnapshot,
1253 pointer_capture: BTreeMap<u64, crate::NodeId>,
1254}
1255
1256#[derive(Debug, Error)]
1257pub enum UiTransactionError {
1258 #[error("transaction snapshot belongs to another UiRuntimeState")]
1259 ForeignSnapshot,
1260 #[error("unbalanced runtime transaction depth: expected {expected}, got {actual}")]
1261 Unbalanced { expected: usize, actual: usize },
1262 #[error(transparent)]
1263 Asset(#[from] AssetError),
1264}
1265
1266pub struct UiStateSnapshot {
1267 runtime_id: RuntimeStateId,
1268 transaction_depth: usize,
1269 dispatch_lease_checkpoint: usize,
1270 component_state: StateStore,
1271 stores: StoreRegistry,
1272 native_collections: crate::NativeCollectionRegistry,
1273 native_documents: crate::NativeTextDocumentRegistry,
1274 actions: ActionRegistry,
1275 component_event_handlers: BTreeMap<(ComponentInstancePath, String), ScriptCallback>,
1276 component_incarnations: BTreeMap<ComponentInstancePath, ComponentIncarnation>,
1277 next_component_incarnation: u64,
1278 dirty: BTreeSet<ComponentInstancePath>,
1279 pending_events: Vec<PendingEvent>,
1280 pending_actions: Vec<ActionInvocation>,
1281 pending_async: Vec<crate::AsyncDelivery>,
1282 pending_element_commands: Vec<crate::element_ref::ElementCommand>,
1283 locale: Option<LocaleManager>,
1284 theme: Option<ThemeManager>,
1285 component_styles: crate::ComponentStyleSheet,
1286 component_style_generation: u64,
1287 motions: MotionRuntime,
1288 page_visibility: crate::retained_page::PageVisibility,
1289 effects: crate::EffectRegistry,
1290 effect_cascades: crate::effect::EffectCascadeCheckpoint,
1291 signals: crate::SignalRegistry,
1292 element_refs: crate::ElementRefRegistry,
1293 geometry: crate::geometry::GeometrySnapshot,
1294 pointer_capture: BTreeMap<u64, crate::NodeId>,
1295 presentations: BTreeMap<String, ViewPresentationSnapshot>,
1296 budgets: crate::RuntimeBudgets,
1297 virtual_requests: crate::virtual_list::VirtualRequestSnapshot,
1298 motion_values: BTreeMap<MotionKey, f64>,
1299 motion_ghosts: Vec<crate::motion::MotionGhost>,
1300 windows: WindowCommandRegistry,
1301 responsive: ResponsiveRuntime,
1302 environment_dependencies: crate::environment_dependency::EnvironmentDependencyRegistry,
1303 repaint_windows: BTreeSet<String>,
1304 tasks: crate::async_runtime::TaskRegistrySnapshot,
1305 subscriptions: crate::async_runtime::SubscriptionRegistrySnapshot,
1306 timers: crate::TimerRegistry,
1307 image_decodes: crate::asset::ImageDecodeSnapshot,
1308}
1309
1310impl Clone for UiStateSnapshot {
1311 fn clone(&self) -> Self {
1312 Self {
1313 runtime_id: self.runtime_id,
1314 transaction_depth: self.transaction_depth,
1315 dispatch_lease_checkpoint: self.dispatch_lease_checkpoint,
1316 component_state: self.component_state.clone(),
1317 stores: self.stores.clone(),
1318 native_collections: self.native_collections.clone(),
1319 native_documents: self.native_documents.clone(),
1320 actions: self.actions.clone(),
1321 component_event_handlers: self.component_event_handlers.clone(),
1322 component_incarnations: self.component_incarnations.clone(),
1323 next_component_incarnation: self.next_component_incarnation,
1324 dirty: self.dirty.clone(),
1325 pending_events: self.pending_events.clone(),
1326 pending_actions: self.pending_actions.clone(),
1327 pending_async: self.pending_async.clone(),
1328 pending_element_commands: self.pending_element_commands.clone(),
1329 locale: self.locale.clone(),
1330 theme: self.theme.clone(),
1331 component_styles: self.component_styles.clone(),
1332 component_style_generation: self.component_style_generation,
1333 motions: self.motions.transaction_snapshot(),
1334 page_visibility: self.page_visibility.clone(),
1335 effects: self.effects.clone(),
1336 effect_cascades: self.effect_cascades.clone(),
1337 signals: self.signals.clone(),
1338 element_refs: self.element_refs.clone(),
1339 geometry: self.geometry.clone(),
1340 pointer_capture: self.pointer_capture.clone(),
1341 presentations: self.presentations.clone(),
1342 budgets: self.budgets.clone(),
1343 virtual_requests: self.virtual_requests.clone(),
1344 motion_values: self.motion_values.clone(),
1345 motion_ghosts: self.motion_ghosts.clone(),
1346 windows: self.windows.clone(),
1347 responsive: self.responsive.clone(),
1348 environment_dependencies: self.environment_dependencies.clone(),
1349 repaint_windows: self.repaint_windows.clone(),
1350 tasks: self.tasks.clone(),
1351 subscriptions: self.subscriptions.clone(),
1352 timers: self.timers.clone(),
1353 image_decodes: self.image_decodes.clone(),
1354 }
1355 }
1356}
1357
1358impl UiStateSnapshot {
1359 pub(crate) const fn component_state(&self) -> &StateStore {
1360 &self.component_state
1361 }
1362}
1363
1364#[derive(Clone, Debug)]
1365pub struct PendingEvent {
1366 pub target: ComponentInstancePath,
1367 pub event: UiEvent,
1368 pub origin: crate::InvocationOrigin,
1371 pub owner: Option<SemanticDispatchOwner>,
1374}
1375
1376#[derive(Clone, Debug)]
1380pub struct SemanticDispatchOwner {
1381 source: Rc<SemanticDispatchSource>,
1382}
1383
1384#[derive(Clone, Debug)]
1385pub(crate) struct SemanticDispatchSource {
1386 runtime_id: RuntimeStateId,
1387 pub(crate) generation: ScriptGeneration,
1388 pub(crate) component: ComponentInstancePath,
1389 incarnation: ComponentIncarnation,
1390 pub(crate) effect: Option<AsyncScope>,
1391 cascade: Option<(ComponentInstancePath, u64)>,
1392 publication_valid: Cell<bool>,
1393}
1394
1395impl SemanticDispatchSource {
1396 pub(crate) fn publication_valid(&self) -> bool {
1397 self.publication_valid.get()
1398 }
1399
1400 pub(crate) fn active(
1401 &self,
1402 incarnations: &BTreeMap<ComponentInstancePath, ComponentIncarnation>,
1403 effects: &crate::EffectRegistry,
1404 cascades: &crate::effect::EffectCascadeBudget,
1405 ) -> bool {
1406 self.publication_valid.get()
1407 && incarnations.get(&self.component) == Some(&self.incarnation)
1408 && cascades
1409 .generation_for(&self.component)
1410 .is_none_or(|generation| generation == self.generation)
1411 && self
1412 .effect
1413 .as_ref()
1414 .is_none_or(|scope| effects.contains_scope(scope))
1415 && self
1416 .cascade
1417 .as_ref()
1418 .is_none_or(|(root, epoch)| cascades.accepts_dispatch(root, *epoch))
1419 }
1420}
1421
1422impl SemanticDispatchOwner {
1423 pub(crate) fn cascade_root(&self) -> Option<&ComponentInstancePath> {
1424 self.source.cascade.as_ref().map(|(root, _)| root)
1425 }
1426}
1427
1428#[derive(Clone, Debug, Default)]
1429pub struct UiMutationBatch {
1430 pub dirty: BTreeSet<ComponentInstancePath>,
1431 pub events: Vec<PendingEvent>,
1432 pub actions: Vec<ActionInvocation>,
1433}
1434
1435#[derive(Clone, Debug)]
1436pub struct UiContext {
1437 runtime: Rc<RefCell<UiRuntimeState>>,
1438 component: ComponentInstancePath,
1439 incarnation: ComponentIncarnation,
1440 callback_component: ComponentInstancePath,
1441 callback_incarnation: ComponentIncarnation,
1442 callback_events: BTreeMap<String, EventSchema>,
1443 read_dependency: crate::read_dependency::ReadDependency,
1444 window: Option<String>,
1445 view: Option<String>,
1446 phase: ExecutionPhase,
1447 events: BTreeMap<String, EventSchema>,
1448 generation: ScriptGeneration,
1449 native_context: Option<crate::invocation::ScriptInvocationContext>,
1450 async_scope: Option<AsyncScope>,
1451 component_style: Option<crate::Style>,
1452 component_part_styles: BTreeMap<String, crate::Style>,
1453 global_component_part_styles: BTreeMap<String, crate::Style>,
1454 non_reusable_render_reads: Rc<RefCell<BTreeSet<ComponentInstancePath>>>,
1455 event_target: Option<crate::GeometryBounds>,
1456}
1457
1458impl UiContext {
1459 pub fn is_visible(&self) -> Result<bool, UiContextError> {
1467 let mut runtime = self
1468 .runtime
1469 .try_borrow_mut()
1470 .map_err(|_| UiContextError::Borrowed)?;
1471 Ok(runtime
1472 .page_visibility
1473 .read(&self.component, self.phase == ExecutionPhase::Render))
1474 }
1475
1476 #[must_use]
1477 pub fn new(
1478 runtime: Rc<RefCell<UiRuntimeState>>,
1479 component: ComponentInstancePath,
1480 window: Option<String>,
1481 phase: ExecutionPhase,
1482 events: BTreeMap<String, EventSchema>,
1483 ) -> Self {
1484 if let Some(window) = window.as_deref()
1485 && let Ok(mut runtime) = runtime.try_borrow_mut()
1486 {
1487 runtime.ensure_presentation(window);
1488 }
1489 let incarnation = runtime
1490 .try_borrow_mut()
1491 .map(|mut runtime| runtime.ensure_component_incarnation(&component))
1492 .unwrap_or_default();
1493 let read_dependency = crate::read_dependency::ReadDependency::component(&component);
1494 let context = Self {
1495 runtime,
1496 component: component.clone(),
1497 incarnation,
1498 callback_component: component,
1499 read_dependency,
1500 callback_incarnation: incarnation,
1501 callback_events: events.clone(),
1502 window,
1503 view: None,
1504 phase,
1505 events,
1506 generation: ScriptGeneration::default(),
1507 native_context: None,
1508 async_scope: None,
1509 component_style: None,
1510 component_part_styles: BTreeMap::new(),
1511 global_component_part_styles: BTreeMap::new(),
1512 non_reusable_render_reads: Rc::new(RefCell::new(BTreeSet::new())),
1513 event_target: None,
1514 };
1515 if phase == ExecutionPhase::Render
1516 && let Ok(mut runtime) = context.runtime.try_borrow_mut()
1517 {
1518 runtime.reset_component_readers(&context.component);
1519 }
1520 context
1521 }
1522
1523 #[must_use]
1524 pub fn with_generation(mut self, generation: ScriptGeneration) -> Self {
1525 self.generation = generation;
1526 self
1527 }
1528
1529 #[must_use]
1530 pub fn with_view_id(mut self, view: impl Into<String>) -> Self {
1531 let view = view.into();
1532 if let Ok(mut runtime) = self.runtime.try_borrow_mut() {
1533 runtime.ensure_presentation(&view);
1534 }
1535 self.view = Some(view);
1536 self
1537 }
1538
1539 #[must_use]
1540 pub(crate) fn with_optional_view_id(mut self, view: Option<String>) -> Self {
1541 if let Some(view) = view.as_deref()
1542 && let Ok(mut runtime) = self.runtime.try_borrow_mut()
1543 {
1544 runtime.ensure_presentation(view);
1545 }
1546 self.view = view;
1547 self
1548 }
1549
1550 pub(crate) fn for_component(
1551 &self,
1552 component: ComponentInstancePath,
1553 events: BTreeMap<String, EventSchema>,
1554 ) -> Self {
1555 let incarnation = self
1556 .runtime
1557 .try_borrow_mut()
1558 .map(|mut runtime| runtime.ensure_component_incarnation(&component))
1559 .unwrap_or_default();
1560 let read_dependency = crate::read_dependency::ReadDependency::component(&component);
1561 let context = Self {
1562 runtime: Rc::clone(&self.runtime),
1563 component: component.clone(),
1564 incarnation,
1565 callback_component: component,
1566 read_dependency,
1567 callback_incarnation: incarnation,
1568 callback_events: events.clone(),
1569 window: self.window.clone(),
1570 view: self.view.clone(),
1571 phase: self.phase,
1572 events,
1573 generation: self.generation,
1574 native_context: self.native_context.clone(),
1575 async_scope: self.async_scope.clone(),
1576 component_style: self.component_style.clone(),
1577 component_part_styles: self.component_part_styles.clone(),
1578 global_component_part_styles: self.global_component_part_styles.clone(),
1579 non_reusable_render_reads: Rc::clone(&self.non_reusable_render_reads),
1580 event_target: self.event_target,
1581 };
1582 if context.phase == ExecutionPhase::Render
1583 && let Ok(mut runtime) = context.runtime.try_borrow_mut()
1584 {
1585 runtime.reset_component_readers(&context.component);
1586 }
1587 context
1588 }
1589
1590 pub(crate) fn for_structural_scope(
1591 &self,
1592 component: ComponentInstancePath,
1593 events: BTreeMap<String, EventSchema>,
1594 ) -> Self {
1595 let mut context = self.for_component(component, events);
1598 context.callback_component = self.callback_component.clone();
1599 context.callback_incarnation = self.callback_incarnation;
1600 context.callback_events = self.callback_events.clone();
1601 context.read_dependency = self.read_dependency.clone();
1602 context
1603 }
1604
1605 pub(crate) fn for_virtual_item(
1606 &self,
1607 collection: &crate::VirtualCollectionId,
1608 key: &str,
1609 ) -> Self {
1610 let mut context = self.clone();
1611 context.read_dependency = crate::read_dependency::ReadDependency::virtual_item(
1612 &self.callback_component,
1613 collection,
1614 key,
1615 );
1616 if let Ok(mut runtime) = context.runtime.try_borrow_mut() {
1617 runtime
1618 .native_collections
1619 .reset_contribution(&context.read_dependency);
1620 runtime
1621 .native_documents
1622 .reset_contribution(&context.read_dependency);
1623 runtime.stores.reset_contribution(&context.read_dependency);
1624 runtime
1625 .environment_dependencies
1626 .reset_contribution(&context.read_dependency);
1627 runtime.reset_geometry_read_contribution(&context.read_dependency);
1628 }
1629 context
1630 }
1631
1632 pub(crate) fn with_native_context(
1633 mut self,
1634 native_context: Option<crate::invocation::ScriptInvocationContext>,
1635 ) -> Self {
1636 self.native_context = native_context;
1637 self
1638 }
1639
1640 pub(crate) const fn with_event_target(mut self, target: Option<crate::GeometryBounds>) -> Self {
1641 self.event_target = target;
1642 self
1643 }
1644
1645 pub(crate) fn with_async_scope(mut self, scope: AsyncScope) -> Self {
1646 self.async_scope = Some(scope);
1647 self
1648 }
1649
1650 pub(crate) fn with_component_styles(
1651 mut self,
1652 global_part_styles: BTreeMap<String, crate::Style>,
1653 style: Option<crate::Style>,
1654 part_styles: BTreeMap<String, crate::Style>,
1655 ) -> Self {
1656 self.global_component_part_styles = global_part_styles;
1657 self.component_style = style;
1658 self.component_part_styles = part_styles;
1659 self
1660 }
1661
1662 pub(crate) fn reset_non_reusable_render_reads(&self) {
1663 self.non_reusable_render_reads.borrow_mut().clear();
1664 }
1665
1666 pub(crate) fn component_render_is_reusable(&self) -> bool {
1667 !self
1668 .non_reusable_render_reads
1669 .borrow()
1670 .contains(&self.component)
1671 }
1672
1673 fn render_reader(&self) -> Option<&crate::read_dependency::ReadDependency> {
1676 (self.phase == ExecutionPhase::Render).then_some(&self.read_dependency)
1677 }
1678
1679 fn mark_non_reusable_render_read(&self) {
1680 if self.phase == ExecutionPhase::Render {
1681 self.non_reusable_render_reads
1682 .borrow_mut()
1683 .insert(self.callback_component.clone());
1684 }
1685 }
1686
1687 fn resolve_component_style(&self, part: &str, mut base: crate::Style) -> crate::Style {
1688 if let Some(style) = self.global_component_part_styles.get(part) {
1689 base = base.merged(style);
1690 }
1691 if part == "root"
1692 && let Some(style) = &self.component_style
1693 {
1694 base = base.merged(style);
1695 }
1696 if let Some(style) = self.component_part_styles.get(part) {
1697 base = base.merged(style);
1698 }
1699 base
1700 }
1701
1702 pub(crate) fn node_factory_callback(
1705 &self,
1706 renderer: Dynamic,
1707 ) -> Result<ScriptCallback, Box<EvalAltResult>> {
1708 if self.phase != ExecutionPhase::Render {
1709 return Err(Box::new(EvalAltResult::ErrorRuntime(
1710 "render_node is only available during component rendering".into(),
1711 Position::NONE,
1712 )));
1713 }
1714 let renderer = renderer.try_cast::<FnPtr>().ok_or_else(|| {
1715 Box::new(EvalAltResult::ErrorRuntime(
1716 "render_node requires a named Rhai Fn; native event handlers are not Node factories"
1717 .into(),
1718 Position::NONE,
1719 ))
1720 })?;
1721 let callback = self
1722 .scoped_callback(renderer)
1723 .map_err(|error| Box::new(context_runtime_error(&error)))?;
1724 if !callback.is_node_factory() {
1725 return Err(Box::new(EvalAltResult::ErrorRuntime(
1726 "bind the Node factory with ctx.node_factory(Fn(...)) at its declaration site"
1727 .into(),
1728 Position::NONE,
1729 )));
1730 }
1731 Ok(callback)
1732 }
1733
1734 fn scoped_callback(&self, function: FnPtr) -> Result<ScriptCallback, UiContextError> {
1735 let mut callback = ScriptCallback::try_from_fn_ptr(function, self.generation)?;
1736 callback.bind_component_scope_if_unset(
1737 &self.callback_component,
1738 self.callback_incarnation,
1739 self.callback_events.clone(),
1740 );
1741 if let Some(context) = &self.native_context {
1742 callback.bind_native_context_if_unset(context.clone());
1743 }
1744 Ok(callback)
1745 }
1746
1747 #[must_use]
1748 pub fn runtime(&self) -> &Rc<RefCell<UiRuntimeState>> {
1749 &self.runtime
1750 }
1751
1752 pub(crate) fn component_path(&self) -> &ComponentInstancePath {
1753 &self.component
1754 }
1755
1756 pub(crate) const fn component_incarnation(&self) -> ComponentIncarnation {
1757 self.incarnation
1758 }
1759
1760 pub(crate) fn event_schemas(&self) -> &BTreeMap<String, EventSchema> {
1761 &self.events
1762 }
1763
1764 pub(crate) fn callback_component_path(&self) -> &ComponentInstancePath {
1765 &self.callback_component
1766 }
1767
1768 pub(crate) const fn callback_component_incarnation(&self) -> ComponentIncarnation {
1769 self.callback_incarnation
1770 }
1771
1772 pub(crate) fn callback_event_schemas(&self) -> &BTreeMap<String, EventSchema> {
1773 &self.callback_events
1774 }
1775
1776 pub(crate) fn native_context(&self) -> Option<&crate::invocation::ScriptInvocationContext> {
1777 self.native_context.as_ref()
1778 }
1779
1780 pub fn get_state(&self, field: &str) -> Result<UiValue, UiContextError> {
1787 self.runtime
1788 .try_borrow()
1789 .map_err(|_| UiContextError::Borrowed)?
1790 .component_state
1791 .get(&self.callback_component, field)
1792 .cloned()
1793 .ok_or_else(|| UiContextError::UnknownState {
1794 component: self.callback_component.clone(),
1795 field: field.to_owned(),
1796 })
1797 }
1798
1799 pub fn get_state_path(
1809 &self,
1810 field: &str,
1811 path: &UiValuePath,
1812 ) -> Result<UiValue, UiContextError> {
1813 Ok(self.get_state(field)?.get_path(path)?.clone())
1814 }
1815
1816 pub fn set_state(&self, field: &str, value: Dynamic) -> Result<(), UiContextError> {
1823 self.require_mutation()?;
1824 let value = UiValue::from_dynamic(value)?;
1825 let mut runtime = self
1826 .runtime
1827 .try_borrow_mut()
1828 .map_err(|_| UiContextError::Borrowed)?;
1829 let sensitive = runtime.component_state.is_sensitive(&self.component, field);
1830 let changed = runtime
1831 .component_state
1832 .set(&self.component, field, value.clone())?;
1833 if changed {
1834 if runtime.origin != crate::InvocationOrigin::Effect {
1835 runtime.effect_cascades.restart_containing(&self.component);
1836 }
1837 runtime.mark_dirty([self.component.clone()]);
1838 }
1839 runtime.traces.push(
1840 crate::RuntimeTraceKind::State,
1841 self.component.to_string(),
1842 format!("set {field}"),
1843 Some(value),
1844 sensitive,
1845 );
1846 Ok(())
1847 }
1848
1849 pub fn set_state_path(
1856 &self,
1857 field: &str,
1858 path: &UiValuePath,
1859 value: Dynamic,
1860 ) -> Result<(), UiContextError> {
1861 self.require_mutation()?;
1862 let value = UiValue::from_dynamic(value)?;
1863 let mut runtime = self
1864 .runtime
1865 .try_borrow_mut()
1866 .map_err(|_| UiContextError::Borrowed)?;
1867 let mut root = runtime
1868 .component_state
1869 .get(&self.component, field)
1870 .cloned()
1871 .ok_or_else(|| UiContextError::UnknownState {
1872 component: self.component.clone(),
1873 field: field.to_owned(),
1874 })?;
1875 root.set_path(path, value.clone())?;
1876 let sensitive = runtime.component_state.is_sensitive(&self.component, field);
1877 if runtime.component_state.set(&self.component, field, root)? {
1878 if runtime.origin != crate::InvocationOrigin::Effect {
1879 runtime.effect_cascades.restart_containing(&self.component);
1880 }
1881 runtime.mark_dirty([self.component.clone()]);
1882 }
1883 runtime.traces.push(
1884 crate::RuntimeTraceKind::State,
1885 self.component.to_string(),
1886 format!("set nested {field}"),
1887 Some(value),
1888 sensitive,
1889 );
1890 Ok(())
1891 }
1892
1893 pub fn get_signal(&self, signal: &crate::NativeSignal) -> Result<Dynamic, UiContextError> {
1899 self.mark_non_reusable_render_read();
1900 Ok(self
1901 .runtime
1902 .try_borrow()
1903 .map_err(|_| UiContextError::Borrowed)?
1904 .signals
1905 .read(signal)?
1906 .into_dynamic())
1907 }
1908
1909 pub fn set_signal(
1916 &self,
1917 signal: &crate::NativeSignal,
1918 value: Dynamic,
1919 ) -> Result<(), UiContextError> {
1920 self.require_mutation()?;
1921 let value = crate::SignalValue::from_dynamic_for_kind(value, signal.id().kind())?;
1922 let mut runtime = self
1923 .runtime
1924 .try_borrow_mut()
1925 .map_err(|_| UiContextError::Borrowed)?;
1926 let changed =
1927 runtime
1928 .signals
1929 .write_from(signal, value.clone(), crate::SignalWriter::Script)?;
1930 runtime.traces.push(
1931 crate::RuntimeTraceKind::Signal,
1932 signal.id().component().to_string(),
1933 format!(
1934 "set {} ({}){}",
1935 signal.id().key(),
1936 signal.id().kind().as_str(),
1937 if changed { "" } else { " unchanged" }
1938 ),
1939 None,
1940 false,
1941 );
1942 Ok(())
1943 }
1944
1945 pub fn get_signal_by_key(&self, key: &str) -> Result<Dynamic, UiContextError> {
1951 self.mark_non_reusable_render_read();
1952 let runtime = self
1953 .runtime
1954 .try_borrow()
1955 .map_err(|_| UiContextError::Borrowed)?;
1956 let signal = runtime.signals.resolve(&self.component, key)?;
1957 Ok(runtime.signals.read(&signal)?.into_dynamic())
1958 }
1959
1960 pub(crate) fn parent_optional_float_signal_ref(
1970 &self,
1971 key: &str,
1972 pending: &[crate::SignalId],
1973 ) -> Result<crate::NativeSignal, UiContextError> {
1974 let runtime = self
1975 .runtime
1976 .try_borrow()
1977 .map_err(|_| UiContextError::Borrowed)?;
1978 let mut scope = self.component.parent();
1979 while let Some(component) = scope {
1980 let signal = pending
1981 .iter()
1982 .find(|id| id.component() == &component && id.key() == key)
1983 .cloned()
1984 .map(crate::NativeSignal::new)
1985 .or_else(|| runtime.signals.resolve(&component, key).ok());
1986 if let Some(signal) = signal {
1987 if signal.id().kind() == crate::SignalKind::OptionalFloat {
1988 return Ok(signal);
1989 }
1990 return Err(crate::SignalError::TypeMismatch {
1991 expected: crate::SignalKind::OptionalFloat,
1992 actual: signal.id().kind(),
1993 }
1994 .into());
1995 }
1996 scope = component.parent();
1997 }
1998 Err(crate::SignalError::UnknownKey {
1999 component: self.component.clone(),
2000 key: key.to_owned(),
2001 }
2002 .into())
2003 }
2004
2005 pub fn set_signal_by_key(&self, key: &str, value: Dynamic) -> Result<(), UiContextError> {
2011 self.require_mutation()?;
2012 let signal = self
2013 .runtime
2014 .try_borrow()
2015 .map_err(|_| UiContextError::Borrowed)?
2016 .signals
2017 .resolve(&self.component, key)?;
2018 self.set_signal(&signal, value)
2019 }
2020
2021 pub fn element_bounds(&self, reference: &crate::ElementRef) -> Result<UiValue, UiContextError> {
2030 let Some(geometry) = self.element_geometry(
2031 reference,
2032 crate::element_ref::ElementRefGeometryRead::Bounds,
2033 )?
2034 else {
2035 return Ok(UiValue::Null);
2036 };
2037 Ok(UiValue::Map(BTreeMap::from([
2038 ("layout".to_owned(), geometry_bounds_value(geometry.layout)),
2039 ("visual".to_owned(), geometry_bounds_value(geometry.visual)),
2040 (
2041 "clip".to_owned(),
2042 geometry.clip.map_or(UiValue::Null, geometry_bounds_value),
2043 ),
2044 ])))
2045 }
2046
2047 pub fn element_size(&self, reference: &crate::ElementRef) -> Result<UiValue, UiContextError> {
2057 let Some(geometry) = self.element_geometry(
2058 reference,
2059 crate::element_ref::ElementRefGeometryRead::LayoutSize,
2060 )?
2061 else {
2062 return Ok(UiValue::Null);
2063 };
2064 Ok(UiValue::Map(BTreeMap::from([
2065 ("width".to_owned(), UiValue::Float(geometry.layout.width)),
2066 ("height".to_owned(), UiValue::Float(geometry.layout.height)),
2067 ])))
2068 }
2069
2070 fn element_geometry(
2071 &self,
2072 reference: &crate::ElementRef,
2073 observation: crate::element_ref::ElementRefGeometryRead,
2074 ) -> Result<Option<crate::ElementGeometry>, UiContextError> {
2075 use crate::element_ref::ElementRefGeometryRead;
2076
2077 let mut runtime = self
2078 .runtime
2079 .try_borrow_mut()
2080 .map_err(|_| UiContextError::Borrowed)?;
2081 let node = if self.phase == ExecutionPhase::Render {
2082 match observation {
2083 ElementRefGeometryRead::Bounds => runtime
2084 .element_refs
2085 .resolve_and_track_geometry(reference, &self.read_dependency),
2086 ElementRefGeometryRead::LayoutSize => runtime
2087 .element_refs
2088 .resolve_and_track_geometry_read(reference, &self.read_dependency, observation),
2089 }
2090 } else if observation == ElementRefGeometryRead::LayoutSize {
2091 runtime.element_refs.resolve(reference).ok()
2092 } else {
2093 Some(runtime.element_refs.resolve(reference)?)
2094 };
2095 let Some(node) = node else {
2096 return Ok(None);
2097 };
2098 let geometry_registry =
2099 runtime.geometry_for(self.view.as_deref().or(self.window.as_deref()));
2100 drop(runtime);
2101 let geometry = if self.phase == ExecutionPhase::Render {
2102 match observation {
2103 ElementRefGeometryRead::Bounds => {
2104 geometry_registry.read_ref_tracked(reference.id(), node, &self.read_dependency)
2105 }
2106 ElementRefGeometryRead::LayoutSize => geometry_registry.read_ref_observation(
2107 reference.id(),
2108 node,
2109 &self.read_dependency,
2110 observation,
2111 ),
2112 }
2113 } else {
2114 geometry_registry.get(node)
2115 };
2116 Ok(geometry)
2117 }
2118
2119 pub fn element_bounds_by_key(&self, key: &str) -> Result<UiValue, UiContextError> {
2128 let reference = self
2129 .runtime
2130 .try_borrow()
2131 .map_err(|_| UiContextError::Borrowed)?
2132 .element_refs
2133 .resolve_key(&self.component, key)?;
2134 self.element_bounds(&reference)
2135 }
2136
2137 pub fn element_size_by_key(&self, key: &str) -> Result<UiValue, UiContextError> {
2146 let reference =
2147 crate::ElementRef::new(crate::ElementRefId::new(self.component.clone(), key)?);
2148 self.element_size(&reference)
2149 }
2150
2151 pub fn virtual_item_bounds(
2159 &self,
2160 collection: &str,
2161 index: usize,
2162 ) -> Result<UiValue, UiContextError> {
2163 let id = crate::VirtualCollectionId {
2164 component: self.component.clone(),
2165 key: collection.to_owned(),
2166 };
2167 let registry = self
2168 .runtime
2169 .try_borrow()
2170 .map_err(|_| UiContextError::Borrowed)?
2171 .virtual_requests
2172 .clone();
2173 Ok(registry
2174 .item_bounds(&id, index)
2175 .map_or(UiValue::Null, crate::GeometryBounds::into_value))
2176 }
2177
2178 pub fn event_target_bounds(&self) -> Result<UiValue, UiContextError> {
2189 if self.phase != ExecutionPhase::Event {
2190 return Err(UiContextError::EventTargetOutsideEvent);
2191 }
2192 Ok(self
2193 .event_target
2194 .map_or(UiValue::Null, crate::GeometryBounds::into_value))
2195 }
2196
2197 pub fn focus_element(&self, reference: &crate::ElementRef) -> Result<(), UiContextError> {
2203 self.require_mutation()?;
2204 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
2205 let mut runtime = self
2206 .runtime
2207 .try_borrow_mut()
2208 .map_err(|_| UiContextError::Borrowed)?;
2209 let node = runtime.element_refs.resolve(reference)?;
2210 runtime
2211 .pending_element_commands
2212 .push(crate::element_ref::ElementCommand::Focus { window, node });
2213 Ok(())
2214 }
2215
2216 pub fn focus_element_by_key(&self, key: &str) -> Result<(), UiContextError> {
2222 let reference = self
2223 .runtime
2224 .try_borrow()
2225 .map_err(|_| UiContextError::Borrowed)?
2226 .element_refs
2227 .resolve_key(&self.component, key)?;
2228 self.focus_element(&reference)
2229 }
2230
2231 pub fn scroll_collection_to_end(&self, key: &str) -> Result<(), UiContextError> {
2237 self.scroll_collection_to_edge(key, true)
2238 }
2239
2240 pub fn scroll_collection_to_start(&self, key: &str) -> Result<(), UiContextError> {
2245 self.scroll_collection_to_edge(key, false)
2246 }
2247
2248 pub fn scroll_collection_by(&self, key: &str, distance: f64) -> Result<(), UiContextError> {
2254 self.require_mutation()?;
2255 if !distance.is_finite() {
2256 return Err(UiContextError::InvalidScrollOffset {
2257 x: 0.0,
2258 y: distance,
2259 });
2260 }
2261 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
2262 self.runtime
2263 .try_borrow_mut()
2264 .map_err(|_| UiContextError::Borrowed)?
2265 .pending_element_commands
2266 .push(crate::element_ref::ElementCommand::ScrollCollectionBy {
2267 window,
2268 id: crate::VirtualCollectionId {
2269 component: self.component.clone(),
2270 key: key.to_owned(),
2271 },
2272 distance,
2273 });
2274 Ok(())
2275 }
2276
2277 pub fn scroll_collection_to_key(&self, key: &str, item: &str) -> Result<(), UiContextError> {
2284 self.require_mutation()?;
2285 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
2286 self.runtime
2287 .try_borrow_mut()
2288 .map_err(|_| UiContextError::Borrowed)?
2289 .pending_element_commands
2290 .push(crate::element_ref::ElementCommand::ScrollCollectionToKey {
2291 window,
2292 id: crate::VirtualCollectionId {
2293 component: self.component.clone(),
2294 key: key.to_owned(),
2295 },
2296 item: item.to_owned(),
2297 });
2298 Ok(())
2299 }
2300
2301 fn scroll_collection_to_edge(&self, key: &str, end: bool) -> Result<(), UiContextError> {
2302 self.require_mutation()?;
2303 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
2304 self.runtime
2305 .try_borrow_mut()
2306 .map_err(|_| UiContextError::Borrowed)?
2307 .pending_element_commands
2308 .push(crate::element_ref::ElementCommand::ScrollCollection {
2309 window,
2310 id: crate::VirtualCollectionId {
2311 component: self.component.clone(),
2312 key: key.to_owned(),
2313 },
2314 end,
2315 });
2316 Ok(())
2317 }
2318
2319 pub fn collection_follow_status(
2326 &self,
2327 key: &str,
2328 ) -> Result<Option<crate::VirtualCollectionFollowStatus>, UiContextError> {
2329 let runtime = self
2330 .runtime
2331 .try_borrow()
2332 .map_err(|_| UiContextError::Borrowed)?;
2333 Ok(runtime
2334 .virtual_requests
2335 .scroll_handle(&crate::VirtualCollectionId {
2336 component: self.component.clone(),
2337 key: key.to_owned(),
2338 })
2339 .map(|handle| handle.status()))
2340 }
2341
2342 pub fn scroll_element_to(
2349 &self,
2350 reference: &crate::ElementRef,
2351 x: f64,
2352 y: f64,
2353 ) -> Result<(), UiContextError> {
2354 self.require_mutation()?;
2355 if !x.is_finite() || !y.is_finite() || x < 0.0 || y < 0.0 {
2356 return Err(UiContextError::InvalidScrollOffset { x, y });
2357 }
2358 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
2359 let mut runtime = self
2360 .runtime
2361 .try_borrow_mut()
2362 .map_err(|_| UiContextError::Borrowed)?;
2363 let node = runtime.element_refs.resolve(reference)?;
2364 runtime
2365 .pending_element_commands
2366 .push(crate::element_ref::ElementCommand::ScrollTo { window, node, x, y });
2367 Ok(())
2368 }
2369
2370 pub fn scroll_element_to_by_key(
2376 &self,
2377 key: &str,
2378 x: f64,
2379 y: f64,
2380 ) -> Result<(), UiContextError> {
2381 let reference = self
2382 .runtime
2383 .try_borrow()
2384 .map_err(|_| UiContextError::Borrowed)?
2385 .element_refs
2386 .resolve_key(&self.component, key)?;
2387 self.scroll_element_to(&reference, x, y)
2388 }
2389
2390 pub fn scroll_element_into_view(
2396 &self,
2397 reference: &crate::ElementRef,
2398 ) -> Result<(), UiContextError> {
2399 self.require_mutation()?;
2400 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
2401 let mut runtime = self
2402 .runtime
2403 .try_borrow_mut()
2404 .map_err(|_| UiContextError::Borrowed)?;
2405 let node = runtime.element_refs.resolve(reference)?;
2406 runtime
2407 .pending_element_commands
2408 .push(crate::element_ref::ElementCommand::ScrollIntoView { window, node });
2409 Ok(())
2410 }
2411
2412 pub fn copy_text(&self, text: String) -> Result<(), UiContextError> {
2421 self.require_mutation()?;
2422 self.view.as_ref().ok_or(UiContextError::MissingView)?;
2423 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
2424 UiValue::String(text.clone()).validate()?;
2425 let mut runtime = self
2426 .runtime
2427 .try_borrow_mut()
2428 .map_err(|_| UiContextError::Borrowed)?;
2429 if !matches!(
2430 runtime.origin,
2431 crate::InvocationOrigin::UserInput { .. } | crate::InvocationOrigin::Automation
2432 ) {
2433 return Err(UiContextError::ClipboardRequiresUserInput);
2434 }
2435 runtime
2436 .pending_element_commands
2437 .push(crate::element_ref::ElementCommand::CopyText { window, text });
2438 Ok(())
2439 }
2440
2441 pub fn scroll_element_into_view_by_key(&self, key: &str) -> Result<(), UiContextError> {
2447 let reference = self
2448 .runtime
2449 .try_borrow()
2450 .map_err(|_| UiContextError::Borrowed)?
2451 .element_refs
2452 .resolve_key(&self.component, key)?;
2453 self.scroll_element_into_view(&reference)
2454 }
2455
2456 pub fn get_app_store(&self, store: &str, field: &str) -> Result<UiValue, UiContextError> {
2462 let mut runtime = self
2463 .runtime
2464 .try_borrow_mut()
2465 .map_err(|_| UiContextError::Borrowed)?;
2466 Ok(runtime
2467 .stores
2468 .read_dependency(self.render_reader(), &StoreId::app(store), field)?)
2469 }
2470
2471 pub fn get_native_collection(
2480 &self,
2481 name: &str,
2482 ) -> Result<crate::NativeCollection, UiContextError> {
2483 let mut runtime = self
2484 .runtime
2485 .try_borrow_mut()
2486 .map_err(|_| UiContextError::Borrowed)?;
2487 Ok(runtime
2488 .native_collections
2489 .read_dependency(self.render_reader(), name, true)?)
2490 }
2491
2492 pub fn get_native_text_document(
2498 &self,
2499 name: &str,
2500 ) -> Result<crate::NativeTextDocument, UiContextError> {
2501 let mut runtime = self
2502 .runtime
2503 .try_borrow_mut()
2504 .map_err(|_| UiContextError::Borrowed)?;
2505 Ok(runtime
2506 .native_documents
2507 .read_dependency(self.render_reader(), name)?)
2508 }
2509
2510 #[cfg(feature = "charts")]
2518 pub fn get_native_chart_data(
2519 &self,
2520 name: &str,
2521 ) -> Result<crate::NativeChartData, UiContextError> {
2522 self.runtime
2523 .try_borrow()
2524 .map_err(|_| UiContextError::Borrowed)?
2525 .native_chart_data
2526 .get(name)
2527 .cloned()
2528 .ok_or_else(|| UiContextError::UnknownChartData(name.to_owned()))
2529 }
2530
2531 pub fn get_app_store_path(
2537 &self,
2538 store: &str,
2539 field: &str,
2540 path: &UiValuePath,
2541 ) -> Result<UiValue, UiContextError> {
2542 let mut runtime = self
2543 .runtime
2544 .try_borrow_mut()
2545 .map_err(|_| UiContextError::Borrowed)?;
2546 Ok(runtime.stores.read_path_dependency(
2547 self.render_reader(),
2548 &StoreId::app(store),
2549 field,
2550 path,
2551 )?)
2552 }
2553
2554 pub fn set_app_store(
2560 &self,
2561 store: &str,
2562 field: &str,
2563 value: Dynamic,
2564 ) -> Result<(), UiContextError> {
2565 self.require_mutation()?;
2566 let value = UiValue::from_dynamic(value)?;
2567 let mut runtime = self
2568 .runtime
2569 .try_borrow_mut()
2570 .map_err(|_| UiContextError::Borrowed)?;
2571 let id = StoreId::app(store);
2572 let sensitive = runtime.stores.is_sensitive(&id, field);
2573 let invalidated = runtime.stores.write(&id, field, value.clone())?;
2574 runtime.mark_dirty(invalidated);
2575 runtime.traces.push(
2576 crate::RuntimeTraceKind::Store,
2577 format!("app:{store}"),
2578 format!("set {field}"),
2579 Some(value),
2580 sensitive,
2581 );
2582 Ok(())
2583 }
2584
2585 pub fn set_app_store_path(
2591 &self,
2592 store: &str,
2593 field: &str,
2594 path: &UiValuePath,
2595 value: Dynamic,
2596 ) -> Result<(), UiContextError> {
2597 self.require_mutation()?;
2598 let value = UiValue::from_dynamic(value)?;
2599 let mut runtime = self
2600 .runtime
2601 .try_borrow_mut()
2602 .map_err(|_| UiContextError::Borrowed)?;
2603 let id = StoreId::app(store);
2604 let sensitive = runtime.stores.is_sensitive(&id, field);
2605 let invalidated = runtime.stores.write_path(&id, field, path, value.clone())?;
2606 runtime.mark_dirty(invalidated);
2607 runtime.traces.push(
2608 crate::RuntimeTraceKind::Store,
2609 format!("app:{store}"),
2610 format!("set nested {field}"),
2611 Some(value),
2612 sensitive,
2613 );
2614 Ok(())
2615 }
2616
2617 pub fn get_window_store(&self, store: &str, field: &str) -> Result<UiValue, UiContextError> {
2624 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
2625 let mut runtime = self
2626 .runtime
2627 .try_borrow_mut()
2628 .map_err(|_| UiContextError::Borrowed)?;
2629 Ok(runtime.stores.read_dependency(
2630 self.render_reader(),
2631 &StoreId::window(window, store),
2632 field,
2633 )?)
2634 }
2635
2636 pub fn get_window_store_path(
2642 &self,
2643 store: &str,
2644 field: &str,
2645 path: &UiValuePath,
2646 ) -> Result<UiValue, UiContextError> {
2647 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
2648 let mut runtime = self
2649 .runtime
2650 .try_borrow_mut()
2651 .map_err(|_| UiContextError::Borrowed)?;
2652 Ok(runtime.stores.read_path_dependency(
2653 self.render_reader(),
2654 &StoreId::window(window, store),
2655 field,
2656 path,
2657 )?)
2658 }
2659
2660 pub fn set_window_store(
2666 &self,
2667 store: &str,
2668 field: &str,
2669 value: Dynamic,
2670 ) -> Result<(), UiContextError> {
2671 self.require_mutation()?;
2672 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
2673 let value = UiValue::from_dynamic(value)?;
2674 let mut runtime = self
2675 .runtime
2676 .try_borrow_mut()
2677 .map_err(|_| UiContextError::Borrowed)?;
2678 let id = StoreId::window(window, store);
2679 let sensitive = runtime.stores.is_sensitive(&id, field);
2680 let invalidated = runtime.stores.write(&id, field, value.clone())?;
2681 runtime.mark_dirty(invalidated);
2682 runtime.traces.push(
2683 crate::RuntimeTraceKind::Store,
2684 format!("window:{window}:{store}"),
2685 format!("set {field}"),
2686 Some(value),
2687 sensitive,
2688 );
2689 Ok(())
2690 }
2691
2692 pub fn set_window_store_path(
2699 &self,
2700 store: &str,
2701 field: &str,
2702 path: &UiValuePath,
2703 value: Dynamic,
2704 ) -> Result<(), UiContextError> {
2705 self.require_mutation()?;
2706 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
2707 let value = UiValue::from_dynamic(value)?;
2708 let mut runtime = self
2709 .runtime
2710 .try_borrow_mut()
2711 .map_err(|_| UiContextError::Borrowed)?;
2712 let id = StoreId::window(window, store);
2713 let sensitive = runtime.stores.is_sensitive(&id, field);
2714 let invalidated = runtime.stores.write_path(&id, field, path, value.clone())?;
2715 runtime.mark_dirty(invalidated);
2716 runtime.traces.push(
2717 crate::RuntimeTraceKind::Store,
2718 format!("window:{window}:{store}"),
2719 format!("set nested {field}"),
2720 Some(value),
2721 sensitive,
2722 );
2723 Ok(())
2724 }
2725
2726 pub fn emit(&self, event: &str, payload: Dynamic) -> Result<(), UiContextError> {
2732 self.require_mutation()?;
2733 let schema = self
2734 .events
2735 .get(event)
2736 .ok_or_else(|| UiContextError::UnknownEvent(event.to_owned()))?;
2737 schema
2738 .payload
2739 .validate(&payload)
2740 .map_err(UiContextError::InvalidEvent)?;
2741 let payload = UiValue::from_dynamic(payload)?;
2742 let mut runtime = self
2743 .runtime
2744 .try_borrow_mut()
2745 .map_err(|_| UiContextError::Borrowed)?;
2746 let origin = runtime.origin.clone();
2747 let owner = Some(self.semantic_dispatch_owner(&mut runtime));
2748 runtime.pending_events.push(PendingEvent {
2749 target: self.component.clone(),
2750 event: UiEvent {
2751 name: event.to_owned(),
2752 payload,
2753 },
2754 origin,
2755 owner,
2756 });
2757 runtime.publish_committed_work();
2758 runtime.traces.push(
2759 crate::RuntimeTraceKind::Event,
2760 self.component.to_string(),
2761 format!("emit {event}"),
2762 None,
2763 true,
2764 );
2765 Ok(())
2766 }
2767
2768 pub fn dispatch_action(&self, action: &str, payload: Dynamic) -> Result<(), UiContextError> {
2774 self.require_mutation()?;
2775 let id = ActionId::parse(action)?;
2776 let payload = UiValue::from_dynamic(payload)?;
2777 let mut runtime = self
2778 .runtime
2779 .try_borrow_mut()
2780 .map_err(|_| UiContextError::Borrowed)?;
2781 let mut invocation = runtime.actions.dispatch(&id, payload)?;
2782 invocation.origin = runtime.origin.clone();
2783 invocation.owner = Some(self.semantic_dispatch_owner(&mut runtime));
2784 runtime.pending_actions.push(invocation);
2785 runtime.publish_committed_work();
2786 runtime.traces.push(
2787 crate::RuntimeTraceKind::Action,
2788 self.component.to_string(),
2789 format!("dispatch {action}"),
2790 None,
2791 true,
2792 );
2793 Ok(())
2794 }
2795
2796 fn semantic_dispatch_owner(&self, runtime: &mut UiRuntimeState) -> SemanticDispatchOwner {
2797 let source = runtime.dispatch_owner.as_ref().map_or_else(
2798 || SemanticDispatchSource {
2799 runtime_id: runtime.runtime_id,
2800 generation: self.generation,
2801 component: self.component.clone(),
2802 incarnation: self.incarnation,
2803 effect: self
2804 .async_scope
2805 .clone()
2806 .filter(|scope| matches!(scope, AsyncScope::Effect { .. })),
2807 cascade: (runtime.origin == crate::InvocationOrigin::Effect)
2808 .then(|| runtime.effect_cascades.dispatch_token(&self.component))
2809 .flatten(),
2810 publication_valid: Cell::new(true),
2811 },
2812 |owner| owner.source.as_ref().clone(),
2813 );
2814 source.publication_valid.set(true);
2815 let source = Rc::new(source);
2816 if runtime.transaction_depth > 0 {
2817 runtime.dispatch_leases.push(Rc::clone(&source));
2818 }
2819 if let Some((root, _)) = &source.cascade {
2820 runtime.effect_cascades.track_dispatch(root, &source);
2821 }
2822 SemanticDispatchOwner { source }
2823 }
2824
2825 pub fn register_action(&self, action: &str, callback: FnPtr) -> Result<(), UiContextError> {
2831 self.require_mutation()?;
2832 let id = ActionId::parse(action)?;
2833 let callback = self.scoped_callback(callback)?;
2834 self.runtime
2835 .try_borrow_mut()
2836 .map_err(|_| UiContextError::Borrowed)?
2837 .actions
2838 .register_or_replace(id, callback);
2839 Ok(())
2840 }
2841
2842 pub fn set_action_enabled(&self, action: &str, enabled: bool) -> Result<(), UiContextError> {
2848 self.require_mutation()?;
2849 let id = ActionId::parse(action)?;
2850 self.runtime
2851 .try_borrow_mut()
2852 .map_err(|_| UiContextError::Borrowed)?
2853 .actions
2854 .set_enabled(&id, enabled)?;
2855 Ok(())
2856 }
2857
2858 pub fn action_shortcut(
2865 &self,
2866 action: &str,
2867 ) -> Result<Option<crate::ActionShortcut>, UiContextError> {
2868 let id = ActionId::parse(action)?;
2869 let runtime = self
2870 .runtime
2871 .try_borrow()
2872 .map_err(|_| UiContextError::Borrowed)?;
2873 Ok(runtime
2874 .key_bindings
2875 .iter()
2876 .find(|binding| binding.action == id)
2877 .map(crate::KeyBindingSpec::shortcut))
2878 }
2879
2880 pub fn action_enabled(&self, action: &str) -> Result<bool, UiContextError> {
2886 let id = ActionId::parse(action)?;
2887 Ok(self
2888 .runtime
2889 .try_borrow()
2890 .map_err(|_| UiContextError::Borrowed)?
2891 .actions
2892 .is_enabled(&id)
2893 .unwrap_or(false))
2894 }
2895
2896 pub fn actions(&self) -> Result<Vec<UiValue>, UiContextError> {
2903 let runtime = self
2904 .runtime
2905 .try_borrow()
2906 .map_err(|_| UiContextError::Borrowed)?;
2907 Ok(runtime
2908 .actions
2909 .ids()
2910 .map(|id| {
2911 let shortcut = runtime
2912 .key_bindings
2913 .iter()
2914 .find(|binding| &binding.action == id)
2915 .map_or(UiValue::Null, |binding| binding.shortcut().to_ui_value());
2916 UiValue::Map(BTreeMap::from([
2917 ("id".to_owned(), UiValue::String(id.as_str().to_owned())),
2918 (
2919 "enabled".to_owned(),
2920 UiValue::Bool(runtime.actions.is_enabled(id).unwrap_or(false)),
2921 ),
2922 ("shortcut".to_owned(), shortcut),
2923 ]))
2924 })
2925 .collect())
2926 }
2927
2928 pub fn call_capability(
2934 &self,
2935 capability: &str,
2936 method: &str,
2937 input: Dynamic,
2938 ) -> Result<UiValue, UiContextError> {
2939 self.require_mutation()?;
2940 let id = CapabilityId::parse(capability)?;
2941 let input = UiValue::from_dynamic(input)?;
2942 let mut runtime = self
2943 .runtime
2944 .try_borrow_mut()
2945 .map_err(|_| UiContextError::Borrowed)?;
2946 let context = self.invocation_context(&runtime);
2947 let output = runtime
2948 .capabilities
2949 .call_with(&context, &id, method, input)?;
2950 runtime.traces.push(
2951 crate::RuntimeTraceKind::Capability,
2952 self.component.to_string(),
2953 format!("call {capability}.{method}"),
2954 None,
2955 true,
2956 );
2957 Ok(output)
2958 }
2959
2960 fn invocation_context(&self, runtime: &UiRuntimeState) -> crate::InvocationContext {
2962 crate::InvocationContext {
2963 origin: runtime.origin.clone(),
2964 view_id: self.view.clone(),
2965 component: self.component.clone(),
2966 }
2967 }
2968
2969 fn read_locale<T>(
2970 &self,
2971 read: impl FnOnce(
2972 &LocaleManager,
2973 Option<&str>,
2974 &ComponentInstancePath,
2975 ) -> Result<T, LocaleError>,
2976 ) -> Result<T, UiContextError> {
2977 let mut runtime = self
2978 .runtime
2979 .try_borrow_mut()
2980 .map_err(|_| UiContextError::Borrowed)?;
2981 if let Some(reader) = self.render_reader() {
2982 runtime
2983 .environment_dependencies
2984 .track_locale(self.window.as_deref(), reader);
2985 }
2986 let locale = runtime
2987 .locale
2988 .as_ref()
2989 .ok_or(UiContextError::LocaleUnavailable)?;
2990 Ok(read(locale, self.window.as_deref(), &self.component)?)
2991 }
2992
2993 pub fn text(&self, key: &str) -> Result<String, UiContextError> {
2999 self.read_locale(|locale, window, component| locale.text(window, Some(component), key))
3000 }
3001
3002 pub fn text_or(&self, key: &str, fallback: &str) -> Result<String, UiContextError> {
3010 match self.text(key) {
3011 Ok(text) => Ok(text),
3012 Err(
3013 UiContextError::LocaleUnavailable
3014 | UiContextError::Locale(crate::LocaleError::UnknownMessage(_)),
3015 ) => Ok(fallback.to_owned()),
3016 Err(error) => Err(error),
3017 }
3018 }
3019
3020 pub fn text_direction(&self) -> Result<String, UiContextError> {
3027 let direction = match self
3028 .read_locale(|locale, window, component| locale.direction(window, Some(component)))
3029 {
3030 Ok(direction) => direction,
3031 Err(UiContextError::LocaleUnavailable) => TextDirection::LeftToRight,
3032 Err(error) => return Err(error),
3033 };
3034 match direction {
3035 TextDirection::LeftToRight => Ok("ltr".to_owned()),
3036 TextDirection::RightToLeft => Ok("rtl".to_owned()),
3037 }
3038 }
3039
3040 pub fn today(&self) -> Result<String, UiContextError> {
3048 let runtime = self
3049 .runtime
3050 .try_borrow()
3051 .map_err(|_| UiContextError::Borrowed)?;
3052 runtime
3053 .calendar_clock
3054 .presentation_today(&runtime.wall_clock)
3055 .map(crate::GregorianDate::to_iso)
3056 .map_err(|error| LocaleError::Decode(error.to_string()).into())
3057 }
3058
3059 pub fn now(&self) -> Result<i64, UiContextError> {
3064 Ok(self
3065 .runtime
3066 .try_borrow()
3067 .map_err(|_| UiContextError::Borrowed)?
3068 .wall_clock
3069 .now_ms())
3070 }
3071
3072 pub fn format_time(&self, ms: i64, style: &str, zone: &str) -> Result<String, UiContextError> {
3077 self.read_locale(|locale, window, component| {
3078 let bundle = locale.selected_bundle(window, Some(component))?;
3079 crate::time::format_time(
3080 ms,
3081 style,
3082 zone,
3083 &bundle.time,
3084 &bundle.calendar,
3085 &bundle.number,
3086 )
3087 .map_err(|e| LocaleError::Decode(e.to_string()))
3088 })
3089 }
3090
3091 pub fn format_duration(&self, ms: i64) -> Result<String, UiContextError> {
3096 self.read_locale(|locale, window, component| {
3097 let bundle = locale.selected_bundle(window, Some(component))?;
3098 Ok(crate::time::format_duration(
3099 ms,
3100 &bundle.time,
3101 &bundle.number,
3102 ))
3103 })
3104 }
3105
3106 pub fn format_relative(&self, ms: i64) -> Result<String, UiContextError> {
3111 let now = self.now()?;
3112 self.read_locale(|locale, window, component| {
3113 let bundle = locale.selected_bundle(window, Some(component))?;
3114 Ok(crate::time::format_relative(
3115 ms,
3116 now,
3117 &bundle.time,
3118 &bundle.number,
3119 ))
3120 })
3121 }
3122
3123 pub fn time_metadata(&self) -> Result<Map, UiContextError> {
3128 let metadata = self.read_locale(|locale, window, component| {
3129 Ok(locale
3130 .selected_bundle(window, Some(component))?
3131 .time
3132 .clone())
3133 })?;
3134 rhai::serde::to_dynamic(metadata)
3135 .map(Dynamic::cast::<Map>)
3136 .map_err(|e| LocaleError::Decode(e.to_string()).into())
3137 }
3138
3139 pub fn parse_time(&self, value: &str, precision: &str) -> Result<Dynamic, UiContextError> {
3144 self.read_locale(|locale, window, component| {
3145 let bundle = locale.selected_bundle(window, Some(component))?;
3146 Ok(
3147 crate::time::parse_time(value, precision, &bundle.time, &bundle.number)
3148 .map_or(Dynamic::UNIT, Dynamic::from),
3149 )
3150 })
3151 }
3152
3153 pub fn format_date(&self, iso_date: &str, style: &str) -> Result<String, UiContextError> {
3159 let style = DateStyle::parse(style)?;
3160 self.read_locale(|locale, window, component| {
3161 locale.format_date(window, Some(component), iso_date, style)
3162 })
3163 }
3164
3165 pub fn format_month_year(&self, iso_date: &str) -> Result<String, UiContextError> {
3171 self.read_locale(|locale, window, component| {
3172 locale.format_month_year(window, Some(component), iso_date)
3173 })
3174 }
3175
3176 pub fn calendar_metadata(&self) -> Result<Map, UiContextError> {
3182 let calendar = self.read_locale(|locale, window, component| {
3183 locale.calendar(window, Some(component)).cloned()
3184 })?;
3185 let dynamic = rhai::serde::to_dynamic(calendar)
3186 .map_err(|error| LocaleError::Decode(error.to_string()))?;
3187 Ok(dynamic.cast::<Map>())
3188 }
3189
3190 pub fn number_metadata(&self) -> Result<Map, UiContextError> {
3196 let number = self.read_locale(|locale, window, component| {
3197 locale.number(window, Some(component)).cloned()
3198 })?;
3199 let dynamic = rhai::serde::to_dynamic(number)
3200 .map_err(|error| LocaleError::Decode(error.to_string()))?;
3201 Ok(dynamic.cast::<Map>())
3202 }
3203
3204 pub fn format_integer(
3210 &self,
3211 value: INT,
3212 options: NumberFormatOptions,
3213 ) -> Result<String, UiContextError> {
3214 self.read_locale(|locale, window, component| {
3215 locale.format_integer(window, Some(component), value, options)
3216 })
3217 }
3218
3219 pub fn format_number(
3225 &self,
3226 value: FLOAT,
3227 options: NumberFormatOptions,
3228 ) -> Result<String, UiContextError> {
3229 self.read_locale(|locale, window, component| {
3230 locale.format_number(window, Some(component), value, options)
3231 })
3232 }
3233
3234 pub fn set_locale(&self, locale: &str) -> Result<(), UiContextError> {
3240 self.require_mutation()?;
3241 let mut runtime = self
3242 .runtime
3243 .try_borrow_mut()
3244 .map_err(|_| UiContextError::Borrowed)?;
3245 let changed = {
3246 let locales = runtime
3247 .locale
3248 .as_mut()
3249 .ok_or(UiContextError::LocaleUnavailable)?;
3250 let previous = locales.generation();
3251 locales.set_app(locale)?;
3252 locales.generation() != previous
3253 };
3254 if changed {
3255 let invalidated = runtime.environment_dependencies.invalidate_locale_app();
3256 runtime.mark_dirty(invalidated);
3257 runtime.mark_all_windows_repaint();
3258 }
3259 runtime.traces.push(
3260 crate::RuntimeTraceKind::Locale,
3261 self.component.to_string(),
3262 format!("select {locale}"),
3263 None,
3264 false,
3265 );
3266 Ok(())
3267 }
3268
3269 pub fn set_theme(&self, family: &str, variant: &str) -> Result<(), UiContextError> {
3275 self.set_theme_preference(
3276 ThemeTarget::App,
3277 ThemePreference::Fixed {
3278 selection: ThemeSelection::new(family, variant),
3279 },
3280 format!("select {family}/{variant}"),
3281 )
3282 }
3283
3284 pub fn set_window_theme(&self, family: &str, variant: &str) -> Result<(), UiContextError> {
3290 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
3291 self.set_theme_preference(
3292 ThemeTarget::Window(window),
3293 ThemePreference::Fixed {
3294 selection: ThemeSelection::new(family, variant),
3295 },
3296 format!("select window {family}/{variant}"),
3297 )
3298 }
3299
3300 pub fn window_id(&self) -> Result<String, UiContextError> {
3306 self.window.clone().ok_or(UiContextError::MissingWindow)
3307 }
3308
3309 pub fn view_id(&self) -> Result<String, UiContextError> {
3316 self.view.clone().ok_or(UiContextError::MissingView)
3317 }
3318
3319 pub fn viewport_class(&self) -> Result<String, UiContextError> {
3325 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
3326 let mut runtime = self
3327 .runtime
3328 .try_borrow_mut()
3329 .map_err(|_| UiContextError::Borrowed)?;
3330 if let Some(reader) = self.render_reader() {
3331 runtime
3332 .environment_dependencies
3333 .track_viewport(window, reader);
3334 }
3335 Ok(runtime.responsive.class(window).as_str().to_owned())
3336 }
3337
3338 pub fn open_window(&self, spec: ScriptWindowSpec) -> Result<(), UiContextError> {
3344 self.require_mutation()?;
3345 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
3346 let id = spec.id.clone();
3347 let mut runtime = self
3348 .runtime
3349 .try_borrow_mut()
3350 .map_err(|_| UiContextError::Borrowed)?;
3351 runtime.windows.request_open_from(window, spec)?;
3352 runtime.traces.push(
3353 crate::RuntimeTraceKind::Window,
3354 self.component.to_string(),
3355 format!("open {id}"),
3356 None,
3357 false,
3358 );
3359 Ok(())
3360 }
3361
3362 pub fn focus_window(&self, id: &str) -> Result<(), UiContextError> {
3368 self.require_mutation()?;
3369 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
3370 let mut runtime = self
3371 .runtime
3372 .try_borrow_mut()
3373 .map_err(|_| UiContextError::Borrowed)?;
3374 runtime.windows.request_focus_from(window, id)?;
3375 runtime.traces.push(
3376 crate::RuntimeTraceKind::Window,
3377 self.component.to_string(),
3378 format!("focus {id}"),
3379 None,
3380 false,
3381 );
3382 Ok(())
3383 }
3384
3385 pub fn close_window(&self, id: &str) -> Result<(), UiContextError> {
3391 self.require_mutation()?;
3392 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
3393 let mut runtime = self
3394 .runtime
3395 .try_borrow_mut()
3396 .map_err(|_| UiContextError::Borrowed)?;
3397 runtime.windows.request_close_from(window, id)?;
3398 runtime.traces.push(
3399 crate::RuntimeTraceKind::Window,
3400 self.component.to_string(),
3401 format!("close {id}"),
3402 None,
3403 false,
3404 );
3405 Ok(())
3406 }
3407
3408 pub fn set_close_handler(&self, callback: FnPtr) -> Result<(), UiContextError> {
3415 self.require_mutation()?;
3416 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
3417 let callback = self.scoped_callback(callback)?;
3418 self.runtime
3419 .try_borrow_mut()
3420 .map_err(|_| UiContextError::Borrowed)?
3421 .windows
3422 .set_close_handler(window, Some(callback))?;
3423 Ok(())
3424 }
3425
3426 pub fn clear_close_handler(&self) -> Result<(), UiContextError> {
3432 self.require_mutation()?;
3433 let window = self.window.as_ref().ok_or(UiContextError::MissingWindow)?;
3434 self.runtime
3435 .try_borrow_mut()
3436 .map_err(|_| UiContextError::Borrowed)?
3437 .windows
3438 .set_close_handler(window, None)?;
3439 Ok(())
3440 }
3441
3442 pub fn set_window_locale(&self, locale: &str) -> Result<(), UiContextError> {
3448 self.require_mutation()?;
3449 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
3450 let mut runtime = self
3451 .runtime
3452 .try_borrow_mut()
3453 .map_err(|_| UiContextError::Borrowed)?;
3454 let changed = {
3455 let locales = runtime
3456 .locale
3457 .as_mut()
3458 .ok_or(UiContextError::LocaleUnavailable)?;
3459 let previous = locales.generation();
3460 locales.set_window(window.clone(), locale)?;
3461 locales.generation() != previous
3462 };
3463 if changed {
3464 let invalidated = runtime
3465 .environment_dependencies
3466 .invalidate_locale_window(&window);
3467 runtime.mark_dirty(invalidated);
3468 runtime.mark_window_repaint(window.clone());
3469 }
3470 runtime.traces.push(
3471 crate::RuntimeTraceKind::Locale,
3472 self.component.to_string(),
3473 format!("select window {window} locale {locale}"),
3474 None,
3475 false,
3476 );
3477 Ok(())
3478 }
3479
3480 pub fn set_local_locale(&self, locale: &str) -> Result<(), UiContextError> {
3486 self.require_mutation()?;
3487 let mut runtime = self
3488 .runtime
3489 .try_borrow_mut()
3490 .map_err(|_| UiContextError::Borrowed)?;
3491 let changed = {
3492 let locales = runtime
3493 .locale
3494 .as_mut()
3495 .ok_or(UiContextError::LocaleUnavailable)?;
3496 let previous = locales.generation();
3497 locales.set_scope(self.component.clone(), locale)?;
3498 locales.generation() != previous
3499 };
3500 if changed {
3501 let invalidated = runtime
3502 .environment_dependencies
3503 .invalidate_locale_scope(&self.component);
3504 runtime.mark_dirty(invalidated);
3505 if let Some(window) = &self.window {
3506 runtime.mark_window_repaint(window.clone());
3507 }
3508 }
3509 runtime.traces.push(
3510 crate::RuntimeTraceKind::Locale,
3511 self.component.to_string(),
3512 format!("select subtree locale {locale}"),
3513 None,
3514 false,
3515 );
3516 Ok(())
3517 }
3518
3519 pub fn set_local_theme(&self, family: &str, variant: &str) -> Result<(), UiContextError> {
3525 self.set_theme_preference(
3526 ThemeTarget::Local,
3527 ThemePreference::Fixed {
3528 selection: ThemeSelection::new(family, variant),
3529 },
3530 format!("select subtree {family}/{variant}"),
3531 )
3532 }
3533
3534 pub fn set_theme_system(&self, family: &str) -> Result<(), UiContextError> {
3540 self.set_theme_preference(
3541 ThemeTarget::App,
3542 ThemePreference::System {
3543 family: family.to_owned(),
3544 },
3545 format!("follow system family {family}"),
3546 )
3547 }
3548
3549 pub fn set_window_theme_system(&self, family: &str) -> Result<(), UiContextError> {
3555 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
3556 self.set_theme_preference(
3557 ThemeTarget::Window(window),
3558 ThemePreference::System {
3559 family: family.to_owned(),
3560 },
3561 format!("follow window system family {family}"),
3562 )
3563 }
3564
3565 pub fn set_local_theme_system(&self, family: &str) -> Result<(), UiContextError> {
3571 self.set_theme_preference(
3572 ThemeTarget::Local,
3573 ThemePreference::System {
3574 family: family.to_owned(),
3575 },
3576 format!("follow subtree system family {family}"),
3577 )
3578 }
3579
3580 pub fn set_theme_system_pair(
3587 &self,
3588 light: ThemeSelection,
3589 dark: ThemeSelection,
3590 ) -> Result<(), UiContextError> {
3591 let message = format!(
3592 "follow system pair {}/{} and {}/{}",
3593 light.family, light.variant, dark.family, dark.variant
3594 );
3595 self.set_theme_preference(
3596 ThemeTarget::App,
3597 ThemePreference::SystemPair { light, dark },
3598 message,
3599 )
3600 }
3601
3602 pub fn set_window_theme_system_pair(
3608 &self,
3609 light: ThemeSelection,
3610 dark: ThemeSelection,
3611 ) -> Result<(), UiContextError> {
3612 let window = self.window.clone().ok_or(UiContextError::MissingWindow)?;
3613 let message = format!(
3614 "follow window system pair {}/{} and {}/{}",
3615 light.family, light.variant, dark.family, dark.variant
3616 );
3617 self.set_theme_preference(
3618 ThemeTarget::Window(window),
3619 ThemePreference::SystemPair { light, dark },
3620 message,
3621 )
3622 }
3623
3624 pub fn set_local_theme_system_pair(
3630 &self,
3631 light: ThemeSelection,
3632 dark: ThemeSelection,
3633 ) -> Result<(), UiContextError> {
3634 let message = format!(
3635 "follow subtree system pair {}/{} and {}/{}",
3636 light.family, light.variant, dark.family, dark.variant
3637 );
3638 self.set_theme_preference(
3639 ThemeTarget::Local,
3640 ThemePreference::SystemPair { light, dark },
3641 message,
3642 )
3643 }
3644
3645 fn set_theme_preference(
3646 &self,
3647 target: ThemeTarget,
3648 preference: ThemePreference,
3649 message: String,
3650 ) -> Result<(), UiContextError> {
3651 self.require_mutation()?;
3652 let mut runtime = self
3653 .runtime
3654 .try_borrow_mut()
3655 .map_err(|_| UiContextError::Borrowed)?;
3656 let invalidated = match &target {
3657 ThemeTarget::App => runtime.environment_dependencies.invalidate_theme_app(),
3658 ThemeTarget::Window(window) => runtime
3659 .environment_dependencies
3660 .invalidate_theme_window(window),
3661 ThemeTarget::Local => runtime
3662 .environment_dependencies
3663 .invalidate_theme_scope(&self.component),
3664 };
3665 let app_target = matches!(&target, ThemeTarget::App);
3666 let theme = runtime
3667 .theme
3668 .as_mut()
3669 .ok_or(UiContextError::ThemeUnavailable)?;
3670 match target {
3671 ThemeTarget::App => theme.set_app(preference)?,
3672 ThemeTarget::Window(window) => theme.set_window(window, preference)?,
3673 ThemeTarget::Local => theme.set_scope(self.component.clone(), preference)?,
3674 }
3675 if app_target {
3676 runtime.mark_all_windows_dirty();
3677 } else {
3678 runtime.mark_dirty([self.component.clone()]);
3679 }
3680 runtime.mark_dirty(invalidated);
3681 runtime.traces.push(
3682 crate::RuntimeTraceKind::Theme,
3683 self.component.to_string(),
3684 message,
3685 None,
3686 false,
3687 );
3688 Ok(())
3689 }
3690
3691 pub fn set_reduced_motion(&self, reduced: bool) -> Result<(), UiContextError> {
3698 self.require_mutation()?;
3699 let mut runtime = self
3700 .runtime
3701 .try_borrow_mut()
3702 .map_err(|_| UiContextError::Borrowed)?;
3703 runtime.motions.request_preference(if reduced {
3704 crate::MotionPreference::Reduced
3705 } else {
3706 crate::MotionPreference::Normal
3707 });
3708 let now = runtime.clock.now();
3709 runtime.motion_values = runtime.motions.snapshot(now);
3710 runtime.mark_dirty([self.component.clone()]);
3711 runtime.traces.push(
3712 crate::RuntimeTraceKind::State,
3713 self.component.to_string(),
3714 format!("reduced motion {reduced}"),
3715 None,
3716 false,
3717 );
3718 Ok(())
3719 }
3720
3721 pub fn motion_handle(&self, name: &str) -> Result<crate::MotionHandle, UiContextError> {
3727 let scope = self.motion_scope();
3728 Ok(self
3729 .runtime
3730 .try_borrow()
3731 .map_err(|_| UiContextError::Borrowed)?
3732 .motions
3733 .timeline_handle_for_owner(
3734 &scope,
3735 &self.component,
3736 self.incarnation,
3737 self.generation,
3738 name,
3739 )?)
3740 }
3741
3742 #[must_use]
3743 pub fn motion_tokens(&self) -> crate::ThemeMotion {
3744 self.with_resolved_theme(|variant| variant.tokens.motion.clone())
3745 .unwrap_or_default()
3746 }
3747
3748 #[must_use]
3755 pub fn resolved_theme_variant(&self) -> Option<crate::ThemeVariantInfo> {
3756 self.with_resolved_theme(|variant| crate::ThemeVariantInfo {
3757 family: variant.family.clone(),
3758 name: variant.name.clone(),
3759 mode: variant.mode,
3760 })
3761 }
3762
3763 #[must_use]
3766 pub fn theme_variants(&self) -> Vec<crate::ThemeVariantInfo> {
3767 let Ok(runtime) = self.runtime.try_borrow() else {
3768 return Vec::new();
3769 };
3770 runtime
3771 .theme
3772 .as_ref()
3773 .map(|theme| {
3774 theme
3775 .variants()
3776 .map(|variant| crate::ThemeVariantInfo {
3777 family: variant.family.clone(),
3778 name: variant.name.clone(),
3779 mode: variant.mode,
3780 })
3781 .collect()
3782 })
3783 .unwrap_or_default()
3784 }
3785
3786 #[must_use]
3791 pub fn theme_colors(&self, family: &str, name: &str) -> Option<BTreeMap<String, crate::Rgba8>> {
3792 let runtime = self.runtime.try_borrow().ok()?;
3793 runtime
3794 .theme
3795 .as_ref()?
3796 .variants()
3797 .find(|variant| variant.family == family && variant.name == name)
3798 .map(|variant| variant.tokens.color_snapshot())
3799 }
3800
3801 fn with_resolved_theme<R>(&self, project: impl FnOnce(&crate::ThemeVariant) -> R) -> Option<R> {
3802 let Ok(mut runtime) = self.runtime.try_borrow_mut() else {
3803 return None;
3804 };
3805 if self.phase == ExecutionPhase::Render {
3806 runtime
3807 .environment_dependencies
3808 .track_theme(self.window.as_deref(), &self.read_dependency);
3809 }
3810 let appearance = self
3811 .window
3812 .as_deref()
3813 .and_then(|window| runtime.window_appearances.get(window).copied())
3814 .unwrap_or(crate::SystemAppearance::Dark);
3815 runtime
3816 .theme
3817 .as_ref()
3818 .and_then(|theme| {
3819 theme
3820 .resolve(self.window.as_deref(), Some(&self.component), appearance)
3821 .ok()
3822 })
3823 .map(|theme| project(theme.variant()))
3824 }
3825
3826 #[must_use]
3828 pub fn resolved_theme_selection(&self) -> Option<ThemeSelection> {
3829 self.with_resolved_theme(|variant| ThemeSelection::new(&variant.family, &variant.name))
3830 }
3831
3832 pub fn motion_duration(&self, role: &str) -> Result<u64, UiContextError> {
3838 self.motion_tokens()
3839 .durations_ms
3840 .get(role)
3841 .copied()
3842 .ok_or_else(|| UiContextError::UnknownMotionToken {
3843 category: "duration",
3844 role: role.to_owned(),
3845 })
3846 }
3847
3848 pub fn motion_easing(&self, role: &str) -> Result<crate::MotionEasing, UiContextError> {
3854 self.motion_tokens()
3855 .easings
3856 .get(role)
3857 .copied()
3858 .ok_or_else(|| UiContextError::UnknownMotionToken {
3859 category: "easing",
3860 role: role.to_owned(),
3861 })
3862 }
3863
3864 pub fn motion_spring(&self, role: &str) -> Result<crate::ThemeMotionSpring, UiContextError> {
3870 self.motion_tokens()
3871 .springs
3872 .get(role)
3873 .copied()
3874 .ok_or_else(|| UiContextError::UnknownMotionToken {
3875 category: "spring",
3876 role: role.to_owned(),
3877 })
3878 }
3879
3880 pub fn motion_distance(&self, role: &str) -> Result<f64, UiContextError> {
3886 self.motion_tokens()
3887 .distances
3888 .get(role)
3889 .copied()
3890 .ok_or_else(|| UiContextError::UnknownMotionToken {
3891 category: "distance",
3892 role: role.to_owned(),
3893 })
3894 }
3895
3896 pub fn motion_stagger(&self, role: &str) -> Result<u64, UiContextError> {
3902 self.motion_tokens()
3903 .staggers_ms
3904 .get(role)
3905 .copied()
3906 .ok_or_else(|| UiContextError::UnknownMotionToken {
3907 category: "stagger",
3908 role: role.to_owned(),
3909 })
3910 }
3911
3912 #[must_use]
3913 pub fn motion_quality(&self) -> crate::MotionQuality {
3914 self.runtime
3915 .try_borrow()
3916 .map_or(crate::MotionQuality::Low, |runtime| {
3917 runtime.motions.quality()
3918 })
3919 }
3920
3921 pub fn play_motion(&self, handle: &crate::MotionHandle) -> Result<(), UiContextError> {
3927 self.require_mutation()?;
3928 let mut runtime = self
3929 .runtime
3930 .try_borrow_mut()
3931 .map_err(|_| UiContextError::Borrowed)?;
3932 runtime.motions.validate_handle_owner(
3933 handle,
3934 &self.motion_scope(),
3935 &self.component,
3936 self.incarnation,
3937 self.generation,
3938 )?;
3939 let now = runtime.clock.now();
3940 runtime.motions.play_timeline(handle, now)?;
3941 Ok(())
3942 }
3943
3944 pub fn pause_motion(&self, handle: &crate::MotionHandle) -> Result<(), UiContextError> {
3950 self.require_mutation()?;
3951 let mut runtime = self
3952 .runtime
3953 .try_borrow_mut()
3954 .map_err(|_| UiContextError::Borrowed)?;
3955 runtime.motions.validate_handle_owner(
3956 handle,
3957 &self.motion_scope(),
3958 &self.component,
3959 self.incarnation,
3960 self.generation,
3961 )?;
3962 let now = runtime.clock.now();
3963 runtime.motions.pause_timeline(handle, now)?;
3964 Ok(())
3965 }
3966
3967 pub fn seek_motion(
3973 &self,
3974 handle: &crate::MotionHandle,
3975 position_ms: u64,
3976 ) -> Result<(), UiContextError> {
3977 self.require_mutation()?;
3978 let mut runtime = self
3979 .runtime
3980 .try_borrow_mut()
3981 .map_err(|_| UiContextError::Borrowed)?;
3982 runtime.motions.validate_handle_owner(
3983 handle,
3984 &self.motion_scope(),
3985 &self.component,
3986 self.incarnation,
3987 self.generation,
3988 )?;
3989 let now = runtime.clock.now();
3990 runtime.motions.seek_timeline(handle, position_ms, now)?;
3991 runtime.motion_values = runtime.motions.snapshot(now);
3992 Ok(())
3993 }
3994
3995 pub fn restart_motion(&self, handle: &crate::MotionHandle) -> Result<(), UiContextError> {
4001 self.require_mutation()?;
4002 let mut runtime = self
4003 .runtime
4004 .try_borrow_mut()
4005 .map_err(|_| UiContextError::Borrowed)?;
4006 runtime.motions.validate_handle_owner(
4007 handle,
4008 &self.motion_scope(),
4009 &self.component,
4010 self.incarnation,
4011 self.generation,
4012 )?;
4013 let now = runtime.clock.now();
4014 runtime.motions.restart_timeline(handle, now)?;
4015 Ok(())
4016 }
4017
4018 pub fn cancel_motion(&self, handle: &crate::MotionHandle) -> Result<(), UiContextError> {
4024 self.require_mutation()?;
4025 let mut runtime = self
4026 .runtime
4027 .try_borrow_mut()
4028 .map_err(|_| UiContextError::Borrowed)?;
4029 runtime.motions.validate_handle_owner(
4030 handle,
4031 &self.motion_scope(),
4032 &self.component,
4033 self.incarnation,
4034 self.generation,
4035 )?;
4036 runtime.motions.cancel_timeline(handle)?;
4037 Ok(())
4038 }
4039
4040 fn motion_scope(&self) -> String {
4041 match (self.window.as_deref(), self.view.as_deref()) {
4042 (Some(window), Some(view)) => format!("window:{window}/view:{view}/root"),
4043 (Some(window), None) => format!("window:{window}/root"),
4044 (None, Some(view)) => format!("view:{view}/root"),
4045 (None, None) => "root".to_owned(),
4046 }
4047 }
4048
4049 pub fn load_image(&self, asset: &AssetId) -> Result<OpaqueHandle, UiContextError> {
4055 self.require_mutation()?;
4056 Ok(self
4057 .runtime
4058 .try_borrow()
4059 .map_err(|_| UiContextError::Borrowed)?
4060 .assets
4061 .load_image(asset)?
4062 .opaque()
4063 .clone())
4064 }
4065
4066 pub fn start_image_decode(
4072 &self,
4073 asset: &AssetId,
4074 success: FnPtr,
4075 error: FnPtr,
4076 ) -> Result<ImageDecodeHandle, UiContextError> {
4077 self.require_mutation()?;
4078 self.require_async_start()?;
4079 self.require_generation()?;
4080 let success = self.scoped_callback(success)?;
4081 let error = self.scoped_callback(error)?;
4082 let mut runtime = self
4083 .runtime
4084 .try_borrow_mut()
4085 .map_err(|_| UiContextError::Borrowed)?;
4086 crate::RuntimeBudgets::check(
4087 "image_decodes",
4088 runtime.assets.pending_decode_count().saturating_add(1),
4089 runtime.budgets.image_decodes,
4090 )?;
4091 let handle = runtime.assets.start_image_decode(
4092 asset,
4093 self.async_scope
4094 .clone()
4095 .unwrap_or_else(|| AsyncScope::Component(self.component.clone())),
4096 self.generation,
4097 success,
4098 error,
4099 )?;
4100 runtime.traces.push(
4101 crate::RuntimeTraceKind::Task,
4102 self.component.to_string(),
4103 format!("decode image {}", asset.as_str()),
4104 None,
4105 false,
4106 );
4107 Ok(handle)
4108 }
4109
4110 pub fn cancel_image_decode(&self, handle: ImageDecodeHandle) -> Result<bool, UiContextError> {
4116 self.require_mutation()?;
4117 let runtime = self
4118 .runtime
4119 .try_borrow()
4120 .map_err(|_| UiContextError::Borrowed)?;
4121 self.require_async_owner(runtime.assets.image_decode_scope(handle)?.as_ref())?;
4122 Ok(runtime.assets.cancel_image_decode(handle)?)
4123 }
4124
4125 pub fn cancel_task(&self, handle: TaskHandle) -> Result<bool, UiContextError> {
4131 self.require_mutation()?;
4132 let mut runtime = self
4133 .runtime
4134 .try_borrow_mut()
4135 .map_err(|_| UiContextError::Borrowed)?;
4136 self.require_async_owner(runtime.tasks.scope(handle))?;
4137 Ok(runtime.tasks.cancel(handle))
4138 }
4139
4140 pub fn cancel_subscription(&self, handle: SubscriptionHandle) -> Result<bool, UiContextError> {
4146 self.require_mutation()?;
4147 let mut runtime = self
4148 .runtime
4149 .try_borrow_mut()
4150 .map_err(|_| UiContextError::Borrowed)?;
4151 self.require_async_owner(runtime.subscriptions.scope(handle))?;
4152 Ok(runtime.subscriptions.cancel(handle))
4153 }
4154
4155 pub fn pause_timeout(&self, key: &str) -> Result<bool, UiContextError> {
4161 self.require_mutation()?;
4162 let id = crate::TimerId::new(self.component.clone(), key)?;
4163 let mut runtime = self
4164 .runtime
4165 .try_borrow_mut()
4166 .map_err(|_| UiContextError::Borrowed)?;
4167 let now = runtime.clock.now();
4168 Ok(runtime.timers.pause(&id, now))
4169 }
4170
4171 pub fn resume_timeout(&self, key: &str) -> Result<bool, UiContextError> {
4177 self.require_mutation()?;
4178 let id = crate::TimerId::new(self.component.clone(), key)?;
4179 let mut runtime = self
4180 .runtime
4181 .try_borrow_mut()
4182 .map_err(|_| UiContextError::Borrowed)?;
4183 let now = runtime.clock.now();
4184 Ok(runtime.timers.resume(&id, now))
4185 }
4186
4187 pub fn cancel_timeout(&self, key: &str) -> Result<bool, UiContextError> {
4193 self.require_mutation()?;
4194 let id = crate::TimerId::new(self.component.clone(), key)?;
4195 Ok(self
4196 .runtime
4197 .try_borrow_mut()
4198 .map_err(|_| UiContextError::Borrowed)?
4199 .timers
4200 .cancel(&id))
4201 }
4202
4203 pub fn start_task(
4209 &self,
4210 capability: &str,
4211 method: &str,
4212 input: Dynamic,
4213 success: FnPtr,
4214 error: FnPtr,
4215 ) -> Result<TaskHandle, UiContextError> {
4216 self.require_mutation()?;
4217 self.require_async_start()?;
4218 self.require_generation()?;
4219 let id = CapabilityId::parse(capability)?;
4220 let input = UiValue::from_dynamic(input)?;
4221 let success = self.scoped_callback(success)?;
4222 let error = self.scoped_callback(error)?;
4223 let mut runtime = self
4224 .runtime
4225 .try_borrow_mut()
4226 .map_err(|_| UiContextError::Borrowed)?;
4227 crate::RuntimeBudgets::check(
4228 "background_tasks",
4229 runtime.tasks.active_count().saturating_add(1),
4230 runtime.budgets.background_tasks,
4231 )?;
4232 let context = self.invocation_context(&runtime);
4233 let (work, output) = runtime
4234 .capabilities
4235 .start_task_with(&context, &id, method, input)?;
4236 let handle = runtime.tasks.spawn_cancellable(
4237 self.async_scope
4238 .clone()
4239 .unwrap_or_else(|| AsyncScope::Component(self.component.clone())),
4240 self.generation,
4241 success,
4242 error,
4243 output,
4244 move |cancellation| work.run(cancellation),
4245 )?;
4246 runtime.traces.push(
4247 crate::RuntimeTraceKind::Task,
4248 self.component.to_string(),
4249 format!("start {capability}.{method}"),
4250 None,
4251 true,
4252 );
4253 Ok(handle)
4254 }
4255
4256 pub fn start_subscription(
4262 &self,
4263 capability: &str,
4264 method: &str,
4265 input: Dynamic,
4266 success: FnPtr,
4267 error: FnPtr,
4268 options: SubscriptionOptions,
4269 ) -> Result<SubscriptionHandle, UiContextError> {
4270 self.require_mutation()?;
4271 self.require_async_start()?;
4272 self.require_generation()?;
4273 if !matches!(self.async_scope, Some(AsyncScope::Effect { .. })) {
4274 return Err(UiContextError::SubscriptionRequiresEffect);
4275 }
4276 let id = CapabilityId::parse(capability)?;
4277 let input = UiValue::from_dynamic(input)?;
4278 let success = self.scoped_callback(success)?;
4279 let error = self.scoped_callback(error)?;
4280 let mut runtime = self
4281 .runtime
4282 .try_borrow_mut()
4283 .map_err(|_| UiContextError::Borrowed)?;
4284 crate::RuntimeBudgets::check(
4285 "subscriptions",
4286 runtime.subscriptions.active_count().saturating_add(1),
4287 runtime.budgets.subscriptions,
4288 )?;
4289 let context = self.invocation_context(&runtime);
4290 let (work, output) = runtime
4291 .capabilities
4292 .start_subscription_with(&context, &id, method, input)?;
4293 let registration = SubscriptionRegistration::new(
4294 format!("{capability}.{method}"),
4295 self.async_scope
4296 .clone()
4297 .unwrap_or_else(|| AsyncScope::Component(self.component.clone())),
4298 self.generation,
4299 success,
4300 error,
4301 output,
4302 )
4303 .with_options(options);
4304 let (handle, emitter) = runtime.subscriptions.subscribe(registration);
4305 let closer = emitter.clone();
4306 if let Err(spawn_error) = std::thread::Builder::new()
4307 .name("gpui-rhai-subscription".to_owned())
4308 .spawn(move || run_subscription_work(work, emitter, &closer))
4309 {
4310 let _ = runtime
4311 .subscriptions
4312 .cancel_with_reason(handle, SubscriptionCloseReason::StartupFailed);
4313 return Err(AsyncRuntimeError::Spawn(spawn_error).into());
4314 }
4315 runtime.traces.push(
4316 crate::RuntimeTraceKind::Subscription,
4317 self.component.to_string(),
4318 format!("start {capability}.{method}"),
4319 None,
4320 true,
4321 );
4322 Ok(handle)
4323 }
4324
4325 fn require_mutation(&self) -> Result<(), UiContextError> {
4326 if self.phase.allows_mutation() {
4327 Ok(())
4328 } else {
4329 Err(UiContextError::MutationDuringRender)
4330 }
4331 }
4332
4333 fn require_async_start(&self) -> Result<(), UiContextError> {
4334 if self.phase.allows_async_start() {
4335 Ok(())
4336 } else {
4337 Err(UiContextError::AsyncDuringSuspend)
4338 }
4339 }
4340
4341 fn require_async_owner(&self, scope: Option<&AsyncScope>) -> Result<(), UiContextError> {
4344 let Some(owner) = scope.and_then(AsyncScope::component) else {
4345 return Ok(());
4346 };
4347 if owner == &self.component
4348 || self.async_scope.as_ref().and_then(AsyncScope::component) == Some(owner)
4349 {
4350 Ok(())
4351 } else {
4352 Err(UiContextError::ForeignAsyncHandle {
4353 owner: owner.clone(),
4354 })
4355 }
4356 }
4357
4358 fn require_generation(&self) -> Result<(), UiContextError> {
4359 if self.generation == ScriptGeneration::default() {
4360 Err(UiContextError::MissingGeneration)
4361 } else {
4362 Ok(())
4363 }
4364 }
4365}
4366
4367fn run_subscription_work(
4368 work: crate::SubscriptionWork,
4369 emitter: crate::SubscriptionEmitter,
4370 closer: &crate::SubscriptionEmitter,
4371) {
4372 work.run(emitter);
4373 closer.close_with_reason(SubscriptionCloseReason::WorkReturned);
4374}
4375
4376impl CustomType for UiContext {
4377 fn build(mut builder: TypeBuilder<Self>) {
4378 builder
4379 .with_name("UiContext")
4380 .with_fn(
4381 "node_factory",
4382 |call: NativeCallContext<'_>, context: &mut Self, renderer: FnPtr| {
4383 if context.phase != ExecutionPhase::Render {
4384 return Err(Box::new(EvalAltResult::ErrorRuntime(
4385 "node_factory is only available during component rendering".into(),
4386 Position::NONE,
4387 )));
4388 }
4389 context
4390 .scoped_callback(renderer.clone())
4391 .map_err(|error| Box::new(context_runtime_error(&error)))?;
4392 Ok(ScriptCallback::bind_node_factory(renderer, context, &call))
4393 },
4394 )
4395 .with_fn(
4396 "emit",
4397 |context: &mut Self, event: ImmutableString, payload: Dynamic| {
4398 context
4399 .emit(event.as_str(), payload)
4400 .map_err(|error| Box::new(context_runtime_error(&error)))
4401 },
4402 )
4403 .with_fn(
4404 "component_style",
4405 |context: &mut Self, part: ImmutableString, base: crate::Style| {
4406 context.resolve_component_style(part.as_str(), base)
4407 },
4408 )
4409 .with_fn(
4410 "call_capability",
4411 |context: &mut Self,
4412 capability: ImmutableString,
4413 method: ImmutableString,
4414 input: Dynamic| {
4415 context
4416 .call_capability(capability.as_str(), method.as_str(), input)
4417 .map(UiValue::into_dynamic)
4418 .map_err(|error| Box::new(context_runtime_error(&error)))
4419 },
4420 );
4421 register_state_store_context_methods(&mut builder);
4422 register_native_collection_context_methods(&mut builder);
4423 register_native_document_context_methods(&mut builder);
4424 #[cfg(feature = "charts")]
4425 register_native_chart_data_context_methods(&mut builder);
4426 register_signal_context_methods(&mut builder);
4427 register_element_ref_context_methods(&mut builder);
4428 register_async_context_methods(&mut builder);
4429 register_action_context_methods(&mut builder);
4430 register_locale_context_methods(&mut builder);
4431 register_theme_context_methods(&mut builder);
4432 register_motion_context_methods(&mut builder);
4433 register_asset_context_methods(&mut builder);
4434 register_window_context_methods(&mut builder);
4435 }
4436}
4437
4438fn register_native_collection_context_methods(builder: &mut TypeBuilder<UiContext>) {
4439 builder.with_fn(
4440 "get_native_collection",
4441 |context: &mut UiContext, name: ImmutableString| {
4442 context
4443 .get_native_collection(name.as_str())
4444 .map_err(|error| Box::new(context_runtime_error(&error)))
4445 },
4446 );
4447}
4448
4449fn register_native_document_context_methods(builder: &mut TypeBuilder<UiContext>) {
4450 builder.with_fn(
4451 "get_native_text_document",
4452 |context: &mut UiContext, name: ImmutableString| {
4453 context
4454 .get_native_text_document(name.as_str())
4455 .map_err(|error| Box::new(context_runtime_error(&error)))
4456 },
4457 );
4458}
4459
4460#[cfg(feature = "charts")]
4461fn register_native_chart_data_context_methods(builder: &mut TypeBuilder<UiContext>) {
4462 builder.with_fn(
4463 "get_native_chart_data",
4464 |context: &mut UiContext, name: ImmutableString| {
4465 context
4466 .get_native_chart_data(name.as_str())
4467 .map_err(|error| Box::new(context_runtime_error(&error)))
4468 },
4469 );
4470}
4471
4472fn register_state_store_context_methods(builder: &mut TypeBuilder<UiContext>) {
4473 register_state_context_methods(builder);
4474 register_app_store_context_methods(builder);
4475 register_window_store_context_methods(builder);
4476}
4477
4478fn register_state_context_methods(builder: &mut TypeBuilder<UiContext>) {
4479 builder
4480 .with_fn(
4481 "get_state",
4482 |context: &mut UiContext, field: ImmutableString| {
4483 context
4484 .get_state(field.as_str())
4485 .map(UiValue::into_dynamic)
4486 .map_err(|error| Box::new(context_runtime_error(&error)))
4487 },
4488 )
4489 .with_fn(
4490 "get_state_path",
4491 |context: &mut UiContext, field: ImmutableString, path: Array| {
4492 let path = rhai_value_path(path)?;
4493 context
4494 .get_state_path(field.as_str(), &path)
4495 .map(UiValue::into_dynamic)
4496 .map_err(|error| Box::new(context_runtime_error(&error)))
4497 },
4498 )
4499 .with_fn(
4500 "set_state",
4501 |context: &mut UiContext, field: ImmutableString, value: Dynamic| {
4502 context
4503 .set_state(field.as_str(), value)
4504 .map_err(|error| Box::new(context_runtime_error(&error)))
4505 },
4506 )
4507 .with_fn(
4508 "set_state_path",
4509 |context: &mut UiContext, field: ImmutableString, path: Array, value: Dynamic| {
4510 let path = rhai_value_path(path)?;
4511 context
4512 .set_state_path(field.as_str(), &path, value)
4513 .map_err(|error| Box::new(context_runtime_error(&error)))
4514 },
4515 );
4516}
4517
4518fn register_app_store_context_methods(builder: &mut TypeBuilder<UiContext>) {
4519 builder
4520 .with_fn(
4521 "get_app_store",
4522 |context: &mut UiContext, store: ImmutableString, field: ImmutableString| {
4523 context
4524 .get_app_store(store.as_str(), field.as_str())
4525 .map(UiValue::into_dynamic)
4526 .map_err(|error| Box::new(context_runtime_error(&error)))
4527 },
4528 )
4529 .with_fn(
4530 "get_app_store_path",
4531 |context: &mut UiContext,
4532 store: ImmutableString,
4533 field: ImmutableString,
4534 path: Array| {
4535 let path = rhai_value_path(path)?;
4536 context
4537 .get_app_store_path(store.as_str(), field.as_str(), &path)
4538 .map(UiValue::into_dynamic)
4539 .map_err(|error| Box::new(context_runtime_error(&error)))
4540 },
4541 )
4542 .with_fn(
4543 "set_app_store",
4544 |context: &mut UiContext,
4545 store: ImmutableString,
4546 field: ImmutableString,
4547 value: Dynamic| {
4548 context
4549 .set_app_store(store.as_str(), field.as_str(), value)
4550 .map_err(|error| Box::new(context_runtime_error(&error)))
4551 },
4552 )
4553 .with_fn(
4554 "set_app_store_path",
4555 |context: &mut UiContext,
4556 store: ImmutableString,
4557 field: ImmutableString,
4558 path: Array,
4559 value: Dynamic| {
4560 let path = rhai_value_path(path)?;
4561 context
4562 .set_app_store_path(store.as_str(), field.as_str(), &path, value)
4563 .map_err(|error| Box::new(context_runtime_error(&error)))
4564 },
4565 );
4566}
4567
4568fn register_window_store_context_methods(builder: &mut TypeBuilder<UiContext>) {
4569 builder
4570 .with_fn(
4571 "get_window_store",
4572 |context: &mut UiContext, store: ImmutableString, field: ImmutableString| {
4573 context
4574 .get_window_store(store.as_str(), field.as_str())
4575 .map(UiValue::into_dynamic)
4576 .map_err(|error| Box::new(context_runtime_error(&error)))
4577 },
4578 )
4579 .with_fn(
4580 "get_window_store_path",
4581 |context: &mut UiContext,
4582 store: ImmutableString,
4583 field: ImmutableString,
4584 path: Array| {
4585 let path = rhai_value_path(path)?;
4586 context
4587 .get_window_store_path(store.as_str(), field.as_str(), &path)
4588 .map(UiValue::into_dynamic)
4589 .map_err(|error| Box::new(context_runtime_error(&error)))
4590 },
4591 )
4592 .with_fn(
4593 "set_window_store",
4594 |context: &mut UiContext,
4595 store: ImmutableString,
4596 field: ImmutableString,
4597 value: Dynamic| {
4598 context
4599 .set_window_store(store.as_str(), field.as_str(), value)
4600 .map_err(|error| Box::new(context_runtime_error(&error)))
4601 },
4602 )
4603 .with_fn(
4604 "set_window_store_path",
4605 |context: &mut UiContext,
4606 store: ImmutableString,
4607 field: ImmutableString,
4608 path: Array,
4609 value: Dynamic| {
4610 let path = rhai_value_path(path)?;
4611 context
4612 .set_window_store_path(store.as_str(), field.as_str(), &path, value)
4613 .map_err(|error| Box::new(context_runtime_error(&error)))
4614 },
4615 );
4616}
4617
4618fn rhai_value_path(values: Array) -> Result<UiValuePath, Box<EvalAltResult>> {
4619 if values.len() > 64 {
4620 return Err(Box::new(EvalAltResult::ErrorRuntime(
4621 "value path must have at most 64 segments".into(),
4622 Position::NONE,
4623 )));
4624 }
4625 let segments = values
4626 .into_iter()
4627 .enumerate()
4628 .map(|(index, value)| {
4629 let actual = value.type_name().to_owned();
4630 if value.is::<ImmutableString>() {
4631 return Ok(UiValuePathSegment::Key(
4632 value.cast::<ImmutableString>().to_string(),
4633 ));
4634 }
4635 if value.is::<INT>() {
4636 let index_value = value.cast::<INT>();
4637 return usize::try_from(index_value)
4638 .map(UiValuePathSegment::Index)
4639 .map_err(|_| {
4640 Box::new(EvalAltResult::ErrorRuntime(
4641 format!("value path segment {index} must be a non-negative integer")
4642 .into(),
4643 Position::NONE,
4644 ))
4645 });
4646 }
4647 if let Some(mut selector) = value.try_cast::<Map>() {
4648 let by = selector
4649 .remove("by")
4650 .and_then(Dynamic::try_cast::<ImmutableString>);
4651 let key = selector
4652 .remove("key")
4653 .and_then(Dynamic::try_cast::<ImmutableString>);
4654 if selector.is_empty()
4655 && let (Some(by), Some(key)) = (by, key)
4656 {
4657 return Ok(UiValuePathSegment::Item {
4658 key_field: by.to_string(),
4659 key: key.to_string(),
4660 });
4661 }
4662 return Err(Box::new(EvalAltResult::ErrorRuntime(
4663 format!(
4664 "value path segment {index} keyed selector must be exactly #{{ by: string, key: string }}"
4665 )
4666 .into(),
4667 Position::NONE,
4668 )));
4669 }
4670 Err(Box::new(EvalAltResult::ErrorRuntime(
4671 format!(
4672 "value path segment {index} must be a string, non-negative integer, or keyed selector map; got {actual}"
4673 )
4674 .into(),
4675 Position::NONE,
4676 )))
4677 })
4678 .collect::<Result<Vec<_>, _>>()?;
4679 UiValuePath::new(segments).map_err(|error| {
4680 Box::new(EvalAltResult::ErrorRuntime(
4681 error.to_string().into(),
4682 Position::NONE,
4683 ))
4684 })
4685}
4686
4687fn register_signal_context_methods(builder: &mut TypeBuilder<UiContext>) {
4688 builder
4689 .with_fn(
4690 "get_signal",
4691 |context: &mut UiContext, signal: crate::NativeSignal| {
4692 context
4693 .get_signal(&signal)
4694 .map_err(|error| Box::new(context_runtime_error(&error)))
4695 },
4696 )
4697 .with_fn(
4698 "get_signal",
4699 |context: &mut UiContext, key: ImmutableString| {
4700 context
4701 .get_signal_by_key(key.as_str())
4702 .map_err(|error| Box::new(context_runtime_error(&error)))
4703 },
4704 )
4705 .with_fn(
4706 "set_signal",
4707 |context: &mut UiContext, signal: crate::NativeSignal, value: Dynamic| {
4708 context
4709 .set_signal(&signal, value)
4710 .map_err(|error| Box::new(context_runtime_error(&error)))
4711 },
4712 )
4713 .with_fn(
4714 "set_signal",
4715 |context: &mut UiContext, key: ImmutableString, value: Dynamic| {
4716 context
4717 .set_signal_by_key(key.as_str(), value)
4718 .map_err(|error| Box::new(context_runtime_error(&error)))
4719 },
4720 );
4721}
4722
4723fn register_element_ref_context_methods(builder: &mut TypeBuilder<UiContext>) {
4724 builder
4725 .with_fn(
4726 "element_size",
4727 |context: &mut UiContext, reference: crate::ElementRef| {
4728 context
4729 .element_size(&reference)
4730 .map(UiValue::into_dynamic)
4731 .map_err(|error| Box::new(context_runtime_error(&error)))
4732 },
4733 )
4734 .with_fn(
4735 "element_size",
4736 |context: &mut UiContext, key: ImmutableString| {
4737 context
4738 .element_size_by_key(key.as_str())
4739 .map(UiValue::into_dynamic)
4740 .map_err(|error| Box::new(context_runtime_error(&error)))
4741 },
4742 )
4743 .with_fn(
4744 "element_bounds",
4745 |context: &mut UiContext, reference: crate::ElementRef| {
4746 context
4747 .element_bounds(&reference)
4748 .map(UiValue::into_dynamic)
4749 .map_err(|error| Box::new(context_runtime_error(&error)))
4750 },
4751 )
4752 .with_fn(
4753 "element_bounds",
4754 |context: &mut UiContext, key: ImmutableString| {
4755 context
4756 .element_bounds_by_key(key.as_str())
4757 .map(UiValue::into_dynamic)
4758 .map_err(|error| Box::new(context_runtime_error(&error)))
4759 },
4760 )
4761 .with_fn("event_target_bounds", |context: &mut UiContext| {
4762 context
4763 .event_target_bounds()
4764 .map(UiValue::into_dynamic)
4765 .map_err(|error| Box::new(context_runtime_error(&error)))
4766 })
4767 .with_fn(
4768 "virtual_item_bounds",
4769 |context: &mut UiContext, collection: ImmutableString, index: rhai::INT| {
4770 let index = usize::try_from(index).map_err(|_| {
4771 Box::new(EvalAltResult::ErrorRuntime(
4772 "virtual item index must be non-negative".into(),
4773 Position::NONE,
4774 ))
4775 })?;
4776 context
4777 .virtual_item_bounds(collection.as_str(), index)
4778 .map(UiValue::into_dynamic)
4779 .map_err(|error| Box::new(context_runtime_error(&error)))
4780 },
4781 )
4782 .with_fn(
4783 "focus",
4784 |context: &mut UiContext, reference: crate::ElementRef| {
4785 context
4786 .focus_element(&reference)
4787 .map_err(|error| Box::new(context_runtime_error(&error)))
4788 },
4789 )
4790 .with_fn("focus", |context: &mut UiContext, key: ImmutableString| {
4791 context
4792 .focus_element_by_key(key.as_str())
4793 .map_err(|error| Box::new(context_runtime_error(&error)))
4794 });
4795}
4796
4797fn geometry_bounds_value(bounds: crate::GeometryBounds) -> UiValue {
4798 bounds.into_value()
4799}
4800
4801#[allow(clippy::too_many_lines)]
4802fn register_action_context_methods(builder: &mut TypeBuilder<UiContext>) {
4803 builder
4804 .with_fn(
4805 "scroll_collection_by",
4806 |context: &mut UiContext, key: ImmutableString, distance: Dynamic| {
4807 context
4808 .scroll_collection_by(key.as_str(), scroll_number(&distance)?)
4809 .map_err(|error| Box::new(context_runtime_error(&error)))
4810 },
4811 )
4812 .with_fn(
4813 "scroll_collection_to_end",
4814 |context: &mut UiContext, key: ImmutableString| {
4815 context
4816 .scroll_collection_to_end(key.as_str())
4817 .map_err(|error| Box::new(context_runtime_error(&error)))
4818 },
4819 )
4820 .with_fn(
4821 "scroll_collection_to_start",
4822 |context: &mut UiContext, key: ImmutableString| {
4823 context
4824 .scroll_collection_to_start(key.as_str())
4825 .map_err(|error| Box::new(context_runtime_error(&error)))
4826 },
4827 )
4828 .with_fn(
4829 "scroll_collection_to_key",
4830 |context: &mut UiContext, key: ImmutableString, item: ImmutableString| {
4831 context
4832 .scroll_collection_to_key(key.as_str(), item.as_str())
4833 .map_err(|error| Box::new(context_runtime_error(&error)))
4834 },
4835 )
4836 .with_fn(
4837 "collection_follow_status",
4838 |context: &mut UiContext, key: ImmutableString| {
4839 context
4840 .collection_follow_status(key.as_str())
4841 .map(|status| {
4842 status.map_or(Dynamic::UNIT, |status| status.to_ui_value().into_dynamic())
4843 })
4844 .map_err(|error| Box::new(context_runtime_error(&error)))
4845 },
4846 )
4847 .with_fn(
4848 "dispatch_action",
4849 |context: &mut UiContext, action: ImmutableString, payload: Dynamic| {
4850 context
4851 .dispatch_action(action.as_str(), payload)
4852 .map_err(|error| Box::new(context_runtime_error(&error)))
4853 },
4854 )
4855 .with_fn(
4856 "register_action",
4857 |call: NativeCallContext<'_>,
4858 context: &mut UiContext,
4859 action: ImmutableString,
4860 callback: FnPtr| {
4861 context_at_call(context, &call)
4862 .register_action(action.as_str(), callback)
4863 .map_err(|error| Box::new(context_runtime_error(&error)))
4864 },
4865 )
4866 .with_fn(
4867 "set_action_enabled",
4868 |context: &mut UiContext, action: ImmutableString, enabled: bool| {
4869 context
4870 .set_action_enabled(action.as_str(), enabled)
4871 .map_err(|error| Box::new(context_runtime_error(&error)))
4872 },
4873 )
4874 .with_fn(
4875 "action_shortcut",
4876 |context: &mut UiContext, action: ImmutableString| {
4877 context
4878 .action_shortcut(action.as_str())
4879 .map(|shortcut| {
4880 shortcut.map_or(Dynamic::UNIT, |shortcut| {
4881 shortcut.to_ui_value().into_dynamic()
4882 })
4883 })
4884 .map_err(|error| Box::new(context_runtime_error(&error)))
4885 },
4886 )
4887 .with_fn(
4888 "action_enabled",
4889 |context: &mut UiContext, action: ImmutableString| {
4890 context
4891 .action_enabled(action.as_str())
4892 .map_err(|error| Box::new(context_runtime_error(&error)))
4893 },
4894 )
4895 .with_fn("actions", |context: &mut UiContext| {
4896 context
4897 .actions()
4898 .map(|actions| {
4899 actions
4900 .into_iter()
4901 .map(UiValue::into_dynamic)
4902 .collect::<rhai::Array>()
4903 })
4904 .map_err(|error| Box::new(context_runtime_error(&error)))
4905 })
4906 .with_fn(
4907 "scroll_to",
4908 |context: &mut UiContext, reference: crate::ElementRef, x: FLOAT, y: FLOAT| {
4909 context
4910 .scroll_element_to(&reference, x, y)
4911 .map_err(|error| Box::new(context_runtime_error(&error)))
4912 },
4913 )
4914 .with_fn(
4915 "scroll_to",
4916 |context: &mut UiContext, key: ImmutableString, x: FLOAT, y: FLOAT| {
4917 context
4918 .scroll_element_to_by_key(key.as_str(), x, y)
4919 .map_err(|error| Box::new(context_runtime_error(&error)))
4920 },
4921 )
4922 .with_fn(
4924 "scroll_to",
4925 |context: &mut UiContext,
4926 reference: crate::ElementRef,
4927 x: Dynamic,
4928 y: Dynamic|
4929 -> Result<(), Box<EvalAltResult>> {
4930 context
4931 .scroll_element_to(&reference, scroll_number(&x)?, scroll_number(&y)?)
4932 .map_err(|error| Box::new(context_runtime_error(&error)))
4933 },
4934 )
4935 .with_fn(
4936 "scroll_to",
4937 |context: &mut UiContext,
4938 key: ImmutableString,
4939 x: Dynamic,
4940 y: Dynamic|
4941 -> Result<(), Box<EvalAltResult>> {
4942 context
4943 .scroll_element_to_by_key(key.as_str(), scroll_number(&x)?, scroll_number(&y)?)
4944 .map_err(|error| Box::new(context_runtime_error(&error)))
4945 },
4946 )
4947 .with_fn(
4948 "scroll_into_view",
4949 |context: &mut UiContext, reference: crate::ElementRef| {
4950 context
4951 .scroll_element_into_view(&reference)
4952 .map_err(|error| Box::new(context_runtime_error(&error)))
4953 },
4954 )
4955 .with_fn(
4956 "scroll_into_view",
4957 |context: &mut UiContext, key: ImmutableString| {
4958 context
4959 .scroll_element_into_view_by_key(key.as_str())
4960 .map_err(|error| Box::new(context_runtime_error(&error)))
4961 },
4962 )
4963 .with_fn(
4964 "copy_text",
4965 |context: &mut UiContext, text: ImmutableString| {
4966 context
4967 .copy_text(text.to_string())
4968 .map_err(|error| Box::new(context_runtime_error(&error)))
4969 },
4970 );
4971}
4972
4973fn register_async_context_methods(builder: &mut TypeBuilder<UiContext>) {
4974 builder
4975 .with_fn(
4976 "start_task",
4977 |call: NativeCallContext<'_>,
4978 context: &mut UiContext,
4979 capability: ImmutableString,
4980 method: ImmutableString,
4981 input: Dynamic,
4982 success: FnPtr,
4983 error: FnPtr| {
4984 context_at_call(context, &call)
4985 .start_task(capability.as_str(), method.as_str(), input, success, error)
4986 .map_err(|error| Box::new(context_runtime_error(&error)))
4987 },
4988 )
4989 .with_fn(
4990 "start_subscription",
4991 |call: NativeCallContext<'_>,
4992 context: &mut UiContext,
4993 capability: ImmutableString,
4994 method: ImmutableString,
4995 input: Dynamic,
4996 success: FnPtr,
4997 error: FnPtr,
4998 options: Map| {
4999 let options = subscription_options(options)?;
5000 context_at_call(context, &call)
5001 .start_subscription(
5002 capability.as_str(),
5003 method.as_str(),
5004 input,
5005 success,
5006 error,
5007 options,
5008 )
5009 .map_err(|error| Box::new(context_runtime_error(&error)))
5010 },
5011 )
5012 .with_fn(
5013 "cancel_task",
5014 |context: &mut UiContext, handle: TaskHandle| {
5015 context
5016 .cancel_task(handle)
5017 .map_err(|error| Box::new(context_runtime_error(&error)))
5018 },
5019 )
5020 .with_fn(
5021 "cancel_subscription",
5022 |context: &mut UiContext, handle: SubscriptionHandle| {
5023 context
5024 .cancel_subscription(handle)
5025 .map_err(|error| Box::new(context_runtime_error(&error)))
5026 },
5027 )
5028 .with_fn(
5029 "pause_timeout",
5030 |context: &mut UiContext, key: ImmutableString| {
5031 context
5032 .pause_timeout(key.as_str())
5033 .map_err(|error| Box::new(context_runtime_error(&error)))
5034 },
5035 )
5036 .with_fn(
5037 "resume_timeout",
5038 |context: &mut UiContext, key: ImmutableString| {
5039 context
5040 .resume_timeout(key.as_str())
5041 .map_err(|error| Box::new(context_runtime_error(&error)))
5042 },
5043 )
5044 .with_fn(
5045 "cancel_timeout",
5046 |context: &mut UiContext, key: ImmutableString| {
5047 context
5048 .cancel_timeout(key.as_str())
5049 .map_err(|error| Box::new(context_runtime_error(&error)))
5050 },
5051 );
5052}
5053
5054fn subscription_options(mut options: Map) -> Result<SubscriptionOptions, Box<EvalAltResult>> {
5055 let defaults = SubscriptionOptions::default();
5056 let delivery = options.remove("delivery").map_or(
5057 Ok(defaults.delivery()),
5058 |value| -> Result<_, Box<EvalAltResult>> {
5059 let value = value.try_cast::<ImmutableString>().ok_or_else(|| {
5060 Box::new(EvalAltResult::ErrorRuntime(
5061 "subscription delivery must be `all` or `latest`".into(),
5062 Position::NONE,
5063 ))
5064 })?;
5065 match value.as_str() {
5066 "all" => Ok(SubscriptionDeliveryPolicy::All),
5067 "latest" => Ok(SubscriptionDeliveryPolicy::Latest),
5068 _ => Err(Box::new(EvalAltResult::ErrorRuntime(
5069 "subscription delivery must be `all` or `latest`".into(),
5070 Position::NONE,
5071 ))),
5072 }
5073 },
5074 )?;
5075 let capacity = options.remove("capacity").map_or(
5076 Ok(defaults.capacity()),
5077 |value| -> Result<_, Box<EvalAltResult>> {
5078 value
5079 .try_cast::<INT>()
5080 .and_then(|value| usize::try_from(value).ok())
5081 .ok_or_else(|| {
5082 Box::new(EvalAltResult::ErrorRuntime(
5083 "subscription capacity must be a positive integer".into(),
5084 Position::NONE,
5085 ))
5086 })
5087 },
5088 )?;
5089 let throttle = options.remove("throttle_ms").map_or(
5090 Ok(defaults.throttle()),
5091 |value| -> Result<_, Box<EvalAltResult>> {
5092 value
5093 .try_cast::<INT>()
5094 .and_then(|value| u64::try_from(value).ok())
5095 .map(Duration::from_millis)
5096 .ok_or_else(|| {
5097 Box::new(EvalAltResult::ErrorRuntime(
5098 "subscription throttle_ms must be a non-negative integer".into(),
5099 Position::NONE,
5100 ))
5101 })
5102 },
5103 )?;
5104 if let Some(name) = options.keys().next() {
5105 return Err(Box::new(EvalAltResult::ErrorRuntime(
5106 format!("unknown subscription option `{name}`").into(),
5107 Position::NONE,
5108 )));
5109 }
5110 SubscriptionOptions::new(delivery, capacity, throttle).map_err(|error| {
5111 Box::new(EvalAltResult::ErrorRuntime(
5112 error.to_string().into(),
5113 Position::NONE,
5114 ))
5115 })
5116}
5117
5118fn register_time_context_methods(builder: &mut TypeBuilder<UiContext>) {
5119 builder
5120 .with_fn("is_visible", |context: &mut UiContext| {
5121 context
5122 .is_visible()
5123 .map_err(|error| Box::new(context_runtime_error(&error)))
5124 })
5125 .with_fn("now", |context: &mut UiContext| {
5126 context
5127 .now()
5128 .map_err(|e| Box::new(context_runtime_error(&e)))
5129 })
5130 .with_fn("time", |context: &mut UiContext| {
5131 context
5132 .time_metadata()
5133 .map_err(|e| Box::new(context_runtime_error(&e)))
5134 })
5135 .with_fn(
5136 "parse_time",
5137 |context: &mut UiContext, value: ImmutableString, precision: ImmutableString| {
5138 context
5139 .parse_time(&value, &precision)
5140 .map_err(|e| Box::new(context_runtime_error(&e)))
5141 },
5142 )
5143 .with_fn(
5144 "format_time",
5145 |context: &mut UiContext, ms: INT, style: ImmutableString, zone: ImmutableString| {
5146 context
5147 .format_time(ms, &style, &zone)
5148 .map_err(|e| Box::new(context_runtime_error(&e)))
5149 },
5150 )
5151 .with_fn("format_duration", |context: &mut UiContext, ms: INT| {
5152 context
5153 .format_duration(ms)
5154 .map_err(|e| Box::new(context_runtime_error(&e)))
5155 })
5156 .with_fn("format_relative", |context: &mut UiContext, ms: INT| {
5157 context
5158 .format_relative(ms)
5159 .map_err(|e| Box::new(context_runtime_error(&e)))
5160 });
5161}
5162
5163fn register_message_context_methods(builder: &mut TypeBuilder<UiContext>) {
5164 builder
5165 .with_fn("t", |context: &mut UiContext, key: ImmutableString| {
5166 context
5167 .text(key.as_str())
5168 .map_err(|error| Box::new(context_runtime_error(&error)))
5169 })
5170 .with_fn(
5171 "t_or",
5172 |context: &mut UiContext, key: ImmutableString, fallback: ImmutableString| {
5173 context
5174 .text_or(key.as_str(), fallback.as_str())
5175 .map_err(|error| Box::new(context_runtime_error(&error)))
5176 },
5177 )
5178 .with_fn(
5179 "t_or",
5180 |context: &mut UiContext,
5181 key: ImmutableString,
5182 fallback: ImmutableString,
5183 values: rhai::Map| {
5184 let mut text = context
5185 .text_or(key.as_str(), fallback.as_str())
5186 .map_err(|error| Box::new(context_runtime_error(&error)))?;
5187 for (name, value) in values {
5188 text = text.replace(&format!("{{{name}}}"), &value.to_string());
5189 }
5190 Ok::<_, Box<EvalAltResult>>(text)
5191 },
5192 );
5193}
5194
5195fn register_locale_context_methods(builder: &mut TypeBuilder<UiContext>) {
5196 register_time_context_methods(builder);
5197 register_message_context_methods(builder);
5198 builder
5199 .with_fn(
5200 "set_locale",
5201 |context: &mut UiContext, locale: ImmutableString| {
5202 context
5203 .set_locale(locale.as_str())
5204 .map_err(|error| Box::new(context_runtime_error(&error)))
5205 },
5206 )
5207 .with_fn("text_direction", |context: &mut UiContext| {
5208 context
5209 .text_direction()
5210 .map_err(|error| Box::new(context_runtime_error(&error)))
5211 })
5212 .with_fn("today", |context: &mut UiContext| {
5213 context
5214 .today()
5215 .map_err(|error| Box::new(context_runtime_error(&error)))
5216 })
5217 .with_fn(
5218 "format_date",
5219 |context: &mut UiContext, date: ImmutableString, style: ImmutableString| {
5220 context
5221 .format_date(date.as_str(), style.as_str())
5222 .map_err(|error| Box::new(context_runtime_error(&error)))
5223 },
5224 )
5225 .with_fn(
5226 "format_month_year",
5227 |context: &mut UiContext, date: ImmutableString| {
5228 context
5229 .format_month_year(date.as_str())
5230 .map_err(|error| Box::new(context_runtime_error(&error)))
5231 },
5232 )
5233 .with_fn("calendar", |context: &mut UiContext| {
5234 context
5235 .calendar_metadata()
5236 .map_err(|error| Box::new(context_runtime_error(&error)))
5237 })
5238 .with_fn("number", |context: &mut UiContext| {
5239 context
5240 .number_metadata()
5241 .map_err(|error| Box::new(context_runtime_error(&error)))
5242 })
5243 .with_fn("format_number", |context: &mut UiContext, value: INT| {
5244 context
5245 .format_integer(value, NumberFormatOptions::default())
5246 .map_err(|error| Box::new(context_runtime_error(&error)))
5247 })
5248 .with_fn("format_number", |context: &mut UiContext, value: FLOAT| {
5249 context
5250 .format_number(value, NumberFormatOptions::default())
5251 .map_err(|error| Box::new(context_runtime_error(&error)))
5252 })
5253 .with_fn(
5254 "format_number",
5255 |context: &mut UiContext,
5256 value: INT,
5257 options: Map|
5258 -> Result<String, Box<EvalAltResult>> {
5259 let options = number_format_options(options)?;
5260 context
5261 .format_integer(value, options)
5262 .map_err(|error| Box::new(context_runtime_error(&error)))
5263 },
5264 )
5265 .with_fn(
5266 "format_number",
5267 |context: &mut UiContext,
5268 value: FLOAT,
5269 options: Map|
5270 -> Result<String, Box<EvalAltResult>> {
5271 let options = number_format_options(options)?;
5272 context
5273 .format_number(value, options)
5274 .map_err(|error| Box::new(context_runtime_error(&error)))
5275 },
5276 );
5277}
5278
5279fn number_format_options(mut options: Map) -> Result<NumberFormatOptions, Box<EvalAltResult>> {
5280 let mut parsed = NumberFormatOptions::default();
5281 if let Some(value) = options.remove("min_fraction_digits") {
5282 let value = value.try_cast::<INT>().ok_or_else(|| {
5283 Box::new(EvalAltResult::ErrorRuntime(
5284 "min_fraction_digits must be an integer".into(),
5285 Position::NONE,
5286 ))
5287 })?;
5288 parsed.min_fraction_digits = u8::try_from(value).map_err(|_| {
5289 Box::new(EvalAltResult::ErrorRuntime(
5290 "min_fraction_digits must be between 0 and 12".into(),
5291 Position::NONE,
5292 ))
5293 })?;
5294 }
5295 if let Some(value) = options.remove("max_fraction_digits") {
5296 let value = value.try_cast::<INT>().ok_or_else(|| {
5297 Box::new(EvalAltResult::ErrorRuntime(
5298 "max_fraction_digits must be an integer".into(),
5299 Position::NONE,
5300 ))
5301 })?;
5302 parsed.max_fraction_digits = u8::try_from(value).map_err(|_| {
5303 Box::new(EvalAltResult::ErrorRuntime(
5304 "max_fraction_digits must be between 0 and 12".into(),
5305 Position::NONE,
5306 ))
5307 })?;
5308 }
5309 if let Some(value) = options.remove("grouping") {
5310 parsed.grouping = value.try_cast::<bool>().ok_or_else(|| {
5311 Box::new(EvalAltResult::ErrorRuntime(
5312 "grouping must be a bool".into(),
5313 Position::NONE,
5314 ))
5315 })?;
5316 }
5317 if let Some((unknown, _)) = options.into_iter().next() {
5318 return Err(Box::new(EvalAltResult::ErrorRuntime(
5319 format!("unknown number format option `{unknown}`").into(),
5320 Position::NONE,
5321 )));
5322 }
5323 parsed.validate().map_err(|error| {
5324 Box::new(EvalAltResult::ErrorRuntime(
5325 error.to_string().into(),
5326 Position::NONE,
5327 ))
5328 })?;
5329 Ok(parsed)
5330}
5331
5332fn theme_variant_map(variant: &crate::ThemeVariantInfo) -> Dynamic {
5333 let mut map = rhai::Map::new();
5334 map.insert("family".into(), Dynamic::from(variant.family.clone()));
5335 map.insert("name".into(), Dynamic::from(variant.name.clone()));
5336 map.insert(
5337 "mode".into(),
5338 Dynamic::from(match variant.mode {
5339 crate::ThemeMode::Light => "light",
5340 crate::ThemeMode::Dark => "dark",
5341 }),
5342 );
5343 Dynamic::from(map)
5344}
5345
5346fn theme_color_map(
5349 context: &UiContext,
5350 family: &str,
5351 name: &str,
5352 keys: Option<rhai::Array>,
5353) -> Result<rhai::Map, Box<EvalAltResult>> {
5354 let error =
5355 |message: String| Box::new(EvalAltResult::ErrorRuntime(message.into(), Position::NONE));
5356 let colors = context
5357 .theme_colors(family, name)
5358 .ok_or_else(|| error(format!("no theme variant {family}/{name}")))?;
5359 let color = |value: crate::Rgba8| Dynamic::from(crate::ColorValue::Literal(value));
5360 match keys {
5361 None => Ok(colors
5362 .into_iter()
5363 .map(|(key, value)| (key.into(), color(value)))
5364 .collect()),
5365 Some(keys) => keys
5366 .into_iter()
5367 .map(|key| {
5368 let key = key
5369 .into_immutable_string()
5370 .map_err(|_| error("theme_colors keys are strings".to_owned()))?;
5371 let value = colors.get(key.as_str()).copied().ok_or_else(|| {
5372 error(format!("theme variant {family}/{name} has no color {key}"))
5373 })?;
5374 Ok((key.as_str().into(), color(value)))
5375 })
5376 .collect(),
5377 }
5378}
5379
5380fn register_theme_context_methods(builder: &mut TypeBuilder<UiContext>) {
5381 builder
5382 .with_fn(
5383 "theme_variant",
5384 |context: &mut UiContext| -> Result<Dynamic, Box<EvalAltResult>> {
5385 Ok(context
5386 .resolved_theme_variant()
5387 .map_or(Dynamic::UNIT, |variant| theme_variant_map(&variant)))
5388 },
5389 )
5390 .with_fn("theme_variants", |context: &mut UiContext| -> rhai::Array {
5391 context
5392 .theme_variants()
5393 .iter()
5394 .map(theme_variant_map)
5395 .collect()
5396 })
5397 .with_fn(
5398 "theme_colors",
5399 |context: &mut UiContext,
5400 family: ImmutableString,
5401 name: ImmutableString|
5402 -> Result<rhai::Map, Box<EvalAltResult>> {
5403 theme_color_map(context, family.as_str(), name.as_str(), None)
5404 },
5405 )
5406 .with_fn(
5407 "theme_colors",
5408 |context: &mut UiContext,
5409 family: ImmutableString,
5410 name: ImmutableString,
5411 keys: rhai::Array|
5412 -> Result<rhai::Map, Box<EvalAltResult>> {
5413 theme_color_map(context, family.as_str(), name.as_str(), Some(keys))
5414 },
5415 )
5416 .with_fn(
5417 "set_theme",
5418 |context: &mut UiContext, family: ImmutableString, variant: ImmutableString| {
5419 context
5420 .set_theme(family.as_str(), variant.as_str())
5421 .map_err(|error| Box::new(context_runtime_error(&error)))
5422 },
5423 )
5424 .with_fn(
5425 "set_window_theme",
5426 |context: &mut UiContext, family: ImmutableString, variant: ImmutableString| {
5427 context
5428 .set_window_theme(family.as_str(), variant.as_str())
5429 .map_err(|error| Box::new(context_runtime_error(&error)))
5430 },
5431 )
5432 .with_fn(
5433 "set_local_theme",
5434 |context: &mut UiContext, family: ImmutableString, variant: ImmutableString| {
5435 context
5436 .set_local_theme(family.as_str(), variant.as_str())
5437 .map_err(|error| Box::new(context_runtime_error(&error)))
5438 },
5439 )
5440 .with_fn(
5441 "set_theme_system",
5442 |context: &mut UiContext, family: ImmutableString| {
5443 context
5444 .set_theme_system(family.as_str())
5445 .map_err(|error| Box::new(context_runtime_error(&error)))
5446 },
5447 )
5448 .with_fn(
5449 "set_window_theme_system",
5450 |context: &mut UiContext, family: ImmutableString| {
5451 context
5452 .set_window_theme_system(family.as_str())
5453 .map_err(|error| Box::new(context_runtime_error(&error)))
5454 },
5455 )
5456 .with_fn(
5457 "set_local_theme_system",
5458 |context: &mut UiContext, family: ImmutableString| {
5459 context
5460 .set_local_theme_system(family.as_str())
5461 .map_err(|error| Box::new(context_runtime_error(&error)))
5462 },
5463 );
5464 register_theme_pair_context_methods(builder);
5465}
5466
5467fn theme_selection_map(map: &rhai::Map, which: &str) -> Result<ThemeSelection, Box<EvalAltResult>> {
5469 let field = |name: &str| {
5470 map.get(name)
5471 .and_then(|value| value.clone().into_immutable_string().ok())
5472 .ok_or_else(|| {
5473 Box::new(EvalAltResult::ErrorRuntime(
5474 format!(
5475 "`{which}` needs string `family` and `name`, as ctx.theme_variant() returns"
5476 )
5477 .into(),
5478 Position::NONE,
5479 ))
5480 })
5481 };
5482 Ok(ThemeSelection::new(
5483 field("family")?.as_str(),
5484 field("name")?.as_str(),
5485 ))
5486}
5487
5488fn register_theme_pair_context_methods(builder: &mut TypeBuilder<UiContext>) {
5489 builder
5490 .with_fn(
5491 "set_theme_system_pair",
5492 |context: &mut UiContext, light: rhai::Map, dark: rhai::Map| {
5493 context
5494 .set_theme_system_pair(
5495 theme_selection_map(&light, "light")?,
5496 theme_selection_map(&dark, "dark")?,
5497 )
5498 .map_err(|error| Box::new(context_runtime_error(&error)))
5499 },
5500 )
5501 .with_fn(
5502 "set_window_theme_system_pair",
5503 |context: &mut UiContext, light: rhai::Map, dark: rhai::Map| {
5504 context
5505 .set_window_theme_system_pair(
5506 theme_selection_map(&light, "light")?,
5507 theme_selection_map(&dark, "dark")?,
5508 )
5509 .map_err(|error| Box::new(context_runtime_error(&error)))
5510 },
5511 )
5512 .with_fn(
5513 "set_local_theme_system_pair",
5514 |context: &mut UiContext, light: rhai::Map, dark: rhai::Map| {
5515 context
5516 .set_local_theme_system_pair(
5517 theme_selection_map(&light, "light")?,
5518 theme_selection_map(&dark, "dark")?,
5519 )
5520 .map_err(|error| Box::new(context_runtime_error(&error)))
5521 },
5522 );
5523}
5524
5525#[allow(clippy::too_many_lines)]
5526fn register_motion_context_methods(builder: &mut TypeBuilder<UiContext>) {
5527 builder
5528 .with_fn(
5529 "set_reduced_motion",
5530 |context: &mut UiContext, reduced: bool| {
5531 context
5532 .set_reduced_motion(reduced)
5533 .map_err(|error| Box::new(context_runtime_error(&error)))
5534 },
5535 )
5536 .with_fn(
5537 "motion_handle",
5538 |context: &mut UiContext, name: ImmutableString| {
5539 context
5540 .motion_handle(name.as_str())
5541 .map_err(|error| Box::new(context_runtime_error(&error)))
5542 },
5543 )
5544 .with_fn(
5545 "motion_duration",
5546 |context: &mut UiContext, role: ImmutableString| {
5547 context
5548 .motion_duration(role.as_str())
5549 .map(|value| INT::try_from(value).unwrap_or(INT::MAX))
5550 .map_err(|error| Box::new(context_runtime_error(&error)))
5551 },
5552 )
5553 .with_fn(
5554 "motion_easing",
5555 |context: &mut UiContext, role: ImmutableString| {
5556 context
5557 .motion_easing(role.as_str())
5558 .map(|value| ImmutableString::from(value.to_string()))
5559 .map_err(|error| Box::new(context_runtime_error(&error)))
5560 },
5561 )
5562 .with_fn(
5563 "motion_spring",
5564 |context: &mut UiContext, role: ImmutableString| {
5565 context
5566 .motion_spring(role.as_str())
5567 .map(|spring| {
5568 Map::from_iter([
5569 ("stiffness".into(), Dynamic::from_float(spring.stiffness)),
5570 ("damping".into(), Dynamic::from_float(spring.damping)),
5571 ("mass".into(), Dynamic::from_float(spring.mass)),
5572 ])
5573 })
5574 .map_err(|error| Box::new(context_runtime_error(&error)))
5575 },
5576 )
5577 .with_fn(
5578 "motion_distance",
5579 |context: &mut UiContext, role: ImmutableString| {
5580 context
5581 .motion_distance(role.as_str())
5582 .map_err(|error| Box::new(context_runtime_error(&error)))
5583 },
5584 )
5585 .with_fn(
5586 "motion_stagger",
5587 |context: &mut UiContext, role: ImmutableString| {
5588 context
5589 .motion_stagger(role.as_str())
5590 .map(|value| INT::try_from(value).unwrap_or(INT::MAX))
5591 .map_err(|error| Box::new(context_runtime_error(&error)))
5592 },
5593 )
5594 .with_fn("motion_quality", |context: &mut UiContext| {
5595 match context.motion_quality() {
5596 crate::MotionQuality::Low => "low",
5597 crate::MotionQuality::Medium => "medium",
5598 crate::MotionQuality::High => "high",
5599 }
5600 })
5601 .with_fn(
5602 "play_motion",
5603 |context: &mut UiContext, handle: crate::MotionHandle| {
5604 context
5605 .play_motion(&handle)
5606 .map_err(|error| Box::new(context_runtime_error(&error)))
5607 },
5608 )
5609 .with_fn(
5610 "resume_motion",
5611 |context: &mut UiContext, handle: crate::MotionHandle| {
5612 context
5613 .play_motion(&handle)
5614 .map_err(|error| Box::new(context_runtime_error(&error)))
5615 },
5616 )
5617 .with_fn(
5618 "pause_motion",
5619 |context: &mut UiContext, handle: crate::MotionHandle| {
5620 context
5621 .pause_motion(&handle)
5622 .map_err(|error| Box::new(context_runtime_error(&error)))
5623 },
5624 )
5625 .with_fn(
5626 "seek_motion",
5627 |context: &mut UiContext, handle: crate::MotionHandle, position_ms: INT| {
5628 let position_ms = u64::try_from(position_ms).map_err(|_| {
5629 Box::new(context_runtime_error(&UiContextError::Motion(
5630 crate::MotionError::InvalidTimeline(
5631 "seek position must be non-negative".to_owned(),
5632 ),
5633 )))
5634 })?;
5635 context
5636 .seek_motion(&handle, position_ms)
5637 .map_err(|error| Box::new(context_runtime_error(&error)))
5638 },
5639 )
5640 .with_fn(
5641 "restart_motion",
5642 |context: &mut UiContext, handle: crate::MotionHandle| {
5643 context
5644 .restart_motion(&handle)
5645 .map_err(|error| Box::new(context_runtime_error(&error)))
5646 },
5647 )
5648 .with_fn(
5649 "cancel_motion",
5650 |context: &mut UiContext, handle: crate::MotionHandle| {
5651 context
5652 .cancel_motion(&handle)
5653 .map_err(|error| Box::new(context_runtime_error(&error)))
5654 },
5655 );
5656}
5657
5658fn register_asset_context_methods(builder: &mut TypeBuilder<UiContext>) {
5659 builder
5660 .with_fn("load_image", |context: &mut UiContext, asset: AssetId| {
5661 context
5662 .load_image(&asset)
5663 .map_err(|error| Box::new(context_runtime_error(&error)))
5664 })
5665 .with_fn(
5666 "start_image_decode",
5667 |call: NativeCallContext<'_>,
5668 context: &mut UiContext,
5669 asset: AssetId,
5670 success: FnPtr,
5671 error: FnPtr| {
5672 context_at_call(context, &call)
5673 .start_image_decode(&asset, success, error)
5674 .map_err(|error| Box::new(context_runtime_error(&error)))
5675 },
5676 )
5677 .with_fn(
5678 "cancel_image_decode",
5679 |context: &mut UiContext, handle: ImageDecodeHandle| {
5680 context
5681 .cancel_image_decode(handle)
5682 .map_err(|error| Box::new(context_runtime_error(&error)))
5683 },
5684 );
5685}
5686
5687fn register_window_context_methods(builder: &mut TypeBuilder<UiContext>) {
5688 builder
5689 .with_fn("window_id", |context: &mut UiContext| {
5690 context
5691 .window_id()
5692 .map_err(|error| Box::new(context_runtime_error(&error)))
5693 })
5694 .with_fn("view_id", |context: &mut UiContext| {
5695 context
5696 .view_id()
5697 .map_err(|error| Box::new(context_runtime_error(&error)))
5698 })
5699 .with_fn("viewport_class", |context: &mut UiContext| {
5700 context
5701 .viewport_class()
5702 .map_err(|error| Box::new(context_runtime_error(&error)))
5703 })
5704 .with_fn(
5705 "open_window",
5706 |context: &mut UiContext,
5707 id: ImmutableString,
5708 title: ImmutableString,
5709 width: rhai::INT,
5710 height: rhai::INT,
5711 focus: bool| {
5712 context
5713 .open_window(ScriptWindowSpec {
5714 id: id.to_string(),
5715 title: title.to_string(),
5716 width: width.to_string().parse::<f64>().unwrap_or(f64::INFINITY),
5717 height: height.to_string().parse::<f64>().unwrap_or(f64::INFINITY),
5718 focus,
5719 })
5720 .map_err(|error| Box::new(context_runtime_error(&error)))
5721 },
5722 )
5723 .with_fn(
5724 "focus_window",
5725 |context: &mut UiContext, id: ImmutableString| {
5726 context
5727 .focus_window(id.as_str())
5728 .map_err(|error| Box::new(context_runtime_error(&error)))
5729 },
5730 )
5731 .with_fn(
5732 "close_window",
5733 |context: &mut UiContext, id: ImmutableString| {
5734 context
5735 .close_window(id.as_str())
5736 .map_err(|error| Box::new(context_runtime_error(&error)))
5737 },
5738 )
5739 .with_fn(
5740 "set_close_handler",
5741 |call: NativeCallContext<'_>, context: &mut UiContext, callback: FnPtr| {
5742 context_at_call(context, &call)
5743 .set_close_handler(callback)
5744 .map_err(|error| Box::new(context_runtime_error(&error)))
5745 },
5746 )
5747 .with_fn("clear_close_handler", |context: &mut UiContext| {
5748 context
5749 .clear_close_handler()
5750 .map_err(|error| Box::new(context_runtime_error(&error)))
5751 })
5752 .with_fn(
5753 "set_window_locale",
5754 |context: &mut UiContext, locale: ImmutableString| {
5755 context
5756 .set_window_locale(locale.as_str())
5757 .map_err(|error| Box::new(context_runtime_error(&error)))
5758 },
5759 )
5760 .with_fn(
5761 "set_local_locale",
5762 |context: &mut UiContext, locale: ImmutableString| {
5763 context
5764 .set_local_locale(locale.as_str())
5765 .map_err(|error| Box::new(context_runtime_error(&error)))
5766 },
5767 );
5768}
5769
5770fn context_at_call(context: &UiContext, call: &NativeCallContext<'_>) -> UiContext {
5771 context.clone().with_native_context(Some(
5772 crate::invocation::ScriptInvocationContext::capture_retained(call),
5773 ))
5774}
5775
5776pub(crate) fn register_ui_context_api(engine: &mut Engine) {
5777 engine.build_type::<UiContext>();
5778}
5779
5780fn scroll_number(value: &Dynamic) -> Result<f64, Box<EvalAltResult>> {
5781 crate::value::script_number(value).ok_or_else(|| {
5782 Box::new(EvalAltResult::ErrorRuntime(
5783 format!("scroll offset must be a number, got {}", value.type_name()).into(),
5784 Position::NONE,
5785 ))
5786 })
5787}
5788
5789fn context_runtime_error(error: &UiContextError) -> EvalAltResult {
5790 EvalAltResult::ErrorRuntime(error.to_string().into(), Position::NONE)
5791}
5792
5793#[derive(Debug, Error)]
5794pub enum UiContextError {
5795 #[error("clipboard writes require direct user input or an explicit automation command")]
5796 ClipboardRequiresUserInput,
5797 #[error("UI runtime state is already mutably borrowed by another callback")]
5798 Borrowed,
5799 #[error("state mutation and effects are forbidden during view rendering")]
5800 MutationDuringRender,
5801 #[error("new async work is forbidden while a view is suspending")]
5802 AsyncDuringSuspend,
5803 #[error("subscriptions must be started by a declarative component effect")]
5804 SubscriptionRequiresEffect,
5805 #[error("event target geometry is available only during event callbacks")]
5806 EventTargetOutsideEvent,
5807 #[error("async work requires a bound script generation")]
5808 MissingGeneration,
5809 #[error("this async handle belongs to component `{owner}`; only that component may cancel it")]
5810 ForeignAsyncHandle { owner: ComponentInstancePath },
5811 #[error("no locale manager is configured for this application")]
5812 LocaleUnavailable,
5813 #[error("no theme manager is configured for this application")]
5814 ThemeUnavailable,
5815 #[cfg(feature = "charts")]
5816 #[error("native chart data name `{0}` must be a safe identifier")]
5817 InvalidChartDataName(String),
5818 #[cfg(feature = "charts")]
5819 #[error("native chart data `{0}` is not registered")]
5820 UnknownChartData(String),
5821 #[error("unknown theme motion {category} token `{role}`")]
5822 UnknownMotionToken {
5823 category: &'static str,
5824 role: String,
5825 },
5826 #[error("component `{component}` has no state field `{field}`")]
5827 UnknownState {
5828 component: ComponentInstancePath,
5829 field: String,
5830 },
5831 #[error("event `{0}` is not declared by this component")]
5832 UnknownEvent(String),
5833 #[error("event payload is invalid: {0}")]
5834 InvalidEvent(crate::SchemaValidationError),
5835 #[error("this UI context is not associated with a window")]
5836 MissingWindow,
5837 #[error("this UI context is not associated with a mounted script view")]
5838 MissingView,
5839 #[error(transparent)]
5840 Window(#[from] WindowCommandError),
5841 #[error(transparent)]
5842 Responsive(#[from] ResponsiveError),
5843 #[error(transparent)]
5844 State(#[from] StateError),
5845 #[error(transparent)]
5846 Store(#[from] StoreError),
5847 #[error(transparent)]
5848 NativeCollection(#[from] crate::NativeCollectionError),
5849 #[error(transparent)]
5850 Document(#[from] crate::DocumentError),
5851 #[error(transparent)]
5852 Action(#[from] ActionError),
5853 #[error(transparent)]
5854 Capability(#[from] CapabilityError),
5855 #[error(transparent)]
5856 Async(#[from] AsyncRuntimeError),
5857 #[error(transparent)]
5858 Locale(#[from] LocaleError),
5859 #[error(transparent)]
5860 Theme(#[from] ThemeError),
5861 #[error(transparent)]
5862 Asset(#[from] AssetError),
5863 #[error(transparent)]
5864 Value(#[from] UiValueError),
5865 #[error(transparent)]
5866 ValuePath(#[from] UiValuePathError),
5867 #[error(transparent)]
5868 Signal(#[from] crate::SignalError),
5869 #[error(transparent)]
5870 ElementRef(#[from] crate::ElementRefError),
5871 #[error(transparent)]
5872 Geometry(#[from] crate::GeometryError),
5873 #[error("scroll offset must be finite and non-negative, got ({x}, {y})")]
5874 InvalidScrollOffset { x: f64, y: f64 },
5875 #[error(transparent)]
5876 Callback(#[from] crate::ScriptCallbackDefinitionError),
5877 #[error(transparent)]
5878 Timer(#[from] crate::TimerError),
5879 #[error(transparent)]
5880 Motion(#[from] crate::MotionError),
5881 #[error(transparent)]
5882 Budget(#[from] crate::RuntimeBudgetError),
5883}
5884
5885#[cfg(test)]
5886mod tests {
5887 use super::*;
5888 use crate::{ComponentStateSchema, RuntimeEngine, StateField, SubscriptionWork, ValueSchema};
5889
5890 #[test]
5891 fn dirty_delivery_wakes_only_after_a_successful_outermost_commit() {
5892 use std::future::Future;
5893 use std::task::{Context, Poll, Waker};
5894
5895 let mut runtime = UiRuntimeState::new();
5896 let root = ComponentInstancePath::root("View", "main");
5897 let wake = runtime.tasks.wake();
5898 let mut listener = std::pin::pin!(wake.listen());
5899 let mut context = Context::from_waker(Waker::noop());
5900 let _outer = runtime.begin_transaction().unwrap();
5901 let _inner = runtime.begin_transaction().unwrap();
5902 runtime.dirty.insert(root.clone());
5903 runtime.commit_transaction().unwrap();
5904 assert_eq!(listener.as_mut().poll(&mut context), Poll::Pending);
5905 runtime.commit_transaction().unwrap();
5906 assert_eq!(listener.as_mut().poll(&mut context), Poll::Ready(()));
5907
5908 runtime.dirty.clear();
5909 let mut listener = std::pin::pin!(wake.listen());
5910 let failed = runtime.begin_transaction().unwrap();
5911 runtime.dirty.insert(root.clone());
5912 runtime.rollback_transaction(failed).unwrap();
5913 assert_eq!(listener.as_mut().poll(&mut context), Poll::Pending);
5914 let _quiescent = runtime.begin_transaction().unwrap();
5915 runtime.commit_transaction().unwrap();
5916 assert_eq!(listener.as_mut().poll(&mut context), Poll::Pending);
5917
5918 runtime.effect_cascades.restart(&root);
5921 runtime.effect_cascades.charge(&root, 64).unwrap();
5922 assert!(runtime.effect_cascades.charge(&root, 1).is_err());
5923 let _unrelated = runtime.begin_transaction().unwrap();
5924 runtime.dirty.insert(root.clone());
5925 runtime.commit_transaction().unwrap();
5926 assert!(!runtime.has_window_dirty(&root));
5927 assert_eq!(listener.as_mut().poll(&mut context), Poll::Pending);
5928 }
5929
5930 #[test]
5931 fn host_document_and_state_writes_publish_without_a_transaction_but_failures_do_not() {
5932 use std::future::Future;
5933 use std::task::{Context, Poll, Waker};
5934
5935 let context = mounted_context(ExecutionPhase::Event);
5936 let mut runtime = context.runtime.borrow_mut();
5937 let root = context.component.clone();
5938 runtime
5939 .native_documents
5940 .register(
5941 "source",
5942 crate::NativeTextDocument::new("source", 1, "first").unwrap(),
5943 )
5944 .unwrap();
5945 runtime
5946 .native_documents
5947 .read_tracked(&root, "source")
5948 .unwrap();
5949 let wake = runtime.tasks.wake();
5950 let mut listener = std::pin::pin!(wake.listen());
5951 let mut poll_context = Context::from_waker(Waker::noop());
5952 assert!(
5953 runtime
5954 .replace_native_text_document_from_host(
5955 "source",
5956 crate::NativeTextDocument::new("source", 1, "stale").unwrap()
5957 )
5958 .is_err()
5959 );
5960 assert_eq!(listener.as_mut().poll(&mut poll_context), Poll::Pending);
5961 assert!(
5962 runtime
5963 .replace_native_text_document_from_host(
5964 "source",
5965 crate::NativeTextDocument::new("source", 2, "second").unwrap()
5966 )
5967 .unwrap()
5968 );
5969 assert_eq!(listener.as_mut().poll(&mut poll_context), Poll::Ready(()));
5970
5971 runtime.dirty.clear();
5972 let mut listener = std::pin::pin!(wake.listen());
5973 let rollback = runtime.begin_transaction().unwrap();
5974 assert!(
5975 runtime
5976 .replace_native_text_document_from_host(
5977 "source",
5978 crate::NativeTextDocument::new("source", 3, "rolled back").unwrap()
5979 )
5980 .unwrap()
5981 );
5982 assert_eq!(listener.as_mut().poll(&mut poll_context), Poll::Pending);
5983 runtime.rollback_transaction(rollback).unwrap();
5984 assert_eq!(
5985 runtime
5986 .native_documents
5987 .read_tracked(&root, "source")
5988 .unwrap()
5989 .revision(),
5990 2
5991 );
5992 assert_eq!(listener.as_mut().poll(&mut poll_context), Poll::Pending);
5993 assert!(
5994 runtime
5995 .set_component_state_from_host(&root, "count", UiValue::Integer(7))
5996 .unwrap()
5997 );
5998 assert_eq!(listener.as_mut().poll(&mut poll_context), Poll::Ready(()));
5999 }
6000
6001 #[test]
6002 fn rollback_quarantine_removes_only_the_rejected_root_effect_derivations() {
6003 let mut runtime = UiRuntimeState::new();
6004 let first = ComponentInstancePath::root("App", "first");
6005 let second = ComponentInstancePath::root("App", "second");
6006 for root in [&first, &second] {
6007 runtime.ensure_component_incarnation(root);
6008 runtime.effect_cascades.restart(root);
6009 runtime
6010 .effect_cascades
6011 .register_generation(root, ScriptGeneration::default());
6012 }
6013 let owner = |runtime: &UiRuntimeState, root: &ComponentInstancePath, effect: bool| {
6014 SemanticDispatchOwner {
6015 source: Rc::new(SemanticDispatchSource {
6016 runtime_id: runtime.runtime_id,
6017 generation: ScriptGeneration::default(),
6018 component: root.clone(),
6019 incarnation: runtime.component_incarnation(root).unwrap(),
6020 effect: None,
6021 cascade: effect
6022 .then(|| runtime.effect_cascades.dispatch_token(root))
6023 .flatten(),
6024 publication_valid: Cell::new(true),
6025 }),
6026 }
6027 };
6028 let stale = owner(&runtime, &first, true);
6029 runtime.pending_events = vec![
6030 PendingEvent {
6031 target: first.clone(),
6032 event: UiEvent {
6033 name: "rejected".into(),
6034 payload: UiValue::Null,
6035 },
6036 origin: crate::InvocationOrigin::Effect,
6037 owner: Some(stale.clone()),
6038 },
6039 PendingEvent {
6040 target: first.clone(),
6041 event: UiEvent {
6042 name: "external".into(),
6043 payload: UiValue::Null,
6044 },
6045 origin: crate::InvocationOrigin::Automation,
6046 owner: Some(owner(&runtime, &first, false)),
6047 },
6048 PendingEvent {
6049 target: second.clone(),
6050 event: UiEvent {
6051 name: "other_root".into(),
6052 payload: UiValue::Null,
6053 },
6054 origin: crate::InvocationOrigin::Effect,
6055 owner: Some(owner(&runtime, &second, true)),
6056 },
6057 ];
6058 let checkpoint = runtime.begin_transaction().unwrap();
6059 runtime.effect_cascades.charge(&first, 64).unwrap();
6060 assert!(runtime.effect_cascades.charge(&first, 1).is_err());
6061 runtime.rollback_transaction(checkpoint).unwrap();
6062 assert!(!runtime.dispatch_owner_active(Some(&stale)));
6063 let (_, first_events) = runtime.drain_window_dispatch(&first);
6064 assert_eq!(
6065 first_events
6066 .iter()
6067 .map(|event| event.event.name.as_str())
6068 .collect::<Vec<_>>(),
6069 ["external"]
6070 );
6071 assert!(runtime.has_window_pending_dispatch(&second));
6072 let (_, second_events) = runtime.drain_window_dispatch(&second);
6073 assert_eq!(
6074 second_events
6075 .iter()
6076 .map(|event| event.event.name.as_str())
6077 .collect::<Vec<_>>(),
6078 ["other_root"]
6079 );
6080 runtime.effect_cascades.restart(&first);
6081 assert!(
6082 !runtime.dispatch_owner_active(Some(&stale)),
6083 "a fresh external operation cannot revive an old epoch"
6084 );
6085 }
6086
6087 fn mounted_context(phase: ExecutionPhase) -> UiContext {
6088 let path = ComponentInstancePath::root("Counter", "counter");
6089 let schema = ComponentStateSchema::new(BTreeMap::from([
6090 (
6091 "count".to_owned(),
6092 StateField::new(ValueSchema::integer(), UiValue::Integer(0)),
6093 ),
6094 (
6095 "profile".to_owned(),
6096 StateField::new(
6097 ValueSchema::UiValue,
6098 UiValue::Map(BTreeMap::from([(
6099 "name".to_owned(),
6100 UiValue::String("Ada".to_owned()),
6101 )])),
6102 ),
6103 ),
6104 ]))
6105 .unwrap();
6106 let mut state = UiRuntimeState::new();
6107 let mut render = state.component_state.begin_render();
6108 render.mount(path.clone(), &schema).unwrap();
6109 state.component_state.commit_render(render);
6110 UiContext::new(
6111 Rc::new(RefCell::new(state)),
6112 path,
6113 Some("main".to_owned()),
6114 phase,
6115 BTreeMap::from([(
6116 "change".to_owned(),
6117 EventSchema {
6118 doc: None,
6119 payload: ValueSchema::integer(),
6120 },
6121 )]),
6122 )
6123 }
6124
6125 #[test]
6126 fn theme_variant_reads_the_resolved_selection() {
6127 let context = mounted_context(ExecutionPhase::Event);
6128 assert!(context.resolved_theme_variant().is_none());
6130 assert_eq!(context.resolved_theme_selection(), None);
6131
6132 let engine = RuntimeEngine::new();
6133 let dark = crate::load_theme_source(
6134 engine.engine(),
6135 "default_dark.rhai",
6136 include_str!("../../../registry/themes/default_dark.rhai"),
6137 )
6138 .unwrap();
6139 let mut light = dark.clone();
6140 light.name = "Light".to_owned();
6141 light.mode = crate::ThemeMode::Light;
6142 let manager = crate::ThemeManager::from_variants(
6143 [dark, light],
6144 crate::ThemeSelection::new("Default".to_owned(), "Dark".to_owned()),
6145 )
6146 .unwrap();
6147 context.runtime.borrow_mut().theme = Some(manager);
6148
6149 let variant = context.resolved_theme_variant().expect("resolves");
6150 assert_eq!(variant.mode, crate::ThemeMode::Dark);
6151 assert_eq!(
6152 context.resolved_theme_selection(),
6153 Some(ThemeSelection::new("Default", "Dark"))
6154 );
6155 }
6156
6157 #[test]
6158 fn first_native_appearance_replaces_dark_fallback_and_invalidates_render_readers_once() {
6159 let context = mounted_context(ExecutionPhase::Render);
6160 let engine = RuntimeEngine::new();
6161 let dark = crate::load_theme_source(
6162 engine.engine(),
6163 "dark",
6164 include_str!("../../../registry/themes/default_dark.rhai"),
6165 )
6166 .unwrap();
6167 let light = crate::load_theme_source(
6168 engine.engine(),
6169 "light",
6170 include_str!("../../../registry/themes/default_light.rhai"),
6171 )
6172 .unwrap();
6173 let mut manager = crate::ThemeManager::from_variants(
6174 [dark, light],
6175 ThemeSelection::new("Default", "Dark"),
6176 )
6177 .unwrap();
6178 manager
6179 .set_app(ThemePreference::System {
6180 family: "Default".into(),
6181 })
6182 .unwrap();
6183 context.runtime.borrow_mut().theme = Some(manager);
6184 assert_eq!(
6185 context.resolved_theme_variant().unwrap().mode,
6186 crate::ThemeMode::Dark
6187 );
6188 {
6189 let mut runtime = context.runtime.borrow_mut();
6190 runtime.dirty.clear();
6191 assert!(runtime.update_window_appearance("main", crate::SystemAppearance::Light));
6192 assert_eq!(
6193 runtime.dirty,
6194 BTreeSet::from([context.component_path().clone()])
6195 );
6196 runtime.dirty.clear();
6197 assert!(!runtime.update_window_appearance("main", crate::SystemAppearance::Light));
6198 assert!(runtime.dirty.is_empty());
6199 }
6200 assert_eq!(
6201 context.resolved_theme_variant().unwrap().mode,
6202 crate::ThemeMode::Light
6203 );
6204 context
6205 .runtime
6206 .borrow_mut()
6207 .update_window_appearance("main", crate::SystemAppearance::Dark);
6208 assert_eq!(
6209 context.resolved_theme_variant().unwrap().mode,
6210 crate::ThemeMode::Dark
6211 );
6212 }
6213
6214 #[test]
6215 fn render_signal_reads_disable_component_reuse() {
6216 let context = mounted_context(ExecutionPhase::Render);
6217 let signal = crate::NativeSignal::new(
6218 crate::SignalId::new(
6219 context.component_path().clone(),
6220 "hot",
6221 crate::SignalKind::Float,
6222 )
6223 .unwrap(),
6224 );
6225 assert!(context.get_signal(&signal).is_err());
6226 assert!(!context.component_render_is_reusable());
6227 }
6228
6229 #[test]
6230 fn image_decodes_are_new_async_work_and_never_start_while_suspending() {
6231 for phase in [ExecutionPhase::Suspend, ExecutionPhase::Dispose] {
6232 assert!(
6233 matches!(
6234 mounted_context(phase).start_image_decode(
6235 &AssetId::parse("app/avatar").unwrap(),
6236 FnPtr::new("loaded").unwrap(),
6237 FnPtr::new("failed").unwrap(),
6238 ),
6239 Err(UiContextError::AsyncDuringSuspend)
6240 ),
6241 "{phase:?}"
6242 );
6243 }
6244 }
6245
6246 #[test]
6247 fn async_handles_cancel_only_from_the_component_that_owns_them() {
6248 let mut engine = RuntimeEngine::new();
6249 let compiled = engine
6250 .compile(
6251 "fn view() { text(\"owner\") } fn done(ctx, value) {} fn failed(ctx, error) {}",
6252 )
6253 .unwrap();
6254 let generation = compiled.generation();
6255 let callback = |name| engine.callback(&compiled, name).unwrap();
6256 let owner = ComponentInstancePath::root("View", "main").child("Owner", "owner");
6257 let other = ComponentInstancePath::root("View", "main").child("Other", "other");
6258 let mut state = UiRuntimeState::new();
6259 let spawn = |state: &mut UiRuntimeState, scope| {
6260 state
6261 .tasks
6262 .spawn(
6263 scope,
6264 generation,
6265 callback("done"),
6266 callback("failed"),
6267 ValueSchema::Null,
6268 || Ok(UiValue::Null),
6269 )
6270 .unwrap()
6271 };
6272 let task = spawn(&mut state, AsyncScope::Component(owner.clone()));
6273 let app_task = spawn(&mut state, AsyncScope::App);
6274 let (subscription, _emitter) =
6275 state.subscriptions.subscribe(SubscriptionRegistration::new(
6276 "watch",
6277 AsyncScope::Effect {
6278 component: owner.clone(),
6279 key: "watch".into(),
6280 activation: 1,
6281 },
6282 generation,
6283 callback("done"),
6284 callback("failed"),
6285 ValueSchema::integer(),
6286 ));
6287 let runtime = Rc::new(RefCell::new(state));
6288 let context = |component: &ComponentInstancePath| {
6289 UiContext::new(
6290 Rc::clone(&runtime),
6291 component.clone(),
6292 Some("main".to_owned()),
6293 ExecutionPhase::Event,
6294 BTreeMap::new(),
6295 )
6296 };
6297
6298 let foreign = context(&other);
6299 assert!(matches!(
6300 foreign.cancel_task(task),
6301 Err(UiContextError::ForeignAsyncHandle { owner: found }) if found == owner
6302 ));
6303 assert!(matches!(
6304 foreign.cancel_subscription(subscription),
6305 Err(UiContextError::ForeignAsyncHandle { owner: found }) if found == owner
6306 ));
6307 assert!(
6308 foreign.cancel_task(app_task).unwrap(),
6309 "app-scoped work has no component owner"
6310 );
6311 let own = context(&owner);
6312 assert!(own.cancel_task(task).unwrap());
6313 assert!(own.cancel_subscription(subscription).unwrap());
6314 assert!(
6315 !foreign.cancel_task(task).unwrap(),
6316 "a finished handle is no longer anyone's"
6317 );
6318 }
6319
6320 #[test]
6321 fn only_render_reads_subscribe_to_stores_and_locale() {
6322 let engine = Engine::new();
6323 let en = crate::load_locale_source(
6324 &engine,
6325 "en.rhai",
6326 include_str!("../../../registry/locales/en.rhai"),
6327 )
6328 .unwrap();
6329 let zh = crate::load_locale_source(
6330 &engine,
6331 "zh_cn.rhai",
6332 include_str!("../../../registry/locales/zh_cn.rhai"),
6333 )
6334 .unwrap();
6335 let mut state = UiRuntimeState::new();
6336 state.locale = Some(LocaleManager::new([en, zh], "en", "en").unwrap());
6337 state.windows.register_open("main").unwrap();
6338 for store in [StoreId::app("data"), StoreId::window("main", "data")] {
6339 state
6340 .stores
6341 .declare(
6342 store,
6343 ComponentStateSchema::new(BTreeMap::from([(
6344 "count".to_owned(),
6345 StateField::new(ValueSchema::integer(), UiValue::Integer(0)),
6346 )]))
6347 .unwrap(),
6348 )
6349 .unwrap();
6350 }
6351 let runtime = Rc::new(RefCell::new(state));
6352 let reader = ComponentInstancePath::root("View", "main").child("Reader", "reader");
6353 let writer = ComponentInstancePath::root("View", "main").child("Writer", "writer");
6354 let context = |component: &ComponentInstancePath, phase| {
6355 UiContext::new(
6356 Rc::clone(&runtime),
6357 component.clone(),
6358 Some("main".to_owned()),
6359 phase,
6360 BTreeMap::new(),
6361 )
6362 };
6363 let read_everything = |context: &UiContext| {
6364 context.get_app_store("data", "count").unwrap();
6365 context.get_window_store("data", "count").unwrap();
6366 context.text("common.loading").unwrap();
6367 };
6368 let write_everything = |value: i64, locale: &str| {
6369 let writer = context(&writer, ExecutionPhase::Event);
6370 writer
6371 .set_app_store("data", "count", Dynamic::from(value))
6372 .unwrap();
6373 writer
6374 .set_window_store("data", "count", Dynamic::from(value))
6375 .unwrap();
6376 writer.set_locale(locale).unwrap();
6377 runtime.borrow_mut().drain_batch().dirty
6378 };
6379
6380 read_everything(&context(&reader, ExecutionPhase::Event));
6381 assert!(
6382 !write_everything(1, "zh-CN").contains(&reader),
6383 "a callback read is no dependency"
6384 );
6385
6386 read_everything(&context(&reader, ExecutionPhase::Render));
6387 assert!(write_everything(2, "en").contains(&reader));
6388 }
6389
6390 #[test]
6391 fn render_context_rejects_mutation() {
6392 let context = mounted_context(ExecutionPhase::Render);
6393 assert!(matches!(
6394 context.set_state("count", Dynamic::from(1_i64)),
6395 Err(UiContextError::MutationDuringRender)
6396 ));
6397 }
6398
6399 #[test]
6400 fn event_target_bounds_are_untracked_and_event_only() {
6401 let context = mounted_context(ExecutionPhase::Event).with_event_target(Some(
6402 crate::GeometryBounds::new(13.0, 24.0, 90.0, 40.0).unwrap(),
6403 ));
6404 assert_eq!(
6405 context.event_target_bounds().unwrap(),
6406 crate::GeometryBounds::new(13.0, 24.0, 90.0, 40.0)
6407 .unwrap()
6408 .into_value()
6409 );
6410 assert!(context.runtime().borrow().geometry.take_dirty().is_empty());
6411
6412 assert!(matches!(
6413 mounted_context(ExecutionPhase::Render).event_target_bounds(),
6414 Err(UiContextError::EventTargetOutsideEvent)
6415 ));
6416 assert_eq!(
6417 mounted_context(ExecutionPhase::Event)
6418 .event_target_bounds()
6419 .unwrap(),
6420 UiValue::Null
6421 );
6422 }
6423
6424 #[test]
6425 fn viewport_class_is_window_scoped_and_script_readable() {
6426 let context = mounted_context(ExecutionPhase::Render);
6427 context
6428 .runtime()
6429 .borrow_mut()
6430 .responsive
6431 .update_window("main", 480.0)
6432 .unwrap();
6433 assert_eq!(context.viewport_class().unwrap(), "compact");
6434 }
6435
6436 #[test]
6437 fn locale_and_viewport_reads_register_exact_component_dependencies() {
6438 let engine = Engine::new();
6439 let en = crate::load_locale_source(
6440 &engine,
6441 "en.rhai",
6442 include_str!("../../../registry/locales/en.rhai"),
6443 )
6444 .unwrap();
6445 let zh = crate::load_locale_source(
6446 &engine,
6447 "zh_cn.rhai",
6448 include_str!("../../../registry/locales/zh_cn.rhai"),
6449 )
6450 .unwrap();
6451 let mut state = UiRuntimeState::new();
6452 state.locale = Some(LocaleManager::new([en, zh], "en", "en").unwrap());
6453 state.responsive.update_window("main", 480.0).unwrap();
6454 state.windows.register_open("main").unwrap();
6455 let runtime = Rc::new(RefCell::new(state));
6456 let reader = ComponentInstancePath::root("View", "main").child("Reader", "reader");
6457 let unrelated = ComponentInstancePath::root("View", "main").child("Static", "static");
6458 let render_context = UiContext::new(
6459 Rc::clone(&runtime),
6460 reader.clone(),
6461 Some("main".to_owned()),
6462 ExecutionPhase::Render,
6463 BTreeMap::new(),
6464 );
6465 assert_ne!(render_context.text("common.loading").unwrap(), "");
6466 assert_eq!(render_context.viewport_class().unwrap(), "compact");
6467 let event = UiContext::new(
6468 Rc::clone(&runtime),
6469 unrelated,
6470 Some("main".to_owned()),
6471 ExecutionPhase::Event,
6472 BTreeMap::new(),
6473 );
6474 event.set_locale("zh-CN").unwrap();
6475
6476 assert_eq!(
6477 runtime.borrow_mut().drain_batch().dirty,
6478 BTreeSet::from([reader.clone()])
6479 );
6480 assert_eq!(
6481 runtime
6482 .borrow()
6483 .environment_dependencies
6484 .invalidate_viewport("main"),
6485 BTreeSet::from([reader])
6486 );
6487 assert!(runtime.borrow_mut().take_window_repaint("main"));
6488 }
6489
6490 #[test]
6491 fn event_mutations_are_batched() {
6492 let context = mounted_context(ExecutionPhase::Event);
6493 context.set_state("count", Dynamic::from(1_i64)).unwrap();
6494 context.set_state("count", Dynamic::from(2_i64)).unwrap();
6495 context.emit("change", Dynamic::from(2_i64)).unwrap();
6496
6497 let mut runtime = context.runtime().borrow_mut();
6498 let batch = runtime.drain_batch();
6499 assert_eq!(batch.dirty.len(), 1);
6500 assert_eq!(batch.events.len(), 1);
6501 assert_eq!(
6502 runtime
6503 .component_state
6504 .get(&ComponentInstancePath::root("Counter", "counter"), "count",),
6505 Some(&UiValue::Integer(2))
6506 );
6507 }
6508
6509 #[test]
6510 fn semantic_event_and_action_traces_never_retain_payload_values() {
6511 let secret = "AUDIT_ONLY_SYNTHETIC_TOKEN";
6512 let path = ComponentInstancePath::root("SecretInput", "audit");
6513 let schema = ComponentStateSchema::new(BTreeMap::from([(
6514 "token".to_owned(),
6515 StateField::new(ValueSchema::string(), UiValue::String(secret.to_owned()))
6516 .sensitive(true),
6517 )]))
6518 .unwrap();
6519 let mut state = UiRuntimeState::new();
6520 let mut render = state.component_state.begin_render();
6521 render.mount(path.clone(), &schema).unwrap();
6522 state.component_state.commit_render(render);
6523
6524 let mut engine = RuntimeEngine::new();
6525 let compiled = engine
6526 .compile("fn view() { text(\"trace\") } fn receive(ctx, payload) {}")
6527 .unwrap();
6528 state.actions.register_or_replace(
6529 crate::ActionId::parse("audit.receive").unwrap(),
6530 engine.callback(&compiled, "receive").unwrap(),
6531 );
6532 let runtime = Rc::new(RefCell::new(state));
6533 let context = UiContext::new(
6534 Rc::clone(&runtime),
6535 path,
6536 Some("main".to_owned()),
6537 ExecutionPhase::Event,
6538 BTreeMap::from([(
6539 "change".to_owned(),
6540 EventSchema {
6541 doc: None,
6542 payload: ValueSchema::string(),
6543 },
6544 )]),
6545 );
6546
6547 let event_value = context.get_state("token").unwrap().into_dynamic();
6548 context.emit("change", event_value).unwrap();
6549 let action_value = context.get_state("token").unwrap().into_dynamic();
6550 context
6551 .dispatch_action("audit.receive", action_value)
6552 .unwrap();
6553
6554 let traces = runtime.borrow().traces.snapshot();
6555 let semantic = traces
6556 .iter()
6557 .filter(|trace| {
6558 matches!(
6559 trace.kind,
6560 crate::RuntimeTraceKind::Event | crate::RuntimeTraceKind::Action
6561 )
6562 })
6563 .collect::<Vec<_>>();
6564 assert_eq!(semantic.len(), 2);
6565 assert!(
6566 semantic
6567 .iter()
6568 .all(|trace| trace.sensitive && trace.payload.is_none())
6569 );
6570 assert!(!format!("{traces:?}").contains(secret));
6571 }
6572
6573 #[test]
6574 fn scripts_receive_restricted_context_without_gpui_types() {
6575 let context = mounted_context(ExecutionPhase::Event);
6576 let mut runtime = RuntimeEngine::new();
6577 let compiled = runtime
6578 .compile(
6579 r#"
6580 fn view() { text("context") }
6581 fn increment(ctx) {
6582 ctx.set_state("count", ctx.get_state("count") + 1);
6583 }
6584 "#,
6585 )
6586 .unwrap();
6587 runtime.render(&compiled).unwrap();
6588 let callback = runtime.callback(&compiled, "increment").unwrap();
6589 let _ = runtime
6590 .invoke_callback(&compiled, &callback, (context.clone(),))
6591 .unwrap();
6592 assert_eq!(context.get_state("count").unwrap(), UiValue::Integer(1));
6593 }
6594
6595 #[test]
6596 fn structural_store_paths_invalidate_executable_owner_not_synthetic_scope() {
6597 for window_store in [false, true] {
6598 let runtime = Rc::new(RefCell::new(UiRuntimeState::new()));
6599 let owner = ComponentInstancePath::root("Panel", "paths");
6600 let store = if window_store {
6601 StoreId::window("main", "data")
6602 } else {
6603 StoreId::app("data")
6604 };
6605 runtime
6606 .borrow_mut()
6607 .stores
6608 .declare(
6609 store,
6610 ComponentStateSchema::new(BTreeMap::from([(
6611 "model".into(),
6612 StateField::new(
6613 ValueSchema::UiValue,
6614 UiValue::Map(BTreeMap::from([
6615 ("label".into(), UiValue::String("before".into())),
6616 ("sibling".into(), UiValue::String("untouched".into())),
6617 ])),
6618 ),
6619 )]))
6620 .unwrap(),
6621 )
6622 .unwrap();
6623 let render = UiContext::new(
6624 Rc::clone(&runtime),
6625 owner.clone(),
6626 Some("main".into()),
6627 ExecutionPhase::Render,
6628 BTreeMap::new(),
6629 );
6630 let structural = render
6631 .for_structural_scope(owner.child("VirtualCollection", "rows"), BTreeMap::new());
6632 let label = UiValuePath::new(vec![UiValuePathSegment::Key("label".into())]).unwrap();
6633 let sibling =
6634 UiValuePath::new(vec![UiValuePathSegment::Key("sibling".into())]).unwrap();
6635 let value = if window_store {
6636 structural.get_window_store_path("data", "model", &label)
6637 } else {
6638 structural.get_app_store_path("data", "model", &label)
6639 }
6640 .unwrap();
6641 assert_eq!(value, UiValue::String("before".into()));
6642 let mut event = render.clone();
6643 event.phase = ExecutionPhase::Event;
6644 let write = |path: &UiValuePath| {
6645 if window_store {
6646 event.set_window_store_path("data", "model", path, Dynamic::from("after"))
6647 } else {
6648 event.set_app_store_path("data", "model", path, Dynamic::from("after"))
6649 }
6650 .unwrap();
6651 };
6652 write(&sibling);
6653 assert!(runtime.borrow().dirty.is_empty());
6654 write(&label);
6655 assert_eq!(runtime.borrow().dirty, BTreeSet::from([owner]));
6656 }
6657 }
6658
6659 #[test]
6660 fn scripts_use_bounded_nested_and_keyed_store_paths() {
6661 let context = mounted_context(ExecutionPhase::Event);
6662 let row = |id: &str, label: &str| {
6663 UiValue::Map(BTreeMap::from([
6664 ("id".to_owned(), UiValue::String(id.to_owned())),
6665 ("label".to_owned(), UiValue::String(label.to_owned())),
6666 ]))
6667 };
6668 context
6669 .runtime()
6670 .borrow_mut()
6671 .stores
6672 .declare(
6673 StoreId::app("model"),
6674 ComponentStateSchema::new(BTreeMap::from([(
6675 "data".to_owned(),
6676 StateField::new(
6677 ValueSchema::UiValue,
6678 UiValue::Map(BTreeMap::from([(
6679 "rows".to_owned(),
6680 UiValue::Array(vec![row("alpha", "Alpha"), row("beta", "Beta")]),
6681 )])),
6682 ),
6683 )]))
6684 .unwrap(),
6685 )
6686 .unwrap();
6687 let mut runtime = RuntimeEngine::new();
6688 let compiled = runtime
6689 .compile(
6690 r#"
6691 fn view() { text("paths") }
6692 fn update(ctx) {
6693 let name = ctx.get_state_path("profile", ["name"]);
6694 ctx.set_state_path("profile", ["name"], name + " Lovelace");
6695 let label = ctx.get_app_store_path(
6696 "model",
6697 "data",
6698 ["rows", #{ by: "id", key: "beta" }, "label"]
6699 );
6700 ctx.set_app_store_path(
6701 "model",
6702 "data",
6703 ["rows", #{ by: "id", key: "beta" }, "label"],
6704 label + "!"
6705 );
6706 }
6707 "#,
6708 )
6709 .unwrap();
6710 runtime.render(&compiled).unwrap();
6711 let callback = runtime.callback(&compiled, "update").unwrap();
6712 let _: Dynamic = runtime
6713 .invoke_callback(&compiled, &callback, (context.clone(),))
6714 .unwrap();
6715
6716 let profile = context.get_state("profile").unwrap();
6717 assert_eq!(
6718 profile
6719 .get_path(
6720 &UiValuePath::new(vec![UiValuePathSegment::Key("name".to_owned())]).unwrap()
6721 )
6722 .unwrap(),
6723 &UiValue::String("Ada Lovelace".to_owned())
6724 );
6725 let row_path = UiValuePath::new(vec![
6726 UiValuePathSegment::Key("rows".to_owned()),
6727 UiValuePathSegment::Item {
6728 key_field: "id".to_owned(),
6729 key: "beta".to_owned(),
6730 },
6731 UiValuePathSegment::Key("label".to_owned()),
6732 ])
6733 .unwrap();
6734 assert_eq!(
6735 context
6736 .runtime()
6737 .borrow_mut()
6738 .stores
6739 .read_path_tracked(
6740 &ComponentInstancePath::root("Test", "reader"),
6741 &StoreId::app("model"),
6742 "data",
6743 &row_path,
6744 )
6745 .unwrap(),
6746 UiValue::String("Beta!".to_owned())
6747 );
6748 assert!(rhai_value_path(vec![Dynamic::from(-1_i64)]).is_err());
6749 }
6750
6751 #[test]
6752 fn script_theme_switch_preserves_component_state_and_ast_generation() {
6753 let context = mounted_context(ExecutionPhase::Event);
6754 context.set_state("count", Dynamic::from(7_i64)).unwrap();
6755 let mut runtime = RuntimeEngine::new();
6756 let dark = crate::load_theme_source(
6757 runtime.engine(),
6758 "default_dark.rhai",
6759 include_str!("../../../registry/themes/default_dark.rhai"),
6760 )
6761 .unwrap();
6762 let mocha = crate::load_theme_source(
6763 runtime.engine(),
6764 "catppuccin_mocha.rhai",
6765 include_str!("../../../registry/themes/catppuccin_mocha.rhai"),
6766 )
6767 .unwrap();
6768 context.runtime().borrow_mut().theme = Some(
6769 ThemeManager::from_variants([dark, mocha], ThemeSelection::new("Default", "Dark"))
6770 .unwrap(),
6771 );
6772 let compiled = runtime
6773 .compile(
6774 r#"
6775 fn view() { text("theme") }
6776 fn switch_theme(ctx) { ctx.set_theme("Catppuccin", "Mocha"); }
6777 "#,
6778 )
6779 .unwrap();
6780 runtime.render(&compiled).unwrap();
6781 let generation = compiled.generation();
6782 let callback = runtime.callback(&compiled, "switch_theme").unwrap();
6783 let _ = runtime
6784 .invoke_callback(&compiled, &callback, (context.clone(),))
6785 .unwrap();
6786
6787 assert_eq!(context.get_state("count").unwrap(), UiValue::Integer(7));
6788 assert_eq!(compiled.generation(), generation);
6789 let state = context.runtime().borrow();
6790 let theme = state
6791 .theme
6792 .as_ref()
6793 .unwrap()
6794 .resolve(Some("main"), None, crate::SystemAppearance::Dark)
6795 .unwrap();
6796 assert_eq!(theme.variant().family, "Catppuccin");
6797 assert_eq!(theme.variant().name, "Mocha");
6798 drop(state);
6799 context.set_theme_system("Default").unwrap();
6800 let state = context.runtime().borrow();
6801 assert!(matches!(
6802 state.theme.as_ref().unwrap().app_preference(),
6803 ThemePreference::System { family } if family == "Default"
6804 ));
6805 }
6806
6807 #[test]
6808 fn a_system_pair_takes_the_maps_theme_variant_returns() {
6809 let context = mounted_context(ExecutionPhase::Event);
6810 let runtime = RuntimeEngine::new();
6811 let light = crate::load_theme_source(
6812 runtime.engine(),
6813 "default_light.rhai",
6814 include_str!("../../../registry/themes/default_light.rhai"),
6815 )
6816 .unwrap();
6817 let mocha = crate::load_theme_source(
6818 runtime.engine(),
6819 "catppuccin_mocha.rhai",
6820 include_str!("../../../registry/themes/catppuccin_mocha.rhai"),
6821 )
6822 .unwrap();
6823 context.runtime().borrow_mut().theme = Some(
6824 ThemeManager::from_variants([light, mocha], ThemeSelection::new("Default", "Light"))
6825 .unwrap(),
6826 );
6827 let mut engine = Engine::new();
6828 register_ui_context_api(&mut engine);
6829 let mut scope = rhai::Scope::new();
6830 scope.push("ctx", context.clone());
6831 engine
6832 .eval_with_scope::<()>(
6833 &mut scope,
6834 r#"ctx.set_theme_system_pair(#{ family: "Default", name: "Light" },
6835 #{ family: "Catppuccin", name: "Mocha", mode: "dark" })"#,
6836 )
6837 .unwrap();
6838 let resolved = |system| {
6839 let state = context.runtime().borrow();
6840 let theme = state.theme.as_ref().unwrap();
6841 let resolved = theme.resolve(Some("main"), None, system).unwrap();
6842 let variant = resolved.variant();
6843 format!("{}/{}", variant.family, variant.name)
6844 };
6845 assert_eq!(resolved(crate::SystemAppearance::Light), "Default/Light");
6846 assert_eq!(resolved(crate::SystemAppearance::Dark), "Catppuccin/Mocha");
6847 let error = engine
6848 .eval_with_scope::<()>(
6849 &mut scope,
6850 r#"ctx.set_theme_system_pair(#{ family: "Default" }, #{ family: "Catppuccin", name: "Mocha" })"#,
6851 )
6852 .unwrap_err();
6853 assert!(
6854 error
6855 .to_string()
6856 .contains("`light` needs string `family` and `name`"),
6857 "{error}"
6858 );
6859 }
6860
6861 #[test]
6862 fn scroll_offsets_take_integers_and_floats() {
6863 let mut engine = Engine::new();
6864 register_ui_context_api(&mut engine);
6865 let mut scope = rhai::Scope::new();
6866 scope.push("ctx", mounted_context(ExecutionPhase::Event));
6867 for script in [
6868 r#"ctx.scroll_to("missing", 0, 0)"#,
6869 r#"ctx.scroll_to("missing", 0, 12.5)"#,
6870 ] {
6871 let error = engine
6872 .eval_with_scope::<()>(&mut scope, script)
6873 .unwrap_err();
6874 assert!(
6875 !matches!(*error, EvalAltResult::ErrorFunctionNotFound(..)),
6876 "{script}: {error}"
6877 );
6878 }
6879 let error = engine
6880 .eval_with_scope::<()>(&mut scope, r#"ctx.scroll_to("missing", "0", 0)"#)
6881 .unwrap_err();
6882 assert!(
6883 error.to_string().contains("scroll offset must be a number"),
6884 "{error}"
6885 );
6886 }
6887
6888 #[test]
6889 fn script_reads_fixed_today_calendar_and_locale_formatters() {
6890 let mut engine = Engine::new();
6891 register_ui_context_api(&mut engine);
6892 let bundle = crate::load_locale_source(
6893 &engine,
6894 "en.rhai",
6895 include_str!("../../../registry/locales/en.rhai"),
6896 )
6897 .unwrap();
6898 let mut state = UiRuntimeState::new();
6899 state.locale = Some(LocaleManager::new([bundle], "en", "en").unwrap());
6900 state.calendar_clock =
6901 crate::CalendarClock::fixed(crate::GregorianDate::parse_iso("2026-08-29").unwrap());
6902 let context = UiContext::new(
6903 Rc::new(RefCell::new(state)),
6904 ComponentInstancePath::root("App", "root"),
6905 Some("main".to_owned()),
6906 ExecutionPhase::Render,
6907 BTreeMap::new(),
6908 );
6909 let mut scope = rhai::Scope::new();
6910 scope.push("ctx", context);
6911 let values = engine
6912 .eval_with_scope::<rhai::Array>(
6913 &mut scope,
6914 r#"[
6915 ctx.today(),
6916 ctx.format_date("2024-02-29", "long"),
6917 ctx.format_number(12345, #{ min_fraction_digits: 0, max_fraction_digits: 0 }),
6918 ctx.calendar().first_weekday,
6919 ]"#,
6920 )
6921 .unwrap();
6922 assert_eq!(values[0].clone_cast::<String>(), "2026-08-29");
6923 assert_eq!(
6924 values[1].clone_cast::<String>(),
6925 "Thursday, February 29, 2024"
6926 );
6927 assert_eq!(values[2].clone_cast::<String>(), "12,345");
6928 assert_eq!(values[3].clone_cast::<String>(), "sunday");
6929 }
6930
6931 #[test]
6932 fn returning_subscription_work_closes_external_emitters_with_reason() {
6933 let mut engine = RuntimeEngine::new();
6934 let compiled = engine
6935 .compile(
6936 r#"
6937 fn view() { text("subscription") }
6938 fn success(ctx, value) { value }
6939 fn failure(ctx, error) { error }
6940 "#,
6941 )
6942 .unwrap();
6943 let generation = compiled.generation();
6944 let success = engine.callback(&compiled, "success").unwrap();
6945 let failure = engine.callback(&compiled, "failure").unwrap();
6946 let mut state = UiRuntimeState::new();
6947 let registration = SubscriptionRegistration::new(
6948 "app.stream.watch",
6949 AsyncScope::App,
6950 generation,
6951 success,
6952 failure,
6953 ValueSchema::integer(),
6954 );
6955 let (_, emitter) = state.subscriptions.subscribe(registration);
6956 let external = emitter.clone();
6957 run_subscription_work(SubscriptionWork::new(|_| {}), emitter.clone(), &emitter);
6958
6959 assert!(matches!(
6960 external.emit(UiValue::Integer(1)),
6961 Err(AsyncRuntimeError::Closed {
6962 reason: SubscriptionCloseReason::WorkReturned
6963 })
6964 ));
6965 let _ = state.subscriptions.drain(generation);
6966 assert_eq!(
6967 state.subscriptions.take_closures()[0].reason,
6968 SubscriptionCloseReason::WorkReturned
6969 );
6970 let registration = SubscriptionRegistration::new(
6971 "app.stream.trace",
6972 AsyncScope::App,
6973 generation,
6974 engine.callback(&compiled, "success").unwrap(),
6975 engine.callback(&compiled, "failure").unwrap(),
6976 ValueSchema::integer(),
6977 );
6978 let (_, emitter) = state.subscriptions.subscribe(registration);
6979 emitter.close_with_reason(SubscriptionCloseReason::WorkReturned);
6980 let _ = state.subscriptions.drain(generation);
6981 state.trace_subscription_closures();
6982 let traces = state.traces.snapshot();
6983 assert!(traces.iter().any(|trace| {
6984 trace.kind == crate::RuntimeTraceKind::Subscription
6985 && trace.message == "close app.stream.trace: the subscription work returned"
6986 }));
6987 }
6988
6989 #[test]
6990 fn receiver_subscription_forwards_external_values_until_sender_drop() {
6991 let mut engine = RuntimeEngine::new();
6992 let compiled = engine
6993 .compile(
6994 r#"
6995 fn view() { text("subscription") }
6996 fn success(ctx, value) { value }
6997 fn failure(ctx, error) { error }
6998 "#,
6999 )
7000 .unwrap();
7001 let generation = compiled.generation();
7002 let registration = SubscriptionRegistration::new(
7003 "app.stream.receiver",
7004 AsyncScope::App,
7005 generation,
7006 engine.callback(&compiled, "success").unwrap(),
7007 engine.callback(&compiled, "failure").unwrap(),
7008 ValueSchema::integer(),
7009 );
7010 let mut subscriptions = SubscriptionRegistry::new();
7011 let (_, emitter) = subscriptions.subscribe(registration);
7012 let external = emitter.clone();
7013 let closer = emitter.clone();
7014 let (sender, receiver) = std::sync::mpsc::channel();
7015 let worker = std::thread::spawn(move || {
7016 run_subscription_work(SubscriptionWork::from_receiver(receiver), emitter, &closer);
7017 });
7018 sender.send(UiValue::Integer(42)).unwrap();
7019 drop(sender);
7020 worker.join().unwrap();
7021
7022 let deliveries = subscriptions.drain(generation);
7023 assert_eq!(deliveries[0].payload, UiValue::Integer(42));
7024 assert!(matches!(
7025 external.emit(UiValue::Integer(43)),
7026 Err(AsyncRuntimeError::Closed {
7027 reason: SubscriptionCloseReason::WorkReturned
7028 })
7029 ));
7030 }
7031
7032 #[test]
7033 fn receiver_subscription_waits_for_lossless_capacity_without_ending_the_stream() {
7034 let mut engine = RuntimeEngine::new();
7035 let compiled = engine
7036 .compile(
7037 "fn view() { text(\"stream\") } fn success(ctx, value) {} fn failure(ctx, value) {}",
7038 )
7039 .unwrap();
7040 engine.render(&compiled).unwrap();
7041 let generation = compiled.generation();
7042 let registration = SubscriptionRegistration::new(
7043 "stream",
7044 AsyncScope::App,
7045 generation,
7046 engine.callback(&compiled, "success").unwrap(),
7047 engine.callback(&compiled, "failure").unwrap(),
7048 ValueSchema::integer(),
7049 )
7050 .with_capacity(1)
7051 .unwrap();
7052 let mut subscriptions = SubscriptionRegistry::new();
7053 let (_, emitter) = subscriptions.subscribe(registration);
7054 let closer = emitter.clone();
7055 let (sender, receiver) = std::sync::mpsc::channel();
7056 let worker = std::thread::spawn(move || {
7057 run_subscription_work(SubscriptionWork::from_receiver(receiver), emitter, &closer);
7058 });
7059 sender.send(UiValue::Integer(1)).unwrap();
7060 sender.send(UiValue::Integer(2)).unwrap();
7061 let deadline = std::time::Instant::now() + Duration::from_secs(1);
7062 let first = loop {
7063 let values = subscriptions.drain(generation);
7064 if !values.is_empty() {
7065 break values;
7066 }
7067 assert!(std::time::Instant::now() < deadline);
7068 std::thread::yield_now();
7069 };
7070 assert_eq!(first[0].payload, UiValue::Integer(1));
7071 let second = loop {
7072 let values = subscriptions.drain(generation);
7073 if !values.is_empty() {
7074 break values;
7075 }
7076 assert!(std::time::Instant::now() < deadline);
7077 std::thread::yield_now();
7078 };
7079 assert_eq!(second[0].payload, UiValue::Integer(2));
7080 assert_eq!(subscriptions.active_count(), 1);
7081 drop(sender);
7082 worker.join().unwrap();
7083 }
7084
7085 #[test]
7086 fn runtime_transaction_rollback_restores_cancelled_subscription() {
7087 let mut engine = RuntimeEngine::new();
7088 let compiled = engine
7089 .compile(
7090 "fn view() { text(\"test\") } fn success(ctx, value) {} fn failure(ctx, value) {}",
7091 )
7092 .unwrap();
7093 engine.render(&compiled).unwrap();
7094 let success = engine.callback(&compiled, "success").unwrap();
7095 let error = engine.callback(&compiled, "failure").unwrap();
7096 let generation = compiled.generation();
7097 let mut state = UiRuntimeState::new();
7098 let (handle, emitter) = state.subscriptions.subscribe(SubscriptionRegistration::new(
7099 "rollback",
7100 AsyncScope::App,
7101 generation,
7102 success,
7103 error,
7104 ValueSchema::integer(),
7105 ));
7106 let checkpoint = state.begin_transaction().unwrap();
7107 assert!(state.subscriptions.cancel(handle));
7108 assert_eq!(emitter.close_reason(), None);
7109 state.rollback_transaction(checkpoint).unwrap();
7110 assert_eq!(state.subscriptions.active_count(), 1);
7111 emitter.emit(UiValue::Integer(7)).unwrap();
7112 assert_eq!(state.subscriptions.drain(generation).len(), 1);
7113 }
7114
7115 #[test]
7116 fn transaction_tokens_cannot_cross_runtime_or_commit_unbalanced() {
7117 let mut first = UiRuntimeState::new();
7118 let mut second = UiRuntimeState::new();
7119 let checkpoint = first.begin_transaction().unwrap();
7120 assert!(matches!(
7121 second.rollback_transaction(checkpoint.clone()),
7122 Err(UiTransactionError::ForeignSnapshot)
7123 ));
7124 assert!(matches!(
7125 second.commit_transaction(),
7126 Err(UiTransactionError::Unbalanced { .. })
7127 ));
7128 first.rollback_transaction(checkpoint).unwrap();
7129 }
7130
7131 #[test]
7132 fn presentation_geometry_and_capture_are_isolated_per_view() {
7133 let mut first = crate::RetainedUiTree::new();
7134 first.reconcile(crate::UiNode::text("first")).unwrap();
7135 let mut second = crate::RetainedUiTree::new();
7136 second.reconcile(crate::UiNode::text("second")).unwrap();
7137 let first_node = first.root_id().unwrap();
7138 let second_node = second.root_id().unwrap();
7139 assert_eq!(
7140 first_node, second_node,
7141 "tree-local IDs intentionally overlap"
7142 );
7143
7144 let mut state = UiRuntimeState::new();
7145 state.ensure_presentation("first");
7146 state.ensure_presentation("second");
7147 let first_geometry = state.geometry_for(Some("first"));
7148 let second_geometry = state.geometry_for(Some("second"));
7149 let bounds = |width| crate::ElementGeometry {
7150 layout: crate::GeometryBounds::new(0.0, 0.0, width, 20.0).unwrap(),
7151 visual: crate::GeometryBounds::new(0.0, 0.0, width, 20.0).unwrap(),
7152 clip: None,
7153 };
7154 first_geometry.update(first_node, bounds(100.0));
7155 second_geometry.update(second_node, bounds(300.0));
7156 second_geometry.begin_frame();
7157 assert!(
7158 (first_geometry.get(first_node).unwrap().visual.width - 100.0).abs() < f64::EPSILON
7159 );
7160 assert!(first_geometry.is_presented(first_node));
7161
7162 let first_capture = state.pointer_capture_for(Some("first"));
7163 let second_capture = state.pointer_capture_for(Some("second"));
7164 first_capture.capture(0, first_node);
7165 second_capture.capture(0, second_node);
7166 assert_eq!(first_capture.captured(0), Some(first_node));
7167 assert_eq!(second_capture.captured(0), Some(second_node));
7168 }
7169
7170 #[test]
7171 fn window_release_uses_segment_boundaries_and_clears_suspend_tombstones() {
7172 let now = std::time::Instant::now();
7173 let transition = || {
7174 let mut spec =
7175 crate::MotionTransition::new(crate::MotionProperty::Opacity, 0.0, 1.0, 1_000);
7176 spec.easing = crate::MotionEasing::Linear;
7177 crate::MotionSource::Transition(spec)
7178 };
7179 let mut state = UiRuntimeState::new();
7180 let ghost_path = "window:w2/view:v2/root/ghost:1";
7181 state
7182 .motions
7183 .start_exit(
7184 ComponentInstancePath::root("UiNode", ghost_path),
7185 transition(),
7186 now,
7187 )
7188 .unwrap();
7189 state.motion_ghosts.push(crate::motion::MotionGhost {
7190 id: "1".to_owned(),
7191 node: crate::UiNode::text("ghost"),
7192 bounds: crate::GeometryBounds::new(0.0, 0.0, 10.0, 10.0).unwrap(),
7193 path: ghost_path.to_owned(),
7194 domain: "window:w2/view:v2/root".to_owned(),
7195 });
7196 state
7197 .release_window("w", &ComponentInstancePath::root("View", "v"))
7198 .unwrap();
7199 assert_eq!(state.motion_ghosts.len(), 1);
7200 assert_eq!(state.motions.resource_usage().active, 1);
7201
7202 let mut reopened = UiRuntimeState::new();
7203 let scope = "window:w/view:v/root";
7204 reopened
7205 .motions
7206 .start(
7207 ComponentInstancePath::root("UiNode", format!("{scope}/node:1")),
7208 transition(),
7209 now,
7210 )
7211 .unwrap();
7212 reopened
7213 .motions
7214 .suspend_node_scope(scope, now + Duration::from_millis(200));
7215 reopened
7216 .release_window("w", &ComponentInstancePath::root("View", "v"))
7217 .unwrap();
7218 let key = reopened
7219 .motions
7220 .start(
7221 ComponentInstancePath::root("UiNode", format!("{scope}/node:2")),
7222 transition(),
7223 now + Duration::from_millis(200),
7224 )
7225 .unwrap();
7226 let frame = reopened.motions.tick(now + Duration::from_millis(400));
7227 assert!(frame.needs_frame);
7228 assert!((frame.values[&key] - 0.2).abs() < 0.01);
7229 }
7230
7231 #[test]
7232 fn timeline_handles_cannot_cross_view_contexts() {
7233 let runtime = Rc::new(RefCell::new(UiRuntimeState::new()));
7234 let now = std::time::Instant::now();
7235 let mut transition =
7236 crate::MotionTransition::new(crate::MotionProperty::Opacity, 0.0, 1.0, 1_000);
7237 transition.easing = crate::MotionEasing::Linear;
7238 let handle = runtime
7239 .borrow_mut()
7240 .motions
7241 .start_timeline(
7242 ComponentInstancePath::root("UiNode", "window:a/view:a/root"),
7243 crate::MotionTimeline::new(
7244 "foreign",
7245 crate::MotionTimelineStep::Track(crate::MotionTrack {
7246 target: ".".to_owned(),
7247 source: crate::MotionSource::Transition(transition),
7248 }),
7249 ),
7250 now,
7251 )
7252 .unwrap();
7253 let foreign = UiContext::new(
7254 Rc::clone(&runtime),
7255 ComponentInstancePath::root("View", "b"),
7256 Some("b".to_owned()),
7257 ExecutionPhase::Event,
7258 BTreeMap::new(),
7259 )
7260 .with_view_id("b");
7261
7262 assert!(matches!(
7263 foreign.cancel_motion(&handle),
7264 Err(UiContextError::Motion(
7265 crate::MotionError::ForeignTimelineHandle(_)
7266 ))
7267 ));
7268 assert_eq!(
7269 runtime.borrow().motions.timeline_state(&handle),
7270 Some(crate::MotionPlaybackState::Playing)
7271 );
7272 }
7273
7274 #[test]
7275 fn element_size_is_a_pending_size_only_read_for_both_script_overloads() {
7276 let context = mounted_context(ExecutionPhase::Render);
7277 let owner = context.component_path().clone();
7278 let reference =
7279 crate::ElementRef::new(crate::ElementRefId::new(owner.clone(), "field").unwrap());
7280 let mut engine = Engine::new();
7281 register_ui_context_api(&mut engine);
7282 let mut scope = rhai::Scope::new();
7283 scope.push("ctx", context.clone());
7284 scope.push("reference", reference.clone());
7285 let read_script = |scope: &mut rhai::Scope<'_>| {
7286 engine
7287 .eval_with_scope::<rhai::Array>(
7288 scope,
7289 r#"[ctx.element_size(reference), ctx.element_size("field")]"#,
7290 )
7291 .unwrap()
7292 };
7293 let pending = read_script(&mut scope);
7294 assert!(pending.iter().all(Dynamic::is_unit));
7295 let mut tree = crate::RetainedUiTree::new();
7296 tree.reconcile(crate::UiNode::text("field")).unwrap();
7297 let node = tree.root_id().unwrap();
7298 let geometry = context.runtime().borrow().geometry_for(Some("main"));
7299 {
7300 let mut runtime = context.runtime().borrow_mut();
7301 runtime
7302 .element_refs
7303 .reconcile(&owner, BTreeMap::from([(reference.id().clone(), node)]));
7304 geometry.sync_ref_readers(&owner, runtime.element_refs.geometry_bindings(&owner));
7305 assert_eq!(
7306 runtime.element_refs.take_dirty(),
7307 BTreeSet::from([owner.clone()])
7308 );
7309 }
7310 let mut measured = crate::ElementGeometry {
7311 layout: crate::GeometryBounds::new(10.0, 20.0, 120.0, 24.0).unwrap(),
7312 visual: crate::GeometryBounds::new(10.0, 20.0, 240.0, 48.0).unwrap(),
7313 clip: None,
7314 };
7315 geometry.update(node, measured);
7316 assert_eq!(geometry.take_dirty(), BTreeSet::from([owner.clone()]));
7317 let ready = read_script(&mut scope);
7318 for value in ready {
7319 let size = value.cast::<rhai::Map>();
7320 assert_eq!(size.len(), 2);
7321 assert!((size["width"].clone_cast::<rhai::FLOAT>() - 120.0).abs() < f64::EPSILON);
7322 assert!((size["height"].clone_cast::<rhai::FLOAT>() - 24.0).abs() < f64::EPSILON);
7323 }
7324 measured.layout.x = 30.0;
7325 measured.visual.height = 96.0;
7326 geometry.update(node, measured);
7327 assert!(geometry.take_dirty().is_empty());
7328 measured.layout.width = 140.0;
7329 geometry.update(node, measured);
7330 assert_eq!(geometry.take_dirty(), BTreeSet::from([owner]));
7331 }
7332
7333 #[test]
7334 fn element_size_event_reads_are_untracked_and_missing_refs_return_null() {
7335 let context = mounted_context(ExecutionPhase::Event);
7336 let reference = crate::ElementRef::new(
7337 crate::ElementRefId::new(context.component_path().clone(), "field").unwrap(),
7338 );
7339 assert_eq!(context.element_size(&reference).unwrap(), UiValue::Null);
7340 assert_eq!(context.element_size_by_key("field").unwrap(), UiValue::Null);
7341 assert!(context.element_size_by_key("").is_err());
7342 let mut tree = crate::RetainedUiTree::new();
7343 tree.reconcile(crate::UiNode::text("field")).unwrap();
7344 let node = tree.root_id().unwrap();
7345 context.runtime().borrow_mut().element_refs.reconcile(
7346 context.component_path(),
7347 BTreeMap::from([(reference.id().clone(), node)]),
7348 );
7349 assert!(
7350 context
7351 .runtime()
7352 .borrow_mut()
7353 .element_refs
7354 .take_dirty()
7355 .is_empty()
7356 );
7357 let geometry = context.runtime().borrow().geometry_for(Some("main"));
7358 let mut measured = crate::ElementGeometry {
7359 layout: crate::GeometryBounds::new(0.0, 0.0, 120.0, 24.0).unwrap(),
7360 visual: crate::GeometryBounds::new(0.0, 0.0, 120.0, 24.0).unwrap(),
7361 clip: None,
7362 };
7363 geometry.update(node, measured);
7364 context.element_size(&reference).unwrap();
7365 context.element_size_by_key("field").unwrap();
7366 measured.layout.width = 140.0;
7367 geometry.update(node, measured);
7368 assert!(geometry.take_dirty().is_empty());
7369 }
7370
7371 #[test]
7372 fn focus_by_ref_key_queues_a_window_scoped_retained_command() {
7373 let context = mounted_context(ExecutionPhase::Event);
7374 let mut tree = crate::RetainedUiTree::new();
7375 tree.reconcile(crate::UiNode::text("field")).unwrap();
7376 let reference = crate::ElementRef::new(
7377 crate::ElementRefId::new(context.component_path().clone(), "field").unwrap(),
7378 );
7379 context.runtime().borrow_mut().element_refs.reconcile(
7380 context.component_path(),
7381 BTreeMap::from([(reference.id().clone(), tree.root_id().unwrap())]),
7382 );
7383 let node = tree.root_id().unwrap();
7384 context
7385 .runtime()
7386 .borrow()
7387 .geometry_for(Some("main"))
7388 .update(
7389 node,
7390 crate::ElementGeometry {
7391 layout: crate::GeometryBounds::new(1.0, 2.0, 120.0, 24.0).unwrap(),
7392 visual: crate::GeometryBounds::new(3.0, 4.0, 120.0, 24.0).unwrap(),
7393 clip: None,
7394 },
7395 );
7396 assert!(matches!(
7397 context.element_bounds_by_key("field").unwrap(),
7398 UiValue::Map(bounds)
7399 if matches!(bounds.get("visual"), Some(UiValue::Map(visual))
7400 if visual.get("width") == Some(&UiValue::Float(120.0)))
7401 ));
7402 context.focus_element_by_key("field").unwrap();
7403 context
7404 .scroll_element_to_by_key("field", 12.0, 24.0)
7405 .unwrap();
7406 context.scroll_element_into_view_by_key("field").unwrap();
7407 let commands = context
7408 .runtime()
7409 .borrow_mut()
7410 .take_window_element_commands("main");
7411 assert!(matches!(
7412 commands.as_slice(),
7413 [crate::element_ref::ElementCommand::Focus { node, .. },
7414 crate::element_ref::ElementCommand::ScrollTo { node: scroll_node, x, y, .. },
7415 crate::element_ref::ElementCommand::ScrollIntoView { node: reveal_node, .. }]
7416 if *node == tree.root_id().unwrap()
7417 && scroll_node == node
7418 && reveal_node == node
7419 && (*x - 12.0).abs() < f64::EPSILON
7420 && (*y - 24.0).abs() < f64::EPSILON
7421 ));
7422 }
7423
7424 #[test]
7425 fn copy_text_is_user_activated_window_scoped_bounded_and_transactional() {
7426 let context = mounted_context(ExecutionPhase::Event).with_view_id("view");
7427 assert!(matches!(
7428 context.copy_text("path".into()),
7429 Err(UiContextError::ClipboardRequiresUserInput)
7430 ));
7431 for origin in [
7432 crate::InvocationOrigin::UserInput {
7433 event: "click".into(),
7434 },
7435 crate::InvocationOrigin::Automation,
7436 ] {
7437 context.runtime().borrow_mut().replace_origin(origin);
7438 let checkpoint = context.runtime().borrow_mut().begin_transaction().unwrap();
7439 context
7440 .copy_text("payments/checkout/timeout_ms".into())
7441 .unwrap();
7442 context
7443 .runtime()
7444 .borrow_mut()
7445 .rollback_transaction(checkpoint)
7446 .unwrap();
7447 assert_eq!(
7448 context
7449 .runtime()
7450 .borrow_mut()
7451 .take_window_element_commands("main"),
7452 []
7453 );
7454 }
7455 context.copy_text("committed".into()).unwrap();
7456 assert_eq!(
7457 context
7458 .runtime()
7459 .borrow_mut()
7460 .take_window_element_commands("other"),
7461 []
7462 );
7463 assert!(
7464 matches!(context.runtime().borrow_mut().take_window_element_commands("main").as_slice(),
7465 [crate::element_ref::ElementCommand::CopyText { text, .. }] if text == "committed")
7466 );
7467 context
7468 .runtime()
7469 .borrow_mut()
7470 .replace_origin(crate::InvocationOrigin::Timer {
7471 started_by: Box::new(crate::InvocationOrigin::UserInput {
7472 event: "click".into(),
7473 }),
7474 });
7475 assert!(context.copy_text("late".into()).is_err());
7476 assert!(
7477 mounted_context(ExecutionPhase::Render)
7478 .with_view_id("view")
7479 .copy_text("render".into())
7480 .is_err()
7481 );
7482 assert!(
7483 mounted_context(ExecutionPhase::Event)
7484 .copy_text("unbound".into())
7485 .is_err()
7486 );
7487 context
7488 .runtime()
7489 .borrow_mut()
7490 .replace_origin(crate::InvocationOrigin::Automation);
7491 assert!(context.copy_text("x".repeat(16 * 1024 * 1024 + 1)).is_err());
7492 }
7493
7494 #[test]
7495 fn host_motion_preference_changes_without_replacing_runtime_state() {
7496 let mut runtime = UiRuntimeState::new();
7497 runtime.motions = crate::MotionRuntime::new(crate::MotionPreference::Normal);
7498 runtime.responsive.update_window("main", 480.0).unwrap();
7499
7500 assert!(!runtime.set_motion_preference_from_host(crate::MotionPreference::Normal));
7501 assert!(runtime.set_motion_preference_from_host(crate::MotionPreference::Reduced));
7502 assert_eq!(
7503 runtime.motions.preference(),
7504 crate::MotionPreference::Reduced
7505 );
7506 assert_eq!(
7507 runtime.responsive.class("main"),
7508 crate::ViewportClass::Compact
7509 );
7510 assert!(runtime.set_motion_preference_from_host(crate::MotionPreference::None));
7511 assert_eq!(runtime.motions.preference(), crate::MotionPreference::None);
7512 }
7513
7514 #[test]
7515 fn host_can_register_a_new_native_collection_after_mount() {
7516 let mut runtime = UiRuntimeState::new();
7517 let root = ComponentInstancePath::root("View", "live");
7518 assert!(
7519 runtime
7520 .native_collections
7521 .read_tracked(&root, "live_rows")
7522 .is_err()
7523 );
7524 let collection = crate::NativeCollection::new(
7525 "id",
7526 [BTreeMap::from([(
7527 "id".to_owned(),
7528 UiValue::String("row-1".to_owned()),
7529 )])],
7530 )
7531 .unwrap();
7532 runtime
7533 .register_native_collection_from_host(&root, "live_rows", collection)
7534 .unwrap();
7535 assert!(runtime.has_window_dirty(&root));
7536 assert!(matches!(
7537 runtime.register_native_collection_from_host(
7538 &root,
7539 "live_rows",
7540 crate::NativeCollection::new("id", std::iter::empty::<BTreeMap<String, UiValue>>())
7541 .unwrap(),
7542 ),
7543 Err(crate::NativeCollectionError::DuplicateCollection(_))
7544 ));
7545 }
7546}