Skip to main content

gpui_rhai/
app.rs

1use std::borrow::Cow;
2use std::cell::{Cell, RefCell};
3use std::collections::{BTreeMap, BTreeSet};
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7use std::time::{Duration, Instant};
8
9use gpui::KeyBinding;
10use gpui::actions;
11use gpui::{
12    AnyElement, AnyWindowHandle, App, AppContext, Bounds, Context, DispatchPhase, Element,
13    ElementId, Entity, FocusHandle, Global, GlobalElementId, InspectorElementId,
14    InteractiveElement, IntoElement, LayoutId, MouseButton, MouseDownEvent, ParentElement, Pixels,
15    Render, Role, ScrollAnchor, ScrollHandle, SharedString, StatefulInteractiveElement, Styled,
16    Subscription, Task, TitlebarOptions, Window, WindowAppearance, WindowBounds, WindowOptions,
17    deferred, div, px, rgba, size,
18};
19use thiserror::Error;
20
21#[cfg(feature = "dev-reload")]
22use crate::FileWatcher;
23use crate::overlay_element::WindowOverlayCoordinator;
24use crate::{
25    ActionError, ActionId, AppManifest, AssetData, AssetId, AssetRegistry, CapabilityError,
26    CompiledUi, ComponentExportError, ComponentInstancePath, ComponentRegistry,
27    ComponentStateSchema, ComponentStyleError, ComponentStyleSheet, DependencyError, Diagnostic,
28    DirectoryAssetProvider, DispatchScriptAction, EmbeddedScriptSource, FileScriptSource,
29    GpuiNodeRenderer, InMemoryAssetProvider, InteractionState, KeyBindingSpec, LocaleBundle,
30    LocaleManager, ModuleCompileCache, ModuleId, MotionPreference, MotionRuntime,
31    NodeEventDispatcher, PrimitiveRegistry, ResponsiveError, ResponsiveRuntime,
32    RestrictedModuleResolver, RuntimeEngine, RuntimeError, ScriptCallback, ScriptLifecycle,
33    ScriptSource, ScriptWindowSpec, SystemAppearance, TextDirection, ThemeManager, ThemeSelection,
34    ThemeSnapshot, ThemeTokenOverrides, ThemeVariant, UiRuntimeState, UiValue, ViewportBreakpoints,
35    WindowCommand, WindowCommandPolicy, init_text_area, init_text_input, load_component_styles,
36    load_locale_source,
37};
38
39#[cfg(feature = "dev-reload")]
40actions!(gpui_rhai_devtools, [ToggleInspector]);
41actions!(gpui_rhai_host, [CopySelectedText, NavigateBack]);
42
43const HOST_KEY_CONTEXT: &str = "GPUIRhaiHost";
44
45type InteractionContractSnapshots =
46    BTreeMap<crate::interaction::InteractionOwner, Option<crate::interaction::InteractionContract>>;
47
48#[derive(Default)]
49struct ScriptRuntimeInstallation {
50    bindings: BTreeMap<(String, Option<String>), ActionId>,
51    loaded_fonts: BTreeSet<u64>,
52    window_command_owners: BTreeMap<gpui::WindowId, (std::rc::Weak<()>, String)>,
53}
54
55impl Global for ScriptRuntimeInstallation {}
56
57thread_local! {
58    static FONT_NAMES: RefCell<Option<(usize, Rc<BTreeSet<String>>)>> =
59        const { RefCell::new(None) };
60}
61
62/// The font families the text system can resolve, cached per set of fonts
63/// loaded through the runtime.
64fn available_font_names(cx: &App) -> Rc<BTreeSet<String>> {
65    let loaded = cx
66        .try_global::<ScriptRuntimeInstallation>()
67        .map_or(0, |installation| installation.loaded_fonts.len());
68    FONT_NAMES.with(|cache| {
69        let mut cache = cache.borrow_mut();
70        if let Some((key, names)) = cache.as_ref()
71            && *key == loaded
72        {
73            return Rc::clone(names);
74        }
75        let names = Rc::new(cx.text_system().all_font_names().into_iter().collect());
76        *cache = Some((loaded, Rc::clone(&names)));
77        names
78    })
79}
80
81/// Install GPUI Rhai's application-wide input actions once.
82pub fn install(cx: &mut App) {
83    if cx.has_global::<ScriptRuntimeInstallation>() {
84        return;
85    }
86    init_text_input(cx);
87    init_text_area(cx);
88    crate::init_document_view(cx);
89    crate::markdown_view::init_markdown_view(cx);
90    cx.bind_keys([KeyBinding::new(
91        "cmd-c",
92        CopySelectedText,
93        Some(HOST_KEY_CONTEXT),
94    )]);
95    cx.set_global(ScriptRuntimeInstallation::default());
96}
97
98#[derive(Clone, Debug)]
99#[allow(clippy::struct_excessive_bools)]
100pub struct ScriptViewConfig {
101    view_id: String,
102    paint_background: bool,
103    show_error_banner: bool,
104    window_drag_areas: bool,
105    error_reporting: ErrorReporting,
106    render_islands: Option<bool>,
107    /// What the width of the view's root follows: its content (by default),
108    /// its window, as [`ScriptApplication`] and script windows lay it out, or
109    /// the Host ([`Self::host_sets_width`]).
110    root_width: RootWidth,
111    focus_indicators: FocusIndicators,
112}
113
114/// When a view shows focus indicators: the focus frame of a focused control or
115/// container, the keyboard cursor of a list, a focused handle's color. A text
116/// field that holds focus always shows its frame, since typing goes there.
117#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
118pub enum FocusIndicators {
119    /// After a navigation key (Tab, Shift+Tab, an arrow, Home, End, Page Up,
120    /// Page Down, F6) until the next pointer press, as a browser's
121    /// `:focus-visible`. A key with Command, Control or Alt, a shortcut, does
122    /// not show them.
123    #[default]
124    Navigation,
125    /// Whenever a node holds focus.
126    Always,
127    /// Never, for an application driven by shortcuts rather than by moving
128    /// focus.
129    Never,
130}
131
132/// A new failure of a mounted view, as [`ScriptViewConfig::on_error`] passes it.
133#[derive(Clone, Debug)]
134pub struct ScriptErrorReport {
135    pub domain: ScriptErrorDomain,
136    /// The view, or the script window it opened, that failed.
137    pub view_id: String,
138    /// What [`ScriptViewHandle::last_error`] returns for it.
139    pub message: String,
140    /// What [`ScriptViewHandle::last_diagnostic`] returns for it; `None` for
141    /// a Host error.
142    pub diagnostic: Option<Diagnostic>,
143    /// Recoverable native presentation context; does not set `last_error`.
144    pub presentation: Option<crate::PresentationDiagnostic>,
145}
146
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
148pub enum ScriptErrorDomain {
149    Transaction,
150    Presentation,
151}
152
153type ErrorCallback = dyn Fn(&ScriptErrorReport, &mut App);
154
155#[derive(Clone)]
156struct ErrorObserver(Rc<ErrorCallback>);
157
158impl std::fmt::Debug for ErrorObserver {
159    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        formatter.write_str("ErrorObserver")
161    }
162}
163
164/// How a view reports a new failure beyond its banner and `last_error`.
165#[derive(Clone, Debug, Default)]
166struct ErrorReporting {
167    observer: Option<ErrorObserver>,
168    stderr: bool,
169}
170
171impl ScriptViewConfig {
172    #[must_use]
173    pub fn new(view_id: impl Into<String>) -> Self {
174        Self {
175            view_id: view_id.into(),
176            paint_background: false,
177            show_error_banner: true,
178            window_drag_areas: false,
179            error_reporting: ErrorReporting::default(),
180            render_islands: None,
181            root_width: RootWidth::Content,
182            focus_indicators: FocusIndicators::Navigation,
183        }
184    }
185
186    #[must_use]
187    pub const fn paint_background(mut self, paint: bool) -> Self {
188        self.paint_background = paint;
189        self
190    }
191
192    /// Control the built-in selectable runtime-error banner for this view.
193    ///
194    /// Hosts that disable it must surface [`ScriptViewHandle::last_error`]
195    /// themselves so failed candidates are not silent.
196    #[must_use]
197    pub const fn show_error_banner(mut self, show: bool) -> Self {
198        self.show_error_banner = show;
199        self
200    }
201
202    /// Call `observer` once for each new failure of this view: the render,
203    /// callback, delivery, effect or reload error that
204    /// [`ScriptViewHandle::last_error`] then reports. It runs on the
205    /// foreground after the frame that presents the failure, so it may read
206    /// the handle; several failures before that frame report the latest, as
207    /// `last_error` does. Recoverable image errors also report here with
208    /// `domain == Presentation`, deduplicated and bounded to 256 active entries
209    /// per view; they do not change `last_error` or roll back a transaction.
210    /// Script windows the view opens report through it too.
211    #[must_use]
212    pub fn on_error(mut self, observer: impl Fn(&ScriptErrorReport, &mut App) + 'static) -> Self {
213        self.error_reporting.observer = Some(ErrorObserver(Rc::new(observer)));
214        self
215    }
216
217    /// Also print each new failure to stderr, as
218    /// ``gpui-rhai: view `id`: message``, so an unattended run fails loudly.
219    /// Off for an embedded view; [`ScriptApplication`] turns it on.
220    #[must_use]
221    pub const fn mirror_errors_to_stderr(mut self, mirror: bool) -> Self {
222        self.error_reporting.stderr = mirror;
223        self
224    }
225
226    /// Let `window_drag_area()` nodes in this view move the window. Off by
227    /// default, so an embedded view cannot turn its content into a window
228    /// control surface; a Host that draws its own title bar (a transparent
229    /// `TitlebarOptions`) turns it on for the view that renders the bar.
230    #[must_use]
231    pub const fn window_drag_areas(mut self, enabled: bool) -> Self {
232        self.window_drag_areas = enabled;
233        self
234    }
235
236    /// Whether frames replay the unchanged parts of the view instead of
237    /// building them again (on by default). Turning it off renders every
238    /// frame in full, as 0.3.2 did, which also
239    /// `GPUI_RHAI_RENDER_ISLANDS=off` does for every view. Script windows
240    /// the view opens follow it.
241    #[must_use]
242    pub const fn render_islands(mut self, enabled: bool) -> Self {
243        self.render_islands = Some(enabled);
244        self
245    }
246
247    /// Tell the view that the Host lays it out at a width its content does
248    /// not change, as when it fills a window or a pane the Host sizes. Frames
249    /// then also replay the unchanged subtrees whose width follows the
250    /// view's, which they cannot otherwise tell from content. Off by default;
251    /// [`ScriptApplication`] windows are laid out so.
252    #[must_use]
253    pub const fn host_sets_width(mut self, fixed: bool) -> Self {
254        self.root_width = if fixed {
255            RootWidth::Host
256        } else {
257            RootWidth::Content
258        };
259        self
260    }
261
262    const fn fills_window(mut self) -> Self {
263        self.root_width = RootWidth::Window;
264        self
265    }
266
267    /// When the view shows focus indicators; [`FocusIndicators::Navigation`]
268    /// by default. Script windows the view opens follow it.
269    #[must_use]
270    pub const fn focus_indicators(mut self, indicators: FocusIndicators) -> Self {
271        self.focus_indicators = indicators;
272        self
273    }
274
275    #[must_use]
276    pub fn view_id(&self) -> &str {
277        &self.view_id
278    }
279}
280
281#[derive(Clone)]
282pub struct ScriptViewHost {
283    inner: Rc<RefCell<ScriptViewHostState>>,
284}
285
286struct ScriptViewHostState {
287    window_id: String,
288    overlays: WindowOverlayCoordinator,
289    interactions: crate::interaction::WindowInteractionCoordinator,
290    interaction_lifecycle: Entity<HostInteractionLifecycle>,
291    fallback_focus: FocusHandle,
292    views: BTreeMap<String, HostViewRegistration>,
293    pending_focus_recovery: Vec<FocusHandle>,
294    overlay_viewport: Option<crate::OverlayBounds>,
295    native_window: Option<AnyWindowHandle>,
296    window_command_owner: Option<NativeWindowCommandOwner>,
297    frame_active: bool,
298    container_bounds: Option<Bounds<Pixels>>,
299    #[allow(dead_code)]
300    escape_interceptor: Option<Subscription>,
301    #[allow(dead_code)]
302    keystroke_observer: Option<Subscription>,
303}
304
305struct HostInteractionLifecycle {
306    interactions: crate::interaction::WindowInteractionCoordinator,
307    activation: Option<Subscription>,
308}
309
310struct NativeWindowCommandOwner {
311    view_id: String,
312    _lease: Rc<()>,
313}
314
315struct HostViewRegistration {
316    focus: FocusHandle,
317    lease: Rc<()>,
318    entity: Option<gpui::WeakEntity<ScriptHostView>>,
319}
320
321#[derive(Clone)]
322struct NativeWindowAuthority {
323    window: gpui::WindowId,
324    lease: std::rc::Weak<()>,
325}
326
327impl NativeWindowAuthority {
328    fn is_current(&self, cx: &App) -> bool {
329        self.lease.strong_count() > 0
330            && cx
331                .windows()
332                .iter()
333                .any(|window| window.window_id() == self.window)
334            && cx
335                .global::<ScriptRuntimeInstallation>()
336                .window_command_owners
337                .get(&self.window)
338                .is_some_and(|(lease, _)| lease.ptr_eq(&self.lease))
339    }
340}
341
342impl ScriptViewHost {
343    /// Create a themed scrollbar factory for a Host-native surface. `scope`
344    /// identifies that surface within this Host and must be stable and unique.
345    /// Render it under [`Self::container`] so disappearance and window input
346    /// cancel gestures through the Host's shared interaction lifecycle.
347    ///
348    /// # Errors
349    ///
350    /// Returns [`ScriptViewError::InvalidId`] for an unsafe scope identifier.
351    pub fn scrollbars(
352        &self,
353        scope: &str,
354        theme: &crate::PrimitiveTheme,
355    ) -> Result<crate::ScrollbarContext, ScriptViewError> {
356        validate_view_id(scope)?;
357        Ok(crate::ScrollbarContext::new(
358            crate::interaction::InteractionOwner::new(format!("host:{scope}"), "scrollbars"),
359            self.interactions(),
360            theme,
361        ))
362    }
363
364    /// Create one interaction/overlay domain, normally one per GPUI window.
365    ///
366    /// # Errors
367    ///
368    /// Returns [`ScriptViewError::InvalidId`] for an unsafe window identifier.
369    pub fn new(window_id: impl Into<String>, cx: &mut App) -> Result<Self, ScriptViewError> {
370        install(cx);
371        let window_id = window_id.into();
372        validate_view_id(&window_id)?;
373        let interactions = crate::interaction::WindowInteractionCoordinator::default();
374        let interaction_lifecycle = cx.new(|_| HostInteractionLifecycle {
375            interactions: interactions.clone(),
376            activation: None,
377        });
378        let inner = Rc::new(RefCell::new(ScriptViewHostState {
379            window_id,
380            overlays: WindowOverlayCoordinator::default(),
381            interactions,
382            interaction_lifecycle,
383            fallback_focus: cx.focus_handle(),
384            views: BTreeMap::new(),
385            pending_focus_recovery: Vec::new(),
386            overlay_viewport: None,
387            native_window: None,
388            window_command_owner: None,
389            frame_active: false,
390            container_bounds: None,
391            escape_interceptor: None,
392            keystroke_observer: None,
393        }));
394        let weak = Rc::downgrade(&inner);
395        let interceptor = cx.intercept_keystrokes(move |event, window, cx| {
396            DISPATCHING_KEYSTROKE.with(|current| current.replace(Some(event.keystroke.clone())));
397            if event.keystroke.key.as_str() != "escape" {
398                return;
399            }
400            let Some(state) = weak.upgrade() else {
401                return;
402            };
403            let interactions = state.borrow().interactions.clone();
404            if interactions.cancel_window(window, cx) {
405                cx.stop_propagation();
406            }
407        });
408        inner.borrow_mut().escape_interceptor = Some(interceptor);
409        // Observers run once the keystroke's dispatch has ended.
410        inner.borrow_mut().keystroke_observer = Some(cx.observe_keystrokes(|_, _, _| {
411            DISPATCHING_KEYSTROKE.with(|current| current.replace(None));
412        }));
413        Ok(Self { inner })
414    }
415
416    #[must_use]
417    pub fn window_id(&self) -> String {
418        self.inner.borrow().window_id.clone()
419    }
420
421    /// The native window this Host's views are mounted in, once one is.
422    pub(crate) fn native_window(&self) -> Option<AnyWindowHandle> {
423        self.inner.borrow().native_window
424    }
425
426    /// Restrict this Host's overlays to an explicit absolute rectangle.
427    ///
428    /// # Errors
429    ///
430    /// Returns [`ScriptViewError::Overlay`] for invalid geometry.
431    pub fn set_overlay_viewport(
432        &self,
433        viewport: crate::OverlayBounds,
434    ) -> Result<(), ScriptViewError> {
435        crate::OverlayManager::new(viewport)?;
436        self.inner.borrow_mut().overlay_viewport = Some(viewport);
437        Ok(())
438    }
439
440    pub fn use_window_overlay_viewport(&self) {
441        self.inner.borrow_mut().overlay_viewport = None;
442    }
443
444    /// The placement of the overlay a view rendered with this script key, as
445    /// of the last frame; `None` while it is closed or not rendered.
446    ///
447    /// # Errors
448    ///
449    /// Returns [`crate::OverlayLookupError::Ambiguous`] when several component
450    /// instances in the view declare an overlay with this key; name one with
451    /// [`Self::overlay_placement_in`].
452    pub fn overlay_placement(
453        &self,
454        view_id: &str,
455        local_id: &str,
456    ) -> Result<Option<crate::PlacementResult>, crate::OverlayLookupError> {
457        let found = self.inner.borrow().overlays.placements(
458            view_id,
459            None,
460            &crate::OverlayId::new(local_id),
461        );
462        match found.as_slice() {
463            [] => Ok(None),
464            [(_, placement)] => Ok(*placement),
465            _ => Err(crate::OverlayLookupError::Ambiguous {
466                view_id: view_id.to_owned(),
467                key: local_id.to_owned(),
468                instances: found
469                    .iter()
470                    .map(|(owner, _)| owner.clone().unwrap_or_default())
471                    .collect(),
472            }),
473        }
474    }
475
476    /// The placement of the overlay that one component instance declared with
477    /// this key, as of the last frame. `component` is the instance path as
478    /// diagnostics print it (`/View[main]/Filter[eu]/Select[region]`).
479    #[must_use]
480    pub fn overlay_placement_in(
481        &self,
482        view_id: &str,
483        component: &str,
484        local_id: &str,
485    ) -> Option<crate::PlacementResult> {
486        self.inner
487            .borrow()
488            .overlays
489            .placements(view_id, Some(component), &crate::OverlayId::new(local_id))
490            .into_iter()
491            .find_map(|(_, placement)| placement)
492    }
493
494    /// The script overlays open in this Host's views as of the last frame,
495    /// bottom to top: the last entry is the topmost. Escape closes the last
496    /// one with `dismiss_on_escape`; a modal holds focus while it is the
497    /// topmost modal. Overlays declared inside components are listed too
498    /// (a Select's `<key>-combobox`, a Dialog in a third-party widget), with
499    /// the declaring instance in `owner`. Read it from an action handler or
500    /// from the Host's `render`, before the container lays out: while the
501    /// container lays out and prepaints, the list is being rebuilt.
502    #[must_use]
503    pub fn open_overlays(&self) -> Vec<crate::OpenOverlay> {
504        self.inner.borrow().overlays.open_overlays()
505    }
506
507    /// Close the topmost script overlay that Escape closes, as the
508    /// [`Self::container`]'s Escape handler does, and report whether one took
509    /// the key. An App-level Escape binding, which GPUI dispatches before any
510    /// key-down listener, calls this first and handles Escape itself only when
511    /// it returns `false`.
512    pub fn dismiss_escape(&self, window: &mut Window, cx: &mut App) -> bool {
513        self.overlays().dismiss_escape(window, cx)
514    }
515
516    /// Visible controlled scopes. Only the focused scope is eligible for Back.
517    #[must_use]
518    pub fn navigation_stacks(&self, window: &Window, cx: &App) -> Vec<crate::NavigationStackInfo> {
519        let entities = self
520            .inner
521            .borrow()
522            .views
523            .values()
524            .filter_map(|view| view.entity.clone())
525            .collect::<Vec<_>>();
526        entities
527            .into_iter()
528            .filter_map(|entity| entity.upgrade())
529            .flat_map(|entity| entity.read(cx).navigation_stacks(window, cx))
530            .collect()
531    }
532
533    /// Propose a pop to the deepest focused inner stack. False lets the Host
534    /// perform its outer Back. Ignored/rejected proposals still own Back.
535    pub fn navigate_back(&self, window: &mut Window, cx: &mut App) -> bool {
536        let entities = self
537            .inner
538            .borrow()
539            .views
540            .values()
541            .filter_map(|view| view.entity.clone())
542            .collect::<Vec<_>>();
543        for entity in entities.into_iter().filter_map(|entity| entity.upgrade()) {
544            if entity.update(cx, |view, cx| {
545                view.propose_navigation_back("host", window, cx)
546            }) {
547                return true;
548            }
549        }
550        false
551    }
552
553    /// Bind host-approved script actions once at App scope.
554    ///
555    /// # Errors
556    ///
557    /// Returns a conflict when another binding already owns the same keys and
558    /// context, or an invalid-key error from GPUI conversion.
559    pub fn bind_keys(
560        &self,
561        bindings: impl IntoIterator<Item = KeyBindingSpec>,
562        cx: &mut App,
563    ) -> Result<(), ScriptViewError> {
564        install(cx);
565        let bindings = bindings.into_iter().collect::<Vec<_>>();
566        let converted = bindings
567            .iter()
568            .map(|binding| binding.to_gpui(cx))
569            .collect::<Result<Vec<_>, _>>()?;
570        let mut new = Vec::new();
571        {
572            let installed = cx.global_mut::<ScriptRuntimeInstallation>();
573            for (index, binding) in bindings.iter().enumerate() {
574                let key = (binding.keystrokes.clone(), binding.context.clone());
575                if let Some(existing) = installed.bindings.get(&key)
576                    && existing != &binding.action
577                {
578                    return Err(ScriptViewError::KeyBindingConflict {
579                        keystrokes: binding.keystrokes.clone(),
580                        context: binding.context.clone(),
581                        existing: existing.clone(),
582                        requested: binding.action.clone(),
583                    });
584                }
585                if let std::collections::btree_map::Entry::Vacant(entry) =
586                    installed.bindings.entry(key)
587                {
588                    entry.insert(binding.action.clone());
589                    new.push(index);
590                }
591            }
592        }
593        cx.bind_keys(new.into_iter().map(|index| converted[index].clone()));
594        Ok(())
595    }
596
597    #[must_use]
598    pub fn container(&self, child: impl IntoElement) -> AnyElement {
599        let (fallback, overlays) = {
600            let state = self.inner.borrow();
601            (state.fallback_focus.clone(), state.overlays.clone())
602        };
603        let escape_overlays = overlays.clone();
604        let child = div()
605            .size_full()
606            .track_focus(&fallback)
607            .on_key_down(move |event, window, cx| {
608                if event.keystroke.key.as_str() == "escape"
609                    && escape_overlays.dismiss_escape(window, cx)
610                {
611                    cx.stop_propagation();
612                }
613            })
614            .child(child)
615            .child(SharedLayerPortalElement {
616                coordinator: overlays,
617            })
618            .into_any_element();
619        ScriptViewHostFrame {
620            host: self.clone(),
621            child: Some(child),
622        }
623        .into_any_element()
624    }
625
626    fn reserve_view(&self, view_id: &str) -> Result<std::rc::Weak<()>, ScriptViewError> {
627        validate_view_id(view_id)?;
628        let mut state = self.inner.borrow_mut();
629        if state.views.contains_key(view_id) {
630            return Err(ScriptViewError::DuplicateView(view_id.to_owned()));
631        }
632        let fallback = state.fallback_focus.clone();
633        let lease = Rc::new(());
634        let weak = Rc::downgrade(&lease);
635        state.views.insert(
636            view_id.to_owned(),
637            HostViewRegistration {
638                focus: fallback,
639                lease,
640                entity: None,
641            },
642        );
643        Ok(weak)
644    }
645
646    fn attach_view_focus(&self, view_id: &str, focus: FocusHandle) {
647        if let Some(entry) = self.inner.borrow_mut().views.get_mut(view_id) {
648            entry.focus = focus;
649        }
650    }
651
652    fn bind_window(
653        &self,
654        view_id: &str,
655        handle: AnyWindowHandle,
656        policy: WindowCommandPolicy,
657        cx: &mut App,
658    ) -> Result<Option<NativeWindowAuthority>, ScriptViewError> {
659        let mut state = self.inner.borrow_mut();
660        if state
661            .native_window
662            .is_some_and(|previous| previous.window_id() != handle.window_id())
663        {
664            return Err(ScriptViewError::WrongNativeWindow(state.window_id.clone()));
665        }
666        if policy == WindowCommandPolicy::ApplicationOwned {
667            if let Some(owner) = &state.window_command_owner {
668                return Err(ScriptViewError::WindowCommandOwner {
669                    window: state.window_id.clone(),
670                    owner: owner.view_id.clone(),
671                });
672            }
673            let owners = &mut cx
674                .global_mut::<ScriptRuntimeInstallation>()
675                .window_command_owners;
676            owners.retain(|_, (lease, _)| lease.strong_count() > 0);
677            if let Some((_, owner)) = owners.get(&handle.window_id()) {
678                return Err(ScriptViewError::WindowCommandOwner {
679                    window: state.window_id.clone(),
680                    owner: owner.clone(),
681                });
682            }
683            let lease = Rc::clone(&state.views[view_id].lease);
684            owners.insert(
685                handle.window_id(),
686                (Rc::downgrade(&lease), view_id.to_owned()),
687            );
688            state.window_command_owner = Some(NativeWindowCommandOwner {
689                view_id: view_id.to_owned(),
690                _lease: lease,
691            });
692        }
693        state.native_window = Some(handle);
694        Ok(
695            (policy == WindowCommandPolicy::ApplicationOwned).then(|| NativeWindowAuthority {
696                window: handle.window_id(),
697                lease: Rc::downgrade(&state.views[view_id].lease),
698            }),
699        )
700    }
701
702    fn unregister_view(&self, view_id: &str, lease: &std::rc::Weak<()>) {
703        let mut state = self.inner.borrow_mut();
704        if state
705            .views
706            .get(view_id)
707            .is_none_or(|current| !Rc::downgrade(&current.lease).ptr_eq(lease))
708        {
709            return;
710        }
711        if state
712            .window_command_owner
713            .as_ref()
714            .is_some_and(|owner| owner.view_id == view_id)
715        {
716            state.window_command_owner = None;
717        }
718        if let Some(registration) = state.views.remove(view_id) {
719            state.pending_focus_recovery.push(registration.focus);
720        }
721        state.overlays.remove_view(view_id);
722        state.interactions.discard_view(view_id);
723    }
724
725    fn quiesce_view(&self, view_id: &str, focus: &FocusHandle, window: &mut Window, cx: &mut App) {
726        let (fallback, overlays, interactions) = {
727            let state = self.inner.borrow();
728            (
729                state.fallback_focus.clone(),
730                state.overlays.clone(),
731                state.interactions.clone(),
732            )
733        };
734        if focus.contains_focused(window, cx) {
735            fallback.focus(window, cx);
736        }
737        overlays.remove_view(view_id);
738        interactions.cancel_view(view_id, window, cx);
739    }
740
741    fn overlays(&self) -> WindowOverlayCoordinator {
742        self.inner.borrow().overlays.clone()
743    }
744
745    fn interactions(&self) -> crate::interaction::WindowInteractionCoordinator {
746        self.inner.borrow().interactions.clone()
747    }
748
749    fn frame_active(&self) -> bool {
750        self.inner.borrow().frame_active
751    }
752}
753
754fn validate_view_id(id: &str) -> Result<(), ScriptViewError> {
755    let valid = (1..=64).contains(&id.len())
756        && id
757            .chars()
758            .next()
759            .is_some_and(|character| character.is_ascii_alphanumeric())
760        && id
761            .chars()
762            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'));
763    if valid {
764        Ok(())
765    } else {
766        Err(ScriptViewError::InvalidId(id.to_owned()))
767    }
768}
769
770struct ScriptViewHostFrame {
771    host: ScriptViewHost,
772    child: Option<AnyElement>,
773}
774
775thread_local! {
776    /// The keystroke GPUI is dispatching, from the Host's interceptor (which
777    /// runs before key bindings) until its keystroke observers run.
778    static DISPATCHING_KEYSTROKE: RefCell<Option<gpui::Keystroke>> = const { RefCell::new(None) };
779}
780
781/// The keystroke being dispatched, if a key dispatch is under way.
782pub(crate) fn dispatching_keystroke() -> Option<gpui::Keystroke> {
783    DISPATCHING_KEYSTROKE.with(|current| current.borrow().clone())
784}
785
786/// Bumped each time a host frame lays out and read by every runtime view's
787/// render. gpui-fast draws a view again from its last frame while nothing it
788/// read changed; a view that reads this is never drawn from a frame older than
789/// the host frame around it, whose layout clears the window registries the
790/// view's prepaint fills. Under gpui-pre it is an unobserved global.
791#[derive(Default)]
792pub(crate) struct HostFrameEpoch(u64);
793
794impl gpui::Global for HostFrameEpoch {}
795
796pub(crate) fn read_host_frame_epoch(cx: &App) {
797    let _ = cx.try_global::<HostFrameEpoch>();
798}
799
800impl Element for ScriptViewHostFrame {
801    type RequestLayoutState = AnyElement;
802    type PrepaintState = ();
803
804    fn id(&self) -> Option<ElementId> {
805        None
806    }
807
808    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
809        None
810    }
811
812    fn request_layout(
813        &mut self,
814        _id: Option<&GlobalElementId>,
815        _inspector_id: Option<&InspectorElementId>,
816        window: &mut Window,
817        cx: &mut App,
818    ) -> (LayoutId, Self::RequestLayoutState) {
819        let lifecycle = self.host.inner.borrow().interaction_lifecycle.clone();
820        lifecycle.update(cx, |lifecycle, cx| {
821            if lifecycle.activation.is_none() {
822                lifecycle.activation = Some(cx.observe_window_activation(
823                    window,
824                    |lifecycle, window, cx| {
825                        if !window.is_window_active() {
826                            lifecycle.interactions.cancel_window(window, cx);
827                        }
828                    },
829                ));
830            }
831        });
832        let (overlays, viewport, fallback, pending) = {
833            let mut state = self.host.inner.borrow_mut();
834            state.frame_active = true;
835            let viewport = state
836                .overlay_viewport
837                .unwrap_or_else(|| crate::OverlayBounds {
838                    x: 0.0,
839                    y: 0.0,
840                    width: f64::from(window.viewport_size().width),
841                    height: f64::from(window.viewport_size().height),
842                });
843            (
844                state.overlays.clone(),
845                viewport,
846                state.fallback_focus.clone(),
847                std::mem::take(&mut state.pending_focus_recovery),
848            )
849        };
850        let epoch = cx.default_global::<HostFrameEpoch>();
851        epoch.0 = epoch.0.wrapping_add(1);
852        overlays.begin_host_frame(viewport);
853        self.host.interactions().begin_frame();
854        if pending
855            .iter()
856            .any(|focus| focus.contains_focused(window, cx))
857        {
858            fallback.focus(window, cx);
859        }
860        let mut child = self.child.take().expect("host frame lays out once");
861        let layout = child.request_layout(window, cx);
862        (layout, child)
863    }
864
865    fn prepaint(
866        &mut self,
867        _id: Option<&GlobalElementId>,
868        _inspector_id: Option<&InspectorElementId>,
869        bounds: Bounds<Pixels>,
870        child: &mut Self::RequestLayoutState,
871        window: &mut Window,
872        cx: &mut App,
873    ) {
874        self.host.inner.borrow_mut().container_bounds = Some(bounds);
875        child.prepaint(window, cx);
876    }
877
878    fn paint(
879        &mut self,
880        _id: Option<&GlobalElementId>,
881        _inspector_id: Option<&InspectorElementId>,
882        _bounds: Bounds<Pixels>,
883        child: &mut Self::RequestLayoutState,
884        _prepaint: &mut Self::PrepaintState,
885        window: &mut Window,
886        cx: &mut App,
887    ) {
888        // Event boundaries, unlike prepaint side effects, are replayed by a
889        // cached native child. Collect its body regions anew for each wheel.
890        self.host.interactions().install_wheel_capture_start(window);
891        child.paint(window, cx);
892        self.host.inner.borrow_mut().frame_active = false;
893        let (overlays, interactions, container_bounds) = {
894            let state = self.host.inner.borrow();
895            (
896                state.overlays.clone(),
897                state.interactions.clone(),
898                state.container_bounds,
899            )
900        };
901        interactions.finish_frame(window, cx);
902        interactions.install(window);
903        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
904            if phase == DispatchPhase::Capture
905                && container_bounds.is_some_and(|bounds| bounds.contains(&event.position))
906            {
907                let _ = overlays.dismiss_outside(event.position, window, cx);
908            }
909        });
910    }
911}
912
913impl IntoElement for ScriptViewHostFrame {
914    type Element = Self;
915
916    fn into_element(self) -> Self::Element {
917        self
918    }
919}
920
921struct SharedLayerPortalElement {
922    coordinator: WindowOverlayCoordinator,
923}
924
925impl Element for SharedLayerPortalElement {
926    type RequestLayoutState = AnyElement;
927    type PrepaintState = ();
928
929    fn id(&self) -> Option<ElementId> {
930        None
931    }
932
933    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
934        None
935    }
936
937    fn request_layout(
938        &mut self,
939        _id: Option<&GlobalElementId>,
940        _inspector_id: Option<&InspectorElementId>,
941        window: &mut Window,
942        cx: &mut App,
943    ) -> (LayoutId, Self::RequestLayoutState) {
944        let viewport = self.coordinator.viewport_or_window(window.viewport_size());
945        let layers = self.coordinator.take_layer_elements();
946        let mut layer = deferred(
947            div()
948                .absolute()
949                .left(pixel_from_f64(viewport.x))
950                .top(pixel_from_f64(viewport.y))
951                .w(pixel_from_f64(viewport.width))
952                .h(pixel_from_f64(viewport.height))
953                .children(layers),
954        )
955        .with_priority(9_000)
956        .into_any_element();
957        let layout = layer.request_layout(window, cx);
958        (layout, layer)
959    }
960
961    fn prepaint(
962        &mut self,
963        _id: Option<&GlobalElementId>,
964        _inspector_id: Option<&InspectorElementId>,
965        _bounds: Bounds<Pixels>,
966        layer: &mut Self::RequestLayoutState,
967        window: &mut Window,
968        cx: &mut App,
969    ) {
970        layer.prepaint(window, cx);
971    }
972
973    fn paint(
974        &mut self,
975        _id: Option<&GlobalElementId>,
976        _inspector_id: Option<&InspectorElementId>,
977        _bounds: Bounds<Pixels>,
978        layer: &mut Self::RequestLayoutState,
979        _prepaint: &mut Self::PrepaintState,
980        window: &mut Window,
981        cx: &mut App,
982    ) {
983        layer.paint(window, cx);
984    }
985}
986
987impl IntoElement for SharedLayerPortalElement {
988    type Element = Self;
989
990    fn into_element(self) -> Self::Element {
991        self
992    }
993}
994
995#[derive(Clone)]
996pub struct ScriptViewHandle(Rc<ScriptViewHandleInner>);
997
998#[derive(Clone, Copy, Debug, Eq, PartialEq)]
999pub enum ScriptViewState {
1000    Active,
1001    Suspended,
1002    Disposed,
1003}
1004
1005#[derive(Clone)]
1006pub struct ThemeHandle(Entity<ThemeHandleState>);
1007
1008struct ThemeHandleState {
1009    snapshot: ThemeSnapshot,
1010}
1011
1012impl ThemeHandleState {
1013    fn replace(&mut self, variant: ThemeVariant) -> bool {
1014        if self.snapshot.variant == variant {
1015            return false;
1016        }
1017        self.snapshot = ThemeSnapshot::new(self.snapshot.revision.saturating_add(1), variant);
1018        true
1019    }
1020}
1021
1022impl ThemeHandle {
1023    fn new(variant: ThemeVariant, cx: &mut App) -> Self {
1024        Self(cx.new(|_| ThemeHandleState {
1025            snapshot: ThemeSnapshot::new(1, variant),
1026        }))
1027    }
1028
1029    /// Read the latest effective theme without invoking Rhai.
1030    #[must_use]
1031    pub fn snapshot(&self, cx: &App) -> ThemeSnapshot {
1032        self.0.read(cx).snapshot.clone()
1033    }
1034
1035    /// Observe effective-theme changes from application-level host code.
1036    ///
1037    /// The returned subscription must be retained for as long as observation is
1038    /// required.
1039    pub fn observe(
1040        &self,
1041        cx: &mut App,
1042        mut on_change: impl FnMut(ThemeSnapshot, &mut App) + 'static,
1043    ) -> Subscription {
1044        cx.observe(&self.0, move |entity, cx| {
1045            let snapshot = entity.read(cx).snapshot.clone();
1046            on_change(snapshot, cx);
1047        })
1048    }
1049
1050    /// Observe effective-theme changes from another GPUI entity.
1051    ///
1052    /// This is the ergonomic path for Host-owned chrome: retain the returned
1053    /// subscription in the observing entity and redraw only that entity.
1054    pub fn observe_in<T: 'static>(
1055        &self,
1056        cx: &mut Context<T>,
1057        mut on_change: impl FnMut(&mut T, ThemeSnapshot, &mut Context<T>) + 'static,
1058    ) -> Subscription {
1059        cx.observe(&self.0, move |owner, entity, cx| {
1060            let snapshot = entity.read(cx).snapshot.clone();
1061            on_change(owner, snapshot, cx);
1062        })
1063    }
1064
1065    fn matches(&self, variant: &ThemeVariant, cx: &App) -> bool {
1066        &self.0.read(cx).snapshot.variant == variant
1067    }
1068
1069    fn publish(&self, variant: ThemeVariant, cx: &mut App) {
1070        self.0.update(cx, |state, cx| {
1071            if state.replace(variant) {
1072                cx.notify();
1073            }
1074        });
1075    }
1076}
1077
1078/// Drainable execution diagnostics for one mounted script view.
1079///
1080/// Taking a snapshot does not invoke Rhai or alter the mounted UI. Timings are
1081/// drained so benchmark samples never double-count earlier work.
1082#[derive(Clone, Debug)]
1083pub struct ScriptViewPerformanceSnapshot {
1084    pub timings: Vec<crate::ExecutionTiming>,
1085    pub virtual_collections: Vec<crate::VirtualCollectionMetrics>,
1086    pub retained_nodes: usize,
1087    pub dirty_components: usize,
1088    pub dirty_component_paths: Vec<String>,
1089    pub pending_virtual_requests: bool,
1090}
1091
1092/// Render and commit counters of one mounted view since the last
1093/// [`ScriptViewHandle::take_render_statistics`], for benchmarks and performance
1094/// tests. Not a stable interface: fields are added as the runtime counts more.
1095#[doc(hidden)]
1096#[derive(Clone, Debug, Default, PartialEq, Eq)]
1097#[non_exhaustive]
1098pub struct ScriptViewRenderStatistics {
1099    /// Frames that rendered the view.
1100    pub host_renders: u64,
1101    /// Time in the view's render, building its elements included.
1102    pub host_render_time: Duration,
1103    /// Time turning the retained tree into GPUI elements.
1104    pub build_time: Duration,
1105    /// Frames that walked the whole committed tree to sync primitive mounts,
1106    /// focus and scroll handles and page focus: frames after a commit.
1107    pub tree_walks: u64,
1108    /// Polls that ran script work: effects, virtual realization, dirty renders.
1109    pub polls: u64,
1110    /// Time in those polls, the application checkpoint included.
1111    pub poll_time: Duration,
1112    /// Trees committed.
1113    pub commits: u64,
1114    /// Time in each commit phase, summed over the commits, in the order the
1115    /// phases first ran.
1116    pub commit_phases: Vec<(&'static str, Duration)>,
1117    /// Nodes in the committed tree when the statistics were taken.
1118    pub retained_nodes: usize,
1119    /// Cache islands replayed from the frame before.
1120    pub island_hits: u64,
1121    /// Cache islands embedded cached that rendered.
1122    pub island_misses: u64,
1123    /// Cache islands rendered in place.
1124    pub island_uncached: u64,
1125    /// Cached island renders whose height differed from the pinned one.
1126    pub island_drift: u64,
1127}
1128
1129/// What a view committed and presented, for comparing two windows that run the
1130/// same script through the same events. Not a stable interface.
1131#[doc(hidden)]
1132#[derive(Clone, Debug, PartialEq)]
1133#[non_exhaustive]
1134pub struct ScriptViewFrameDigest {
1135    /// Nodes in the committed tree.
1136    pub retained_nodes: usize,
1137    /// Layout, visual and clip bounds of every presented node, in node order.
1138    pub geometry: Vec<(crate::NodeId, crate::ElementGeometry)>,
1139    /// The accessibility snapshot of the presented nodes.
1140    pub accessibility: Vec<crate::AccessibilityNode>,
1141    /// The focused node and its ancestors, innermost first.
1142    pub focus_path: Vec<crate::NodeId>,
1143    /// The offset of every scroll container.
1144    pub scroll_offsets: Vec<(crate::NodeId, [f32; 2])>,
1145    /// Every virtual collection's window, scroll position and policies.
1146    pub virtual_collections: Vec<crate::VirtualCollectionMetrics>,
1147    /// The view's last error.
1148    pub last_error: Option<String>,
1149}
1150
1151/// The committed tree (generation and revision) and the primitive
1152/// registrations the per-frame tree walks derived from.
1153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1154struct DerivedKey {
1155    generation: crate::ScriptGeneration,
1156    revision: u64,
1157    primitives: usize,
1158}
1159
1160struct ScriptViewHandleInner {
1161    entity: Entity<ScriptHostView>,
1162    theme: ThemeHandle,
1163    host: ScriptViewHost,
1164    view_id: String,
1165    state: Rc<Cell<ScriptViewState>>,
1166    measured_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
1167    mount_lease: std::rc::Weak<()>,
1168}
1169
1170impl Drop for ScriptViewHandleInner {
1171    fn drop(&mut self) {
1172        if self.state.get() != ScriptViewState::Disposed {
1173            self.host.unregister_view(&self.view_id, &self.mount_lease);
1174        }
1175    }
1176}
1177
1178impl ScriptViewHandle {
1179    fn require_not_disposed(&self) -> Result<ScriptViewState, ScriptViewError> {
1180        let state = self.0.state.get();
1181        if state == ScriptViewState::Disposed {
1182            Err(ScriptViewError::DisposedView(self.0.view_id.clone()))
1183        } else {
1184            Ok(state)
1185        }
1186    }
1187
1188    fn require_active(&self) -> Result<(), ScriptViewError> {
1189        match self.require_not_disposed()? {
1190            ScriptViewState::Active => Ok(()),
1191            ScriptViewState::Suspended => {
1192                Err(ScriptViewError::SuspendedView(self.0.view_id.clone()))
1193            }
1194            ScriptViewState::Disposed => unreachable!(),
1195        }
1196    }
1197
1198    #[must_use]
1199    pub fn view_id(&self) -> &str {
1200        &self.0.view_id
1201    }
1202
1203    #[must_use]
1204    pub fn state(&self) -> ScriptViewState {
1205        self.0.state.get()
1206    }
1207
1208    /// Resolve a mounted collection's native scrolling capability. The ID must
1209    /// belong to this view's component scope; equal keys in other views cannot
1210    /// resolve here. Resolve again after replacement instead of retaining a
1211    /// handle to a removed collection.
1212    ///
1213    /// # Errors
1214    /// Returns after suspension or disposal.
1215    pub fn collection_scroll_handle(
1216        &self,
1217        id: &crate::VirtualCollectionId,
1218        cx: &App,
1219    ) -> Result<Option<crate::VirtualCollectionScrollHandle>, ScriptViewError> {
1220        self.require_active()?;
1221        let view = self.0.entity.read(cx);
1222        if !id.component.is_within(view.lifecycle.root_path()) {
1223            return Ok(None);
1224        }
1225        Ok(view
1226            .lifecycle
1227            .runtime()
1228            .borrow()
1229            .virtual_requests
1230            .scroll_handle(id))
1231    }
1232
1233    /// Return a read-only, observable handle to this view's effective theme.
1234    ///
1235    /// # Errors
1236    ///
1237    /// Returns [`ScriptViewError::DisposedView`] after explicit disposal.
1238    pub fn theme(&self) -> Result<ThemeHandle, ScriptViewError> {
1239        self.require_not_disposed()?;
1240        Ok(self.0.theme.clone())
1241    }
1242
1243    /// Read this view's latest effective theme without invoking Rhai.
1244    ///
1245    /// # Errors
1246    ///
1247    /// Returns [`ScriptViewError::DisposedView`] after explicit disposal.
1248    pub fn theme_snapshot(&self, cx: &App) -> Result<ThemeSnapshot, ScriptViewError> {
1249        Ok(self.theme()?.snapshot(cx))
1250    }
1251
1252    /// Select this view's app-level theme from trusted Host code.
1253    ///
1254    /// # Errors
1255    ///
1256    /// Returns after disposal or when the requested theme is unavailable.
1257    pub fn select_theme(
1258        &self,
1259        family: &str,
1260        variant: &str,
1261        cx: &mut App,
1262    ) -> Result<bool, ScriptViewError> {
1263        self.require_not_disposed()?;
1264        self.0.entity.update(cx, |view, cx| {
1265            let changed = view
1266                .lifecycle
1267                .runtime()
1268                .borrow_mut()
1269                .select_theme_from_host(family, variant)
1270                .map_err(|error| ScriptViewError::Theme(error.to_string()))?;
1271            if changed {
1272                cx.notify();
1273            }
1274            Ok(changed)
1275        })
1276    }
1277
1278    /// Select this view's app-level locale from trusted Host code.
1279    ///
1280    /// # Errors
1281    ///
1282    /// Returns after disposal or when the requested locale is unavailable.
1283    pub fn select_locale(&self, locale: &str, cx: &mut App) -> Result<bool, ScriptViewError> {
1284        self.require_not_disposed()?;
1285        self.0.entity.update(cx, |view, cx| {
1286            let changed = view
1287                .lifecycle
1288                .runtime()
1289                .borrow_mut()
1290                .select_locale_from_host(locale)
1291                .map_err(|error| ScriptViewError::Locale(error.to_string()))?;
1292            if changed {
1293                cx.notify();
1294            }
1295            Ok(changed)
1296        })
1297    }
1298
1299    /// Replace this view's Host-owned motion preference without resetting state.
1300    ///
1301    /// # Errors
1302    ///
1303    /// Returns after disposal.
1304    pub fn set_motion_preference(
1305        &self,
1306        preference: MotionPreference,
1307        cx: &mut App,
1308    ) -> Result<bool, ScriptViewError> {
1309        self.require_not_disposed()?;
1310        self.0.entity.update(cx, |view, cx| {
1311            let changed = view
1312                .lifecycle
1313                .runtime()
1314                .borrow_mut()
1315                .set_motion_preference_from_host(preference);
1316            if changed {
1317                cx.notify();
1318            }
1319            Ok(changed)
1320        })
1321    }
1322
1323    /// Return the last successfully committed declarative tree.
1324    ///
1325    /// A failed transaction rolls back, so this is always a committed tree,
1326    /// never a partial candidate. [`Self::last_error`] reports whether some
1327    /// script work failed since the last reload or [`Self::clear_error`].
1328    ///
1329    /// # Errors
1330    ///
1331    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1332    pub fn root(&self, cx: &App) -> Result<Option<crate::UiNode>, ScriptViewError> {
1333        self.require_not_disposed()?;
1334        Ok(self.0.entity.read(cx).lifecycle.root().cloned())
1335    }
1336
1337    /// The revision of the view's committed tree. It advances whenever a render
1338    /// commits, so Host work that depends only on the committed composition
1339    /// (an audit, a snapshot) can skip frames that merely repaint.
1340    ///
1341    /// # Errors
1342    ///
1343    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1344    pub fn committed_revision(&self, cx: &App) -> Result<u64, ScriptViewError> {
1345        self.require_not_disposed()?;
1346        Ok(self.0.entity.read(cx).lifecycle.revision())
1347    }
1348
1349    /// The path of a file or folder dropped from the operating system, by the
1350    /// opaque `file` handle its `drop` event gave the script
1351    /// ([`ScriptView::accept_file_drops`]); `None` for any other handle. A
1352    /// capability handler, which gets no `App`, uses a clone of
1353    /// [`crate::UiRuntimeState::dropped_files`] instead.
1354    ///
1355    /// # Errors
1356    ///
1357    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1358    pub fn dropped_file_path(
1359        &self,
1360        handle: &crate::OpaqueHandle,
1361        cx: &App,
1362    ) -> Result<Option<PathBuf>, ScriptViewError> {
1363        self.require_not_disposed()?;
1364        Ok(self
1365            .0
1366            .entity
1367            .read(cx)
1368            .lifecycle
1369            .runtime()
1370            .borrow()
1371            .dropped_files
1372            .path(handle))
1373    }
1374
1375    /// Return the latest mounted-view render, callback, delivery, or reload error.
1376    ///
1377    /// A failed transaction rolls back to the last committed tree, and the view
1378    /// keeps working, so later transactions usually succeed. The error stays
1379    /// until a successful reload or [`Self::clear_error`]; otherwise a failure
1380    /// in one event would be gone before anyone could read it.
1381    ///
1382    /// # Errors
1383    ///
1384    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1385    pub fn last_error(&self, cx: &App) -> Result<Option<String>, ScriptViewError> {
1386        self.require_not_disposed()?;
1387        Ok(self
1388            .0
1389            .entity
1390            .read(cx)
1391            .last_failure
1392            .as_ref()
1393            .map(|failure| failure.message.clone()))
1394    }
1395
1396    /// Return structured details for the latest script runtime error.
1397    ///
1398    /// Non-script host errors only have a string representation and return
1399    /// `None` here.
1400    ///
1401    /// # Errors
1402    ///
1403    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1404    pub fn last_diagnostic(&self, cx: &App) -> Result<Option<Diagnostic>, ScriptViewError> {
1405        self.require_not_disposed()?;
1406        Ok(self
1407            .0
1408            .entity
1409            .read(cx)
1410            .last_failure
1411            .as_ref()
1412            .and_then(|failure| failure.diagnostic.as_deref().cloned()))
1413    }
1414
1415    /// Acknowledge the reported error: [`Self::last_error`] returns `None` and
1416    /// the built-in banner closes until the next failure.
1417    ///
1418    /// # Errors
1419    ///
1420    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1421    pub fn clear_error(&self, cx: &mut App) -> Result<(), ScriptViewError> {
1422        self.require_not_disposed()?;
1423        self.0.entity.update(cx, |view, cx| {
1424            if view.last_failure.is_some() {
1425                view.clear_failure();
1426                cx.notify();
1427            }
1428        });
1429        Ok(())
1430    }
1431
1432    /// What the view committed and presented in its last frame, for comparing
1433    /// two windows that run the same script. Not a stable interface.
1434    ///
1435    /// # Errors
1436    ///
1437    /// Returns [`ScriptViewError`] unless the view is active.
1438    #[doc(hidden)]
1439    pub fn debug_frame_digest(
1440        &self,
1441        window: &Window,
1442        cx: &App,
1443    ) -> Result<ScriptViewFrameDigest, ScriptViewError> {
1444        let accessibility = self.accessibility_snapshot(cx)?.nodes().cloned().collect();
1445        let view = self.0.entity.read(cx);
1446        let runtime = view.lifecycle.runtime();
1447        let runtime = runtime.borrow();
1448        let geometry = runtime.geometry_for(Some(&view.view_id));
1449        let retained = view.lifecycle.retained();
1450        Ok(ScriptViewFrameDigest {
1451            retained_nodes: retained.len(),
1452            geometry: retained
1453                .nodes()
1454                .map(crate::RetainedNode::id)
1455                .filter(|node| geometry.is_presented(*node))
1456                .filter_map(|node| geometry.get(node).map(|bounds| (node, bounds)))
1457                .collect(),
1458            accessibility,
1459            focus_path: view.focus_path(window),
1460            scroll_offsets: view
1461                .scroll_handles
1462                .iter()
1463                .map(|(node, handle)| {
1464                    let offset = handle.offset();
1465                    (*node, [f32::from(offset.x), f32::from(offset.y)])
1466                })
1467                .collect(),
1468            virtual_collections: runtime.virtual_requests.inspect(),
1469            last_error: view
1470                .last_failure
1471                .as_ref()
1472                .map(|failure| failure.message.clone()),
1473        })
1474    }
1475
1476    /// Render and commit counters since the last call, for benchmarks and
1477    /// performance tests. Not a stable interface.
1478    ///
1479    /// # Errors
1480    ///
1481    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1482    #[doc(hidden)]
1483    pub fn take_render_statistics(
1484        &self,
1485        cx: &mut App,
1486    ) -> Result<ScriptViewRenderStatistics, ScriptViewError> {
1487        self.require_not_disposed()?;
1488        Ok(self.0.entity.update(cx, |view, _| {
1489            let commits = view.lifecycle.take_commit_statistics();
1490            let mut statistics = std::mem::take(&mut view.render_statistics);
1491            statistics.commits = commits.commits;
1492            statistics.commit_phases = commits.phases;
1493            statistics.retained_nodes = view.lifecycle.retained().len();
1494            let islands = std::mem::take(&mut *view.islands.counters.borrow_mut());
1495            // Islands render after the view, as part of its frame.
1496            statistics.host_render_time += islands.render_time;
1497            statistics.build_time += islands.render_time;
1498            statistics.island_hits = islands.hits;
1499            statistics.island_misses = islands.misses;
1500            statistics.island_uncached = islands.uncached;
1501            statistics.island_drift = islands.drift;
1502            statistics
1503        }))
1504    }
1505
1506    /// Drain execution timings and snapshot retained/virtual metrics.
1507    ///
1508    /// # Errors
1509    ///
1510    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1511    pub fn take_performance_snapshot(
1512        &self,
1513        cx: &mut App,
1514    ) -> Result<ScriptViewPerformanceSnapshot, ScriptViewError> {
1515        self.require_not_disposed()?;
1516        Ok(self.0.entity.update(cx, |view, _| {
1517            let (
1518                virtual_collections,
1519                dirty_components,
1520                dirty_component_paths,
1521                pending_virtual_requests,
1522            ) = {
1523                let runtime_handle = view.lifecycle.runtime();
1524                let runtime = runtime_handle.borrow();
1525                (
1526                    runtime.virtual_requests.inspect(),
1527                    runtime.dirty_components().len(),
1528                    runtime
1529                        .dirty_components()
1530                        .iter()
1531                        .map(ToString::to_string)
1532                        .collect(),
1533                    runtime.has_virtual_requests(),
1534                )
1535            };
1536            ScriptViewPerformanceSnapshot {
1537                timings: std::mem::take(&mut view.timings),
1538                virtual_collections,
1539                retained_nodes: view.lifecycle.retained().len(),
1540                dirty_components,
1541                dirty_component_paths,
1542                pending_virtual_requests,
1543            }
1544        }))
1545    }
1546
1547    /// Read one mounted native hot value without invoking Rhai.
1548    ///
1549    /// # Errors
1550    ///
1551    /// Returns after disposal or when the signal is stale.
1552    pub fn read_signal(
1553        &self,
1554        signal: &crate::NativeSignal,
1555        cx: &App,
1556    ) -> Result<crate::SignalValue, ScriptViewError> {
1557        self.require_not_disposed()?;
1558        Ok(self
1559            .0
1560            .entity
1561            .read(cx)
1562            .lifecycle
1563            .runtime()
1564            .borrow()
1565            .signals
1566            .read(signal)?)
1567    }
1568
1569    /// Update one mounted native hot value on the GPUI foreground thread.
1570    ///
1571    /// This repaints signal-bound properties without running a Rhai component.
1572    ///
1573    /// # Errors
1574    ///
1575    /// Returns after disposal or for stale/type-incompatible values.
1576    pub fn write_signal(
1577        &self,
1578        signal: &crate::NativeSignal,
1579        value: crate::SignalValue,
1580        cx: &mut App,
1581    ) -> Result<bool, ScriptViewError> {
1582        self.require_not_disposed()?;
1583        self.0.entity.update(cx, |view, cx| {
1584            let changed = view
1585                .lifecycle
1586                .runtime()
1587                .borrow_mut()
1588                .signals
1589                .write(signal, value)?;
1590            if changed {
1591                cx.notify();
1592            }
1593            Ok::<_, ScriptViewError>(changed)
1594        })
1595    }
1596
1597    /// Replace one registered Rust-owned collection on the GPUI foreground thread.
1598    ///
1599    /// Only components that read this collection are marked dirty. The
1600    /// replacement is immutable and can be prepared away from the Rhai runtime.
1601    ///
1602    /// # Errors
1603    ///
1604    /// Returns after disposal or when the collection name is unknown.
1605    pub fn replace_native_collection(
1606        &self,
1607        name: &str,
1608        collection: crate::NativeCollection,
1609        cx: &mut App,
1610    ) -> Result<bool, ScriptViewError> {
1611        self.require_not_disposed()?;
1612        self.0.entity.update(cx, |view, cx| {
1613            let changed = view
1614                .lifecycle
1615                .runtime()
1616                .borrow_mut()
1617                .replace_native_collection_from_host(name, collection)?;
1618            if changed {
1619                cx.notify();
1620            }
1621            Ok::<_, ScriptViewError>(changed)
1622        })
1623    }
1624
1625    /// Register a new Rust-owned collection on an already mounted view.
1626    ///
1627    /// The name must not already exist. Registration marks the view root dirty;
1628    /// an active view rerenders on the next foreground cycle, while a suspended
1629    /// view consumes the collection when it resumes.
1630    ///
1631    /// # Errors
1632    ///
1633    /// Returns after disposal or for an unsafe/duplicate collection name.
1634    pub fn register_native_collection(
1635        &self,
1636        name: &str,
1637        collection: crate::NativeCollection,
1638        cx: &mut App,
1639    ) -> Result<(), ScriptViewError> {
1640        self.require_not_disposed()?;
1641        self.0.entity.update(cx, |view, cx| {
1642            let root = view.lifecycle.root_path().clone();
1643            view.lifecycle
1644                .runtime()
1645                .borrow_mut()
1646                .register_native_collection_from_host(&root, name, collection)?;
1647            if view.state.get() == ScriptViewState::Active {
1648                cx.notify();
1649            }
1650            Ok::<_, ScriptViewError>(())
1651        })
1652    }
1653
1654    /// Register a Host-owned document after mount, invalidating only components
1655    /// that previously attempted to read this name. No preallocated pool is needed.
1656    ///
1657    /// # Errors
1658    /// Returns after disposal or for an invalid/duplicate name.
1659    pub fn register_native_text_document(
1660        &self,
1661        name: &str,
1662        document: crate::NativeTextDocument,
1663        cx: &mut App,
1664    ) -> Result<(), ScriptViewError> {
1665        self.require_not_disposed()?;
1666        self.0.entity.update(cx, |view, cx| {
1667            view.lifecycle
1668                .runtime()
1669                .borrow_mut()
1670                .register_native_text_document_from_host(name, document)?;
1671            if view.state.get() == ScriptViewState::Active {
1672                cx.notify();
1673            }
1674            Ok::<_, ScriptViewError>(())
1675        })
1676    }
1677
1678    /// Release this name's registry ownership. In-flight viewers retain their
1679    /// immutable snapshot safely; stop referring to the name before releasing it.
1680    /// The boolean reports whether readers were invalidated; a successful
1681    /// `false` result still released the registry's snapshot.
1682    ///
1683    /// # Errors
1684    /// Returns after disposal or for an unknown name.
1685    pub fn release_native_text_document(
1686        &self,
1687        name: &str,
1688        cx: &mut App,
1689    ) -> Result<bool, ScriptViewError> {
1690        self.require_not_disposed()?;
1691        self.0.entity.update(cx, |view, cx| {
1692            let changed = view
1693                .lifecycle
1694                .runtime()
1695                .borrow_mut()
1696                .release_native_text_document_from_host(name)?;
1697            if changed {
1698                cx.notify();
1699            }
1700            Ok::<_, ScriptViewError>(changed)
1701        })
1702    }
1703
1704    /// Replace one registered Host-owned text document revision.
1705    ///
1706    /// Only components that read this document are invalidated. The immutable
1707    /// text snapshot may be prepared on a background thread before publication.
1708    ///
1709    /// # Errors
1710    ///
1711    /// Returns after disposal or when the document name is unknown.
1712    pub fn replace_native_text_document(
1713        &self,
1714        name: &str,
1715        document: crate::NativeTextDocument,
1716        cx: &mut App,
1717    ) -> Result<bool, ScriptViewError> {
1718        self.require_not_disposed()?;
1719        self.0.entity.update(cx, |view, cx| {
1720            let changed = view
1721                .lifecycle
1722                .runtime()
1723                .borrow_mut()
1724                .replace_native_text_document_from_host(name, document)?;
1725            if changed {
1726                cx.notify();
1727            }
1728            Ok::<_, ScriptViewError>(changed)
1729        })
1730    }
1731
1732    /// Append `text` to one registered Host-owned document as its next revision
1733    /// (the same identity, the following revision): a streamed reply sends each
1734    /// chunk instead of the whole text so far. A `MarkdownViewer` reading it then
1735    /// prepares only the last block and the new text, not the whole reply.
1736    ///
1737    /// # Errors
1738    ///
1739    /// Returns after disposal, when the document name is unknown, or when its
1740    /// revision cannot advance.
1741    pub fn append_native_text_document(
1742        &self,
1743        name: &str,
1744        text: &str,
1745        cx: &mut App,
1746    ) -> Result<bool, ScriptViewError> {
1747        self.require_not_disposed()?;
1748        self.0.entity.update(cx, |view, cx| {
1749            let changed = view
1750                .lifecycle
1751                .runtime()
1752                .borrow_mut()
1753                .append_native_text_document_from_host(name, text)?;
1754            if changed {
1755                cx.notify();
1756            }
1757            Ok::<_, ScriptViewError>(changed)
1758        })
1759    }
1760
1761    /// Return the measured embedding element.
1762    ///
1763    /// # Errors
1764    ///
1765    /// Returns [`ScriptViewError::DisposedView`] after explicit disposal.
1766    pub fn element(&self) -> Result<AnyElement, ScriptViewError> {
1767        self.require_active()?;
1768        Ok(MeasuredScriptViewElement {
1769            entity: self.0.entity.clone(),
1770            measured_bounds: Rc::clone(&self.0.measured_bounds),
1771        }
1772        .into_any_element())
1773    }
1774
1775    /// Return the measured view as a zero-basis, shrinkable host flex item.
1776    ///
1777    /// Use this as the direct child of a Rust flex row or column. It prevents
1778    /// horizontally scrollable script content from contributing an automatic
1779    /// min-content width that expands the surrounding host layout.
1780    ///
1781    /// # Errors
1782    ///
1783    /// Returns [`ScriptViewError::DisposedView`] after explicit disposal.
1784    pub fn flex_item(&self) -> Result<AnyElement, ScriptViewError> {
1785        Ok(div()
1786            .flex_1()
1787            .min_w(px(0.0))
1788            .min_h(px(0.0))
1789            .debug_selector(|| format!("gpui-rhai-flex-item:{}", self.view_id()))
1790            .child(self.element()?)
1791            .into_any_element())
1792    }
1793
1794    pub(crate) fn host_slot_item(&self) -> Result<AnyElement, ScriptViewError> {
1795        let item = self.flex_item()?;
1796        if self.0.host.frame_active() {
1797            Ok(item)
1798        } else {
1799            Ok(self.0.host.container(item))
1800        }
1801    }
1802
1803    /// Quiesce this retained view without discarding script or native UI state.
1804    ///
1805    /// # Errors
1806    ///
1807    /// Returns after disposal or when a suspend hook/effect cleanup fails.
1808    pub fn suspend(&self, window: &mut Window, cx: &mut App) -> Result<bool, ScriptViewError> {
1809        match self.require_not_disposed()? {
1810            ScriptViewState::Suspended => return Ok(false),
1811            ScriptViewState::Active => {}
1812            ScriptViewState::Disposed => unreachable!(),
1813        }
1814        self.0
1815            .entity
1816            .update(cx, |view, cx| view.suspend_view(window, cx))
1817    }
1818
1819    /// Atomically resume a suspended view before returning it to Host layout.
1820    ///
1821    /// # Errors
1822    ///
1823    /// Returns after disposal or when pending delivery, resume hook, reload, or
1824    /// the first restored render fails. A compensable failure leaves the view
1825    /// suspended; failed compensation disposes and quarantines the view.
1826    pub fn resume(&self, cx: &mut App) -> Result<bool, ScriptViewError> {
1827        match self.require_not_disposed()? {
1828            ScriptViewState::Active => return Ok(false),
1829            ScriptViewState::Suspended => {}
1830            ScriptViewState::Disposed => unreachable!(),
1831        }
1832        self.0.entity.update(cx, ScriptHostView::resume_view)
1833    }
1834
1835    /// Dispose this view immediately. The operation is idempotent.
1836    ///
1837    /// # Errors
1838    ///
1839    /// Returns an entity update error only if GPUI has already released the
1840    /// underlying view unexpectedly.
1841    pub fn dispose(&self, cx: &mut App) -> Result<(), ScriptViewError> {
1842        if self.0.state.get() == ScriptViewState::Disposed {
1843            return Ok(());
1844        }
1845        self.0.entity.update(cx, |view, cx| {
1846            view.release_view();
1847            cx.notify();
1848        });
1849        self.0
1850            .host
1851            .unregister_view(&self.0.view_id, &self.0.mount_lease);
1852        cx.refresh_windows();
1853        Ok(())
1854    }
1855
1856    /// Focus this view's stable root handle.
1857    ///
1858    /// # Errors
1859    ///
1860    /// Returns [`ScriptViewError::DisposedView`] after disposal.
1861    pub fn focus(&self, window: &mut Window, cx: &mut App) -> Result<(), ScriptViewError> {
1862        self.require_active()?;
1863        let focus = self.0.entity.update(cx, |view, _| {
1864            view.navigation_focus_epoch = view.navigation_focus_epoch.wrapping_add(1);
1865            view.host_focus.clone()
1866        });
1867        focus.focus(window, cx);
1868        Ok(())
1869    }
1870
1871    /// Audit the committed composition with the rules of this view's profile
1872    /// (`ui/profile.rhai` or [`ScriptView::profile_source`]). With no
1873    /// profile the result is empty.
1874    ///
1875    /// # Errors
1876    ///
1877    /// Returns after disposal.
1878    pub fn composition_audit(&self, cx: &App) -> Result<Vec<crate::AuditFinding>, ScriptViewError> {
1879        let rules = self
1880            .0
1881            .entity
1882            .read(cx)
1883            .lifecycle
1884            .runtime()
1885            .borrow()
1886            .audit_rules
1887            .clone();
1888        self.composition_audit_with(&rules, cx)
1889    }
1890
1891    /// Controls the committed layout cuts off where nothing scrolls, or lays
1892    /// over one another: a check for reading scales and narrow windows, not
1893    /// yet a composition rule. Hidden and unstable.
1894    ///
1895    /// # Errors
1896    ///
1897    /// Returns after disposal.
1898    #[doc(hidden)]
1899    pub fn debug_unreachable_controls(&self, cx: &App) -> Result<Vec<String>, ScriptViewError> {
1900        self.require_active()?;
1901        let view = self.0.entity.read(cx);
1902        let geometry = view
1903            .lifecycle
1904            .runtime()
1905            .borrow()
1906            .geometry_for(Some(&view.view_id));
1907        Ok(crate::composition_audit::unreachable_controls(
1908            view.lifecycle.retained(),
1909            &geometry,
1910        ))
1911    }
1912
1913    /// Audit the committed composition with an explicit rule set.
1914    ///
1915    /// # Errors
1916    ///
1917    /// Returns after disposal.
1918    pub fn composition_audit_with(
1919        &self,
1920        rules: &crate::AuditRules,
1921        cx: &App,
1922    ) -> Result<Vec<crate::AuditFinding>, ScriptViewError> {
1923        self.require_active()?;
1924        let theme = self.theme_snapshot(cx)?.variant;
1925        let view = self.0.entity.read(cx);
1926        let geometry = view
1927            .lifecycle
1928            .runtime()
1929            .borrow()
1930            .geometry_for(Some(&view.view_id));
1931        let direction = {
1932            let runtime = view.lifecycle.runtime();
1933            let runtime = runtime.borrow();
1934            let root = view.lifecycle.root_path();
1935            runtime
1936                .locale
1937                .as_ref()
1938                .and_then(|locale| locale.direction(Some(&view.window_id), Some(root)).ok())
1939                .unwrap_or(TextDirection::LeftToRight)
1940        };
1941        // Enumerating system fonts costs about 100 ms, so it happens only when
1942        // the font rule is on, and once per set of loaded fonts.
1943        let fonts = rules
1944            .contains(crate::AuditRule::UnresolvedFont)
1945            .then(|| available_font_names(cx));
1946        Ok(crate::composition_audit::audit(
1947            &crate::composition_audit::AuditInputs {
1948                tree: view.lifecycle.retained(),
1949                geometry: &geometry,
1950                theme: &theme,
1951                rules,
1952                available_fonts: fonts.as_deref(),
1953                direction,
1954            },
1955        ))
1956    }
1957
1958    /// Snapshot the retained semantic tree and last committed geometry.
1959    ///
1960    /// # Errors
1961    ///
1962    /// Returns after disposal or for an invalid retained semantic graph.
1963    pub fn accessibility_snapshot(
1964        &self,
1965        cx: &App,
1966    ) -> Result<crate::AccessibilityTree, ScriptViewError> {
1967        self.require_active()?;
1968        let view = self.0.entity.read(cx);
1969        let geometry = view
1970            .lifecycle
1971            .runtime()
1972            .borrow()
1973            .geometry_for(Some(&view.view_id));
1974        let mut tree = crate::AccessibilityTree::from_committed(
1975            view.lifecycle.semantics(),
1976            view.lifecycle.retained(),
1977            &geometry,
1978            true,
1979        );
1980        tree.apply_primitive_projections(
1981            view.primitives
1982                .accessibility_projections(view.lifecycle.retained(), cx),
1983        );
1984        if let Some(failure) = &view.last_failure {
1985            let chart_error = failure.diagnostic.as_ref().is_some_and(|diagnostic| {
1986                diagnostic
1987                    .source
1988                    .as_deref()
1989                    .is_some_and(|source| source.starts_with("charts/"))
1990                    || diagnostic
1991                        .component
1992                        .as_deref()
1993                        .is_some_and(|component| component.contains("/Chart["))
1994            });
1995            tree.mark_runtime_error(&failure.message, chart_error);
1996        }
1997        Ok(tree)
1998    }
1999
2000    /// Snapshot the stable language-neutral automation tree.
2001    ///
2002    /// # Errors
2003    ///
2004    /// Returns after disposal or for an invalid retained semantic graph.
2005    pub fn automation_snapshot(
2006        &self,
2007        cx: &App,
2008    ) -> Result<crate::AutomationSnapshot, ScriptViewError> {
2009        Ok(crate::AutomationSnapshot::from_accessibility(
2010            &self.accessibility_snapshot(cx)?,
2011        ))
2012    }
2013
2014    /// Execute one automation command on the GPUI foreground thread.
2015    ///
2016    /// Dispatch and action commands use the mounted production handlers;
2017    /// deterministic time advance requires an injected controllable clock.
2018    ///
2019    /// # Errors
2020    ///
2021    /// Returns after disposal, for locator/command failures, or runtime errors.
2022    pub fn automate(
2023        &self,
2024        command: crate::AutomationCommand,
2025        window: &mut Window,
2026        cx: &mut App,
2027    ) -> Result<crate::AutomationResult, ScriptViewError> {
2028        self.require_active()?;
2029        match command {
2030            crate::AutomationCommand::Snapshot => Ok(crate::AutomationResult::Snapshot {
2031                snapshot: self.automation_snapshot(cx)?,
2032            }),
2033            crate::AutomationCommand::Query { locator } => {
2034                let view = self.0.entity.read(cx);
2035                let geometry = view
2036                    .lifecycle
2037                    .runtime()
2038                    .borrow()
2039                    .geometry_for(Some(&view.view_id));
2040                let mut tree = crate::AccessibilityTree::from_committed(
2041                    view.lifecycle.semantics(),
2042                    view.lifecycle.retained(),
2043                    &geometry,
2044                    true,
2045                );
2046                tree.apply_primitive_projections(
2047                    view.primitives
2048                        .accessibility_projections(view.lifecycle.retained(), cx),
2049                );
2050                let id = crate::automation::resolve_locator(&tree, &locator)?;
2051                let node = tree
2052                    .node(id)
2053                    .ok_or_else(|| crate::AutomationError::StaleTarget(id.get()))?;
2054                Ok(crate::AutomationResult::Node {
2055                    node: Box::new(crate::AutomationNode::from(node)),
2056                })
2057            }
2058            command => self
2059                .0
2060                .entity
2061                .update(cx, |view, cx| view.execute_automation(command, window, cx)),
2062        }
2063    }
2064
2065    /// Return the last successfully committed retained diff report.
2066    ///
2067    /// # Errors
2068    ///
2069    /// Returns after disposal.
2070    pub fn reconcile_report(&self, cx: &App) -> Result<crate::ReconcileReport, ScriptViewError> {
2071        self.require_not_disposed()?;
2072        Ok(self
2073            .0
2074            .entity
2075            .read(cx)
2076            .lifecycle
2077            .retained()
2078            .last_report()
2079            .clone())
2080    }
2081
2082    /// Focus a mounted retained element without invoking Rhai.
2083    ///
2084    /// # Errors
2085    ///
2086    /// Returns after disposal, for a stale ref, or when the ref has no active
2087    /// GPUI focus handle.
2088    pub fn focus_element(
2089        &self,
2090        reference: &crate::ElementRef,
2091        window: &mut Window,
2092        cx: &mut App,
2093    ) -> Result<(), ScriptViewError> {
2094        self.require_active()?;
2095        let handle = self.0.entity.update(cx, |view, _| {
2096            let node = view
2097                .lifecycle
2098                .runtime()
2099                .borrow()
2100                .element_refs
2101                .resolve(reference)?;
2102            let handle = view
2103                .focus_handles
2104                .get(&node)
2105                .filter(|_| view.lifecycle.retained().is_page_visible(node))
2106                .cloned()
2107                .ok_or_else(|| {
2108                    ScriptViewError::ElementRef(crate::ElementRefError::Stale(
2109                        reference.id().clone(),
2110                    ))
2111                })?;
2112            view.navigation_focus_epoch = view.navigation_focus_epoch.wrapping_add(1);
2113            Ok::<_, ScriptViewError>(handle)
2114        })?;
2115        handle.focus(window, cx);
2116        Ok(())
2117    }
2118
2119    #[cfg(feature = "dev-reload")]
2120    /// Open or close this view's isolated development inspector.
2121    ///
2122    /// # Errors
2123    ///
2124    /// Returns [`ScriptViewError::DisposedView`] after disposal.
2125    pub fn set_inspector_open(&self, open: bool, cx: &mut App) -> Result<(), ScriptViewError> {
2126        self.require_active()?;
2127        self.0.entity.update(cx, |view, cx| {
2128            view.inspector_open = open;
2129            cx.notify();
2130        });
2131        Ok(())
2132    }
2133}
2134
2135struct MeasuredScriptViewElement {
2136    entity: Entity<ScriptHostView>,
2137    measured_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
2138}
2139
2140impl Element for MeasuredScriptViewElement {
2141    type RequestLayoutState = AnyElement;
2142    type PrepaintState = ();
2143
2144    fn id(&self) -> Option<ElementId> {
2145        None
2146    }
2147
2148    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
2149        None
2150    }
2151
2152    fn request_layout(
2153        &mut self,
2154        _id: Option<&GlobalElementId>,
2155        _inspector_id: Option<&InspectorElementId>,
2156        window: &mut Window,
2157        cx: &mut App,
2158    ) -> (LayoutId, Self::RequestLayoutState) {
2159        let mut child = self.entity.clone().into_any_element();
2160        let layout = child.request_layout(window, cx);
2161        (layout, child)
2162    }
2163
2164    fn prepaint(
2165        &mut self,
2166        _id: Option<&GlobalElementId>,
2167        _inspector_id: Option<&InspectorElementId>,
2168        bounds: Bounds<Pixels>,
2169        child: &mut Self::RequestLayoutState,
2170        window: &mut Window,
2171        cx: &mut App,
2172    ) {
2173        child.prepaint(window, cx);
2174        if self.measured_bounds.get() != Some(bounds) {
2175            self.measured_bounds.set(Some(bounds));
2176            let view = self.entity.downgrade();
2177            window.defer(cx, move |_, cx| {
2178                let _ = view.update(cx, |view, cx| view.set_content_bounds(bounds, cx));
2179            });
2180        }
2181    }
2182
2183    fn paint(
2184        &mut self,
2185        _id: Option<&GlobalElementId>,
2186        _inspector_id: Option<&InspectorElementId>,
2187        _bounds: Bounds<Pixels>,
2188        child: &mut Self::RequestLayoutState,
2189        _prepaint: &mut Self::PrepaintState,
2190        window: &mut Window,
2191        cx: &mut App,
2192    ) {
2193        child.paint(window, cx);
2194    }
2195}
2196
2197/// The root width (`f32` bits) a build of a view's content anchored its
2198/// islands on, and whether it pinned one of them to a measured height.
2199struct ContentAnchor {
2200    width: u32,
2201    pinned: Rc<Cell<bool>>,
2202}
2203
2204/// The content of a view a Host sizes, built with its islands anchored on the
2205/// width its root laid out at last frame. A Host that resizes the view without
2206/// resizing the window changes that width only in layout: when the root lays
2207/// out at another width and an island was pinned to a height measured at the
2208/// old one, the content is built again for the new width and laid out in place
2209/// of the first build, so no frame shows the old heights.
2210struct ReanchoredContent {
2211    child: AnyElement,
2212    /// The root width (`f32` bits) the build anchored on.
2213    width: u32,
2214    pinned: Rc<Cell<bool>>,
2215    laid_out_width: Rc<Cell<Option<u32>>>,
2216    view: gpui::WeakEntity<ScriptHostView>,
2217    frame: Rc<HostFrame>,
2218}
2219
2220impl Element for ReanchoredContent {
2221    type RequestLayoutState = ();
2222    type PrepaintState = ();
2223
2224    fn id(&self) -> Option<ElementId> {
2225        None
2226    }
2227
2228    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
2229        None
2230    }
2231
2232    fn request_layout(
2233        &mut self,
2234        _id: Option<&GlobalElementId>,
2235        _inspector_id: Option<&InspectorElementId>,
2236        window: &mut Window,
2237        cx: &mut App,
2238    ) -> (LayoutId, Self::RequestLayoutState) {
2239        (self.child.request_layout(window, cx), ())
2240    }
2241
2242    fn prepaint(
2243        &mut self,
2244        _id: Option<&GlobalElementId>,
2245        _inspector_id: Option<&InspectorElementId>,
2246        bounds: Bounds<Pixels>,
2247        _request_layout: &mut Self::RequestLayoutState,
2248        window: &mut Window,
2249        cx: &mut App,
2250    ) {
2251        let width = f32::from(bounds.size.width).to_bits();
2252        self.laid_out_width.set(Some(width));
2253        if width != self.width
2254            && self.pinned.get()
2255            && let Some(view) = self.view.upgrade()
2256        {
2257            let frame = Rc::clone(&self.frame);
2258            let (mut content, _) = view.update(cx, |view, cx| {
2259                view.build_content(&frame, Some(width), window, cx)
2260            });
2261            content.layout_as_root(bounds.size.into(), window, cx);
2262            content.prepaint_at(bounds.origin, window, cx);
2263            self.child = content;
2264            return;
2265        }
2266        self.child.prepaint(window, cx);
2267    }
2268
2269    fn paint(
2270        &mut self,
2271        _id: Option<&GlobalElementId>,
2272        _inspector_id: Option<&InspectorElementId>,
2273        _bounds: Bounds<Pixels>,
2274        _request_layout: &mut Self::RequestLayoutState,
2275        _prepaint: &mut Self::PrepaintState,
2276        window: &mut Window,
2277        cx: &mut App,
2278    ) {
2279        self.child.paint(window, cx);
2280    }
2281}
2282
2283impl IntoElement for ReanchoredContent {
2284    type Element = Self;
2285
2286    fn into_element(self) -> Self::Element {
2287        self
2288    }
2289}
2290
2291impl IntoElement for MeasuredScriptViewElement {
2292    type Element = Self;
2293
2294    fn into_element(self) -> Self::Element {
2295        self
2296    }
2297}
2298
2299pub trait ScriptViewExtension {
2300    /// Register custom primitives or engine APIs before scripts compile.
2301    ///
2302    /// # Errors
2303    ///
2304    /// Returns an application-facing extension diagnostic.
2305    fn configure_engine(&self, _engine: &mut RuntimeEngine) -> Result<(), String> {
2306        Ok(())
2307    }
2308
2309    /// Change the Rhai engine itself before scripts compile, for what [`RuntimeEngine`] does
2310    /// not cover: disable a keyword (`disable_symbol("eval")`), replace a standard-library
2311    /// function by registering one with the same name and parameter types (each overload,
2312    /// such as `sleep(i64)` and `sleep(f64)`, separately), or route `print` and `debug`
2313    /// (`on_print`, `on_debug`). The runtime calls it on every engine it builds for the view
2314    /// (preparation, each script window and each dev-reload candidate), after every
2315    /// extension's [`Self::configure_engine`].
2316    ///
2317    /// The runtime restricts nothing itself: scripts get Rhai's standard library as
2318    /// `rhai::Engine::new()` sets it up. The operation budget runs in the engine's
2319    /// `on_progress` callback, so replacing that callback removes the budget.
2320    ///
2321    /// # Errors
2322    ///
2323    /// Returns an application-facing extension diagnostic.
2324    fn configure_rhai_engine(&self, _engine: &mut rhai::Engine) -> Result<(), String> {
2325        Ok(())
2326    }
2327
2328    /// Register and activate capabilities or stores before lifecycle init.
2329    ///
2330    /// # Errors
2331    ///
2332    /// Returns an application-facing extension diagnostic.
2333    fn configure_runtime(&self, _runtime: &mut UiRuntimeState) -> Result<(), String> {
2334        Ok(())
2335    }
2336
2337    /// Declare resources owned by each script window, such as window stores.
2338    /// This runs once before that window's lifecycle `init`.
2339    ///
2340    /// # Errors
2341    ///
2342    /// Returns an application-facing extension diagnostic.
2343    fn configure_window(
2344        &self,
2345        _window_id: &str,
2346        _runtime: &mut UiRuntimeState,
2347    ) -> Result<(), String> {
2348        Ok(())
2349    }
2350
2351    /// Runs with the application at each delivery poll of a mounted view
2352    /// (within a frame while it is active), for platform work a capability
2353    /// handler queued: handlers get no `App`. `window` is the view's native
2354    /// window. [`crate::system::SystemServices`] posts notifications here.
2355    fn poll(&self, _window: Option<AnyWindowHandle>, _cx: &mut App) {}
2356}
2357
2358/// Every extension's [`ScriptViewExtension::configure_engine`], then every
2359/// [`ScriptViewExtension::configure_rhai_engine`], on one engine built for the view.
2360fn configure_extension_engine(
2361    extensions: &[Box<dyn ScriptViewExtension>],
2362    engine: &mut RuntimeEngine,
2363) -> Result<(), String> {
2364    for extension in extensions {
2365        extension.configure_engine(engine)?;
2366    }
2367    for extension in extensions {
2368        extension.configure_rhai_engine(engine.engine_mut())?;
2369    }
2370    Ok(())
2371}
2372
2373fn motion_preference_from_env() -> MotionPreference {
2374    std::env::var("GPUI_RHAI_REDUCED_MOTION")
2375        .ok()
2376        .as_deref()
2377        .map_or(MotionPreference::Normal, parse_motion_preference)
2378}
2379
2380fn parse_motion_preference(value: &str) -> MotionPreference {
2381    if matches!(
2382        value.trim().to_ascii_lowercase().as_str(),
2383        "1" | "true" | "reduce" | "reduced"
2384    ) {
2385        MotionPreference::Reduced
2386    } else {
2387        MotionPreference::Normal
2388    }
2389}
2390
2391#[derive(Clone, Copy, Default)]
2392struct ScriptExecutionPolicy {
2393    operation_limit: Option<u64>,
2394    expression_depth_limits: Option<(usize, usize)>,
2395}
2396
2397impl ScriptExecutionPolicy {
2398    fn apply(self, engine: &mut RuntimeEngine) {
2399        if let Some(limit) = self.operation_limit {
2400            engine.set_operation_limit(limit);
2401        }
2402        if let Some((global, functions)) = self.expression_depth_limits {
2403            engine.set_expression_depth_limits(global, functions);
2404        }
2405    }
2406}
2407
2408/// Where a [`ScriptView`] reads its `ui/` tree.
2409enum UiSource {
2410    /// An entry script, or a `ui` directory whose `app.toml` names the entry.
2411    Files(PathBuf),
2412    /// A tree `gpui-rhai-build` compiled into the binary.
2413    Embedded(&'static crate::EmbeddedUi),
2414    /// Sources the Host supplies in memory.
2415    Sources(Box<UiSources>),
2416}
2417
2418/// In-memory sources: the parts of a `ui/` directory.
2419pub(crate) struct UiSources {
2420    pub(crate) entry: ModuleId,
2421    pub(crate) scripts: EmbeddedScriptSource,
2422    pub(crate) theme_source: String,
2423    pub(crate) component_style_source: Option<String>,
2424    pub(crate) locales: Vec<(String, String)>,
2425    pub(crate) themes: Vec<(String, String)>,
2426    pub(crate) manifest: AppManifest,
2427    pub(crate) assets: BTreeMap<String, AssetData>,
2428    pub(crate) profile_source: Option<String>,
2429}
2430
2431impl UiSources {
2432    pub(crate) fn new(
2433        entry: ModuleId,
2434        scripts: EmbeddedScriptSource,
2435        theme_source: String,
2436    ) -> Self {
2437        Self {
2438            manifest: AppManifest::new(entry.clone()),
2439            entry,
2440            scripts,
2441            theme_source,
2442            component_style_source: None,
2443            locales: Vec::new(),
2444            themes: Vec::new(),
2445            assets: BTreeMap::new(),
2446            profile_source: None,
2447        }
2448    }
2449}
2450
2451/// A script view: its `ui/` tree and the Host's configuration.
2452///
2453/// [`script_view!`](crate::script_view) reads the files of the crate's `ui/`
2454/// directory in a debug build and the copy `gpui-rhai-build` embedded in a
2455/// release build, so a Host writes one mount. [`ScriptView::files`],
2456/// [`ScriptView::embedded`] and [`ScriptView::sources`] choose explicitly.
2457pub struct ScriptView {
2458    source: UiSource,
2459    /// An option that supplies in-memory sources, used on another source.
2460    misplaced_source_option: Option<&'static str>,
2461    ui_override_env: Option<String>,
2462    development: bool,
2463    motion_preference: MotionPreference,
2464    motion_quality: crate::MotionQuality,
2465    extensions: Vec<Box<dyn ScriptViewExtension>>,
2466    key_bindings: Vec<KeyBindingSpec>,
2467    viewport_breakpoints: ViewportBreakpoints,
2468    calendar_clock: crate::CalendarClock,
2469    wall_clock: crate::WallClock,
2470    runtime_clock: Option<crate::RuntimeClock>,
2471    fonts: Vec<crate::FontSource>,
2472    token_base: Option<String>,
2473    theme_token_overrides: ThemeTokenOverrides,
2474    execution_policy: ScriptExecutionPolicy,
2475    accept_file_drops: bool,
2476}
2477
2478impl ScriptView {
2479    fn with_source(source: UiSource, development: bool) -> Self {
2480        Self {
2481            source,
2482            misplaced_source_option: None,
2483            ui_override_env: None,
2484            development,
2485            motion_preference: motion_preference_from_env(),
2486            motion_quality: crate::MotionQuality::High,
2487            extensions: Vec::new(),
2488            key_bindings: Vec::new(),
2489            viewport_breakpoints: ViewportBreakpoints::default(),
2490            calendar_clock: crate::CalendarClock::default(),
2491            wall_clock: crate::WallClock::default(),
2492            runtime_clock: None,
2493            fonts: Vec::new(),
2494            token_base: None,
2495            theme_token_overrides: ThemeTokenOverrides::default(),
2496            execution_policy: ScriptExecutionPolicy::default(),
2497            accept_file_drops: false,
2498        }
2499    }
2500
2501    /// Read the `ui/` tree from disk: `path` is the entry script, or a `ui`
2502    /// directory whose `app.toml` names it. Development (hot reload) is on in
2503    /// a debug build with the `dev-reload` feature.
2504    #[must_use]
2505    pub fn files(path: impl Into<PathBuf>) -> Self {
2506        Self::with_source(
2507            UiSource::Files(path.into()),
2508            cfg!(feature = "dev-reload") && cfg!(debug_assertions),
2509        )
2510    }
2511
2512    /// Read the tree `gpui-rhai-build` compiled into the binary.
2513    #[must_use]
2514    pub fn embedded(ui: &'static crate::EmbeddedUi) -> Self {
2515        Self::with_source(UiSource::Embedded(ui), false)
2516    }
2517
2518    /// Run sources the Host supplies in memory: the entry module, the modules
2519    /// it may import and the primary theme. [`Self::theme_sources`],
2520    /// [`Self::locale_sources`], [`Self::asset_sources`],
2521    /// [`Self::component_styles`], [`Self::profile_source`] and
2522    /// [`Self::manifest`] add the other parts of a `ui/` directory.
2523    #[must_use]
2524    pub fn sources(
2525        entry: ModuleId,
2526        scripts: EmbeddedScriptSource,
2527        theme_source: impl Into<String>,
2528    ) -> Self {
2529        Self::with_source(
2530            UiSource::Sources(Box::new(UiSources::new(
2531                entry,
2532                scripts,
2533                theme_source.into(),
2534            ))),
2535            false,
2536        )
2537    }
2538
2539    /// Read the `ui/` tree from the files at the path in environment variable
2540    /// `name` when it is set, whatever the source. [`script_view!`](crate::script_view)
2541    /// honors `GPUI_RHAI_UI` in a debug build; a release build honors a
2542    /// variable only when the Host names one here, since swapping the scripts
2543    /// of a signed application is a way to inject code into it.
2544    #[must_use]
2545    pub fn ui_override_env(mut self, name: impl Into<String>) -> Self {
2546        self.ui_override_env = Some(name.into());
2547        self
2548    }
2549
2550    /// Let a `DropZone` that lists the `os.files` payload type take files and
2551    /// folders the operating system drags in. Off by default. The script's
2552    /// `drop` event carries an opaque handle for each, never its path; the Host
2553    /// turns one back into the path with [`crate::DroppedFiles::path`] on
2554    /// [`crate::UiRuntimeState::dropped_files`].
2555    #[must_use]
2556    pub const fn accept_file_drops(mut self, accept: bool) -> Self {
2557        self.accept_file_drops = accept;
2558        self
2559    }
2560
2561    fn sources_option(mut self, option: &'static str, apply: impl FnOnce(&mut UiSources)) -> Self {
2562        match &mut self.source {
2563            UiSource::Sources(sources) => apply(sources),
2564            UiSource::Files(_) | UiSource::Embedded(_) => {
2565                self.misplaced_source_option.get_or_insert(option);
2566            }
2567        }
2568        self
2569    }
2570
2571    /// Install an application profile (`profile() -> map`) whose audit rules
2572    /// [`ScriptViewHandle::composition_audit`] applies. In-memory sources only.
2573    #[must_use]
2574    pub fn profile_source(self, source: impl Into<String>) -> Self {
2575        let source = source.into();
2576        self.sources_option("profile_source", |sources| {
2577            sources.profile_source = Some(source);
2578        })
2579    }
2580
2581    /// The locales (name, source) of in-memory sources.
2582    #[must_use]
2583    pub fn locale_sources(self, locales: impl IntoIterator<Item = (String, String)>) -> Self {
2584        let locales = locales.into_iter().collect();
2585        self.sources_option("locale_sources", |sources| sources.locales = locales)
2586    }
2587
2588    /// The additional themes (name, source) of in-memory sources.
2589    #[must_use]
2590    pub fn theme_sources(self, themes: impl IntoIterator<Item = (String, String)>) -> Self {
2591        let themes = themes.into_iter().collect();
2592        self.sources_option("theme_sources", |sources| sources.themes = themes)
2593    }
2594
2595    /// Install one application-wide typed component stylesheet. In-memory
2596    /// sources only.
2597    #[must_use]
2598    pub fn component_styles(self, source: impl Into<String>) -> Self {
2599        let source = source.into();
2600        self.sources_option("component_styles", |sources| {
2601            sources.component_style_source = Some(source);
2602        })
2603    }
2604
2605    /// The application manifest of in-memory sources.
2606    #[must_use]
2607    pub fn manifest(self, manifest: AppManifest) -> Self {
2608        self.sources_option("manifest", |sources| sources.manifest = manifest)
2609    }
2610
2611    /// The `app` asset namespace of in-memory sources.
2612    #[must_use]
2613    pub fn asset_sources(self, assets: impl IntoIterator<Item = (String, AssetData)>) -> Self {
2614        let assets = assets.into_iter().collect();
2615        self.sources_option("asset_sources", |sources| sources.assets = assets)
2616    }
2617
2618    /// Use this token base source instead of the tree's `tokens.rhai`.
2619    #[must_use]
2620    pub fn token_base(mut self, source: impl Into<String>) -> Self {
2621        self.token_base = Some(source.into());
2622        self
2623    }
2624
2625    /// Reload changed sources while the view runs (with the `dev-reload`
2626    /// feature). Files only.
2627    #[must_use]
2628    pub const fn development(mut self, enabled: bool) -> Self {
2629        self.development = enabled;
2630        self
2631    }
2632    #[must_use]
2633    pub const fn motion_preference(mut self, preference: MotionPreference) -> Self {
2634        self.motion_preference = preference;
2635        self
2636    }
2637
2638    #[must_use]
2639    pub const fn motion_quality(mut self, quality: crate::MotionQuality) -> Self {
2640        self.motion_quality = quality;
2641        self
2642    }
2643
2644    #[must_use]
2645    pub fn extension(mut self, extension: impl ScriptViewExtension + 'static) -> Self {
2646        self.extensions.push(Box::new(extension));
2647        self
2648    }
2649
2650    #[must_use]
2651    pub fn key_binding(mut self, binding: KeyBindingSpec) -> Self {
2652        self.key_bindings.push(binding);
2653        self
2654    }
2655
2656    #[must_use]
2657    pub const fn viewport_breakpoints(mut self, breakpoints: ViewportBreakpoints) -> Self {
2658        self.viewport_breakpoints = breakpoints;
2659        self
2660    }
2661
2662    #[must_use]
2663    pub fn calendar_clock(mut self, clock: crate::CalendarClock) -> Self {
2664        self.calendar_clock = clock;
2665        self
2666    }
2667
2668    /// Inject a presentation wall clock, independent from animation and calendar clocks.
2669    #[must_use]
2670    pub fn wall_clock(mut self, clock: crate::WallClock) -> Self {
2671        self.wall_clock = clock;
2672        self
2673    }
2674
2675    #[must_use]
2676    pub fn runtime_clock(mut self, clock: crate::RuntimeClock) -> Self {
2677        self.runtime_clock = Some(clock);
2678        self
2679    }
2680
2681    #[must_use]
2682    pub fn font_source(mut self, font: crate::FontSource) -> Self {
2683        self.fonts.push(font);
2684        self
2685    }
2686
2687    #[must_use]
2688    pub fn font_sources(mut self, fonts: impl IntoIterator<Item = crate::FontSource>) -> Self {
2689        self.fonts.extend(fonts);
2690        self
2691    }
2692
2693    /// Apply host-owned user preferences to every theme loaded by this view.
2694    #[must_use]
2695    pub fn theme_token_overrides(mut self, overrides: ThemeTokenOverrides) -> Self {
2696        self.theme_token_overrides = overrides;
2697        self
2698    }
2699
2700    /// Raise or lower the per-execution script operation budget for this
2701    /// view's scripts. Omitting this builder keeps the runtime's built-in
2702    /// 1,000,000-operation budget; hosts that run known one-shot cacheable
2703    /// script phases may raise it. The limit is applied to every engine
2704    /// instantiated for this view, including hot-reload candidates and
2705    /// additional windows.
2706    /// Zero normalizes to one. This quota does not promise a frame time or
2707    /// preempt native Rust work. Trusted extensions run after builder policy.
2708    #[must_use]
2709    pub fn operation_limit(mut self, limit: u64) -> Self {
2710        self.execution_policy.operation_limit = Some(limit);
2711        self
2712    }
2713
2714    /// Set trusted parser depth limits; default global=64/function=64.
2715    /// Zero normalizes to one. Builder policy is applied before trusted
2716    /// extensions, which may override it; the same ordering applies to children.
2717    #[must_use]
2718    pub fn expression_depth_limits(mut self, global: usize, functions: usize) -> Self {
2719        self.execution_policy.expression_depth_limits = Some((global, functions));
2720        self
2721    }
2722
2723    /// Read, compile, initialize, and render the app before opening GPUI.
2724    ///
2725    /// # Errors
2726    ///
2727    /// Returns [`ScriptViewError`] for source I/O, compilation, lifecycle, or
2728    /// initial rendering failures, or an in-memory source option used on
2729    /// another source.
2730    pub fn prepare(mut self) -> Result<PreparedScriptView, ScriptViewError> {
2731        if let Some(option) = self.misplaced_source_option {
2732            return Err(ScriptViewError::SourceOption(option));
2733        }
2734        if let Some(path) = self
2735            .ui_override_env
2736            .as_deref()
2737            .and_then(std::env::var_os)
2738            .filter(|path| !path.is_empty())
2739        {
2740            self.source = UiSource::Files(PathBuf::from(path));
2741        }
2742        match std::mem::replace(&mut self.source, UiSource::Files(PathBuf::new())) {
2743            UiSource::Files(path) => {
2744                let entry = file_entry(path)?;
2745                self.prepare_files(entry)
2746            }
2747            UiSource::Embedded(ui) => {
2748                let tree = ui.tree()?;
2749                if self.token_base.is_none() {
2750                    self.token_base = tree.token_base;
2751                }
2752                self.fonts.extend(tree.fonts);
2753                self.prepare_sources(tree.sources)
2754            }
2755            UiSource::Sources(sources) => self.prepare_sources(*sources),
2756        }
2757    }
2758
2759    /// The runtime state every source starts from: motion, breakpoints,
2760    /// clocks and key bindings from the builder.
2761    fn base_runtime_state(&self) -> UiRuntimeState {
2762        let mut runtime_state = UiRuntimeState::new();
2763        runtime_state.motions = MotionRuntime::new(self.motion_preference);
2764        runtime_state.motions.set_quality(self.motion_quality);
2765        runtime_state.responsive = ResponsiveRuntime::new(self.viewport_breakpoints);
2766        runtime_state.calendar_clock = self.calendar_clock.clone();
2767        runtime_state.wall_clock = self.wall_clock.clone();
2768        runtime_state.clock = self.runtime_clock.clone().unwrap_or_default();
2769        runtime_state.key_bindings.clone_from(&self.key_bindings);
2770        runtime_state
2771    }
2772
2773    // Only hot reload keeps the theme layers, to rebuild themes from them.
2774    #[cfg_attr(not(feature = "dev-reload"), allow(clippy::needless_pass_by_value))]
2775    fn window_factory(
2776        &self,
2777        program: WindowProgram,
2778        runtime: Rc<RefCell<UiRuntimeState>>,
2779        extensions: Rc<Vec<Box<dyn ScriptViewExtension>>>,
2780        theme: &ThemeVariant,
2781        theme_layers: ThemeLayers,
2782    ) -> Rc<ScriptWindowFactory> {
2783        #[cfg(not(feature = "dev-reload"))]
2784        let _ = &theme_layers;
2785        Rc::new(ScriptWindowFactory {
2786            program: RefCell::new(program),
2787            runtime,
2788            extensions,
2789            theme: theme.clone(),
2790            #[cfg(feature = "dev-reload")]
2791            theme_layers: RefCell::new(theme_layers),
2792            show_error_banner: Cell::new(true),
2793            error_reporting: RefCell::new(ErrorReporting::default()),
2794            render_islands: Cell::new(None),
2795            focus_indicators: Cell::new(FocusIndicators::Navigation),
2796            execution_policy: self.execution_policy,
2797            accept_file_drops: self.accept_file_drops,
2798            #[cfg(feature = "dev-reload")]
2799            development: self.development,
2800        })
2801    }
2802
2803    fn prepare_files(mut self, entry: PathBuf) -> Result<PreparedScriptView, ScriptViewError> {
2804        let source = fs::read_to_string(&entry).map_err(|source| ScriptViewError::Io {
2805            path: entry.clone(),
2806            source,
2807        })?;
2808        let extensions = Rc::new(std::mem::take(&mut self.extensions));
2809        let mut engine = RuntimeEngine::new();
2810        self.execution_policy.apply(&mut engine);
2811        configure_extension_engine(&extensions, &mut engine).map_err(ScriptViewError::Extension)?;
2812        let theme_layers = file_theme_layers(
2813            engine.engine(),
2814            &entry,
2815            self.token_base.as_deref(),
2816            &self.theme_token_overrides,
2817        )?;
2818        let (ui_root, theme_path, theme) = load_primary_file_theme(&engine, &entry, &theme_layers)?;
2819        let style_path = ui_root.join("styles.rhai");
2820        let mut fonts = std::mem::take(&mut self.fonts);
2821        fonts.extend(load_file_fonts(&ui_root.join("fonts"))?);
2822        crate::validate_font_sources(&fonts)?;
2823        let manifest = load_file_manifest(&ui_root, &entry)?;
2824        let (module_cache, compiled) = engine.with_program_preparation(|engine| {
2825            let module_cache =
2826                configure_file_modules(engine, &ui_root, &entry, &theme_path, &style_path)?;
2827            let compiled =
2828                engine.compile_self_contained_named(&entry.to_string_lossy(), &source)?;
2829            Ok::<_, ScriptViewError>((module_cache, compiled))
2830        })?;
2831        #[cfg(not(feature = "dev-reload"))]
2832        let _ = &module_cache;
2833        let component_exports = engine.component_exports()?;
2834        let component_renderers = engine.component_renderer_snapshot()?;
2835        manifest.validate_components(&component_exports)?;
2836        let component_styles =
2837            load_file_component_styles(engine.engine(), &style_path, &component_exports)?;
2838        let state_schema = engine.root_state_schema(&compiled)?;
2839        let mut runtime_state = self.base_runtime_state();
2840        runtime_state.locale = load_locale_directory(engine.engine(), &ui_root.join("locales"))?;
2841        let themes = load_theme_directory(
2842            engine.engine(),
2843            &ui_root.join("themes"),
2844            &theme,
2845            &theme_layers,
2846        )?;
2847        validate_component_tokens(&themes, &component_exports)?;
2848        runtime_state.theme = Some(themes);
2849        runtime_state.audit_rules = load_file_profile(engine.engine(), &ui_root)?.audit;
2850        runtime_state.replace_component_styles_from_host(component_styles);
2851        register_file_assets(&runtime_state, &ui_root)?;
2852        preload_component_assets(&runtime_state, &component_exports)?;
2853        preload_lucide_icons(&runtime_state, file_lucide_icons(&ui_root)?)?;
2854        for extension in extensions.iter() {
2855            extension
2856                .configure_runtime(&mut runtime_state)
2857                .map_err(ScriptViewError::Extension)?;
2858        }
2859        manifest.activate(&mut runtime_state.capabilities)?;
2860        let runtime = Rc::new(RefCell::new(runtime_state));
2861        let program = WindowProgram {
2862            compiled: compiled.clone(),
2863            state_schema: state_schema.clone(),
2864            component_exports,
2865            component_renderers,
2866        };
2867        let factory = self.window_factory(program, runtime, extensions, &theme, theme_layers);
2868        Ok(PreparedScriptView {
2869            engine,
2870            theme,
2871            entry,
2872            ui_root,
2873            theme_path,
2874            style_path,
2875            development: self.development,
2876            factory,
2877            executor_clock: self.runtime_clock.is_none(),
2878            key_bindings: self.key_bindings,
2879            fonts,
2880            #[cfg(feature = "dev-reload")]
2881            module_cache,
2882        })
2883    }
2884
2885    fn prepare_sources(
2886        mut self,
2887        sources: UiSources,
2888    ) -> Result<PreparedScriptView, ScriptViewError> {
2889        crate::validate_font_sources(&self.fonts)?;
2890        let entry = sources.scripts.load(&sources.entry)?;
2891        validate_manifest_entry(&sources.manifest, &sources.entry)?;
2892        let extensions = Rc::new(std::mem::take(&mut self.extensions));
2893        let mut engine = RuntimeEngine::new();
2894        self.execution_policy.apply(&mut engine);
2895        configure_extension_engine(&extensions, &mut engine).map_err(ScriptViewError::Extension)?;
2896        let theme_layers = embedded_theme_layers(
2897            engine.engine(),
2898            self.token_base.as_deref(),
2899            &self.theme_token_overrides,
2900        )?;
2901        let theme = load_theme_with_overrides(
2902            engine.engine(),
2903            "<embedded-theme>",
2904            &sources.theme_source,
2905            &theme_layers,
2906        )?;
2907        engine.set_module_resolver(RestrictedModuleResolver::from_source(&sources.scripts)?);
2908        let compiled = engine.with_program_preparation(|engine| {
2909            preload_component_modules(engine, sources.scripts.module_ids())?;
2910            engine
2911                .compile_self_contained_named(sources.entry.as_str(), &entry.source)
2912                .map_err(ScriptViewError::from)
2913        })?;
2914        let component_exports = engine.component_exports()?;
2915        let component_renderers = engine.component_renderer_snapshot()?;
2916        sources.manifest.validate_components(&component_exports)?;
2917        let component_styles = sources.component_style_source.map_or_else(
2918            || Ok(ComponentStyleSheet::default()),
2919            |source| {
2920                load_component_styles(
2921                    engine.engine(),
2922                    "<embedded-component-styles>",
2923                    &source,
2924                    &component_exports,
2925                )
2926            },
2927        )?;
2928        let state_schema = engine.root_state_schema(&compiled)?;
2929        let mut runtime_state = self.base_runtime_state();
2930        runtime_state.locale = load_embedded_locales(engine.engine(), sources.locales)?;
2931        runtime_state.theme = Some(validated_themes(
2932            load_embedded_themes(engine.engine(), sources.themes, &theme, &theme_layers)?,
2933            &component_exports,
2934        )?);
2935        runtime_state.replace_component_styles_from_host(component_styles);
2936        if let Some(source) = &sources.profile_source {
2937            runtime_state.audit_rules =
2938                crate::load_profile_source(engine.engine(), "<embedded-profile>", source)
2939                    .map_err(ScriptViewError::Extension)?
2940                    .audit;
2941        }
2942        let lucide = sources
2943            .assets
2944            .keys()
2945            .filter_map(|asset| asset.strip_prefix("lucide/"))
2946            .map(ToOwned::to_owned)
2947            .collect::<Vec<_>>();
2948        if !sources.assets.is_empty() {
2949            runtime_state
2950                .assets
2951                .register("app", InMemoryAssetProvider::new(sources.assets))?;
2952        }
2953        preload_component_assets(&runtime_state, &component_exports)?;
2954        preload_lucide_icons(&runtime_state, lucide)?;
2955        for extension in extensions.iter() {
2956            extension
2957                .configure_runtime(&mut runtime_state)
2958                .map_err(ScriptViewError::Extension)?;
2959        }
2960        sources.manifest.activate(&mut runtime_state.capabilities)?;
2961        let runtime = Rc::new(RefCell::new(runtime_state));
2962        let program = WindowProgram {
2963            compiled: compiled.clone(),
2964            state_schema: state_schema.clone(),
2965            component_exports,
2966            component_renderers,
2967        };
2968        let factory = self.window_factory(program, runtime, extensions, &theme, theme_layers);
2969        Ok(PreparedScriptView {
2970            engine,
2971            theme,
2972            entry: PathBuf::new(),
2973            ui_root: PathBuf::new(),
2974            theme_path: PathBuf::new(),
2975            style_path: PathBuf::new(),
2976            development: self.development,
2977            factory,
2978            executor_clock: self.runtime_clock.is_none(),
2979            key_bindings: self.key_bindings,
2980            fonts: self.fonts,
2981            #[cfg(feature = "dev-reload")]
2982            module_cache: ModuleCompileCache::new(),
2983        })
2984    }
2985}
2986
2987/// The entry script at `path`: the file itself, or in a directory the module
2988/// its `app.toml` names.
2989fn file_entry(path: PathBuf) -> Result<PathBuf, ScriptViewError> {
2990    if !path.is_dir() {
2991        return Ok(path);
2992    }
2993    let manifest_path = path.join("app.toml");
2994    let source = fs::read_to_string(&manifest_path).map_err(|source| ScriptViewError::Io {
2995        path: manifest_path,
2996        source,
2997    })?;
2998    let manifest: AppManifest =
2999        toml::from_str(&source).map_err(|error| ScriptViewError::Manifest(error.to_string()))?;
3000    Ok(path.join(format!("{}.rhai", manifest.entry)))
3001}
3002
3003fn load_embedded_locales(
3004    engine: &rhai::Engine,
3005    sources: Vec<(String, String)>,
3006) -> Result<Option<LocaleManager>, ScriptViewError> {
3007    let mut bundles = sources
3008        .into_iter()
3009        .map(|(name, source)| {
3010            load_locale_source(engine, &name, &source)
3011                .map_err(|error| ScriptViewError::Locale(error.to_string()))
3012        })
3013        .collect::<Result<Vec<_>, _>>()?;
3014    bundles.sort_by(|left, right| left.locale.cmp(&right.locale));
3015    if bundles.is_empty() {
3016        return Ok(None);
3017    }
3018    let fallback = bundles
3019        .iter()
3020        .find(|bundle| bundle.locale == "en")
3021        .unwrap_or(&bundles[0])
3022        .locale
3023        .clone();
3024    Ok(Some(
3025        LocaleManager::new(bundles, fallback.clone(), fallback)
3026            .map_err(|error| ScriptViewError::Locale(error.to_string()))?,
3027    ))
3028}
3029
3030fn load_embedded_themes(
3031    engine: &rhai::Engine,
3032    sources: Vec<(String, String)>,
3033    primary: &ThemeVariant,
3034    overrides: &ThemeLayers,
3035) -> Result<ThemeManager, ScriptViewError> {
3036    let mut variants = BTreeMap::from([(
3037        (primary.family.clone(), primary.name.clone()),
3038        primary.clone(),
3039    )]);
3040    for (name, source) in sources {
3041        let variant = load_theme_with_overrides(engine, &name, &source, overrides)?;
3042        insert_theme_variant(&mut variants, variant)?;
3043    }
3044    theme_manager(variants.into_values(), primary)
3045}
3046
3047fn module_id_from_path(root: &Path, path: &Path) -> Result<ModuleId, ScriptViewError> {
3048    let relative = path
3049        .strip_prefix(root)
3050        .map_err(|_| ScriptViewError::ModulePath(path.to_path_buf()))?;
3051    let id = relative
3052        .with_extension("")
3053        .components()
3054        .map(|component| component.as_os_str().to_string_lossy())
3055        .collect::<Vec<_>>()
3056        .join("/");
3057    Ok(ModuleId::parse(id)?)
3058}
3059
3060fn load_file_manifest(root: &Path, entry: &Path) -> Result<AppManifest, ScriptViewError> {
3061    let path = root.join("app.toml");
3062    let source = fs::read_to_string(&path).map_err(|source| ScriptViewError::Io {
3063        path: path.clone(),
3064        source,
3065    })?;
3066    let manifest: AppManifest =
3067        toml::from_str(&source).map_err(|error| ScriptViewError::Manifest(error.to_string()))?;
3068    let entry = module_id_from_path(root, entry)?;
3069    validate_manifest_entry(&manifest, &entry)?;
3070    Ok(manifest)
3071}
3072
3073fn load_primary_file_theme(
3074    engine: &RuntimeEngine,
3075    entry: &Path,
3076    overrides: &ThemeLayers,
3077) -> Result<(PathBuf, PathBuf, ThemeVariant), ScriptViewError> {
3078    let root = entry
3079        .parent()
3080        .unwrap_or_else(|| Path::new("."))
3081        .to_path_buf();
3082    let path = root.join("theme.rhai");
3083    let source = fs::read_to_string(&path).map_err(|source| ScriptViewError::Io {
3084        path: path.clone(),
3085        source,
3086    })?;
3087    let theme =
3088        load_theme_with_overrides(engine.engine(), &path.to_string_lossy(), &source, overrides)?;
3089    Ok((root, path, theme))
3090}
3091
3092fn load_file_component_styles(
3093    engine: &rhai::Engine,
3094    path: &Path,
3095    components: &ComponentRegistry,
3096) -> Result<ComponentStyleSheet, ScriptViewError> {
3097    match fs::read_to_string(path) {
3098        Ok(source) => Ok(load_component_styles(
3099            engine,
3100            &path.to_string_lossy(),
3101            &source,
3102            components,
3103        )?),
3104        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
3105            Ok(ComponentStyleSheet::default())
3106        }
3107        Err(source) => Err(ScriptViewError::Io {
3108            path: path.to_path_buf(),
3109            source,
3110        }),
3111    }
3112}
3113
3114fn configure_file_modules(
3115    engine: &mut RuntimeEngine,
3116    root: &Path,
3117    entry: &Path,
3118    theme: &Path,
3119    styles: &Path,
3120) -> Result<ModuleCompileCache, ScriptViewError> {
3121    let modules = discover_modules(root, entry, theme, styles)?;
3122    let source = FileScriptSource::new(root, modules)?;
3123    let mut cache = ModuleCompileCache::new();
3124    cache.refresh(engine.engine(), &source, source.module_ids())?;
3125    engine.set_module_resolver(RestrictedModuleResolver::from_source_with_cache(
3126        &source, &cache,
3127    )?);
3128    preload_component_modules(engine, source.module_ids())?;
3129    Ok(cache)
3130}
3131
3132fn preload_component_modules(
3133    engine: &mut RuntimeEngine,
3134    modules: impl IntoIterator<Item = ModuleId>,
3135) -> Result<(), ScriptViewError> {
3136    let imports = modules
3137        .into_iter()
3138        .filter(|id| {
3139            ["components/", "layouts/", "patterns/"]
3140                .iter()
3141                .any(|category| id.as_str().starts_with(category))
3142        })
3143        .enumerate()
3144        .map(|(index, id)| format!("import \"{id}\" as component_{index};"))
3145        .collect::<Vec<_>>()
3146        .join("\n");
3147    if !imports.is_empty() {
3148        engine.compile_self_contained_named("<component-registry>", &imports)?;
3149    }
3150    Ok(())
3151}
3152
3153fn register_file_assets(runtime: &UiRuntimeState, root: &Path) -> Result<(), ScriptViewError> {
3154    let asset_root = root.join("assets");
3155    if asset_root.exists() {
3156        runtime
3157            .assets
3158            .register("app", DirectoryAssetProvider::new(&asset_root)?)?;
3159    }
3160    Ok(())
3161}
3162
3163fn load_file_fonts(directory: &Path) -> Result<Vec<crate::FontSource>, ScriptViewError> {
3164    if !directory.exists() {
3165        return Ok(Vec::new());
3166    }
3167    let mut paths = collect_font_paths(directory)?;
3168    paths.retain(|path| {
3169        path.extension()
3170            .and_then(|extension| extension.to_str())
3171            .is_some_and(|extension| {
3172                matches!(
3173                    extension.to_ascii_lowercase().as_str(),
3174                    "ttf" | "otf" | "ttc"
3175                )
3176            })
3177    });
3178    paths.sort();
3179    paths
3180        .into_iter()
3181        .map(|path| {
3182            let bytes = fs::read(&path).map_err(|error| crate::FontError::Io {
3183                path: path.display().to_string(),
3184                message: error.to_string(),
3185            })?;
3186            let label = path
3187                .file_name()
3188                .and_then(|name| name.to_str())
3189                .unwrap_or("font")
3190                .to_owned();
3191            crate::FontSource::new(label, bytes).map_err(ScriptViewError::from)
3192        })
3193        .collect()
3194}
3195
3196fn collect_font_paths(directory: &Path) -> Result<Vec<PathBuf>, ScriptViewError> {
3197    let mut pending = vec![directory.to_path_buf()];
3198    let mut files = Vec::new();
3199    while let Some(current) = pending.pop() {
3200        for entry in fs::read_dir(&current).map_err(|error| crate::FontError::Io {
3201            path: current.display().to_string(),
3202            message: error.to_string(),
3203        })? {
3204            let path = entry
3205                .map_err(|error| crate::FontError::Io {
3206                    path: current.display().to_string(),
3207                    message: error.to_string(),
3208                })?
3209                .path();
3210            if path.is_dir() {
3211                pending.push(path);
3212            } else {
3213                files.push(path);
3214            }
3215        }
3216    }
3217    Ok(files)
3218}
3219
3220fn install_declared_fonts(
3221    fonts: Vec<crate::FontSource>,
3222    cx: &mut App,
3223) -> Result<(), ScriptViewError> {
3224    if fonts.is_empty() {
3225        return Ok(());
3226    }
3227    let fresh = {
3228        let loaded = &cx.global::<ScriptRuntimeInstallation>().loaded_fonts;
3229        fonts
3230            .into_iter()
3231            .filter(|font| !loaded.contains(&font.fingerprint()))
3232            .collect::<Vec<_>>()
3233    };
3234    if fresh.is_empty() {
3235        return Ok(());
3236    }
3237    let fingerprints = fresh
3238        .iter()
3239        .map(crate::FontSource::fingerprint)
3240        .collect::<Vec<_>>();
3241    let bytes = fresh
3242        .into_iter()
3243        .map(|font| Cow::Owned(font.into_bytes()))
3244        .collect();
3245    cx.text_system()
3246        .add_fonts(bytes)
3247        .map_err(|error| crate::FontError::Load(error.to_string()))?;
3248    cx.global_mut::<ScriptRuntimeInstallation>()
3249        .loaded_fonts
3250        .extend(fingerprints);
3251    Ok(())
3252}
3253
3254fn preload_component_assets(
3255    runtime: &UiRuntimeState,
3256    components: &ComponentRegistry,
3257) -> Result<(), ScriptViewError> {
3258    let ids = components
3259        .iter()
3260        .flat_map(|(_, component)| component.metadata.assets.iter())
3261        .map(|asset| {
3262            let logical = Path::new(asset).with_extension("");
3263            let logical = logical
3264                .components()
3265                .map(|component| component.as_os_str().to_string_lossy())
3266                .collect::<Vec<_>>()
3267                .join("/");
3268            AssetId::parse(format!("app/{logical}")).map_err(ScriptViewError::Asset)
3269        })
3270        .collect::<Result<BTreeSet<_>, _>>()?;
3271    runtime.assets.preload_images(ids)?;
3272    Ok(())
3273}
3274
3275/// The Lucide icons `gpui-rhai add lucide/<name>` installed in `ui/assets/lucide/`,
3276/// preloaded like a component's assets so `asset("app/lucide/<name>")` draws.
3277fn preload_lucide_icons(
3278    runtime: &UiRuntimeState,
3279    names: impl IntoIterator<Item = String>,
3280) -> Result<(), ScriptViewError> {
3281    let ids = names
3282        .into_iter()
3283        .map(|name| AssetId::parse(format!("app/lucide/{name}")).map_err(ScriptViewError::Asset))
3284        .collect::<Result<Vec<_>, _>>()?;
3285    runtime.assets.preload_images(ids)?;
3286    Ok(())
3287}
3288
3289fn file_lucide_icons(root: &Path) -> Result<Vec<String>, ScriptViewError> {
3290    let directory = root.join("assets/lucide");
3291    if !directory.is_dir() {
3292        return Ok(Vec::new());
3293    }
3294    let entries = fs::read_dir(&directory).map_err(|source| ScriptViewError::Io {
3295        path: directory.clone(),
3296        source,
3297    })?;
3298    let mut names = Vec::new();
3299    for entry in entries {
3300        let path = entry
3301            .map_err(|source| ScriptViewError::Io {
3302                path: directory.clone(),
3303                source,
3304            })?
3305            .path();
3306        if path.extension().and_then(|extension| extension.to_str()) == Some("svg")
3307            && let Some(name) = path.file_stem().and_then(|stem| stem.to_str())
3308        {
3309            names.push(name.to_owned());
3310        }
3311    }
3312    names.sort();
3313    Ok(names)
3314}
3315
3316fn validate_manifest_entry(
3317    manifest: &AppManifest,
3318    entry: &ModuleId,
3319) -> Result<(), ScriptViewError> {
3320    if &manifest.entry == entry {
3321        Ok(())
3322    } else {
3323        Err(ScriptViewError::ManifestEntry {
3324            manifest: manifest.entry.clone(),
3325            host: entry.clone(),
3326        })
3327    }
3328}
3329
3330fn discover_modules(
3331    root: &Path,
3332    entry: &Path,
3333    theme: &Path,
3334    styles: &Path,
3335) -> Result<Vec<ModuleId>, ScriptViewError> {
3336    let mut pending = vec![root.to_path_buf()];
3337    let mut modules = Vec::new();
3338    while let Some(directory) = pending.pop() {
3339        for item in fs::read_dir(&directory).map_err(|source| ScriptViewError::Io {
3340            path: directory.clone(),
3341            source,
3342        })? {
3343            let item = item.map_err(|source| ScriptViewError::Io {
3344                path: directory.clone(),
3345                source,
3346            })?;
3347            let path = item.path();
3348            if path.is_dir() {
3349                if !matches!(
3350                    path.file_name().and_then(|name| name.to_str()),
3351                    Some("locales" | "themes")
3352                ) {
3353                    pending.push(path);
3354                }
3355            } else if path.extension().and_then(|extension| extension.to_str()) == Some("rhai")
3356                && path != entry
3357                && path != theme
3358                && path != styles
3359                && path != root.join(TOKEN_BASE_FILE)
3360                && path != root.join(PROFILE_FILE)
3361            {
3362                modules.push(module_id_from_path(root, &path)?);
3363            }
3364        }
3365    }
3366    modules.sort();
3367    Ok(modules)
3368}
3369
3370fn load_locale_directory(
3371    engine: &rhai::Engine,
3372    directory: &Path,
3373) -> Result<Option<LocaleManager>, ScriptViewError> {
3374    if !directory.exists() {
3375        return Ok(None);
3376    }
3377    let mut paths = fs::read_dir(directory)
3378        .map_err(|source| ScriptViewError::Io {
3379            path: directory.to_path_buf(),
3380            source,
3381        })?
3382        .map(|entry| {
3383            entry
3384                .map(|entry| entry.path())
3385                .map_err(|source| ScriptViewError::Io {
3386                    path: directory.to_path_buf(),
3387                    source,
3388                })
3389        })
3390        .collect::<Result<Vec<_>, _>>()?;
3391    paths.retain(|path| path.extension().and_then(|extension| extension.to_str()) == Some("rhai"));
3392    paths.sort();
3393    let mut bundles = Vec::<LocaleBundle>::new();
3394    for path in paths {
3395        let source = fs::read_to_string(&path).map_err(|source| ScriptViewError::Io {
3396            path: path.clone(),
3397            source,
3398        })?;
3399        bundles.push(
3400            load_locale_source(engine, &path.to_string_lossy(), &source)
3401                .map_err(|error| ScriptViewError::Locale(error.to_string()))?,
3402        );
3403    }
3404    if bundles.is_empty() {
3405        return Ok(None);
3406    }
3407    let fallback = bundles
3408        .iter()
3409        .find(|bundle| bundle.locale == "en")
3410        .unwrap_or(&bundles[0])
3411        .locale
3412        .clone();
3413    Ok(Some(
3414        LocaleManager::new(bundles, fallback.clone(), fallback)
3415            .map_err(|error| ScriptViewError::Locale(error.to_string()))?,
3416    ))
3417}
3418
3419fn load_theme_directory(
3420    engine: &rhai::Engine,
3421    directory: &Path,
3422    primary: &ThemeVariant,
3423    overrides: &ThemeLayers,
3424) -> Result<ThemeManager, ScriptViewError> {
3425    let mut variants = BTreeMap::from([(
3426        (primary.family.clone(), primary.name.clone()),
3427        primary.clone(),
3428    )]);
3429    if directory.exists() {
3430        let mut paths = fs::read_dir(directory)
3431            .map_err(|source| ScriptViewError::Io {
3432                path: directory.to_path_buf(),
3433                source,
3434            })?
3435            .map(|entry| {
3436                entry
3437                    .map(|entry| entry.path())
3438                    .map_err(|source| ScriptViewError::Io {
3439                        path: directory.to_path_buf(),
3440                        source,
3441                    })
3442            })
3443            .collect::<Result<Vec<_>, _>>()?;
3444        paths.retain(|path| {
3445            path.extension().and_then(|extension| extension.to_str()) == Some("rhai")
3446        });
3447        paths.sort();
3448        for path in paths {
3449            let source = fs::read_to_string(&path).map_err(|source| ScriptViewError::Io {
3450                path: path.clone(),
3451                source,
3452            })?;
3453            let variant =
3454                load_theme_with_overrides(engine, &path.to_string_lossy(), &source, overrides)?;
3455            insert_theme_variant(&mut variants, variant)?;
3456        }
3457    }
3458    theme_manager(variants.into_values(), primary)
3459}
3460
3461/// A reloaded token base and themes, checked before they become visible.
3462#[cfg(feature = "dev-reload")]
3463struct ThemeCandidate {
3464    /// The new token base, when the application has a token file.
3465    base: Option<crate::TokenLayer>,
3466    themes: ThemeManager,
3467    theme: ThemeVariant,
3468}
3469
3470/// The token layers beneath and above every palette theme of one view.
3471#[derive(Clone, Debug, Default)]
3472pub(crate) struct ThemeLayers {
3473    base: Option<crate::TokenLayer>,
3474    overrides: ThemeTokenOverrides,
3475}
3476
3477/// The token base of a file application: the builder source, else
3478/// `ui/tokens.rhai` when present.
3479fn file_theme_layers(
3480    engine: &rhai::Engine,
3481    entry: &Path,
3482    builder_source: Option<&str>,
3483    overrides: &ThemeTokenOverrides,
3484) -> Result<ThemeLayers, ScriptViewError> {
3485    let path = entry
3486        .parent()
3487        .unwrap_or_else(|| Path::new("."))
3488        .join(TOKEN_BASE_FILE);
3489    let base = match builder_source {
3490        Some(source) => Some((String::from("<token-base>"), source.to_owned())),
3491        None if path.exists() => Some((
3492            path.to_string_lossy().into_owned(),
3493            fs::read_to_string(&path).map_err(|source| ScriptViewError::Io {
3494                path: path.clone(),
3495                source,
3496            })?,
3497        )),
3498        None => None,
3499    };
3500    Ok(ThemeLayers {
3501        base: base
3502            .map(|(name, source)| {
3503                crate::load_token_base(engine, &name, &source)
3504                    .map_err(|error| ScriptViewError::Theme(error.to_string()))
3505            })
3506            .transpose()?,
3507        overrides: overrides.clone(),
3508    })
3509}
3510
3511fn load_file_profile(
3512    engine: &rhai::Engine,
3513    ui_root: &Path,
3514) -> Result<crate::Profile, ScriptViewError> {
3515    let path = ui_root.join(PROFILE_FILE);
3516    if !path.exists() {
3517        return Ok(crate::Profile::default());
3518    }
3519    let source = fs::read_to_string(&path).map_err(|source| ScriptViewError::Io {
3520        path: path.clone(),
3521        source,
3522    })?;
3523    crate::load_profile_source(engine, &path.to_string_lossy(), &source)
3524        .map_err(ScriptViewError::Extension)
3525}
3526
3527fn embedded_theme_layers(
3528    engine: &rhai::Engine,
3529    token_base: Option<&str>,
3530    overrides: &ThemeTokenOverrides,
3531) -> Result<ThemeLayers, ScriptViewError> {
3532    Ok(ThemeLayers {
3533        base: token_base
3534            .map(|source| {
3535                crate::load_token_base(engine, "<embedded-tokens>", source)
3536                    .map_err(|error| ScriptViewError::Theme(error.to_string()))
3537            })
3538            .transpose()?,
3539        overrides: overrides.clone(),
3540    })
3541}
3542
3543/// File name of the token base inside the UI root.
3544pub(crate) const TOKEN_BASE_FILE: &str = "tokens.rhai";
3545/// File name of the profile configuration inside the UI root.
3546pub(crate) const PROFILE_FILE: &str = "profile.rhai";
3547
3548fn load_theme_with_overrides(
3549    engine: &rhai::Engine,
3550    source_name: &str,
3551    source: &str,
3552    layers: &ThemeLayers,
3553) -> Result<ThemeVariant, ScriptViewError> {
3554    crate::load_theme_with_layers(
3555        engine,
3556        layers.base.as_ref(),
3557        source_name,
3558        source,
3559        &layers.overrides,
3560    )
3561    .map_err(|error| ScriptViewError::Theme(error.to_string()))
3562}
3563
3564fn validated_themes(
3565    themes: ThemeManager,
3566    exports: &crate::ComponentRegistry,
3567) -> Result<ThemeManager, ScriptViewError> {
3568    validate_component_tokens(&themes, exports)?;
3569    Ok(themes)
3570}
3571
3572/// Check every loaded theme against the tokens declared by components.
3573fn validate_component_tokens(
3574    themes: &ThemeManager,
3575    exports: &crate::ComponentRegistry,
3576) -> Result<(), ScriptViewError> {
3577    for variant in themes.variants() {
3578        for (_, definition) in exports.iter() {
3579            let metadata = &definition.metadata;
3580            let environment = metadata
3581                .environment
3582                .iter()
3583                .map(|name| format!("environment.{name}"))
3584                .collect::<Vec<_>>();
3585            variant
3586                .require(
3587                    metadata.id.as_str(),
3588                    metadata
3589                        .tokens
3590                        .iter()
3591                        .chain(&environment)
3592                        .map(String::as_str),
3593                )
3594                .map_err(|error| ScriptViewError::Theme(error.to_string()))?;
3595        }
3596    }
3597    Ok(())
3598}
3599
3600fn insert_theme_variant(
3601    variants: &mut BTreeMap<(String, String), ThemeVariant>,
3602    variant: ThemeVariant,
3603) -> Result<(), ScriptViewError> {
3604    let key = (variant.family.clone(), variant.name.clone());
3605    if let Some(existing) = variants.get(&key) {
3606        if existing == &variant {
3607            return Ok(());
3608        }
3609        return Err(ScriptViewError::Theme(format!(
3610            "theme `{}/{}` is defined more than once with different tokens",
3611            key.0, key.1
3612        )));
3613    }
3614    variants.insert(key, variant);
3615    Ok(())
3616}
3617
3618fn theme_manager(
3619    variants: impl IntoIterator<Item = ThemeVariant>,
3620    primary: &ThemeVariant,
3621) -> Result<ThemeManager, ScriptViewError> {
3622    ThemeManager::from_variants(
3623        variants,
3624        ThemeSelection::new(primary.family.clone(), primary.name.clone()),
3625    )
3626    .map_err(|error| ScriptViewError::Theme(error.to_string()))
3627}
3628
3629#[derive(Clone)]
3630struct WindowProgram {
3631    compiled: CompiledUi,
3632    state_schema: ComponentStateSchema,
3633    component_exports: ComponentRegistry,
3634    component_renderers: BTreeMap<ModuleId, crate::engine::RegisteredComponentRender>,
3635}
3636
3637struct ScriptWindowFactory {
3638    program: RefCell<WindowProgram>,
3639    runtime: Rc<RefCell<UiRuntimeState>>,
3640    extensions: Rc<Vec<Box<dyn ScriptViewExtension>>>,
3641    theme: ThemeVariant,
3642    #[cfg(feature = "dev-reload")]
3643    theme_layers: RefCell<ThemeLayers>,
3644    show_error_banner: Cell<bool>,
3645    /// The mounting view's reporting, which the script windows it opens share.
3646    error_reporting: RefCell<ErrorReporting>,
3647    /// The mounting view's [`ScriptViewConfig::render_islands`].
3648    render_islands: Cell<Option<bool>>,
3649    /// The mounting view's [`ScriptViewConfig::focus_indicators`].
3650    focus_indicators: Cell<FocusIndicators>,
3651    execution_policy: ScriptExecutionPolicy,
3652    /// [`ScriptView::accept_file_drops`], for every view the factory mounts.
3653    accept_file_drops: bool,
3654    #[cfg(feature = "dev-reload")]
3655    development: bool,
3656}
3657
3658impl ScriptWindowFactory {
3659    fn instantiate(
3660        &self,
3661        view_id: &str,
3662        window_id: &str,
3663        mount_lease: Option<&std::rc::Weak<()>>,
3664    ) -> Result<(RuntimeEngine, ScriptLifecycle, PrimitiveRegistry), ScriptViewError> {
3665        let mut engine = RuntimeEngine::new();
3666        self.execution_policy.apply(&mut engine);
3667        configure_extension_engine(&self.extensions, &mut engine)
3668            .map_err(ScriptViewError::Extension)?;
3669        let program = self.program.borrow().clone();
3670        engine.restore_component_exports(program.component_exports.clone())?;
3671        engine.restore_component_renderers(program.component_renderers.clone())?;
3672        let lifecycle = self.mount_lifecycle(
3673            &mut engine,
3674            program,
3675            view_id,
3676            window_id,
3677            WindowCommandPolicy::ApplicationOwned,
3678            false,
3679            mount_lease,
3680        )?;
3681        let primitives = engine.primitive_registry();
3682        primitives.set_file_drops(
3683            self.accept_file_drops
3684                .then(|| self.runtime.borrow().dropped_files.clone()),
3685        );
3686        Ok((engine, lifecycle, primitives))
3687    }
3688
3689    #[allow(clippy::too_many_arguments)]
3690    fn mount_lifecycle(
3691        &self,
3692        engine: &mut RuntimeEngine,
3693        program: WindowProgram,
3694        view_id: &str,
3695        window_id: &str,
3696        policy: WindowCommandPolicy,
3697        register_window: bool,
3698        mount_lease: Option<&std::rc::Weak<()>>,
3699    ) -> Result<ScriptLifecycle, ScriptViewError> {
3700        {
3701            let mut runtime = self.runtime.borrow_mut();
3702            if register_window {
3703                runtime
3704                    .windows
3705                    .register_open_for_view(window_id, policy, view_id)
3706                    .map_err(|error| ScriptViewError::Extension(error.to_string()))?;
3707            }
3708            if let Some(lease) = mount_lease {
3709                runtime
3710                    .windows
3711                    .qualify_mount(window_id, lease)
3712                    .map_err(|error| ScriptViewError::Extension(error.to_string()))?;
3713            }
3714            for extension in self.extensions.iter() {
3715                extension
3716                    .configure_window(window_id, &mut runtime)
3717                    .map_err(ScriptViewError::Extension)?;
3718            }
3719        }
3720        let mut lifecycle = ScriptLifecycle::new(
3721            program.compiled,
3722            Rc::clone(&self.runtime),
3723            ComponentInstancePath::root("View", view_id),
3724            Some(window_id.to_owned()),
3725            BTreeMap::new(),
3726            &program.state_schema,
3727        )?
3728        .with_view_id(view_id);
3729        if let Err(error) = lifecycle.start(engine) {
3730            let message = error.to_string();
3731            if let crate::LifecycleError::Runtime(runtime_error) = &error
3732                && let Ok(context) = lifecycle.diagnostic_context(engine, None)
3733            {
3734                return Err(ScriptViewError::ScriptDiagnostic {
3735                    message,
3736                    diagnostic: Box::new(Diagnostic::from_runtime(runtime_error, &context)),
3737                });
3738            }
3739            return Err(ScriptViewError::Lifecycle(error));
3740        }
3741        Ok(lifecycle)
3742    }
3743
3744    #[cfg(feature = "dev-reload")]
3745    fn update_program(
3746        &self,
3747        compiled: CompiledUi,
3748        state_schema: ComponentStateSchema,
3749        component_exports: ComponentRegistry,
3750        component_renderers: BTreeMap<ModuleId, crate::engine::RegisteredComponentRender>,
3751    ) {
3752        *self.program.borrow_mut() = WindowProgram {
3753            compiled,
3754            state_schema,
3755            component_exports,
3756            component_renderers,
3757        };
3758    }
3759
3760    fn program(&self) -> WindowProgram {
3761        self.program.borrow().clone()
3762    }
3763}
3764
3765#[derive(Default)]
3766struct NativeWindowRegistry {
3767    handles: BTreeMap<String, NativeWindowRegistration>,
3768    force_close: std::collections::BTreeSet<String>,
3769}
3770
3771#[derive(Clone)]
3772struct NativeWindowRegistration {
3773    handle: AnyWindowHandle,
3774    authority: NativeWindowAuthority,
3775}
3776
3777fn window_command_is_current(
3778    command: &crate::QueuedWindowCommand,
3779    windows: &crate::WindowCommandRegistry,
3780    cx: &App,
3781) -> bool {
3782    windows.is_current_target(command)
3783        && windows.is_current_origin(command)
3784        && (command.is_host_origin()
3785            || command.source_binding().is_some_and(|binding| {
3786                NativeWindowAuthority {
3787                    window: binding.window,
3788                    lease: binding.lease,
3789                }
3790                .is_current(cx)
3791            }))
3792}
3793
3794/// The runtime clock a mounted view uses unless its Host sets one: GPUI's
3795/// executor clock, which is the system clock in an application and the test
3796/// scheduler's in a test, where `advance_clock` moves timers and motion along
3797/// with GPUI's own timers instead of waiting on real time.
3798struct ExecutorRuntimeClock(gpui::BackgroundExecutor);
3799
3800impl crate::RuntimeClockSource for ExecutorRuntimeClock {
3801    fn now(&self) -> Instant {
3802        self.0.now()
3803    }
3804}
3805
3806pub struct PreparedScriptView {
3807    engine: RuntimeEngine,
3808    theme: ThemeVariant,
3809    entry: PathBuf,
3810    ui_root: PathBuf,
3811    theme_path: PathBuf,
3812    style_path: PathBuf,
3813    development: bool,
3814    factory: Rc<ScriptWindowFactory>,
3815    /// The Host set no runtime clock: mounting installs GPUI's.
3816    executor_clock: bool,
3817    key_bindings: Vec<KeyBindingSpec>,
3818    fonts: Vec<crate::FontSource>,
3819    #[cfg(feature = "dev-reload")]
3820    module_cache: ModuleCompileCache,
3821}
3822
3823impl PreparedScriptView {
3824    #[must_use]
3825    pub fn key_bindings(&self) -> &[KeyBindingSpec] {
3826        &self.key_bindings
3827    }
3828
3829    /// Mount one isolated script view into an existing GPUI window.
3830    ///
3831    /// # Errors
3832    ///
3833    /// Returns identity, lifecycle, extension, or watcher errors.
3834    pub fn mount(
3835        self,
3836        config: ScriptViewConfig,
3837        host: ScriptViewHost,
3838        window: &mut Window,
3839        cx: &mut App,
3840    ) -> Result<ScriptViewHandle, ScriptViewError> {
3841        self.mount_with_registry(
3842            config,
3843            host,
3844            &Rc::new(RefCell::new(NativeWindowRegistry::default())),
3845            WindowCommandPolicy::Disabled,
3846            window,
3847            cx,
3848        )
3849    }
3850
3851    /// Mount the single script command owner of an existing Rust-owned window.
3852    ///
3853    /// Unlike [`Self::mount`], this explicitly enables open/focus/close commands,
3854    /// registers the native window, and installs the script close interceptor.
3855    /// Rust still owns the window's root and layout. Other views on the same
3856    /// Host use ordinary `mount` and do not inherit this authority. This replaces
3857    /// the window's previous should-close callback; opt in only when delegating
3858    /// that policy to this view. Disposing the view does not close the window.
3859    ///
3860    /// # Errors
3861    ///
3862    /// Returns mount errors, [`ScriptViewError::WindowCommandOwner`] for an
3863    /// existing command owner, or [`ScriptViewError::WrongNativeWindow`] when
3864    /// the Host belongs to another native window.
3865    pub fn mount_window(
3866        self,
3867        config: ScriptViewConfig,
3868        host: ScriptViewHost,
3869        window: &mut Window,
3870        cx: &mut App,
3871    ) -> Result<ScriptViewHandle, ScriptViewError> {
3872        self.mount_with_registry(
3873            config,
3874            host,
3875            &Rc::new(RefCell::new(NativeWindowRegistry::default())),
3876            WindowCommandPolicy::ApplicationOwned,
3877            window,
3878            cx,
3879        )
3880    }
3881
3882    #[allow(clippy::too_many_lines)]
3883    fn mount_with_registry(
3884        mut self,
3885        config: ScriptViewConfig,
3886        host: ScriptViewHost,
3887        native_windows: &Rc<RefCell<NativeWindowRegistry>>,
3888        policy: WindowCommandPolicy,
3889        window: &mut Window,
3890        cx: &mut App,
3891    ) -> Result<ScriptViewHandle, ScriptViewError> {
3892        install(cx);
3893        install_declared_fonts(std::mem::take(&mut self.fonts), cx)?;
3894        #[cfg(feature = "dev-reload")]
3895        let watcher = development_watcher(self.development, &self.ui_root)?;
3896        let mount_lease = host.reserve_view(&config.view_id)?;
3897        self.factory
3898            .error_reporting
3899            .replace(config.error_reporting.clone());
3900        self.factory.render_islands.set(config.render_islands);
3901        self.factory.focus_indicators.set(config.focus_indicators);
3902        let window_authority = host
3903            .bind_window(&config.view_id, window.window_handle(), policy, cx)
3904            .inspect_err(|_| {
3905                host.unregister_view(&config.view_id, &mount_lease);
3906            })?;
3907        let window_id = host.window_id();
3908        if self.executor_clock {
3909            self.factory.runtime.borrow_mut().clock = crate::RuntimeClock::from_source(
3910                ExecutorRuntimeClock(cx.background_executor().clone()),
3911            );
3912        }
3913        self.factory
3914            .runtime
3915            .borrow_mut()
3916            .update_window_appearance(&window_id, system_appearance(window.appearance()));
3917        let lifecycle = mount_prepared_lifecycle(
3918            &self.factory,
3919            &mut self.engine,
3920            &host,
3921            &config.view_id,
3922            &window_id,
3923            policy,
3924            &mount_lease,
3925        )?;
3926        if window_authority.is_some() {
3927            self.factory
3928                .runtime
3929                .borrow_mut()
3930                .windows
3931                .bind_native(&window_id, window.window_handle().window_id())
3932                .map_err(|error| ScriptViewError::Extension(error.to_string()))?;
3933        }
3934        #[cfg(not(feature = "dev-reload"))]
3935        let _ = (
3936            &self.entry,
3937            &self.ui_root,
3938            &self.theme_path,
3939            &self.style_path,
3940            self.development,
3941        );
3942        let primitives = self.engine.primitive_registry();
3943        primitives.set_file_drops(
3944            self.factory
3945                .accept_file_drops
3946                .then(|| self.factory.runtime.borrow().dropped_files.clone()),
3947        );
3948        let timings = self.engine.take_timings();
3949        let factory = Rc::clone(&self.factory);
3950        let overlays = host.overlays();
3951        let view_id = config.view_id.clone();
3952        let view_host = host.clone();
3953        let (theme_handle, view_theme_handle) =
3954            theme_handles_for_lifecycle(&lifecycle, &self.theme, window, cx);
3955        let view_state = Rc::new(Cell::new(ScriptViewState::Active));
3956        let entity_view_state = Rc::clone(&view_state);
3957        let entity_activity_wake = crate::async_runtime::AsyncWake::default();
3958        let entity = cx.new(|entity_cx| {
3959            let runtime_tasks = spawn_host_runtime_tasks(
3960                entity_cx,
3961                &lifecycle,
3962                Rc::clone(&entity_view_state),
3963                entity_activity_wake.clone(),
3964            );
3965            let host_focus = entity_cx.focus_handle();
3966            #[cfg(feature = "dev-reload")]
3967            let reload_task = watcher
3968                .as_ref()
3969                .map(|_| spawn_host_reload_poll(entity_cx, Rc::clone(&entity_view_state)));
3970            ScriptHostView {
3971                mount_lease: mount_lease.clone(),
3972                view_id: view_id.clone(),
3973                window_id,
3974                engine: self.engine,
3975                lifecycle,
3976                primitives,
3977                last_failure: None,
3978                failure_serial: 0,
3979                reported_failure_serial: 0,
3980                presentation_diagnostics:
3981                    crate::presentation_diagnostic::PresentationDiagnostics::default(),
3982                theme: self.theme,
3983                theme_handle: view_theme_handle,
3984                #[cfg(feature = "dev-reload")]
3985                development: self.development,
3986                #[cfg(feature = "dev-reload")]
3987                inspector_open: false,
3988                timings,
3989                render_statistics: ScriptViewRenderStatistics::default(),
3990                derived_key: None,
3991                islands: IslandTable::new(config.render_islands, config.root_width),
3992                frame: None,
3993                overlays,
3994                host: view_host,
3995                paint_background: config.paint_background,
3996                show_error_banner: config.show_error_banner,
3997                error_reporting: config.error_reporting.clone(),
3998                window_drag_areas: config.window_drag_areas,
3999                focus_indicators: config.focus_indicators,
4000                navigating: false,
4001                content_bounds: None,
4002                factory,
4003                native_windows: Rc::clone(native_windows),
4004                host_focus,
4005                focus_handles: BTreeMap::new(),
4006                page_focus: BTreeMap::new(),
4007                page_scopes: BTreeMap::new(),
4008                navigation_focus_epoch: 0,
4009                visible_pages: BTreeSet::new(),
4010                focus_within_listeners: BTreeMap::new(),
4011                scroll_handles: BTreeMap::new(),
4012                scroll_anchors: BTreeMap::new(),
4013                text_selection: crate::renderer::TextSelectionRegistry::default(),
4014                last_motion_sample: None,
4015                motion_waits_for_clock: false,
4016                state: entity_view_state,
4017                direct_signal_access: Rc::new(Cell::new(false)),
4018                pending_interaction_cancels: BTreeSet::new(),
4019                activity_wake: entity_activity_wake,
4020                _runtime_tasks: runtime_tasks,
4021                window_activation: None,
4022                window_appearance: None,
4023                window_closed: None,
4024                #[cfg(feature = "dev-reload")]
4025                module_cache: self.module_cache,
4026                #[cfg(feature = "dev-reload")]
4027                watcher,
4028                #[cfg(feature = "dev-reload")]
4029                entry: self.entry,
4030                #[cfg(feature = "dev-reload")]
4031                ui_root: self.ui_root,
4032                #[cfg(feature = "dev-reload")]
4033                theme_path: self.theme_path,
4034                #[cfg(feature = "dev-reload")]
4035                style_path: self.style_path,
4036                #[cfg(feature = "dev-reload")]
4037                _reload_task: reload_task,
4038                #[cfg(feature = "dev-reload")]
4039                pending_reload_paths: BTreeSet::new(),
4040                #[cfg(feature = "dev-reload")]
4041                failed_reload_paths: BTreeSet::new(),
4042            }
4043        });
4044        install_window_lifecycle_hooks(&entity, window, cx);
4045        if let Some(authority) = window_authority {
4046            native_windows.borrow_mut().handles.insert(
4047                host.window_id(),
4048                NativeWindowRegistration {
4049                    handle: window.window_handle(),
4050                    authority,
4051                },
4052            );
4053            install_close_interceptor(window, cx, &entity);
4054        }
4055        attach_script_view_focus(&host, &config.view_id, &entity, cx);
4056        Ok(mounted_script_view_handle(
4057            entity,
4058            theme_handle,
4059            host,
4060            config,
4061            view_state,
4062            mount_lease,
4063        ))
4064    }
4065}
4066
4067#[cfg(feature = "dev-reload")]
4068fn development_watcher(
4069    development: bool,
4070    ui_root: &Path,
4071) -> Result<Option<FileWatcher>, ScriptViewError> {
4072    if development && !ui_root.as_os_str().is_empty() {
4073        Ok(Some(FileWatcher::new(ui_root)?))
4074    } else {
4075        Ok(None)
4076    }
4077}
4078
4079type WindowOptionsConfigurator =
4080    Box<dyn FnOnce(WindowOptions, &mut App) -> WindowOptions + 'static>;
4081
4082pub struct ScriptApplication {
4083    prepared: PreparedScriptView,
4084    window_size: (f32, f32),
4085    window_options: Option<WindowOptionsConfigurator>,
4086    show_error_banner: bool,
4087    mirror_errors_to_stderr: bool,
4088    window_drag_areas: bool,
4089    app_identity: Option<(String, String)>,
4090}
4091
4092impl ScriptApplication {
4093    #[must_use]
4094    pub const fn new(prepared: PreparedScriptView) -> Self {
4095        Self {
4096            prepared,
4097            window_size: (720.0, 480.0),
4098            window_options: None,
4099            show_error_banner: true,
4100            mirror_errors_to_stderr: true,
4101            window_drag_areas: false,
4102            app_identity: None,
4103        }
4104    }
4105
4106    #[must_use]
4107    pub const fn window_size(mut self, width: f32, height: f32) -> Self {
4108        self.window_size = (width, height);
4109        self
4110    }
4111
4112    /// Control built-in runtime-error banners in standalone script windows.
4113    ///
4114    /// Applications that disable them must provide another visible surface for
4115    /// [`ScriptViewHandle::last_error`].
4116    #[must_use]
4117    pub const fn show_error_banner(mut self, show: bool) -> Self {
4118        self.show_error_banner = show;
4119        self
4120    }
4121
4122    /// Print each new failure of a script window to stderr, so an unattended
4123    /// run fails loudly. On by default; see
4124    /// [`ScriptViewConfig::mirror_errors_to_stderr`].
4125    #[must_use]
4126    pub const fn mirror_errors_to_stderr(mut self, mirror: bool) -> Self {
4127        self.mirror_errors_to_stderr = mirror;
4128        self
4129    }
4130
4131    /// Let `window_drag_area()` nodes in the main window's view move the window,
4132    /// for an application that hides the platform title bar through
4133    /// [`Self::window_options`] and draws its own (`TitleBar` with
4134    /// `window_drag`). See [`ScriptViewConfig::window_drag_areas`].
4135    #[must_use]
4136    pub const fn window_drag_areas(mut self, enabled: bool) -> Self {
4137        self.window_drag_areas = enabled;
4138        self
4139    }
4140
4141    /// Configure the trusted standalone window without exposing native window
4142    /// authority to Rhai. The callback receives the centered default options.
4143    #[must_use]
4144    pub fn window_options(
4145        mut self,
4146        configure: impl FnOnce(WindowOptions, &mut App) -> WindowOptions + 'static,
4147    ) -> Self {
4148        self.window_options = Some(Box::new(configure));
4149        self
4150    }
4151
4152    /// The application's identifier (reverse DNS, `com.example.app`) and
4153    /// name, which Linux and Windows show on system notifications. macOS takes
4154    /// both from the bundle's `Info.plist` instead (see [`crate::system`]).
4155    #[must_use]
4156    pub fn app_identity(mut self, identifier: impl Into<String>, name: impl Into<String>) -> Self {
4157        self.app_identity = Some((identifier.into(), name.into()));
4158        self
4159    }
4160
4161    /// Run this prepared view as a standalone GPUI application.
4162    ///
4163    /// # Errors
4164    ///
4165    /// Returns key-binding, mount, or native-window errors.
4166    pub fn run(self) -> Result<(), ScriptViewError> {
4167        let error = Rc::new(RefCell::new(None));
4168        let reported_error = Rc::clone(&error);
4169        let native_windows = Rc::new(RefCell::new(NativeWindowRegistry::default()));
4170        let window_size = self.window_size;
4171        let window_options = self.window_options;
4172        let prepared = self.prepared;
4173        let show_error_banner = self.show_error_banner;
4174        let mirror_errors_to_stderr = self.mirror_errors_to_stderr;
4175        let window_drag_areas = self.window_drag_areas;
4176        let app_identity = self.app_identity;
4177        prepared.factory.show_error_banner.set(show_error_banner);
4178        gpui_platform::application().run(move |cx: &mut App| {
4179            install(cx);
4180            if let Some((identifier, name)) = &app_identity {
4181                cx.set_app_identity(identifier, name);
4182            }
4183            let host = match ScriptViewHost::new("main", cx) {
4184                Ok(host) => host,
4185                Err(error) => {
4186                    report_fatal(&reported_error, error.to_string());
4187                    cx.quit();
4188                    return;
4189                }
4190            };
4191            if let Err(error) = host.bind_keys(prepared.key_bindings.clone(), cx) {
4192                report_fatal(&reported_error, error.to_string());
4193                cx.quit();
4194                return;
4195            }
4196            #[cfg(feature = "dev-reload")]
4197            cx.bind_keys([
4198                KeyBinding::new("cmd-alt-i", ToggleInspector, Some(HOST_KEY_CONTEXT)),
4199                KeyBinding::new("f12", ToggleInspector, Some(HOST_KEY_CONTEXT)),
4200            ]);
4201            let window_options = standalone_window_options(window_size, window_options, cx);
4202            cx.on_window_closed(|cx, _| {
4203                if cx.windows().is_empty() {
4204                    cx.quit();
4205                }
4206            })
4207            .detach();
4208            let view_native_windows = Rc::clone(&native_windows);
4209            let mount_error = Rc::clone(&reported_error);
4210            let result = cx.open_window(window_options, move |window, cx| {
4211                let root = cx.new(|_| ScriptApplicationRoot {
4212                    host: host.clone(),
4213                    view: None,
4214                    error: None,
4215                });
4216                let weak_root = root.downgrade();
4217                window.defer(cx, move |window, cx| {
4218                    let view = prepared.mount_with_registry(
4219                        ScriptViewConfig::new("main")
4220                            .fills_window()
4221                            .paint_background(true)
4222                            .show_error_banner(show_error_banner)
4223                            .mirror_errors_to_stderr(mirror_errors_to_stderr)
4224                            .window_drag_areas(window_drag_areas),
4225                        host,
4226                        &view_native_windows,
4227                        WindowCommandPolicy::ApplicationOwned,
4228                        window,
4229                        cx,
4230                    );
4231                    match view {
4232                        Ok(view) => {
4233                            let _ = view.focus(window, cx);
4234                            let _ = weak_root.update(cx, |root, cx| {
4235                                root.view = Some(view);
4236                                cx.notify();
4237                            });
4238                        }
4239                        Err(error) => {
4240                            let message = error.to_string();
4241                            report_fatal(&mount_error, message.clone());
4242                            let _ = weak_root.update(cx, |root, cx| {
4243                                root.error = Some(message);
4244                                cx.notify();
4245                            });
4246                            cx.defer(|cx| cx.quit());
4247                        }
4248                    }
4249                });
4250                root
4251            });
4252            match result {
4253                Ok(_handle) => {
4254                    cx.activate(true);
4255                }
4256                Err(error) => {
4257                    report_fatal(&reported_error, error.to_string());
4258                    cx.quit();
4259                }
4260            }
4261        });
4262        match error.borrow_mut().take() {
4263            Some(message) => Err(ScriptViewError::Window(message)),
4264            None => Ok(()),
4265        }
4266    }
4267}
4268
4269/// Record a fatal startup error. Platforms such as macOS terminate the process
4270/// on quit, so `run` may never return it; the message is also written to stderr.
4271fn report_fatal(slot: &RefCell<Option<String>>, message: String) {
4272    eprintln!("gpui-rhai: {message}");
4273    *slot.borrow_mut() = Some(message);
4274}
4275
4276fn standalone_window_options(
4277    window_size: (f32, f32),
4278    configure: Option<WindowOptionsConfigurator>,
4279    cx: &mut App,
4280) -> WindowOptions {
4281    let bounds = Bounds::centered(None, size(px(window_size.0), px(window_size.1)), cx);
4282    let options = WindowOptions {
4283        window_bounds: Some(WindowBounds::Windowed(bounds)),
4284        ..WindowOptions::default()
4285    };
4286    match configure {
4287        Some(configure) => configure(options, cx),
4288        None => options,
4289    }
4290}
4291
4292struct ScriptApplicationRoot {
4293    host: ScriptViewHost,
4294    view: Option<ScriptViewHandle>,
4295    error: Option<String>,
4296}
4297
4298impl Render for ScriptApplicationRoot {
4299    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4300        self.host.container(self.view.as_ref().map_or_else(
4301            || {
4302                self.error.as_ref().map_or_else(
4303                    || div().child("Loading…").into_any_element(),
4304                    |error| div().child(error.clone()).into_any_element(),
4305                )
4306            },
4307            |view| {
4308                view.element()
4309                    .unwrap_or_else(|error| div().child(error.to_string()).into_any_element())
4310            },
4311        ))
4312    }
4313}
4314
4315#[allow(clippy::too_many_lines)]
4316fn open_secondary_window(
4317    spec: &ScriptWindowSpec,
4318    factory: &Rc<ScriptWindowFactory>,
4319    native_windows: &Rc<RefCell<NativeWindowRegistry>>,
4320    cx: &mut App,
4321) -> Result<(), ScriptFailure> {
4322    let factory = Rc::clone(factory);
4323    let native_windows = Rc::clone(native_windows);
4324    let window_id = spec.id.clone();
4325    let host = ScriptViewHost::new(window_id.clone(), cx).map_err(ScriptFailure::from)?;
4326    let mount_lease = host.reserve_view(&window_id).map_err(ScriptFailure::from)?;
4327    factory
4328        .runtime
4329        .borrow_mut()
4330        .windows
4331        .qualify_mount(&window_id, &mount_lease)
4332        .map_err(|error| ScriptFailure::plain(error.to_string()))?;
4333    let startup_error = Rc::new(RefCell::new(None));
4334    let view_startup_error = Rc::clone(&startup_error);
4335    let options = script_window_options(spec, cx);
4336    let view_factory = Rc::clone(&factory);
4337    let view_native_windows = Rc::clone(&native_windows);
4338    let view_window_id = window_id.clone();
4339    let view_host = host.clone();
4340    let view_mount_lease = mount_lease.clone();
4341    let result = cx.open_window(options, move |window, cx| {
4342        let window_authority = view_host
4343            .bind_window(
4344                &view_window_id,
4345                window.window_handle(),
4346                WindowCommandPolicy::ApplicationOwned,
4347                cx,
4348            )
4349            .expect("fresh secondary Host has no native window or command owner");
4350        view_factory
4351            .runtime
4352            .borrow_mut()
4353            .windows
4354            .bind_native(&view_window_id, window.window_handle().window_id())
4355            .expect("secondary reservation keeps its qualified mount identity");
4356        view_factory
4357            .runtime
4358            .borrow_mut()
4359            .update_window_appearance(&view_window_id, system_appearance(window.appearance()));
4360        // Init/effects run only after the native appearance and the same
4361        // reserved mount are known. Never replay side-effecting init to repair
4362        // a guessed pre-native theme.
4363        let (engine, lifecycle, primitives) = match view_factory.instantiate(
4364            &view_window_id,
4365            &view_window_id,
4366            Some(&view_mount_lease),
4367        ) {
4368            Ok(instance) => instance,
4369            Err(error) => {
4370                view_host.unregister_view(&view_window_id, &view_mount_lease);
4371                let root = ComponentInstancePath::root("View", &view_window_id);
4372                let _ = view_factory
4373                    .runtime
4374                    .borrow_mut()
4375                    .release_window(&view_window_id, &root);
4376                let failure = ScriptFailure::from(error);
4377                let message = failure.message.clone();
4378                *view_startup_error.borrow_mut() = Some(failure);
4379                return cx.new(|_| ScriptApplicationRoot {
4380                    host: view_host,
4381                    view: None,
4382                    error: Some(message),
4383                });
4384            }
4385        };
4386        let timings = engine.take_timings();
4387        let (theme_handle, view_theme_handle) =
4388            theme_handles_for_lifecycle(&lifecycle, &view_factory.theme, window, cx);
4389        let view_state = Rc::new(Cell::new(ScriptViewState::Active));
4390        let entity_view_state = Rc::clone(&view_state);
4391        let entity_activity_wake = crate::async_runtime::AsyncWake::default();
4392        let entity = cx.new(|entity_cx| {
4393            let runtime_tasks = spawn_host_runtime_tasks(
4394                entity_cx,
4395                &lifecycle,
4396                Rc::clone(&entity_view_state),
4397                entity_activity_wake.clone(),
4398            );
4399            let host_focus = entity_cx.focus_handle();
4400            ScriptHostView {
4401                mount_lease: view_mount_lease.clone(),
4402                view_id: view_window_id.clone(),
4403                window_id: view_window_id.clone(),
4404                engine,
4405                lifecycle,
4406                primitives,
4407                last_failure: None,
4408                failure_serial: 0,
4409                reported_failure_serial: 0,
4410                presentation_diagnostics:
4411                    crate::presentation_diagnostic::PresentationDiagnostics::default(),
4412                theme: view_factory.theme.clone(),
4413                theme_handle: view_theme_handle,
4414                #[cfg(feature = "dev-reload")]
4415                development: view_factory.development,
4416                #[cfg(feature = "dev-reload")]
4417                inspector_open: false,
4418                timings,
4419                render_statistics: ScriptViewRenderStatistics::default(),
4420                derived_key: None,
4421                islands: IslandTable::new(view_factory.render_islands.get(), RootWidth::Window),
4422                frame: None,
4423                overlays: view_host.overlays(),
4424                host: view_host.clone(),
4425                paint_background: true,
4426                show_error_banner: view_factory.show_error_banner.get(),
4427                error_reporting: view_factory.error_reporting.borrow().clone(),
4428                window_drag_areas: false,
4429                focus_indicators: view_factory.focus_indicators.get(),
4430                navigating: false,
4431                content_bounds: None,
4432                factory: Rc::clone(&view_factory),
4433                native_windows: Rc::clone(&view_native_windows),
4434                host_focus,
4435                focus_handles: BTreeMap::new(),
4436                page_focus: BTreeMap::new(),
4437                page_scopes: BTreeMap::new(),
4438                navigation_focus_epoch: 0,
4439                visible_pages: BTreeSet::new(),
4440                focus_within_listeners: BTreeMap::new(),
4441                scroll_handles: BTreeMap::new(),
4442                scroll_anchors: BTreeMap::new(),
4443                text_selection: crate::renderer::TextSelectionRegistry::default(),
4444                last_motion_sample: None,
4445                motion_waits_for_clock: false,
4446                state: entity_view_state,
4447                direct_signal_access: Rc::new(Cell::new(false)),
4448                pending_interaction_cancels: BTreeSet::new(),
4449                activity_wake: entity_activity_wake,
4450                _runtime_tasks: runtime_tasks,
4451                window_activation: None,
4452                window_appearance: None,
4453                window_closed: None,
4454                #[cfg(feature = "dev-reload")]
4455                module_cache: ModuleCompileCache::new(),
4456                #[cfg(feature = "dev-reload")]
4457                watcher: None,
4458                #[cfg(feature = "dev-reload")]
4459                entry: PathBuf::new(),
4460                #[cfg(feature = "dev-reload")]
4461                ui_root: PathBuf::new(),
4462                #[cfg(feature = "dev-reload")]
4463                theme_path: PathBuf::new(),
4464                #[cfg(feature = "dev-reload")]
4465                style_path: PathBuf::new(),
4466                #[cfg(feature = "dev-reload")]
4467                _reload_task: None,
4468                #[cfg(feature = "dev-reload")]
4469                pending_reload_paths: BTreeSet::new(),
4470                #[cfg(feature = "dev-reload")]
4471                failed_reload_paths: BTreeSet::new(),
4472            }
4473        });
4474        install_window_lifecycle_hooks(&entity, window, cx);
4475        if let Some(authority) = window_authority {
4476            view_native_windows.borrow_mut().handles.insert(
4477                view_window_id.clone(),
4478                NativeWindowRegistration {
4479                    handle: window.window_handle(),
4480                    authority,
4481                },
4482            );
4483        }
4484        view_host.attach_view_focus(&view_window_id, entity.read(cx).host_focus.clone());
4485        let view = ScriptViewHandle(Rc::new(ScriptViewHandleInner {
4486            entity: entity.clone(),
4487            theme: theme_handle,
4488            host: view_host.clone(),
4489            view_id: view_window_id,
4490            state: view_state,
4491            measured_bounds: Rc::new(Cell::new(None)),
4492            mount_lease: view_mount_lease,
4493        }));
4494        let _ = view.focus(window, cx);
4495        install_close_interceptor(window, cx, &entity);
4496        cx.new(|_| ScriptApplicationRoot {
4497            host: view_host,
4498            view: Some(view),
4499            error: None,
4500        })
4501    });
4502    match result {
4503        Ok(handle) => {
4504            if let Some(error) = startup_error.borrow_mut().take() {
4505                let _ = handle.update(cx, |_, window, _| window.remove_window());
4506                return Err(error);
4507            }
4508            factory
4509                .runtime
4510                .borrow_mut()
4511                .windows
4512                .mark_open(&window_id)
4513                .map_err(|error| ScriptFailure::plain(error.to_string()))?;
4514            Ok(())
4515        }
4516        Err(error) => {
4517            host.unregister_view(&window_id, &mount_lease);
4518            let root = ComponentInstancePath::root("View", &window_id);
4519            let mut runtime = factory.runtime.borrow_mut();
4520            let _ = runtime.release_window(&window_id, &root);
4521            Err(ScriptFailure::plain(error.to_string()))
4522        }
4523    }
4524}
4525
4526fn script_window_options(spec: &ScriptWindowSpec, cx: &mut App) -> WindowOptions {
4527    let bounds = Bounds::centered(
4528        None,
4529        size(
4530            px(validated_dimension_to_f32(spec.width)),
4531            px(validated_dimension_to_f32(spec.height)),
4532        ),
4533        cx,
4534    );
4535    WindowOptions {
4536        window_bounds: Some(WindowBounds::Windowed(bounds)),
4537        titlebar: Some(TitlebarOptions {
4538            title: Some(SharedString::from(spec.title.clone())),
4539            ..TitlebarOptions::default()
4540        }),
4541        focus: spec.focus,
4542        ..WindowOptions::default()
4543    }
4544}
4545
4546fn install_close_interceptor(window: &Window, cx: &App, entity: &gpui::Entity<ScriptHostView>) {
4547    let weak = entity.downgrade();
4548    window.on_window_should_close(cx, move |_, app| {
4549        weak.update(app, ScriptHostView::should_close)
4550            .unwrap_or(true)
4551    });
4552}
4553
4554struct HostRuntimeTasks {
4555    _frame_poll: Task<()>,
4556    _task_delivery: Task<()>,
4557    _subscription_delivery: Task<()>,
4558    _virtual_delivery: Task<()>,
4559}
4560
4561fn spawn_host_runtime_tasks(
4562    cx: &mut Context<ScriptHostView>,
4563    lifecycle: &ScriptLifecycle,
4564    state: Rc<Cell<ScriptViewState>>,
4565    activity_wake: crate::async_runtime::AsyncWake,
4566) -> HostRuntimeTasks {
4567    let (task_wake, subscription_wake, virtual_wake) = {
4568        let runtime = lifecycle.runtime();
4569        let runtime = runtime.borrow();
4570        (
4571            runtime.tasks.wake(),
4572            runtime.subscriptions.wake(),
4573            runtime.virtual_requests.wake(),
4574        )
4575    };
4576    HostRuntimeTasks {
4577        _frame_poll: spawn_host_frame_poll(cx, state, activity_wake),
4578        _task_delivery: spawn_host_delivery_pump(cx, task_wake),
4579        _subscription_delivery: spawn_host_delivery_pump(cx, subscription_wake),
4580        _virtual_delivery: spawn_host_delivery_pump(cx, virtual_wake),
4581    }
4582}
4583
4584fn spawn_host_frame_poll(
4585    cx: &mut Context<ScriptHostView>,
4586    state: Rc<Cell<ScriptViewState>>,
4587    activity_wake: crate::async_runtime::AsyncWake,
4588) -> Task<()> {
4589    let mut listener = activity_wake.listen();
4590    cx.spawn(async move |entity: gpui::WeakEntity<ScriptHostView>, cx| {
4591        loop {
4592            match state.get() {
4593                ScriptViewState::Disposed => break,
4594                ScriptViewState::Suspended => {
4595                    listener.await;
4596                    listener = activity_wake.listen();
4597                    continue;
4598                }
4599                ScriptViewState::Active => {}
4600            }
4601            cx.background_executor()
4602                .timer(Duration::from_millis(16))
4603                .await;
4604            if entity.update(cx, ScriptHostView::poll_async).is_err() {
4605                break;
4606            }
4607        }
4608    })
4609}
4610
4611fn spawn_host_delivery_pump(
4612    cx: &mut Context<ScriptHostView>,
4613    wake: crate::async_runtime::AsyncWake,
4614) -> Task<()> {
4615    // Register before the entity becomes externally visible. The first drain
4616    // catches work that completed during lifecycle initialization; thereafter
4617    // the listener closes the send/drain race without fixed-rate polling.
4618    let mut listener = wake.listen();
4619    cx.spawn(async move |entity: gpui::WeakEntity<ScriptHostView>, cx| {
4620        loop {
4621            if entity.update(cx, ScriptHostView::poll_async).is_err() {
4622                break;
4623            }
4624            listener.await;
4625            listener = wake.listen();
4626        }
4627    })
4628}
4629
4630#[cfg(feature = "dev-reload")]
4631fn spawn_host_reload_poll(
4632    cx: &mut Context<ScriptHostView>,
4633    state: Rc<Cell<ScriptViewState>>,
4634) -> Task<()> {
4635    cx.spawn(async move |entity: gpui::WeakEntity<ScriptHostView>, cx| {
4636        loop {
4637            if state.get() == ScriptViewState::Disposed {
4638                break;
4639            }
4640            cx.background_executor()
4641                .timer(Duration::from_millis(100))
4642                .await;
4643            if entity.update(cx, ScriptHostView::poll_reload).is_err() {
4644                break;
4645            }
4646        }
4647    })
4648}
4649
4650#[allow(clippy::cast_possible_truncation)]
4651fn validated_dimension_to_f32(value: f64) -> f32 {
4652    debug_assert!(value.is_finite() && (200.0..=4096.0).contains(&value));
4653    value as f32
4654}
4655
4656fn pixel_from_f64(value: f64) -> Pixels {
4657    px(value.to_string().parse::<f32>().unwrap_or(f32::MAX))
4658}
4659
4660fn event_response_from_dynamic(value: &rhai::Dynamic) -> crate::EventResponse {
4661    if value.is::<crate::EventResponse>() {
4662        value.clone_cast::<crate::EventResponse>()
4663    } else if value.is::<rhai::ImmutableString>()
4664        && value.clone_cast::<rhai::ImmutableString>().as_str() == "propagate"
4665    {
4666        crate::EventResponse::new()
4667    } else {
4668        crate::EventResponse::new().stop()
4669    }
4670}
4671
4672fn automation_pointer_id(payload: &UiValue) -> Option<u64> {
4673    let UiValue::Map(payload) = payload else {
4674        return None;
4675    };
4676    match payload.get("pointer_id") {
4677        Some(UiValue::Integer(id)) => u64::try_from(*id).ok(),
4678        _ => None,
4679    }
4680}
4681
4682#[derive(Clone, Debug)]
4683struct ScriptFailure {
4684    message: String,
4685    diagnostic: Option<Box<Diagnostic>>,
4686}
4687
4688impl ScriptFailure {
4689    fn plain(message: impl Into<String>) -> Self {
4690        Self {
4691            message: message.into(),
4692            diagnostic: None,
4693        }
4694    }
4695
4696    fn with_diagnostic(message: impl Into<String>, diagnostic: Diagnostic) -> Self {
4697        Self {
4698            message: message.into(),
4699            diagnostic: Some(Box::new(diagnostic)),
4700        }
4701    }
4702
4703    fn append_context(mut self, context: impl AsRef<str>) -> Self {
4704        self.message = format!("{}; {}", self.message, context.as_ref());
4705        self
4706    }
4707
4708    fn into_view_error(self) -> ScriptViewError {
4709        match self.diagnostic {
4710            Some(diagnostic) => ScriptViewError::ScriptDiagnostic {
4711                message: self.message,
4712                diagnostic,
4713            },
4714            None => ScriptViewError::Resume(self.message),
4715        }
4716    }
4717}
4718
4719impl From<String> for ScriptFailure {
4720    fn from(message: String) -> Self {
4721        Self::plain(message)
4722    }
4723}
4724
4725#[allow(clippy::struct_excessive_bools)]
4726struct ScriptHostView {
4727    mount_lease: std::rc::Weak<()>,
4728    view_id: String,
4729    window_id: String,
4730    engine: RuntimeEngine,
4731    lifecycle: ScriptLifecycle,
4732    primitives: PrimitiveRegistry,
4733    last_failure: Option<ScriptFailure>,
4734    /// Counts failures, so one command can tell whether it failed without
4735    /// clearing an earlier failure the developer has not seen yet.
4736    failure_serial: u64,
4737    /// The `failure_serial` last reported to the Host.
4738    reported_failure_serial: u64,
4739    presentation_diagnostics: crate::presentation_diagnostic::PresentationDiagnostics,
4740    error_reporting: ErrorReporting,
4741    theme: ThemeVariant,
4742    theme_handle: ThemeHandle,
4743    #[cfg(feature = "dev-reload")]
4744    development: bool,
4745    #[cfg(feature = "dev-reload")]
4746    inspector_open: bool,
4747    timings: Vec<crate::ExecutionTiming>,
4748    render_statistics: ScriptViewRenderStatistics,
4749    /// The committed tree and primitives the last frame's walks derived from.
4750    derived_key: Option<DerivedKey>,
4751    islands: IslandTable,
4752    /// What the last frame rendered from, which its islands render from.
4753    frame: Option<Rc<HostFrame>>,
4754    overlays: WindowOverlayCoordinator,
4755    host: ScriptViewHost,
4756    paint_background: bool,
4757    show_error_banner: bool,
4758    window_drag_areas: bool,
4759    focus_indicators: FocusIndicators,
4760    /// A navigation key came after the last pointer press, so
4761    /// [`FocusIndicators::Navigation`] shows indicators.
4762    navigating: bool,
4763    content_bounds: Option<Bounds<Pixels>>,
4764    factory: Rc<ScriptWindowFactory>,
4765    native_windows: Rc<RefCell<NativeWindowRegistry>>,
4766    host_focus: FocusHandle,
4767    focus_handles: BTreeMap<crate::NodeId, FocusHandle>,
4768    page_focus: BTreeMap<crate::NodeId, (crate::NodeId, FocusHandle)>,
4769    page_scopes: BTreeMap<crate::NodeId, crate::NodeId>,
4770    navigation_focus_epoch: u64,
4771    visible_pages: BTreeSet<crate::NodeId>,
4772    /// Focus-in and focus-out listeners of each node with a `focus_within_change` handler.
4773    focus_within_listeners: BTreeMap<crate::NodeId, [Subscription; 2]>,
4774    scroll_handles: BTreeMap<crate::NodeId, ScrollHandle>,
4775    scroll_anchors: BTreeMap<crate::NodeId, ScrollAnchor>,
4776    text_selection: crate::renderer::TextSelectionRegistry,
4777    last_motion_sample: Option<Instant>,
4778    /// Motion still runs but the last sample saw the runtime clock where the
4779    /// one before saw it, so no animation frame was asked for; the next poll
4780    /// that finds the clock moved repaints instead.
4781    motion_waits_for_clock: bool,
4782    state: Rc<Cell<ScriptViewState>>,
4783    direct_signal_access: Rc<Cell<bool>>,
4784    pending_interaction_cancels: BTreeSet<crate::interaction::InteractionOwner>,
4785    activity_wake: crate::async_runtime::AsyncWake,
4786    _runtime_tasks: HostRuntimeTasks,
4787    #[allow(dead_code)]
4788    window_activation: Option<Subscription>,
4789    window_appearance: Option<Subscription>,
4790    #[allow(dead_code)]
4791    window_closed: Option<Subscription>,
4792    #[cfg(feature = "dev-reload")]
4793    module_cache: ModuleCompileCache,
4794    #[cfg(feature = "dev-reload")]
4795    watcher: Option<FileWatcher>,
4796    #[cfg(feature = "dev-reload")]
4797    entry: PathBuf,
4798    #[cfg(feature = "dev-reload")]
4799    ui_root: PathBuf,
4800    #[cfg(feature = "dev-reload")]
4801    theme_path: PathBuf,
4802    #[cfg(feature = "dev-reload")]
4803    style_path: PathBuf,
4804    #[cfg(feature = "dev-reload")]
4805    _reload_task: Option<Task<()>>,
4806    #[cfg(feature = "dev-reload")]
4807    pending_reload_paths: BTreeSet<PathBuf>,
4808    #[cfg(feature = "dev-reload")]
4809    failed_reload_paths: BTreeSet<PathBuf>,
4810}
4811
4812fn install_window_lifecycle_hooks(
4813    entity: &Entity<ScriptHostView>,
4814    window: &mut Window,
4815    cx: &mut App,
4816) {
4817    let subscription = entity.update(cx, |_, entity_cx| {
4818        entity_cx.observe_window_activation(window, |view, window, cx| {
4819            if !window.is_window_active() && view.cancel_view_interaction(window, cx) {
4820                cx.notify();
4821            }
4822        })
4823    });
4824    entity.update(cx, |view, _| view.window_activation = Some(subscription));
4825    let appearance = entity.update(cx, |_, entity_cx| {
4826        entity_cx.observe_window_appearance(window, |view, window, cx| {
4827            view.on_window_appearance_changed(window.appearance(), cx);
4828        })
4829    });
4830    entity.update(cx, |view, _| view.window_appearance = Some(appearance));
4831    let window_id = window.window_handle().window_id();
4832    let weak = entity.downgrade();
4833    let closed = cx.on_window_closed(move |cx, closed_id| {
4834        if closed_id == window_id {
4835            let weak = weak.clone();
4836            cx.defer(move |cx| {
4837                let _ = weak.update(cx, |view, cx| {
4838                    view.release_view();
4839                    cx.notify();
4840                });
4841            });
4842        }
4843    });
4844    entity.update(cx, |view, _| view.window_closed = Some(closed));
4845}
4846
4847struct DirectSignalAccessGuard {
4848    flag: Rc<Cell<bool>>,
4849    previous: bool,
4850}
4851
4852#[derive(Clone)]
4853struct PrimitiveRuntimeReader {
4854    owner: gpui::WeakEntity<ScriptHostView>,
4855    runtime: Rc<RefCell<UiRuntimeState>>,
4856    view_id: String,
4857    lifecycle_access: Rc<Cell<bool>>,
4858}
4859
4860impl PrimitiveRuntimeReader {
4861    fn read<T>(
4862        &self,
4863        app: &App,
4864        query: impl FnOnce(&UiRuntimeState, &str) -> Option<T>,
4865    ) -> Option<T> {
4866        if self.lifecycle_access.get() {
4867            query(&self.runtime.borrow(), &self.view_id)
4868        } else {
4869            self.owner
4870                .read_with(app, |view, _| {
4871                    query(&view.lifecycle.runtime().borrow(), &view.view_id)
4872                })
4873                .ok()
4874                .flatten()
4875        }
4876    }
4877}
4878
4879impl Drop for DirectSignalAccessGuard {
4880    fn drop(&mut self) {
4881        self.flag.set(self.previous);
4882    }
4883}
4884
4885fn nearest_scroll_ancestor(
4886    tree: &crate::RetainedUiTree,
4887    node: crate::NodeId,
4888) -> Option<crate::NodeId> {
4889    let mut current = tree.node(node)?.parent();
4890    while let Some(node) = current {
4891        let retained = tree.node(node)?;
4892        if retained.scrollable() {
4893            return Some(node);
4894        }
4895        current = retained.parent();
4896    }
4897    None
4898}
4899
4900struct ScriptRenderSnapshot {
4901    now: Instant,
4902    clock: crate::RuntimeClock,
4903    motion_preference: crate::MotionPreference,
4904    motion_quality: crate::MotionQuality,
4905    assets: AssetRegistry,
4906    theme: ThemeVariant,
4907    /// The variants of the component subtrees with a local theme.
4908    local_themes: crate::theme::LocalThemes,
4909    motions: BTreeMap<crate::MotionKey, f64>,
4910    motion_ghosts: Vec<crate::motion::MotionGhost>,
4911    signals: crate::SignalRegistry,
4912    geometry: crate::GeometryRegistry,
4913    pointer_capture: crate::PointerCaptureRegistry,
4914    virtual_requests: crate::VirtualRequestRegistry,
4915    direction: TextDirection,
4916    locale: String,
4917    number: Option<crate::NumberMetadata>,
4918}
4919
4920struct ScriptViewTransaction {
4921    runtime: crate::UiStateSnapshot,
4922    engine: crate::engine::RuntimeEngineCheckpoint,
4923    lifecycle: crate::lifecycle::ScriptLifecycleCheckpoint,
4924}
4925
4926fn retained_within(
4927    tree: &crate::RetainedUiTree,
4928    node: crate::NodeId,
4929    ancestor: crate::NodeId,
4930) -> bool {
4931    let mut cursor = Some(node);
4932    while let Some(node) = cursor {
4933        if node == ancestor {
4934            return true;
4935        }
4936        cursor = tree.node(node).and_then(crate::RetainedNode::parent);
4937    }
4938    false
4939}
4940
4941fn retained_depth(tree: &crate::RetainedUiTree, node: crate::NodeId) -> usize {
4942    let mut depth = 0;
4943    let mut cursor = Some(node);
4944    while let Some(node) = cursor {
4945        depth += 1;
4946        cursor = tree.node(node).and_then(crate::RetainedNode::parent);
4947    }
4948    depth
4949}
4950
4951/// A key that moves or uses focus: Tab, an arrow, Home, End, Page Up, Page Down
4952/// or F6, with Shift at most. With Command, Control or Alt it is a shortcut.
4953fn is_navigation_key(keystroke: &gpui::Keystroke) -> bool {
4954    let modifiers = &keystroke.modifiers;
4955    !(modifiers.control || modifiers.alt || modifiers.platform || modifiers.function)
4956        && matches!(
4957            keystroke.key.as_str(),
4958            "tab"
4959                | "up"
4960                | "down"
4961                | "left"
4962                | "right"
4963                | "home"
4964                | "end"
4965                | "pageup"
4966                | "pagedown"
4967                | "f6"
4968        )
4969}
4970
4971fn handle_tab_navigation(event: &gpui::KeyDownEvent, window: &mut Window, cx: &mut App) {
4972    if event.keystroke.key.as_str() == "tab" {
4973        if event.keystroke.modifiers.shift {
4974            window.focus_prev(cx);
4975        } else {
4976            window.focus_next(cx);
4977        }
4978        cx.stop_propagation();
4979    }
4980}
4981
4982fn apply_root_text_direction(
4983    root: gpui::Stateful<gpui::Div>,
4984    direction: TextDirection,
4985) -> gpui::Stateful<gpui::Div> {
4986    match direction {
4987        TextDirection::LeftToRight => root.text_left(),
4988        TextDirection::RightToLeft => root.text_right(),
4989    }
4990}
4991
4992/// A view's keyboard handling: its key context, Tab navigation and the actions
4993/// Host key bindings dispatch to it. The view root carries it, and so does each
4994/// `layer(...)` the Host portal paints outside the root.
4995#[derive(Clone)]
4996struct ViewKeyScope {
4997    /// Records whether the last input that decides focus indicators was a
4998    /// navigation key (`true`) or a pointer press (`false`).
4999    input_modality: ActionListener<bool>,
5000    dispatch_key_binding: ActionListener<DispatchScriptAction>,
5001    copy_selected_text: ActionListener<CopySelectedText>,
5002    navigate_back: ActionListener<NavigateBack>,
5003    #[cfg(feature = "dev-reload")]
5004    toggle_inspector: ActionListener<ToggleInspector>,
5005}
5006
5007type ActionListener<A> = Rc<dyn Fn(&A, &mut Window, &mut App)>;
5008
5009impl ViewKeyScope {
5010    fn new(cx: &mut Context<ScriptHostView>) -> Self {
5011        Self {
5012            input_modality: Rc::new(cx.listener(|view, navigating: &bool, _, cx| {
5013                if view.navigating != *navigating {
5014                    view.navigating = *navigating;
5015                    if view.focus_indicators == FocusIndicators::Navigation {
5016                        cx.notify();
5017                    }
5018                }
5019            })),
5020            dispatch_key_binding: Rc::new(cx.listener(ScriptHostView::dispatch_key_binding)),
5021            copy_selected_text: Rc::new(cx.listener(ScriptHostView::copy_selected_text)),
5022            navigate_back: Rc::new(cx.listener(|view, _: &NavigateBack, window, cx| {
5023                if !view.propose_navigation_back("keyboard", window, cx) {
5024                    cx.propagate();
5025                }
5026            })),
5027            #[cfg(feature = "dev-reload")]
5028            toggle_inspector: Rc::new(cx.listener(ScriptHostView::toggle_inspector)),
5029        }
5030    }
5031
5032    fn apply<E: InteractiveElement>(&self, element: E) -> E {
5033        let dispatch_key_binding = Rc::clone(&self.dispatch_key_binding);
5034        let copy_selected_text = Rc::clone(&self.copy_selected_text);
5035        let navigate_back = Rc::clone(&self.navigate_back);
5036        let (key_modality, pointer_modality) = (
5037            Rc::clone(&self.input_modality),
5038            Rc::clone(&self.input_modality),
5039        );
5040        let element = element
5041            .key_context(HOST_KEY_CONTEXT)
5042            // Seen before any handler takes the key or the press, and never stopped.
5043            .capture_key_down(move |event, window, cx| {
5044                if is_navigation_key(&event.keystroke) {
5045                    key_modality(&true, window, cx);
5046                }
5047            })
5048            .capture_any_mouse_down(move |_, window, cx| pointer_modality(&false, window, cx))
5049            .on_key_down(handle_tab_navigation)
5050            .on_action(move |action: &DispatchScriptAction, window, cx| {
5051                dispatch_key_binding(action, window, cx);
5052            })
5053            .on_action(move |action: &CopySelectedText, window, cx| {
5054                copy_selected_text(action, window, cx);
5055            })
5056            .on_action(move |action: &NavigateBack, window, cx| {
5057                navigate_back(action, window, cx);
5058            });
5059        #[cfg(feature = "dev-reload")]
5060        let element = {
5061            let toggle_inspector = Rc::clone(&self.toggle_inspector);
5062            element.on_action(move |action: &ToggleInspector, window, cx| {
5063                toggle_inspector(action, window, cx);
5064            })
5065        };
5066        element
5067    }
5068}
5069
5070fn build_host_root(
5071    host_focus: &FocusHandle,
5072    theme: &ThemeVariant,
5073    paint_background: bool,
5074) -> gpui::Stateful<gpui::Div> {
5075    // Themes need not use the semantic vocabulary; without it the host keeps
5076    // GPUI's default text color and paints no background.
5077    let mut root = div()
5078        .id("gpui-rhai-host")
5079        .size_full()
5080        .track_focus(host_focus);
5081    if let Some(color) = theme.tokens.color("text_primary") {
5082        root = root.text_color(rgba(color.as_rgba_hex()));
5083    }
5084    match theme.tokens.color("surface") {
5085        Some(color) if paint_background => root.bg(rgba(color.as_rgba_hex())),
5086        _ => root,
5087    }
5088}
5089
5090#[cfg(target_os = "macos")]
5091const fn error_banner_font_family() -> &'static str {
5092    "Menlo"
5093}
5094
5095#[cfg(target_os = "windows")]
5096const fn error_banner_font_family() -> &'static str {
5097    "Consolas"
5098}
5099
5100#[cfg(not(any(target_os = "macos", target_os = "windows")))]
5101const fn error_banner_font_family() -> &'static str {
5102    "DejaVu Sans Mono"
5103}
5104
5105#[allow(clippy::too_many_arguments)]
5106fn build_error_banner(
5107    view_id: &str,
5108    window_id: &str,
5109    error: &str,
5110    theme: &ThemeVariant,
5111    selection: crate::renderer::TextSelectionRegistry,
5112    host_focus: FocusHandle,
5113    on_dismiss: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static,
5114    content: AnyElement,
5115) -> AnyElement {
5116    let selector = format!("gpui-rhai-error-banner:{view_id}");
5117    let dismiss_selector = format!("gpui-rhai-error-banner-dismiss:{view_id}");
5118    let accessibility_id = selector.clone();
5119    let owner = format!("window:{window_id}/view:{view_id}/error-banner");
5120    let owner_id = owner.clone();
5121    // The banner is developer-facing and must render with any vocabulary.
5122    let color = |token: &str, fallback: u32| {
5123        theme
5124            .tokens
5125            .color(token)
5126            .unwrap_or(crate::Rgba8::from_rgba_hex(fallback))
5127    };
5128    let error_text = crate::renderer::selectable_text_element(
5129        owner,
5130        error,
5131        color("selection", 0x3a5f_cd66),
5132        selection,
5133        Some(host_focus),
5134    );
5135    div()
5136        .flex()
5137        .flex_col()
5138        .child(
5139            div()
5140                .id(ElementId::Name(accessibility_id.into()))
5141                .role(Role::Alert)
5142                .aria_label("Script view error")
5143                .aria_description(error.to_owned())
5144                .debug_selector(move || selector.clone())
5145                .p_2()
5146                .font_family(error_banner_font_family())
5147                .text_size(px(12.0))
5148                .line_height(px(18.0))
5149                .bg(rgba(color("surface_raised", 0x1f1f_1fff).as_rgba_hex()))
5150                .text_color(rgba(color("danger", 0xff55_55ff).as_rgba_hex()))
5151                .border_1()
5152                .border_color(rgba(color("danger", 0xff55_55ff).as_rgba_hex()))
5153                .flex()
5154                .items_start()
5155                .gap_2()
5156                .child(div().flex_1().min_w_0().child(error_text))
5157                .child(
5158                    // The error outlives the transaction that raised it; the
5159                    // developer closes it once read.
5160                    div()
5161                        .id(ElementId::Name(format!("{owner_id}/dismiss").into()))
5162                        .role(Role::Button)
5163                        .aria_label("Dismiss script view error")
5164                        .debug_selector(move || dismiss_selector.clone())
5165                        .flex_none()
5166                        .px_1()
5167                        .cursor_pointer()
5168                        .text_color(rgba(color("text_muted", 0xc8c8_c8ff).as_rgba_hex()))
5169                        .child("Dismiss")
5170                        .on_click(on_dismiss),
5171                ),
5172        )
5173        .child(content)
5174        .into_any_element()
5175}
5176
5177#[allow(clippy::too_many_lines)]
5178fn script_node_dispatcher(
5179    cx: &Context<ScriptHostView>,
5180    runtime: Rc<RefCell<UiRuntimeState>>,
5181    direct_signal_access: Rc<Cell<bool>>,
5182    view_id: &str,
5183) -> NodeEventDispatcher {
5184    let script_entity = cx.entity().downgrade();
5185    let native_entity = script_entity.clone();
5186    let signal_entity = script_entity.clone();
5187    let signal_read_entity = script_entity.clone();
5188    let signal_read_runtime = Rc::clone(&runtime);
5189    let signal_read_direct = Rc::clone(&direct_signal_access);
5190    let geometry_reader = PrimitiveRuntimeReader {
5191        owner: script_entity.clone(),
5192        runtime: Rc::clone(&runtime),
5193        view_id: view_id.to_owned(),
5194        lifecycle_access: Rc::clone(&direct_signal_access),
5195    };
5196    let canvas_geometry_reader = geometry_reader.clone();
5197    let hitbox_reader = geometry_reader.clone();
5198    let canvas_bounds_reader = geometry_reader.clone();
5199    NodeEventDispatcher::with_event_names(move |callback, event, payload, target, window, app| {
5200        let origin = crate::InvocationOrigin::UserInput {
5201            event: event.to_owned(),
5202        };
5203        script_entity
5204            .update(app, |view, cx| {
5205                view.handle_node_event(&callback, payload, target, origin, window, cx)
5206            })
5207            .unwrap_or_else(|_| crate::EventResponse::new().stop())
5208    })
5209    .with_native(move |handler, event, payload, target, window, app| {
5210        native_entity
5211            .update(app, |view, cx| {
5212                view.handle_native_event(&handler, event, payload, target, window, cx)
5213            })
5214            .unwrap_or_else(|_| crate::EventResponse::new().stop())
5215    })
5216    .with_signal_write(move |updates, app| {
5217        let stale = updates
5218            .first()
5219            .map(|(signal, _)| crate::SignalError::Stale(signal.id().clone()));
5220        let direct_runtime = Rc::clone(&runtime);
5221        if direct_signal_access.get() {
5222            return direct_runtime
5223                .try_borrow_mut()
5224                .map_err(|_| stale.expect("non-empty signal patches have a first member"))?
5225                .signals
5226                .write_batch_from(&updates, crate::SignalWriter::Primitive);
5227        }
5228        signal_entity
5229            .update(app, |view, cx| {
5230                let changed = view
5231                    .lifecycle
5232                    .runtime()
5233                    .borrow_mut()
5234                    .signals
5235                    .write_batch_from(&updates, crate::SignalWriter::Primitive)?;
5236                if changed && view.state.get() == ScriptViewState::Active {
5237                    cx.notify();
5238                }
5239                Ok(changed)
5240            })
5241            .unwrap_or_else(|_| Err(stale.expect("non-empty signal patches have a first member")))
5242    })
5243    .with_signal_read(move |signal, app| {
5244        if signal_read_direct.get() {
5245            return signal_read_runtime.borrow().signals.read(signal);
5246        }
5247        signal_read_entity
5248            .read_with(app, |view, _| {
5249                view.lifecycle.runtime().borrow().signals.read(signal)
5250            })
5251            .unwrap_or_else(|_| Err(crate::SignalError::Stale(signal.id().clone())))
5252    })
5253    .with_element_bounds(move |reference, app| {
5254        geometry_reader.read(app, |runtime, view_id| {
5255            let node = runtime.element_refs.resolve(reference).ok()?;
5256            runtime
5257                .geometry_for(Some(view_id))
5258                .presented(node)
5259                .ok()
5260                .map(|geometry| geometry.layout)
5261        })
5262    })
5263    .with_element_hitbox(move |reference, app| {
5264        hitbox_reader.read(app, |runtime, view_id| {
5265            let node = runtime.element_refs.resolve(reference).ok()?;
5266            runtime.geometry_for(Some(view_id)).hitbox(node)
5267        })
5268    })
5269    .with_canvas_local_point(move |reference, point, app| {
5270        canvas_geometry_reader.read(app, |runtime, view_id| {
5271            let node = runtime.element_refs.resolve(reference).ok()?;
5272            let geometry = runtime.geometry_for(Some(view_id));
5273            let bounds = geometry.canvas_drawable(node)?;
5274            let local = (point.0 - bounds.visual.x, point.1 - bounds.visual.y);
5275            Some(
5276                crate::canvas::canvas_motion_affine(
5277                    bounds.layout.width,
5278                    bounds.layout.height,
5279                    geometry.canvas_transform(node),
5280                )
5281                .inverse()?
5282                .map_point(local),
5283            )
5284        })
5285    })
5286    .with_canvas_bounds(move |reference, app| {
5287        canvas_bounds_reader.read(app, |runtime, view_id| {
5288            let node = runtime.element_refs.resolve(reference).ok()?;
5289            runtime
5290                .geometry_for(Some(view_id))
5291                .canvas_drawable(node)
5292                .map(|bounds| bounds.layout)
5293        })
5294    })
5295}
5296
5297const fn system_appearance(appearance: WindowAppearance) -> SystemAppearance {
5298    match appearance {
5299        WindowAppearance::Dark | WindowAppearance::VibrantDark => SystemAppearance::Dark,
5300        WindowAppearance::Light | WindowAppearance::VibrantLight => SystemAppearance::Light,
5301    }
5302}
5303
5304fn resolve_root_theme(
5305    lifecycle: &ScriptLifecycle,
5306    fallback: &ThemeVariant,
5307    appearance: SystemAppearance,
5308) -> ThemeVariant {
5309    let runtime = lifecycle.runtime();
5310    resolve_root_theme_from_runtime(
5311        &runtime.borrow(),
5312        lifecycle.root_path(),
5313        lifecycle.window_id().unwrap_or_default(),
5314        appearance,
5315        fallback,
5316    )
5317}
5318
5319fn theme_handles_for_lifecycle(
5320    lifecycle: &ScriptLifecycle,
5321    fallback: &ThemeVariant,
5322    window: &Window,
5323    cx: &mut App,
5324) -> (ThemeHandle, ThemeHandle) {
5325    let handle = ThemeHandle::new(
5326        resolve_root_theme(lifecycle, fallback, system_appearance(window.appearance())),
5327        cx,
5328    );
5329    (handle.clone(), handle)
5330}
5331
5332fn attach_script_view_focus(
5333    host: &ScriptViewHost,
5334    view_id: &str,
5335    entity: &Entity<ScriptHostView>,
5336    cx: &App,
5337) {
5338    host.attach_view_focus(view_id, entity.read(cx).host_focus.clone());
5339    if let Some(view) = host.inner.borrow_mut().views.get_mut(view_id) {
5340        view.entity = Some(entity.downgrade());
5341    }
5342}
5343
5344fn mounted_script_view_handle(
5345    entity: Entity<ScriptHostView>,
5346    theme: ThemeHandle,
5347    host: ScriptViewHost,
5348    config: ScriptViewConfig,
5349    state: Rc<Cell<ScriptViewState>>,
5350    mount_lease: std::rc::Weak<()>,
5351) -> ScriptViewHandle {
5352    ScriptViewHandle(Rc::new(ScriptViewHandleInner {
5353        entity,
5354        theme,
5355        host,
5356        view_id: config.view_id,
5357        state,
5358        measured_bounds: Rc::new(Cell::new(None)),
5359        mount_lease,
5360    }))
5361}
5362
5363fn mount_prepared_lifecycle(
5364    factory: &ScriptWindowFactory,
5365    engine: &mut RuntimeEngine,
5366    host: &ScriptViewHost,
5367    view_id: &str,
5368    window_id: &str,
5369    policy: WindowCommandPolicy,
5370    lease: &std::rc::Weak<()>,
5371) -> Result<ScriptLifecycle, ScriptViewError> {
5372    factory
5373        .mount_lifecycle(
5374            engine,
5375            factory.program(),
5376            view_id,
5377            window_id,
5378            policy,
5379            true,
5380            Some(lease),
5381        )
5382        .inspect_err(|_| {
5383            host.unregister_view(view_id, lease);
5384            factory.runtime.borrow_mut().windows.remove(window_id);
5385        })
5386}
5387
5388fn resolve_root_theme_from_runtime(
5389    runtime: &UiRuntimeState,
5390    root: &ComponentInstancePath,
5391    window_id: &str,
5392    appearance: SystemAppearance,
5393    fallback: &ThemeVariant,
5394) -> ThemeVariant {
5395    runtime
5396        .theme
5397        .as_ref()
5398        .and_then(|themes| themes.resolve(Some(window_id), Some(root), appearance).ok())
5399        .map_or_else(|| fallback.clone(), |resolved| resolved.variant().clone())
5400}
5401
5402impl Render for ScriptHostView {
5403    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5404        crate::app::read_host_frame_epoch(cx);
5405        if self.state.get() != ScriptViewState::Active {
5406            return div().into_any_element();
5407        }
5408        let started = Instant::now();
5409        let element = self.render_active(window, cx);
5410        self.render_statistics.host_renders += 1;
5411        self.render_statistics.host_render_time += started.elapsed();
5412        element
5413    }
5414}
5415
5416impl ScriptHostView {
5417    #[allow(clippy::too_many_lines)]
5418    fn render_active(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
5419        self.consume_pending_interaction_cancel(window, cx);
5420        self.prepare_host_render(window, cx);
5421        self.consume_pending_interaction_cancel(window, cx);
5422        // Every failure since the last frame, from events, effects or this
5423        // render's preparation, reaches the Host once.
5424        self.report_new_failure(cx);
5425        self.primitives.set_generation(self.lifecycle.generation());
5426        let motion_root = format!("window:{}/view:{}/root", self.window_id, self.view_id);
5427        let (motion_active, committed_motion_events) = self.sample_motion_frame(&motion_root);
5428        let dispatcher = script_node_dispatcher(
5429            cx,
5430            self.lifecycle.runtime(),
5431            Rc::clone(&self.direct_signal_access),
5432            &self.view_id,
5433        )
5434        .with_presentation_sink(
5435            self.presentation_diagnostics
5436                .sink(self.lifecycle.generation()),
5437        );
5438        let appearance = system_appearance(window.appearance());
5439        let snapshot = self.render_snapshot(appearance);
5440        self.presentation_diagnostics
5441            .retain_nodes(|node| snapshot.geometry.get(node).is_some());
5442        self.publish_theme_after_render(&snapshot.theme, cx);
5443        let a11y_active = window.is_a11y_active();
5444        let interactions = self.host.interactions();
5445        let mut semantics = self.lifecycle.semantics().clone();
5446        if a11y_active {
5447            semantics.apply_primitive_projections(
5448                self.primitives
5449                    .accessibility_projections(self.lifecycle.retained(), cx),
5450            );
5451        }
5452        let focus_path = self.focus_path(window);
5453        let focus_indicators = self.focus_indicators_shown(&focus_path);
5454        let frame = Rc::new(HostFrame {
5455            number: self.islands.next_frame(),
5456            snapshot,
5457            dispatcher,
5458            interactions,
5459            semantics,
5460            focus_path,
5461            focus_indicators,
5462            motion_root,
5463            a11y_active,
5464            focus_owners: BTreeMap::new(),
5465        });
5466        self.frame = Some(Rc::clone(&frame));
5467        let (content, anchored) = self.build_content(&frame, None, window, cx);
5468        let content = match anchored {
5469            Some(ContentAnchor { width, pinned }) if self.islands.root_width == RootWidth::Host => {
5470                ReanchoredContent {
5471                    child: content,
5472                    width,
5473                    pinned,
5474                    laid_out_width: Rc::clone(&self.islands.laid_out_width),
5475                    view: cx.entity().downgrade(),
5476                    frame: Rc::clone(&frame),
5477                }
5478                .into_any_element()
5479            }
5480            _ => content,
5481        };
5482        self.report_presentation_diagnostics(cx);
5483        let snapshot = &frame.snapshot;
5484        let content = match (&self.last_failure, self.show_error_banner) {
5485            (Some(failure), true) => build_error_banner(
5486                &self.view_id,
5487                &self.window_id,
5488                &failure.message,
5489                &snapshot.theme,
5490                self.text_selection.clone(),
5491                self.host_focus.clone(),
5492                cx.listener(|view, _, _, cx| {
5493                    view.clear_failure();
5494                    cx.notify();
5495                }),
5496                content,
5497            ),
5498            _ => content,
5499        };
5500        let motion_ghosts = {
5501            let resources = frame.resources(self);
5502            snapshot
5503                .motion_ghosts
5504                .iter()
5505                .map(|ghost| {
5506                    crate::renderer::render_motion_ghost(
5507                        ghost,
5508                        &snapshot.theme,
5509                        &self.primitives,
5510                        &resources,
5511                    )
5512                })
5513                .collect::<Vec<_>>()
5514        };
5515        #[cfg(feature = "dev-reload")]
5516        let runtime = self.lifecycle.runtime();
5517        #[cfg(feature = "dev-reload")]
5518        let inspector = self.inspector_element(&runtime, &snapshot.theme);
5519        let text_selection = self.text_selection.clone();
5520        let (down, up, up_outside) = (
5521            Rc::clone(&self.islands.pressed),
5522            Rc::clone(&self.islands.pressed),
5523            Rc::clone(&self.islands.pressed),
5524        );
5525        let root = build_host_root(&self.host_focus, &snapshot.theme, self.paint_background)
5526            .on_mouse_down(MouseButton::Left, move |event, window, _| {
5527                if text_selection.clear_outside(event.position) {
5528                    window.refresh();
5529                }
5530            })
5531            .capture_any_mouse_down(move |_, _, _| down.set(true))
5532            .capture_any_mouse_up(move |_, _, _| up.set(false))
5533            .on_mouse_up_out(MouseButton::Left, move |_, _, _| up_outside.set(false))
5534            .child(content)
5535            .children(motion_ghosts)
5536            .children({
5537                #[cfg(feature = "dev-reload")]
5538                {
5539                    inspector
5540                }
5541                #[cfg(not(feature = "dev-reload"))]
5542                {
5543                    Option::<gpui::AnyElement>::None
5544                }
5545            });
5546        let root = apply_root_text_direction(root, snapshot.direction);
5547        let key_scope = ViewKeyScope::new(cx);
5548        let root = key_scope.apply(root);
5549        self.overlays.set_layer_key_scope(
5550            &self.view_id,
5551            Rc::new(move |layer: gpui::Div| key_scope.apply(layer)),
5552        );
5553        let has_committed_motion_events = !committed_motion_events.is_empty();
5554        cx.on_next_frame(window, move |view, _, cx| {
5555            view.lifecycle
5556                .runtime()
5557                .borrow()
5558                .geometry_for(Some(&view.view_id))
5559                .finish_frame();
5560            view.deliver_committed_motion_events(committed_motion_events, cx);
5561        });
5562        if motion_active || has_committed_motion_events {
5563            window.request_animation_frame();
5564        }
5565        crate::renderer::pointer_capture_router_element(
5566            root.into_any_element(),
5567            &self.view_id,
5568            self.lifecycle.retained(),
5569            &frame.dispatcher,
5570            &snapshot.pointer_capture,
5571            &snapshot.geometry,
5572            &self.scroll_handles,
5573            frame.interactions.clone(),
5574        )
5575    }
5576
5577    /// The retained tree's elements for `frame`, with the root width its islands
5578    /// anchor on (`laid_out_width`, else the last one) and whether one of them
5579    /// was pinned, when the root anchors them.
5580    fn build_content(
5581        &mut self,
5582        frame: &Rc<HostFrame>,
5583        laid_out_width: Option<u32>,
5584        window: &Window,
5585        cx: &mut Context<Self>,
5586    ) -> (AnyElement, Option<ContentAnchor>) {
5587        let islands = self.island_frame(frame, laid_out_width, window, cx);
5588        let build_started = Instant::now();
5589        let content = self.lifecycle.retained().root().map_or_else(
5590            || div().child("Script view has no root").into_any_element(),
5591            |_| {
5592                let mut resources = frame.resources(self);
5593                resources.islands = islands.as_ref();
5594                GpuiNodeRenderer::render_retained_with_window_runtime(
5595                    self.lifecycle.retained(),
5596                    &frame.snapshot.theme,
5597                    &InteractionState::default(),
5598                    &self.primitives,
5599                    &resources,
5600                )
5601            },
5602        );
5603        self.render_statistics.build_time += build_started.elapsed();
5604        #[allow(clippy::cast_possible_truncation)]
5605        let anchored = islands.and_then(|islands| {
5606            islands.root_anchor.map(|anchor| ContentAnchor {
5607                width: anchor as u32,
5608                pinned: Rc::clone(&islands.pinned),
5609            })
5610        });
5611        (content, anchored)
5612    }
5613
5614    /// This frame's cache islands: the plan of the committed tree, made again
5615    /// after a commit, and what every island's render depends on beyond its
5616    /// subtree. `None` when the view embeds none.
5617    fn island_frame(
5618        &mut self,
5619        frame: &HostFrame,
5620        laid_out_width: Option<u32>,
5621        window: &Window,
5622        cx: &mut Context<Self>,
5623    ) -> Option<crate::island::IslandFrame> {
5624        let policy = self.islands.policy;
5625        if !policy.enabled {
5626            return None;
5627        }
5628        let tree = self.lifecycle.retained();
5629        let planned = (self.lifecycle.generation(), self.lifecycle.revision());
5630        let generation_changed =
5631            self.islands.planned.map(|(generation, _)| generation) != Some(planned.0);
5632        // A new plan moves the elements of the islands it changes to other
5633        // GPUI element ids, which would drop a click in progress: while a
5634        // button is down, the islands of the last plan stay.
5635        if self.islands.planned != Some(planned)
5636            && (generation_changed || !self.islands.pressed.get())
5637        {
5638            if generation_changed {
5639                self.islands.entries.clear();
5640            }
5641            let entries = &mut self.islands.entries;
5642            let roots = crate::island::plan(tree, policy.min_nodes, |id| entries.contains_key(&id));
5643            entries.retain(|id, _| roots.contains(id));
5644            let host = cx.weak_entity();
5645            for root in roots {
5646                entries.entry(root).or_insert_with(|| {
5647                    let slot = Rc::default();
5648                    let island = cx.new(|_| RetainedIsland {
5649                        host: host.clone(),
5650                        slot: Rc::clone(&slot),
5651                    });
5652                    (
5653                        island.clone(),
5654                        crate::island::IslandEntry {
5655                            view: island.into(),
5656                            slot,
5657                        },
5658                    )
5659                });
5660            }
5661            self.islands.planned = Some(planned);
5662        }
5663        if self.islands.entries.is_empty() {
5664            return None;
5665        }
5666        // Reading every island keeps it among the entities the window tracks,
5667        // so a notify from GPUI inside a replayed island still reaches it.
5668        for (island, _) in self.islands.entries.values() {
5669            island.read(cx);
5670        }
5671        let snapshot = &frame.snapshot;
5672        let fingerprint = crate::island::FrameFingerprint {
5673            generation: planned.0,
5674            theme: snapshot.theme.clone(),
5675            local_themes: snapshot.local_themes.clone(),
5676            locale: snapshot.locale.clone(),
5677            number: snapshot.number.clone(),
5678            motion_preference: snapshot.motion_preference,
5679            motion_quality: snapshot.motion_quality,
5680            primitives: self.primitives.epoch(),
5681            window_drag: self.window_drag_areas,
5682            rem_bits: f32::from(window.rem_size()).to_bits(),
5683            scale_bits: window.scale_factor().to_bits(),
5684        };
5685        let fingerprint = match &self.islands.fingerprint {
5686            Some(previous) if **previous == fingerprint => Rc::clone(previous),
5687            _ => Rc::new(fingerprint),
5688        };
5689        self.islands.fingerprint = Some(Rc::clone(&fingerprint));
5690        // The viewport is the width of a view that fills its window. A Host
5691        // that sizes the view can resize it within one viewport, so its anchor
5692        // also holds the width the root last laid out at; the error banner lays
5693        // the content out itself.
5694        let viewport = f32::from(window.viewport_size().width).to_bits();
5695        let root_anchor = if self.last_failure.is_some() && self.show_error_banner {
5696            None
5697        } else {
5698            match self.islands.root_width {
5699                RootWidth::Content => None,
5700                RootWidth::Window => Some(u64::from(viewport)),
5701                RootWidth::Host => {
5702                    let width = laid_out_width
5703                        .or_else(|| self.islands.laid_out_width.get())
5704                        .unwrap_or(viewport);
5705                    Some((u64::from(viewport) << 32) | u64::from(width))
5706                }
5707            }
5708        };
5709        let mut islands = crate::island::IslandFrame {
5710            frame: frame.number,
5711            policy,
5712            fingerprint,
5713            revision: planned.1,
5714            entries: self
5715                .islands
5716                .entries
5717                .iter()
5718                .map(|(id, (_, entry))| (*id, entry.clone()))
5719                .collect(),
5720            counters: Rc::clone(&self.islands.counters),
5721            root_anchor,
5722            pinned: Rc::default(),
5723            motions: BTreeMap::new(),
5724            motion_unknown: false,
5725        };
5726        islands.assign_motions(tree, &snapshot.motions, &frame.motion_root);
5727        Some(islands)
5728    }
5729}
5730
5731/// What one frame of a view rendered from, kept for the cache islands it
5732/// embeds: they render after the view, from the same frame.
5733struct HostFrame {
5734    number: u64,
5735    snapshot: ScriptRenderSnapshot,
5736    dispatcher: NodeEventDispatcher,
5737    interactions: crate::interaction::WindowInteractionCoordinator,
5738    semantics: crate::CommittedSemanticFrame,
5739    focus_path: Vec<crate::NodeId>,
5740    /// Whether focus styles paint this frame ([`ScriptViewConfig::focus_indicators`]).
5741    focus_indicators: bool,
5742    motion_root: String,
5743    a11y_active: bool,
5744    /// The view renders its retained tree, where owners are found by walking
5745    /// ancestors; only slot content carries an owner map.
5746    focus_owners: BTreeMap<crate::NodeId, FocusHandle>,
5747}
5748
5749impl HostFrame {
5750    fn resources<'a>(
5751        &'a self,
5752        view: &'a ScriptHostView,
5753    ) -> crate::renderer::WindowRenderResources<'a> {
5754        let snapshot = &self.snapshot;
5755        crate::renderer::WindowRenderResources {
5756            now: snapshot.now,
5757            clock: &snapshot.clock,
5758            motion_preference: snapshot.motion_preference,
5759            motion_quality: snapshot.motion_quality,
5760            assets: &snapshot.assets,
5761            dispatcher: &self.dispatcher,
5762            overlays: &view.overlays,
5763            interactions: &self.interactions,
5764            motions: &snapshot.motions,
5765            signals: &snapshot.signals,
5766            geometry: &snapshot.geometry,
5767            pointer_capture: &snapshot.pointer_capture,
5768            focus_handles: &view.focus_handles,
5769            focus_owners: &self.focus_owners,
5770            scroll_handles: &view.scroll_handles,
5771            scroll_anchors: &view.scroll_anchors,
5772            wheel_parents: &[],
5773            key_captures: &[],
5774            intrinsic_size: None,
5775            virtual_requests: &snapshot.virtual_requests,
5776            text_selection: &view.text_selection,
5777            host_focus: Some(&view.host_focus),
5778            direction: snapshot.direction,
5779            locale: &snapshot.locale,
5780            number: snapshot.number.as_ref(),
5781            ambient_text_color: None,
5782            environment: crate::Environment::EMPTY,
5783            inherited_disabled: false,
5784            focus_path: &self.focus_path,
5785            focus_indicators: self.focus_indicators,
5786            owner_focused: false,
5787            root_path: &self.motion_root,
5788            view_id: &view.view_id,
5789            semantics: &self.semantics,
5790            a11y_active: self.a11y_active,
5791            window_drag: view.window_drag_areas,
5792            islands: None,
5793            theme_scopes: (!snapshot.local_themes.is_empty()).then_some(&snapshot.local_themes),
5794        }
5795    }
5796}
5797
5798/// What the width of a view's root follows, which decides the width anchor
5799/// of the islands under it.
5800#[derive(Clone, Copy, Debug, Eq, PartialEq)]
5801enum RootWidth {
5802    /// Its content: only explicit widths anchor islands.
5803    Content,
5804    /// Its window: the viewport's width anchors the root.
5805    Window,
5806    /// The Host, which may resize it without resizing the window: the width
5807    /// the root last laid out at anchors it, checked again in the frame
5808    /// ([`ReanchoredContent`]).
5809    Host,
5810}
5811
5812/// A view's cache islands ([`crate::island`]) across frames.
5813struct IslandTable {
5814    policy: crate::island::IslandPolicy,
5815    root_width: RootWidth,
5816    /// The width (`f32` bits) a Host-sized root last laid out at.
5817    laid_out_width: Rc<Cell<Option<u32>>>,
5818    /// The committed tree (generation and revision) the plan was made from.
5819    planned: Option<(crate::ScriptGeneration, u64)>,
5820    entries: BTreeMap<crate::NodeId, (Entity<RetainedIsland>, crate::island::IslandEntry)>,
5821    fingerprint: Option<Rc<crate::island::FrameFingerprint>>,
5822    counters: Rc<RefCell<crate::island::IslandCounters>>,
5823    frames: u64,
5824    /// A mouse button went down in the view and has not come up.
5825    pressed: Rc<Cell<bool>>,
5826}
5827
5828impl IslandTable {
5829    fn new(config: Option<bool>, root_width: RootWidth) -> Self {
5830        let policy = crate::island::IslandPolicy::resolve(config);
5831        // Aggressive mode takes a view that a Host lays out as sized by it.
5832        let root_width = if root_width == RootWidth::Content && policy.anchor_hosted_root {
5833            RootWidth::Host
5834        } else {
5835            root_width
5836        };
5837        Self {
5838            policy,
5839            root_width,
5840            laid_out_width: Rc::default(),
5841            planned: None,
5842            entries: BTreeMap::new(),
5843            fingerprint: None,
5844            counters: Rc::default(),
5845            frames: 0,
5846            pressed: Rc::default(),
5847        }
5848    }
5849
5850    const fn next_frame(&mut self) -> u64 {
5851        self.frames += 1;
5852        self.frames
5853    }
5854}
5855
5856/// A cache island's view: its root, rendered from the frame its view last
5857/// rendered with what the root inherits there.
5858struct RetainedIsland {
5859    host: gpui::WeakEntity<ScriptHostView>,
5860    slot: Rc<RefCell<crate::island::IslandSlot>>,
5861}
5862
5863impl Render for RetainedIsland {
5864    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5865        let Some(host) = self.host.upgrade() else {
5866            return gpui::Empty.into_any_element();
5867        };
5868        let host = host.read(cx);
5869        let (capture, root_width) = {
5870            let slot = self.slot.borrow();
5871            (
5872                slot.capture.clone(),
5873                slot.render_bounds.map(|bounds| bounds.size.width),
5874            )
5875        };
5876        let (Some(frame), Some(capture)) = (host.frame.as_deref(), capture) else {
5877            return gpui::Empty.into_any_element();
5878        };
5879        let started = Instant::now();
5880        let tree = host.lifecycle.retained();
5881        let element = GpuiNodeRenderer::render_island_root(
5882            tree,
5883            &frame.snapshot.theme,
5884            &host.primitives,
5885            &frame.resources(host),
5886            &capture,
5887            root_width,
5888        );
5889        self.slot.borrow_mut().rendered(frame.number, tree);
5890        host.islands.counters.borrow_mut().render_time += started.elapsed();
5891        element
5892    }
5893}
5894
5895fn native_lifecycle_error(
5896    operation: &str,
5897    error: &crate::PrimitiveError,
5898    rollback: Option<&crate::PrimitiveError>,
5899) -> String {
5900    rollback.map_or_else(
5901        || format!("native primitive {operation} failed: {error}"),
5902        |rollback| {
5903            format!("native primitive {operation} failed: {error}; compensation failed: {rollback}")
5904        },
5905    )
5906}
5907
5908impl ScriptHostView {
5909    fn on_window_appearance_changed(
5910        &mut self,
5911        appearance: WindowAppearance,
5912        cx: &mut Context<Self>,
5913    ) {
5914        if self.state.get() == ScriptViewState::Disposed {
5915            return;
5916        }
5917        let changed = self
5918            .lifecycle
5919            .runtime()
5920            .borrow_mut()
5921            .update_window_appearance(&self.window_id, system_appearance(appearance));
5922        if changed && self.state.get() == ScriptViewState::Active {
5923            // Ingest before scheduling normal transactional work. Do not run
5924            // Rhai or effects inside GPUI's appearance observer delivery.
5925            // Defer with a weak entity; poll_async rechecks current lifecycle.
5926            let owner = cx.weak_entity();
5927            cx.defer(move |cx| {
5928                let _ = owner.update(cx, Self::poll_async);
5929            });
5930            cx.notify();
5931        }
5932        // Suspended views retain the new environment/dirty owners for resume;
5933        // no script, effect or animation is activated by this notification.
5934    }
5935
5936    fn sample_motion_frame(&mut self, domain: &str) -> (bool, Vec<crate::MotionTimelineEvent>) {
5937        let runtime = self.lifecycle.runtime();
5938        let mut runtime = runtime.borrow_mut();
5939        let now = runtime.clock.now();
5940        let clock_advanced = self.last_motion_sample != Some(now);
5941        self.last_motion_sample = Some(now);
5942        let (frame, events) = sample_motion_domain(&mut runtime, domain, now);
5943        self.motion_waits_for_clock = frame.needs_frame && !clock_advanced;
5944        (clock_advanced && frame.needs_frame, events)
5945    }
5946
5947    fn deliver_committed_motion_events(
5948        &mut self,
5949        events: Vec<crate::MotionTimelineEvent>,
5950        cx: &mut Context<Self>,
5951    ) {
5952        match self.state.get() {
5953            ScriptViewState::Suspended => {
5954                self.lifecycle
5955                    .runtime()
5956                    .borrow_mut()
5957                    .motions
5958                    .prepend_timeline_events(events);
5959                return;
5960            }
5961            ScriptViewState::Disposed => return,
5962            ScriptViewState::Active => {}
5963        }
5964        let mut changed = false;
5965        let mut first_error = None;
5966        for event in events {
5967            if event.callback.is_none() {
5968                continue;
5969            }
5970            let result = self.run_script_transaction(|view| {
5971                let callback_changed = view.invoke_motion_timeline_callback(event)?;
5972                let mut work_changed = view.invoke_pending_effects()?;
5973                work_changed |= view
5974                    .lifecycle
5975                    .render_dirty(&mut view.engine)
5976                    .map_err(|error| view.lifecycle_failure(&error, None))?;
5977                Ok(callback_changed || work_changed)
5978            });
5979            match result {
5980                Ok(event_changed) => changed |= event_changed,
5981                Err(error) => {
5982                    first_error.get_or_insert(error);
5983                }
5984            }
5985        }
5986        if let Some(error) = first_error {
5987            self.set_failure(error);
5988            changed = true;
5989        }
5990        if changed {
5991            cx.notify();
5992        }
5993    }
5994
5995    fn lifecycle_failure(
5996        &self,
5997        error: &crate::LifecycleError,
5998        component: Option<&ComponentInstancePath>,
5999    ) -> ScriptFailure {
6000        self.lifecycle_failure_with_engine(&self.engine, error, component)
6001    }
6002
6003    fn lifecycle_failure_with_engine(
6004        &self,
6005        engine: &RuntimeEngine,
6006        error: &crate::LifecycleError,
6007        component: Option<&ComponentInstancePath>,
6008    ) -> ScriptFailure {
6009        let message = error.to_string();
6010        if let crate::LifecycleError::Runtime(runtime_error) = error
6011            && let Ok(context) = self.lifecycle.diagnostic_context(engine, component)
6012        {
6013            return ScriptFailure::with_diagnostic(
6014                message,
6015                Diagnostic::from_runtime(runtime_error, &context),
6016            );
6017        }
6018        ScriptFailure::plain(message)
6019    }
6020
6021    #[cfg(feature = "dev-reload")]
6022    fn runtime_failure_with_engine(
6023        &self,
6024        engine: &RuntimeEngine,
6025        error: &RuntimeError,
6026        component: Option<&ComponentInstancePath>,
6027    ) -> ScriptFailure {
6028        let message = error.to_string();
6029        match self.lifecycle.diagnostic_context(engine, component) {
6030            Ok(context) => {
6031                ScriptFailure::with_diagnostic(message, Diagnostic::from_runtime(error, &context))
6032            }
6033            Err(_) => ScriptFailure::plain(message),
6034        }
6035    }
6036
6037    fn set_failure(&mut self, failure: ScriptFailure) {
6038        self.failure_serial += 1;
6039        self.last_failure = Some(failure);
6040    }
6041
6042    fn set_plain_failure(&mut self, message: impl Into<String>) {
6043        self.set_failure(ScriptFailure::plain(message));
6044    }
6045
6046    fn clear_failure(&mut self) {
6047        self.last_failure = None;
6048    }
6049
6050    fn failure_message(&self) -> Option<String> {
6051        self.last_failure
6052            .as_ref()
6053            .map(|failure| failure.message.clone())
6054    }
6055
6056    /// The failure recorded after `serial` was read, if any.
6057    fn failure_since(&self, serial: u64) -> Option<String> {
6058        if self.failure_serial == serial {
6059            None
6060        } else {
6061            self.failure_message()
6062        }
6063    }
6064
6065    /// Report a failure recorded since the last report: to stderr when
6066    /// mirroring, and to the Host's observer after this frame, when the view
6067    /// is no longer borrowed and the observer may read its handle.
6068    fn report_new_failure(&mut self, cx: &mut Context<Self>) {
6069        if self.failure_serial == self.reported_failure_serial {
6070            return;
6071        }
6072        self.reported_failure_serial = self.failure_serial;
6073        let Some(failure) = &self.last_failure else {
6074            return;
6075        };
6076        self.report_to_host(
6077            ScriptErrorReport {
6078                domain: ScriptErrorDomain::Transaction,
6079                view_id: self.view_id.clone(),
6080                message: failure.message.clone(),
6081                diagnostic: failure.diagnostic.as_deref().cloned(),
6082                presentation: None,
6083            },
6084            cx,
6085        );
6086    }
6087
6088    fn report_presentation_diagnostics(&self, cx: &mut Context<Self>) {
6089        // A reload may commit before the next presentation/pump turn.
6090        // Invalidate queued reports from that old generation before delivery.
6091        self.presentation_diagnostics
6092            .sink(self.lifecycle.generation());
6093        for diagnostic in self.presentation_diagnostics.drain() {
6094            self.report_to_host(
6095                ScriptErrorReport {
6096                    domain: ScriptErrorDomain::Presentation,
6097                    view_id: self.view_id.clone(),
6098                    message: diagnostic.message.clone(),
6099                    diagnostic: None,
6100                    presentation: Some(diagnostic),
6101                },
6102                cx,
6103            );
6104        }
6105    }
6106
6107    fn report_to_host(&self, report: ScriptErrorReport, cx: &mut Context<Self>) {
6108        if self.error_reporting.stderr {
6109            if report.domain == ScriptErrorDomain::Transaction {
6110                eprintln!("gpui-rhai: view `{}`: {}", report.view_id, report.message);
6111            } else {
6112                eprintln!(
6113                    "gpui-rhai: view `{}` [presentation]: {}",
6114                    report.view_id, report.message
6115                );
6116            }
6117        }
6118        if let Some(ErrorObserver(observer)) = self.error_reporting.observer.clone() {
6119            cx.defer(move |cx| observer(&report, cx));
6120        }
6121    }
6122
6123    fn publish_theme_after_render(&self, theme: &ThemeVariant, cx: &mut Context<Self>) {
6124        if self.theme_handle.matches(theme, cx) {
6125            return;
6126        }
6127        let handle = self.theme_handle.clone();
6128        let theme = theme.clone();
6129        cx.defer(move |cx| handle.publish(theme, cx));
6130    }
6131
6132    fn execute_automation(
6133        &mut self,
6134        command: crate::AutomationCommand,
6135        window: &mut Window,
6136        cx: &mut Context<Self>,
6137    ) -> Result<crate::AutomationResult, ScriptViewError> {
6138        let serial = self.failure_serial;
6139        match command {
6140            crate::AutomationCommand::Dispatch {
6141                locator,
6142                event,
6143                payload,
6144            } => self.automation_dispatch(&locator, &event, payload, window, cx),
6145            crate::AutomationCommand::Action { id, payload } => {
6146                let action = ActionId::parse(&id)?;
6147                let invocation = self
6148                    .lifecycle
6149                    .runtime()
6150                    .borrow()
6151                    .actions
6152                    .dispatch(&action, payload.unwrap_or(UiValue::Null))?;
6153                let _ = self.handle_node_event(
6154                    &invocation.callback,
6155                    invocation.payload,
6156                    None,
6157                    crate::InvocationOrigin::Automation,
6158                    window,
6159                    cx,
6160                );
6161                if let Some(error) = self.failure_since(serial) {
6162                    return Err(crate::AutomationError::Command(error).into());
6163                }
6164                Ok(crate::AutomationResult::Action { id })
6165            }
6166            crate::AutomationCommand::AdvanceTime { millis } => {
6167                let duration = Duration::from_millis(millis);
6168                let clock = self.lifecycle.runtime().borrow().clock.clone();
6169                if !clock.advance(duration) {
6170                    return Err(crate::AutomationError::ClockNotControllable.into());
6171                }
6172                self.poll_async(cx);
6173                if let Some(error) = self.failure_since(serial) {
6174                    return Err(crate::AutomationError::Command(error).into());
6175                }
6176                Ok(crate::AutomationResult::Advanced { millis })
6177            }
6178            crate::AutomationCommand::Snapshot | crate::AutomationCommand::Query { .. } => {
6179                unreachable!("read-only automation commands are handled by ScriptViewHandle")
6180            }
6181        }
6182    }
6183
6184    #[allow(clippy::too_many_lines)]
6185    fn automation_dispatch(
6186        &mut self,
6187        locator: &crate::AutomationLocator,
6188        event: &str,
6189        payload: Option<UiValue>,
6190        window: &mut Window,
6191        cx: &mut Context<Self>,
6192    ) -> Result<crate::AutomationResult, ScriptViewError> {
6193        let serial = self.failure_serial;
6194        let runtime = self.lifecycle.runtime();
6195        let geometry = runtime.borrow().geometry_for(Some(&self.view_id));
6196        let mut accessibility = crate::AccessibilityTree::from_committed(
6197            self.lifecycle.semantics(),
6198            self.lifecycle.retained(),
6199            &geometry,
6200            true,
6201        );
6202        accessibility.apply_primitive_projections(
6203            self.primitives
6204                .accessibility_projections(self.lifecycle.retained(), cx),
6205        );
6206        let target = crate::automation::resolve_locator(&accessibility, locator)?;
6207        let target_node = self
6208            .lifecycle
6209            .retained()
6210            .node(target)
6211            .ok_or_else(|| crate::AutomationError::StaleTarget(target.get()))?;
6212        // An explicit payload reaches every handler; otherwise a handler
6213        // declared with its own value receives it, and the rest the node's.
6214        let explicit = payload.is_some();
6215        let payload = payload
6216            .or_else(|| target_node.node_payload(event).cloned())
6217            .unwrap_or(UiValue::Null);
6218        let native_target = target_node
6219            .primitive()
6220            .zip(target_node.key())
6221            .map(|(primitive, key)| (primitive.clone(), key.to_owned()));
6222        let steps = crate::automation::dispatch_plan(self.lifecycle.retained(), target, event)?;
6223        let mut response = crate::EventResponse::new();
6224        let mut invoked = 0usize;
6225        let mut visited = Vec::new();
6226        let mut stop_after: Option<(crate::NodeId, crate::EventPhase)> = None;
6227        for step in steps {
6228            if stop_after.is_some_and(|phase| phase != (step.node, step.phase)) {
6229                break;
6230            }
6231            if visited.last() != Some(&step.node) {
6232                visited.push(step.node);
6233            }
6234            let event_target = geometry.get(step.node).map(|geometry| geometry.visual);
6235            let step_payload = match &step.value {
6236                Some(value) if !explicit => value.clone(),
6237                _ => payload.clone(),
6238            };
6239            let current = match &step.handler {
6240                crate::UiEventHandler::Script(callback) => self.handle_node_event(
6241                    callback,
6242                    step_payload,
6243                    event_target,
6244                    crate::InvocationOrigin::Automation,
6245                    window,
6246                    cx,
6247                ),
6248                crate::UiEventHandler::Host(callback) => callback.invoke(step_payload, window, cx),
6249                crate::UiEventHandler::Native(handler) => self.handle_native_event(
6250                    handler,
6251                    event.to_owned(),
6252                    step_payload,
6253                    event_target,
6254                    window,
6255                    cx,
6256                ),
6257            };
6258            invoked = invoked.saturating_add(1);
6259            if let Some(error) = self.failure_since(serial) {
6260                return Err(crate::AutomationError::Command(error).into());
6261            }
6262            response.merge(current);
6263            match current.propagation() {
6264                crate::PropagationControl::StopImmediate => break,
6265                crate::PropagationControl::Stop => stop_after = Some((step.node, step.phase)),
6266                crate::PropagationControl::Continue => {}
6267            }
6268            if let Some(pointer_id) = automation_pointer_id(&payload) {
6269                match current.pointer_capture() {
6270                    crate::PointerCaptureDirective::Capture => {
6271                        runtime
6272                            .borrow()
6273                            .pointer_capture_for(Some(&self.view_id))
6274                            .capture(pointer_id, target);
6275                    }
6276                    crate::PointerCaptureDirective::Release => {
6277                        runtime
6278                            .borrow()
6279                            .pointer_capture_for(Some(&self.view_id))
6280                            .release(pointer_id);
6281                    }
6282                    crate::PointerCaptureDirective::None => {}
6283                }
6284            }
6285        }
6286        if invoked == 0
6287            && let Some(key) = event.strip_prefix("key:")
6288            && let Some((primitive, keyed)) = native_target
6289        {
6290            let instance = crate::PrimitiveInstanceId::new(primitive, keyed, target);
6291            if let Some(proposal) = self
6292                .primitives
6293                .perform_key(&instance, key)
6294                .map_err(|error| crate::AutomationError::Command(error.to_string()))?
6295            {
6296                visited.push(target);
6297                invoked = 1;
6298                let current = match proposal.handler {
6299                    Some(crate::UiEventHandler::Script(callback)) => self.handle_node_event(
6300                        &callback,
6301                        proposal.payload,
6302                        None,
6303                        crate::InvocationOrigin::Automation,
6304                        window,
6305                        cx,
6306                    ),
6307                    Some(crate::UiEventHandler::Host(callback)) => {
6308                        callback.invoke(proposal.payload, window, cx)
6309                    }
6310                    Some(crate::UiEventHandler::Native(handler)) => self.handle_native_event(
6311                        &handler,
6312                        proposal.event,
6313                        proposal.payload,
6314                        None,
6315                        window,
6316                        cx,
6317                    ),
6318                    None => crate::EventResponse::new().stop(),
6319                };
6320                if let Some(error) = self.failure_since(serial) {
6321                    return Err(crate::AutomationError::Command(error).into());
6322                }
6323                response.merge(current.stop());
6324            }
6325        }
6326        Ok(crate::AutomationResult::Dispatch {
6327            report: crate::AutomationDispatchReport {
6328                target: target.get(),
6329                visited: visited.into_iter().map(crate::NodeId::get).collect(),
6330                invoked,
6331                default_prevented: response.default_prevented(),
6332                stopped: response.stops_propagation(),
6333            },
6334        })
6335    }
6336
6337    fn render_snapshot(&self, appearance: SystemAppearance) -> ScriptRenderSnapshot {
6338        let runtime = self.lifecycle.runtime();
6339        let mut runtime = runtime.borrow_mut();
6340        runtime.update_window_appearance(&self.window_id, appearance);
6341        let root = self.lifecycle.root_path();
6342        let theme = resolve_root_theme_from_runtime(
6343            &runtime,
6344            root,
6345            &self.window_id,
6346            appearance,
6347            &self.theme,
6348        );
6349        let local_themes = runtime
6350            .theme
6351            .as_ref()
6352            .map(|themes| themes.local_themes(appearance))
6353            .unwrap_or_default();
6354        let direction = runtime
6355            .locale
6356            .as_ref()
6357            .and_then(|locale| locale.direction(Some(&self.window_id), Some(root)).ok())
6358            .unwrap_or(TextDirection::LeftToRight);
6359        let locale = runtime
6360            .locale
6361            .as_ref()
6362            .and_then(|locale| locale.locale(Some(&self.window_id), Some(root)).ok())
6363            .unwrap_or("en")
6364            .to_owned();
6365        let number = runtime
6366            .locale
6367            .as_ref()
6368            .and_then(|locale| locale.number(Some(&self.window_id), Some(root)).ok())
6369            .cloned();
6370        let motion_domain = format!("window:{}/view:{}/root", self.window_id, self.view_id);
6371        ScriptRenderSnapshot {
6372            now: runtime.clock.now(),
6373            clock: runtime.clock.clone(),
6374            motion_preference: runtime.motions.preference(),
6375            motion_quality: runtime.motions.quality(),
6376            assets: runtime.assets.clone(),
6377            theme,
6378            local_themes,
6379            motions: runtime.motion_values.clone(),
6380            motion_ghosts: runtime
6381                .motion_ghosts
6382                .iter()
6383                .filter(|ghost| ghost.domain == motion_domain)
6384                .cloned()
6385                .collect(),
6386            signals: runtime.signals.clone(),
6387            geometry: runtime.geometry_for(Some(&self.view_id)),
6388            pointer_capture: runtime.pointer_capture_for(Some(&self.view_id)),
6389            virtual_requests: runtime.virtual_requests.clone(),
6390            direction,
6391            locale,
6392            number,
6393        }
6394    }
6395
6396    fn prepare_host_render(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6397        self.prepare_render(window);
6398        // What the walks below derive (primitive mounts, the parent map,
6399        // focus and scroll handles, page focus) comes from the committed tree
6400        // and the registered primitives; when neither changed since the last
6401        // frame, that frame's result stands.
6402        let derived = DerivedKey {
6403            generation: self.lifecycle.generation(),
6404            revision: self.lifecycle.revision(),
6405            primitives: self.primitives.epoch(),
6406        };
6407        let walk = self.derived_key != Some(derived);
6408        if walk {
6409            self.retain_mounted_primitives();
6410        }
6411        self.host.interactions().set_retained_tree(
6412            &self.view_id,
6413            self.lifecycle.retained(),
6414            (derived.generation, derived.revision),
6415        );
6416        self.lifecycle
6417            .runtime()
6418            .borrow()
6419            .geometry_for(Some(&self.view_id))
6420            .begin_frame();
6421        self.text_selection.retain(self.lifecycle.retained());
6422        if walk {
6423            self.sync_focus_handles(window, cx);
6424            self.derived_key = Some(derived);
6425            self.render_statistics.tree_walks += 1;
6426        } else {
6427            #[cfg(debug_assertions)]
6428            self.debug_assert_walks_current();
6429        }
6430        self.process_element_commands(window, cx);
6431    }
6432
6433    fn set_content_bounds(&mut self, bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
6434        if self.content_bounds != Some(bounds) {
6435            self.content_bounds = Some(bounds);
6436            cx.notify();
6437        }
6438    }
6439
6440    fn prepare_render(&mut self, window: &Window) {
6441        if !self.host.frame_active() {
6442            self.set_plain_failure(
6443                "embedded ScriptView must be rendered inside ScriptViewHost::container",
6444            );
6445        }
6446        self.sync_viewport_class(window);
6447        debug_assert!(self.engine.is_current(self.lifecycle.generation()));
6448        self.primitives.set_generation(self.lifecycle.generation());
6449    }
6450
6451    /// Listens for focus entering and leaving each node with a `focus_within_change` handler,
6452    /// through the focus handle the renderer tracks on it. GPUI reports both after a frame,
6453    /// from the focus path of that frame, so focus inside the node's subtree counts whether or
6454    /// not the focused element has a handle of the view's own.
6455    fn sync_focus_within_listeners(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6456        let watched = self
6457            .lifecycle
6458            .retained()
6459            .host_nodes()
6460            .into_iter()
6461            .filter(|node| !node.event_handlers("focus_within_change").is_empty())
6462            .map(crate::RetainedNode::id)
6463            .collect::<BTreeSet<_>>();
6464        self.focus_within_listeners
6465            .retain(|node, _| watched.contains(node));
6466        for node in watched {
6467            if self.focus_within_listeners.contains_key(&node) {
6468                continue;
6469            }
6470            let Some(handle) = self.focus_handles.get(&node).cloned() else {
6471                continue;
6472            };
6473            let focus_in = cx.on_focus_in(&handle, window, move |_, window, cx| {
6474                cx.defer_in(window, move |view, window, cx| {
6475                    view.dispatch_focus_within_change(node, true, window, cx);
6476                });
6477            });
6478            let focus_out = cx.on_focus_out(&handle, window, move |_, _, window, cx| {
6479                cx.defer_in(window, move |view, window, cx| {
6480                    view.dispatch_focus_within_change(node, false, window, cx);
6481                });
6482            });
6483            self.focus_within_listeners
6484                .insert(node, [focus_in, focus_out]);
6485        }
6486    }
6487
6488    /// Runs the node's `focus_within_change` handlers; the listeners defer it past the frame
6489    /// that reported the change, since scripts never run inside a draw.
6490    fn dispatch_focus_within_change(
6491        &mut self,
6492        node: crate::NodeId,
6493        focused: bool,
6494        window: &mut Window,
6495        cx: &mut Context<Self>,
6496    ) {
6497        if self.state.get() != ScriptViewState::Active {
6498            return;
6499        }
6500        let Some(retained) = self.lifecycle.retained().node(node) else {
6501            return;
6502        };
6503        let value = retained.node_payload("focus_within_change").cloned();
6504        // A handler with a value, its own or the node's, receives `#{ focused, value }`; a
6505        // plain handler receives the bool, as with `hover_change`.
6506        let calls = retained
6507            .event_handlers("focus_within_change")
6508            .iter()
6509            .filter(|binding| binding.phase() == crate::EventPhase::Target)
6510            .map(|binding| {
6511                let payload =
6512                    binding
6513                        .value()
6514                        .or(value.as_ref())
6515                        .map_or(UiValue::Bool(focused), |value| {
6516                            UiValue::Map(BTreeMap::from([
6517                                ("focused".to_owned(), UiValue::Bool(focused)),
6518                                ("value".to_owned(), value.clone()),
6519                            ]))
6520                        });
6521                (binding.handler().clone(), payload)
6522            })
6523            .collect::<Vec<_>>();
6524        let target = self
6525            .lifecycle
6526            .runtime()
6527            .borrow()
6528            .geometry_for(Some(&self.view_id))
6529            .get(node)
6530            .map(|geometry| geometry.visual);
6531        for (handler, payload) in calls {
6532            let crate::UiEventHandler::Script(callback) = handler else {
6533                continue;
6534            };
6535            let origin = crate::InvocationOrigin::UserInput {
6536                event: "focus_within_change".to_owned(),
6537            };
6538            self.handle_node_event(&callback, payload, target, origin, window, cx);
6539        }
6540    }
6541
6542    /// The focused retained node followed by its ancestors, for `group_focus`
6543    /// and `focus_within` styles.
6544    /// Whether focus styles paint, by the view's policy, unless a text field holds
6545    /// focus: its frame shows where typing goes.
6546    fn focus_indicators_shown(&self, focus_path: &[crate::NodeId]) -> bool {
6547        let by_policy = match self.focus_indicators {
6548            FocusIndicators::Always => true,
6549            FocusIndicators::Never => false,
6550            FocusIndicators::Navigation => self.navigating,
6551        };
6552        by_policy
6553            || focus_path.first().is_some_and(|focused| {
6554                self.lifecycle
6555                    .retained()
6556                    .node(*focused)
6557                    .and_then(crate::RetainedNode::primitive)
6558                    .is_some_and(|primitive| {
6559                        matches!(
6560                            primitive.as_str(),
6561                            "gpui_rhai.text_input" | "gpui_rhai.textarea"
6562                        )
6563                    })
6564            })
6565    }
6566
6567    fn focus_path(&self, window: &Window) -> Vec<crate::NodeId> {
6568        let Some(focused) = self
6569            .focus_handles
6570            .iter()
6571            .find(|(_, handle)| handle.is_focused(window))
6572            .map(|(node, _)| *node)
6573        else {
6574            return Vec::new();
6575        };
6576        let mut path = vec![focused];
6577        let mut cursor = self
6578            .lifecycle
6579            .retained()
6580            .node(focused)
6581            .and_then(crate::RetainedNode::parent);
6582        while let Some(node) = cursor {
6583            path.push(node);
6584            cursor = self
6585                .lifecycle
6586                .retained()
6587                .node(node)
6588                .and_then(crate::RetainedNode::parent);
6589        }
6590        path
6591    }
6592
6593    fn navigation_stacks(&self, window: &Window, cx: &App) -> Vec<crate::NavigationStackInfo> {
6594        if self.state.get() != ScriptViewState::Active {
6595            return Vec::new();
6596        }
6597        self.lifecycle
6598            .retained()
6599            .nodes()
6600            .filter_map(|node| {
6601                let UiValue::Integer(depth) = node
6602                    .attributes()
6603                    .get(crate::retained_page::NAVIGATION_DEPTH)?
6604                else {
6605                    return None;
6606                };
6607                if !self.lifecycle.retained().is_page_visible(node.id()) {
6608                    return None;
6609                }
6610                Some(crate::NavigationStackInfo {
6611                    view_id: self.view_id.clone(),
6612                    node: node.id(),
6613                    label: match node.attributes().get("label") {
6614                        Some(UiValue::String(label)) => label.clone(),
6615                        _ => String::new(),
6616                    },
6617                    depth: usize::try_from(*depth).ok()?,
6618                    can_pop: *depth > 1
6619                        && !node
6620                            .event_handlers(crate::retained_page::NAVIGATION_BACK)
6621                            .is_empty(),
6622                    focused: self
6623                        .focus_handles
6624                        .get(&node.id())
6625                        .is_some_and(|handle| handle.contains_focused(window, cx)),
6626                })
6627            })
6628            .collect()
6629    }
6630
6631    fn propose_navigation_back(
6632        &mut self,
6633        source: &str,
6634        window: &mut Window,
6635        cx: &mut Context<Self>,
6636    ) -> bool {
6637        let target = self
6638            .navigation_stacks(window, cx)
6639            .into_iter()
6640            .filter(|stack| stack.focused && stack.can_pop)
6641            .max_by_key(|stack| retained_depth(self.lifecycle.retained(), stack.node));
6642        let Some(target) = target else {
6643            return false;
6644        };
6645        let handlers = self
6646            .lifecycle
6647            .retained()
6648            .node(target.node)
6649            .map(|node| {
6650                node.event_handlers(crate::retained_page::NAVIGATION_BACK)
6651                    .to_vec()
6652            })
6653            .unwrap_or_default();
6654        let payload = UiValue::Map(BTreeMap::from([
6655            (
6656                "depth".to_owned(),
6657                UiValue::Integer(i64::try_from(target.depth - 1).unwrap_or(1)),
6658            ),
6659            ("source".to_owned(), UiValue::String(source.to_owned())),
6660        ]));
6661        for binding in handlers {
6662            let response = match binding.handler() {
6663                crate::UiEventHandler::Script(callback) => self.handle_node_event(
6664                    callback,
6665                    payload.clone(),
6666                    None,
6667                    crate::InvocationOrigin::UserInput {
6668                        event: crate::retained_page::NAVIGATION_BACK.to_owned(),
6669                    },
6670                    window,
6671                    cx,
6672                ),
6673                crate::UiEventHandler::Host(callback) => {
6674                    callback.invoke(payload.clone(), window, cx)
6675                }
6676                crate::UiEventHandler::Native(handler) => self.handle_native_event(
6677                    handler,
6678                    crate::retained_page::NAVIGATION_BACK.to_owned(),
6679                    payload.clone(),
6680                    None,
6681                    window,
6682                    cx,
6683                ),
6684            };
6685            if response.propagation() == crate::PropagationControl::StopImmediate {
6686                break;
6687            }
6688        }
6689        true
6690    }
6691
6692    #[allow(clippy::too_many_lines)]
6693    fn sync_retained_page_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6694        let tree = self.lifecycle.retained();
6695        let pages = tree
6696            .host_nodes()
6697            .into_iter()
6698            .filter(|node| {
6699                node.attributes()
6700                    .contains_key(crate::retained_page::PAGE_VISIBLE)
6701            })
6702            .map(crate::RetainedNode::id)
6703            .collect::<BTreeSet<_>>();
6704        let visible = pages
6705            .iter()
6706            .copied()
6707            .filter(|node| tree.is_page_visible(*node))
6708            .collect::<BTreeSet<_>>();
6709        if visible != self.visible_pages {
6710            self.navigation_focus_epoch = self.navigation_focus_epoch.wrapping_add(1);
6711        }
6712        let focused = self
6713            .focus_handles
6714            .iter()
6715            .find(|(_, handle)| handle.is_focused(window))
6716            .map(|(node, handle)| (*node, handle.clone()));
6717        let mut hid_focus = false;
6718        let mut hidden_page = None;
6719        for page in self.visible_pages.difference(&visible) {
6720            if self
6721                .focus_handles
6722                .get(page)
6723                .is_some_and(|handle| handle.contains_focused(window, cx))
6724            {
6725                hid_focus = true;
6726                if tree.node(*page).is_some() {
6727                    hidden_page = Some(*page);
6728                }
6729                if pages.contains(page)
6730                    && let Some(focused) = focused.clone()
6731                {
6732                    self.page_focus.insert(*page, focused);
6733                }
6734            }
6735        }
6736        self.page_focus.retain(|page, _| pages.contains(page));
6737        let scopes = pages
6738            .iter()
6739            .filter_map(|page| {
6740                let mut cursor = tree.node(*page).and_then(crate::RetainedNode::parent);
6741                while let Some(node) = cursor {
6742                    let retained = tree.node(node)?;
6743                    if retained
6744                        .attributes()
6745                        .contains_key(crate::retained_page::NAVIGATION_DEPTH)
6746                    {
6747                        return Some((*page, node));
6748                    }
6749                    cursor = retained.parent();
6750                }
6751                None
6752            })
6753            .collect::<BTreeMap<_, _>>();
6754        let unfocused = window.focused(cx).is_none();
6755        let target = visible
6756            .difference(&self.visible_pages)
6757            .copied()
6758            .filter(|page| {
6759                let Some(scope) = scopes.get(page) else {
6760                    return false;
6761                };
6762                // Revealing an unchanged inner stack by switching a retained
6763                // tab must not steal the tab list's keyboard focus. Only a
6764                // new visit or a change within a previously visible stack does.
6765                !self.page_scopes.contains_key(page)
6766                    || self
6767                        .visible_pages
6768                        .iter()
6769                        .any(|previous| self.page_scopes.get(previous) == Some(scope))
6770            })
6771            .filter(|page| {
6772                // Mounting/revealing a stack is not permission to take focus
6773                // from a sidebar, another stack or another embedded view.
6774                unfocused
6775                    || scopes
6776                        .get(page)
6777                        .and_then(|scope| self.focus_handles.get(scope))
6778                        .is_some_and(|handle| handle.contains_focused(window, cx))
6779            })
6780            .max_by_key(|page| retained_depth(tree, *page));
6781        if hid_focus {
6782            self.host_focus.focus(window, cx);
6783        }
6784        if let Some(page) = target {
6785            let generation = self.lifecycle.generation();
6786            let epoch = self.navigation_focus_epoch;
6787            let focus_owner = window.focused(cx);
6788            let window_id = window.window_handle().window_id();
6789            // Wait until the new heading's handle has entered the real focus tree.
6790            cx.on_next_frame(window, move |view, window, cx| {
6791                let tree = view.lifecycle.retained();
6792                if view.state.get() != ScriptViewState::Active
6793                    || view.lifecycle.generation() != generation
6794                    || !tree.is_page_visible(page)
6795                    || view.navigation_focus_epoch != epoch
6796                    || window.window_handle().window_id() != window_id
6797                    || window.focused(cx) != focus_owner
6798                {
6799                    return;
6800                }
6801                let saved = view
6802                    .page_focus
6803                    .get(&page)
6804                    .filter(|(node, _)| {
6805                        tree.is_page_visible(*node) && retained_within(tree, *node, page)
6806                    })
6807                    .map(|(_, handle)| handle.clone());
6808                let heading = tree
6809                    .nodes()
6810                    .find(|node| {
6811                        retained_within(tree, node.id(), page)
6812                            && node.attributes().get("role")
6813                                == Some(&UiValue::String("heading".to_owned()))
6814                            && tree.is_page_visible(node.id())
6815                    })
6816                    .and_then(|node| view.focus_handles.get(&node.id()))
6817                    .cloned();
6818                if let Some(handle) = saved
6819                    .or(heading)
6820                    .or_else(|| view.focus_handles.get(&page).cloned())
6821                {
6822                    handle.focus(window, cx);
6823                }
6824            });
6825        } else if hid_focus {
6826            // A tab switch retains focus on its tab list, not in an invisible panel.
6827            if let Some(handle) = tree
6828                .nodes()
6829                .filter(|node| {
6830                    node.attributes().get("role") == Some(&UiValue::String("tablist".to_owned()))
6831                        && tree.is_page_visible(node.id())
6832                })
6833                .max_by_key(|node| {
6834                    hidden_page.map_or(0, |page| {
6835                        let mut ancestor = tree.node(page).and_then(crate::RetainedNode::parent);
6836                        while let Some(scope) = ancestor {
6837                            if retained_within(tree, node.id(), scope) {
6838                                return retained_depth(tree, scope);
6839                            }
6840                            ancestor = tree.node(scope).and_then(crate::RetainedNode::parent);
6841                        }
6842                        0
6843                    })
6844                })
6845                .and_then(|node| self.focus_handles.get(&node.id()))
6846            {
6847                handle.focus(window, cx);
6848            }
6849        }
6850        self.visible_pages = visible;
6851        self.page_scopes = scopes;
6852    }
6853
6854    /// The nodes that get a focus handle.
6855    fn focusable_nodes(&self) -> BTreeSet<crate::NodeId> {
6856        self.lifecycle
6857            .retained()
6858            .host_nodes()
6859            .into_iter()
6860            // An overlay's handle is its panel's: the view owns it so the panel
6861            // holding focus is part of the focus path seen by `group_focus`.
6862            .filter(|node| {
6863                node.element_ref().is_some()
6864                    || node.focus_styled()
6865                    || !node.event_handlers("click").is_empty()
6866                    || node.attributes().get("tab_stop") == Some(&UiValue::Bool(true))
6867                    || node
6868                        .attributes()
6869                        .contains_key(crate::retained_page::PAGE_VISIBLE)
6870                    || node
6871                        .attributes()
6872                        .contains_key(crate::retained_page::NAVIGATION_DEPTH)
6873                    || node.attributes().get("role") == Some(&UiValue::String("heading".to_owned()))
6874                    || node
6875                        .primitive()
6876                        .is_some_and(|primitive| self.primitives.uses_primary_focus(primitive))
6877                    || node.kind() == crate::UiNodeKindTag::Overlay
6878                    || !node.event_handlers("focus_within_change").is_empty()
6879            })
6880            .map(crate::RetainedNode::id)
6881            .collect()
6882    }
6883
6884    /// The nodes that get a scroll handle.
6885    fn scrollable_nodes(&self) -> BTreeSet<crate::NodeId> {
6886        self.lifecycle
6887            .retained()
6888            .host_nodes()
6889            .into_iter()
6890            .filter(|node| node.scrollable())
6891            .map(crate::RetainedNode::id)
6892            .collect()
6893    }
6894
6895    /// In debug builds, a frame that kept the last frame's walks checks they
6896    /// still describe the committed tree.
6897    #[cfg(debug_assertions)]
6898    fn debug_assert_walks_current(&self) {
6899        debug_assert!(
6900            self.focus_handles
6901                .keys()
6902                .copied()
6903                .eq(self.focusable_nodes()),
6904            "focus handles fell behind the committed tree"
6905        );
6906        debug_assert!(
6907            self.scroll_handles
6908                .keys()
6909                .copied()
6910                .eq(self.scrollable_nodes()),
6911            "scroll handles fell behind the committed tree"
6912        );
6913    }
6914
6915    fn sync_focus_handles(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6916        self.sync_retained_page_focus(window, cx);
6917        let active = self.focusable_nodes();
6918        self.focus_handles.retain(|node, _| active.contains(node));
6919        for node in active {
6920            self.focus_handles
6921                .entry(node)
6922                .or_insert_with(|| cx.focus_handle());
6923        }
6924        self.sync_focus_within_listeners(window, cx);
6925        let scrollable = self.scrollable_nodes();
6926        self.scroll_handles
6927            .retain(|node, _| scrollable.contains(node));
6928        for node in scrollable {
6929            self.scroll_handles.entry(node).or_default();
6930        }
6931        let anchors = self
6932            .lifecycle
6933            .retained()
6934            .host_nodes()
6935            .into_iter()
6936            .filter(|node| node.element_ref().is_some())
6937            .filter_map(|node| {
6938                nearest_scroll_ancestor(self.lifecycle.retained(), node.id())
6939                    .map(|ancestor| (node.id(), ancestor))
6940            })
6941            .collect::<BTreeMap<_, _>>();
6942        self.scroll_anchors
6943            .retain(|node, _| anchors.contains_key(node));
6944        for (node, ancestor) in anchors {
6945            if let Some(handle) = self.scroll_handles.get(&ancestor) {
6946                self.scroll_anchors
6947                    .entry(node)
6948                    .or_insert_with(|| ScrollAnchor::for_handle(handle.clone()));
6949            }
6950        }
6951    }
6952
6953    fn process_element_commands(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6954        let commands = self
6955            .lifecycle
6956            .runtime()
6957            .borrow_mut()
6958            .take_window_element_commands(&self.window_id);
6959        let mut deferred = Vec::new();
6960        for command in commands {
6961            match command {
6962                crate::element_ref::ElementCommand::CopyText { text, .. } => {
6963                    cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
6964                }
6965                crate::element_ref::ElementCommand::ScrollCollectionBy { id, distance, .. } => {
6966                    self.lifecycle
6967                        .runtime()
6968                        .borrow()
6969                        .virtual_requests
6970                        .queue_scroll(
6971                            id,
6972                            crate::virtual_list::CollectionScrollCommand::By(distance),
6973                        );
6974                    cx.notify();
6975                }
6976                crate::element_ref::ElementCommand::ScrollCollectionToKey { id, item, .. } => {
6977                    self.lifecycle
6978                        .runtime()
6979                        .borrow()
6980                        .virtual_requests
6981                        .queue_scroll(id, crate::virtual_list::CollectionScrollCommand::Key(item));
6982                    cx.notify();
6983                }
6984                crate::element_ref::ElementCommand::ScrollCollection { id, end, .. } => {
6985                    self.lifecycle
6986                        .runtime()
6987                        .borrow()
6988                        .virtual_requests
6989                        .queue_scroll(
6990                            id,
6991                            if end {
6992                                crate::virtual_list::CollectionScrollCommand::End
6993                            } else {
6994                                crate::virtual_list::CollectionScrollCommand::Start
6995                            },
6996                        );
6997                    cx.notify();
6998                }
6999                crate::element_ref::ElementCommand::Focus { node, .. } => {
7000                    if !self.lifecycle.retained().is_page_visible(node) {
7001                        continue;
7002                    }
7003                    if let Some(handle) = self.focus_handles.get(&node) {
7004                        self.navigation_focus_epoch = self.navigation_focus_epoch.wrapping_add(1);
7005                        handle.focus(window, cx);
7006                    } else {
7007                        self.set_plain_failure(format!(
7008                            "retained node {node} is not focusable or has been unmounted"
7009                        ));
7010                    }
7011                }
7012                crate::element_ref::ElementCommand::ScrollTo { node, x, y, .. } => {
7013                    if let Some(handle) = self.scroll_handles.get(&node) {
7014                        handle.set_offset(gpui::point(pixel_from_f64(-x), pixel_from_f64(-y)));
7015                    } else {
7016                        self.set_plain_failure(format!(
7017                            "retained node {node} is not a scroll container or has been unmounted"
7018                        ));
7019                    }
7020                }
7021                crate::element_ref::ElementCommand::ScrollIntoView { node, .. } => {
7022                    let retained = self.lifecycle.retained();
7023                    let ancestor = nearest_scroll_ancestor(retained, node);
7024                    let handle = ancestor.and_then(|ancestor| self.scroll_handles.get(&ancestor));
7025                    // A direct child scrolls the minimal amount that shows it, in the next
7026                    // prepaint, which also finds a child laid out for the first time.
7027                    let child_index = ancestor.and_then(|ancestor| {
7028                        retained
7029                            .node(ancestor)?
7030                            .children()
7031                            .position(|link| link.node() == node)
7032                    });
7033                    if let (Some(handle), Some(index)) = (handle, child_index) {
7034                        handle.scroll_to_item(index);
7035                        cx.notify();
7036                    } else if let Some(anchor) = self.scroll_anchors.get(&node) {
7037                        anchor.scroll_to(window, cx);
7038                    } else if retained.node(node).is_none() {
7039                        // Unmounted before the request ran (the view moved on): a reveal is a
7040                        // request, not a command that must take effect.
7041                    } else if ancestor.is_some() {
7042                        // Mounted or ref'd in this transaction: the scroll handle and anchor
7043                        // exist after the next frame's sync.
7044                        deferred.push(command);
7045                    } else {
7046                        self.set_plain_failure(format!(
7047                            "retained node {node} has no scrollable ancestor"
7048                        ));
7049                    }
7050                }
7051            }
7052        }
7053        if !deferred.is_empty() {
7054            self.lifecycle
7055                .runtime()
7056                .borrow_mut()
7057                .requeue_element_commands(deferred);
7058            cx.notify();
7059        }
7060    }
7061
7062    fn retain_mounted_primitives(&mut self) {
7063        if !self.lifecycle.retained().is_empty()
7064            && let Err(error) = self.primitives.retain_tree(self.lifecycle.retained())
7065        {
7066            self.set_plain_failure(error.to_string());
7067        }
7068    }
7069
7070    fn sync_viewport_class(&mut self, window: &Window) {
7071        let width = self.content_bounds.map_or_else(
7072            || f64::from(window.viewport_size().width),
7073            |bounds| f64::from(bounds.size.width),
7074        );
7075        let needs_update = self
7076            .lifecycle
7077            .runtime()
7078            .borrow()
7079            .responsive
7080            .would_update_window(&self.window_id, width);
7081        match needs_update {
7082            Ok(false) => return,
7083            Err(error) => {
7084                self.set_plain_failure(error.to_string());
7085                return;
7086            }
7087            Ok(true) => {}
7088        }
7089        let result = self.run_script_transaction(|view| {
7090            let runtime = view.lifecycle.runtime();
7091            let changed = {
7092                let mut runtime = runtime.borrow_mut();
7093                let changed = runtime
7094                    .responsive
7095                    .update_window(&view.window_id, width)
7096                    .map_err(|error| error.to_string())?;
7097                if changed {
7098                    let invalidated = runtime
7099                        .environment_dependencies
7100                        .invalidate_viewport(&view.window_id);
7101                    runtime.mark_dirty(invalidated);
7102                }
7103                changed
7104            };
7105            if changed {
7106                let result = view.lifecycle.render_dirty(&mut view.engine);
7107                result.map_err(|error| view.lifecycle_failure(&error, None))?;
7108            }
7109            Ok(())
7110        });
7111        if let Err(error) = result {
7112            self.set_failure(error);
7113        }
7114    }
7115
7116    fn dispatch_key_binding(
7117        &mut self,
7118        action: &DispatchScriptAction,
7119        window: &mut Window,
7120        cx: &mut Context<Self>,
7121    ) {
7122        let result = ActionId::parse(&action.id).and_then(|id| {
7123            self.lifecycle
7124                .runtime()
7125                .borrow()
7126                .actions
7127                .dispatch(&id, UiValue::Null)
7128        });
7129        match result {
7130            Ok(invocation) => {
7131                if let Ok(mut runtime) = self.lifecycle.runtime().try_borrow_mut() {
7132                    runtime.traces.push(
7133                        crate::RuntimeTraceKind::Action,
7134                        self.lifecycle.root_path().to_string(),
7135                        format!("key binding {}", action.id),
7136                        None,
7137                        false,
7138                    );
7139                }
7140                // A Host key binding is user input.
7141                self.handle_node_event(
7142                    &invocation.callback,
7143                    invocation.payload,
7144                    None,
7145                    crate::InvocationOrigin::UserInput {
7146                        event: "action".to_owned(),
7147                    },
7148                    window,
7149                    cx,
7150                );
7151            }
7152            Err(error) => {
7153                self.set_plain_failure(error.to_string());
7154                cx.notify();
7155            }
7156        }
7157    }
7158
7159    fn copy_selected_text(&mut self, _: &CopySelectedText, _: &mut Window, cx: &mut Context<Self>) {
7160        if let Some(text) = self.text_selection.selected_text(self.lifecycle.retained()) {
7161            cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
7162            cx.stop_propagation();
7163        } else {
7164            cx.propagate();
7165        }
7166    }
7167
7168    fn invoke_pending_effects(&mut self) -> Result<bool, ScriptFailure> {
7169        let mut processed = 0usize;
7170        loop {
7171            let (actions, events) = {
7172                let runtime = self.lifecycle.runtime();
7173                let mut runtime = runtime.borrow_mut();
7174                runtime.drain_window_dispatch(self.lifecycle.root_path())
7175            };
7176            if actions.is_empty() && events.is_empty() {
7177                return Ok(processed > 0);
7178            }
7179            // Each runs with the origin it was queued under: the delivery,
7180            // timer or effect that queued it has returned by now.
7181            for action in actions {
7182                processed = processed.saturating_add(1);
7183                if processed > crate::effect::EFFECT_TRANSITION_CALLBACK_BUDGET {
7184                    self.lifecycle
7185                        .reject_semantic_dispatch_budget(&action.origin, action.owner.as_ref())
7186                        .map_err(|error| self.lifecycle_failure(&error, None))?;
7187                    return Err(ScriptFailure::plain(
7188                        "semantic event/action dispatch exceeded the 64-callback budget",
7189                    ));
7190                }
7191                let component = action.callback.component().cloned();
7192                let result = self
7193                    .lifecycle
7194                    .invoke_action_transactional(&self.engine, action);
7195                let _ =
7196                    result.map_err(|error| self.lifecycle_failure(&error, component.as_ref()))?;
7197            }
7198            for event in events {
7199                processed = processed.saturating_add(1);
7200                if processed > crate::effect::EFFECT_TRANSITION_CALLBACK_BUDGET {
7201                    self.lifecycle
7202                        .reject_semantic_dispatch_budget(&event.origin, event.owner.as_ref())
7203                        .map_err(|error| self.lifecycle_failure(&error, None))?;
7204                    return Err(ScriptFailure::plain(
7205                        "semantic event/action dispatch exceeded the 64-callback budget",
7206                    ));
7207                }
7208                let component = event.target.clone();
7209                let result = self
7210                    .lifecycle
7211                    .invoke_component_event_transactional(&self.engine, event);
7212                let _ = result.map_err(|error| self.lifecycle_failure(&error, Some(&component)))?;
7213            }
7214        }
7215    }
7216
7217    fn invoke_motion_timeline_callback(
7218        &mut self,
7219        event: crate::MotionTimelineEvent,
7220    ) -> Result<bool, ScriptFailure> {
7221        let Some(callback) = event.callback else {
7222            return Ok(false);
7223        };
7224        if callback.generation() != self.lifecycle.generation()
7225            || callback
7226                .component()
7227                .zip(callback.incarnation())
7228                .is_some_and(|(component, incarnation)| {
7229                    self.lifecycle
7230                        .runtime()
7231                        .borrow()
7232                        .component_incarnation(component)
7233                        != Some(incarnation)
7234                })
7235        {
7236            return Ok(false);
7237        }
7238        let component = callback.component().cloned();
7239        let previous_origin = self
7240            .lifecycle
7241            .runtime()
7242            .borrow_mut()
7243            .replace_origin(crate::InvocationOrigin::Effect);
7244        let payload = UiValue::Map(BTreeMap::from([
7245            (
7246                "name".to_owned(),
7247                UiValue::String(event.handle.name().to_owned()),
7248            ),
7249            (
7250                "kind".to_owned(),
7251                UiValue::String(
7252                    match event.kind {
7253                        crate::MotionTimelineEventKind::Complete => "complete",
7254                        crate::MotionTimelineEventKind::Cancel => "cancel",
7255                    }
7256                    .to_owned(),
7257                ),
7258            ),
7259        ]));
7260        let result = self
7261            .lifecycle
7262            .invoke_callback(&self.engine, &callback, payload);
7263        self.lifecycle
7264            .runtime()
7265            .borrow_mut()
7266            .replace_origin(previous_origin);
7267        let _ = result.map_err(|error| self.lifecycle_failure(&error, component.as_ref()))?;
7268        Ok(true)
7269    }
7270
7271    #[cfg(feature = "dev-reload")]
7272    fn inspector_element(
7273        &self,
7274        runtime: &Rc<RefCell<UiRuntimeState>>,
7275        theme: &ThemeVariant,
7276    ) -> Option<gpui::AnyElement> {
7277        (self.development && self.inspector_open).then(|| {
7278            let components = self.engine.component_exports().unwrap_or_default();
7279            let runtime = runtime.borrow();
7280            let snapshot = crate::InspectorSnapshot::capture_for_view(
7281                self.lifecycle.root(),
7282                &runtime,
7283                theme,
7284                &components,
7285                self.timings.clone(),
7286                Some(&self.view_id),
7287            );
7288            crate::devtools::inspector_element(&snapshot)
7289        })
7290    }
7291
7292    fn should_close(&mut self, cx: &mut Context<Self>) -> bool {
7293        if self.state.get() == ScriptViewState::Disposed {
7294            return true;
7295        }
7296        if self.state.get() == ScriptViewState::Suspended {
7297            self.release_view();
7298            return true;
7299        }
7300        let forced = self
7301            .native_windows
7302            .borrow_mut()
7303            .force_close
7304            .remove(&self.window_id);
7305        if forced {
7306            self.release_view();
7307            return true;
7308        }
7309        let handler = self
7310            .lifecycle
7311            .runtime()
7312            .borrow()
7313            .windows
7314            .close_handler(&self.window_id);
7315        let Some(handler) = handler else {
7316            self.release_view();
7317            return true;
7318        };
7319        let component = handler.component().cloned();
7320        // Closing a window is user input.
7321        let previous_origin = self.lifecycle.runtime().borrow_mut().replace_origin(
7322            crate::InvocationOrigin::UserInput {
7323                event: "window_close".to_owned(),
7324            },
7325        );
7326        let result = self.run_script_transaction(|view| {
7327            let result = view
7328                .lifecycle
7329                .invoke_callback(&view.engine, &handler, UiValue::Null);
7330            let _ = result.map_err(|error| view.lifecycle_failure(&error, component.as_ref()))?;
7331            view.invoke_pending_effects()?;
7332            let result = view.lifecycle.render_dirty(&mut view.engine);
7333            result.map_err(|error| view.lifecycle_failure(&error, None))?;
7334            Ok(())
7335        });
7336        self.lifecycle
7337            .runtime()
7338            .borrow_mut()
7339            .replace_origin(previous_origin);
7340        match result {
7341            Ok(()) => {
7342                self.process_window_commands(cx);
7343                cx.notify();
7344                false
7345            }
7346            Err(error) => {
7347                self.set_failure(error);
7348                self.release_view();
7349                true
7350            }
7351        }
7352    }
7353
7354    fn suspend_view(
7355        &mut self,
7356        window: &mut Window,
7357        cx: &mut Context<Self>,
7358    ) -> Result<bool, ScriptViewError> {
7359        let _signal_access = self.direct_signal_access_guard();
7360        if let Err(error) = self.primitives.suspend_mounted(cx) {
7361            let rollback = self.restore_native_active(cx).err();
7362            let message = native_lifecycle_error("suspend", &error, rollback.as_ref());
7363            if rollback.is_some() {
7364                self.quiesce_host_view(window, cx);
7365                let message = self.fault_native_lifecycle(message, cx);
7366                return Err(ScriptViewError::Suspend(message));
7367            }
7368            self.set_plain_failure(message.clone());
7369            return Err(ScriptViewError::Suspend(message));
7370        }
7371        let changed = match self.lifecycle.suspend(&mut self.engine) {
7372            Ok(changed) => changed,
7373            Err(error) => {
7374                let rollback = self.restore_native_active(cx).err();
7375                let rollback_failed = rollback.is_some();
7376                let message = rollback.as_ref().map_or_else(
7377                    || error.to_string(),
7378                    |rollback| format!("{error}; native rollback failed: {rollback}"),
7379                );
7380                if rollback_failed {
7381                    self.quiesce_host_view(window, cx);
7382                    let message = self.fault_native_lifecycle(message, cx);
7383                    return Err(ScriptViewError::Suspend(message));
7384                }
7385                self.set_plain_failure(message);
7386                return Err(error.into());
7387            }
7388        };
7389        if !changed {
7390            if let Err(error) = self.restore_native_active(cx) {
7391                let message = self.fault_native_lifecycle(error.to_string(), cx);
7392                return Err(ScriptViewError::Suspend(message));
7393            }
7394            return Ok(false);
7395        }
7396        self.quiesce_host_view(window, cx);
7397        self.navigation_focus_epoch = self.navigation_focus_epoch.wrapping_add(1);
7398        self.state.set(ScriptViewState::Suspended);
7399        Ok(true)
7400    }
7401
7402    fn quiesce_host_view(&self, window: &mut Window, cx: &mut App) {
7403        let _signal_access = self.direct_signal_access_guard();
7404        self.host
7405            .quiesce_view(&self.view_id, &self.host_focus, window, cx);
7406    }
7407
7408    fn cancel_view_interaction(&self, window: &mut Window, cx: &mut App) -> bool {
7409        let _signal_access = self.direct_signal_access_guard();
7410        self.host
7411            .interactions()
7412            .cancel_view(&self.view_id, window, cx)
7413    }
7414
7415    fn active_interaction_contracts(&self) -> Result<InteractionContractSnapshots, ScriptFailure> {
7416        let owners = self.host.interactions().active_owners(&self.view_id);
7417        if owners.is_empty() {
7418            return Ok(BTreeMap::new());
7419        }
7420        let runtime = self.lifecycle.runtime();
7421        let runtime = runtime
7422            .try_borrow()
7423            .map_err(|_| ScriptFailure::plain("UI runtime state is already borrowed"))?;
7424        let direction = self.interaction_text_direction(&runtime);
7425        Ok(owners
7426            .into_iter()
7427            .map(|owner| {
7428                let contract = crate::interaction::InteractionContract::capture(
7429                    &owner,
7430                    self.lifecycle.retained(),
7431                    &runtime,
7432                    self.lifecycle.generation(),
7433                    direction,
7434                );
7435                (owner, contract)
7436            })
7437            .collect())
7438    }
7439
7440    fn invalidate_changed_interaction_contracts(&mut self, previous: InteractionContractSnapshots) {
7441        if previous.is_empty() {
7442            return;
7443        }
7444        let runtime = self.lifecycle.runtime();
7445        let runtime = runtime.borrow();
7446        let direction = self.interaction_text_direction(&runtime);
7447        for (owner, previous) in previous {
7448            let current = crate::interaction::InteractionContract::capture(
7449                &owner,
7450                self.lifecycle.retained(),
7451                &runtime,
7452                self.lifecycle.generation(),
7453                direction,
7454            );
7455            if previous != current {
7456                self.pending_interaction_cancels.insert(owner);
7457            }
7458        }
7459    }
7460
7461    fn interaction_text_direction(&self, runtime: &UiRuntimeState) -> TextDirection {
7462        runtime
7463            .locale
7464            .as_ref()
7465            .and_then(|locale| {
7466                locale
7467                    .direction(Some(&self.window_id), Some(self.lifecycle.root_path()))
7468                    .ok()
7469            })
7470            .unwrap_or(TextDirection::LeftToRight)
7471    }
7472
7473    fn consume_pending_interaction_cancel(&mut self, window: &mut Window, cx: &mut App) {
7474        let owners = std::mem::take(&mut self.pending_interaction_cancels);
7475        if !owners.is_empty() {
7476            let _signal_access = self.direct_signal_access_guard();
7477            let interactions = self.host.interactions();
7478            for owner in owners {
7479                interactions.cancel_owner(&owner, window, cx);
7480            }
7481        }
7482    }
7483
7484    fn direct_signal_access_guard(&self) -> DirectSignalAccessGuard {
7485        let previous = self.direct_signal_access.replace(true);
7486        DirectSignalAccessGuard {
7487            flag: Rc::clone(&self.direct_signal_access),
7488            previous,
7489        }
7490    }
7491
7492    #[allow(clippy::too_many_lines)]
7493    fn resume_view(&mut self, cx: &mut Context<Self>) -> Result<bool, ScriptViewError> {
7494        if self.state.get() == ScriptViewState::Active {
7495            return Ok(false);
7496        }
7497        let _signal_access = self.direct_signal_access_guard();
7498        #[cfg(feature = "dev-reload")]
7499        let pending_reload_error = self.apply_pending_reload_on_resume();
7500        #[cfg(not(feature = "dev-reload"))]
7501        let pending_reload_error: Option<ScriptFailure> = None;
7502        self.collect_suspended_deliveries()?;
7503        let program = self.factory.program();
7504        let migrating = program.compiled.generation() != self.lifecycle.generation();
7505        let previous_exports = migrating
7506            .then(|| self.engine.component_exports())
7507            .transpose()
7508            .map_err(|error| ScriptViewError::Resume(error.to_string()))?;
7509        let previous_renderers = migrating
7510            .then(|| self.engine.component_renderer_snapshot())
7511            .transpose()
7512            .map_err(|error| ScriptViewError::Resume(error.to_string()))?;
7513        if migrating {
7514            self.engine
7515                .restore_component_exports(program.component_exports.clone())
7516                .map_err(|error| ScriptViewError::Resume(error.to_string()))?;
7517            if let Err(error) = self
7518                .engine
7519                .restore_component_renderers(program.component_renderers.clone())
7520            {
7521                if let Some(previous_exports) = previous_exports.clone() {
7522                    let _ = self.engine.restore_component_exports(previous_exports);
7523                }
7524                return Err(ScriptViewError::Resume(error.to_string()));
7525            }
7526        }
7527        self.prepare_native_resume(cx)?;
7528        let result = self.run_script_transaction(|view| {
7529            if migrating {
7530                view.lifecycle
7531                    .runtime()
7532                    .borrow_mut()
7533                    .discard_component_async_before_generation(
7534                        view.lifecycle.root_path(),
7535                        program.compiled.generation(),
7536                    );
7537                let result = view.lifecycle.resume_reload(
7538                    &mut view.engine,
7539                    program.compiled,
7540                    &program.state_schema,
7541                );
7542                result
7543                    .map(|_| true)
7544                    .map_err(|error| view.lifecycle_failure(&error, None))?;
7545                return Ok(true);
7546            }
7547            let pending = view
7548                .lifecycle
7549                .runtime()
7550                .borrow_mut()
7551                .take_window_async(&view.window_id, view.lifecycle.root_path());
7552            for delivery in pending {
7553                let component = delivery
7554                    .callback
7555                    .component()
7556                    .cloned()
7557                    .or_else(|| delivery.scope.component().cloned());
7558                let result = view.lifecycle.invoke_async_delivery(&view.engine, delivery);
7559                let _ =
7560                    result.map_err(|error| view.lifecycle_failure(&error, component.as_ref()))?;
7561            }
7562            view.invoke_pending_effects()?;
7563            let result = view.lifecycle.resume(&mut view.engine);
7564            result.map_err(|error| view.lifecycle_failure(&error, None))
7565        });
7566        match result {
7567            Ok(changed) => {
7568                if let Err(error) = self.primitives.commit_resume_mounted(cx) {
7569                    let rollback = self.primitives.suspend_mounted(cx).err();
7570                    let message =
7571                        native_lifecycle_error("commit resume", &error, rollback.as_ref());
7572                    let message = self.fault_native_lifecycle(message, cx);
7573                    return Err(ScriptViewError::Resume(message));
7574                }
7575                self.state.set(ScriptViewState::Active);
7576                self.activity_wake.notify();
7577                if let Some(error) = pending_reload_error {
7578                    self.set_failure(error);
7579                } else if migrating {
7580                    // The reload deferred while suspended rendered.
7581                    self.clear_failure();
7582                }
7583                self.collect_timings();
7584                cx.notify();
7585                Ok(changed)
7586            }
7587            Err(error) => {
7588                let native_rollback = self.primitives.suspend_mounted(cx).err();
7589                if let Some(previous_exports) = previous_exports {
7590                    let _ = self.engine.restore_component_exports(previous_exports);
7591                }
7592                if let Some(previous_renderers) = previous_renderers {
7593                    let _ = self.engine.restore_component_renderers(previous_renderers);
7594                }
7595                let public_error = error.clone().into_view_error();
7596                if let Some(native_rollback) = native_rollback {
7597                    let message = format!(
7598                        "{public_error}; native suspend compensation failed: {native_rollback}"
7599                    );
7600                    let message = self.fault_native_lifecycle(message, cx);
7601                    Err(ScriptViewError::Resume(message))
7602                } else {
7603                    self.set_failure(error);
7604                    Err(public_error)
7605                }
7606            }
7607        }
7608    }
7609
7610    fn prepare_native_resume(&mut self, cx: &mut Context<Self>) -> Result<(), ScriptViewError> {
7611        if let Err(error) = self.primitives.resume_mounted(cx) {
7612            let rollback = self.primitives.suspend_mounted(cx).err();
7613            let message = native_lifecycle_error("resume", &error, rollback.as_ref());
7614            if rollback.is_some() {
7615                let message = self.fault_native_lifecycle(message, cx);
7616                return Err(ScriptViewError::Resume(message));
7617            }
7618            self.set_plain_failure(message.clone());
7619            return Err(ScriptViewError::Resume(message));
7620        }
7621        Ok(())
7622    }
7623
7624    fn restore_native_active(
7625        &mut self,
7626        cx: &mut Context<Self>,
7627    ) -> Result<(), crate::PrimitiveError> {
7628        self.primitives.resume_mounted(cx)?;
7629        self.primitives.commit_resume_mounted(cx)
7630    }
7631
7632    fn fault_native_lifecycle(&mut self, message: String, cx: &mut Context<Self>) -> String {
7633        self.set_plain_failure(message.clone());
7634        self.release_view();
7635        cx.notify();
7636        message
7637    }
7638
7639    fn collect_suspended_deliveries(&mut self) -> Result<(), ScriptViewError> {
7640        let generation = self.lifecycle.generation();
7641        let runtime = self.lifecycle.runtime();
7642        let mut runtime = runtime.borrow_mut();
7643        let capacity = runtime.suspended_delivery_capacity_remaining();
7644        let mut deliveries = runtime.tasks.drain_up_to(generation, capacity);
7645        let remaining = capacity.saturating_sub(deliveries.len());
7646        deliveries.extend(runtime.subscriptions.drain_up_to(generation, remaining));
7647        runtime.trace_subscription_closures();
7648        runtime.queue_suspended_async(deliveries)?;
7649        Ok(())
7650    }
7651
7652    fn release_view(&mut self) {
7653        if self.state.get() == ScriptViewState::Disposed {
7654            return;
7655        }
7656        self.presentation_diagnostics.clear();
7657        self.window_appearance.take();
7658        if let Err(error) = self.primitives.retain_mounted(&BTreeSet::new()) {
7659            self.set_plain_failure(error.to_string());
7660        }
7661        let _ = self.lifecycle.dispose(&mut self.engine);
7662        let root = self.lifecycle.root_path().clone();
7663        let _ = self
7664            .lifecycle
7665            .runtime()
7666            .borrow_mut()
7667            .release_window(&self.window_id, &root);
7668        self.lifecycle
7669            .runtime()
7670            .borrow_mut()
7671            .remove_presentation(&self.view_id);
7672        let mut native = self.native_windows.borrow_mut();
7673        if native
7674            .handles
7675            .get(&self.window_id)
7676            .is_some_and(|registration| registration.authority.lease.ptr_eq(&self.mount_lease))
7677        {
7678            native.handles.remove(&self.window_id);
7679            native.force_close.remove(&self.window_id);
7680        }
7681        drop(native);
7682        self.host.unregister_view(&self.view_id, &self.mount_lease);
7683        self.state.set(ScriptViewState::Disposed);
7684        self.activity_wake.notify();
7685    }
7686
7687    fn process_window_commands(&mut self, cx: &mut Context<Self>) {
7688        let commands = self
7689            .lifecycle
7690            .runtime()
7691            .borrow_mut()
7692            .windows
7693            .drain_commands();
7694        let runtime = self.lifecycle.runtime();
7695        for queued in commands {
7696            if !window_command_is_current(&queued, &runtime.borrow().windows, cx) {
7697                runtime.borrow_mut().windows.cancel_open(&queued);
7698                continue;
7699            }
7700            let closing = matches!(queued.command(), WindowCommand::Close(_));
7701            let result = match queued.command().clone() {
7702                WindowCommand::Open(spec) => {
7703                    open_secondary_window(&spec, &self.factory, &self.native_windows, cx)
7704                }
7705                WindowCommand::Focus(id) | WindowCommand::Close(id) => {
7706                    let registration = self
7707                        .native_windows
7708                        .borrow()
7709                        .handles
7710                        .get(&id)
7711                        .cloned()
7712                        .filter(|registration| {
7713                            registration.authority.is_current(cx)
7714                                && queued.target_binding().is_some_and(|target| {
7715                                    target.window == registration.handle.window_id()
7716                                        && target.lease.ptr_eq(&registration.authority.lease)
7717                                })
7718                        });
7719                    registration.map_or_else(
7720                        || {
7721                            Err(ScriptFailure::plain(format!(
7722                                "native window `{id}` is unavailable"
7723                            )))
7724                        },
7725                        |registration| {
7726                            let handle = registration.handle;
7727                            let target_authority = registration.authority;
7728                            // A script commonly focuses/closes from an event
7729                            // dispatched by the same window. Updating that window
7730                            // recursively fails in GPUI with `window not found`, so
7731                            // apply it after the current entity update unwinds.
7732                            let view = cx.weak_entity();
7733                            let native_windows = Rc::clone(&self.native_windows);
7734                            let runtime = Rc::clone(&runtime);
7735                            let close_id = id.clone();
7736                            cx.defer(move |cx| {
7737                                // Authority may be revoked between queueing and
7738                                // execution. Do not let a disposed owner operate
7739                                // on its replacement or leave a stale close bypass.
7740                                if !window_command_is_current(
7741                                    &queued,
7742                                    &runtime.borrow().windows,
7743                                    cx,
7744                                ) || !target_authority.is_current(cx)
7745                                    || native_windows.borrow().handles.get(&close_id).is_none_or(
7746                                        |current| current.handle.window_id() != handle.window_id(),
7747                                    )
7748                                {
7749                                    return;
7750                                }
7751                                if closing {
7752                                    native_windows
7753                                        .borrow_mut()
7754                                        .force_close
7755                                        .insert(close_id.clone());
7756                                }
7757                                if let Err(error) = handle.update(cx, |_, window, _| {
7758                                    if closing {
7759                                        window.remove_window();
7760                                    } else {
7761                                        window.activate_window();
7762                                    }
7763                                }) {
7764                                    native_windows.borrow_mut().force_close.remove(&close_id);
7765                                    let message = error.to_string();
7766                                    let _ = view.update(cx, |view, cx| {
7767                                        view.set_plain_failure(message);
7768                                        cx.notify();
7769                                    });
7770                                }
7771                            });
7772                            Ok(())
7773                        },
7774                    )
7775                }
7776            };
7777            if let Err(error) = result {
7778                self.set_failure(error);
7779            }
7780        }
7781    }
7782
7783    #[cfg(feature = "dev-reload")]
7784    fn toggle_inspector(&mut self, _: &ToggleInspector, _: &mut Window, cx: &mut Context<Self>) {
7785        if self.development {
7786            self.inspector_open = !self.inspector_open;
7787            cx.notify();
7788        }
7789    }
7790
7791    fn handle_node_event(
7792        &mut self,
7793        callback: &ScriptCallback,
7794        payload: UiValue,
7795        event_target: Option<crate::GeometryBounds>,
7796        origin: crate::InvocationOrigin,
7797        window: &mut Window,
7798        cx: &mut Context<Self>,
7799    ) -> crate::EventResponse {
7800        if self.state.get() != ScriptViewState::Active {
7801            return crate::EventResponse::new().stop();
7802        }
7803        if let Ok(mut runtime) = self.lifecycle.runtime().try_borrow_mut() {
7804            runtime.traces.push(
7805                crate::RuntimeTraceKind::Event,
7806                "/App[root]",
7807                format!("callback {}", callback.name()),
7808                None,
7809                true,
7810            );
7811        }
7812        let previous_origin = self.lifecycle.runtime().borrow_mut().replace_origin(origin);
7813        let callback_result = self.run_script_transaction(|view| {
7814            let result = view.lifecycle.invoke_callback_with_event_target(
7815                &view.engine,
7816                callback,
7817                payload,
7818                event_target,
7819            );
7820            let value =
7821                result.map_err(|error| view.lifecycle_failure(&error, callback.component()))?;
7822            view.invoke_pending_effects()?;
7823            let result = view.lifecycle.render_dirty(&mut view.engine);
7824            let rendered = result.map_err(|error| view.lifecycle_failure(&error, None))?;
7825            Ok((value, rendered))
7826        });
7827        self.lifecycle
7828            .runtime()
7829            .borrow_mut()
7830            .replace_origin(previous_origin);
7831        let response = callback_result.as_ref().map_or_else(
7832            |_| crate::EventResponse::new().stop(),
7833            |(value, _)| event_response_from_dynamic(value),
7834        );
7835        let succeeded = callback_result.is_ok();
7836        if let Err(error) = callback_result {
7837            self.set_failure(error);
7838        }
7839        self.process_window_commands(cx);
7840        self.process_element_commands(window, cx);
7841        self.consume_pending_interaction_cancel(window, cx);
7842        self.collect_timings();
7843        cx.notify();
7844        if succeeded {
7845            response
7846        } else {
7847            crate::EventResponse::new().stop()
7848        }
7849    }
7850
7851    fn handle_native_event(
7852        &mut self,
7853        handler: &crate::NativeHandlerRef,
7854        event: String,
7855        payload: UiValue,
7856        event_target: Option<crate::GeometryBounds>,
7857        window: &mut Window,
7858        cx: &mut Context<Self>,
7859    ) -> crate::EventResponse {
7860        if self.state.get() != ScriptViewState::Active {
7861            return crate::EventResponse::new().stop();
7862        }
7863        let registry = self.engine.native_handler_registry();
7864        let result = self.run_script_transaction(|view| {
7865            let response = {
7866                let runtime = view.lifecycle.runtime();
7867                let mut runtime = runtime
7868                    .try_borrow_mut()
7869                    .map_err(|_| "UI runtime state is already borrowed".to_owned())?;
7870                registry
7871                    .invoke(
7872                        handler,
7873                        crate::NativeEvent {
7874                            name: event,
7875                            payload,
7876                            target: event_target,
7877                        },
7878                        &mut runtime,
7879                        window,
7880                        cx,
7881                    )
7882                    .map_err(|error| error.to_string())?
7883            };
7884            view.invoke_pending_effects()?;
7885            let result = view.lifecycle.render_dirty(&mut view.engine);
7886            let rendered = result.map_err(|error| view.lifecycle_failure(&error, None))?;
7887            Ok((response, rendered))
7888        });
7889        match result {
7890            Ok((response, _)) => {
7891                self.process_window_commands(cx);
7892                self.process_element_commands(window, cx);
7893                self.consume_pending_interaction_cancel(window, cx);
7894                self.collect_timings();
7895                cx.notify();
7896                response
7897            }
7898            Err(error) => {
7899                self.set_failure(error);
7900                cx.notify();
7901                crate::EventResponse::new().stop()
7902            }
7903        }
7904    }
7905
7906    fn begin_script_transaction(&self) -> Result<ScriptViewTransaction, String> {
7907        let runtime = self
7908            .lifecycle
7909            .runtime()
7910            .try_borrow_mut()
7911            .map_err(|_| "UI runtime state is already borrowed".to_owned())?
7912            .begin_transaction()
7913            .map_err(|error| error.to_string())?;
7914        Ok(ScriptViewTransaction {
7915            runtime,
7916            engine: self.engine.execution_checkpoint(),
7917            lifecycle: self.lifecycle.execution_checkpoint(),
7918        })
7919    }
7920
7921    fn rollback_script_transaction(
7922        &mut self,
7923        transaction: ScriptViewTransaction,
7924    ) -> Result<(), String> {
7925        let runtime = self.lifecycle.runtime();
7926        let runtime_result = match runtime.try_borrow_mut() {
7927            Ok(mut runtime) => runtime
7928                .restore(transaction.runtime)
7929                .map_err(|error| error.to_string()),
7930            Err(_) => Err("UI runtime state is already borrowed".to_owned()),
7931        };
7932        self.engine.restore_execution_checkpoint(transaction.engine);
7933        self.lifecycle
7934            .restore_execution_checkpoint(transaction.lifecycle);
7935        runtime_result
7936    }
7937
7938    fn run_script_transaction<T>(
7939        &mut self,
7940        operation: impl FnOnce(&mut Self) -> Result<T, ScriptFailure>,
7941    ) -> Result<T, ScriptFailure> {
7942        let interaction_contracts = self.active_interaction_contracts()?;
7943        let transaction = self
7944            .begin_script_transaction()
7945            .map_err(ScriptFailure::from)?;
7946        match operation(self) {
7947            Ok(value) => {
7948                let runtime = self.lifecycle.runtime();
7949                let commit = match runtime.try_borrow_mut() {
7950                    Ok(mut runtime) => runtime
7951                        .commit_transaction()
7952                        .map_err(|error| error.to_string()),
7953                    Err(_) => Err("UI runtime state is already borrowed".to_owned()),
7954                };
7955                match commit {
7956                    Ok(()) => {
7957                        // Only a successful commit can invalidate an active
7958                        // owner. Keep earlier successful batch invalidations
7959                        // even if a later delivery rolls back.
7960                        self.invalidate_changed_interaction_contracts(interaction_contracts);
7961                        Ok(value)
7962                    }
7963                    Err(error) => {
7964                        let rollback = self.rollback_script_transaction(transaction);
7965                        Err(ScriptFailure::plain(rollback.map_or_else(
7966                            |rollback| {
7967                                format!(
7968                                    "transaction commit failed: {error}; rollback also failed: {rollback}"
7969                                )
7970                            },
7971                            |()| format!("transaction commit failed: {error}"),
7972                        )))
7973                    }
7974                }
7975            }
7976            Err(error) => {
7977                let rollback = self.rollback_script_transaction(transaction);
7978                match rollback {
7979                    Ok(()) => Err(error),
7980                    Err(rollback) => Err(error
7981                        .append_context(format!("transaction rollback also failed: {rollback}"))),
7982                }
7983            }
7984        }
7985    }
7986
7987    fn collect_timings(&mut self) {
7988        self.timings.extend(self.engine.take_timings());
7989        if self.timings.len() > 200 {
7990            self.timings.drain(0..self.timings.len() - 200);
7991        }
7992    }
7993
7994    #[allow(clippy::too_many_lines)]
7995    fn poll_async(&mut self, cx: &mut Context<Self>) {
7996        if self.state.get() == ScriptViewState::Suspended {
7997            if let Err(error) = self.collect_suspended_deliveries() {
7998                self.set_plain_failure(error.to_string());
7999                cx.notify();
8000            }
8001            return;
8002        }
8003        if self.state.get() == ScriptViewState::Disposed {
8004            return;
8005        }
8006        let window = self.host.native_window();
8007        for extension in self.factory.extensions.iter() {
8008            extension.poll(window, cx);
8009        }
8010        self.report_presentation_diagnostics(cx);
8011        self.process_window_commands(cx);
8012        self.sync_program();
8013        let generation = self.lifecycle.generation();
8014        let runtime = self.lifecycle.runtime();
8015        let root = self.lifecycle.root_path().clone();
8016        let (deliveries, dirty, pending_dispatch, virtual_requests, repaint) = {
8017            let mut runtime = runtime.borrow_mut();
8018            runtime.flush_geometry_dependencies();
8019            let _ = runtime.assets.retain_decode_generation(generation);
8020            let now = runtime.clock.now();
8021            let mut deliveries = runtime.tasks.drain(generation);
8022            deliveries.extend(runtime.subscriptions.drain(generation));
8023            deliveries.extend(runtime.timers.drain(now, generation));
8024            runtime.trace_subscription_closures();
8025            if let Ok(asset_deliveries) = runtime.assets.drain_image_decodes(generation) {
8026                deliveries.extend(asset_deliveries);
8027            }
8028            runtime.queue_async(deliveries);
8029            let deliveries = runtime.take_window_async(&self.window_id, &root);
8030            (
8031                deliveries,
8032                runtime.has_window_dirty(&root),
8033                runtime.has_window_pending_dispatch(&root),
8034                runtime.has_virtual_requests(),
8035                runtime.take_window_repaint(&self.window_id),
8036            )
8037        };
8038        let has_script_work =
8039            !deliveries.is_empty() || dirty || pending_dispatch || virtual_requests;
8040        if self.motion_waits_for_clock
8041            && self.last_motion_sample != Some(runtime.borrow().clock.now())
8042        {
8043            self.motion_waits_for_clock = false;
8044            cx.notify();
8045        }
8046        if !has_script_work && !repaint {
8047            return;
8048        }
8049
8050        let (delivery_changed, delivery_error) = self.deliver_async_batch(deliveries);
8051        let result = if dirty || pending_dispatch || virtual_requests {
8052            let started = Instant::now();
8053            let result = self.run_script_transaction(|view| {
8054                let mut changed = view.invoke_pending_effects()?;
8055                let result = view.lifecycle.realize_virtual_requests(&mut view.engine);
8056                changed |= result.map_err(|error| view.lifecycle_failure(&error, None))?;
8057                let result = view.lifecycle.render_dirty(&mut view.engine);
8058                changed |= result.map_err(|error| view.lifecycle_failure(&error, None))?;
8059                Ok(changed || delivery_changed)
8060            });
8061            self.render_statistics.polls += 1;
8062            self.render_statistics.poll_time += started.elapsed();
8063            result
8064        } else {
8065            Ok(delivery_changed)
8066        };
8067        let result = match (result, delivery_error) {
8068            (Ok(_), Some(error)) => Err(error),
8069            (result, _) => result,
8070        };
8071        let notify = match result {
8072            Ok(changed) => {
8073                self.process_window_commands(cx);
8074                changed || repaint
8075            }
8076            Err(error) => {
8077                self.set_failure(error);
8078                true
8079            }
8080        };
8081        self.collect_timings();
8082        if notify {
8083            cx.notify();
8084        }
8085    }
8086
8087    fn deliver_async_batch(
8088        &mut self,
8089        deliveries: Vec<crate::AsyncDelivery>,
8090    ) -> (bool, Option<ScriptFailure>) {
8091        let mut changed = false;
8092        let mut first_error = None;
8093        for delivery in deliveries {
8094            let scope = format!("{:?}", delivery.scope);
8095            let component = delivery
8096                .callback
8097                .component()
8098                .cloned()
8099                .or_else(|| delivery.scope.component().cloned());
8100            let result = self.run_script_transaction(|view| {
8101                let mut delivery_changed = view.invoke_pending_effects()?;
8102                let result = view.lifecycle.invoke_async_delivery(&view.engine, delivery);
8103                let _ =
8104                    result.map_err(|error| view.lifecycle_failure(&error, component.as_ref()))?;
8105                delivery_changed |= view.invoke_pending_effects()?;
8106                let result = view.lifecycle.render_dirty(&mut view.engine);
8107                let rendered = result.map_err(|error| view.lifecycle_failure(&error, None))?;
8108                delivery_changed |= rendered;
8109                Ok(delivery_changed)
8110            });
8111            match result {
8112                Ok(delivery_changed) => {
8113                    changed |= delivery_changed;
8114                }
8115                Err(error) => {
8116                    self.lifecycle.runtime().borrow_mut().traces.push(
8117                        crate::RuntimeTraceKind::Task,
8118                        scope,
8119                        format!("delivery failed: {}", error.message),
8120                        None,
8121                        false,
8122                    );
8123                    first_error.get_or_insert(error);
8124                }
8125            }
8126        }
8127        (changed, first_error)
8128    }
8129
8130    fn sync_program(&mut self) {
8131        let program = self.factory.program();
8132        if program.compiled.generation() == self.lifecycle.generation() {
8133            return;
8134        }
8135        let interaction_contracts = match self.active_interaction_contracts() {
8136            Ok(contracts) => contracts,
8137            Err(error) => {
8138                self.set_failure(error);
8139                return;
8140            }
8141        };
8142        let previous_exports = match self.engine.component_exports() {
8143            Ok(exports) => exports,
8144            Err(error) => {
8145                self.set_plain_failure(error.to_string());
8146                return;
8147            }
8148        };
8149        let previous_renderers = match self.engine.component_renderer_snapshot() {
8150            Ok(renderers) => renderers,
8151            Err(error) => {
8152                self.set_plain_failure(error.to_string());
8153                return;
8154            }
8155        };
8156        if let Err(error) = self
8157            .engine
8158            .restore_component_exports(program.component_exports.clone())
8159        {
8160            self.set_plain_failure(error.to_string());
8161            return;
8162        }
8163        if let Err(error) = self
8164            .engine
8165            .restore_component_renderers(program.component_renderers.clone())
8166        {
8167            self.set_plain_failure(error.to_string());
8168            let _ = self.engine.restore_component_exports(previous_exports);
8169            return;
8170        }
8171        if let Err(error) =
8172            self.lifecycle
8173                .reload(&mut self.engine, program.compiled, &program.state_schema)
8174        {
8175            let mut failure = self.lifecycle_failure(&error, None);
8176            let rollback_exports = self.engine.restore_component_exports(previous_exports);
8177            let rollback_renderers = self.engine.restore_component_renderers(previous_renderers);
8178            if let Some(rollback) = rollback_exports.err().or_else(|| rollback_renderers.err()) {
8179                failure = failure.append_context(format!("rollback failed: {rollback}"));
8180            }
8181            self.set_failure(failure);
8182        } else {
8183            self.invalidate_changed_interaction_contracts(interaction_contracts);
8184        }
8185    }
8186
8187    #[cfg(feature = "dev-reload")]
8188    fn poll_reload(&mut self, cx: &mut Context<Self>) {
8189        let Some(watcher) = &self.watcher else {
8190            return;
8191        };
8192        let batch = match watcher.poll() {
8193            Ok(batch) => batch,
8194            Err(error) => {
8195                self.set_plain_failure(error.to_string());
8196                cx.notify();
8197                return;
8198            }
8199        };
8200        if batch.paths.is_empty() {
8201            return;
8202        }
8203        // A rejected batch is tried again with the next edit, so fixing one file
8204        // also applies the other files of the batch that failed.
8205        let mut paths = batch.paths;
8206        paths.append(&mut self.failed_reload_paths);
8207        if self.state.get() == ScriptViewState::Suspended {
8208            self.pending_reload_paths.extend(paths);
8209            return;
8210        }
8211        let result = self.reload_changed_paths(&paths);
8212        match result {
8213            Ok(()) => self.clear_failure(),
8214            Err(error) => {
8215                self.failed_reload_paths = paths;
8216                self.set_failure(error);
8217            }
8218        }
8219        self.collect_timings();
8220        cx.notify();
8221    }
8222
8223    #[cfg(feature = "dev-reload")]
8224    fn apply_pending_reload_on_resume(&mut self) -> Option<ScriptFailure> {
8225        let paths = std::mem::take(&mut self.pending_reload_paths);
8226        if paths.is_empty() {
8227            return None;
8228        }
8229        // A broken edit does not strand the retained view. Resume keeps using
8230        // the last successfully compiled program and exposes the candidate
8231        // error through the normal development error banner.
8232        self.reload_changed_paths(&paths).err()
8233    }
8234
8235    #[cfg(feature = "dev-reload")]
8236    fn reload_changed_paths(&mut self, paths: &BTreeSet<PathBuf>) -> Result<(), ScriptFailure> {
8237        let theme_path = self.theme_path.canonicalize().ok();
8238        let style_path = self.style_path.canonicalize().ok();
8239        let themes_root = self.ui_root.join("themes").canonicalize().ok();
8240        let tokens_path = self.ui_root.join(TOKEN_BASE_FILE).canonicalize().ok();
8241        let theme_changed = tokens_path
8242            .as_ref()
8243            .is_some_and(|tokens| paths.contains(tokens))
8244            || theme_path
8245                .as_ref()
8246                .is_some_and(|theme| paths.contains(theme))
8247            || themes_root
8248                .as_ref()
8249                .is_some_and(|themes_root| paths.iter().any(|path| path.starts_with(themes_root)));
8250        let style_changed = style_path
8251            .as_ref()
8252            .is_some_and(|styles| paths.contains(styles))
8253            || paths.iter().any(|path| path.ends_with(&self.style_path));
8254        let locale_root = self.ui_root.join("locales").canonicalize().ok();
8255        let locale_changed = locale_root
8256            .as_ref()
8257            .is_some_and(|locale_root| paths.iter().any(|path| path.starts_with(locale_root)));
8258        let assets_root = self.ui_root.join("assets").canonicalize().ok();
8259        let assets_changed = assets_root
8260            .as_ref()
8261            .is_some_and(|assets_root| paths.iter().any(|path| path.starts_with(assets_root)));
8262        let manifest_path = self.ui_root.join("app.toml").canonicalize().ok();
8263        let manifest_changed = manifest_path
8264            .as_ref()
8265            .is_some_and(|manifest| paths.contains(manifest));
8266        let script_changed = paths.iter().any(|path| {
8267            path.extension().and_then(|extension| extension.to_str()) == Some("rhai")
8268                && Some(path) != theme_path.as_ref()
8269                && Some(path) != tokens_path.as_ref()
8270                && Some(path) != style_path.as_ref()
8271                && !path.ends_with(&self.style_path)
8272                && !locale_root
8273                    .as_ref()
8274                    .is_some_and(|locale_root| path.starts_with(locale_root))
8275                && !themes_root
8276                    .as_ref()
8277                    .is_some_and(|themes_root| path.starts_with(themes_root))
8278        });
8279
8280        // A theme edit is a candidate until it passes the components' token
8281        // requirements, together with any scripts edited in the same batch.
8282        let theme = if theme_changed {
8283            Some(self.theme_candidate().map_err(ScriptFailure::from)?)
8284        } else {
8285            None
8286        };
8287        if script_changed {
8288            self.reload_scripts(paths, theme.as_ref().map(|candidate| &candidate.themes))
8289        } else {
8290            Ok(())
8291        }
8292        .and_then(|()| {
8293            let Some(candidate) = theme else {
8294                return Ok(());
8295            };
8296            validate_component_tokens(&candidate.themes, &self.factory.program().component_exports)
8297                .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8298            self.commit_theme(candidate);
8299            Ok(())
8300        })
8301        .and_then(|()| {
8302            if style_changed {
8303                self.reload_component_styles()
8304            } else {
8305                Ok(())
8306            }
8307        })
8308        .and_then(|()| {
8309            if locale_changed {
8310                self.reload_locales().map_err(ScriptFailure::from)
8311            } else {
8312                Ok(())
8313            }
8314        })
8315        .and_then(|()| {
8316            if assets_changed {
8317                self.reload_assets().map_err(ScriptFailure::from)
8318            } else {
8319                Ok(())
8320            }
8321        })
8322        .and_then(|()| {
8323            if manifest_changed {
8324                self.reload_manifest().map_err(ScriptFailure::from)
8325            } else {
8326                Ok(())
8327            }
8328        })
8329    }
8330
8331    #[cfg(feature = "dev-reload")]
8332    fn reload_scripts(
8333        &mut self,
8334        changed_paths: &BTreeSet<PathBuf>,
8335        candidate_themes: Option<&ThemeManager>,
8336    ) -> Result<(), ScriptFailure> {
8337        let source = fs::read_to_string(&self.entry)
8338            .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8339        let modules = discover_modules(
8340            &self.ui_root,
8341            &self.entry,
8342            &self.theme_path,
8343            &self.style_path,
8344        )
8345        .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8346        let file_source = FileScriptSource::new(&self.ui_root, modules)
8347            .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8348        let root = self
8349            .ui_root
8350            .canonicalize()
8351            .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8352        let changed_modules = changed_module_ids(&root, changed_paths);
8353        let mut candidate_engine = self.engine.candidate_engine();
8354        configure_extension_engine(&self.factory.extensions, &mut candidate_engine)
8355            .map_err(ScriptFailure::plain)?;
8356        let mut candidate_cache = self.module_cache.clone();
8357        let refresh = candidate_cache
8358            .refresh(candidate_engine.engine(), &file_source, changed_modules)
8359            .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8360        let resolver =
8361            RestrictedModuleResolver::from_source_with_cache(&file_source, &candidate_cache)
8362                .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8363        let candidate = candidate_engine.with_program_preparation(|engine| {
8364            engine.set_module_resolver(resolver);
8365            preload_component_modules(engine, file_source.module_ids())
8366                .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8367            let candidate = engine
8368                .compile_self_contained_named(&self.entry.to_string_lossy(), &source)
8369                .map_err(|error| self.runtime_failure_with_engine(engine, &error, None))?;
8370            let state_schema = engine
8371                .root_state_schema(&candidate)
8372                .map_err(|error| self.runtime_failure_with_engine(engine, &error, None))?;
8373            let program_exports = engine
8374                .component_exports()
8375                .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8376            let program_renderers = engine
8377                .component_renderer_snapshot()
8378                .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8379            Ok::<_, ScriptFailure>((candidate, state_schema, program_exports, program_renderers))
8380        });
8381        let result = candidate.and_then(
8382            |(candidate, state_schema, program_exports, program_renderers)| {
8383                let program_compiled = candidate.clone();
8384                let program_schema = state_schema.clone();
8385                load_file_component_styles(
8386                    candidate_engine.engine(),
8387                    &self.style_path,
8388                    &program_exports,
8389                )
8390                .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8391                // Components may declare tokens the themes must provide, as at
8392                // preparation.
8393                {
8394                    let runtime = self.lifecycle.runtime();
8395                    let runtime = runtime.borrow();
8396                    if let Some(themes) = candidate_themes.or(runtime.theme.as_ref()) {
8397                        validate_component_tokens(themes, &program_exports)
8398                            .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8399                    }
8400                }
8401                if self.state.get() != ScriptViewState::Suspended {
8402                    if let Err(error) =
8403                        self.lifecycle
8404                            .reload(&mut candidate_engine, candidate, &state_schema)
8405                    {
8406                        return Err(self.lifecycle_failure_with_engine(
8407                            &candidate_engine,
8408                            &error,
8409                            None,
8410                        ));
8411                    }
8412                    self.engine = candidate_engine;
8413                }
8414                self.module_cache = candidate_cache;
8415                self.factory.update_program(
8416                    program_compiled,
8417                    program_schema,
8418                    program_exports,
8419                    program_renderers,
8420                );
8421                Ok(())
8422            },
8423        );
8424        if result.is_ok() {
8425            self.trace_script_reload(refresh.affected.len(), refresh.compiled.len());
8426        }
8427        result
8428    }
8429
8430    #[cfg(feature = "dev-reload")]
8431    fn trace_script_reload(&self, affected: usize, compiled: usize) {
8432        self.lifecycle.runtime().borrow_mut().traces.push(
8433            crate::RuntimeTraceKind::Reload,
8434            self.lifecycle.root_path().to_string(),
8435            format!("refreshed {affected} affected module(s), compiled {compiled}"),
8436            None,
8437            false,
8438        );
8439    }
8440
8441    /// Build the reloaded token base and themes without making them visible:
8442    /// the caller checks them against the components and then commits.
8443    #[cfg(feature = "dev-reload")]
8444    fn theme_candidate(&self) -> Result<ThemeCandidate, String> {
8445        let tokens_path = self.ui_root.join(TOKEN_BASE_FILE);
8446        let mut layers = self.factory.theme_layers.borrow().clone();
8447        let base = if tokens_path.exists() {
8448            let source = fs::read_to_string(&tokens_path).map_err(|error| error.to_string())?;
8449            let base = crate::load_token_base(
8450                self.engine.engine(),
8451                &tokens_path.to_string_lossy(),
8452                &source,
8453            )
8454            .map_err(|error| error.to_string())?;
8455            layers.base = Some(base.clone());
8456            Some(base)
8457        } else {
8458            None
8459        };
8460        let source = fs::read_to_string(&self.theme_path).map_err(|error| error.to_string())?;
8461        let primary = crate::load_theme_with_layers(
8462            self.engine.engine(),
8463            layers.base.as_ref(),
8464            &self.theme_path.to_string_lossy(),
8465            &source,
8466            &layers.overrides,
8467        )
8468        .map_err(|error| error.to_string())?;
8469        let previous = self
8470            .lifecycle
8471            .runtime()
8472            .borrow()
8473            .theme
8474            .as_ref()
8475            .map(|themes| themes.app_preference().clone());
8476        let mut themes = load_theme_directory(
8477            self.engine.engine(),
8478            &self.ui_root.join("themes"),
8479            &primary,
8480            &layers,
8481        )
8482        .map_err(|error| error.to_string())?;
8483        if let Some(previous) = previous {
8484            themes
8485                .set_app(previous)
8486                .map_err(|error| error.to_string())?;
8487        }
8488        let theme = themes
8489            .resolve(
8490                Some(&self.window_id),
8491                Some(&ComponentInstancePath::root("App", &self.window_id)),
8492                SystemAppearance::Dark,
8493            )
8494            .map_err(|error| error.to_string())?
8495            .variant()
8496            .clone();
8497        Ok(ThemeCandidate {
8498            base,
8499            themes,
8500            theme,
8501        })
8502    }
8503
8504    #[cfg(feature = "dev-reload")]
8505    fn commit_theme(&mut self, candidate: ThemeCandidate) {
8506        if let Some(base) = candidate.base {
8507            self.factory.theme_layers.borrow_mut().base = Some(base);
8508        }
8509        self.theme = candidate.theme;
8510        let runtime = self.lifecycle.runtime();
8511        runtime.borrow_mut().theme = Some(candidate.themes);
8512        runtime.borrow_mut().mark_all_windows_dirty();
8513    }
8514
8515    #[cfg(feature = "dev-reload")]
8516    fn reload_component_styles(&mut self) -> Result<(), ScriptFailure> {
8517        let components = self
8518            .engine
8519            .component_exports()
8520            .map_err(|error| ScriptFailure::plain(error.to_string()))?;
8521        let styles = self
8522            .load_current_component_styles(&components)
8523            .map_err(ScriptFailure::from)?;
8524        self.run_script_transaction(|view| {
8525            let changed = view
8526                .lifecycle
8527                .runtime()
8528                .borrow_mut()
8529                .replace_component_styles_from_host(styles);
8530            if changed && view.state.get() == ScriptViewState::Active {
8531                let result = view.lifecycle.render_dirty(&mut view.engine);
8532                result.map_err(|error| view.lifecycle_failure(&error, None))?;
8533            }
8534            Ok(())
8535        })
8536    }
8537
8538    #[cfg(feature = "dev-reload")]
8539    fn load_current_component_styles(
8540        &self,
8541        components: &ComponentRegistry,
8542    ) -> Result<ComponentStyleSheet, String> {
8543        load_file_component_styles(self.engine.engine(), &self.style_path, components)
8544            .map_err(|error| error.to_string())
8545    }
8546
8547    #[cfg(feature = "dev-reload")]
8548    fn reload_locales(&mut self) -> Result<(), String> {
8549        let runtime = self.lifecycle.runtime();
8550        let previous = runtime
8551            .borrow()
8552            .locale
8553            .as_ref()
8554            .map(|locale| locale.app_locale().to_owned());
8555        let mut locales =
8556            load_locale_directory(self.engine.engine(), &self.ui_root.join("locales"))
8557                .map_err(|error| error.to_string())?;
8558        if let (Some(previous), Some(locales)) = (&previous, &mut locales) {
8559            let _ = locales.set_app(previous);
8560        }
8561        let mut runtime = runtime.borrow_mut();
8562        runtime.locale = locales;
8563        runtime.mark_all_windows_dirty();
8564        Ok(())
8565    }
8566
8567    #[cfg(feature = "dev-reload")]
8568    fn reload_assets(&mut self) -> Result<(), String> {
8569        let runtime = self.lifecycle.runtime();
8570        let mut runtime = runtime.borrow_mut();
8571        runtime
8572            .assets
8573            .refresh_namespace("app")
8574            .map_err(|error| error.to_string())?;
8575        runtime.mark_all_windows_dirty();
8576        Ok(())
8577    }
8578
8579    #[cfg(feature = "dev-reload")]
8580    fn reload_manifest(&mut self) -> Result<(), String> {
8581        let manifest =
8582            load_file_manifest(&self.ui_root, &self.entry).map_err(|error| error.to_string())?;
8583        let runtime = self.lifecycle.runtime();
8584        let mut runtime = runtime.borrow_mut();
8585        manifest
8586            .activate(&mut runtime.capabilities)
8587            .map_err(|error| error.to_string())?;
8588        runtime.mark_all_windows_dirty();
8589        Ok(())
8590    }
8591}
8592
8593fn sample_motion_domain(
8594    runtime: &mut UiRuntimeState,
8595    domain: &str,
8596    now: Instant,
8597) -> (crate::MotionFrame, Vec<crate::MotionTimelineEvent>) {
8598    let frame = runtime.motions.tick_scope(now, domain);
8599    runtime.motion_values = runtime.motions.snapshot(now);
8600    let ghosts = std::mem::take(&mut runtime.motion_ghosts);
8601    let mut retained = Vec::with_capacity(ghosts.len());
8602    for ghost in ghosts {
8603        if ghost.domain != domain || runtime.motions.is_node_scope_active(&ghost.path) {
8604            retained.push(ghost);
8605        } else {
8606            runtime.motions.cancel_node_scope(&ghost.path);
8607        }
8608    }
8609    runtime.motion_ghosts = retained;
8610    let events = runtime.motions.drain_timeline_events_for_domain(domain);
8611    (frame, events)
8612}
8613
8614#[cfg(feature = "dev-reload")]
8615fn changed_module_ids(root: &Path, changed_paths: &BTreeSet<PathBuf>) -> Vec<ModuleId> {
8616    changed_paths
8617        .iter()
8618        .filter_map(|path| {
8619            let relative = path.strip_prefix(root).ok()?;
8620            (relative.extension().and_then(|value| value.to_str()) == Some("rhai"))
8621                .then(|| {
8622                    ModuleId::parse(
8623                        relative
8624                            .with_extension("")
8625                            .components()
8626                            .map(|component| component.as_os_str().to_string_lossy())
8627                            .collect::<Vec<_>>()
8628                            .join("/"),
8629                    )
8630                    .ok()
8631                })
8632                .flatten()
8633        })
8634        .collect()
8635}
8636
8637impl Drop for ScriptHostView {
8638    fn drop(&mut self) {
8639        self.release_view();
8640    }
8641}
8642
8643#[derive(Debug, Error)]
8644pub enum ScriptViewError {
8645    #[error("failed to read script entry `{path}`: {source}")]
8646    Io {
8647        path: PathBuf,
8648        #[source]
8649        source: std::io::Error,
8650    },
8651    #[error(transparent)]
8652    Runtime(#[from] RuntimeError),
8653    #[error(transparent)]
8654    Lifecycle(#[from] crate::LifecycleError),
8655    #[error("{message}")]
8656    ScriptDiagnostic {
8657        message: String,
8658        diagnostic: Box<Diagnostic>,
8659    },
8660    #[error("failed to open GPUI window: {0}")]
8661    Window(String),
8662    #[error("script view ID `{0}` must be 1-64 ASCII alphanumeric, `_`, or `-` characters")]
8663    InvalidId(String),
8664    #[error("script view `{0}` is already mounted in this host")]
8665    DuplicateView(String),
8666    #[error("Host `{0}` is already bound to a different native window")]
8667    WrongNativeWindow(String),
8668    #[error("window `{window}` already has script command owner `{owner}`")]
8669    WindowCommandOwner { window: String, owner: String },
8670    #[error("script view `{0}` has been disposed")]
8671    DisposedView(String),
8672    #[error("script view `{0}` is suspended; resume it before rendering or interaction")]
8673    SuspendedView(String),
8674    #[error("script view suspend failed: {0}")]
8675    Suspend(String),
8676    #[error("script view resume failed: {0}")]
8677    Resume(String),
8678    #[error(
8679        "key binding `{keystrokes}` ({context:?}) conflicts: `{existing:?}` is already bound, requested `{requested:?}`"
8680    )]
8681    KeyBindingConflict {
8682        keystrokes: String,
8683        context: Option<String>,
8684        existing: ActionId,
8685        requested: ActionId,
8686    },
8687    #[error("failed to load UI theme: {0}")]
8688    Theme(String),
8689    #[error(transparent)]
8690    ComponentStyle(#[from] ComponentStyleError),
8691    #[error("failed to load UI locale: {0}")]
8692    Locale(String),
8693    #[error("runtime extension failed: {0}")]
8694    Extension(String),
8695    #[error("failed to decode application manifest: {0}")]
8696    Manifest(String),
8697    #[error("`{0}` supplies an in-memory source; it applies only to `ScriptView::sources`")]
8698    SourceOption(&'static str),
8699    #[error("application manifest entry `{manifest}` does not match host entry `{host}`")]
8700    ManifestEntry { manifest: ModuleId, host: ModuleId },
8701    #[error(transparent)]
8702    Capability(#[from] CapabilityError),
8703    #[error(transparent)]
8704    Async(#[from] crate::AsyncRuntimeError),
8705    #[error(transparent)]
8706    Responsive(#[from] ResponsiveError),
8707    #[error(transparent)]
8708    Dependency(#[from] DependencyError),
8709    #[error(transparent)]
8710    ComponentExport(#[from] ComponentExportError),
8711    #[error(transparent)]
8712    Action(#[from] ActionError),
8713    #[error(transparent)]
8714    Signal(#[from] crate::SignalError),
8715    #[error(transparent)]
8716    NativeCollection(#[from] crate::NativeCollectionError),
8717    #[error(transparent)]
8718    Document(#[from] crate::DocumentError),
8719    #[error(transparent)]
8720    ElementRef(#[from] crate::ElementRefError),
8721    #[error(transparent)]
8722    Overlay(#[from] crate::OverlayError),
8723    #[error("Rhai module path `{0}` is outside the UI root")]
8724    ModulePath(PathBuf),
8725    #[error(transparent)]
8726    ModuleId(#[from] crate::ModuleIdError),
8727    #[error(transparent)]
8728    ScriptSource(#[from] crate::ScriptSourceError),
8729    #[error(transparent)]
8730    Asset(#[from] crate::AssetError),
8731    #[error(transparent)]
8732    Font(#[from] crate::FontError),
8733    #[error(transparent)]
8734    Accessibility(#[from] crate::AccessibilityError),
8735    #[error(transparent)]
8736    Automation(#[from] crate::AutomationError),
8737    #[cfg(feature = "dev-reload")]
8738    #[error(transparent)]
8739    Watcher(#[from] crate::WatcherError),
8740}
8741
8742impl ScriptViewError {
8743    #[must_use]
8744    pub fn diagnostic(&self) -> Option<&Diagnostic> {
8745        match self {
8746            Self::ScriptDiagnostic { diagnostic, .. } => Some(diagnostic),
8747            _ => None,
8748        }
8749    }
8750}
8751
8752impl From<ScriptViewError> for ScriptFailure {
8753    fn from(error: ScriptViewError) -> Self {
8754        match error {
8755            ScriptViewError::ScriptDiagnostic {
8756                message,
8757                diagnostic,
8758            } => Self::with_diagnostic(message, *diagnostic),
8759            error => Self::plain(error.to_string()),
8760        }
8761    }
8762}
8763
8764#[cfg(test)]
8765mod tests {
8766    use super::*;
8767    use crate::WindowCommand;
8768
8769    #[test]
8770    fn motion_frame_freezes_only_events_present_at_its_sample_boundary() {
8771        let now = Instant::now();
8772        let domain = "window:w/view:v/root";
8773        let source = |name: &str| {
8774            crate::MotionTimeline::new(
8775                name,
8776                crate::MotionTimelineStep::Track(crate::MotionTrack {
8777                    target: ".".to_owned(),
8778                    source: crate::MotionSource::Transition(crate::MotionTransition::new(
8779                        crate::MotionProperty::Opacity,
8780                        0.0,
8781                        1.0,
8782                        1,
8783                    )),
8784                }),
8785            )
8786        };
8787        let mut runtime = UiRuntimeState::new();
8788        runtime
8789            .motions
8790            .start_timeline(
8791                ComponentInstancePath::root("UiNode", format!("{domain}/first")),
8792                source("first"),
8793                now,
8794            )
8795            .unwrap();
8796        let (_, committed) = sample_motion_domain(
8797            &mut runtime,
8798            domain,
8799            now + std::time::Duration::from_millis(1),
8800        );
8801        assert_eq!(committed.len(), 1);
8802
8803        let later = runtime
8804            .motions
8805            .start_timeline(
8806                ComponentInstancePath::root("UiNode", format!("{domain}/later")),
8807                source("later"),
8808                now,
8809            )
8810            .unwrap();
8811        runtime.motions.cancel_timeline(&later).unwrap();
8812        assert_eq!(committed.len(), 1, "the committed batch is immutable");
8813        assert_eq!(
8814            runtime
8815                .motions
8816                .drain_timeline_events_for_domain(domain)
8817                .len(),
8818            1,
8819            "events created after sampling remain for the next rendered frame"
8820        );
8821    }
8822
8823    fn write_manifest(directory: &Path) {
8824        fs::write(
8825            directory.join("app.toml"),
8826            "entry = \"main\"\nruntime_api = 3\n",
8827        )
8828        .unwrap();
8829    }
8830
8831    fn start_prepared(
8832        mut prepared: PreparedScriptView,
8833        view_id: &str,
8834        window_id: &str,
8835    ) -> (RuntimeEngine, ScriptLifecycle) {
8836        let program = prepared.factory.program();
8837        let lifecycle = prepared
8838            .factory
8839            .mount_lifecycle(
8840                &mut prepared.engine,
8841                program,
8842                view_id,
8843                window_id,
8844                WindowCommandPolicy::Disabled,
8845                true,
8846                None,
8847            )
8848            .unwrap();
8849        (prepared.engine, lifecycle)
8850    }
8851
8852    #[test]
8853    fn error_banner_policy_defaults_on_and_can_be_disabled() {
8854        assert!(ScriptViewConfig::new("default").show_error_banner);
8855        assert!(
8856            !ScriptViewConfig::new("custom")
8857                .show_error_banner(false)
8858                .show_error_banner
8859        );
8860    }
8861
8862    #[test]
8863    fn structured_script_error_keeps_human_display_separate_from_diagnostic() {
8864        let mut engine = RuntimeEngine::new();
8865        let compiled = engine
8866            .compile_named("ui/failure.rhai", "fn view() { throw \"boom\"; }")
8867            .unwrap();
8868        let runtime_error = engine.render(&compiled).unwrap_err();
8869        let diagnostic = Diagnostic::from_runtime(
8870            &runtime_error,
8871            &crate::DiagnosticContext {
8872                source: Some("ui/failure.rhai".to_owned()),
8873                component: Some(ComponentInstancePath::root("View", "failure")),
8874                execution_timing: engine.last_failed_timing(),
8875                ..crate::DiagnosticContext::default()
8876            },
8877        );
8878        let error = ScriptViewError::ScriptDiagnostic {
8879            message: "human message".to_owned(),
8880            diagnostic: Box::new(diagnostic.clone()),
8881        };
8882
8883        assert_eq!(error.to_string(), "human message");
8884        assert_eq!(error.diagnostic(), Some(&diagnostic));
8885        let failure = ScriptFailure::from(error);
8886        assert_eq!(failure.message, "human message");
8887        assert_eq!(failure.diagnostic, Some(Box::new(diagnostic)));
8888    }
8889
8890    #[test]
8891    fn initial_mount_failure_returns_a_structured_root_diagnostic() {
8892        let entry = ModuleId::parse("main").unwrap();
8893        let mut prepared = ScriptView::sources(
8894            entry.clone(),
8895            EmbeddedScriptSource::new(BTreeMap::from([(
8896                entry,
8897                "fn view(ctx) { throw \"mount failure\"; }".to_owned(),
8898            )])),
8899            include_str!("../../../registry/themes/default_dark.rhai"),
8900        )
8901        .prepare()
8902        .unwrap();
8903        let program = prepared.factory.program();
8904        let Err(error) = prepared.factory.mount_lifecycle(
8905            &mut prepared.engine,
8906            program,
8907            "broken-view",
8908            "main",
8909            WindowCommandPolicy::Disabled,
8910            true,
8911            None,
8912        ) else {
8913            panic!("mount unexpectedly succeeded");
8914        };
8915
8916        assert!(error.to_string().contains("mount failure"));
8917        assert!(!error.to_string().contains("component_state"));
8918        let diagnostic = error.diagnostic().expect("script diagnostic");
8919        assert_eq!(diagnostic.component.as_deref(), Some("/View[broken-view]"));
8920        assert_eq!(diagnostic.key.as_deref(), Some("broken-view"));
8921        assert_eq!(
8922            diagnostic
8923                .execution
8924                .as_ref()
8925                .map(|execution| &execution.operation),
8926            Some(&crate::ExecutionOperation::Render)
8927        );
8928    }
8929
8930    #[test]
8931    fn theme_handle_state_only_advances_for_an_effective_theme_change() {
8932        let engine = RuntimeEngine::new();
8933        let dark = crate::load_theme_with_layers(
8934            engine.engine(),
8935            Some(
8936                &crate::load_token_base(
8937                    engine.engine(),
8938                    "tokens.rhai",
8939                    include_str!("../../../registry/tokens.rhai"),
8940                )
8941                .unwrap(),
8942            ),
8943            "default_dark.rhai",
8944            include_str!("../../../registry/themes/default_dark.rhai"),
8945            &crate::ThemeTokenOverrides::default(),
8946        )
8947        .unwrap();
8948        let mut light = dark.clone();
8949        light.name = "Light".to_owned();
8950        light.mode = crate::ThemeMode::Light;
8951        let mut state = ThemeHandleState {
8952            snapshot: ThemeSnapshot::new(7, dark.clone()),
8953        };
8954
8955        assert!(!state.replace(dark));
8956        assert_eq!(state.snapshot.revision, 7);
8957        assert!(state.replace(light.clone()));
8958        assert_eq!(state.snapshot.revision, 8);
8959        assert_eq!(state.snapshot.variant, light);
8960        assert!(state.snapshot.variant.tokens.radii.contains_key("md"));
8961        assert!(
8962            state
8963                .snapshot
8964                .variant
8965                .tokens
8966                .typography
8967                .roles
8968                .contains_key("body")
8969        );
8970    }
8971
8972    #[test]
8973    fn reduced_motion_environment_values_are_normalized() {
8974        assert_eq!(parse_motion_preference("1"), MotionPreference::Reduced);
8975        assert_eq!(parse_motion_preference("TRUE"), MotionPreference::Reduced);
8976        assert_eq!(
8977            parse_motion_preference("reduced"),
8978            MotionPreference::Reduced
8979        );
8980        assert_eq!(parse_motion_preference("0"), MotionPreference::Normal);
8981    }
8982
8983    #[test]
8984    fn retained_descendant_resolves_nearest_scroll_ancestor() {
8985        let root = crate::UiNode::box_node(vec![
8986            crate::UiNode::box_node(vec![crate::UiNode::text("target").with_key("target")])
8987                .with_key("middle"),
8988        ])
8989        .with_key("scroll")
8990        .with_style(&crate::Style::new().overflow_y_scroll());
8991        let mut tree = crate::RetainedUiTree::new();
8992        tree.reconcile(root).unwrap();
8993        let target = tree
8994            .nodes()
8995            .find(|node| node.key() == Some("target"))
8996            .unwrap()
8997            .id();
8998        assert_eq!(nearest_scroll_ancestor(&tree, target), tree.root_id());
8999    }
9000
9001    #[test]
9002    fn pointer_callback_return_controls_gpui_propagation() {
9003        assert_eq!(
9004            event_response_from_dynamic(&rhai::Dynamic::from("propagate")).propagation(),
9005            crate::PropagationControl::Continue
9006        );
9007        assert_eq!(
9008            event_response_from_dynamic(&rhai::Dynamic::UNIT).propagation(),
9009            crate::PropagationControl::Stop
9010        );
9011        let response = crate::EventResponse::new()
9012            .prevent_default()
9013            .capture_pointer();
9014        assert_eq!(
9015            event_response_from_dynamic(&rhai::Dynamic::from(response)),
9016            response
9017        );
9018    }
9019
9020    #[test]
9021    fn prepared_view_starts_engine_and_lifecycle_on_mount() {
9022        let directory = tempfile::tempdir().unwrap();
9023        let entry = directory.path().join("main.rhai");
9024        fs::write(&entry, "fn view(ctx) { text(\"prepared\") }").unwrap();
9025        fs::write(
9026            directory.path().join("theme.rhai"),
9027            include_str!("../../../registry/themes/default_dark.rhai"),
9028        )
9029        .unwrap();
9030        write_manifest(directory.path());
9031        let prepared = ScriptView::files(&entry).prepare().unwrap();
9032        let (engine, lifecycle) = start_prepared(prepared, "widget", "main");
9033        assert!(engine.is_current(lifecycle.generation()));
9034        assert!(lifecycle.root().is_some());
9035    }
9036
9037    static EMBEDDED_UI: crate::EmbeddedUi = crate::EmbeddedUi::new(&[
9038        ("app.toml", b"entry = \"main\"\nruntime_api = 3\n"),
9039        (
9040            "theme.rhai",
9041            include_bytes!("../../../registry/themes/default_dark.rhai"),
9042        ),
9043        (
9044            "main.rhai",
9045            b"import \"helpers/text\" as words;\nfn view(ctx) { text(words::label()) }",
9046        ),
9047        ("helpers/text.rhai", b"fn label() { \"embedded\" }"),
9048        (
9049            "themes/nord.rhai",
9050            include_bytes!("../../../registry/themes/nord.rhai"),
9051        ),
9052        (
9053            "locales/en.rhai",
9054            include_bytes!("../../../registry/locales/en.rhai"),
9055        ),
9056        (
9057            "assets/icons/check.svg",
9058            include_bytes!("../../../registry/assets/icons/check.svg"),
9059        ),
9060        ("assets/LICENSE.txt", b"ISC"),
9061        (".DS_Store", b"\0"),
9062    ]);
9063
9064    #[test]
9065    fn an_embedded_tree_prepares_as_its_directory_would() {
9066        let prepared = ScriptView::embedded(&EMBEDDED_UI).prepare().unwrap();
9067        {
9068            let runtime = prepared.factory.runtime.borrow();
9069            assert_eq!(runtime.theme.as_ref().unwrap().variants().count(), 2);
9070            assert!(runtime.locale.is_some());
9071            assert!(
9072                runtime
9073                    .assets
9074                    .load_image(&crate::AssetId::parse("app/icons/check").unwrap())
9075                    .is_ok()
9076            );
9077            assert!(
9078                runtime
9079                    .assets
9080                    .load_image(&crate::AssetId::parse("app/LICENSE").unwrap())
9081                    .is_err()
9082            );
9083        }
9084        let (_engine, lifecycle) = start_prepared(prepared, "embedded", "main");
9085        assert!(matches!(
9086            lifecycle.root().unwrap().kind(),
9087            crate::UiNodeKind::Text { text } if text == "embedded"
9088        ));
9089    }
9090
9091    #[test]
9092    fn a_ui_directory_names_its_entry_in_app_toml() {
9093        let directory = tempfile::tempdir().unwrap();
9094        fs::write(
9095            directory.path().join("app.toml"),
9096            "entry = \"start\"\nruntime_api = 3\n",
9097        )
9098        .unwrap();
9099        fs::write(
9100            directory.path().join("theme.rhai"),
9101            include_str!("../../../registry/themes/default_dark.rhai"),
9102        )
9103        .unwrap();
9104        fs::write(
9105            directory.path().join("start.rhai"),
9106            "fn view(ctx) { text(\"from start\") }",
9107        )
9108        .unwrap();
9109        let prepared = ScriptView::files(directory.path()).prepare().unwrap();
9110        let (_engine, lifecycle) = start_prepared(prepared, "directory", "start");
9111        assert!(matches!(
9112            lifecycle.root().unwrap().kind(),
9113            crate::UiNodeKind::Text { text } if text == "from start"
9114        ));
9115    }
9116
9117    #[test]
9118    fn source_options_and_the_ui_override_follow_the_source() {
9119        let Err(error) = ScriptView::embedded(&EMBEDDED_UI)
9120            .theme_sources([("x.rhai".to_owned(), String::new())])
9121            .prepare()
9122        else {
9123            panic!("theme_sources applies to in-memory sources only");
9124        };
9125        assert!(matches!(
9126            error,
9127            ScriptViewError::SourceOption("theme_sources")
9128        ));
9129        // Cargo sets CARGO_MANIFEST_DIR for test binaries: the override reads
9130        // that directory, which has no app.toml, instead of the embedded tree.
9131        let Err(ScriptViewError::Io { path, .. }) = ScriptView::embedded(&EMBEDDED_UI)
9132            .ui_override_env("CARGO_MANIFEST_DIR")
9133            .prepare()
9134        else {
9135            panic!("the override reads files");
9136        };
9137        assert_eq!(path, Path::new(env!("CARGO_MANIFEST_DIR")).join("app.toml"));
9138        assert!(
9139            ScriptView::embedded(&EMBEDDED_UI)
9140                .ui_override_env("GPUI_RHAI_TEST_UNSET_VARIABLE")
9141                .prepare()
9142                .is_ok()
9143        );
9144    }
9145
9146    #[test]
9147    fn embedded_host_theme_overrides_cover_primary_and_additional_variants() {
9148        let entry = ModuleId::parse("main").unwrap();
9149        let scripts = EmbeddedScriptSource::new(BTreeMap::from([(
9150            entry.clone(),
9151            "fn view(ctx) { text(\"theme override\") }".to_owned(),
9152        )]));
9153        let overrides = ThemeTokenOverrides {
9154            colors: BTreeMap::from([(
9155                "accent".to_owned(),
9156                crate::Rgba8::from_rgb_hex(0x00aa_55cc),
9157            )]),
9158            radii: BTreeMap::from([
9159                ("pill".to_owned(), crate::Length::Pixels(4.0)),
9160                ("md".to_owned(), crate::Length::Pixels(7.0)),
9161                ("lg".to_owned(), crate::Length::Pixels(10.0)),
9162            ]),
9163            ..ThemeTokenOverrides::default()
9164        };
9165        let prepared = ScriptView::sources(
9166            entry,
9167            scripts,
9168            include_str!("../../../registry/themes/default_dark.rhai"),
9169        )
9170        .theme_sources([(
9171            "nord.rhai".to_owned(),
9172            include_str!("../../../registry/themes/nord.rhai").to_owned(),
9173        )])
9174        .theme_token_overrides(overrides)
9175        .prepare()
9176        .unwrap();
9177        assert_eq!(
9178            prepared.theme.tokens.radii["md"],
9179            crate::Variable::Fixed(crate::Length::Pixels(7.0))
9180        );
9181        assert_eq!(
9182            prepared.theme.tokens.color("accent"),
9183            Some(crate::Rgba8::from_rgb_hex(0x00aa_55cc))
9184        );
9185
9186        let mut runtime = prepared.factory.runtime.borrow_mut();
9187        let themes = runtime.theme.as_mut().unwrap();
9188        themes
9189            .set_app(crate::ThemePreference::Fixed {
9190                selection: ThemeSelection::new("Nord", "Dark"),
9191            })
9192            .unwrap();
9193        assert_eq!(
9194            themes
9195                .resolve(None, None, SystemAppearance::Dark)
9196                .unwrap()
9197                .variant()
9198                .tokens
9199                .radii["md"],
9200            crate::Variable::Fixed(crate::Length::Pixels(7.0))
9201        );
9202    }
9203
9204    #[test]
9205    fn prepare_resolves_copied_component_modules() {
9206        let directory = tempfile::tempdir().unwrap();
9207        let components = directory.path().join("components");
9208        fs::create_dir_all(&components).unwrap();
9209        fs::write(
9210            components.join("greeting.rhai"),
9211            "fn Greeting() { text(\"hello\") }",
9212        )
9213        .unwrap();
9214        fs::write(
9215            directory.path().join("main.rhai"),
9216            "import \"components/greeting\" as greeting; fn view(ctx) { greeting::Greeting() }",
9217        )
9218        .unwrap();
9219        fs::write(
9220            directory.path().join("theme.rhai"),
9221            include_str!("../../../registry/themes/default_dark.rhai"),
9222        )
9223        .unwrap();
9224        write_manifest(directory.path());
9225
9226        let prepared = ScriptView::files(directory.path().join("main.rhai"))
9227            .prepare()
9228            .unwrap();
9229        let (_, lifecycle) = start_prepared(prepared, "widget", "main");
9230        let root = lifecycle.root().unwrap();
9231        assert!(matches!(
9232            root.kind(),
9233            crate::UiNodeKind::Text { text } if text == "hello"
9234        ));
9235        assert_eq!(
9236            root.source().map(|source| source.module.as_str()),
9237            Some("components/greeting")
9238        );
9239    }
9240
9241    #[test]
9242    fn file_view_applies_the_validated_component_stylesheet() {
9243        let directory = tempfile::tempdir().unwrap();
9244        let components = directory.path().join("components");
9245        fs::create_dir_all(&components).unwrap();
9246        fs::write(
9247            components.join("button.rhai"),
9248            include_str!("../../../registry/components/button.rhai"),
9249        )
9250        .unwrap();
9251        fs::write(
9252            directory.path().join("main.rhai"),
9253            r#"import "components/button" as button;
9254            fn view(ctx) { button::Button(#{ text: "Styled" }) }
9255            "#,
9256        )
9257        .unwrap();
9258        fs::write(
9259            directory.path().join("styles.rhai"),
9260            r#"fn component_styles() {
9261                #{ "components/button": #{ root: style().height(px(41)) } }
9262            }
9263            "#,
9264        )
9265        .unwrap();
9266        fs::write(
9267            directory.path().join("theme.rhai"),
9268            include_str!("../../../registry/themes/default_dark.rhai"),
9269        )
9270        .unwrap();
9271        fs::write(
9272            directory.path().join(TOKEN_BASE_FILE),
9273            include_str!("../../../registry/tokens.rhai"),
9274        )
9275        .unwrap();
9276        write_manifest(directory.path());
9277
9278        let prepared = ScriptView::files(directory.path().join("main.rhai"))
9279            .prepare()
9280            .unwrap();
9281        let (_, lifecycle) = start_prepared(prepared, "widget", "main");
9282        assert_eq!(
9283            lifecycle.root().unwrap().style().base.height,
9284            Some(crate::LayoutLength::Definite(crate::Length::Pixels(41.0)))
9285        );
9286    }
9287
9288    #[test]
9289    fn secondary_window_engine_restores_compiled_component_exports() {
9290        let entry = ModuleId::parse("main").unwrap();
9291        let button = ModuleId::parse("components/button").unwrap();
9292        let scripts = EmbeddedScriptSource::new(BTreeMap::from([
9293            (
9294                entry.clone(),
9295                r#"
9296                    import "components/button" as button;
9297                    fn view(ctx) {
9298                        button::Button(#{ text: `Window ${ctx.window_id()}` })
9299                    }
9300                "#
9301                .to_owned(),
9302            ),
9303            (
9304                button,
9305                include_str!("../../../registry/components/button.rhai").to_owned(),
9306            ),
9307        ]));
9308        let prepared = ScriptView::sources(
9309            entry,
9310            scripts,
9311            include_str!("../../../registry/themes/default_dark.rhai"),
9312        )
9313        .token_base(include_str!("../../../registry/tokens.rhai"))
9314        .prepare()
9315        .unwrap();
9316
9317        prepared
9318            .factory
9319            .runtime
9320            .borrow_mut()
9321            .windows
9322            .request_open(ScriptWindowSpec {
9323                id: "settings".to_owned(),
9324                title: "Settings".to_owned(),
9325                width: 400.0,
9326                height: 300.0,
9327                focus: true,
9328            })
9329            .unwrap();
9330        let (_, lifecycle, _) = prepared
9331            .factory
9332            .instantiate("settings-view", "settings", None)
9333            .unwrap();
9334        assert!(lifecycle.root().is_some());
9335    }
9336
9337    #[test]
9338    fn startup_rejects_manifest_capabilities_missing_from_host() {
9339        let directory = tempfile::tempdir().unwrap();
9340        fs::write(
9341            directory.path().join("main.rhai"),
9342            "fn view(ctx) { text(\"never starts\") }",
9343        )
9344        .unwrap();
9345        fs::write(
9346            directory.path().join("theme.rhai"),
9347            include_str!("../../../registry/themes/default_dark.rhai"),
9348        )
9349        .unwrap();
9350        fs::write(
9351            directory.path().join("app.toml"),
9352            "entry = \"main\"\nruntime_api = 3\n[capabilities]\n\"app.missing\" = \"*\"\n",
9353        )
9354        .unwrap();
9355
9356        assert!(matches!(
9357            ScriptView::files(directory.path().join("main.rhai")).prepare(),
9358            Err(ScriptViewError::Capability(CapabilityError::Missing(_)))
9359        ));
9360    }
9361
9362    #[test]
9363    fn embedded_asset_sources_match_file_provider_namespace() {
9364        let entry = ModuleId::parse("main").unwrap();
9365        let scripts = EmbeddedScriptSource::new(BTreeMap::from([(
9366            entry.clone(),
9367            r#"
9368                fn state_schema() {
9369                    #{ fields: #{ image: #{ schema: #{ type: "handle", kind: "image" },
9370                        "default": #{ type: "handle", value: #{ kind: "image", id: 0 } } } } }
9371                }
9372                fn init(ctx) { ctx.set_state("image", ctx.load_image(asset("app/check"))); }
9373                fn view(ctx) { image(ctx.get_state("image")) }
9374            "#
9375            .to_owned(),
9376        )]));
9377        let prepared = ScriptView::sources(
9378            entry,
9379            scripts,
9380            include_str!("../../../registry/themes/default_dark.rhai"),
9381        )
9382        .asset_sources([(
9383            "check".to_owned(),
9384            AssetData {
9385                mime_type: "image/svg+xml".to_owned(),
9386                bytes: include_bytes!("../../../registry/assets/icons/check.svg").to_vec(),
9387            },
9388        )])
9389        .prepare()
9390        .unwrap();
9391        let (_, lifecycle) = start_prepared(prepared, "asset-view", "main");
9392        assert!(matches!(
9393            lifecycle.root().unwrap().kind(),
9394            crate::UiNodeKind::Image {
9395                source: crate::ImageSourceSpec::Handle(handle),
9396            } if handle.id() != 0
9397        ));
9398    }
9399
9400    #[test]
9401    fn embedded_font_sources_are_validated_and_retained_for_mount() {
9402        let entry = ModuleId::parse("main").unwrap();
9403        let scripts = EmbeddedScriptSource::new(BTreeMap::from([(
9404            entry.clone(),
9405            "fn view(ctx) { text(\"font probe\") }".to_owned(),
9406        )]));
9407        let font =
9408            crate::FontSource::new("Art Display", [b"OTTO".as_slice(), &[0, 1, 2, 3]].concat())
9409                .unwrap();
9410        let prepared = ScriptView::sources(
9411            entry,
9412            scripts,
9413            include_str!("../../../registry/themes/default_dark.rhai"),
9414        )
9415        .font_source(font)
9416        .prepare()
9417        .unwrap();
9418        assert_eq!(prepared.fonts.len(), 1);
9419        assert_eq!(prepared.fonts[0].label(), "Art Display");
9420    }
9421
9422    #[test]
9423    fn embedded_runtime_clock_is_installed_before_initial_render() {
9424        let entry = ModuleId::parse("main").unwrap();
9425        let scripts = EmbeddedScriptSource::new(BTreeMap::from([(
9426            entry.clone(),
9427            "fn view(ctx) { text(\"clock probe\") }".to_owned(),
9428        )]));
9429        let start = std::time::Instant::now();
9430        let manual = crate::ManualRuntimeClock::new(start);
9431        let prepared = ScriptView::sources(
9432            entry,
9433            scripts,
9434            include_str!("../../../registry/themes/default_dark.rhai"),
9435        )
9436        .runtime_clock(manual.clock())
9437        .prepare()
9438        .unwrap();
9439
9440        manual.advance(std::time::Duration::from_millis(48));
9441        assert_eq!(
9442            prepared.factory.runtime.borrow().clock.now(),
9443            start + std::time::Duration::from_millis(48)
9444        );
9445    }
9446
9447    #[test]
9448    fn installed_lucide_icons_preload_from_files_and_embedded_sources() {
9449        let cached = |prepared: &PreparedScriptView, name: &str| {
9450            prepared
9451                .factory
9452                .runtime
9453                .borrow()
9454                .assets
9455                .cached_image(&AssetId::parse(format!("app/lucide/{name}")).unwrap())
9456                .is_ok()
9457        };
9458        let house = gpui_rhai_registry::lucide_icon("house").unwrap();
9459        let entry = ModuleId::parse("main").unwrap();
9460        let prepared = ScriptView::sources(
9461            entry.clone(),
9462            EmbeddedScriptSource::new(BTreeMap::from([(
9463                entry,
9464                "fn view(ctx) { image_source(asset(\"app/lucide/house\")) }".to_owned(),
9465            )])),
9466            include_str!("../../../registry/themes/default_dark.rhai"),
9467        )
9468        .asset_sources([(
9469            "lucide/house".to_owned(),
9470            AssetData {
9471                mime_type: "image/svg+xml".to_owned(),
9472                bytes: house.as_bytes().to_vec(),
9473            },
9474        )])
9475        .prepare()
9476        .unwrap();
9477        assert!(cached(&prepared, "house"));
9478
9479        let directory = tempfile::tempdir().unwrap();
9480        let ui = directory.path().join("ui");
9481        fs::create_dir_all(ui.join("assets/lucide")).unwrap();
9482        fs::write(ui.join("assets/lucide/house.svg"), house).unwrap();
9483        fs::write(
9484            ui.join("main.rhai"),
9485            "fn view(ctx) { image_source(asset(\"app/lucide/house\")) }\n",
9486        )
9487        .unwrap();
9488        fs::write(
9489            ui.join("theme.rhai"),
9490            include_str!("../../../registry/themes/default_dark.rhai"),
9491        )
9492        .unwrap();
9493        fs::write(ui.join("app.toml"), "entry = \"main\"\nruntime_api = 3\n").unwrap();
9494        let prepared = ScriptView::files(ui.join("main.rhai")).prepare().unwrap();
9495        assert!(cached(&prepared, "house"));
9496    }
9497
9498    #[test]
9499    fn declared_component_assets_preload_and_render_without_lifecycle_io() {
9500        let entry = ModuleId::parse("main").unwrap();
9501        let component = ModuleId::parse("components/declarative_icon").unwrap();
9502        let scripts = EmbeddedScriptSource::new(BTreeMap::from([
9503            (
9504                entry.clone(),
9505                r#"
9506                    import "components/declarative_icon" as declarative_icon;
9507                    fn view(ctx) { declarative_icon::DeclarativeIcon(#{} ) }
9508                "#
9509                .to_owned(),
9510            ),
9511            (
9512                component,
9513                r#"/* gpui-rhai
9514{
9515  "id": "components/declarative_icon",
9516  "export": "DeclarativeIcon",
9517  "version": "0.1.0",
9518  "runtime_api": { "min_inclusive": 3, "max_exclusive": 4 },
9519  "dependencies": [],
9520  "capabilities": {},
9521  "assets": ["icons/check.svg"]
9522}
9523*/
9524define_component(#{
9525    metadata: #{ id: "components/declarative_icon", "export": "DeclarativeIcon",
9526        version: "0.1.0", runtime_api: #{ min_inclusive: 3, max_exclusive: 4 },
9527        dependencies: [], capabilities: #{}, assets: ["icons/check.svg"] },
9528    schema: #{ props: #{}, state: #{ fields: #{} }, events: #{}, slots: #{}, parts: ["root"] },
9529    render: Fn("render_DeclarativeIcon")
9530});
9531fn DeclarativeIcon(props) { render_component("components/declarative_icon", props) }
9532fn render_DeclarativeIcon(ctx, props) { image(asset("app/icons/check")) }
9533"#
9534                .to_owned(),
9535            ),
9536        ]));
9537        let prepared = ScriptView::sources(
9538            entry,
9539            scripts,
9540            include_str!("../../../registry/themes/default_dark.rhai"),
9541        )
9542        .asset_sources([(
9543            "icons/check".to_owned(),
9544            AssetData {
9545                mime_type: "image/svg+xml".to_owned(),
9546                bytes: include_bytes!("../../../registry/assets/icons/check.svg").to_vec(),
9547            },
9548        )])
9549        .prepare()
9550        .unwrap();
9551        assert!(
9552            prepared
9553                .factory
9554                .runtime
9555                .borrow()
9556                .assets
9557                .cached_image(&AssetId::parse("app/icons/check").unwrap())
9558                .is_ok()
9559        );
9560        let (_, lifecycle) = start_prepared(prepared, "asset-view", "main");
9561        assert!(matches!(
9562            lifecycle.root().unwrap().kind(),
9563            crate::UiNodeKind::Image {
9564                source: crate::ImageSourceSpec::Asset(asset),
9565            } if asset.as_str() == "app/icons/check"
9566        ));
9567    }
9568
9569    #[test]
9570    fn missing_declared_component_asset_fails_preparation() {
9571        let entry = ModuleId::parse("main").unwrap();
9572        let component = ModuleId::parse("components/missing_asset").unwrap();
9573        let scripts = EmbeddedScriptSource::new(BTreeMap::from([
9574            (
9575                entry.clone(),
9576                "import \"components/missing_asset\" as missing; fn view(ctx) { missing::MissingAsset(#{} ) }"
9577                    .to_owned(),
9578            ),
9579            (
9580                component,
9581                r#"/* gpui-rhai
9582{
9583  "id": "components/missing_asset", "export": "MissingAsset", "version": "0.1.0",
9584  "runtime_api": { "min_inclusive": 3, "max_exclusive": 4 },
9585  "dependencies": [], "capabilities": {}, "assets": ["icons/missing.svg"]
9586}
9587*/
9588define_component(#{ metadata: #{ id: "components/missing_asset", "export": "MissingAsset",
9589    version: "0.1.0", runtime_api: #{ min_inclusive: 3, max_exclusive: 4 },
9590    dependencies: [], capabilities: #{}, assets: ["icons/missing.svg"] },
9591    schema: #{ props: #{}, state: #{ fields: #{} }, events: #{}, slots: #{}, parts: ["root"] },
9592    render: Fn("render_MissingAsset") });
9593fn MissingAsset(props) { render_component("components/missing_asset", props) }
9594fn render_MissingAsset(ctx, props) { image(asset("app/icons/missing")) }
9595"#
9596                .to_owned(),
9597            ),
9598        ]));
9599        let result = ScriptView::sources(
9600            entry,
9601            scripts,
9602            include_str!("../../../registry/themes/default_dark.rhai"),
9603        )
9604        .prepare();
9605        assert!(matches!(result, Err(ScriptViewError::Asset(_))));
9606    }
9607
9608    #[test]
9609    fn file_and_embedded_apps_produce_equivalent_locale_asset_tree() {
9610        let script = r#"
9611            fn state_schema() {
9612                #{ fields: #{ image: #{ schema: #{ type: "handle", kind: "image" },
9613                    "default": #{ type: "handle", value: #{ kind: "image", id: 0 } } } } }
9614            }
9615            fn init(ctx) { ctx.set_state("image", ctx.load_image(asset("app/check"))); }
9616            fn view(ctx) { row([text(ctx.t("common.loading")), image(ctx.get_state("image"))]) }
9617        "#;
9618        let locale = include_str!("../../../registry/locales/en.rhai");
9619        let theme = include_str!("../../../registry/themes/default_dark.rhai");
9620        let svg = include_bytes!("../../../registry/assets/icons/check.svg");
9621        let directory = tempfile::tempdir().unwrap();
9622        fs::create_dir_all(directory.path().join("locales")).unwrap();
9623        fs::create_dir_all(directory.path().join("assets")).unwrap();
9624        fs::write(directory.path().join("main.rhai"), script).unwrap();
9625        fs::write(directory.path().join("theme.rhai"), theme).unwrap();
9626        fs::write(
9627            directory.path().join("app.toml"),
9628            "entry = \"main\"\nruntime_api = 3\n",
9629        )
9630        .unwrap();
9631        fs::write(directory.path().join("locales/en.rhai"), locale).unwrap();
9632        fs::write(directory.path().join("assets/check.svg"), svg).unwrap();
9633        let file = ScriptView::files(directory.path().join("main.rhai"))
9634            .prepare()
9635            .unwrap();
9636
9637        let entry = ModuleId::parse("main").unwrap();
9638        let embedded = ScriptView::sources(
9639            entry.clone(),
9640            EmbeddedScriptSource::new(BTreeMap::from([(entry, script.to_owned())])),
9641            theme,
9642        )
9643        .locale_sources([("locales/en.rhai".to_owned(), locale.to_owned())])
9644        .asset_sources([(
9645            "check".to_owned(),
9646            AssetData {
9647                mime_type: "image/svg+xml".to_owned(),
9648                bytes: svg.to_vec(),
9649            },
9650        )])
9651        .prepare()
9652        .unwrap();
9653
9654        let (_, file) = start_prepared(file, "file-view", "main");
9655        let (_, embedded) = start_prepared(embedded, "embedded-view", "main");
9656
9657        for root in [file.root().unwrap(), embedded.root().unwrap()] {
9658            let crate::UiNodeKind::Box { children } = root.kind() else {
9659                panic!("equivalence app must render a row");
9660            };
9661            assert!(
9662                matches!(&children[0].kind(), crate::UiNodeKind::Text { text } if text == "Loading")
9663            );
9664            assert!(matches!(
9665                &children[1].kind(),
9666                crate::UiNodeKind::Image {
9667                    source: crate::ImageSourceSpec::Handle(handle),
9668                } if handle.id() == 1
9669            ));
9670        }
9671    }
9672
9673    #[test]
9674    fn missing_entry_has_path_aware_error() {
9675        let path = Path::new("definitely-missing-ui/main.rhai");
9676        let Err(error) = ScriptView::files(path).prepare() else {
9677            panic!("missing script unexpectedly prepared");
9678        };
9679        assert!(
9680            error
9681                .to_string()
9682                .contains("definitely-missing-ui/main.rhai")
9683        );
9684    }
9685
9686    #[test]
9687    fn script_window_api_queues_open_and_installs_close_confirmation_handler() {
9688        let mut engine = RuntimeEngine::new();
9689        let compiled = engine
9690            .compile(
9691                r#"
9692                    fn state_schema() { #{ fields: #{
9693                        close_pending: #{ schema: #{ type: "bool" },
9694                            "default": #{ type: "bool", value: false } }
9695                    } } }
9696                    fn close_requested(ctx, payload) {
9697                        ctx.set_state("close_pending", true);
9698                    }
9699                    fn init(ctx) {
9700                        ctx.set_close_handler(Fn("close_requested"));
9701                        ctx.open_window("settings", "Settings", 640, 480, true);
9702                    }
9703                    fn view(ctx) { text(ctx.window_id()) }
9704                "#,
9705            )
9706            .unwrap();
9707        let state_schema = engine.root_state_schema(&compiled).unwrap();
9708        let mut runtime = UiRuntimeState::new();
9709        runtime.windows.register_open("main").unwrap();
9710        let runtime = Rc::new(RefCell::new(runtime));
9711        let mut lifecycle = ScriptLifecycle::new(
9712            compiled,
9713            Rc::clone(&runtime),
9714            ComponentInstancePath::root("App", "main"),
9715            Some("main".to_owned()),
9716            BTreeMap::new(),
9717            &state_schema,
9718        )
9719        .unwrap();
9720        lifecycle.start(&mut engine).unwrap();
9721
9722        let close_handler = runtime.borrow().windows.close_handler("main").unwrap();
9723        let _ = lifecycle
9724            .invoke_callback_transactional(&engine, &close_handler, UiValue::Null)
9725            .unwrap();
9726        assert_eq!(
9727            runtime
9728                .borrow()
9729                .component_state
9730                .get(&ComponentInstancePath::root("App", "main"), "close_pending"),
9731            Some(&UiValue::Bool(true))
9732        );
9733
9734        let mut runtime = runtime.borrow_mut();
9735        assert!(runtime.windows.close_handler("main").is_some());
9736        assert!(matches!(
9737            runtime.windows.drain_commands().iter().map(crate::QueuedWindowCommand::command).collect::<Vec<_>>().as_slice(),
9738            [WindowCommand::Open(spec)] if spec.id == "settings" && spec.focus
9739        ));
9740    }
9741
9742    #[test]
9743    fn script_registered_semantic_action_dispatches_generation_bound_callback() {
9744        let mut engine = RuntimeEngine::new();
9745        let compiled = engine
9746            .compile(
9747                r#"
9748                    fn state_schema() {
9749                        #{ fields: #{ count: #{ schema: #{ type: "integer" },
9750                            "default": #{ type: "integer", value: 0 } } } }
9751                    }
9752                    fn increment(ctx, payload) {
9753                        ctx.set_state("count", ctx.get_state("count") + 1);
9754                    }
9755                    fn fire(ctx, payload) { ctx.dispatch_action("counter.increment", ()); }
9756                    fn init(ctx) { ctx.register_action("counter.increment", Fn("increment")); }
9757                    fn view(ctx) { text(`${ctx.get_state("count")}`).on_click(Fn("fire")) }
9758                "#,
9759            )
9760            .unwrap();
9761        let schema = engine.root_state_schema(&compiled).unwrap();
9762        let runtime = Rc::new(RefCell::new(UiRuntimeState::new()));
9763        let root_path = ComponentInstancePath::root("App", "main");
9764        let mut lifecycle = ScriptLifecycle::new(
9765            compiled,
9766            Rc::clone(&runtime),
9767            root_path.clone(),
9768            Some("main".to_owned()),
9769            BTreeMap::new(),
9770            &schema,
9771        )
9772        .unwrap();
9773        lifecycle.start(&mut engine).unwrap();
9774        let fire = lifecycle
9775            .root()
9776            .unwrap()
9777            .handler("click")
9778            .unwrap()
9779            .as_script()
9780            .unwrap()
9781            .clone();
9782        let _ = lifecycle
9783            .invoke_callback(&engine, &fire, UiValue::Null)
9784            .unwrap();
9785        let actions = runtime.borrow_mut().drain_batch().actions;
9786        for action in actions {
9787            let _ = lifecycle
9788                .invoke_callback(&engine, &action.callback, action.payload)
9789                .unwrap();
9790        }
9791        lifecycle.render(&mut engine).unwrap();
9792        assert_eq!(
9793            runtime.borrow().component_state.get(&root_path, "count"),
9794            Some(&UiValue::Integer(1))
9795        );
9796    }
9797}