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
use bitflags::bitflags;
use indextree::Arena;

use std::{
    cell::RefCell,
    collections::HashMap,
    fmt::Debug,
    sync::{
        atomic::{AtomicBool, AtomicUsize},
        Arc, RwLock,
    },
};
use taffy::prelude::{Layout, NodeId as TaffyNodeId};

use crate::{
    drawing::render_node_tree,
    layers::layer::{render_layer::RenderLayer, Layer},
    types::*, // utils::save_image,
};

use super::{draw_to_picture::DrawDebugInfo, NodeRef};
use crate::engine::draw_to_picture::DrawToPicture;

pub(crate) mod contains_point;
pub(crate) mod draw_cache_management;

pub use contains_point::ContainsPoint;
pub use draw_cache_management::DrawCacheManagement;

/// SceneNode is the main data structure for the engine. It contains a model
/// that can be rendered, and a layout node that can be used to position and size the
/// model. As well it contains the data structures that are used to cache
/// the rendering of the model. Caching is done using skia Picture.

#[derive(Clone, Debug)]
pub struct DrawCache {
    picture: Picture,
    size: skia_safe::Size,
    offset: skia_safe::Point,
}
thread_local! {
    static ID_COUNTER: AtomicUsize = const { AtomicUsize::new(0) };
    static SURFACES: RefCell<HashMap<usize, skia_safe::Surface>> = RefCell::new(HashMap::new());
}

impl DrawCache {
    pub fn new(picture: Picture, size: skia_safe::Size, offset: skia_safe::Point) -> Self {
        Self {
            picture,
            size,
            offset,
        }
    }
    pub fn picture(&self) -> &Picture {
        &self.picture
    }
    pub fn size(&self) -> &skia_safe::Size {
        &self.size
    }
    pub fn draw(&self, canvas: &skia_safe::Canvas, paint: &skia_safe::Paint) {
        if self.size.width == 0.0 || self.size.height == 0.0 {
            return;
        }
        canvas.draw_picture(&self.picture, None, Some(paint));
    }
}

bitflags! {
    pub struct RenderableFlags: u32 {
        const NOOP = 1 << 0;
        const NEEDS_LAYOUT = 1 << 1;
        const NEEDS_PAINT = 1 << 2;
        const ANIMATING = 1 << 3;
    }
}

#[derive(Clone)]
pub struct SceneNode {
    pub layer: Layer,
    pub(crate) render_layer: Arc<RwLock<RenderLayer>>,
    pub(crate) draw_cache: Arc<RwLock<Option<DrawCache>>>,
    pub(crate) flags: Arc<RwLock<RenderableFlags>>,
    pub(crate) layout_node_id: TaffyNodeId,
    pub(crate) deleted: Arc<AtomicBool>,
    pub(crate) pointer_hover: Arc<AtomicBool>,
    pub(crate) debug_info: Arc<RwLock<Option<DrawDebugInfo>>>,
    pub(crate) repaint_damage: Arc<RwLock<skia_safe::Rect>>,
    pub(crate) frame: Arc<AtomicUsize>,
    pub(crate) _follow_node: Arc<RwLock<Option<NodeRef>>>,
}

