1use std::collections::HashMap;
9use std::sync::{Arc, LazyLock, Mutex, Weak};
10use std::sync::atomic::{AtomicU64, Ordering};
11
12use crate::geometry::SizeF;
13
14static NEXT_ID: AtomicU64 = AtomicU64::new(1);
15
16static SHARED_FILES: LazyLock<Mutex<HashMap<String, Weak<ImageData>>>> = LazyLock::new(Mutex::default);
18
19pub const MAX_IMAGE_SIDE: u32 = 16_384;
22pub const MAX_IMAGE_PIXELS: u64 = 100_000_000;
24
25pub fn encode_base64(bytes: &[u8]) -> String {
28 const ABC: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
29 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
30 for chunk in bytes.chunks(3) {
31 let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | (*b as u32) << (16 - 8 * i));
32 for i in 0..4 {
33 out.push(if i <= chunk.len() { ABC[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
34 }
35 }
36 out
37}
38
39pub fn decode_base64(text: &str) -> Option<Vec<u8>> {
42 let value = |c: u8| -> Option<u32> {
43 Some(match c {
44 b'A'..=b'Z' => c - b'A',
45 b'a'..=b'z' => c - b'a' + 26,
46 b'0'..=b'9' => c - b'0' + 52,
47 b'+' | b'-' => 62,
48 b'/' | b'_' => 63,
49 _ => return None,
50 } as u32)
51 };
52 let clean: Vec<u8> = text.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=').collect();
53 let mut out = Vec::with_capacity(clean.len() * 3 / 4);
54 for chunk in clean.chunks(4) {
55 let mut n = 0u32;
56 for (i, c) in chunk.iter().enumerate() {
57 n |= value(*c)? << (18 - 6 * i);
58 }
59 for i in 0..chunk.len().saturating_sub(1) {
60 out.push((n >> (16 - 8 * i) & 0xFF) as u8);
61 }
62 }
63 Some(out)
64}
65
66pub fn dominant_color(width: u32, height: u32, rgba: &[u8]) -> Option<crate::Color> {
71 let total = width as usize * height as usize;
72 if total == 0 || rgba.len() < total * 4 {
73 return None;
74 }
75 let step = (total / 4096).max(1);
76 let mut boxes = vec![(0u64, 0u64, 0u64, 0u32); 512];
78 let mut all = (0u64, 0u64, 0u64, 0u32);
79 for px in rgba.chunks_exact(4).step_by(step) {
80 let (r, g, b, a) = (px[0] as u64, px[1] as u64, px[2] as u64, px[3]);
81 if a < 128 {
82 continue;
83 }
84 all = (all.0 + r, all.1 + g, all.2 + b, all.3 + 1);
85 let (max, min) = (r.max(g).max(b), r.min(g).min(b));
86 if max < 30 || min > 225 {
87 continue;
88 }
89 let i = ((r >> 5) << 6 | (g >> 5) << 3 | (b >> 5)) as usize;
90 let e = &mut boxes[i];
91 *e = (e.0 + r, e.1 + g, e.2 + b, e.3 + 1);
92 }
93 let (r, g, b, n) = boxes.into_iter().max_by_key(|e| e.3).filter(|e| e.3 > 0).unwrap_or(all);
94 (n > 0).then(|| crate::Color::rgb((r / n as u64) as u8, (g / n as u64) as u8, (b / n as u64) as u8))
95}
96
97pub fn checked_size(width: u32, height: u32) -> Result<usize, String> {
101 if width == 0 || height == 0 {
102 return Err(format!("imagem vazia ({width} × {height})"));
103 }
104 if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE || width as u64 * height as u64 > MAX_IMAGE_PIXELS {
105 return Err(format!("imagem grande demais: {width} × {height} (máximo {MAX_IMAGE_SIDE} por lado e {} megapixels)", MAX_IMAGE_PIXELS / 1_000_000));
106 }
107 usize::try_from(width as u64 * height as u64 * 4).map_err(|_| format!("imagem grande demais: {width} × {height}"))
108}
109
110#[derive(Debug, PartialEq)]
112pub enum ImageSource {
113 Encoded(Vec<u8>),
115 Rgba { width: u32, height: u32, pixels: Vec<u8> },
117 Bgra { width: u32, height: u32, pixels: Vec<u8> },
120}
121
122#[derive(Debug)]
123struct ImageData {
124 id: u64,
125 source: ImageSource,
126}
127
128#[derive(Clone, Debug)]
130pub struct Image(Arc<ImageData>);
131
132impl Image {
133 pub fn encoded(bytes: Vec<u8>) -> Self {
135 Self::new(ImageSource::Encoded(bytes))
136 }
137
138 pub fn shared_file(path: &str, bytes: Vec<u8>) -> Self {
145 let mut files = SHARED_FILES.lock().unwrap_or_else(|e| e.into_inner());
146 if let Some(data) = files.get(path).and_then(Weak::upgrade) {
147 if matches!(&data.source, ImageSource::Encoded(b) if *b == bytes) {
148 return Self(data);
149 }
150 }
151 let image = Self::encoded(bytes);
152 if files.len() >= 64 && files.len().is_power_of_two() && !files.contains_key(path) {
154 files.retain(|_, data| data.strong_count() > 0);
155 }
156 files.insert(path.to_string(), Arc::downgrade(&image.0));
157 image
158 }
159
160 pub fn rgba(width: u32, height: u32, pixels: Vec<u8>) -> Self {
162 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
163 Self::new(ImageSource::Rgba { width, height, pixels })
164 }
165
166 pub fn bgra(width: u32, height: u32, pixels: Vec<u8>) -> Self {
169 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
170 Self::new(ImageSource::Bgra { width, height, pixels })
171 }
172
173 fn new(source: ImageSource) -> Self {
174 Self(Arc::new(ImageData { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), source }))
175 }
176
177 pub fn id(&self) -> u64 {
179 self.0.id
180 }
181
182 pub fn downgrade(&self) -> WeakImage {
185 WeakImage(Arc::downgrade(&self.0))
186 }
187
188 pub fn source(&self) -> &ImageSource {
189 &self.0.source
190 }
191
192 pub fn dominant_color(&self) -> Option<crate::Color> {
195 match &self.0.source {
196 ImageSource::Rgba { width, height, pixels } => dominant_color(*width, *height, pixels),
197 ImageSource::Bgra { width, height, pixels } => {
198 let rgba: Vec<u8> = pixels.chunks_exact(4).flat_map(|p| [p[2], p[1], p[0], p[3]]).collect();
199 dominant_color(*width, *height, &rgba)
200 }
201 ImageSource::Encoded(_) => None,
202 }
203 }
204
205 pub fn known_size(&self) -> Option<SizeF> {
207 match &self.0.source {
208 ImageSource::Rgba { width, height, .. } | ImageSource::Bgra { width, height, .. } => {
209 Some(SizeF::new(*width as f32, *height as f32))
210 }
211 ImageSource::Encoded(_) => None,
212 }
213 }
214}
215
216#[derive(Clone, Debug)]
220pub struct WeakImage(Weak<ImageData>);
221
222impl WeakImage {
223 pub fn is_alive(&self) -> bool {
225 self.0.strong_count() > 0
226 }
227}
228
229impl PartialEq for Image {
230 fn eq(&self, other: &Self) -> bool {
231 self.0.id == other.0.id
232 }
233}
234
235#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
237pub enum ImageFit {
238 #[default]
240 Contain,
241 Cover,
243 Stretch,
245 Center,
247 Original,
249}
250
251impl crate::prop::PropEnum for ImageFit {
252 const NAMES: &'static [&'static str] = &["contain", "cover", "stretch", "center", "original"];
253
254 fn from_index(index: usize) -> Option<Self> {
255 [Self::Contain, Self::Cover, Self::Stretch, Self::Center, Self::Original].get(index).copied()
256 }
257
258 fn index(self) -> usize {
259 self as usize
260 }
261}
262
263impl ImageFit {
264 pub fn place(self, image: SizeF, dest: crate::RectF) -> (crate::RectF, crate::RectF) {
267 use crate::RectF;
268 let full = RectF::from_size(image);
269 if image.width <= 0.0 || image.height <= 0.0 {
270 return (full, dest);
271 }
272 let centered = |w: f32, h: f32| RectF::new(dest.x + (dest.width - w) / 2.0, dest.y + (dest.height - h) / 2.0, w, h);
273 match self {
274 ImageFit::Stretch => (full, dest),
275 ImageFit::Contain => {
276 let s = (dest.width / image.width).min(dest.height / image.height);
277 (full, centered(image.width * s, image.height * s))
278 }
279 ImageFit::Cover => {
280 let s = (dest.width / image.width).max(dest.height / image.height);
282 let (w, h) = (dest.width / s, dest.height / s);
283 (RectF::new((image.width - w) / 2.0, (image.height - h) / 2.0, w, h), dest)
284 }
285 ImageFit::Center => (full, centered(image.width, image.height)),
286 ImageFit::Original => (full, RectF::new(dest.x, dest.y, image.width, image.height)),
287 }
288 }
289}
290
291pub fn ico_frame_for_size(bytes: &[u8], size: u32) -> Option<Vec<u8>> {
299 let u16_at = |i: usize| -> Option<u16> { Some(u16::from_le_bytes(bytes.get(i..i + 2)?.try_into().ok()?)) };
300 let u32_at = |i: usize| -> Option<u32> { Some(u32::from_le_bytes(bytes.get(i..i + 4)?.try_into().ok()?)) };
301 if u16_at(0)? != 0 || u16_at(2)? != 1 {
302 return None;
303 }
304 let count = u16_at(4)? as usize;
305 if count < 2 {
306 return None;
307 }
308 let mut frames = Vec::with_capacity(count);
310 for i in 0..count {
311 let at = 6 + i * 16;
312 let entry = bytes.get(at..at + 16)?;
313 let width = if entry[0] == 0 { 256 } else { entry[0] as u32 };
314 let (len, offset) = (u32_at(at + 8)? as usize, u32_at(at + 12)? as usize);
315 let data = bytes.get(offset..offset.checked_add(len)?)?;
316 frames.push((width, u16_at(at + 6)?, entry, data));
317 }
318 let best = frames
320 .iter()
321 .filter(|f| f.0 >= size)
322 .min_by_key(|f| (f.0, std::cmp::Reverse(f.1)))
323 .or_else(|| frames.iter().max_by_key(|f| (f.0, f.1)))?;
324 let mut out = Vec::with_capacity(22 + best.3.len());
325 out.extend_from_slice(&[0, 0, 1, 0, 1, 0]);
326 out.extend_from_slice(&best.2[..12]);
327 out.extend_from_slice(&22u32.to_le_bytes());
328 out.extend_from_slice(best.3);
329 Some(out)
330}