1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use crate::api::math::Point2;
use crate::api::Window;
use pax_lang::interpreter::property_resolution::IdentifierResolver;
use pax_manifest::UniqueTemplateNodeIdentifier;
use pax_message::NativeMessage;
use pax_runtime_api::pax_value::PaxAny;
use pax_runtime_api::properties::UntypedProperty;
use pax_runtime_api::{
    borrow, borrow_mut, use_RefCell, Interpolatable, PaxValue, RenderContext, Store, Variable,
};
use_RefCell!();
use std::any::{Any, TypeId};
use std::cell::Cell;
use std::collections::HashMap;
use std::rc::{Rc, Weak};

use crate::{ComponentInstance, ExpandedNode, Globals, InstanceNode};

impl Interpolatable for ExpandedNodeIdentifier {}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExpandedNodeIdentifier(pub u32);

impl ExpandedNodeIdentifier {
    // used for sending identifiers to chassis
    pub fn to_u32(&self) -> u32 {
        self.0
    }
}

/// Shared context for properties pass recursion
pub struct RuntimeContext {
    next_uid: Cell<ExpandedNodeIdentifier>,
    messages: RefCell<Vec<NativeMessage>>,
    globals: RefCell<Globals>,
    root_expanded_node: RefCell<Weak<ExpandedNode>>,
    #[cfg(feature = "designtime")]
    pub userland_frame_instance_node: RefCell<Rc<dyn InstanceNode>>,
    #[cfg(feature = "designtime")]
    pub userland_root_expanded_node: RefCell<Option<Rc<ExpandedNode>>>,
    node_cache: RefCell<NodeCache>,
    queued_custom_events: RefCell<Vec<(Rc<ExpandedNode>, &'static str)>>,
    queued_renders: RefCell<Vec<Rc<ExpandedNode>>>,
}

struct NodeCache {
    eid_to_node: HashMap<ExpandedNodeIdentifier, Rc<ExpandedNode>>,
    uni_to_eid: HashMap<UniqueTemplateNodeIdentifier, Vec<ExpandedNodeIdentifier>>,
}

impl NodeCache {
    fn new() -> Self {
        Self {
            eid_to_node: Default::default(),
            uni_to_eid: Default::default(),
        }
    }

    // Add this node to all relevant constant lookup cache structures
    fn add_to_cache(&mut self, node: &Rc<ExpandedNode>) {
        self.eid_to_node.insert(node.id, Rc::clone(&node));
        let uni = borrow!(node.instance_node)
            .base()
            .template_node_identifier
            .clone();
        if let Some(uni) = uni {
            self.uni_to_eid.entry(uni).or_default().push(node.id);
        }
    }

    // Remove this node from all relevant constant lookup cache structures
    fn remove_from_cache(&mut self, node: &Rc<ExpandedNode>) {
        self.eid_to_node.remove(&node.id);
        if let Some(uni) = &borrow!(node.instance_node).base().template_node_identifier {
            self.uni_to_eid
                .entry(uni.clone())
                .or_default()
                .retain(|&n| n != node.id);
        }
    }
}

impl RuntimeContext {
    #[cfg(not(feature = "designtime"))]
    pub fn new(globals: Globals) -> Self {
        Self {
            next_uid: Cell::new(ExpandedNodeIdentifier(0)),
            messages: RefCell::new(Vec::new()),
            globals: RefCell::new(globals),
            root_expanded_node: RefCell::new(Weak::new()),
            node_cache: RefCell::new(NodeCache::new()),
            queued_custom_events: Default::default(),
            queued_renders: Default::default(),
        }
    }

    #[cfg(feature = "designtime")]
    pub fn new(globals: Globals, userland: Rc<ComponentInstance>) -> Self {
        Self {
            next_uid: Cell::new(ExpandedNodeIdentifier(0)),
            messages: RefCell::new(Vec::new()),
            globals: RefCell::new(globals),
            root_expanded_node: RefCell::new(Weak::new()),
            userland_frame_instance_node: RefCell::new(userland),
            userland_root_expanded_node: Default::default(),
            node_cache: RefCell::new(NodeCache::new()),
            queued_custom_events: Default::default(),
            queued_renders: Default::default(),
        }
    }

