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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use {
    std::{
        any::{TypeId, Any},
        rc::Rc,
    },
    crate::{
        makepad_futures::executor::Spawner,
        makepad_live_id::*,
        makepad_math::{DVec2, Rect},
        gpu_info::GpuInfo,
        cx::{Cx, CxRef, OsType, XrCapabilities},
        event::{
            DragItem, 
            Timer,
            Trigger,
            NextFrame,
            HttpRequest,
        },
        draw_list::DrawListId,
        window::WindowId,
        cursor::MouseCursor,
        area::{
            Area, 
            //DrawListArea
        },
        texture::Texture,
        macos_menu::MacosMenu,
        pass::{
            PassId,
            CxPassRect,
            CxPassParent
        },
    }
};


pub trait CxOsApi {
    fn init_cx_os(&mut self);
    
    fn spawn_thread<F>(&mut self, f: F) where F: FnOnce() + Send + 'static;
    
    fn start_stdin_service(&mut self){}
    fn pre_start()->bool{false}
    /*
    fn web_socket_open(&mut self, url: String, rec: WebSocketAutoReconnect) -> WebSocket;
    fn web_socket_send(&mut self, socket: WebSocket, data: Vec<u8>);*/
}

#[derive(PartialEq)]
pub enum CxOsOp {
    CreateWindow(WindowId),
    CloseWindow(WindowId),
    MinimizeWindow(WindowId),
    MaximizeWindow(WindowId),
    FullscreenWindow(WindowId),
    NormalizeWindow(WindowId),
    RestoreWindow(WindowId),
    SetTopmost(WindowId, bool),
    
    XrStartPresenting,
    XrStopPresenting,
    
    ShowTextIME(Area, DVec2),
    HideTextIME,
    SetCursor(MouseCursor),
    StartTimer {timer_id: u64, interval: f64, repeats: bool},
    StopTimer(u64),
    Quit,
    
    StartDragging(Vec<DragItem>),
    UpdateMacosMenu(MacosMenu),
    ShowClipboardActions(String),

    HttpRequest{request_id: LiveId, request:HttpRequest},

    WebSocketOpen{request_id: LiveId, request:HttpRequest},
    WebSocketSendString{request_id: LiveId, data:String},
    WebSocketSendBinary{request_id: LiveId, data:Vec<u8>},

    InitializeVideoDecoding(LiveId, Rc<Vec<u8>>, usize),
    DecodeNextVideoChunk(LiveId, usize),
    FetchNextVideoFrames(LiveId, usize),
    CleanupVideoDecoding(LiveId),
}

impl Cx { 
    pub fn xr_capabilities(&self) -> &XrCapabilities {
        &self.xr_capabilities 
    } 
    
    pub fn get_ref(&self)->CxRef{
        CxRef(self.self_ref.clone().unwrap())
    }
    
    pub fn get_dependency(&self, path: &str) -> Result<Rc<Vec<u8>>,
    String> { 
        if let Some(data) = self.dependencies.get(path) {
            if let Some(data) = &data.data {
                return match data {
                    Ok(data) => Ok(data.clone()),
                    Err(s) => Err(s.clone())
                }
            } 
        }
        Err(format!("Dependency not loaded {}", path))
    }
    pub fn null_texture(&self)->Texture{self.null_texture.clone()}
    pub fn redraw_id(&self) -> u64 {self.redraw_id}
    
    pub fn os_type(&self) -> &OsType {&self.os_type}
    pub fn in_makepad_studio(&self)->bool {self.in_makepad_studio}
    
    pub fn cpu_cores(&self) -> usize {self.cpu_cores}
    pub fn gpu_info(&self) -> &GpuInfo {&self.gpu_info}
    
    pub fn update_macos_menu(&mut self, menu: MacosMenu) {
        self.platform_ops.push(CxOsOp::UpdateMacosMenu(menu));
    }
    
    pub fn quit(&mut self){
        self.platform_ops.push(CxOsOp::Quit);
    }
    
    pub fn push_unique_platform_op(&mut self, op: CxOsOp) {
        if self.platform_ops.iter().find( | o | **o == op).is_none() {
            self.platform_ops.push(op);
        }
    }
    
    pub fn show_text_ime(&mut self, area: Area, pos: DVec2) {
        if !self.keyboard.text_ime_dismissed {
            self.ime_area = area;
            self.platform_ops.push(CxOsOp::ShowTextIME(area, pos));
        }
    }
    
