1use std::sync::{Arc, Weak};
9use std::sync::atomic::{AtomicU64, Ordering};
10
11use crate::geometry::SizeF;
12
13static NEXT_ID: AtomicU64 = AtomicU64::new(1);
14
15pub const MAX_IMAGE_SIDE: u32 = 16_384;
18pub const MAX_IMAGE_PIXELS: u64 = 100_000_000;
20
21pub fn encode_base64(bytes: &[u8]) -> String {
24 const ABC: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
25 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
26 for chunk in bytes.chunks(3) {
27 let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | (*b as u32) << (16 - 8 * i));
28 for i in 0..4 {
29 out.push(if i <= chunk.len() { ABC[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
30 }
31 }
32 out
33}
34
35pub fn decode_base64(text: &str) -> Option<Vec<u8>> {
38 let value = |c: u8| -> Option<u32> {
39 Some(match c {
40 b'A'..=b'Z' => c - b'A',
41 b'a'..=b'z' => c - b'a' + 26,
42 b'0'..=b'9' => c - b'0' + 52,
43 b'+' | b'-' => 62,
44 b'/' | b'_' => 63,
45 _ => return None,
46 } as u32)
47 };
48 let clean: Vec<u8> = text.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=').collect();
49 let mut out = Vec::with_capacity(clean.len() * 3 / 4);
50 for chunk in clean.chunks(4) {
51 let mut n = 0u32;
52 for (i, c) in chunk.iter().enumerate() {
53 n |= value(*c)? << (18 - 6 * i);
54 }
55 for i in 0..chunk.len().saturating_sub(1) {
56 out.push((n >> (16 - 8 * i) & 0xFF) as u8);
57 }
58 }
59 Some(out)
60}
61
62pub fn dominant_color(width: u32, height: u32, rgba: &[u8]) -> Option<crate::Color> {
67 let total = width as usize * height as usize;
68 if total == 0 || rgba.len() < total * 4 {
69 return None;
70 }
71 let step = (total / 4096).max(1);
72 let mut boxes = vec![(0u64, 0u64, 0u64, 0u32); 512];
74 let mut all = (0u64, 0u64, 0u64, 0u32);
75 for px in rgba.chunks_exact(4).step_by(step) {
76 let (r, g, b, a) = (px[0] as u64, px[1] as u64, px[2] as u64, px[3]);
77 if a < 128 {
78 continue;
79 }
80 all = (all.0 + r, all.1 + g, all.2 + b, all.3 + 1);
81 let (max, min) = (r.max(g).max(b), r.min(g).min(b));
82 if max < 30 || min > 225 {
83 continue;
84 }
85 let i = ((r >> 5) << 6 | (g >> 5) << 3 | (b >> 5)) as usize;
86 let e = &mut boxes[i];
87 *e = (e.0 + r, e.1 + g, e.2 + b, e.3 + 1);
88 }
89 let (r, g, b, n) = boxes.into_iter().max_by_key(|e| e.3).filter(|e| e.3 > 0).unwrap_or(all);
90 (n > 0).then(|| crate::Color::rgb((r / n as u64) as u8, (g / n as u64) as u8, (b / n as u64) as u8))
91}
92
93pub fn checked_size(width: u32, height: u32) -> Result<usize, String> {
97 if width == 0 || height == 0 {
98 return Err(format!("imagem vazia ({width} × {height})"));
99 }
100 if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE || width as u64 * height as u64 > MAX_IMAGE_PIXELS {
101 return Err(format!("imagem grande demais: {width} × {height} (máximo {MAX_IMAGE_SIDE} por lado e {} megapixels)", MAX_IMAGE_PIXELS / 1_000_000));
102 }
103 usize::try_from(width as u64 * height as u64 * 4).map_err(|_| format!("imagem grande demais: {width} × {height}"))
104}
105
106#[derive(Debug, PartialEq)]
108pub enum ImageSource {
109 Encoded(Vec<u8>),
111 Rgba { width: u32, height: u32, pixels: Vec<u8> },
113 Bgra { width: u32, height: u32, pixels: Vec<u8> },
116}
117
118#[derive(Debug)]
119struct ImageData {
120 id: u64,
121 source: ImageSource,
122}
123
124#[derive(Clone, Debug)]
126pub struct Image(Arc<ImageData>);
127
128impl Image {
129 pub fn encoded(bytes: Vec<u8>) -> Self {
131 Self::new(ImageSource::Encoded(bytes))
132 }
133
134 pub fn rgba(width: u32, height: u32, pixels: Vec<u8>) -> Self {
136 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
137 Self::new(ImageSource::Rgba { width, height, pixels })
138 }
139
140 pub fn bgra(width: u32, height: u32, pixels: Vec<u8>) -> Self {
143 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
144 Self::new(ImageSource::Bgra { width, height, pixels })
145 }
146
147 fn new(source: ImageSource) -> Self {
148 Self(Arc::new(ImageData { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), source }))
149 }
150
151 pub fn id(&self) -> u64 {
153 self.0.id
154 }
155
156 pub fn downgrade(&self) -> WeakImage {
159 WeakImage(Arc::downgrade(&self.0))
160 }
161
162 pub fn source(&self) -> &ImageSource {
163 &self.0.source
164 }
165
166 pub fn dominant_color(&self) -> Option<crate::Color> {
169 match &self.0.source {
170 ImageSource::Rgba { width, height, pixels } => dominant_color(*width, *height, pixels),
171 ImageSource::Bgra { width, height, pixels } => {
172 let rgba: Vec<u8> = pixels.chunks_exact(4).flat_map(|p| [p[2], p[1], p[0], p[3]]).collect();
173 dominant_color(*width, *height, &rgba)
174 }
175 ImageSource::Encoded(_) => None,
176 }
177 }
178
179 pub fn known_size(&self) -> Option<SizeF> {
181 match &self.0.source {
182 ImageSource::Rgba { width, height, .. } | ImageSource::Bgra { width, height, .. } => {
183 Some(SizeF::new(*width as f32, *height as f32))
184 }
185 ImageSource::Encoded(_) => None,
186 }
187 }
188}
189
190#[derive(Clone, Debug)]
194pub struct WeakImage(Weak<ImageData>);
195
196impl WeakImage {
197 pub fn is_alive(&self) -> bool {
199 self.0.strong_count() > 0
200 }
201}
202
203impl PartialEq for Image {
204 fn eq(&self, other: &Self) -> bool {
205 self.0.id == other.0.id
206 }
207}
208
209#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
211pub enum ImageFit {
212 #[default]
214 Contain,
215 Cover,
217 Stretch,
219 Center,
221 Original,
223}
224
225impl crate::prop::PropEnum for ImageFit {
226 const NAMES: &'static [&'static str] = &["contain", "cover", "stretch", "center", "original"];
227
228 fn from_index(index: usize) -> Option<Self> {
229 [Self::Contain, Self::Cover, Self::Stretch, Self::Center, Self::Original].get(index).copied()
230 }
231
232 fn index(self) -> usize {
233 self as usize
234 }
235}
236
237impl ImageFit {
238 pub fn place(self, image: SizeF, dest: crate::RectF) -> (crate::RectF, crate::RectF) {
241 use crate::RectF;
242 let full = RectF::from_size(image);
243 if image.width <= 0.0 || image.height <= 0.0 {
244 return (full, dest);
245 }
246 let centered = |w: f32, h: f32| RectF::new(dest.x + (dest.width - w) / 2.0, dest.y + (dest.height - h) / 2.0, w, h);
247 match self {
248 ImageFit::Stretch => (full, dest),
249 ImageFit::Contain => {
250 let s = (dest.width / image.width).min(dest.height / image.height);
251 (full, centered(image.width * s, image.height * s))
252 }
253 ImageFit::Cover => {
254 let s = (dest.width / image.width).max(dest.height / image.height);
256 let (w, h) = (dest.width / s, dest.height / s);
257 (RectF::new((image.width - w) / 2.0, (image.height - h) / 2.0, w, h), dest)
258 }
259 ImageFit::Center => (full, centered(image.width, image.height)),
260 ImageFit::Original => (full, RectF::new(dest.x, dest.y, image.width, image.height)),
261 }
262 }
263}
264
265pub fn ico_frame_for_size(bytes: &[u8], size: u32) -> Option<Vec<u8>> {
273 let u16_at = |i: usize| -> Option<u16> { Some(u16::from_le_bytes(bytes.get(i..i + 2)?.try_into().ok()?)) };
274 let u32_at = |i: usize| -> Option<u32> { Some(u32::from_le_bytes(bytes.get(i..i + 4)?.try_into().ok()?)) };
275 if u16_at(0)? != 0 || u16_at(2)? != 1 {
276 return None;
277 }
278 let count = u16_at(4)? as usize;
279 if count < 2 {
280 return None;
281 }
282 let mut frames = Vec::with_capacity(count);
284 for i in 0..count {
285 let at = 6 + i * 16;
286 let entry = bytes.get(at..at + 16)?;
287 let width = if entry[0] == 0 { 256 } else { entry[0] as u32 };
288 let (len, offset) = (u32_at(at + 8)? as usize, u32_at(at + 12)? as usize);
289 let data = bytes.get(offset..offset.checked_add(len)?)?;
290 frames.push((width, u16_at(at + 6)?, entry, data));
291 }
292 let best = frames
294 .iter()
295 .filter(|f| f.0 >= size)
296 .min_by_key(|f| (f.0, std::cmp::Reverse(f.1)))
297 .or_else(|| frames.iter().max_by_key(|f| (f.0, f.1)))?;
298 let mut out = Vec::with_capacity(22 + best.3.len());
299 out.extend_from_slice(&[0, 0, 1, 0, 1, 0]);
300 out.extend_from_slice(&best.2[..12]);
301 out.extend_from_slice(&22u32.to_le_bytes());
302 out.extend_from_slice(best.3);
303 Some(out)
304}