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 Rgba16 { width: u32, height: u32, pixels: Vec<u16> },
125}
126
127impl ImageSource {
128 pub fn to_rgba8(&self) -> Option<(u32, u32, std::borrow::Cow<'_, [u8]>)> {
131 match self {
132 ImageSource::Rgba { width, height, pixels } => Some((*width, *height, std::borrow::Cow::Borrowed(&pixels[..]))),
133 ImageSource::Bgra { width, height, pixels } => Some((*width, *height, std::borrow::Cow::Owned(pixels.chunks_exact(4).flat_map(|p| [p[2], p[1], p[0], p[3]]).collect()))),
134 ImageSource::Rgba16 { width, height, pixels } => Some((*width, *height, std::borrow::Cow::Owned(rgba16_to_rgba8(pixels)))),
135 ImageSource::Encoded(_) => None,
136 }
137 }
138}
139
140pub fn rgba16_to_rgba8(pixels: &[u16]) -> Vec<u8> {
142 pixels.iter().map(|&v| ((v as u32 * 255 + 32767) / 65535) as u8).collect()
143}
144
145#[derive(Debug)]
146struct ImageData {
147 id: u64,
148 source: ImageSource,
149}
150
151#[derive(Clone, Debug)]
153pub struct Image(Arc<ImageData>);
154
155impl Image {
156 pub fn encoded(bytes: Vec<u8>) -> Self {
158 Self::new(ImageSource::Encoded(bytes))
159 }
160
161 pub fn shared_file(path: &str, bytes: Vec<u8>) -> Self {
168 let mut files = SHARED_FILES.lock().unwrap_or_else(|e| e.into_inner());
169 if let Some(data) = files.get(path).and_then(Weak::upgrade) {
170 if matches!(&data.source, ImageSource::Encoded(b) if *b == bytes) {
171 return Self(data);
172 }
173 }
174 let image = Self::encoded(bytes);
175 if files.len() >= 64 && files.len().is_power_of_two() && !files.contains_key(path) {
177 files.retain(|_, data| data.strong_count() > 0);
178 }
179 files.insert(path.to_string(), Arc::downgrade(&image.0));
180 image
181 }
182
183 pub fn rgba(width: u32, height: u32, pixels: Vec<u8>) -> Self {
185 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
186 Self::new(ImageSource::Rgba { width, height, pixels })
187 }
188
189 pub fn rgba16(width: u32, height: u32, pixels: Vec<u16>) -> Self {
192 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
193 Self::new(ImageSource::Rgba16 { width, height, pixels })
194 }
195
196 pub fn bgra(width: u32, height: u32, pixels: Vec<u8>) -> Self {
199 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
200 Self::new(ImageSource::Bgra { width, height, pixels })
201 }
202
203 fn new(source: ImageSource) -> Self {
204 Self(Arc::new(ImageData { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), source }))
205 }
206
207 pub fn id(&self) -> u64 {
209 self.0.id
210 }
211
212 pub fn downgrade(&self) -> WeakImage {
215 WeakImage(Arc::downgrade(&self.0))
216 }
217
218 pub fn source(&self) -> &ImageSource {
219 &self.0.source
220 }
221
222 pub fn dominant_color(&self) -> Option<crate::Color> {
225 match &self.0.source {
226 ImageSource::Rgba { width, height, pixels } => dominant_color(*width, *height, pixels),
227 other => {
228 let (w, h, rgba) = other.to_rgba8()?;
229 dominant_color(w, h, &rgba)
230 }
231 }
232 }
233
234 pub fn known_size(&self) -> Option<SizeF> {
236 match &self.0.source {
237 ImageSource::Rgba { width, height, .. } | ImageSource::Bgra { width, height, .. } | ImageSource::Rgba16 { width, height, .. } => {
238 Some(SizeF::new(*width as f32, *height as f32))
239 }
240 ImageSource::Encoded(_) => None,
241 }
242 }
243}
244
245#[derive(Clone, Debug)]
249pub struct WeakImage(Weak<ImageData>);
250
251impl WeakImage {
252 pub fn is_alive(&self) -> bool {
254 self.0.strong_count() > 0
255 }
256}
257
258impl PartialEq for Image {
259 fn eq(&self, other: &Self) -> bool {
260 self.0.id == other.0.id
261 }
262}
263
264#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
266pub enum ImageFit {
267 #[default]
269 Contain,
270 Cover,
272 Stretch,
274 Center,
276 Original,
278}
279
280impl crate::prop::PropEnum for ImageFit {
281 const NAMES: &'static [&'static str] = &["contain", "cover", "stretch", "center", "original"];
282
283 fn from_index(index: usize) -> Option<Self> {
284 [Self::Contain, Self::Cover, Self::Stretch, Self::Center, Self::Original].get(index).copied()
285 }
286
287 fn index(self) -> usize {
288 self as usize
289 }
290}
291
292impl ImageFit {
293 pub fn place(self, image: SizeF, dest: crate::RectF) -> (crate::RectF, crate::RectF) {
296 use crate::RectF;
297 let full = RectF::from_size(image);
298 if image.width <= 0.0 || image.height <= 0.0 {
299 return (full, dest);
300 }
301 let centered = |w: f32, h: f32| RectF::new(dest.x + (dest.width - w) / 2.0, dest.y + (dest.height - h) / 2.0, w, h);
302 match self {
303 ImageFit::Stretch => (full, dest),
304 ImageFit::Contain => {
305 let s = (dest.width / image.width).min(dest.height / image.height);
306 (full, centered(image.width * s, image.height * s))
307 }
308 ImageFit::Cover => {
309 let s = (dest.width / image.width).max(dest.height / image.height);
311 let (w, h) = (dest.width / s, dest.height / s);
312 (RectF::new((image.width - w) / 2.0, (image.height - h) / 2.0, w, h), dest)
313 }
314 ImageFit::Center => (full, centered(image.width, image.height)),
315 ImageFit::Original => (full, RectF::new(dest.x, dest.y, image.width, image.height)),
316 }
317 }
318}
319
320pub fn ico_frame_for_size(bytes: &[u8], size: u32) -> Option<Vec<u8>> {
328 let u16_at = |i: usize| -> Option<u16> { Some(u16::from_le_bytes(bytes.get(i..i + 2)?.try_into().ok()?)) };
329 let u32_at = |i: usize| -> Option<u32> { Some(u32::from_le_bytes(bytes.get(i..i + 4)?.try_into().ok()?)) };
330 if u16_at(0)? != 0 || u16_at(2)? != 1 {
331 return None;
332 }
333 let count = u16_at(4)? as usize;
334 if count < 2 {
335 return None;
336 }
337 let mut frames = Vec::with_capacity(count);
339 for i in 0..count {
340 let at = 6 + i * 16;
341 let entry = bytes.get(at..at + 16)?;
342 let width = if entry[0] == 0 { 256 } else { entry[0] as u32 };
343 let (len, offset) = (u32_at(at + 8)? as usize, u32_at(at + 12)? as usize);
344 let data = bytes.get(offset..offset.checked_add(len)?)?;
345 frames.push((width, u16_at(at + 6)?, entry, data));
346 }
347 let best = frames
349 .iter()
350 .filter(|f| f.0 >= size)
351 .min_by_key(|f| (f.0, std::cmp::Reverse(f.1)))
352 .or_else(|| frames.iter().max_by_key(|f| (f.0, f.1)))?;
353 let mut out = Vec::with_capacity(22 + best.3.len());
354 out.extend_from_slice(&[0, 0, 1, 0, 1, 0]);
355 out.extend_from_slice(&best.2[..12]);
356 out.extend_from_slice(&22u32.to_le_bytes());
357 out.extend_from_slice(best.3);
358 Some(out)
359}