    pub fn hide_text_ime(&mut self) {
        self.keyboard.reset_text_ime_dismissed();
        self.platform_ops.push(CxOsOp::HideTextIME);
    }

    pub fn text_ime_was_dismissed(&mut self) {
        self.keyboard.set_text_ime_dismissed();
        self.platform_ops.push(CxOsOp::HideTextIME);
    }

    pub fn show_clipboard_actions(&mut self, selected: String) {
        self.platform_ops.push(CxOsOp::ShowClipboardActions(selected));
    }

    pub fn start_dragging(&mut self, items: Vec<DragItem>) {
        self.platform_ops.iter().for_each( | p | {
            if let CxOsOp::StartDragging{..} = p {
                panic!("start drag twice");
            }
        });
        self.platform_ops.push(CxOsOp::StartDragging(items));
    }
    
    pub fn set_cursor(&mut self, cursor: MouseCursor) {
        // down cursor overrides the hover cursor
        if let Some(p) = self.platform_ops.iter_mut().find( | p | match p {
            CxOsOp::SetCursor(_) => true,
            _ => false
        }) {
            *p = CxOsOp::SetCursor(cursor)
        }
        else {
            self.platform_ops.push(CxOsOp::SetCursor(cursor))
        }
    }
    
    pub fn sweep_lock(&mut self, value:Area){
        self.fingers.sweep_lock(value);
    }
    
    pub fn sweep_unlock(&mut self, value:Area){
        self.fingers.sweep_unlock(value);
    }
    
    pub fn start_timeout(&mut self, interval: f64) -> Timer {
        self.timer_id += 1;
        self.platform_ops.push(CxOsOp::StartTimer {
            timer_id: self.timer_id,
            interval,
            repeats: false
        });
        Timer(self.timer_id)
    }
    
    pub fn start_interval(&mut self, interval: f64) -> Timer {
        self.timer_id += 1;
        self.platform_ops.push(CxOsOp::StartTimer {
            timer_id: self.timer_id,
            interval,
            repeats: true
        });
        Timer(self.timer_id)
    }
    
    
    
    
    pub fn stop_timer(&mut self, timer: Timer) {
        if timer.0 != 0 {
            self.platform_ops.push(CxOsOp::StopTimer(timer.0));
        }
    }
    
    pub fn xr_start_presenting(&mut self) {
        self.platform_ops.push(CxOsOp::XrStartPresenting);
    }
    
    pub fn xr_stop_presenting(&mut self) {
        self.platform_ops.push(CxOsOp::XrStopPresenting);
    }
    
    pub fn get_dpi_factor_of(&mut self, area: &Area) -> f64 {
        if let Some(draw_list_id) = area.draw_list_id() {
            let pass_id = self.draw_lists[draw_list_id].pass_id.unwrap();
            return self.get_delegated_dpi_factor(pass_id)
        }
        return 1.0;
    }
    
    pub fn get_delegated_dpi_factor(&mut self, pass_id: PassId) -> f64 {
        let mut pass_id_walk = pass_id;
        for _ in 0..25 {
            match self.passes[pass_id_walk].parent {
                CxPassParent::Window(window_id) => {
                    if !self.windows[window_id].is_created {
                        return 1.0
                    }
                    return self.windows[window_id].window_geom.dpi_factor;
                },
                CxPassParent::Pass(next_pass_id) => {
                    pass_id_walk = next_pass_id;
                },
                _ => {break;}
            }
        }
        1.0
    }
    
    pub fn redraw_pass_and_parent_passes(&mut self, pass_id: PassId) {
        let mut walk_pass_id = pass_id;
        loop {
            if let Some(main_list_id) = self.passes[walk_pass_id].main_draw_list_id {
                self.redraw_list_and_children(main_list_id);
            }
            match self.passes[walk_pass_id].parent.clone() {
                CxPassParent::Pass(next_pass_id) => {
                    walk_pass_id = next_pass_id;
                },
                _ => {
                    break;
                }
            }
        } 
    }
    