    pub fn register_root_expanded_node(&self, root: &Rc<ExpandedNode>) {
        *borrow_mut!(self.root_expanded_node) = Rc::downgrade(root);
    }

    pub fn add_to_cache(&self, node: &Rc<ExpandedNode>) {
        borrow_mut!(self.node_cache).add_to_cache(node);
    }

    pub fn remove_from_cache(&self, node: &Rc<ExpandedNode>) {
        borrow_mut!(self.node_cache).remove_from_cache(node);
    }

    pub fn get_expanded_node_by_eid(&self, id: ExpandedNodeIdentifier) -> Option<Rc<ExpandedNode>> {
        borrow!(self.node_cache).eid_to_node.get(&id).cloned()
    }

    /// Finds all ExpandedNodes with the CommonProperty#id matching the provided string
    pub fn get_expanded_nodes_by_id(&self, id: &str) -> Vec<Rc<ExpandedNode>> {
        //v0 limitation: currently an O(n) lookup cost (could be made O(1) with an id->expandednode cache)
        borrow!(self.node_cache)
            .eid_to_node
            .values()
            .filter(|val| {
                let common_props = val.get_common_properties();
                let common_props = borrow!(common_props);
                common_props.id.get().is_some_and(|i| i == id)
            })
            .cloned()
            .collect()
    }

    /// Finds all ExpandedNodes with corresponding UniqueTemplateNodeIdentifier
    pub fn get_expanded_nodes_by_global_ids(
        &self,
        uni: &UniqueTemplateNodeIdentifier,
    ) -> Vec<Rc<ExpandedNode>> {
        let node_cache = borrow!(self.node_cache);
        node_cache
            .uni_to_eid
            .get(uni)
            .map(|eids| {
                let mut nodes = vec![];
                for e in eids {
                    nodes.extend(
                        node_cache
                            .eid_to_node
                            .get(e)
                            .map(|node| vec![Rc::clone(node)])
                            .unwrap_or_default(),
                    )
                }
                nodes
            })
            .unwrap_or_default()
    }

    /// Simple 2D raycasting: the coordinates of the ray represent a
    /// ray running orthogonally to the view plane, intersecting at
    /// the specified point `ray`.  Areas outside of clipping bounds will
    /// not register a `hit`, nor will elements that suppress input events.
    pub fn get_elements_beneath_ray(
        &self,
        ray: Point2<Window>,
        limit_one: bool,
        mut accum: Vec<Rc<ExpandedNode>>,
        hit_invisible: bool,
    ) -> Vec<Rc<ExpandedNode>> {
        //Traverse all elements in render tree sorted by z-index (highest-to-lowest)
        //First: check whether events are suppressed
        //Next: check whether ancestral clipping bounds (hit_test) are satisfied
        //Finally: check whether element itself satisfies hit_test(ray)

        let root_node = borrow!(self.root_expanded_node).upgrade().unwrap();
        let mut to_process = vec![(root_node, false)];
        while let Some((node, clipped)) = to_process.pop() {
            // make sure slot sources are updated for this node
            node.compute_flattened_slot_children();
            let hit = node.ray_cast_test(ray);
            if hit && !clipped {
                if hit_invisible
                    || !borrow!(node.instance_node)
                        .base()
                        .flags()
                        .invisible_to_raycasting
                {
                    //We only care about the topmost node getting hit, and the element
                    //pool is ordered by z-index so we can just resolve the whole
                    //calculation when we find the first matching node
                    if limit_one {
                        return vec![node];
                    }
                    accum.push(Rc::clone(&node));
                }
            }
            let clipped = clipped || (!hit && borrow!(node.instance_node).clips_content(&node));
            to_process.extend(
                node.children
                    .get()
                    .iter()
                    .cloned()
                    .map(|v| {
                        let cp = v.get_common_properties();
                        let unclippable = borrow!(cp).unclippable.get().unwrap_or(false);
                        (v, clipped && !unclippable)
                    })
                    .rev(),
            )
        }
        accum
    }
    /// Alias for `get_elements_beneath_ray` with `limit_one = true`
    pub fn get_topmost_element_beneath_ray(&self, ray: Point2<Window>) -> Option<Rc<ExpandedNode>> {
        let res = self.get_elements_beneath_ray(ray, true, vec![], false);
        Some(
            res.into_iter()
                .next()
                .unwrap_or(borrow!(self.root_expanded_node).upgrade().unwrap()),
        )
    }

