Skip to main content

aylis_core/
image.rs

1//! Imagens para desenhar no [`Canvas`](crate::Canvas): um arquivo codificado (PNG, JPEG,
2//! WebP, GIF...) ou pixels RGBA prontos (um quadro de vídeo, uma imagem gerada).
3//!
4//! O core não decodifica nada: guarda os bytes e um identificador único; cada
5//! implementação de `Canvas` decodifica e guarda em cache pelo [`Image::id`]. Uma `Image`
6//! é barata de clonar e pode ir para outra thread (um decodificador de vídeo, por exemplo).
7
8use 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
16/// As imagens dos arquivos do app em uso, pelo caminho ([`Image::shared_file`]).
17static SHARED_FILES: LazyLock<Mutex<HashMap<String, Weak<ImageData>>>> = LazyLock::new(Mutex::default);
18
19/// O maior lado de uma imagem: o tamanho máximo de textura das placas de vídeo (Direct3D 11);
20/// acima disso o renderizador não desenha num bitmap só.
21pub const MAX_IMAGE_SIDE: u32 = 16_384;
22/// A maior área de uma imagem (100 megapixels, cerca de 400 MB em RGBA).
23pub const MAX_IMAGE_PIXELS: u64 = 100_000_000;
24
25/// Os bytes em base64 (o alfabeto padrão, com `=`): os pixels que um método devolve pelo
26/// protocolo, que só leva texto (`render_rgba`).
27pub 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
39/// O contrário de [`encode_base64`]: os bytes de um texto base64 (o padrão ou o de URL, com ou
40/// sem `=`, ignorando espaços e quebras). `None` com um caractere fora do alfabeto.
41pub 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
66/// A cor dominante de pixels RGBA (`width × height`, sem pré-multiplicar): a mais comum, numa
67/// amostra de até ~4 mil pixels agrupados em caixas de cor, sem os quase transparentes, os quase
68/// pretos e os quase brancos (o fundo de uma capa, o degradê que segue a foto). Só com esses, a
69/// média deles. `None` sem pixels.
70pub 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    // Caixas de 32 níveis por canal (8 × 8 × 8): a soma e a contagem de cada uma.
77    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
97/// Os bytes RGBA de uma imagem `width × height`, sem estouro e dentro dos limites. Todo
98/// lugar que reserva memória para pixels passa por aqui: as dimensões vêm do próprio arquivo,
99/// e um PNG de 1 KB pode declarar 40.000 × 40.000.
100pub 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/// O conteúdo de uma [`Image`].
111#[derive(Debug, PartialEq)]
112pub enum ImageSource {
113    /// Arquivo de imagem como está no disco (o canvas decodifica).
114    Encoded(Vec<u8>),
115    /// Pixels RGBA (4 bytes por pixel, linha a linha, sem pré-multiplicar o alfa).
116    Rgba { width: u32, height: u32, pixels: Vec<u8> },
117    /// Pixels BGRA (a ordem que decodificadores de vídeo e o Windows costumam entregar),
118    /// opacos ou já pré-multiplicados: o Direct2D os usa sem converter.
119    Bgra { width: u32, height: u32, pixels: Vec<u8> },
120    /// Pixels RGBA de 16 bits por canal (0 a 65535, sem pré-multiplicar o alfa): a imagem médica
121    /// e a fotografia de 16 bits. Com a saída de 10 bits ou a HDR (`color_output`), o Direct2D e
122    /// o Skia desenham sem perder os tons; nos outros casos (e no navegador, de 8 bits), sai
123    /// como a de 8 ([`ImageSource::to_rgba8`]).
124    Rgba16 { width: u32, height: u32, pixels: Vec<u16> },
125}
126
127impl ImageSource {
128    /// Os pixels RGBA de 8 bits (o de 16 bits arredondado; o BGRA trocado de ordem). `None` num
129    /// arquivo codificado (quem decodifica é o canvas).
130    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
140/// Os 16 bits de cada canal levados a 8, arredondando.
141pub 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/// Imagem para [`Canvas::draw_image`](crate::Canvas::draw_image).
152#[derive(Clone, Debug)]
153pub struct Image(Arc<ImageData>);
154
155impl Image {
156    /// Um arquivo de imagem (PNG, JPEG, WebP, GIF, BMP, ICO; SVG conforme o canvas).
157    pub fn encoded(bytes: Vec<u8>) -> Self {
158        Self::new(ImageSource::Encoded(bytes))
159    }
160
161    /// Um arquivo do app (`assets/images/logo.png`) com os `bytes` lidos dele: os controles
162    /// que mostram o mesmo arquivo, com os mesmos bytes, recebem a mesma imagem enquanto
163    /// alguém a segura, e o renderizador decodifica e manda à placa uma vez só. Com uma cópia
164    /// por controle, uma grade de 400 células com a mesma imagem passava do limite de imagens
165    /// de arquivo do cache (256) e cada quadro decodificava de novo o PNG de cada célula (de
166    /// 24 para 786 ms). Os bytes conferidos deixam o arquivo trocado (hot reload) virar outra.
167    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        // As soltas saem de tempos em tempos (o mapa fica em até o dobro das vivas).
176        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    /// Pixels RGBA prontos. `pixels.len()` precisa ser `width * height * 4`.
184    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    /// Pixels RGBA de 16 bits por canal (`width * height * 4` valores, sem pré-multiplicar):
190    /// veja [`ImageSource::Rgba16`].
191    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    /// Pixels BGRA prontos (`width * height * 4` bytes), opacos ou pré-multiplicados: o
197    /// caminho mais rápido para quadros de vídeo.
198    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    /// Identificador único (cada imagem criada tem um novo): a chave do cache do canvas.
208    pub fn id(&self) -> u64 {
209        self.0.id
210    }
211
212    /// Uma referência que não segura a imagem: o cache do canvas guarda isto ao lado do que
213    /// fez dela (decodificada, na GPU) e solta quando o app solta a imagem.
214    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    /// A cor dominante ([`dominant_color`]) de uma imagem já em pixels; a de um arquivo
223    /// codificado fica para quem decodifica (o componente `Image`): `None`.
224    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    /// Tamanho em pixels, quando já é conhecido sem decodificar (imagens RGBA).
235    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/// Referência a uma [`Image`] que não a mantém viva ([`Image::downgrade`]). Um `id` só volta
246/// a ser pedido por quem ainda tem a imagem: morta a imagem, o que o cache guardou dela não
247/// serve mais para nada (uma prévia trocada a cada meio segundo, por exemplo).
248#[derive(Clone, Debug)]
249pub struct WeakImage(Weak<ImageData>);
250
251impl WeakImage {
252    /// O app ainda tem a imagem?
253    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/// Como uma imagem ocupa o retângulo de destino.
265#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
266pub enum ImageFit {
267    /// Inteira, mantendo a proporção (pode sobrar espaço).
268    #[default]
269    Contain,
270    /// Cobre tudo, mantendo a proporção (pode cortar as bordas).
271    Cover,
272    /// Estica para o retângulo (pode distorcer).
273    Stretch,
274    /// Tamanho original, centralizada.
275    Center,
276    /// Tamanho original, no canto superior esquerdo.
277    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    /// Retângulos de origem (na imagem) e de destino para desenhar uma imagem de tamanho
294    /// `image` dentro de `dest`.
295    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                // Corta a imagem para a proporção do destino.
310                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
320/// O quadro de um `.ico` com vários tamanhos que melhor serve para `size` pixels: o menor que
321/// tem pelo menos `size` (reduzir sai melhor que ampliar), ou o maior, se nenhum chegar lá.
322/// Devolve um `.ico` só com ele, que os decodificadores leem como qualquer `.ico`. `None` se
323/// `bytes` não for um `.ico` com mais de um quadro (aí vale o arquivo como está).
324///
325/// O ícone da bandeja usava o primeiro quadro, e a 150% (24 pixels) um de 16 ampliado saía
326/// borrado (o relatório do Tabernáculo, C41).
327pub 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    // (largura, bits por pixel, a entrada de 16 bytes, os dados).
338    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    // Do mesmo tamanho, o de mais cores.
348    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}