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 checked_size(width: u32, height: u32) -> Result<usize, String> {
25 if width == 0 || height == 0 {
26 return Err(format!("imagem vazia ({width} × {height})"));
27 }
28 if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE || width as u64 * height as u64 > MAX_IMAGE_PIXELS {
29 return Err(format!("imagem grande demais: {width} × {height} (máximo {MAX_IMAGE_SIDE} por lado e {} megapixels)", MAX_IMAGE_PIXELS / 1_000_000));
30 }
31 usize::try_from(width as u64 * height as u64 * 4).map_err(|_| format!("imagem grande demais: {width} × {height}"))
32}
33
34#[derive(Debug, PartialEq)]
36pub enum ImageSource {
37 Encoded(Vec<u8>),
39 Rgba { width: u32, height: u32, pixels: Vec<u8> },
41 Bgra { width: u32, height: u32, pixels: Vec<u8> },
44}
45
46#[derive(Debug)]
47struct ImageData {
48 id: u64,
49 source: ImageSource,
50}
51
52#[derive(Clone, Debug)]
54pub struct Image(Arc<ImageData>);
55
56impl Image {
57 pub fn encoded(bytes: Vec<u8>) -> Self {
59 Self::new(ImageSource::Encoded(bytes))
60 }
61
62 pub fn rgba(width: u32, height: u32, pixels: Vec<u8>) -> Self {
64 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
65 Self::new(ImageSource::Rgba { width, height, pixels })
66 }
67
68 pub fn bgra(width: u32, height: u32, pixels: Vec<u8>) -> Self {
71 debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
72 Self::new(ImageSource::Bgra { width, height, pixels })
73 }
74
75 fn new(source: ImageSource) -> Self {
76 Self(Arc::new(ImageData { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), source }))
77 }
78
79 pub fn id(&self) -> u64 {
81 self.0.id
82 }
83
84 pub fn downgrade(&self) -> WeakImage {
87 WeakImage(Arc::downgrade(&self.0))
88 }
89
90 pub fn source(&self) -> &ImageSource {
91 &self.0.source
92 }
93
94 pub fn known_size(&self) -> Option<SizeF> {
96 match &self.0.source {
97 ImageSource::Rgba { width, height, .. } | ImageSource::Bgra { width, height, .. } => {
98 Some(SizeF::new(*width as f32, *height as f32))
99 }
100 ImageSource::Encoded(_) => None,
101 }
102 }
103}
104
105#[derive(Clone, Debug)]
109pub struct WeakImage(Weak<ImageData>);
110
111impl WeakImage {
112 pub fn is_alive(&self) -> bool {
114 self.0.strong_count() > 0
115 }
116}
117
118impl PartialEq for Image {
119 fn eq(&self, other: &Self) -> bool {
120 self.0.id == other.0.id
121 }
122}
123
124#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
126pub enum ImageFit {
127 #[default]
129 Contain,
130 Cover,
132 Stretch,
134 Center,
136 Original,
138}
139
140impl crate::prop::PropEnum for ImageFit {
141 const NAMES: &'static [&'static str] = &["contain", "cover", "stretch", "center", "original"];
142
143 fn from_index(index: usize) -> Option<Self> {
144 [Self::Contain, Self::Cover, Self::Stretch, Self::Center, Self::Original].get(index).copied()
145 }
146
147 fn index(self) -> usize {
148 self as usize
149 }
150}
151
152impl ImageFit {
153 pub fn place(self, image: SizeF, dest: crate::RectF) -> (crate::RectF, crate::RectF) {
156 use crate::RectF;
157 let full = RectF::from_size(image);
158 if image.width <= 0.0 || image.height <= 0.0 {
159 return (full, dest);
160 }
161 let centered = |w: f32, h: f32| RectF::new(dest.x + (dest.width - w) / 2.0, dest.y + (dest.height - h) / 2.0, w, h);
162 match self {
163 ImageFit::Stretch => (full, dest),
164 ImageFit::Contain => {
165 let s = (dest.width / image.width).min(dest.height / image.height);
166 (full, centered(image.width * s, image.height * s))
167 }
168 ImageFit::Cover => {
169 let s = (dest.width / image.width).max(dest.height / image.height);
171 let (w, h) = (dest.width / s, dest.height / s);
172 (RectF::new((image.width - w) / 2.0, (image.height - h) / 2.0, w, h), dest)
173 }
174 ImageFit::Center => (full, centered(image.width, image.height)),
175 ImageFit::Original => (full, RectF::new(dest.x, dest.y, image.width, image.height)),
176 }
177 }
178}
179
180pub fn ico_frame_for_size(bytes: &[u8], size: u32) -> Option<Vec<u8>> {
188 let u16_at = |i: usize| -> Option<u16> { Some(u16::from_le_bytes(bytes.get(i..i + 2)?.try_into().ok()?)) };
189 let u32_at = |i: usize| -> Option<u32> { Some(u32::from_le_bytes(bytes.get(i..i + 4)?.try_into().ok()?)) };
190 if u16_at(0)? != 0 || u16_at(2)? != 1 {
191 return None;
192 }
193 let count = u16_at(4)? as usize;
194 if count < 2 {
195 return None;
196 }
197 let mut frames = Vec::with_capacity(count);
199 for i in 0..count {
200 let at = 6 + i * 16;
201 let entry = bytes.get(at..at + 16)?;
202 let width = if entry[0] == 0 { 256 } else { entry[0] as u32 };
203 let (len, offset) = (u32_at(at + 8)? as usize, u32_at(at + 12)? as usize);
204 let data = bytes.get(offset..offset.checked_add(len)?)?;
205 frames.push((width, u16_at(at + 6)?, entry, data));
206 }
207 let best = frames
209 .iter()
210 .filter(|f| f.0 >= size)
211 .min_by_key(|f| (f.0, std::cmp::Reverse(f.1)))
212 .or_else(|| frames.iter().max_by_key(|f| (f.0, f.1)))?;
213 let mut out = Vec::with_capacity(22 + best.3.len());
214 out.extend_from_slice(&[0, 0, 1, 0, 1, 0]);
215 out.extend_from_slice(&best.2[..12]);
216 out.extend_from_slice(&22u32.to_le_bytes());
217 out.extend_from_slice(best.3);
218 Some(out)
219}