    pub fn gen_uid(&self) -> ExpandedNodeIdentifier {
        let val = self.next_uid.get();
        let next_val = ExpandedNodeIdentifier(val.0 + 1);
        self.next_uid.set(next_val);
        val
    }

    pub fn enqueue_native_message(&self, message: NativeMessage) {
        borrow_mut!(self.messages).push(message)
    }

    pub fn take_native_messages(&self) -> Vec<NativeMessage> {
        let mut messages = borrow_mut!(self.messages);
        std::mem::take(&mut *messages)
    }

    pub fn globals(&self) -> Globals {
        borrow!(self.globals).clone()
    }

    pub fn edit_globals(&self, f: impl Fn(&mut Globals)) {
        let mut globals = borrow_mut!(self.globals);
        f(&mut globals);
    }

    pub fn queue_custom_event(&self, source_expanded_node: Rc<ExpandedNode>, name: &'static str) {
        let mut queued_custom_events = borrow_mut!(self.queued_custom_events);
        queued_custom_events.push((source_expanded_node, name));
    }

    pub fn flush_custom_events(self: &Rc<Self>) -> Result<(), String> {
        let mut queued_custom_event = borrow_mut!(self.queued_custom_events);
        let to_flush: Vec<_> = std::mem::take(queued_custom_event.as_mut());
        for (target, ident) in to_flush {
            target.dispatch_custom_event(ident, self)?;
        }
        Ok(())
    }

    #[cfg(feature = "designtime")]
    pub fn get_userland_root_expanded_node(&self) -> Option<Rc<ExpandedNode>> {
        borrow!(self.userland_root_expanded_node).clone()
    }

    #[cfg(feature = "designtime")]
    pub fn get_userland_root_instance_node(&self) -> Option<Rc<dyn InstanceNode>> {
        Some(borrow!(self.userland_frame_instance_node).clone())
    }

    pub fn get_root_expanded_node(&self) -> Option<Rc<ExpandedNode>> {
        borrow!(self.root_expanded_node).upgrade()
    }

    pub fn queue_render(&self, expanded_node: Rc<ExpandedNode>) {
        borrow_mut!(self.queued_renders).push(expanded_node);
    }

    pub fn recurse_flush_queued_renders(self: &Rc<RuntimeContext>, rcs: &mut dyn RenderContext) {
        while !borrow!(self.queued_renders).is_empty() {
            for n in std::mem::take(&mut *borrow_mut!(self.queued_renders)) {
                n.recurse_render(self, rcs);
            }
        }
    }
}

/// Data structure for a single frame of our runtime stack, including
/// a reference to its parent frame and `properties` for
/// runtime evaluation, e.g. of Expressions.  `RuntimePropertiesStackFrame`s also track
/// timeline playhead position.
///
/// `Component`s push `RuntimePropertiesStackFrame`s before computing properties and pop them after computing, thus providing a
/// hierarchical store of node-relevant data that can be bound to symbols in expressions.

pub struct RuntimePropertiesStackFrame {
    symbols_within_frame: HashMap<String, Variable>,
    local_stores: Rc<RefCell<HashMap<TypeId, Box<dyn Any>>>>,
    properties: Rc<RefCell<PaxAny>>,
    parent: Weak<RuntimePropertiesStackFrame>,
}

impl RuntimePropertiesStackFrame {
    pub fn new(
        symbols_within_frame: HashMap<String, Variable>,
        properties: Rc<RefCell<PaxAny>>,
    ) -> Rc<Self> {
        Rc::new(Self {
            symbols_within_frame,
            properties,
            local_stores: Default::default(),
            parent: Weak::new(),
        })
    }

