use std::sync::{Arc, Weak};
use std::sync::atomic::{AtomicU64, Ordering};
use crate::geometry::SizeF;
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
pub const MAX_IMAGE_SIDE: u32 = 16_384;
pub const MAX_IMAGE_PIXELS: u64 = 100_000_000;
pub fn encode_base64(bytes: &[u8]) -> String {
const ABC: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | (*b as u32) << (16 - 8 * i));
for i in 0..4 {
out.push(if i <= chunk.len() { ABC[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
}
}
out
}
pub fn decode_base64(text: &str) -> Option<Vec<u8>> {
let value = |c: u8| -> Option<u32> {
Some(match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' | b'-' => 62,
b'/' | b'_' => 63,
_ => return None,
} as u32)
};
let clean: Vec<u8> = text.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=').collect();
let mut out = Vec::with_capacity(clean.len() * 3 / 4);
for chunk in clean.chunks(4) {
let mut n = 0u32;
for (i, c) in chunk.iter().enumerate() {
n |= value(*c)? << (18 - 6 * i);
}
for i in 0..chunk.len().saturating_sub(1) {
out.push((n >> (16 - 8 * i) & 0xFF) as u8);
}
}
Some(out)
}
pub fn dominant_color(width: u32, height: u32, rgba: &[u8]) -> Option<crate::Color> {
let total = width as usize * height as usize;
if total == 0 || rgba.len() < total * 4 {
return None;
}
let step = (total / 4096).max(1);
let mut boxes = vec![(0u64, 0u64, 0u64, 0u32); 512];
let mut all = (0u64, 0u64, 0u64, 0u32);
for px in rgba.chunks_exact(4).step_by(step) {
let (r, g, b, a) = (px[0] as u64, px[1] as u64, px[2] as u64, px[3]);
if a < 128 {
continue;
}
all = (all.0 + r, all.1 + g, all.2 + b, all.3 + 1);
let (max, min) = (r.max(g).max(b), r.min(g).min(b));
if max < 30 || min > 225 {
continue;
}
let i = ((r >> 5) << 6 | (g >> 5) << 3 | (b >> 5)) as usize;
let e = &mut boxes[i];
*e = (e.0 + r, e.1 + g, e.2 + b, e.3 + 1);
}
let (r, g, b, n) = boxes.into_iter().max_by_key(|e| e.3).filter(|e| e.3 > 0).unwrap_or(all);
(n > 0).then(|| crate::Color::rgb((r / n as u64) as u8, (g / n as u64) as u8, (b / n as u64) as u8))
}
pub fn checked_size(width: u32, height: u32) -> Result<usize, String> {
if width == 0 || height == 0 {
return Err(format!("imagem vazia ({width} × {height})"));
}
if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE || width as u64 * height as u64 > MAX_IMAGE_PIXELS {
return Err(format!("imagem grande demais: {width} × {height} (máximo {MAX_IMAGE_SIDE} por lado e {} megapixels)", MAX_IMAGE_PIXELS / 1_000_000));
}
usize::try_from(width as u64 * height as u64 * 4).map_err(|_| format!("imagem grande demais: {width} × {height}"))
}
#[derive(Debug, PartialEq)]
pub enum ImageSource {
Encoded(Vec<u8>),
Rgba { width: u32, height: u32, pixels: Vec<u8> },
Bgra { width: u32, height: u32, pixels: Vec<u8> },
}
#[derive(Debug)]
struct ImageData {
id: u64,
source: ImageSource,
}
#[derive(Clone, Debug)]
pub struct Image(Arc<ImageData>);
impl Image {
pub fn encoded(bytes: Vec<u8>) -> Self {
Self::new(ImageSource::Encoded(bytes))
}
pub fn rgba(width: u32, height: u32, pixels: Vec<u8>) -> Self {
debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
Self::new(ImageSource::Rgba { width, height, pixels })
}
pub fn bgra(width: u32, height: u32, pixels: Vec<u8>) -> Self {
debug_assert_eq!(pixels.len(), width as usize * height as usize * 4);
Self::new(ImageSource::Bgra { width, height, pixels })
}
fn new(source: ImageSource) -> Self {
Self(Arc::new(ImageData { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), source }))
}
pub fn id(&self) -> u64 {
self.0.id
}
pub fn downgrade(&self) -> WeakImage {
WeakImage(Arc::downgrade(&self.0))
}
pub fn source(&self) -> &ImageSource {
&self.0.source
}
pub fn dominant_color(&self) -> Option<crate::Color> {
match &self.0.source {
ImageSource::Rgba { width, height, pixels } => dominant_color(*width, *height, pixels),
ImageSource::Bgra { width, height, pixels } => {
let rgba: Vec<u8> = pixels.chunks_exact(4).flat_map(|p| [p[2], p[1], p[0], p[3]]).collect();
dominant_color(*width, *height, &rgba)
}
ImageSource::Encoded(_) => None,
}
}
pub fn known_size(&self) -> Option<SizeF> {
match &self.0.source {
ImageSource::Rgba { width, height, .. } | ImageSource::Bgra { width, height, .. } => {
Some(SizeF::new(*width as f32, *height as f32))
}
ImageSource::Encoded(_) => None,
}
}
}
#[derive(Clone, Debug)]
pub struct WeakImage(Weak<ImageData>);
impl WeakImage {
pub fn is_alive(&self) -> bool {
self.0.strong_count() > 0
}
}
impl PartialEq for Image {
fn eq(&self, other: &Self) -> bool {
self.0.id == other.0.id
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ImageFit {
#[default]
Contain,
Cover,
Stretch,
Center,
Original,
}
impl crate::prop::PropEnum for ImageFit {
const NAMES: &'static [&'static str] = &["contain", "cover", "stretch", "center", "original"];
fn from_index(index: usize) -> Option<Self> {
[Self::Contain, Self::Cover, Self::Stretch, Self::Center, Self::Original].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
impl ImageFit {
pub fn place(self, image: SizeF, dest: crate::RectF) -> (crate::RectF, crate::RectF) {
use crate::RectF;
let full = RectF::from_size(image);
if image.width <= 0.0 || image.height <= 0.0 {
return (full, dest);
}
let centered = |w: f32, h: f32| RectF::new(dest.x + (dest.width - w) / 2.0, dest.y + (dest.height - h) / 2.0, w, h);
match self {
ImageFit::Stretch => (full, dest),
ImageFit::Contain => {
let s = (dest.width / image.width).min(dest.height / image.height);
(full, centered(image.width * s, image.height * s))
}
ImageFit::Cover => {
let s = (dest.width / image.width).max(dest.height / image.height);
let (w, h) = (dest.width / s, dest.height / s);
(RectF::new((image.width - w) / 2.0, (image.height - h) / 2.0, w, h), dest)
}
ImageFit::Center => (full, centered(image.width, image.height)),
ImageFit::Original => (full, RectF::new(dest.x, dest.y, image.width, image.height)),
}
}
}
pub fn ico_frame_for_size(bytes: &[u8], size: u32) -> Option<Vec<u8>> {
let u16_at = |i: usize| -> Option<u16> { Some(u16::from_le_bytes(bytes.get(i..i + 2)?.try_into().ok()?)) };
let u32_at = |i: usize| -> Option<u32> { Some(u32::from_le_bytes(bytes.get(i..i + 4)?.try_into().ok()?)) };
if u16_at(0)? != 0 || u16_at(2)? != 1 {
return None;
}
let count = u16_at(4)? as usize;
if count < 2 {
return None;
}
let mut frames = Vec::with_capacity(count);
for i in 0..count {
let at = 6 + i * 16;
let entry = bytes.get(at..at + 16)?;
let width = if entry[0] == 0 { 256 } else { entry[0] as u32 };
let (len, offset) = (u32_at(at + 8)? as usize, u32_at(at + 12)? as usize);
let data = bytes.get(offset..offset.checked_add(len)?)?;
frames.push((width, u16_at(at + 6)?, entry, data));
}
let best = frames
.iter()
.filter(|f| f.0 >= size)
.min_by_key(|f| (f.0, std::cmp::Reverse(f.1)))
.or_else(|| frames.iter().max_by_key(|f| (f.0, f.1)))?;
let mut out = Vec::with_capacity(22 + best.3.len());
out.extend_from_slice(&[0, 0, 1, 0, 1, 0]);
out.extend_from_slice(&best.2[..12]);
out.extend_from_slice(&22u32.to_le_bytes());
out.extend_from_slice(best.3);
Some(out)
}