impl SceneNode {
    pub fn id(&self) -> Option<NodeRef> {
        self.layer.id()
    }
    pub fn with_renderable_and_layout(layer: Layer, layout_node: TaffyNodeId) -> Self {
        let render_layer = RenderLayer::default();
        Self {
            layer,
            draw_cache: Arc::new(RwLock::new(None)),
            flags: Arc::new(RwLock::new(
                RenderableFlags::NEEDS_PAINT
                    | RenderableFlags::NEEDS_LAYOUT
                    | RenderableFlags::NEEDS_PAINT,
            )),
            layout_node_id: layout_node,
            render_layer: Arc::new(RwLock::new(render_layer)),
            deleted: Arc::new(AtomicBool::new(false)),
            pointer_hover: Arc::new(AtomicBool::new(false)),
            repaint_damage: Arc::new(RwLock::new(skia_safe::Rect::default())),
            debug_info: Arc::new(RwLock::new(None)),
            frame: Arc::new(AtomicUsize::new(0)),
            _follow_node: Arc::new(RwLock::new(None)),
        }
    }
    pub fn insert_flags(&self, flags: RenderableFlags) {
        self.flags.write().unwrap().insert(flags);
    }
    pub fn remove_flags(&self, flags: RenderableFlags) {
        self.flags.write().unwrap().remove(flags);
    }
    pub fn bounds(&self) -> skia_safe::Rect {
        let render_layer = self.render_layer.read().unwrap();
        render_layer.bounds.with_outset((
            render_layer.border_width / 2.0,
            render_layer.border_width / 2.0,
        ))
    }
    pub fn bounds_with_children(&self) -> skia_safe::Rect {
        let render_layer = self.render_layer.read().unwrap();
        render_layer.bounds_with_children
    }
    pub fn transformed_bounds(&self) -> skia_safe::Rect {
        let render_layer = self.render_layer.read().unwrap();
        render_layer.global_transformed_bounds
    }
    pub fn transformed_bounds_with_effects(&self) -> skia_safe::Rect {
        let render_layer = self.render_layer.read().unwrap();
        render_layer
            .global_transformed_bounds_with_children
            .with_outset((
                render_layer.border_width / 2.0,
                render_layer.border_width / 2.0,
            ))
    }
    pub fn transform(&self) -> Matrix {
        self.render_layer.read().unwrap().transform.to_m33()
    }
    pub fn mark_for_deletion(&self) {
        self.deleted
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }
    pub fn is_deleted(&self) -> bool {
        self.deleted.load(std::sync::atomic::Ordering::Relaxed)
    }
    pub fn set_debug_info(&self, debug_info: bool) {
        let mut dbg_info = self.debug_info.write().unwrap();
        if debug_info {
            let id: usize = self.layer.id().unwrap().0.into();
            *dbg_info = Some(DrawDebugInfo {
                info: format!("{}", id),
                frame: self.frame.load(std::sync::atomic::Ordering::Relaxed),
                render_layer: self.render_layer(),
            });
        } else {
            *dbg_info = None;
        }
        self.layer.set_opacity(self.layer.opacity(), None);
        self.set_need_repaint(true);
    }
    pub fn is_image_cached(&self) -> bool {
        self.layer
            .image_cache
            .load(std::sync::atomic::Ordering::Relaxed)
    }
    pub fn render_layer(&self) -> RenderLayer {
        self.render_layer.read().unwrap().clone()
    }
    pub fn cached_picture(&self) -> Option<DrawCache> {
        let draw_cache = self.draw_cache.read().unwrap();
        if let Some(dc) = &*draw_cache {
            return Some(dc.clone());
        }
        None
    }
    pub(crate) fn increase_frame(&self) {
        if self.is_image_cached() {
            // println!("{:?} increase  _frame", self.id());
            if self
                .frame
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
                > 99999
            {
                self.frame.store(1, std::sync::atomic::Ordering::Relaxed);
            }
        }
    }
    pub(crate) fn change_hover(&self, value: bool) -> bool {
        let hover = self
            .pointer_hover
            .load(std::sync::atomic::Ordering::Relaxed);
        if hover != value {
            self.pointer_hover
                .store(value, std::sync::atomic::Ordering::SeqCst);
            return true;
        }
        false
    }
    pub(crate) fn follow_node(&self, nodeid: &Option<NodeRef>) {
        let mut _follow_node = self._follow_node.write().unwrap();
        *_follow_node = *nodeid;
    }

    pub fn replicate_node(&self, nodeid: &Option<NodeRef>) {
        if let Some(nodeid) = nodeid {
            let nodeid = *nodeid;
            let draw_function =
                move |c: &skia::Canvas, w: f32, h: f32, arena: &Arena<SceneNode>| {
                    render_node_tree(nodeid, arena, c, 1.0);
                    skia::Rect::from_xywh(0.0, 0.0, w, h)
                };

            self.layer.set_draw_content_internal(draw_function);
        }

        self.follow_node(nodeid);
    }
}

