Skip to main content

gpui_rhai/
primitive.rs

1use std::cell::RefCell;
2use std::collections::{BTreeMap, BTreeSet};
3use std::fmt;
4use std::panic::{AssertUnwindSafe, catch_unwind};
5use std::rc::{Rc, Weak};
6
7use gpui::{AnyElement, App, IntoElement, ParentElement, RenderOnce, Window, div};
8use rhai::{Array, Dynamic, FnPtr, Map};
9use serde::{Deserialize, Serialize};
10use thiserror::Error;
11
12use crate::{
13    AssetId, ColorResolver, ColorValue, ComponentStateSchema, EventSchema, Length,
14    NodeEventDispatcher, ObjectField, Rgba8, SchemaDefinitionError, SchemaValidationError,
15    ScriptCallback, ScriptGeneration, Style, UiEventHandler, UiNode, UiValue, UiValueError,
16    ValueSchema,
17};
18
19#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
20#[serde(try_from = "String", into = "String")]
21pub struct PrimitiveId(String);
22
23impl PrimitiveId {
24    /// Parse a namespaced primitive ID such as `my_app.code_editor`.
25    ///
26    /// # Errors
27    ///
28    /// Returns [`PrimitiveError::InvalidId`] for invalid identifiers.
29    pub fn parse(value: impl Into<String>) -> Result<Self, PrimitiveError> {
30        let value = value.into();
31        if value
32            .split_once('.')
33            .is_some_and(|(namespace, name)| is_identifier(namespace) && is_identifier(name))
34        {
35            Ok(Self(value))
36        } else {
37            Err(PrimitiveError::InvalidId(value))
38        }
39    }
40
41    #[must_use]
42    pub fn as_str(&self) -> &str {
43        &self.0
44    }
45
46    #[must_use]
47    pub fn namespace(&self) -> &str {
48        self.0
49            .split_once('.')
50            .map_or("", |(namespace, _)| namespace)
51    }
52}
53
54impl TryFrom<String> for PrimitiveId {
55    type Error = PrimitiveError;
56
57    fn try_from(value: String) -> Result<Self, Self::Error> {
58        Self::parse(value)
59    }
60}
61
62impl From<PrimitiveId> for String {
63    fn from(value: PrimitiveId) -> Self {
64        value.0
65    }
66}
67
68fn is_identifier(value: &str) -> bool {
69    !value.is_empty()
70        && !value.starts_with('_')
71        && !value.ends_with('_')
72        && !value.contains("__")
73        && value.chars().all(|character| {
74            character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_'
75        })
76}
77
78fn is_pascal_case(value: &str) -> bool {
79    value
80        .chars()
81        .next()
82        .is_some_and(|character| character.is_ascii_uppercase())
83        && value
84            .chars()
85            .all(|character| character.is_ascii_alphanumeric())
86}
87
88#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
89pub struct PrimitiveDescriptor {
90    pub id: PrimitiveId,
91    pub export: String,
92    #[serde(default)]
93    pub props: BTreeMap<String, ObjectField>,
94    #[serde(default)]
95    pub events: BTreeMap<String, EventSchema>,
96    #[serde(default)]
97    pub state: ComponentStateSchema,
98    #[serde(default)]
99    pub lifecycle: bool,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub effect: Option<EffectPrimitiveDescriptor>,
102}
103
104#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
105#[serde(rename_all = "snake_case")]
106pub enum PrimitivePlatform {
107    MacOs,
108    Linux,
109    Windows,
110}
111
112impl PrimitivePlatform {
113    #[must_use]
114    pub const fn current() -> Self {
115        #[cfg(target_os = "macos")]
116        {
117            Self::MacOs
118        }
119        #[cfg(target_os = "linux")]
120        {
121            Self::Linux
122        }
123        #[cfg(target_os = "windows")]
124        {
125            Self::Windows
126        }
127    }
128}
129
130#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
131pub struct EffectPrimitiveDescriptor {
132    pub platforms: BTreeSet<PrimitivePlatform>,
133    pub max_instances: usize,
134    pub max_cost_per_instance: usize,
135    pub reduced_motion: bool,
136    pub quality_tiers: bool,
137}
138
139#[derive(Clone, Debug, PartialEq)]
140pub enum PrimitiveValue {
141    Data(UiValue),
142    Node(Box<UiNode>),
143    Nodes(Vec<UiNode>),
144    Callback(UiEventHandler),
145    Style(Box<Style>),
146    Length(Length),
147    Asset(AssetId),
148    Signal(crate::NativeSignal),
149    Ref(crate::ElementRef),
150    Document(crate::NativeTextDocument),
151    #[cfg(feature = "charts")]
152    ChartData(crate::NativeChartData),
153}
154
155/// Read-only semantic theme values captured for one native primitive render.
156///
157/// Primitive handlers use this snapshot to resolve component-owned paint parts
158/// without receiving a mutable application/theme manager or coupling to a
159/// concrete theme family.
160#[derive(Clone, Debug)]
161pub struct PrimitiveTheme {
162    tokens: Option<std::sync::Arc<crate::ThemeTokens>>,
163    colors: BTreeMap<String, Rgba8>,
164    environment: crate::Environment,
165    inherited_disabled: bool,
166    direction: crate::TextDirection,
167    locale: String,
168    number: Option<crate::NumberMetadata>,
169    motion: crate::ThemeMotion,
170    motion_preference: crate::MotionPreference,
171    motion_quality: crate::MotionQuality,
172    clock: crate::RuntimeClock,
173}
174
175impl Default for PrimitiveTheme {
176    fn default() -> Self {
177        Self {
178            tokens: None,
179            colors: BTreeMap::new(),
180            environment: crate::Environment::EMPTY,
181            inherited_disabled: false,
182            direction: crate::TextDirection::LeftToRight,
183            locale: "en".to_owned(),
184            number: None,
185            motion: crate::ThemeMotion::default(),
186            motion_preference: crate::MotionPreference::Normal,
187            motion_quality: crate::MotionQuality::High,
188            clock: crate::RuntimeClock::default(),
189        }
190    }
191}
192
193impl PrimitiveTheme {
194    /// Capture a Host's read-only color/token resolver for native components.
195    /// Capture a fresh snapshot after the Host theme or direction changes.
196    #[must_use]
197    pub fn from_colors(
198        colors: &(impl ColorResolver + ?Sized),
199        direction: crate::TextDirection,
200    ) -> Self {
201        Self::capture_with_environment(
202            colors,
203            direction,
204            "en",
205            None,
206            crate::RuntimeClock::default(),
207            crate::MotionPreference::Normal,
208            crate::MotionQuality::High,
209        )
210    }
211
212    #[cfg(test)]
213    pub(crate) fn capture(colors: &impl ColorResolver) -> Self {
214        Self::capture_with_direction(colors, crate::TextDirection::LeftToRight)
215    }
216
217    #[cfg(test)]
218    pub(crate) fn capture_with_direction(
219        colors: &impl ColorResolver,
220        direction: crate::TextDirection,
221    ) -> Self {
222        Self::capture_with_motion_policy(
223            colors,
224            direction,
225            crate::MotionPreference::Normal,
226            crate::MotionQuality::High,
227        )
228    }
229
230    #[cfg(test)]
231    pub(crate) fn capture_with_motion_policy(
232        colors: &impl ColorResolver,
233        direction: crate::TextDirection,
234        motion_preference: crate::MotionPreference,
235        motion_quality: crate::MotionQuality,
236    ) -> Self {
237        Self::capture_with_environment(
238            colors,
239            direction,
240            "en",
241            None,
242            crate::RuntimeClock::default(),
243            motion_preference,
244            motion_quality,
245        )
246    }
247
248    pub(crate) fn capture_with_environment(
249        colors: &(impl ColorResolver + ?Sized),
250        direction: crate::TextDirection,
251        locale: &str,
252        number: Option<&crate::NumberMetadata>,
253        clock: crate::RuntimeClock,
254        motion_preference: crate::MotionPreference,
255        motion_quality: crate::MotionQuality,
256    ) -> Self {
257        let tokens = colors.token_set();
258        Self {
259            colors: if tokens.is_some() {
260                BTreeMap::new()
261            } else {
262                colors.color_snapshot()
263            },
264            tokens,
265            environment: colors.environment(),
266            inherited_disabled: false,
267            direction,
268            locale: locale.to_owned(),
269            number: number.cloned(),
270            motion: colors.resolve_motion(),
271            motion_preference,
272            motion_quality,
273            clock,
274        }
275    }
276
277    #[must_use]
278    pub(crate) const fn with_inherited_disabled(mut self, disabled: bool) -> Self {
279        self.inherited_disabled = disabled;
280        self
281    }
282
283    #[must_use]
284    pub fn color(&self, token: &str) -> Option<Rgba8> {
285        match &self.tokens {
286            Some(tokens) => tokens.color(token),
287            None => self.colors.get(token).copied(),
288        }
289    }
290
291    #[must_use]
292    pub fn resolve_color(&self, value: &ColorValue) -> Option<Rgba8> {
293        value.resolve_with(&mut |token| self.color(token))
294    }
295
296    pub(crate) fn part_color(
297        &self,
298        props: &PrimitiveProps,
299        name: &str,
300        background: bool,
301    ) -> Option<Rgba8> {
302        let style = props
303            .style(name)?
304            .resolve(&crate::InteractionState::default());
305        let value = if background {
306            style.background.as_ref().or(style.text_color.as_ref())
307        } else {
308            style.text_color.as_ref().or(style.background.as_ref())
309        }?;
310        self.resolve_color(value)
311    }
312
313    #[must_use]
314    pub fn resolve_length(&self, value: Length) -> Option<Length> {
315        match &self.tokens {
316            Some(tokens) => tokens.resolve_length(value, &self.environment),
317            None => (!value.is_theme_token()).then_some(value),
318        }
319    }
320
321    /// The environment inherited by this primitive.
322    #[must_use]
323    pub const fn environment(&self) -> crate::Environment {
324        self.environment
325    }
326
327    /// Whether an ancestor disabled this subtree. Primitives treat it like
328    /// their own `disabled` prop.
329    #[must_use]
330    pub const fn inherited_disabled(&self) -> bool {
331        self.inherited_disabled
332    }
333
334    #[must_use]
335    pub const fn direction(&self) -> crate::TextDirection {
336        self.direction
337    }
338
339    #[must_use]
340    pub fn locale(&self) -> &str {
341        &self.locale
342    }
343
344    #[must_use]
345    pub const fn number_metadata(&self) -> Option<&crate::NumberMetadata> {
346        self.number.as_ref()
347    }
348
349    #[must_use]
350    pub const fn motion_preference(&self) -> crate::MotionPreference {
351        self.motion_preference
352    }
353
354    #[must_use]
355    pub const fn motion_quality(&self) -> crate::MotionQuality {
356        self.motion_quality
357    }
358
359    #[must_use]
360    pub fn now(&self) -> std::time::Instant {
361        self.clock.now()
362    }
363
364    #[must_use]
365    pub const fn motion(&self) -> &crate::ThemeMotion {
366        &self.motion
367    }
368
369    #[must_use]
370    pub fn typography(&self, role: &str) -> Option<crate::ResolvedTypography> {
371        self.tokens
372            .as_ref()
373            .and_then(|tokens| tokens.resolve_typography(role, &self.environment))
374    }
375}
376
377impl ColorResolver for PrimitiveTheme {
378    fn resolve_token(&self, token: &str) -> Option<Rgba8> {
379        self.color(token)
380    }
381
382    fn color_snapshot(&self) -> BTreeMap<String, Rgba8> {
383        match &self.tokens {
384            Some(tokens) => tokens.color_snapshot(),
385            None => self.colors.clone(),
386        }
387    }
388
389    fn environment(&self) -> crate::Environment {
390        self.environment
391    }
392
393    fn resolve_length_in(
394        &self,
395        length: Length,
396        environment: &crate::Environment,
397    ) -> Option<Length> {
398        match &self.tokens {
399            Some(tokens) => tokens.resolve_length(length, environment),
400            None => (!length.is_theme_token()).then_some(length),
401        }
402    }
403
404    fn resolve_typography_in(
405        &self,
406        role: &str,
407        environment: &crate::Environment,
408    ) -> Option<crate::ResolvedTypography> {
409        self.tokens
410            .as_ref()
411            .and_then(|tokens| tokens.resolve_typography(role, environment))
412    }
413
414    fn token_set(&self) -> Option<std::sync::Arc<crate::ThemeTokens>> {
415        self.tokens.clone()
416    }
417
418    fn resolve_motion(&self) -> crate::ThemeMotion {
419        self.motion.clone()
420    }
421}
422
423#[derive(Clone, Debug, Default, PartialEq)]
424pub struct PrimitiveProps(BTreeMap<String, PrimitiveValue>);
425
426impl PrimitiveProps {
427    #[must_use]
428    pub fn new() -> Self {
429        Self::default()
430    }
431
432    #[must_use]
433    pub fn get(&self, name: &str) -> Option<&PrimitiveValue> {
434        self.0.get(name)
435    }
436
437    #[must_use]
438    pub fn data(&self, name: &str) -> Option<&UiValue> {
439        match self.get(name) {
440            Some(PrimitiveValue::Data(value)) => Some(value),
441            _ => None,
442        }
443    }
444
445    #[must_use]
446    pub fn number(&self, name: &str) -> Option<f64> {
447        match self.data(name) {
448            Some(UiValue::Float(value)) => Some(*value),
449            Some(UiValue::Integer(value)) => value.to_string().parse().ok(),
450            _ => None,
451        }
452    }
453
454    #[must_use]
455    pub fn integer(&self, name: &str) -> Option<i64> {
456        match self.data(name) {
457            Some(UiValue::Integer(value)) => Some(*value),
458            _ => None,
459        }
460    }
461
462    #[must_use]
463    pub fn usize(&self, name: &str) -> Option<usize> {
464        self.integer(name)
465            .and_then(|value| usize::try_from(value).ok())
466    }
467
468    #[must_use]
469    pub fn string(&self, name: &str) -> Option<&str> {
470        match self.data(name) {
471            Some(UiValue::String(value)) => Some(value),
472            _ => None,
473        }
474    }
475
476    #[must_use]
477    pub fn boolean(&self, name: &str) -> Option<bool> {
478        match self.data(name) {
479            Some(UiValue::Bool(value)) => Some(*value),
480            _ => None,
481        }
482    }
483
484    #[must_use]
485    pub fn style(&self, name: &str) -> Option<&Style> {
486        match self.get(name) {
487            Some(PrimitiveValue::Style(style)) => Some(style),
488            _ => None,
489        }
490    }
491
492    #[must_use]
493    pub fn signal(&self, name: &str) -> Option<&crate::NativeSignal> {
494        match self.get(name) {
495            Some(PrimitiveValue::Signal(signal)) => Some(signal),
496            _ => None,
497        }
498    }
499
500    #[must_use]
501    pub fn element_ref(&self, name: &str) -> Option<&crate::ElementRef> {
502        match self.get(name) {
503            Some(PrimitiveValue::Ref(reference)) => Some(reference),
504            _ => None,
505        }
506    }
507
508    #[must_use]
509    pub fn document(&self, name: &str) -> Option<&crate::NativeTextDocument> {
510        match self.get(name) {
511            Some(PrimitiveValue::Document(document)) => Some(document),
512            _ => None,
513        }
514    }
515
516    pub fn insert(
517        &mut self,
518        name: impl Into<String>,
519        value: PrimitiveValue,
520    ) -> Option<PrimitiveValue> {
521        self.0.insert(name.into(), value)
522    }
523
524    #[must_use]
525    pub fn with(mut self, name: impl Into<String>, value: PrimitiveValue) -> Self {
526        self.insert(name, value);
527        self
528    }
529
530    pub fn iter(&self) -> impl Iterator<Item = (&str, &PrimitiveValue)> {
531        self.0.iter().map(|(name, value)| (name.as_str(), value))
532    }
533
534    pub(crate) fn get_mut(&mut self, name: &str) -> Option<&mut PrimitiveValue> {
535        self.0.get_mut(name)
536    }
537
538    pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut PrimitiveValue)> {
539        self.0
540            .iter_mut()
541            .map(|(name, value)| (name.as_str(), value))
542    }
543
544    pub(crate) fn bind_component_scope(
545        &mut self,
546        component: &crate::ComponentInstancePath,
547        incarnation: crate::ComponentIncarnation,
548        events: &BTreeMap<String, EventSchema>,
549        native_context: Option<&crate::invocation::ScriptInvocationContext>,
550    ) {
551        for value in self.0.values_mut() {
552            match value {
553                PrimitiveValue::Callback(callback) => {
554                    if let Some(callback) = callback.as_script_mut() {
555                        callback.bind_component_scope_if_unset(
556                            component,
557                            incarnation,
558                            events.clone(),
559                        );
560                        if let Some(context) = native_context {
561                            callback.bind_native_context_if_unset(context.clone());
562                        }
563                    }
564                }
565                PrimitiveValue::Node(node) => {
566                    node.bind_component_scope(component, incarnation, events, native_context);
567                }
568                PrimitiveValue::Nodes(nodes) => {
569                    for node in nodes {
570                        node.bind_component_scope(component, incarnation, events, native_context);
571                    }
572                }
573                PrimitiveValue::Data(_)
574                | PrimitiveValue::Style(_)
575                | PrimitiveValue::Length(_)
576                | PrimitiveValue::Asset(_)
577                | PrimitiveValue::Signal(_)
578                | PrimitiveValue::Ref(_)
579                | PrimitiveValue::Document(_) => {}
580                #[cfg(feature = "charts")]
581                PrimitiveValue::ChartData(_) => {}
582            }
583        }
584    }
585}
586
587#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
588pub struct PrimitiveInstanceId {
589    primitive: PrimitiveId,
590    key: String,
591    node: crate::NodeId,
592}
593
594impl PrimitiveInstanceId {
595    pub(crate) fn new(primitive: PrimitiveId, key: String, node: crate::NodeId) -> Self {
596        Self {
597            primitive,
598            key,
599            node,
600        }
601    }
602
603    #[must_use]
604    pub const fn primitive(&self) -> &PrimitiveId {
605        &self.primitive
606    }
607
608    #[must_use]
609    pub fn key(&self) -> &str {
610        &self.key
611    }
612
613    #[must_use]
614    pub const fn node(&self) -> crate::NodeId {
615        self.node
616    }
617}
618
619#[derive(Clone, Debug, PartialEq)]
620pub struct PrimitiveNode {
621    pub primitive: PrimitiveId,
622    pub key: Option<String>,
623    pub props: PrimitiveProps,
624}
625
626#[derive(Clone, Debug)]
627pub struct PrimitiveInstance {
628    pub id: Option<PrimitiveInstanceId>,
629    pub node: PrimitiveNode,
630    resources: Option<PrimitiveResourceScope>,
631    focus_handle: Option<gpui::FocusHandle>,
632}
633
634impl PrimitiveInstance {
635    /// Return the runtime-owned cancellation scope for a retained instance.
636    /// Ephemeral primitives have no resource scope and must not start durable
637    /// work from render.
638    #[must_use]
639    pub const fn resources(&self) -> Option<&PrimitiveResourceScope> {
640        self.resources.as_ref()
641    }
642
643    /// Return the runtime-owned focus identity for this native control.
644    ///
645    /// A focus-owning primitive must use this handle instead of allocating a
646    /// second identity so its declarative wrapper, automation target, and
647    /// native editor all observe the same focus state.
648    #[must_use]
649    pub const fn focus_handle(&self) -> Option<&gpui::FocusHandle> {
650        self.focus_handle.as_ref()
651    }
652}
653
654#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
655pub struct PrimitiveResourceHandle(u64);
656
657struct PrimitiveResourceEntry {
658    label: String,
659    cleanup: Option<Box<dyn FnOnce()>>,
660}
661
662#[derive(Default)]
663struct PrimitiveResourceState {
664    next_id: u64,
665    entries: BTreeMap<u64, PrimitiveResourceEntry>,
666}
667
668impl Drop for PrimitiveResourceState {
669    fn drop(&mut self) {
670        let entries = std::mem::take(&mut self.entries);
671        for entry in entries.into_values().rev() {
672            let _ = run_resource_cleanup(entry);
673        }
674    }
675}
676
677#[derive(Clone, Default)]
678pub struct PrimitiveResourceScope {
679    inner: Rc<RefCell<PrimitiveResourceState>>,
680}
681
682impl fmt::Debug for PrimitiveResourceScope {
683    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
684        match self.inner.try_borrow() {
685            Ok(state) => formatter
686                .debug_struct("PrimitiveResourceScope")
687                .field(
688                    "active",
689                    &state
690                        .entries
691                        .values()
692                        .map(|entry| entry.label.as_str())
693                        .collect::<Vec<_>>(),
694                )
695                .finish(),
696            Err(_) => formatter.write_str("PrimitiveResourceScope(<borrowed>)"),
697        }
698    }
699}
700
701impl PrimitiveResourceScope {
702    #[must_use]
703    pub fn new() -> Self {
704        Self::default()
705    }
706
707    /// Own one native task/subscription/resource cancellation callback.
708    ///
709    /// # Errors
710    ///
711    /// Returns [`PrimitiveResourceError`] for an unsafe label or conflicting
712    /// scope borrow.
713    pub fn own(
714        &self,
715        label: impl Into<String>,
716        cleanup: impl FnOnce() + 'static,
717    ) -> Result<PrimitiveResourceHandle, PrimitiveResourceError> {
718        let label = label.into();
719        if label.is_empty()
720            || label.len() > 128
721            || !label.chars().all(|character| {
722                character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '.' | ':')
723            })
724        {
725            return Err(PrimitiveResourceError::InvalidLabel(label));
726        }
727        let mut state = self
728            .inner
729            .try_borrow_mut()
730            .map_err(|_| PrimitiveResourceError::Borrowed)?;
731        let id = state.next_id.max(1);
732        state.next_id = id
733            .checked_add(1)
734            .ok_or(PrimitiveResourceError::IdExhausted)?;
735        state.entries.insert(
736            id,
737            PrimitiveResourceEntry {
738                label,
739                cleanup: Some(Box::new(cleanup)),
740            },
741        );
742        Ok(PrimitiveResourceHandle(id))
743    }
744
745    /// Cancel one owned resource early.
746    ///
747    /// # Errors
748    ///
749    /// Returns a borrow or cleanup-panic diagnostic.
750    pub fn cancel(&self, handle: &PrimitiveResourceHandle) -> Result<bool, PrimitiveResourceError> {
751        let entry = self
752            .inner
753            .try_borrow_mut()
754            .map_err(|_| PrimitiveResourceError::Borrowed)?
755            .entries
756            .remove(&handle.0);
757        let Some(entry) = entry else {
758            return Ok(false);
759        };
760        run_resource_cleanup(entry)?;
761        Ok(true)
762    }
763
764    #[must_use]
765    pub fn active_count(&self) -> usize {
766        self.inner.borrow().entries.len()
767    }
768
769    fn checkpoint(&self) -> Result<u64, PrimitiveResourceError> {
770        self.inner
771            .try_borrow()
772            .map(|state| state.next_id.max(1))
773            .map_err(|_| PrimitiveResourceError::Borrowed)
774    }
775
776    fn rollback(&self, checkpoint: u64) -> Result<(), PrimitiveResourceError> {
777        self.cleanup_where(|id| id >= checkpoint)
778    }
779
780    fn close(&self) -> Result<(), PrimitiveResourceError> {
781        self.cleanup_where(|_| true)
782    }
783
784    fn cleanup_where(&self, predicate: impl Fn(u64) -> bool) -> Result<(), PrimitiveResourceError> {
785        let mut entries = {
786            let mut state = self
787                .inner
788                .try_borrow_mut()
789                .map_err(|_| PrimitiveResourceError::Borrowed)?;
790            let ids = state
791                .entries
792                .keys()
793                .copied()
794                .filter(|id| predicate(*id))
795                .collect::<Vec<_>>();
796            ids.into_iter()
797                .rev()
798                .filter_map(|id| state.entries.remove(&id))
799                .collect::<Vec<_>>()
800        };
801        let mut first_error = None;
802        for entry in entries.drain(..) {
803            if let Err(error) = run_resource_cleanup(entry)
804                && first_error.is_none()
805            {
806                first_error = Some(error);
807            }
808        }
809        first_error.map_or(Ok(()), Err)
810    }
811}
812
813fn run_resource_cleanup(mut entry: PrimitiveResourceEntry) -> Result<(), PrimitiveResourceError> {
814    let label = entry.label;
815    let Some(cleanup) = entry.cleanup.take() else {
816        return Ok(());
817    };
818    catch_unwind(AssertUnwindSafe(cleanup))
819        .map_err(|_| PrimitiveResourceError::CleanupPanic { label })
820}
821
822#[derive(Clone, Debug, Error, Eq, PartialEq)]
823pub enum PrimitiveResourceError {
824    #[error("primitive resource label `{0}` must be 1-128 safe ASCII characters")]
825    InvalidLabel(String),
826    #[error("primitive resource scope is already borrowed")]
827    Borrowed,
828    #[error("primitive resource scope exhausted its handle identity space")]
829    IdExhausted,
830    #[error("primitive resource cleanup `{label}` panicked")]
831    CleanupPanic { label: String },
832}
833
834#[derive(Clone)]
835pub struct PrimitiveContext {
836    assets: Option<crate::AssetRegistry>,
837    registry: Weak<RefCell<PrimitiveRegistryInner>>,
838    primitive: PrimitiveId,
839    event_schemas: BTreeMap<String, EventSchema>,
840    callbacks: BTreeMap<String, UiEventHandler>,
841    dispatcher: Option<NodeEventDispatcher>,
842    interactions: crate::interaction::WindowInteractionCoordinator,
843    scroll_handles: Vec<gpui::ScrollHandle>,
844    wheel_parents: Vec<crate::scrollbar::ScrollWheelSource>,
845    key_captures: Vec<crate::renderer::KeyCaptureScope>,
846    intrinsic_size: Option<crate::intrinsic::IntrinsicSizeInvalidator>,
847    intrinsic_generation: ScriptGeneration,
848    intrinsic_lease: Option<Weak<RefCell<PrimitiveResourceState>>>,
849    view_id: String,
850    instance: Option<PrimitiveInstanceId>,
851    retained_node: Option<crate::NodeId>,
852    /// The focus handle of the node that hosts the primitive, if it has one.
853    focus_handle: Option<gpui::FocusHandle>,
854    /// Whether the view shows focus indicators this frame.
855    focus_indicators: bool,
856    /// Where dropped files go when the Host accepts file drops, read before the
857    /// render borrows the registry.
858    file_drops: Option<crate::DroppedFiles>,
859}
860
861/// A schema-checked semantic proposal produced by a native primitive policy.
862///
863/// The runtime executes this value at the owning `ScriptView` boundary so
864/// synchronous automation can observe the real callback result.
865pub struct PrimitiveSemanticProposal {
866    pub(crate) event: String,
867    pub(crate) payload: UiValue,
868    pub(crate) handler: Option<UiEventHandler>,
869}
870
871impl PrimitiveContext {
872    /// Invalidate this retained native primitive's enclosing virtual-row size.
873    ///
874    /// Call once after committing an intrinsic size change (for example an
875    /// asynchronous document parse or a width-dependent native layout change),
876    /// using the primitive's current context. Do not call on every render.
877    /// Calls are coalesced and deferred, so calling from native render/update
878    /// cannot reenter a parent entity. Only the current live row is remeasured
879    /// by GPUI; nested virtual rows propagate to their enclosing row in turn.
880    /// No Rhai execution or whole-collection measurement is requested.
881    ///
882    /// Outside a virtual row this is a no-op. Unmounted/replaced primitive or
883    /// row leases and contexts from an older script generation are ignored at
884    /// execution time. Hidden retained rows can become dirty without timers or
885    /// continuous repaint; their measurement is refreshed when presented.
886    pub fn invalidate_intrinsic_size(&self, cx: &mut App) {
887        let (Some(invalidator), Some(instance), Some(lease)) = (
888            self.intrinsic_size.clone(),
889            self.instance.clone(),
890            self.intrinsic_lease.clone(),
891        ) else {
892            return;
893        };
894        let registry = self.registry.clone();
895        let generation = self.intrinsic_generation;
896        // The registry is itself borrowed during PrimitiveHandler::render.
897        // Validate after that operation has committed, never synchronously.
898        invalidator.invalidate_if(cx, move || {
899            let Some(registry) = registry.upgrade() else {
900                return false;
901            };
902            registry.try_borrow().is_ok_and(|inner| {
903                inner.generation == generation
904                    && inner.mounted.get(&instance).is_some_and(|mounted| {
905                        mounted
906                            .resources
907                            .as_ref()
908                            .is_some_and(|resources| lease.ptr_eq(&Rc::downgrade(&resources.inner)))
909                    })
910            })
911        });
912    }
913
914    /// Whether a script capture-phase key handler above the primitive
915    /// (`on_capture("key:…")`) takes the key being dispatched: one ran and
916    /// prevented the default or stopped it. A native editor asks before its
917    /// own key binding acts; outside a key dispatch there is no key to take.
918    pub(crate) fn script_takes_key(&self, window: &mut Window, cx: &mut App) -> bool {
919        if self.key_captures.is_empty() {
920            return false;
921        }
922        crate::app::dispatching_keystroke().is_some_and(|keystroke| {
923            crate::renderer::KeyCaptureScope::take(&self.key_captures, &keystroke, window, cx)
924        })
925    }
926
927    /// Create a themed scrollbar factory owned by this retained primitive.
928    /// Dragging is cancelled on unmount, suspension, disposal, Escape and window
929    /// deactivation by the same private coordinator as built-in controls.
930    #[must_use]
931    pub fn scrollbars(&self, theme: &PrimitiveTheme) -> crate::ScrollbarContext {
932        crate::ScrollbarContext::new(
933            self.interaction_owner("scrollbars"),
934            self.interactions.clone(),
935            theme,
936        )
937        .with_wheel_parents(self.wheel_parents.clone())
938    }
939
940    /// Resolve an explicitly provided, preloaded Host asset without provider
941    /// I/O or decoding on the render path. This never treats a URL as a resource
942    /// locator and grants no network authority to the primitive.
943    ///
944    /// # Errors
945    /// Returns an asset resolution error when unavailable, unknown or not yet
946    /// prepared. Hosts preload during setup or use the existing async decoder.
947    pub fn image_asset(&self, id: &crate::AssetId) -> Result<gpui::ImageSource, crate::AssetError> {
948        let assets = self.assets.clone().unwrap_or_default();
949        let image = assets.cached_image(id)?;
950        assets.image_source(image.opaque())
951    }
952    pub(crate) fn observes(&self, event: &str) -> bool {
953        self.callbacks.contains_key(event)
954    }
955
956    /// Prepare a semantic proposal without dispatching it yet.
957    ///
958    /// # Errors
959    ///
960    /// Returns declaration, schema, or released-registry errors.
961    pub fn prepare_proposal(
962        &self,
963        event: impl Into<String>,
964        payload: UiValue,
965    ) -> Result<PrimitiveSemanticProposal, PrimitiveError> {
966        let event = event.into();
967        let schema =
968            self.event_schemas
969                .get(&event)
970                .ok_or_else(|| PrimitiveError::UnknownEvent {
971                    primitive: self.primitive.clone(),
972                    event: event.clone(),
973                })?;
974        schema
975            .payload
976            .validate_ui_value(&payload)
977            .map_err(|source| PrimitiveError::InvalidEvent {
978                primitive: self.primitive.clone(),
979                event: event.clone(),
980                source,
981            })?;
982        Ok(PrimitiveSemanticProposal {
983            handler: self.callbacks.get(&event).cloned(),
984            event,
985            payload,
986        })
987    }
988
989    /// Normalize and dispatch a declared native primitive event.
990    ///
991    /// # Errors
992    ///
993    /// Returns schema and event declaration errors. Missing callback props are
994    /// treated as an intentionally unobserved event.
995    pub fn emit(
996        &self,
997        event: &str,
998        payload: UiValue,
999        window: &mut Window,
1000        cx: &mut App,
1001    ) -> Result<(), PrimitiveError> {
1002        let registry = PrimitiveRegistry {
1003            inner: self
1004                .registry
1005                .upgrade()
1006                .ok_or(PrimitiveError::RegistryReleased)?,
1007        };
1008        let payload = registry.normalize_event(&self.primitive, event, payload)?;
1009        if let Some(handler) = self.callbacks.get(event) {
1010            match handler {
1011                UiEventHandler::Script(callback) => {
1012                    if let Some(dispatcher) = self.dispatcher.as_ref() {
1013                        dispatcher.dispatch(callback.clone(), event, payload, None, window, cx);
1014                    }
1015                }
1016                UiEventHandler::Host(callback) => {
1017                    callback.invoke(payload, window, cx);
1018                }
1019                UiEventHandler::Native(reference) => {
1020                    if let Some(dispatcher) = self.dispatcher.as_ref() {
1021                        dispatcher.dispatch_native(
1022                            reference.clone(),
1023                            event.to_owned(),
1024                            payload,
1025                            None,
1026                            window,
1027                            cx,
1028                        );
1029                    }
1030                }
1031            }
1032        }
1033        Ok(())
1034    }
1035
1036    /// Queue one low-frequency semantic proposal after the active native input
1037    /// callback returns.
1038    ///
1039    /// Hot preview remains in native signals; Rhai or Host code observes only
1040    /// the final schema-checked proposal.
1041    pub fn propose(
1042        &self,
1043        event: impl Into<String>,
1044        payload: UiValue,
1045        window: &mut Window,
1046        cx: &mut App,
1047    ) {
1048        let context = self.clone();
1049        let event = event.into();
1050        window.defer(cx, move |window, cx| {
1051            let _ = context.emit(&event, payload, window, cx);
1052        });
1053    }
1054
1055    /// Write one primitive-owned native signal without invoking Rhai.
1056    ///
1057    /// # Errors
1058    ///
1059    /// Returns a stale or type error when the signal no longer belongs to the
1060    /// mounted component instance.
1061    pub fn write_signal(
1062        &self,
1063        signal: &crate::NativeSignal,
1064        value: crate::SignalValue,
1065        cx: &mut App,
1066    ) -> Result<bool, crate::SignalError> {
1067        self.dispatcher.as_ref().map_or_else(
1068            || Err(crate::SignalError::Stale(signal.id().clone())),
1069            |dispatcher| dispatcher.write_signal(signal.clone(), value, cx),
1070        )
1071    }
1072
1073    pub(crate) fn read_signal(
1074        &self,
1075        signal: &crate::NativeSignal,
1076        cx: &App,
1077    ) -> Result<crate::SignalValue, crate::SignalError> {
1078        self.dispatcher.as_ref().map_or_else(
1079            || Err(crate::SignalError::Stale(signal.id().clone())),
1080            |dispatcher| dispatcher.read_signal(signal, cx),
1081        )
1082    }
1083
1084    /// Atomically apply one related native-preview patch and request at most
1085    /// one repaint.
1086    ///
1087    /// # Errors
1088    ///
1089    /// Returns without changing any signal when a member is stale, duplicated,
1090    /// non-finite, or type-incompatible.
1091    pub fn write_signals(
1092        &self,
1093        updates: impl IntoIterator<Item = (crate::NativeSignal, crate::SignalValue)>,
1094        cx: &mut App,
1095    ) -> Result<bool, crate::SignalError> {
1096        let updates = updates.into_iter().collect::<Vec<_>>();
1097        let Some(dispatcher) = self.dispatcher.as_ref() else {
1098            return updates.first().map_or(Ok(false), |(signal, _)| {
1099                Err(crate::SignalError::Stale(signal.id().clone()))
1100            });
1101        };
1102        dispatcher.write_signals(updates, cx)
1103    }
1104
1105    /// Where dropped files go, when the Host lets this view take files the
1106    /// operating system drags in.
1107    pub(crate) const fn file_drops(&self) -> Option<&crate::DroppedFiles> {
1108        self.file_drops.as_ref()
1109    }
1110
1111    pub(crate) fn interaction_owner(&self, key: &str) -> crate::interaction::InteractionOwner {
1112        let owner = crate::interaction::InteractionOwner::new(
1113            self.view_id.clone(),
1114            format!("{}:{key}", self.primitive.as_str()),
1115        );
1116        if let Some(node) = self
1117            .retained_node
1118            .or_else(|| self.instance.as_ref().map(PrimitiveInstanceId::node))
1119        {
1120            owner.with_retained(node)
1121        } else {
1122            owner
1123        }
1124    }
1125
1126    pub(crate) fn begin_interaction(
1127        &self,
1128        gesture: crate::interaction::NativeGesture,
1129        window: &mut Window,
1130        cx: &mut App,
1131    ) {
1132        self.interactions.begin(gesture, window, cx);
1133    }
1134
1135    pub(crate) fn interaction_is_active(
1136        &self,
1137        owner: &crate::interaction::InteractionOwner,
1138    ) -> bool {
1139        self.interactions.is_active(owner)
1140    }
1141
1142    pub(crate) fn present_interaction(&self, owner: crate::interaction::InteractionOwner) {
1143        self.interactions.present(owner);
1144    }
1145
1146    pub(crate) fn cancel_interaction(
1147        &self,
1148        owner: &crate::interaction::InteractionOwner,
1149        window: &mut Window,
1150        cx: &mut App,
1151    ) -> bool {
1152        self.interactions.cancel_owner(owner, window, cx)
1153    }
1154
1155    pub(crate) fn register_interaction_cancellation(
1156        &self,
1157        owner: crate::interaction::InteractionOwner,
1158        notify: gpui::EntityId,
1159        cancel: impl Fn(&mut Window, &mut App) + 'static,
1160        window: &mut Window,
1161        cx: &mut App,
1162    ) {
1163        self.interactions
1164            .register_auxiliary(owner, notify, cancel, window, cx);
1165    }
1166
1167    pub(crate) fn clear_interaction_cancellation(
1168        &self,
1169        owner: &crate::interaction::InteractionOwner,
1170    ) {
1171        self.interactions.clear_auxiliary(owner);
1172    }
1173
1174    pub(crate) fn register_drop_target(&self, target: crate::interaction::DropTargetRegistration) {
1175        self.interactions.register_drop_target(target);
1176    }
1177
1178    pub(crate) fn drop_target_state(
1179        &self,
1180        owner: &crate::interaction::InteractionOwner,
1181    ) -> crate::interaction::DropTargetState {
1182        self.interactions.drop_target_state(owner)
1183    }
1184
1185    // A drag source passes its press, threshold and both endings through unchanged.
1186    #[allow(clippy::too_many_arguments)]
1187    pub(crate) fn begin_application_drag(
1188        &self,
1189        spec: crate::interaction::ApplicationDragSpec,
1190        position: gpui::Point<gpui::Pixels>,
1191        threshold: f64,
1192        on_end: impl Fn(crate::interaction::ApplicationDropResult, bool, &mut Window, &mut App)
1193        + 'static,
1194        on_tap: Option<crate::interaction::TapHandler>,
1195        window: &mut Window,
1196        cx: &mut App,
1197    ) {
1198        let gesture = crate::interaction::application_drag_gesture(
1199            self.interactions.clone(),
1200            position,
1201            spec.notify(),
1202            spec,
1203            threshold,
1204            on_end,
1205            on_tap,
1206        );
1207        self.interactions.begin(gesture, window, cx);
1208    }
1209
1210    pub(crate) fn perform_keyboard_drop(
1211        &self,
1212        spec: &crate::interaction::ApplicationDragSpec,
1213        target_id: &str,
1214        window: &mut Window,
1215        cx: &mut App,
1216    ) -> crate::interaction::ApplicationDropResult {
1217        self.interactions
1218            .perform_keyboard_drop(spec, target_id, window, cx)
1219    }
1220
1221    pub(crate) fn app_drag_source_active(
1222        &self,
1223        owner: &crate::interaction::InteractionOwner,
1224    ) -> bool {
1225        self.interactions.app_drag_source_active(owner)
1226    }
1227
1228    pub(crate) fn ancestor_scroll_handles(&self) -> Vec<gpui::ScrollHandle> {
1229        self.scroll_handles.clone()
1230    }
1231
1232    /// Whether the node hosting the primitive has keyboard focus.
1233    #[must_use]
1234    pub fn is_focused(&self, window: &Window) -> bool {
1235        self.focus_handle
1236            .as_ref()
1237            .is_some_and(|handle| handle.is_focused(window))
1238    }
1239
1240    /// Whether the view shows focus indicators this frame
1241    /// (`ScriptViewConfig::focus_indicators`); a primitive that paints its own
1242    /// focus state paints it only then.
1243    #[must_use]
1244    pub const fn focus_indicators(&self) -> bool {
1245        self.focus_indicators
1246    }
1247
1248    /// Read the last committed layout bounds for a primitive-owned element ref.
1249    #[must_use]
1250    pub fn element_bounds(
1251        &self,
1252        reference: &crate::ElementRef,
1253        cx: &App,
1254    ) -> Option<crate::GeometryBounds> {
1255        self.dispatcher
1256            .as_ref()
1257            .and_then(|dispatcher| dispatcher.element_bounds(reference, cx))
1258    }
1259
1260    /// This frame's hitbox of the node holding `reference`: hovered only where
1261    /// the node is visible and nothing occluding sits above it.
1262    pub(crate) fn element_hitbox(
1263        &self,
1264        reference: &crate::ElementRef,
1265        cx: &App,
1266    ) -> Option<gpui::HitboxId> {
1267        self.dispatcher
1268            .as_ref()
1269            .and_then(|dispatcher| dispatcher.element_hitbox(reference, cx))
1270    }
1271
1272    pub(crate) fn canvas_local_point(
1273        &self,
1274        reference: &crate::ElementRef,
1275        point: gpui::Point<gpui::Pixels>,
1276        cx: &App,
1277    ) -> Option<(f64, f64)> {
1278        self.dispatcher.as_ref().and_then(|dispatcher| {
1279            dispatcher.canvas_local_point(reference, (f64::from(point.x), f64::from(point.y)), cx)
1280        })
1281    }
1282
1283    pub(crate) fn canvas_bounds(
1284        &self,
1285        reference: &crate::ElementRef,
1286        cx: &App,
1287    ) -> Option<crate::GeometryBounds> {
1288        self.dispatcher
1289            .as_ref()
1290            .and_then(|dispatcher| dispatcher.canvas_bounds(reference, cx))
1291    }
1292}
1293
1294pub trait PrimitiveHandler {
1295    /// Return deterministic work units for this validated effect instance.
1296    /// Non-effect primitives ignore this value.
1297    fn effect_cost(&self, _instance: &PrimitiveInstance) -> usize {
1298        1
1299    }
1300
1301    /// Contribute a bounded semantic summary for the retained primitive node.
1302    /// Native internals remain private; accessibility and automation receive
1303    /// only durable, already-presented values.
1304    fn accessibility(
1305        &self,
1306        _instance: &PrimitiveInstanceId,
1307        _cx: &App,
1308    ) -> Option<PrimitiveAccessibilityProjection> {
1309        None
1310    }
1311
1312    /// Actions that the native primitive can perform for assistive technology.
1313    ///
1314    /// The default is intentionally empty: a primitive must not advertise an
1315    /// operation merely because its outer Rhai node has a compatible role.
1316    fn accessibility_actions(
1317        &self,
1318        _instance: &PrimitiveInstanceId,
1319    ) -> Vec<gpui::AccessibleAction> {
1320        Vec::new()
1321    }
1322
1323    /// Whether this primitive owns one primary native focus target.
1324    ///
1325    /// The runtime allocates and retains that identity before rendering so the
1326    /// declarative wrapper and native control share it from their first frame.
1327    fn uses_primary_focus(&self) -> bool {
1328        false
1329    }
1330
1331    /// Perform one previously advertised accessibility action.
1332    ///
1333    /// # Errors
1334    ///
1335    /// Returns a bounded diagnostic when the instance is stale, disabled, or
1336    /// the platform payload is invalid for the action.
1337    fn perform_accessibility_action(
1338        &mut self,
1339        _instance: &PrimitiveInstanceId,
1340        _action: gpui::AccessibleAction,
1341        _data: Option<&gpui::accesskit::ActionData>,
1342        _window: &mut Window,
1343        _cx: &mut App,
1344    ) -> Result<(), String> {
1345        Err("primitive does not support accessibility actions".to_owned())
1346    }
1347
1348    /// Perform a native key semantic for automation using the same policy as
1349    /// the real focused control.
1350    ///
1351    /// # Errors
1352    ///
1353    /// Returns a bounded primitive diagnostic when the native semantic cannot
1354    /// be evaluated.
1355    fn perform_key(
1356        &mut self,
1357        _instance: &PrimitiveInstanceId,
1358        _key: &str,
1359    ) -> Result<Option<PrimitiveSemanticProposal>, String> {
1360        Ok(None)
1361    }
1362
1363    /// Called once before the first render of a keyed lifecycle primitive.
1364    ///
1365    /// # Errors
1366    ///
1367    /// Returns a diagnostic message when native setup fails.
1368    fn mount(&mut self, _instance: &PrimitiveInstance) -> Result<(), String> {
1369        Ok(())
1370    }
1371
1372    /// Apply a validated prop/style/event snapshot to an existing keyed instance.
1373    ///
1374    /// # Errors
1375    ///
1376    /// Returns a diagnostic message when the retained native update fails.
1377    fn update(
1378        &mut self,
1379        _previous: &PrimitiveInstance,
1380        _next: &PrimitiveInstance,
1381    ) -> Result<(), String> {
1382        Ok(())
1383    }
1384
1385    /// Prepare one retained native instance to cross into suspended state.
1386    /// Implementations must be idempotent because a failed peer is compensated
1387    /// and the whole operation may be retried.
1388    fn suspend(&mut self, _instance: &PrimitiveInstanceId, _cx: &mut App) {}
1389
1390    /// Prepare one suspended native instance to become active. The public view
1391    /// is not marked active until every primitive and the script transaction succeed.
1392    fn resume(&mut self, _instance: &PrimitiveInstanceId, _cx: &mut App) {}
1393
1394    /// Commit a successfully prepared resume after the script transaction has
1395    /// also succeeded. Activity time and event delivery may begin here.
1396    fn commit_resume(&mut self, _instance: &PrimitiveInstanceId, _cx: &mut App) {}
1397
1398    /// Render the primitive into a native GPUI element.
1399    ///
1400    /// # Errors
1401    ///
1402    /// Returns a diagnostic message when native rendering fails.
1403    fn render(
1404        &mut self,
1405        instance: &PrimitiveInstance,
1406        events: &PrimitiveContext,
1407        theme: &PrimitiveTheme,
1408        window: &mut Window,
1409        cx: &mut App,
1410    ) -> Result<AnyElement, String>;
1411
1412    /// Called when a previously mounted keyed primitive is no longer reachable.
1413    fn unmount(&mut self, _instance: &PrimitiveInstanceId) {}
1414}
1415
1416#[derive(Clone, Debug, Default, PartialEq)]
1417pub struct PrimitiveAccessibilityProjection {
1418    pub description: String,
1419    pub value: Option<UiValue>,
1420}
1421
1422struct PrimitiveEntry {
1423    descriptor: PrimitiveDescriptor,
1424    handler: Box<dyn PrimitiveHandler>,
1425}
1426
1427#[derive(Default)]
1428struct PrimitiveRegistryInner {
1429    entries: BTreeMap<PrimitiveId, PrimitiveEntry>,
1430    mounted: BTreeMap<PrimitiveInstanceId, PrimitiveInstance>,
1431    generation: ScriptGeneration,
1432    /// Where `DropZone`s keep the files the operating system drops, when the
1433    /// Host accepts file drops ([`crate::ScriptView::accept_file_drops`]).
1434    file_drops: Option<crate::DroppedFiles>,
1435}
1436
1437#[derive(Clone, Default)]
1438pub struct PrimitiveRegistry {
1439    inner: Rc<RefCell<PrimitiveRegistryInner>>,
1440}
1441
1442impl fmt::Debug for PrimitiveRegistry {
1443    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1444        match self.inner.try_borrow() {
1445            Ok(inner) => formatter
1446                .debug_struct("PrimitiveRegistry")
1447                .field("registered", &inner.entries.keys().collect::<Vec<_>>())
1448                .field("mounted", &inner.mounted.keys().collect::<Vec<_>>())
1449                .finish(),
1450            Err(_) => formatter.write_str("PrimitiveRegistry(<borrowed>)"),
1451        }
1452    }
1453}
1454
1455impl PrimitiveRegistry {
1456    pub(crate) fn generation(&self) -> ScriptGeneration {
1457        self.inner.borrow().generation
1458    }
1459
1460    /// Let `DropZone`s with the `os.files` payload type take files the
1461    /// operating system drags in, kept in `files`; `None` turns it off.
1462    pub(crate) fn set_file_drops(&self, files: Option<crate::DroppedFiles>) {
1463        self.inner.borrow_mut().file_drops = files;
1464    }
1465
1466    pub(crate) fn set_generation(&self, generation: ScriptGeneration) {
1467        self.inner.borrow_mut().generation = generation;
1468    }
1469
1470    /// The descriptors of every registered primitive, in id order.
1471    #[must_use]
1472    pub fn descriptors(&self) -> Vec<PrimitiveDescriptor> {
1473        self.inner
1474            .borrow()
1475            .entries
1476            .values()
1477            .map(|entry| entry.descriptor.clone())
1478            .collect()
1479    }
1480
1481    #[must_use]
1482    pub fn new() -> Self {
1483        Self::default()
1484    }
1485
1486    /// Register a validated primitive descriptor and native handler.
1487    ///
1488    /// # Errors
1489    ///
1490    /// Returns [`PrimitiveError`] for duplicate IDs, invalid exports/defaults,
1491    /// or missing callback props for declared events.
1492    pub fn register(
1493        &self,
1494        descriptor: PrimitiveDescriptor,
1495        handler: impl PrimitiveHandler + 'static,
1496    ) -> Result<(), PrimitiveError> {
1497        validate_descriptor(&descriptor)?;
1498        let mut inner = self
1499            .inner
1500            .try_borrow_mut()
1501            .map_err(|_| PrimitiveError::Borrowed)?;
1502        if inner.entries.contains_key(&descriptor.id) {
1503            return Err(PrimitiveError::Duplicate(descriptor.id));
1504        }
1505        if inner.entries.values().any(|entry| {
1506            entry.descriptor.id.namespace() == descriptor.id.namespace()
1507                && entry.descriptor.export == descriptor.export
1508        }) {
1509            return Err(PrimitiveError::DuplicateExport {
1510                namespace: descriptor.id.namespace().to_owned(),
1511                export: descriptor.export,
1512            });
1513        }
1514        inner.entries.insert(
1515            descriptor.id.clone(),
1516            PrimitiveEntry {
1517                descriptor,
1518                handler: Box::new(handler),
1519            },
1520        );
1521        Ok(())
1522    }
1523
1524    /// Convert validated Rhai props into a custom `UiNode`.
1525    ///
1526    /// # Errors
1527    ///
1528    /// Returns [`PrimitiveError`] for unknown primitives, invalid props, or a
1529    /// missing key on stateful/lifecycle instances.
1530    pub fn create_node(
1531        &self,
1532        id: &PrimitiveId,
1533        key: Option<String>,
1534        props: &Map,
1535        generation: ScriptGeneration,
1536    ) -> Result<UiNode, PrimitiveError> {
1537        let inner = self
1538            .inner
1539            .try_borrow()
1540            .map_err(|_| PrimitiveError::Borrowed)?;
1541        let descriptor = &inner
1542            .entries
1543            .get(id)
1544            .ok_or_else(|| PrimitiveError::Unknown(id.clone()))?
1545            .descriptor;
1546        if (descriptor.lifecycle || !descriptor.state.is_empty()) && key.is_none() {
1547            return Err(PrimitiveError::MissingKey(id.clone()));
1548        }
1549        let schema = ValueSchema::object(descriptor.props.clone());
1550        schema
1551            .validate(&Dynamic::from_map(props.clone()))
1552            .map_err(|source| PrimitiveError::InvalidProps {
1553                primitive: id.clone(),
1554                source,
1555            })?;
1556        let props = convert_props(&descriptor.props, props, generation)?;
1557        Ok(UiNode::custom(PrimitiveNode {
1558            primitive: id.clone(),
1559            key,
1560            props,
1561        }))
1562    }
1563
1564    /// Validate an event emitted by a native primitive adapter.
1565    ///
1566    /// # Errors
1567    ///
1568    /// Returns [`PrimitiveError`] for unknown events or invalid payloads.
1569    pub fn normalize_event(
1570        &self,
1571        id: &PrimitiveId,
1572        event: &str,
1573        payload: UiValue,
1574    ) -> Result<UiValue, PrimitiveError> {
1575        let inner = self
1576            .inner
1577            .try_borrow()
1578            .map_err(|_| PrimitiveError::Borrowed)?;
1579        let descriptor = &inner
1580            .entries
1581            .get(id)
1582            .ok_or_else(|| PrimitiveError::Unknown(id.clone()))?
1583            .descriptor;
1584        let schema = descriptor
1585            .events
1586            .get(event)
1587            .ok_or_else(|| PrimitiveError::UnknownEvent {
1588                primitive: id.clone(),
1589                event: event.to_owned(),
1590            })?;
1591        schema
1592            .payload
1593            .validate_ui_value(&payload)
1594            .map_err(|source| PrimitiveError::InvalidEvent {
1595                primitive: id.clone(),
1596                event: event.to_owned(),
1597                source,
1598            })?;
1599        Ok(payload)
1600    }
1601
1602    pub(crate) fn accessibility_projections(
1603        &self,
1604        tree: &crate::RetainedUiTree,
1605        cx: &App,
1606    ) -> BTreeMap<crate::NodeId, PrimitiveAccessibilityProjection> {
1607        let Ok(inner) = self.inner.try_borrow() else {
1608            return BTreeMap::new();
1609        };
1610        tree.nodes()
1611            .filter_map(|node| {
1612                let primitive = node.primitive()?.clone();
1613                let instance = PrimitiveInstanceId {
1614                    primitive: primitive.clone(),
1615                    key: node.key()?.to_owned(),
1616                    node: node.id(),
1617                };
1618                let projection = inner
1619                    .entries
1620                    .get(&primitive)?
1621                    .handler
1622                    .accessibility(&instance, cx)?;
1623                Some((node.id(), projection))
1624            })
1625            .collect()
1626    }
1627
1628    pub(crate) fn accessibility_actions(
1629        &self,
1630        instance: &PrimitiveInstanceId,
1631    ) -> Vec<gpui::AccessibleAction> {
1632        let Ok(inner) = self.inner.try_borrow() else {
1633            return Vec::new();
1634        };
1635        inner
1636            .entries
1637            .get(&instance.primitive)
1638            .map_or_else(Vec::new, |entry| {
1639                entry.handler.accessibility_actions(instance)
1640            })
1641    }
1642
1643    /// Registrations so far. A registration is never replaced or removed, so
1644    /// anything derived from the registered primitives holds while this does.
1645    pub(crate) fn epoch(&self) -> usize {
1646        self.inner
1647            .try_borrow()
1648            .map_or(0, |inner| inner.entries.len())
1649    }
1650
1651    pub(crate) fn uses_primary_focus(&self, primitive: &PrimitiveId) -> bool {
1652        self.inner.try_borrow().is_ok_and(|inner| {
1653            inner
1654                .entries
1655                .get(primitive)
1656                .is_some_and(|entry| entry.handler.uses_primary_focus())
1657        })
1658    }
1659
1660    pub(crate) fn perform_accessibility_action(
1661        &self,
1662        instance: &PrimitiveInstanceId,
1663        action: gpui::AccessibleAction,
1664        data: Option<&gpui::accesskit::ActionData>,
1665        window: &mut Window,
1666        cx: &mut App,
1667    ) -> Result<(), PrimitiveError> {
1668        let mut inner = self
1669            .inner
1670            .try_borrow_mut()
1671            .map_err(|_| PrimitiveError::Borrowed)?;
1672        if !inner.mounted.contains_key(instance) {
1673            return Err(PrimitiveError::MissingInstance(instance.clone()));
1674        }
1675        let entry = inner
1676            .entries
1677            .get_mut(&instance.primitive)
1678            .ok_or_else(|| PrimitiveError::Unknown(instance.primitive.clone()))?;
1679        guard_primitive_panic(&instance.primitive, "accessibility action", || {
1680            entry
1681                .handler
1682                .perform_accessibility_action(instance, action, data, window, cx)
1683        })?
1684        .map_err(|message| PrimitiveError::Handler {
1685            primitive: instance.primitive.clone(),
1686            message,
1687        })
1688    }
1689
1690    pub(crate) fn perform_key(
1691        &self,
1692        instance: &PrimitiveInstanceId,
1693        key: &str,
1694    ) -> Result<Option<PrimitiveSemanticProposal>, PrimitiveError> {
1695        let mut inner = self
1696            .inner
1697            .try_borrow_mut()
1698            .map_err(|_| PrimitiveError::Borrowed)?;
1699        if !inner.mounted.contains_key(instance) {
1700            return Err(PrimitiveError::MissingInstance(instance.clone()));
1701        }
1702        let entry = inner
1703            .entries
1704            .get_mut(&instance.primitive)
1705            .ok_or_else(|| PrimitiveError::Unknown(instance.primitive.clone()))?;
1706        guard_primitive_panic(&instance.primitive, "key semantic", || {
1707            entry.handler.perform_key(instance, key)
1708        })?
1709        .map_err(|message| PrimitiveError::Handler {
1710            primitive: instance.primitive.clone(),
1711            message,
1712        })
1713    }
1714
1715    /// Unmount keyed lifecycle instances absent from the successful node tree.
1716    ///
1717    /// # Errors
1718    ///
1719    /// Returns [`PrimitiveError::Borrowed`] during a conflicting render borrow.
1720    pub fn retain_mounted(
1721        &self,
1722        active: &BTreeSet<PrimitiveInstanceId>,
1723    ) -> Result<(), PrimitiveError> {
1724        let mut inner = self
1725            .inner
1726            .try_borrow_mut()
1727            .map_err(|_| PrimitiveError::Borrowed)?;
1728        let removed = inner
1729            .mounted
1730            .keys()
1731            .filter(|instance| !active.contains(*instance))
1732            .cloned()
1733            .collect::<Vec<_>>();
1734        let mut first_error = None;
1735        for instance in &removed {
1736            let resources = inner
1737                .mounted
1738                .get(instance)
1739                .and_then(|mounted| mounted.resources.clone());
1740            if let Some(entry) = inner.entries.get_mut(&instance.primitive)
1741                && let Err(error) = guard_primitive_panic(&instance.primitive, "unmount", || {
1742                    entry.handler.unmount(instance);
1743                })
1744                && first_error.is_none()
1745            {
1746                first_error = Some(error);
1747            }
1748            if let Some(resources) = resources
1749                && let Err(error) = resources.close()
1750                && first_error.is_none()
1751            {
1752                first_error = Some(PrimitiveError::Resource(error));
1753            }
1754            inner.mounted.remove(instance);
1755        }
1756        first_error.map_or(Ok(()), Err)
1757    }
1758
1759    /// Unmount keyed primitive instances absent from the current successful tree.
1760    ///
1761    /// # Errors
1762    ///
1763    /// Returns borrow or panic-boundary errors from native unmount handlers.
1764    pub fn retain_tree(&self, tree: &crate::RetainedUiTree) -> Result<(), PrimitiveError> {
1765        let active = collect_primitive_instances(tree);
1766        self.retain_mounted(&active)
1767    }
1768
1769    pub(crate) fn suspend_mounted(&self, cx: &mut App) -> Result<(), PrimitiveError> {
1770        let mut inner = self
1771            .inner
1772            .try_borrow_mut()
1773            .map_err(|_| PrimitiveError::Borrowed)?;
1774        let instances = inner.mounted.keys().cloned().collect::<Vec<_>>();
1775        let mut first_error = None;
1776        for instance in instances {
1777            if let Some(entry) = inner.entries.get_mut(&instance.primitive)
1778                && let Err(error) = guard_primitive_panic(&instance.primitive, "suspend", || {
1779                    entry.handler.suspend(&instance, cx);
1780                })
1781                && first_error.is_none()
1782            {
1783                first_error = Some(error);
1784            }
1785        }
1786        first_error.map_or(Ok(()), Err)
1787    }
1788
1789    pub(crate) fn resume_mounted(&self, cx: &mut App) -> Result<(), PrimitiveError> {
1790        let mut inner = self
1791            .inner
1792            .try_borrow_mut()
1793            .map_err(|_| PrimitiveError::Borrowed)?;
1794        let instances = inner.mounted.keys().cloned().collect::<Vec<_>>();
1795        let mut first_error = None;
1796        for instance in instances {
1797            if let Some(entry) = inner.entries.get_mut(&instance.primitive)
1798                && let Err(error) = guard_primitive_panic(&instance.primitive, "resume", || {
1799                    entry.handler.resume(&instance, cx);
1800                })
1801                && first_error.is_none()
1802            {
1803                first_error = Some(error);
1804            }
1805        }
1806        first_error.map_or(Ok(()), Err)
1807    }
1808
1809    pub(crate) fn commit_resume_mounted(&self, cx: &mut App) -> Result<(), PrimitiveError> {
1810        let mut inner = self
1811            .inner
1812            .try_borrow_mut()
1813            .map_err(|_| PrimitiveError::Borrowed)?;
1814        let instances = inner.mounted.keys().cloned().collect::<Vec<_>>();
1815        let mut first_error = None;
1816        for instance in instances {
1817            if let Some(entry) = inner.entries.get_mut(&instance.primitive)
1818                && let Err(error) =
1819                    guard_primitive_panic(&instance.primitive, "commit resume", || {
1820                        entry.handler.commit_resume(&instance, cx);
1821                    })
1822                && first_error.is_none()
1823            {
1824                first_error = Some(error);
1825            }
1826        }
1827        first_error.map_or(Ok(()), Err)
1828    }
1829
1830    pub(crate) fn element(
1831        &self,
1832        node: PrimitiveNode,
1833        retained: Option<(crate::NodeId, String)>,
1834        focus_handle: Option<gpui::FocusHandle>,
1835        fallback: Option<UiNode>,
1836        runtime: PrimitiveWindowContext,
1837        theme: PrimitiveTheme,
1838    ) -> AnyElement {
1839        RegisteredPrimitiveElement {
1840            registry: self.clone(),
1841            node,
1842            retained,
1843            focus_handle,
1844            fallback,
1845            runtime,
1846            theme,
1847        }
1848        .into_any_element()
1849    }
1850
1851    #[allow(clippy::too_many_lines)]
1852    fn render_instance(
1853        &self,
1854        node: PrimitiveNode,
1855        identity: PrimitiveRenderIdentity,
1856        events: &PrimitiveContext,
1857        theme: &PrimitiveTheme,
1858        window: &mut Window,
1859        cx: &mut App,
1860    ) -> Result<AnyElement, PrimitiveError> {
1861        let mut inner = self
1862            .inner
1863            .try_borrow_mut()
1864            .map_err(|_| PrimitiveError::Borrowed)?;
1865        let retained_instance = primitive_is_retained(&inner, &node.primitive)?;
1866        if retained_instance && identity.retained_id.is_none() {
1867            return Err(PrimitiveError::MissingRetainedIdentity(node.primitive));
1868        }
1869        let instance_id = retained_instance.then(|| PrimitiveInstanceId {
1870            primitive: node.primitive.clone(),
1871            key: identity
1872                .retained_key
1873                .clone()
1874                .expect("retained primitive descriptors require a retained key"),
1875            node: identity
1876                .retained_id
1877                .expect("retained primitive renderer supplies NodeId"),
1878        });
1879        let previous = instance_id
1880            .as_ref()
1881            .and_then(|id| inner.mounted.get(id))
1882            .cloned();
1883        let resources = if retained_instance {
1884            Some(
1885                previous
1886                    .as_ref()
1887                    .and_then(|instance| instance.resources.clone())
1888                    .unwrap_or_default(),
1889            )
1890        } else {
1891            None
1892        };
1893        let checkpoint = resources
1894            .as_ref()
1895            .map(PrimitiveResourceScope::checkpoint)
1896            .transpose()?;
1897        let instance = PrimitiveInstance {
1898            id: instance_id.clone(),
1899            node,
1900            resources: resources.clone(),
1901            focus_handle: identity.focus_handle,
1902        };
1903        let needs_mount = instance_id.is_some() && previous.is_none();
1904        if needs_mount
1905            && let Some(effect) = inner
1906                .entries
1907                .get(&instance.node.primitive)
1908                .and_then(|entry| entry.descriptor.effect.as_ref())
1909        {
1910            let mounted = inner
1911                .mounted
1912                .keys()
1913                .filter(|id| id.primitive == instance.node.primitive)
1914                .count();
1915            if mounted >= effect.max_instances {
1916                return Err(PrimitiveError::EffectInstanceBudget {
1917                    primitive: instance.node.primitive.clone(),
1918                    actual: mounted.saturating_add(1),
1919                    limit: effect.max_instances,
1920                });
1921            }
1922        }
1923        let intrinsic_generation = inner.generation;
1924        let entry = inner
1925            .entries
1926            .get_mut(&instance.node.primitive)
1927            .ok_or_else(|| PrimitiveError::Unknown(instance.node.primitive.clone()))?;
1928        if let Some(effect) = &entry.descriptor.effect {
1929            let cost = guard_primitive_panic(&instance.node.primitive, "effect_cost", || {
1930                entry.handler.effect_cost(&instance)
1931            })?;
1932            if cost > effect.max_cost_per_instance {
1933                return Err(PrimitiveError::EffectCostBudget {
1934                    primitive: instance.node.primitive.clone(),
1935                    actual: cost,
1936                    limit: effect.max_cost_per_instance,
1937                });
1938            }
1939        }
1940        let operation = (|| {
1941            if needs_mount {
1942                guard_primitive_panic(&instance.node.primitive, "mount", || {
1943                    entry.handler.mount(&instance)
1944                })?
1945                .map_err(|message| PrimitiveError::Handler {
1946                    primitive: instance.node.primitive.clone(),
1947                    message,
1948                })?;
1949            }
1950            if let Some(previous) = &previous
1951                && previous.node != instance.node
1952            {
1953                guard_primitive_panic(&instance.node.primitive, "update", || {
1954                    entry.handler.update(previous, &instance)
1955                })?
1956                .map_err(|message| PrimitiveError::Handler {
1957                    primitive: instance.node.primitive.clone(),
1958                    message,
1959                })?;
1960            }
1961            let mut scoped_events = events.clone();
1962            scoped_events.instance.clone_from(&instance_id);
1963            scoped_events.intrinsic_generation = intrinsic_generation;
1964            scoped_events.intrinsic_lease = resources
1965                .as_ref()
1966                .map(|resources| Rc::downgrade(&resources.inner));
1967            guard_primitive_panic(&instance.node.primitive, "render", || {
1968                entry
1969                    .handler
1970                    .render(&instance, &scoped_events, theme, window, cx)
1971            })?
1972            .map_err(|message| PrimitiveError::Handler {
1973                primitive: instance.node.primitive.clone(),
1974                message,
1975            })
1976        })();
1977        let element = match operation {
1978            Ok(element) => element,
1979            Err(error) => {
1980                return Err(rollback_failed_primitive_operation(
1981                    entry,
1982                    &instance,
1983                    needs_mount,
1984                    resources.as_ref(),
1985                    checkpoint,
1986                    error,
1987                ));
1988            }
1989        };
1990        if let Some(id) = instance_id {
1991            inner.mounted.insert(id, instance);
1992        }
1993        Ok(element)
1994    }
1995}
1996
1997fn rollback_failed_primitive_operation(
1998    entry: &mut PrimitiveEntry,
1999    instance: &PrimitiveInstance,
2000    needs_unmount: bool,
2001    resources: Option<&PrimitiveResourceScope>,
2002    checkpoint: Option<u64>,
2003    original: PrimitiveError,
2004) -> PrimitiveError {
2005    let mut rollback_error = None;
2006    if needs_unmount
2007        && let Some(instance_id) = instance.id.as_ref()
2008        && let Err(error) =
2009            guard_primitive_panic(&instance.node.primitive, "failed-mount unmount", || {
2010                entry.handler.unmount(instance_id);
2011            })
2012    {
2013        rollback_error = Some(error);
2014    }
2015    if let (Some(resources), Some(checkpoint)) = (resources, checkpoint)
2016        && let Err(error) = resources.rollback(checkpoint)
2017        && rollback_error.is_none()
2018    {
2019        rollback_error = Some(PrimitiveError::Resource(error));
2020    }
2021    rollback_error.unwrap_or(original)
2022}
2023
2024fn primitive_is_retained(
2025    inner: &PrimitiveRegistryInner,
2026    primitive: &PrimitiveId,
2027) -> Result<bool, PrimitiveError> {
2028    let descriptor = &inner
2029        .entries
2030        .get(primitive)
2031        .ok_or_else(|| PrimitiveError::Unknown(primitive.clone()))?
2032        .descriptor;
2033    Ok(descriptor.lifecycle || !descriptor.state.is_empty())
2034}
2035
2036fn collect_primitive_instances(tree: &crate::RetainedUiTree) -> BTreeSet<PrimitiveInstanceId> {
2037    tree.host_nodes()
2038        .into_iter()
2039        .filter_map(|node| {
2040            Some(PrimitiveInstanceId {
2041                primitive: node.primitive()?.clone(),
2042                key: node.key()?.to_owned(),
2043                node: node.id(),
2044            })
2045        })
2046        .collect()
2047}
2048
2049fn guard_primitive_panic<T>(
2050    primitive: &PrimitiveId,
2051    phase: &'static str,
2052    operation: impl FnOnce() -> T,
2053) -> Result<T, PrimitiveError> {
2054    catch_unwind(AssertUnwindSafe(operation)).map_err(|_| PrimitiveError::Panic {
2055        primitive: primitive.clone(),
2056        phase,
2057    })
2058}
2059
2060#[derive(gpui::IntoElement)]
2061struct RegisteredPrimitiveElement {
2062    registry: PrimitiveRegistry,
2063    node: PrimitiveNode,
2064    retained: Option<(crate::NodeId, String)>,
2065    focus_handle: Option<gpui::FocusHandle>,
2066    fallback: Option<UiNode>,
2067    runtime: PrimitiveWindowContext,
2068    theme: PrimitiveTheme,
2069}
2070
2071#[derive(Clone)]
2072pub(crate) struct PrimitiveWindowContext {
2073    assets: Option<crate::AssetRegistry>,
2074    dispatcher: Option<NodeEventDispatcher>,
2075    interactions: crate::interaction::WindowInteractionCoordinator,
2076    scroll_handles: Vec<gpui::ScrollHandle>,
2077    wheel_parents: Vec<crate::scrollbar::ScrollWheelSource>,
2078    key_captures: Vec<crate::renderer::KeyCaptureScope>,
2079    intrinsic_size: Option<crate::intrinsic::IntrinsicSizeInvalidator>,
2080    view_id: String,
2081    focus_indicators: bool,
2082    /// The focus handle of the node that hosts a primitive without a primary
2083    /// focus of its own: the node tracks it, the primitive only reads it.
2084    host_focus: Option<gpui::FocusHandle>,
2085}
2086
2087impl PrimitiveWindowContext {
2088    pub(crate) fn with_assets(mut self, assets: Option<crate::AssetRegistry>) -> Self {
2089        self.assets = assets;
2090        self
2091    }
2092    pub(crate) fn new(
2093        dispatcher: Option<NodeEventDispatcher>,
2094        interactions: crate::interaction::WindowInteractionCoordinator,
2095        scroll_handles: Vec<gpui::ScrollHandle>,
2096        view_id: impl Into<String>,
2097    ) -> Self {
2098        Self {
2099            assets: None,
2100            dispatcher,
2101            interactions,
2102            scroll_handles,
2103            wheel_parents: Vec::new(),
2104            key_captures: Vec::new(),
2105            intrinsic_size: None,
2106            view_id: view_id.into(),
2107            focus_indicators: true,
2108            host_focus: None,
2109        }
2110    }
2111
2112    pub(crate) fn with_focus_indicators(mut self, shown: bool) -> Self {
2113        self.focus_indicators = shown;
2114        self
2115    }
2116
2117    /// The hosting node's focus handle, for a primitive that paints its host's focus
2118    /// (a `SplitPane` handle's grip) without owning a focus target.
2119    pub(crate) fn with_host_focus(mut self, handle: Option<gpui::FocusHandle>) -> Self {
2120        self.host_focus = handle;
2121        self
2122    }
2123
2124    pub(crate) fn with_wheel_parents(
2125        mut self,
2126        parents: Vec<crate::scrollbar::ScrollWheelSource>,
2127    ) -> Self {
2128        self.wheel_parents = parents;
2129        self
2130    }
2131
2132    pub(crate) fn with_key_captures(
2133        mut self,
2134        scopes: Vec<crate::renderer::KeyCaptureScope>,
2135    ) -> Self {
2136        self.key_captures = scopes;
2137        self
2138    }
2139
2140    pub(crate) fn with_intrinsic_size(
2141        mut self,
2142        invalidator: Option<crate::intrinsic::IntrinsicSizeInvalidator>,
2143    ) -> Self {
2144        self.intrinsic_size = invalidator;
2145        self
2146    }
2147}
2148
2149struct PrimitiveRenderIdentity {
2150    retained_id: Option<crate::NodeId>,
2151    retained_key: Option<String>,
2152    focus_handle: Option<gpui::FocusHandle>,
2153}
2154
2155impl RenderOnce for RegisteredPrimitiveElement {
2156    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
2157        let registry = self.registry;
2158        let callbacks = self
2159            .node
2160            .props
2161            .iter()
2162            .filter_map(|(name, value)| {
2163                name.strip_prefix("on_").and_then(|event| match value {
2164                    PrimitiveValue::Callback(callback) => {
2165                        Some((event.to_owned(), callback.clone()))
2166                    }
2167                    _ => None,
2168                })
2169            })
2170            .collect();
2171        let events = PrimitiveContext {
2172            assets: self.runtime.assets,
2173            registry: Rc::downgrade(&registry.inner),
2174            primitive: self.node.primitive.clone(),
2175            event_schemas: registry
2176                .inner
2177                .borrow()
2178                .entries
2179                .get(&self.node.primitive)
2180                .map(|entry| entry.descriptor.events.clone())
2181                .unwrap_or_default(),
2182            callbacks,
2183            dispatcher: self.runtime.dispatcher,
2184            interactions: self.runtime.interactions,
2185            scroll_handles: self.runtime.scroll_handles,
2186            wheel_parents: self.runtime.wheel_parents,
2187            key_captures: self.runtime.key_captures,
2188            intrinsic_size: self.runtime.intrinsic_size,
2189            intrinsic_generation: ScriptGeneration::default(),
2190            intrinsic_lease: None,
2191            view_id: self.runtime.view_id,
2192            instance: None,
2193            retained_node: self.retained.as_ref().map(|(node, _)| *node),
2194            focus_handle: self.focus_handle.clone().or(self.runtime.host_focus),
2195            focus_indicators: self.runtime.focus_indicators,
2196            file_drops: registry.inner.borrow().file_drops.clone(),
2197        };
2198        match registry.render_instance(
2199            self.node,
2200            PrimitiveRenderIdentity {
2201                retained_id: self.retained.as_ref().map(|(node, _)| *node),
2202                retained_key: self.retained.map(|(_, key)| key),
2203                focus_handle: self.focus_handle,
2204            },
2205            &events,
2206            &self.theme,
2207            window,
2208            cx,
2209        ) {
2210            Ok(element) => element,
2211            Err(error) => self.fallback.map_or_else(
2212                || {
2213                    div()
2214                        .child(format!("Custom primitive error: {error}"))
2215                        .into_any_element()
2216                },
2217                |fallback| {
2218                    crate::GpuiNodeRenderer::render_with_primitives(
2219                        &fallback,
2220                        &crate::LiteralColorResolver,
2221                        &crate::InteractionState::default(),
2222                        &registry,
2223                    )
2224                },
2225            ),
2226        }
2227    }
2228}
2229
2230fn validate_descriptor(descriptor: &PrimitiveDescriptor) -> Result<(), PrimitiveError> {
2231    if !is_pascal_case(&descriptor.export) {
2232        return Err(PrimitiveError::InvalidExport(descriptor.export.clone()));
2233    }
2234    for (name, field) in &descriptor.props {
2235        if !is_identifier(name) {
2236            return Err(PrimitiveError::InvalidPropName(name.clone()));
2237        }
2238        field
2239            .schema
2240            .validate_definition()
2241            .map_err(|source| PrimitiveError::InvalidSchema {
2242                location: format!("prop `{name}`"),
2243                source,
2244            })?;
2245        if let Some(default) = &field.default {
2246            field.schema.validate_ui_value(default).map_err(|source| {
2247                PrimitiveError::InvalidDefault {
2248                    prop: name.clone(),
2249                    source,
2250                }
2251            })?;
2252        }
2253    }
2254    for (name, event) in &descriptor.events {
2255        event
2256            .payload
2257            .validate_definition()
2258            .map_err(|source| PrimitiveError::InvalidSchema {
2259                location: format!("event `{name}`"),
2260                source,
2261            })?;
2262        let callback = format!("on_{name}");
2263        if !descriptor
2264            .props
2265            .get(&callback)
2266            .is_some_and(|field| schema_accepts_callback(&field.schema))
2267        {
2268            return Err(PrimitiveError::MissingEventCallback {
2269                event: name.clone(),
2270                prop: callback,
2271            });
2272        }
2273    }
2274    ComponentStateSchema::new(descriptor.state.fields().clone())
2275        .map_err(|source| PrimitiveError::InvalidStateSchema(source.to_string()))?;
2276    if let Some(effect) = &descriptor.effect {
2277        if effect.platforms.is_empty() || !effect.platforms.contains(&PrimitivePlatform::current())
2278        {
2279            return Err(PrimitiveError::UnsupportedEffectPlatform {
2280                primitive: descriptor.id.clone(),
2281                platform: PrimitivePlatform::current(),
2282            });
2283        }
2284        if effect.max_instances == 0 || effect.max_cost_per_instance == 0 {
2285            return Err(PrimitiveError::InvalidEffectBudget(descriptor.id.clone()));
2286        }
2287        if !descriptor.lifecycle {
2288            return Err(PrimitiveError::EffectRequiresLifecycle(
2289                descriptor.id.clone(),
2290            ));
2291        }
2292    }
2293    Ok(())
2294}
2295
2296fn schema_accepts_callback(schema: &ValueSchema) -> bool {
2297    matches!(schema, ValueSchema::Callback)
2298        || matches!(schema, ValueSchema::Optional { value } if schema_accepts_callback(value))
2299        || matches!(schema, ValueSchema::OneOf { variants } if variants.iter().any(schema_accepts_callback))
2300}
2301
2302fn convert_props(
2303    schema: &BTreeMap<String, ObjectField>,
2304    values: &Map,
2305    generation: ScriptGeneration,
2306) -> Result<PrimitiveProps, PrimitiveError> {
2307    let mut converted = BTreeMap::new();
2308    for (name, field) in schema {
2309        let value = values
2310            .get(name.as_str())
2311            .cloned()
2312            .or_else(|| field.default.clone().map(UiValue::into_dynamic));
2313        if let Some(value) = value {
2314            converted.insert(
2315                name.clone(),
2316                convert_prop(&field.schema, value, generation).map_err(|source| {
2317                    PrimitiveError::PropConversion {
2318                        prop: name.clone(),
2319                        source,
2320                    }
2321                })?,
2322            );
2323        }
2324    }
2325    Ok(PrimitiveProps(converted))
2326}
2327
2328fn convert_prop(
2329    schema: &ValueSchema,
2330    value: Dynamic,
2331    generation: ScriptGeneration,
2332) -> Result<PrimitiveValue, PrimitivePropConversionError> {
2333    match schema {
2334        ValueSchema::Optional { value: inner } if value.is_unit() => {
2335            Ok(PrimitiveValue::Data(UiValue::Null))
2336        }
2337        ValueSchema::Optional { value: inner } => convert_prop(inner, value, generation),
2338        ValueSchema::OneOf { variants } => {
2339            let branch = variants
2340                .iter()
2341                .find(|variant| variant.validate(&value).is_ok())
2342                .expect("validated primitive one_of prop matches one branch");
2343            convert_prop(branch, value, generation)
2344        }
2345        ValueSchema::Node => Ok(PrimitiveValue::Node(Box::new(value.cast::<UiNode>()))),
2346        ValueSchema::Callback if value.is::<FnPtr>() => {
2347            Ok(PrimitiveValue::Callback(UiEventHandler::Script(
2348                ScriptCallback::try_from_fn_ptr(value.cast::<FnPtr>(), generation)?,
2349            )))
2350        }
2351        ValueSchema::Callback => Ok(PrimitiveValue::Callback(UiEventHandler::Native(
2352            value.cast::<crate::NativeHandlerRef>(),
2353        ))),
2354        ValueSchema::Array { items, .. } if matches!(items.as_ref(), ValueSchema::Node) => {
2355            Ok(PrimitiveValue::Nodes(
2356                value
2357                    .cast::<Array>()
2358                    .into_iter()
2359                    .map(Dynamic::cast::<UiNode>)
2360                    .collect(),
2361            ))
2362        }
2363        ValueSchema::Style => Ok(PrimitiveValue::Style(Box::new(value.cast::<Style>()))),
2364        ValueSchema::Length => Ok(PrimitiveValue::Length(value.cast::<Length>())),
2365        ValueSchema::Asset => Ok(PrimitiveValue::Asset(value.cast::<AssetId>())),
2366        ValueSchema::Signal => Ok(PrimitiveValue::Signal(value.cast::<crate::NativeSignal>())),
2367        ValueSchema::Ref => Ok(PrimitiveValue::Ref(value.cast::<crate::ElementRef>())),
2368        ValueSchema::Document => Ok(PrimitiveValue::Document(
2369            value.cast::<crate::NativeTextDocument>(),
2370        )),
2371        #[cfg(feature = "charts")]
2372        ValueSchema::ChartData => Ok(PrimitiveValue::ChartData(
2373            value.cast::<crate::NativeChartData>(),
2374        )),
2375        _ => UiValue::from_dynamic(value)
2376            .map(PrimitiveValue::Data)
2377            .map_err(Into::into),
2378    }
2379}
2380
2381#[derive(Debug, Error)]
2382pub enum PrimitivePropConversionError {
2383    #[error(transparent)]
2384    Value(#[from] UiValueError),
2385    #[error(transparent)]
2386    Callback(#[from] crate::ScriptCallbackDefinitionError),
2387}
2388
2389#[derive(Debug, Error)]
2390pub enum PrimitiveError {
2391    #[error("primitive ID `{0}` must be `namespace.snake_case_name`")]
2392    InvalidId(String),
2393    #[error("primitive export `{0}` must be PascalCase")]
2394    InvalidExport(String),
2395    #[error("primitive prop `{0}` must be `snake_case`")]
2396    InvalidPropName(String),
2397    #[error("invalid schema definition for primitive {location}: {source}")]
2398    InvalidSchema {
2399        location: String,
2400        source: SchemaDefinitionError,
2401    },
2402    #[error("invalid primitive state schema: {0}")]
2403    InvalidStateSchema(String),
2404    #[error("primitive registry is already borrowed during rendering")]
2405    Borrowed,
2406    #[error("primitive `{0:?}` is already registered")]
2407    Duplicate(PrimitiveId),
2408    #[error("primitive export `{namespace}::{export}` is already registered")]
2409    DuplicateExport { namespace: String, export: String },
2410    #[error("primitive `{0:?}` is not registered")]
2411    Unknown(PrimitiveId),
2412    #[error("primitive `{0:?}` requires a stable key")]
2413    MissingKey(PrimitiveId),
2414    #[error("primitive `{0:?}` requires a retained NodeId renderer")]
2415    MissingRetainedIdentity(PrimitiveId),
2416    #[error("primitive accessibility action targeted stale instance {0:?}")]
2417    MissingInstance(PrimitiveInstanceId),
2418    #[error("primitive event emitter outlived its registry")]
2419    RegistryReleased,
2420    #[error("props for primitive `{primitive:?}` are invalid: {source}")]
2421    InvalidProps {
2422        primitive: PrimitiveId,
2423        source: SchemaValidationError,
2424    },
2425    #[error("default for primitive prop `{prop}` is invalid: {source}")]
2426    InvalidDefault {
2427        prop: String,
2428        source: SchemaValidationError,
2429    },
2430    #[error("primitive prop `{prop}` cannot cross the runtime boundary: {source}")]
2431    PropConversion {
2432        prop: String,
2433        source: PrimitivePropConversionError,
2434    },
2435    #[error("primitive event `{event}` requires callback prop `{prop}`")]
2436    MissingEventCallback { event: String, prop: String },
2437    #[error("primitive `{primitive:?}` does not declare event `{event}`")]
2438    UnknownEvent {
2439        primitive: PrimitiveId,
2440        event: String,
2441    },
2442    #[error("primitive `{primitive:?}` event `{event}` is invalid: {source}")]
2443    InvalidEvent {
2444        primitive: PrimitiveId,
2445        event: String,
2446        source: SchemaValidationError,
2447    },
2448    #[error("primitive `{primitive:?}` handler failed: {message}")]
2449    Handler {
2450        primitive: PrimitiveId,
2451        message: String,
2452    },
2453    #[error("primitive `{primitive:?}` panicked during {phase}")]
2454    Panic {
2455        primitive: PrimitiveId,
2456        phase: &'static str,
2457    },
2458    #[error("effect primitive `{primitive:?}` does not support {platform:?}")]
2459    UnsupportedEffectPlatform {
2460        primitive: PrimitiveId,
2461        platform: PrimitivePlatform,
2462    },
2463    #[error("effect primitive `{0:?}` must declare positive instance and cost budgets")]
2464    InvalidEffectBudget(PrimitiveId),
2465    #[error("effect primitive `{0:?}` must opt into scoped lifecycle")]
2466    EffectRequiresLifecycle(PrimitiveId),
2467    #[error("effect primitive `{primitive:?}` instance budget exceeded: {actual} > {limit}")]
2468    EffectInstanceBudget {
2469        primitive: PrimitiveId,
2470        actual: usize,
2471        limit: usize,
2472    },
2473    #[error("effect primitive `{primitive:?}` cost budget exceeded: {actual} > {limit}")]
2474    EffectCostBudget {
2475        primitive: PrimitiveId,
2476        actual: usize,
2477        limit: usize,
2478    },
2479    #[error(transparent)]
2480    Resource(#[from] PrimitiveResourceError),
2481}
2482
2483#[cfg(test)]
2484mod tests {
2485    use super::*;
2486    use crate::{ObjectField, StateField};
2487    use std::cell::Cell;
2488
2489    struct TestHandler;
2490
2491    struct TestTheme;
2492
2493    fn test_tokens() -> std::sync::Arc<crate::ThemeTokens> {
2494        static TOKENS: std::sync::OnceLock<std::sync::Arc<crate::ThemeTokens>> =
2495            std::sync::OnceLock::new();
2496        TOKENS
2497            .get_or_init(|| {
2498                let engine = crate::RuntimeEngine::new();
2499                crate::load_theme_source(
2500                    engine.engine(),
2501                    "test.rhai",
2502                    r#"fn theme() { #{ family: "T", name: "T", mode: "dark", tokens: #{
2503                        colors: #{ accent: 0x123456ff, selection: 0x123456ff,
2504                            "table.selection": 0x123456ff },
2505                        spacing: #{ xxs: px(2), sm: px(6) },
2506                        typography: #{ roles: #{ body: #{ size: px(12), line_height: px(16),
2507                            weight: 400, family: "JetBrains Mono", fallbacks: ["PingFang SC"] } } },
2508                    } } }"#,
2509                )
2510                .expect("test theme")
2511                .tokens
2512            })
2513            .clone()
2514    }
2515
2516    impl ColorResolver for TestTheme {
2517        fn resolve_token(&self, token: &str) -> Option<Rgba8> {
2518            test_tokens().color(token)
2519        }
2520
2521        fn token_set(&self) -> Option<std::sync::Arc<crate::ThemeTokens>> {
2522            Some(test_tokens())
2523        }
2524    }
2525
2526    impl PrimitiveHandler for TestHandler {
2527        fn render(
2528            &mut self,
2529            _: &PrimitiveInstance,
2530            _: &PrimitiveContext,
2531            _: &PrimitiveTheme,
2532            _: &mut Window,
2533            _: &mut App,
2534        ) -> Result<AnyElement, String> {
2535            Ok(div().into_any_element())
2536        }
2537    }
2538
2539    #[test]
2540    fn primitive_theme_exposes_only_resolved_semantic_snapshot() {
2541        let theme = PrimitiveTheme::capture(&TestTheme);
2542        assert_eq!(
2543            theme.color("accent"),
2544            Some(Rgba8::from_rgba_hex(0x1234_56ff))
2545        );
2546        assert_eq!(theme.color("unknown"), None);
2547        assert_eq!(
2548            theme.color("selection"),
2549            Some(Rgba8::from_rgba_hex(0x1234_56ff))
2550        );
2551        assert_eq!(
2552            theme.color("table.selection"),
2553            Some(Rgba8::from_rgba_hex(0x1234_56ff))
2554        );
2555        assert_eq!(
2556            theme.resolve_color(&ColorValue::Literal(Rgba8::from_rgba_hex(0xaabb_ccdd))),
2557            Some(Rgba8::from_rgba_hex(0xaabb_ccdd))
2558        );
2559        assert_eq!(
2560            theme.resolve_length(Length::theme_spacing("sm").unwrap()),
2561            Some(Length::Pixels(6.0))
2562        );
2563        assert_eq!(
2564            theme.resolve_length(Length::theme_spacing("xxs").unwrap()),
2565            Some(Length::Pixels(2.0))
2566        );
2567        assert_eq!(
2568            theme.typography("body").unwrap().family.as_deref(),
2569            Some("JetBrains Mono")
2570        );
2571
2572        let engine = crate::RuntimeEngine::new();
2573        let loaded = crate::load_theme_source(
2574            engine.engine(),
2575            "default_light.rhai",
2576            include_str!("../../../registry/themes/default_light.rhai"),
2577        )
2578        .unwrap();
2579        let captured = PrimitiveTheme::capture(&loaded);
2580        assert_eq!(captured.color("surface"), loaded.tokens.color("surface"));
2581        assert!(captured.color("surface").is_some());
2582    }
2583
2584    fn descriptor() -> PrimitiveDescriptor {
2585        PrimitiveDescriptor {
2586            id: PrimitiveId::parse("my_app.code_editor").unwrap(),
2587            export: "CodeEditor".to_owned(),
2588            props: BTreeMap::from([
2589                (
2590                    "value".to_owned(),
2591                    ObjectField::required(ValueSchema::string()),
2592                ),
2593                (
2594                    "on_change".to_owned(),
2595                    ObjectField::optional(ValueSchema::optional(ValueSchema::Callback)),
2596                ),
2597            ]),
2598            events: BTreeMap::from([(
2599                "change".to_owned(),
2600                EventSchema {
2601                    doc: None,
2602                    payload: ValueSchema::string(),
2603                },
2604            )]),
2605            state: ComponentStateSchema::new(BTreeMap::from([(
2606                "selection".to_owned(),
2607                StateField::new(ValueSchema::integer(), UiValue::Integer(0)),
2608            )]))
2609            .unwrap(),
2610            lifecycle: true,
2611            effect: None,
2612        }
2613    }
2614
2615    #[test]
2616    fn effect_descriptors_require_current_platform_lifecycle_and_budgets() {
2617        let mut descriptor = descriptor();
2618        descriptor.effect = Some(EffectPrimitiveDescriptor {
2619            platforms: BTreeSet::from([PrimitivePlatform::current()]),
2620            max_instances: 8,
2621            max_cost_per_instance: 4_096,
2622            reduced_motion: true,
2623            quality_tiers: true,
2624        });
2625        validate_descriptor(&descriptor).unwrap();
2626        descriptor.lifecycle = false;
2627        assert!(matches!(
2628            validate_descriptor(&descriptor),
2629            Err(PrimitiveError::EffectRequiresLifecycle(_))
2630        ));
2631    }
2632
2633    #[test]
2634    fn custom_primitive_props_and_keys_are_validated() {
2635        let registry = PrimitiveRegistry::new();
2636        let descriptor = descriptor();
2637        let id = descriptor.id.clone();
2638        registry.register(descriptor, TestHandler).unwrap();
2639        assert!(matches!(
2640            registry.create_node(
2641                &id,
2642                None,
2643                &Map::from_iter([("value".into(), Dynamic::from("source"))]),
2644                ScriptGeneration::initial(),
2645            ),
2646            Err(PrimitiveError::MissingKey(_))
2647        ));
2648        registry
2649            .create_node(
2650                &id,
2651                Some("editor".to_owned()),
2652                &Map::from_iter([("value".into(), Dynamic::from("source"))]),
2653                ScriptGeneration::initial(),
2654            )
2655            .unwrap();
2656    }
2657
2658    #[test]
2659    fn custom_primitive_events_are_normalized() {
2660        let registry = PrimitiveRegistry::new();
2661        let descriptor = descriptor();
2662        let id = descriptor.id.clone();
2663        registry.register(descriptor, TestHandler).unwrap();
2664        assert_eq!(
2665            registry
2666                .normalize_event(&id, "change", UiValue::String("new".to_owned()))
2667                .unwrap(),
2668            UiValue::String("new".to_owned())
2669        );
2670        assert!(matches!(
2671            registry.normalize_event(&id, "change", UiValue::Bool(true)),
2672            Err(PrimitiveError::InvalidEvent { .. })
2673        ));
2674    }
2675
2676    #[test]
2677    fn native_panics_are_converted_to_primitive_errors() {
2678        let id = PrimitiveId::parse("my_app.crash").unwrap();
2679        assert!(matches!(
2680            guard_primitive_panic(&id, "render", || panic!("boom")),
2681            Err(PrimitiveError::Panic {
2682                phase: "render",
2683                ..
2684            })
2685        ));
2686    }
2687
2688    #[test]
2689    fn primitive_resource_scope_rolls_back_and_continues_after_cleanup_panic() {
2690        let scope = PrimitiveResourceScope::new();
2691        let retained = Rc::new(Cell::new(0));
2692        let retained_cleanup = Rc::clone(&retained);
2693        scope
2694            .own("retained", move || retained_cleanup.set(1))
2695            .unwrap();
2696        let checkpoint = scope.checkpoint().unwrap();
2697        let order = Rc::new(RefCell::new(Vec::new()));
2698        let first = Rc::clone(&order);
2699        scope
2700            .own("first", move || first.borrow_mut().push(1))
2701            .unwrap();
2702        scope.own("panic", || panic!("cleanup failed")).unwrap();
2703        let last = Rc::clone(&order);
2704        scope
2705            .own("last", move || last.borrow_mut().push(3))
2706            .unwrap();
2707
2708        assert!(matches!(
2709            scope.rollback(checkpoint),
2710            Err(PrimitiveResourceError::CleanupPanic { ref label }) if label == "panic"
2711        ));
2712        assert_eq!(*order.borrow(), vec![3, 1]);
2713        assert_eq!(scope.active_count(), 1);
2714        scope.close().unwrap();
2715        assert_eq!(retained.get(), 1);
2716    }
2717
2718    #[test]
2719    fn successful_tree_cleanup_unmounts_removed_keyed_instances() {
2720        struct UnmountCounter(Rc<Cell<usize>>);
2721        impl PrimitiveHandler for UnmountCounter {
2722            fn render(
2723                &mut self,
2724                _: &PrimitiveInstance,
2725                _: &PrimitiveContext,
2726                _: &PrimitiveTheme,
2727                _: &mut Window,
2728                _: &mut App,
2729            ) -> Result<AnyElement, String> {
2730                Ok(div().into_any_element())
2731            }
2732
2733            fn unmount(&mut self, _: &PrimitiveInstanceId) {
2734                self.0.set(self.0.get() + 1);
2735            }
2736        }
2737
2738        let registry = PrimitiveRegistry::new();
2739        let descriptor = descriptor();
2740        let node = PrimitiveNode {
2741            primitive: descriptor.id.clone(),
2742            key: Some("editor".to_owned()),
2743            props: PrimitiveProps::new(),
2744        };
2745        let mut tree = crate::RetainedUiTree::new();
2746        tree.reconcile(UiNode::custom(node.clone())).unwrap();
2747        let instance = collect_primitive_instances(&tree)
2748            .into_iter()
2749            .next()
2750            .unwrap();
2751        let unmounted = Rc::new(Cell::new(0));
2752        let cleaned = Rc::new(Cell::new(0));
2753        let resources = PrimitiveResourceScope::new();
2754        let cleanup = Rc::clone(&cleaned);
2755        resources
2756            .own("watcher", move || cleanup.set(cleanup.get() + 1))
2757            .unwrap();
2758        registry
2759            .register(descriptor, UnmountCounter(Rc::clone(&unmounted)))
2760            .unwrap();
2761        registry.inner.borrow_mut().mounted.insert(
2762            instance.clone(),
2763            PrimitiveInstance {
2764                id: Some(instance.clone()),
2765                node,
2766                resources: Some(resources),
2767                focus_handle: None,
2768            },
2769        );
2770        tree.reconcile(UiNode::text("removed")).unwrap();
2771        registry.retain_tree(&tree).unwrap();
2772        assert_eq!(unmounted.get(), 1);
2773        assert_eq!(cleaned.get(), 1);
2774    }
2775
2776    #[test]
2777    fn primitive_identity_uses_retained_node_not_component_local_key() {
2778        let primitive = PrimitiveId::parse("my_app.editor").unwrap();
2779        let branch = |branch: &str| {
2780            UiNode::box_node(vec![UiNode::custom(PrimitiveNode {
2781                primitive: primitive.clone(),
2782                key: Some("editor".to_owned()),
2783                props: PrimitiveProps::new().with(
2784                    "branch",
2785                    PrimitiveValue::Data(UiValue::String(branch.to_owned())),
2786                ),
2787            })])
2788            .with_key(branch)
2789        };
2790        let mut tree = crate::RetainedUiTree::new();
2791        tree.reconcile(UiNode::box_node(vec![branch("left"), branch("right")]))
2792            .unwrap();
2793        let before = collect_primitive_instances(&tree);
2794        assert_eq!(before.len(), 2);
2795        assert!(before.iter().all(|instance| instance.key() == "editor"));
2796        assert_eq!(
2797            before
2798                .iter()
2799                .map(PrimitiveInstanceId::node)
2800                .collect::<BTreeSet<_>>()
2801                .len(),
2802            2
2803        );
2804
2805        tree.reconcile(UiNode::box_node(vec![branch("right"), branch("left")]))
2806            .unwrap();
2807        assert_eq!(collect_primitive_instances(&tree), before);
2808    }
2809
2810    #[test]
2811    fn primitive_identity_uses_the_presented_retained_key() {
2812        let primitive = PrimitiveId::parse("my_app.editor").unwrap();
2813        let node = UiNode::custom(PrimitiveNode {
2814            primitive,
2815            key: Some("constructor-key".to_owned()),
2816            props: PrimitiveProps::new(),
2817        })
2818        .with_key("presented-key");
2819        let mut tree = crate::RetainedUiTree::new();
2820        tree.reconcile(node).unwrap();
2821        let instance = collect_primitive_instances(&tree)
2822            .into_iter()
2823            .next()
2824            .unwrap();
2825        assert_eq!(instance.key(), "presented-key");
2826    }
2827
2828    #[test]
2829    fn primitive_context_holds_only_a_weak_registry_reference() {
2830        let registry = PrimitiveRegistry::new();
2831        let weak = Rc::downgrade(&registry.inner);
2832        let emitter = PrimitiveContext {
2833            assets: None,
2834            registry: Rc::downgrade(&registry.inner),
2835            primitive: PrimitiveId::parse("my_app.editor").unwrap(),
2836            event_schemas: BTreeMap::new(),
2837            callbacks: BTreeMap::new(),
2838            dispatcher: None,
2839            interactions: crate::interaction::WindowInteractionCoordinator::default(),
2840            scroll_handles: Vec::new(),
2841            wheel_parents: Vec::new(),
2842            key_captures: Vec::new(),
2843            intrinsic_size: None,
2844            intrinsic_generation: ScriptGeneration::default(),
2845            intrinsic_lease: None,
2846            view_id: "test".to_owned(),
2847            instance: None,
2848            retained_node: None,
2849            focus_handle: None,
2850            focus_indicators: true,
2851            file_drops: None,
2852        };
2853        assert_eq!(Rc::strong_count(&registry.inner), 1);
2854        drop(registry);
2855        assert!(weak.upgrade().is_none());
2856        drop(emitter);
2857    }
2858}