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
use {
    crate::{
        makepad_live_compiler::*,
        cx::Cx,
    }
};

pub use crate::live_cx::LiveBody;

pub trait LiveHook {
    fn before_live_design(_cx:&mut Cx){}
        
    fn apply_value_unknown(&mut self, cx: &mut Cx, _apply_from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> usize {
        if !nodes[index].origin.node_has_prefix() {
            cx.apply_error_no_matching_field(live_error_origin!(), index, nodes);
        }
        nodes.skip_node(index)
    }

    fn apply_value_instance(&mut self, _cx: &mut Cx, _apply_from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> usize {
        nodes.skip_node(index)
    }
    
    fn skip_apply(&mut self, _cx: &mut Cx, _apply_from: ApplyFrom, _index: usize, _nodes: &[LiveNode])->Option<usize>{None}
    fn before_apply(&mut self, _cx: &mut Cx, _apply_from: ApplyFrom, _index: usize, _nodes: &[LiveNode]){}
    fn after_apply(&mut self, _cx: &mut Cx, _apply_from: ApplyFrom, _index: usize, _nodes: &[LiveNode]) {}
    fn after_apply_from(&mut self, cx: &mut Cx, apply_from: ApplyFrom) {
        match apply_from{
            ApplyFrom::NewFromDoc{..}=>self.after_new_from_doc(cx),
            _=>()
        }
    }
    fn after_new_from_doc(&mut self, _cx:&mut Cx){}
    fn after_new_before_apply(&mut self, _cx: &mut Cx) {}
}

pub trait LiveHookDeref {
    fn deref_before_apply(&mut self, _cx: &mut Cx, _apply_from: ApplyFrom, _index: usize, _nodes: &[LiveNode]){}
    fn deref_after_apply(&mut self, _cx: &mut Cx, _apply_from: ApplyFrom, _index: usize, _nodes: &[LiveNode]){}
}

pub trait LiveNew: LiveApply {
    fn new(cx: &mut Cx) -> Self;
    
    fn live_design_with(_cx: &mut Cx) {}
    
    fn live_type_info(cx: &mut Cx) -> LiveTypeInfo;
    
    fn new_apply(cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> Self where Self: Sized {
        let mut ret = Self::new(cx);
        ret.apply(cx, from, index, nodes);
        ret
    }
    
    fn new_apply_mut_index(cx: &mut Cx, from: ApplyFrom, index: &mut usize, nodes: &[LiveNode]) -> Self where Self: Sized {
        let mut ret = Self::new(cx);
        *index = ret.apply(cx, from, *index, nodes);
        ret
    }

    fn new_from_ptr(cx: &mut Cx, live_ptr: Option<LivePtr>) -> Self where Self: Sized {
        let mut ret = Self::new(cx);
        if let Some(live_ptr) = live_ptr{
            cx.get_nodes_from_live_ptr(live_ptr, |cx, file_id, index, nodes|{
                ret.apply(cx, ApplyFrom::NewFromDoc {file_id}, index, nodes)
            });
        }
        return ret
    }
    
    fn new_main(cx: &mut Cx) -> Self where Self: Sized {
        let lti = Self::live_type_info(cx);
        {
            let live_registry_rc = cx.live_registry.clone();
            let mut live_registry = live_registry_rc.borrow_mut();
            live_registry.main_module = Some((lti.module_id, lti.type_name));
        }
        Self::new_from_module(cx, lti.module_id, lti.type_name).unwrap()
    }
    
    fn update_main(&mut self, cx:&mut Cx){
        let (module_id, id) = {
            let live_registry_rc = cx.live_registry.clone();
            let live_registry = live_registry_rc.borrow_mut();
            live_registry.main_module.unwrap()
        };
        self.update_from_module(cx, module_id, id);
    }
    
    fn new_local(cx: &mut Cx) -> Self where Self: Sized {
        let lti = Self::live_type_info(cx);
        Self::new_from_module(cx, lti.module_id, lti.type_name).unwrap()
    }
    
    fn new_from_module(cx: &mut Cx, module_id: LiveModuleId, id: LiveId) -> Option<Self> where Self: Sized {
        let live_registry_rc = cx.live_registry.clone();
        let live_registry = live_registry_rc.borrow();
        if let Some(file_id) = live_registry.module_id_to_file_id.get(&module_id) {
            let file = live_registry.file_id_to_file(*file_id);
            if let Some(index) = file.expanded.nodes.child_by_name(0, id.as_instance()) {
                let mut ret = Self::new(cx);
                ret.apply(cx, ApplyFrom::NewFromDoc {file_id: *file_id}, index, &file.expanded.nodes);
                return Some(ret)
            }
        }
        None
    }
    
    fn update_from_module(&mut self, cx: &mut Cx, module_id: LiveModuleId, id: LiveId)  {
        let live_registry_rc = cx.live_registry.clone();
        let live_registry = live_registry_rc.borrow();
        if let Some(file_id) = live_registry.module_id_to_file_id.get(&module_id) {
            let file = live_registry.file_id_to_file(*file_id);
            if let Some(index) = file.expanded.nodes.child_by_name(0, id.as_instance()) {
                
                self.apply(cx, ApplyFrom::UpdateFromDoc {file_id: *file_id}, index, &file.expanded.nodes);
            }
        }
    }
}

pub trait ToLiveValue {
    fn to_live_value(&self) -> LiveValue;
}

pub trait LiveApplyValue {
    fn apply_value(&mut self, cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> usize;
}

pub trait LiveApply {
    fn apply(&mut self, cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> usize;
    
    fn apply_over(&mut self, cx: &mut Cx, nodes: &[LiveNode]) {
        self.apply(cx, ApplyFrom::ApplyOver, 0, nodes);
    }
}

pub trait LiveRead{
    fn live_read_to(&self, id:LiveId, out:&mut Vec<LiveNode>);
    fn live_read(&self)->Vec<LiveNode>{
        let mut out = Vec::new();
        self.live_read_to(LiveId(0),&mut out);
        out
    }
    
}

impl<T, const N:usize> LiveRead for [T;N]  where T: LiveRead {
    fn live_read_to(&self, id:LiveId, out:&mut Vec<LiveNode>){
        out.open_array(id);
        for i in 0..N{
            self[i].live_read_to(LiveId(i as u64), out);
        }
        out.close();
    }
} 

#[derive(Debug, Clone, Copy)]
pub enum ApplyFrom {
    NewFromDoc {file_id: LiveFileId}, // newed from DSL
    UpdateFromDoc {file_id: LiveFileId}, // live DSL substantially updated
    
    New, // Bare new without file info
    Animate, // from animate
    AnimatorInit,
    ApplyOver, // called from bare apply_live() call
}

impl ApplyFrom {
    pub fn is_from_doc(&self) -> bool {
        match self {
            Self::NewFromDoc {..} => true,
            Self::UpdateFromDoc {..} => true,
            _ => false
        }
    }

    pub fn is_new_from_doc(&self) -> bool {
        match self {
            Self::NewFromDoc {..} => true,
            _ => false
        }
    }
    
    pub fn file_id(&self) -> Option<LiveFileId> {
        match self {
            Self::NewFromDoc {file_id} => Some(*file_id),
            Self::UpdateFromDoc {file_id} => Some(*file_id),
            _ => None
        }
    }
}


impl<T> LiveHook for Option<T> where T: LiveApply + LiveNew + 'static {}
impl<T> LiveApply for Option<T> where T: LiveApply + LiveNew + 'static {
    fn apply(&mut self, cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> usize {
        if let Some(v) = self {
            v.apply(cx, from, index, nodes)
        }
        else {
            let mut inner = T::new(cx);
            let index = inner.apply(cx, from, index, nodes);
            *self = Some(inner);
            index
        }
    }
} 

impl<T> LiveNew for Option<T> where T: LiveApply + LiveNew + 'static{
    fn new(_cx: &mut Cx) -> Self {
        Self::None
    }
    fn new_apply(cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> Self {
        let mut ret = Self::None;
        ret.apply(cx, from, index, nodes);
        ret
    }
    
    fn live_type_info(_cx: &mut Cx) -> LiveTypeInfo {
        T::live_type_info(_cx)
    }
}


impl<T> LiveHook for Vec<T> where T: LiveApply + LiveNew + 'static {}
impl<T> LiveApply for Vec<T> where T: LiveApply + LiveNew + 'static {
    fn apply(&mut self, cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> usize {
        // we can only apply from an Array
        self.clear();
        if nodes[index].is_array(){
            let mut index = index + 1;
            loop{
                if nodes[index].is_close(){
                    index += 1;
                    break;
                }
                let mut inner = T::new(cx);
                index = inner.apply(cx, from, index, nodes);
                self.push(inner);
            }
            index
        }
        else{
            cx.apply_error_expected_array(live_error_origin!(), index, nodes);
            nodes.skip_node(index)
        }
    }
} 

impl<T> LiveNew for Vec<T> where T: LiveApply + LiveNew + 'static{
    fn new(_cx: &mut Cx) -> Self {
        Vec::new()
    }
    fn new_apply(cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> Self {
        let mut ret = Vec::new();
        ret.apply(cx, from, index, nodes);
        ret
    }
    
    fn live_type_info(_cx: &mut Cx) -> LiveTypeInfo {
        T::live_type_info(_cx)
    }
}


impl<T, const N:usize> LiveHook for [T;N] where T: LiveApply + LiveNew + 'static{}
impl<T, const N:usize> LiveApply for [T;N]  where T: LiveApply + LiveNew + 'static {
    fn apply(&mut self, cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> usize {
        // we can only apply from an Array
        if nodes[index].is_array(){
            let mut index = index + 1;
            let mut count = 0;
            loop{
                if nodes[index].is_close(){
                    index += 1;
                    break;
                }
                if count < self.len(){
                    index = self[count].apply(cx, from, index, nodes);
                    count += 1;
                }
                else{
                   index = nodes.skip_node(index)
                }
            }
            index
        }
        else{
            cx.apply_error_expected_array(live_error_origin!(), index, nodes);
            nodes.skip_node(index)
        }
    }
} 

impl<T, const N:usize> LiveNew for [T;N] where T: LiveApply + LiveNew + 'static{
    fn new(cx: &mut Cx) -> Self {
        std::array::from_fn(|_| T::new(cx))
    }
    
    fn new_apply(cx: &mut Cx, from: ApplyFrom, index: usize, nodes: &[LiveNode]) -> Self {
        let mut ret = Self::new(cx);
        ret.apply(cx, from, index, nodes);
        ret
    }
    
    fn live_type_info(_cx: &mut Cx) -> LiveTypeInfo {
        T::live_type_info(_cx)
    }
}