    pub fn get_pass_rect(&self, pass_id: PassId, dpi:f64) -> Option<Rect> {
        match self.passes[pass_id].pass_rect {
            Some(CxPassRect::Area(area)) => {
                let rect = area.get_rect(self);
                Some(Rect{
                    pos: (rect.pos * dpi).floor() / dpi,
                    size: (rect.size * dpi).ceil() / dpi
                })
            }
            Some(CxPassRect::ScaledArea(area, scale)) => {
                let rect = area.get_rect(self);
                Some(Rect{
                    pos: (rect.pos * dpi).floor() / dpi,
                    size:  scale * (rect.size * dpi).ceil() / dpi
                })
            }
            Some(CxPassRect::Size(size)) => Some(Rect {pos: DVec2::default(), size: (size / dpi).floor() * dpi}),
            None => None
        } 
    }
    
    pub fn get_pass_rect2(&self, pass_id: PassId, dpi:f64) -> Option<Rect> {
        match self.passes[pass_id].pass_rect {
            Some(CxPassRect::Area(area)) => {
                let rect = area.get_rect(self);
                Some(Rect{
                    pos: (rect.pos * dpi).floor() / dpi,
                    size: (rect.size * dpi).ceil() / dpi
                })
            }
            Some(CxPassRect::ScaledArea(area, scale)) => {
                let rect = area.get_rect(self);
                Some(Rect{
                    pos: (rect.pos * dpi).floor() / dpi,
                    size:  scale * (rect.size * dpi).ceil() / dpi
                })
            }
            Some(CxPassRect::Size(size)) => {
                Some(Rect {pos: DVec2::default(), size: (size * dpi).floor() / dpi})
            }
            None => None
        } 
    }
    
    pub fn get_pass_name(&self, pass_id: PassId) -> &str {
        &self.passes[pass_id].debug_name
    }
    
    pub fn repaint_pass(&mut self, pass_id: PassId) {
        let cxpass = &mut self.passes[pass_id];
        cxpass.paint_dirty = true;
    }
    
    pub fn repaint_pass_and_child_passes(&mut self, pass_id: PassId) {
        let cxpass = &mut self.passes[pass_id];
        cxpass.paint_dirty = true;
        for sub_pass_id in self.passes.id_iter() {
            if let CxPassParent::Pass(dep_pass_id) = self.passes[sub_pass_id].parent.clone() {
                if dep_pass_id == pass_id {
                    self.repaint_pass_and_child_passes(sub_pass_id);
                }
            }
        }
    }
    
    pub fn redraw_pass_and_child_passes(&mut self, pass_id: PassId) {
        let cxpass = &self.passes[pass_id];
        if let Some(main_list_id) = cxpass.main_draw_list_id {
            self.redraw_list_and_children(main_list_id);
        }
        // lets redraw all subpasses as well
        for sub_pass_id in self.passes.id_iter() {
            if let CxPassParent::Pass(dep_pass_id) = self.passes[sub_pass_id].parent.clone() {
                if dep_pass_id == pass_id {
                    self.redraw_pass_and_child_passes(sub_pass_id);
                }
            }
        }
    }
    
    pub fn redraw_all(&mut self) {
        self.new_draw_event.redraw_all = true;
    }
    
    pub fn redraw_area(&mut self, area: Area) {
        if let Some(draw_list_id) = area.draw_list_id() {
            self.redraw_list(draw_list_id);
        }
    }
    
    pub fn redraw_area_and_children(&mut self, area: Area) {
        if let Some(draw_list_id) = area.draw_list_id() {
            self.redraw_list_and_children(draw_list_id);
        }
    }
    
    pub fn redraw_list(&mut self, draw_list_id: DrawListId) {
        if self.new_draw_event.draw_lists.iter().position( | v | *v == draw_list_id).is_some() {
            return;
        }
        self.new_draw_event.draw_lists.push(draw_list_id);
    }
    
    pub fn redraw_list_and_children(&mut self, draw_list_id: DrawListId) {
        if self.new_draw_event.draw_lists_and_children.iter().position( | v | *v == draw_list_id).is_some() {
            return;
        }
        self.new_draw_event.draw_lists_and_children.push(draw_list_id);
    }
    
    pub fn get_ime_area_rect(&self)->Rect{
        self.ime_area.get_rect(self)
    }
    
    pub fn update_area_refs(&mut self, old_area: Area, new_area: Area) -> Area {
        if old_area == Area::Empty {
            return new_area
        }
        if self.ime_area == old_area {
            self.ime_area = new_area;
        }
        self.fingers.update_area(old_area, new_area);
        self.drag_drop.update_area(old_area, new_area);
        self.keyboard.update_area(old_area, new_area);
        
        new_area
    }
    