impl DrawCacheManagement for SceneNode {
    fn repaint_if_needed(&self, arena: &Arena<SceneNode>) -> skia_safe::Rect {
        let mut damage = skia_safe::Rect::default();
        let render_layer = self.render_layer.read().unwrap();

        if self.layer.hidden() || render_layer.premultiplied_opacity == 0.0 {
            let mut last_damage = self.repaint_damage.write().unwrap();
            let ld = *last_damage;
            *last_damage = damage;
            return ld;
        }
        let mut needs_repaint = self
            .flags
            .read()
            .unwrap()
            .contains(RenderableFlags::NEEDS_PAINT);
        let mut draw_cache = self.draw_cache.write().unwrap();

        // if the size has changed from the layout, we need to repaint
        // the flag want be set if the size has changed from the layout calculations
        if let Some(dc) = &*draw_cache {
            if render_layer.size != *dc.size() {
                needs_repaint = true;
            }
        }
        // FIXME
        if render_layer.blend_mode == BlendMode::BackgroundBlur {
            needs_repaint = true;
        }
        if needs_repaint {
            let (picture, layer_damage) = render_layer.draw_to_picture(arena);
            let (layer_damage_transformed, _) =
                render_layer.transform.to_m33().map_rect(layer_damage);

            damage.join(layer_damage_transformed);
            if self.layer.is_picture_cache() {
                if let Some(picture) = picture {
                    // update or create the draw cache
                    if let Some(dc) = &mut *draw_cache {
                        dc.picture = picture;
                        dc.size = render_layer.size;
                    } else {
                        let size = render_layer.size;

                        let new_cache = DrawCache::new(
                            picture,
                            size,
                            skia_safe::Point {
                                x: render_layer.border_width * 2.0,
                                y: render_layer.border_width * 2.0,
                            },
                        );
                        *draw_cache = Some(new_cache);
                    }
                    let mut repaint_damage = self.repaint_damage.write().unwrap();
                    let previous_damage = *repaint_damage;
                    *repaint_damage = damage;
                    damage.join(previous_damage);
                    self.set_need_repaint(false);
                }
            }
        }
        damage
    }

    fn layout_if_needed(
        &self,
        layout: &Layout,
        matrix: Option<&M44>,
        context_opacity: f32,
        arena: &Arena<SceneNode>,
    ) -> bool {
        if self.layer.hidden() {
            return false;
        }

        if self
            .flags
            .read()
            .unwrap()
            .contains(RenderableFlags::NEEDS_LAYOUT)
        {
            let mut render_layer = self.render_layer.write().unwrap();
            render_layer.update_with_model_and_layout(
                &self.layer.model,
                layout,
                matrix,
                context_opacity,
                self.is_content_cached(),
                arena,
            );

            self.set_need_layout(false);
            // self.increase_frame();
            return true;
        }
        false
    }

    fn set_need_repaint(&self, need_repaint: bool) {
        self.flags
            .write()
            .unwrap()
            .set(RenderableFlags::NEEDS_PAINT, need_repaint);
    }
    fn set_need_layout(&self, need_layout: bool) {
        self.flags
            .write()
            .unwrap()
            .set(RenderableFlags::NEEDS_LAYOUT, need_layout);
    }
    fn needs_repaint(&self) -> bool {
        let render_layer = self.render_layer.read().unwrap();
        let draw_cache = self.draw_cache.read().unwrap();

        let mut needs_repaint = self
            .flags
            .read()
            .unwrap()
            .contains(RenderableFlags::NEEDS_PAINT)
            || render_layer.blend_mode == BlendMode::BackgroundBlur;
        if let Some(dc) = &*draw_cache {
            if render_layer.size != *dc.size() {
                needs_repaint = true;
            }
        }
        needs_repaint
    }
    fn needs_layout(&self) -> bool {
        self.flags
            .read()
            .unwrap()
            .contains(RenderableFlags::NEEDS_LAYOUT)
    }
    fn is_content_cached(&self) -> bool {
        self.layer
            .picture_cache
            .load(std::sync::atomic::Ordering::Relaxed)
    }
}

pub(crate) fn try_get_node(node: &indextree::Node<SceneNode>) -> Option<SceneNode> {
    if node.is_removed() {
        None
    } else {
        Some(node.get().to_owned())
    }
}