    pub fn push(
        self: &Rc<Self>,
        symbols_within_frame: HashMap<String, Variable>,
        properties: &Rc<RefCell<PaxAny>>,
    ) -> Rc<Self> {
        Rc::new(RuntimePropertiesStackFrame {
            symbols_within_frame,
            local_stores: Default::default(),
            parent: Rc::downgrade(&self),
            properties: Rc::clone(properties),
        })
    }

    pub fn pop(self: &Rc<Self>) -> Option<Rc<Self>> {
        self.parent.upgrade()
    }

    /// Traverses stack recursively `n` times to retrieve ancestor;
    /// useful for runtime lookups for identifiers, where `n` is the statically known offset determined by the Pax compiler
    /// when resolving a symbol
    pub fn peek_nth(self: &Rc<Self>, n: isize) -> Option<Rc<RefCell<PaxAny>>> {
        let mut curr = Rc::clone(self);
        for _ in 0..n {
            curr = curr.parent.upgrade()?;
        }
        Some(Rc::clone(&curr.properties))
    }

    pub fn resolve_symbol(&self, symbol: &str) -> Option<Rc<RefCell<PaxAny>>> {
        if let Some(_) = self.symbols_within_frame.get(&clean_symbol(symbol)) {
            Some(Rc::clone(&self.properties))
        } else {
            self.parent.upgrade()?.resolve_symbol(symbol)
        }
    }

    pub fn insert_stack_local_store<T: Store>(&self, store: T) {
        let type_id = TypeId::of::<T>();
        borrow_mut!(self.local_stores).insert(type_id, Box::new(store));
    }

    pub fn peek_stack_local_store<T: Store, V>(
        self: &Rc<Self>,
        f: impl FnOnce(&mut T) -> V,
    ) -> Result<V, String> {
        let mut current = Rc::clone(self);
        let type_id = TypeId::of::<T>();

        while !borrow!(current.local_stores).contains_key(&type_id) {
            current = current
                .parent
                .upgrade()
                .ok_or_else(|| format!("couldn't find store in local stack"))?;
        }
        let v = {
            let mut stores = borrow_mut!(current.local_stores);
            let store = stores.get_mut(&type_id).unwrap().downcast_mut().unwrap();
            f(store)
        };
        Ok(v)
    }

    pub fn resolve_symbol_as_variable(&self, symbol: &str) -> Option<Variable> {
        if let Some(e) = self.symbols_within_frame.get(&clean_symbol(symbol)) {
            Some(e.clone())
        } else {
            self.parent.upgrade()?.resolve_symbol_as_variable(symbol)
        }
    }

    pub fn resolve_symbol_as_erased_property(&self, symbol: &str) -> Option<UntypedProperty> {
        if let Some(e) = self.symbols_within_frame.get(&clean_symbol(symbol)) {
            Some(e.clone().get_untyped_property().clone())
        } else {
            self.parent
                .upgrade()?
                .resolve_symbol_as_erased_property(symbol)
        }
    }

    pub fn resolve_symbol_as_pax_value(&self, symbol: &str) -> Option<PaxValue> {
        if let Some(e) = self.symbols_within_frame.get(&clean_symbol(symbol)) {
            Some(e.get_as_pax_value())
        } else {
            self.parent.upgrade()?.resolve_symbol_as_pax_value(symbol)
        }
    }

    pub fn get_properties(&self) -> Rc<RefCell<PaxAny>> {
        Rc::clone(&self.properties)
    }
}

fn clean_symbol(symbol: &str) -> String {
    symbol.replace("self.", "").replace("this.", "")
}

impl IdentifierResolver for RuntimePropertiesStackFrame {
    fn resolve(&self, name: String) -> Result<PaxValue, String> {
        self.resolve_symbol_as_pax_value(&name)
            .ok_or_else(|| format!("Could not resolve symbol {}", name))
    }
}

/// Data structure used for dynamic injection of values
/// into Expressions, maintaining a pointer e.g. to the current
/// stack frame to enable evaluation of properties & dependencies
pub struct ExpressionContext {
    pub stack_frame: Rc<RuntimePropertiesStackFrame>,
}