    pub fn set_key_focus(&mut self, focus_area: Area) {
        self.keyboard.set_key_focus(focus_area);
    }
    
    pub fn revert_key_focus(&mut self) {
        self.keyboard.revert_key_focus();
    }
    
    pub fn has_key_focus(&self, focus_area: Area) -> bool {
        self.keyboard.has_key_focus(focus_area)
    }
    
    pub fn new_next_frame(&mut self) -> NextFrame {
        let res = NextFrame(self.next_frame_id);
        self.next_frame_id += 1;
        self.new_next_frames.insert(res);
        res
    }
    
    pub fn send_trigger(&mut self, area: Area, trigger: Trigger) {
        if let Some(triggers) = self.triggers.get_mut(&area) {
            triggers.push(trigger);
        }
        else {
            let mut new_set = Vec::new();
            new_set.push(trigger);
            self.triggers.insert(area, new_set);
        }
    }
    
    pub fn set_global<T: 'static + Any + Sized>(&mut self, value: T) {
        if !self.globals.iter().any( | v | v.0 == TypeId::of::<T>()) {
            self.globals.push((TypeId::of::<T>(), Box::new(value)));
        }
    }
    
    pub fn get_global<T: 'static + Any>(&mut self) -> &mut T {
        let item = self.globals.iter_mut().find( | v | v.0 == TypeId::of::<T>()).unwrap();
        item.1.downcast_mut().unwrap()
    }
    
    pub fn has_global<T: 'static + Any>(&mut self) -> bool {
        self.globals.iter_mut().find( | v | v.0 == TypeId::of::<T>()).is_some()
    }
    
    pub fn global<T: 'static + Any + Default>(&mut self) -> &mut T {
        if !self.has_global::<T>() {
            self.set_global(T::default());
        }
        self.get_global::<T>()
    }

    pub fn spawner(&self) -> &Spawner {
        &self.spawner
    }

    pub fn http_request(&mut self, request_id: LiveId, request: HttpRequest) {
        self.platform_ops.push(CxOsOp::HttpRequest{request_id, request});
    }
           
    pub fn web_socket_open(&mut self, request_id: LiveId, request: HttpRequest) {
        self.platform_ops.push(CxOsOp::WebSocketOpen{
            request,
            request_id,
        });
    }
    
    pub fn web_socket_send_binary(&mut self, request_id: LiveId, data: Vec<u8>) {
        self.platform_ops.push(CxOsOp::WebSocketSendBinary{
            request_id,
            data,
        });
    }

    pub fn initialize_video_decoding(&mut self, video_id: LiveId, video: Rc<Vec<u8>>, chunk_size: usize) {
        self.platform_ops.push(CxOsOp::InitializeVideoDecoding(video_id, video, chunk_size));
    }

    pub fn decode_next_video_chunk(&mut self, video_id: LiveId, max_frames_to_decode: usize) {
        self.platform_ops.push(CxOsOp::DecodeNextVideoChunk(video_id, max_frames_to_decode));
    }

    pub fn fetch_next_video_frames(&mut self, video_id: LiveId, number_frames: usize) {
        self.platform_ops.push(CxOsOp::FetchNextVideoFrames(video_id, number_frames));
    }

    pub fn cleanup_video_decoding(&mut self, video_id: LiveId) {
        self.platform_ops.push(CxOsOp::CleanupVideoDecoding(video_id));
    }
    
    pub fn println_resources(&self){
        println!("Num textures: {}",self.textures.0.pool.len());
    }
}

#[macro_export]
macro_rules!register_component_factory {
    ( $ cx: ident, $ registry: ident, $ ty: ty, $ factory: ident) => {
        let module_id = LiveModuleId::from_str(&module_path!()).unwrap();
        if let Some((reg, _)) = $ cx.live_registry.borrow().components.get_or_create::< $ registry>().map.get(&LiveType::of::< $ ty>()) {
            if reg.module_id != module_id {
                panic!("Component already registered {} {}", stringify!( $ ty), reg.module_id);
            }
        }
        $ cx.live_registry.borrow().components.get_or_create::< $ registry>().map.insert(
            LiveType::of::< $ ty>(),
            (LiveComponentInfo {
                name: LiveId::from_str_with_lut(stringify!( $ ty)).unwrap(),
                module_id
            }, Box::new( $ factory()))
        );
    }
}