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
use crate::{makepad_draw::*};
use std::collections::HashMap;
use makepad_zune_jpeg::JpegDecoder;
use makepad_zune_png::PngDecoder;


#[derive(Live, LiveHook)]
#[live_ignore]
pub enum ImageFit{
    #[pick] Stretch,
    Horizontal,
    Vertical,
    Smallest,
    Biggest
}


#[derive(Default, Clone)] 
pub struct ImageBuffer {
    pub width: usize,
    pub height: usize,
    pub data: Vec<u32>,
}

impl ImageBuffer {
    pub fn new(in_data: &[u8], width: usize,height: usize) -> Result<ImageBuffer, String> {
        let mut out = Vec::new();
        let pixels = width * height;
        out.resize(pixels, 0u32);
        // input pixel packing
        if in_data.len() /  pixels== 3{
            for i in 0..pixels{
                let r = in_data[i*3];
                let g = in_data[i*3+1];
                let b = in_data[i*3+2];
                out[i] = 0xff000000 | ((r as u32)<<16) | ((g as u32)<<8) | ((b as u32)<<0);
            }
        }
        else if in_data.len() / pixels == 4{
            for i in 0..pixels{
                let r = in_data[i*4];
                let g = in_data[i*4+1];
                let b = in_data[i*4+2];
                let a = in_data[i*4+3];
                out[i] = ((a as u32)<<24) | ((r as u32)<<16) | ((g as u32)<<8) | ((b as u32)<<0);
            }
        }
        else{
            return Err("ImageBuffer::new Image buffer pixel alignment not 3 or 4".to_string())
        }
        Ok(ImageBuffer {
            width,
            height,
            data: out
        })
    }
    
    pub fn into_new_texture(self, cx:&mut Cx)->Texture{
        let texture = Texture::new(cx);
        self.into_texture(cx, &texture);
        texture
    }
    
    pub fn into_texture(mut self, cx:&mut Cx, texture:&Texture){
        texture.set_desc(
            cx,
            TextureDesc {
                format: TextureFormat::ImageBGRA,
                width: Some(self.width),
                height: Some(self.height),
            },
        );
        texture.swap_image_u32(cx, &mut self.data);
    }
    
    
    pub fn from_png(
        data: &[u8]
    ) -> Result<Self, String> {
        let mut decoder = PngDecoder::new(data);
        match decoder.decode() {
            Ok(image) => {
                if let Some(data) = image.u8(){
                    let (width,height) = decoder.get_dimensions().unwrap();
                    ImageBuffer::new(&data, width as usize, height as usize)
                }
                else{
                    Err("Error decoding PNG: image data empty".to_string())
                }
            }
            Err(err) => {
                Err(format!("Error decoding PNG: {:?}", err))
            }
        }
    }

    pub fn from_jpg(
        data: &[u8]
    ) -> Result<Self, String> {
        let mut decoder = JpegDecoder::new(&*data);
        // decode the file
        match decoder.decode() {
            Ok(data) => {
                let info = decoder.info().unwrap();
                ImageBuffer::new(&data, info.width as usize, info.height as usize)
            },
            Err(err) => {
                Err(format!("Error decoding JPG: {:?}", err))
            }
        }
    }
}

pub struct ImageCache {
    map: HashMap<String, Texture>,
}

impl ImageCache {
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
        }
    }
}

pub trait ImageCacheImpl {
    fn get_texture(&self) -> &Option<Texture>;
    fn set_texture(&mut self, texture: Option<Texture>);

    fn lazy_create_image_cache(&mut self,cx: &mut Cx) {
        if !cx.has_global::<ImageCache>() {
            cx.set_global(ImageCache::new());
        }
    }


    fn load_png_from_data(&mut self, cx:&mut Cx, data:&[u8]){
        match ImageBuffer::from_png(&*data){
            Ok(data)=>{
                if let Some(texture) = self.get_texture(){
                    data.into_texture(cx, texture);
                }
                else{
                    self.set_texture(Some(data.into_new_texture(cx)));
                }
            }
            Err(err)=>{
                error!("load_png_from_data: Cannot load png image from data {}", err);
            }
        }
    }
    
    fn load_jpg_from_data(&mut self, cx:&mut Cx, data:&[u8]){
        match ImageBuffer::from_jpg(&*data){
            Ok(data)=>{
                if let Some(texture) = self.get_texture(){
                    data.into_texture(cx, texture);
                }
                else{
                    self.set_texture(Some(data.into_new_texture(cx)));
                }
            }
            Err(err)=>{
                error!("load_jpg_from_data: Cannot load png image from data {}", err);
            }
        }
    }

    fn load_image_dep_by_path(
        &mut self,
        cx: &mut Cx,
        image_path: &str,
    ) {
        if let Some(texture) = cx.get_global::<ImageCache>().map.get(image_path){
            self.set_texture(Some(texture.clone()));
        }
        else{
            match cx.get_dependency(image_path) {
                Ok(data) => {
                    if image_path.ends_with(".jpg") {
                        match ImageBuffer::from_jpg(&*data){
                            Ok(data)=>{
                                let texture = data.into_new_texture(cx);
                                cx.get_global::<ImageCache>().map.insert(image_path.to_string(), texture.clone());
                                self.set_texture(Some(texture));
                            }
                            Err(err)=>{
                                error!("load_image_dep_by_path: Cannot load jpeg image from path: {} {}",image_path, err);
                            }
                        }
                    } else if image_path.ends_with(".png") {
                        match ImageBuffer::from_png(&*data){
                            Ok(data)=>{
                                let texture = data.into_new_texture(cx);
                                cx.get_global::<ImageCache>().map.insert(image_path.to_string(), texture.clone());
                                self.set_texture(Some(texture));
                            }
                            Err(err)=>{
                                error!("load_image_dep_by_path: Cannot load png image from path: {} {}",image_path, err);
                            }
                        }
                    } else {
                        error!("load_image_dep_by_path: Image format not supported {}",image_path);
                    }
                }
                Err(err) => {
                    error!("load_image_dep_by_path:  Resource not found {} {}",image_path, err);
                }
            }
        }
    }
}