Make a picture's size mean it shows, and keep pixels the size they say
ImageSource::size() read a raster file's header, so a cache file that was cut short or garbled after the header counted as showable, where the Slint version's decoded image was empty. A raster picture is now decoded to tell (the first frame, with the limits the Slint side uses) and an SVG must parse as XML with an svg root (roxmltree, already in the tree through the vector renderer); the answer is kept per file stamp, and per key and content hash for a downloaded picture, and decoding runs outside the lock. The size check of the pixel count no longer overflows on a header that claims u32::MAX. ImageSource::Rgba holds a Pixels value that can only be made with the right length, so the Slint conversion cannot hand clone_from_slice bytes that do not fit (it panics on that). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f92a14fc84
commit
d9de95b985
5 files changed
+224
-79
No files matched your search
Generated
+1
@@ -9764,6 +9764,7 @@ dependencies = [
|
|||||||
"image",
|
"image",
|
||||||
"miniz_oxide 0.8.9",
|
"miniz_oxide 0.8.9",
|
||||||
"png",
|
"png",
|
||||||
|
"roxmltree",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
|
|||||||
@@ -16,12 +16,15 @@ path = "src/lib.rs"
|
|||||||
# must show neither. The front ends convert these types (docs/ui.md).
|
# must show neither. The front ends convert these types (docs/ui.md).
|
||||||
[dependencies]
|
[dependencies]
|
||||||
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
|
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
|
||||||
# Picture sizes (the header of a file); PNG and JPEG are listed as the
|
# Whether a picture file decodes, and its size; PNG and JPEG are listed as
|
||||||
# front end's toolkit used to bring them.
|
# the front end's toolkit used to bring them.
|
||||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
|
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
# JSON values of the settings and the gateway's configuration keys.
|
# JSON values of the settings and the gateway's configuration keys.
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
# Whether an SVG document is XML with an svg root (the vector renderers read
|
||||||
|
# it with this parser too).
|
||||||
|
roxmltree = { version = "0.21", default-features = false, features = ["std"] }
|
||||||
# The Twemoji archive's blocks (raw deflate).
|
# The Twemoji archive's blocks (raw deflate).
|
||||||
miniz_oxide = "0.8"
|
miniz_oxide = "0.8"
|
||||||
# Grapheme clusters for emoji in chat text.
|
# Grapheme clusters for emoji in chat text.
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
use std::hash::{DefaultHasher, Hasher};
|
||||||
|
use std::io::Cursor;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
@@ -28,15 +30,8 @@ pub enum ImageSource {
|
|||||||
/// What the file was when the reference was made.
|
/// What the file was when the reference was made.
|
||||||
stamp: Stamp,
|
stamp: Stamp,
|
||||||
},
|
},
|
||||||
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
|
/// Decoded pixels; [`ImageSource::rgba`] makes them.
|
||||||
Rgba {
|
Rgba(Pixels),
|
||||||
/// Width in pixels.
|
|
||||||
w: u32,
|
|
||||||
/// Height in pixels.
|
|
||||||
h: u32,
|
|
||||||
/// `w * h * 4` bytes.
|
|
||||||
bytes: Arc<[u8]>,
|
|
||||||
},
|
|
||||||
/// An SVG document.
|
/// An SVG document.
|
||||||
Svg(Arc<[u8]>),
|
Svg(Arc<[u8]>),
|
||||||
/// A picture file held in memory (a chat picture downloaded for its
|
/// A picture file held in memory (a chat picture downloaded for its
|
||||||
@@ -55,7 +50,7 @@ impl fmt::Debug for ImageSource {
|
|||||||
match self {
|
match self {
|
||||||
Self::None => f.write_str("None"),
|
Self::None => f.write_str("None"),
|
||||||
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
|
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
|
||||||
Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"),
|
Self::Rgba(pixels) => write!(f, "Rgba({}x{})", pixels.width(), pixels.height()),
|
||||||
Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()),
|
Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()),
|
||||||
Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()),
|
Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()),
|
||||||
}
|
}
|
||||||
@@ -88,6 +83,39 @@ pub struct Size {
|
|||||||
pub height: u32,
|
pub height: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
|
||||||
|
/// The length always fits the size (`width * height * 4`), so a front end
|
||||||
|
/// can hand the bytes to its toolkit without checking them.
|
||||||
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
|
pub struct Pixels {
|
||||||
|
w: u32,
|
||||||
|
h: u32,
|
||||||
|
bytes: Arc<[u8]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Pixels {
|
||||||
|
/// The pixels `bytes` hold, if there are `w * h * 4` of them.
|
||||||
|
pub fn new(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> Option<Self> {
|
||||||
|
let bytes = bytes.into();
|
||||||
|
(bytes.len() as u128 == u128::from(w) * u128::from(h) * 4).then_some(Self { w, h, bytes })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Width in pixels.
|
||||||
|
pub fn width(&self) -> u32 {
|
||||||
|
self.w
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Height in pixels.
|
||||||
|
pub fn height(&self) -> u32 {
|
||||||
|
self.h
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `width * height * 4` bytes: red, green, blue, alpha of each pixel, row by row.
|
||||||
|
pub fn bytes(&self) -> &[u8] {
|
||||||
|
&self.bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl ImageSource {
|
impl ImageSource {
|
||||||
/// A reference to no picture.
|
/// A reference to no picture.
|
||||||
pub fn none() -> ImageRef {
|
pub fn none() -> ImageRef {
|
||||||
@@ -104,27 +132,24 @@ impl ImageSource {
|
|||||||
/// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue,
|
/// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue,
|
||||||
/// alpha); no picture if the length does not fit.
|
/// alpha); no picture if the length does not fit.
|
||||||
pub fn rgba(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> ImageRef {
|
pub fn rgba(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> ImageRef {
|
||||||
let bytes = bytes.into();
|
Pixels::new(w, h, bytes).map_or_else(Self::none, |pixels| Arc::new(Self::Rgba(pixels)))
|
||||||
if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 {
|
|
||||||
Arc::new(Self::Rgba { w, h, bytes })
|
|
||||||
} else {
|
|
||||||
Self::none()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The size the picture shows with; 0 by 0 when there is none or it can
|
/// The size the picture shows with; 0 by 0 when there is none or it can
|
||||||
/// not be shown: a file that is missing, is not a picture, or is too
|
/// not be shown: a file that is missing, does not decode, or is too large
|
||||||
/// large to decode (a front end drops those, as it would show nothing).
|
/// to decode (a front end drops those, as it would show nothing). So a
|
||||||
/// A file's size is read from its header, once while it stays as it is;
|
/// picture that has a size shows: a raster picture is decoded to tell
|
||||||
/// a vector picture has none of its own: its stated width and height,
|
/// (its first frame, as a front end would show it), an SVG document must
|
||||||
/// else 1 by 1.
|
/// parse. A file or a downloaded picture is checked once while it stays
|
||||||
|
/// as it is; a vector picture has no size of its own: its stated width
|
||||||
|
/// and height, else 1 by 1.
|
||||||
pub fn size(&self) -> Size {
|
pub fn size(&self) -> Size {
|
||||||
match self {
|
match self {
|
||||||
Self::None => Size::default(),
|
Self::None => Size::default(),
|
||||||
Self::File { path, stamp } => file_size(path, *stamp),
|
Self::File { path, stamp } => file_size(path, *stamp),
|
||||||
Self::Rgba { w, h, .. } => Size { width: *w, height: *h },
|
Self::Rgba(pixels) => Size { width: pixels.width(), height: pixels.height() },
|
||||||
Self::Svg(bytes) => svg_size(bytes),
|
Self::Svg(bytes) => svg_size(bytes),
|
||||||
Self::Memory { bytes, .. } => bytes_size(bytes),
|
Self::Memory { key, bytes } => memory_size(key, bytes),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,24 +163,38 @@ impl ImageSource {
|
|||||||
const MAX_DECODED_BYTES: u64 = 128 << 20;
|
const MAX_DECODED_BYTES: u64 = 128 << 20;
|
||||||
|
|
||||||
fn checked(width: u32, height: u32) -> Size {
|
fn checked(width: u32, height: u32) -> Size {
|
||||||
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
|
let bytes = u128::from(width) * u128::from(height) * 4;
|
||||||
|
if width == 0 || height == 0 || bytes > u128::from(MAX_DECODED_BYTES) {
|
||||||
Size::default()
|
Size::default()
|
||||||
} else {
|
} else {
|
||||||
Size { width, height }
|
Size { width, height }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The size of a picture file's bytes, told by content.
|
/// What a picture file's bytes show as, told by content: a raster picture is
|
||||||
|
/// decoded (its first frame; the size comes from the header, the decoding
|
||||||
|
/// tells whether the rest of the file is a picture too), an SVG document
|
||||||
|
/// must parse. Anything else, or anything that does not decode, shows
|
||||||
|
/// nothing.
|
||||||
fn bytes_size(bytes: &[u8]) -> Size {
|
fn bytes_size(bytes: &[u8]) -> Size {
|
||||||
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
|
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
|
||||||
let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()
|
let Ok(mut reader) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format() else {
|
||||||
else {
|
|
||||||
return Size::default();
|
return Size::default();
|
||||||
};
|
};
|
||||||
if reader.format().is_none() {
|
if reader.format().is_none() {
|
||||||
return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() };
|
return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() };
|
||||||
}
|
}
|
||||||
reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h))
|
// What a front end allows itself: 16 bits a channel take twice the bytes.
|
||||||
|
let mut limits = image::Limits::default();
|
||||||
|
limits.max_alloc = Some(2 * MAX_DECODED_BYTES + (64 << 20));
|
||||||
|
reader.limits(limits);
|
||||||
|
let Ok(decoder) = reader.into_decoder() else { return Size::default() };
|
||||||
|
let (width, height) = image::ImageDecoder::dimensions(&decoder);
|
||||||
|
let size = checked(width, height);
|
||||||
|
if size == Size::default() || image::DynamicImage::from_decoder(decoder).is_err() {
|
||||||
|
return Size::default();
|
||||||
|
}
|
||||||
|
size
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The number at the start of an attribute's value ("48", "48px", "4.5em").
|
/// The number at the start of an attribute's value ("48", "48px", "4.5em").
|
||||||
@@ -164,34 +203,25 @@ fn number(value: &str) -> Option<u32> {
|
|||||||
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
|
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The value of `name="…"` in the root tag of an SVG.
|
/// The size of an SVG document: none unless it is XML (as the vector
|
||||||
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
|
/// renderers read it, a doctype allowed) whose root is an `svg` element.
|
||||||
let mut rest = tag;
|
|
||||||
while let Some(at) = rest.find(name) {
|
|
||||||
let before = rest[..at].chars().next_back();
|
|
||||||
let after = &rest[at + name.len()..];
|
|
||||||
let after = after.trim_start();
|
|
||||||
if before.is_none_or(char::is_whitespace)
|
|
||||||
&& let Some(value) = after.strip_prefix('=')
|
|
||||||
{
|
|
||||||
let value = value.trim_start();
|
|
||||||
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
|
|
||||||
return value[1..].split(quote).next();
|
|
||||||
}
|
|
||||||
rest = &rest[at + name.len()..];
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn svg_size(bytes: &[u8]) -> Size {
|
fn svg_size(bytes: &[u8]) -> Size {
|
||||||
let text = String::from_utf8_lossy(bytes);
|
const NAMESPACE: &str = "http://www.w3.org/2000/svg";
|
||||||
let Some(start) = text.find("<svg") else { return Size { width: 1, height: 1 } };
|
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
|
||||||
let tag = &text[start..];
|
let Ok(text) = std::str::from_utf8(bytes) else { return Size::default() };
|
||||||
let tag = &tag[..tag.find('>').unwrap_or(tag.len())];
|
let options = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };
|
||||||
|
let Ok(document) = roxmltree::Document::parse_with_options(text, options) else {
|
||||||
|
return Size::default();
|
||||||
|
};
|
||||||
|
let root = document.root_element();
|
||||||
|
let name = root.tag_name();
|
||||||
|
if name.name() != "svg" || name.namespace().is_some_and(|ns| ns != NAMESPACE) {
|
||||||
|
return Size::default();
|
||||||
|
}
|
||||||
let stated =
|
let stated =
|
||||||
attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number));
|
root.attribute("width").and_then(number).zip(root.attribute("height").and_then(number));
|
||||||
let boxed = || {
|
let boxed = || {
|
||||||
let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
|
let mut parts = root.attribute("viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
|
||||||
let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
|
let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
|
||||||
number(w).zip(number(h))
|
number(w).zip(number(h))
|
||||||
};
|
};
|
||||||
@@ -199,34 +229,66 @@ fn svg_size(bytes: &[u8]) -> Size {
|
|||||||
checked(width, height)
|
checked(width, height)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a probe of a file found, and what the file was then.
|
/// What identifies the bytes a probe looked at.
|
||||||
type Probe = (Stamp, Size);
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Seen {
|
||||||
|
/// A file as it was (length and time).
|
||||||
|
File(Stamp),
|
||||||
|
/// A picture in memory: its length and a hash of its bytes.
|
||||||
|
Bytes(usize, u64),
|
||||||
|
}
|
||||||
|
|
||||||
/// Probed files, so a picture shown in many rows is read once; entries are
|
/// Where a probed picture is.
|
||||||
/// checked against the file's length and time before use.
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
static PROBES: Mutex<Option<HashMap<PathBuf, Probe>>> = Mutex::new(None);
|
enum Probed {
|
||||||
|
File(PathBuf),
|
||||||
|
Memory(Arc<str>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Probed pictures with what they were then, so a picture shown in many
|
||||||
|
/// rows is decoded once; an entry is checked against the picture's length
|
||||||
|
/// and time (or bytes) before use.
|
||||||
|
static PROBES: Mutex<Option<HashMap<Probed, (Seen, Size)>>> = Mutex::new(None);
|
||||||
|
|
||||||
/// Probes kept at most; the picture cache is far smaller than this.
|
/// Probes kept at most; the picture cache is far smaller than this.
|
||||||
const MAX_PROBES: usize = 4096;
|
const MAX_PROBES: usize = 4096;
|
||||||
|
|
||||||
|
/// The size of the picture at `at`, from the cache when it is still the
|
||||||
|
/// same, else from `probe` (run without the lock: it decodes).
|
||||||
|
fn probed(at: Probed, seen: Seen, probe: impl FnOnce() -> Size) -> Size {
|
||||||
|
{
|
||||||
|
let guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if let Some((was, size)) = guard.as_ref().and_then(|probes| probes.get(&at))
|
||||||
|
&& *was == seen
|
||||||
|
{
|
||||||
|
return *size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let size = probe();
|
||||||
|
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let probes = guard.get_or_insert_with(HashMap::new);
|
||||||
|
if probes.len() >= MAX_PROBES {
|
||||||
|
probes.clear();
|
||||||
|
}
|
||||||
|
probes.insert(at, (seen, size));
|
||||||
|
size
|
||||||
|
}
|
||||||
|
|
||||||
fn file_size(path: &Path, stamp: Stamp) -> Size {
|
fn file_size(path: &Path, stamp: Stamp) -> Size {
|
||||||
if stamp == Stamp::default() {
|
if stamp == Stamp::default() {
|
||||||
return Size::default();
|
return Size::default();
|
||||||
}
|
}
|
||||||
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
|
probed(Probed::File(path.to_owned()), Seen::File(stamp), || {
|
||||||
let probes = guard.get_or_insert_with(HashMap::new);
|
std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes))
|
||||||
if let Some((was, size)) = probes.get(path)
|
})
|
||||||
&& *was == stamp
|
}
|
||||||
{
|
|
||||||
return *size;
|
fn memory_size(key: &Arc<str>, bytes: &[u8]) -> Size {
|
||||||
}
|
let mut hasher = DefaultHasher::new();
|
||||||
// The file is read with the lock held; probes are short and rare.
|
hasher.write(bytes);
|
||||||
let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes));
|
probed(Probed::Memory(key.clone()), Seen::Bytes(bytes.len(), hasher.finish()), || {
|
||||||
if probes.len() >= MAX_PROBES {
|
bytes_size(bytes)
|
||||||
probes.clear();
|
})
|
||||||
}
|
|
||||||
probes.insert(path.to_owned(), (stamp, size));
|
|
||||||
size
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -239,7 +301,15 @@ mod tests {
|
|||||||
let mut encoder = ::png::Encoder::new(&mut bytes, width, height);
|
let mut encoder = ::png::Encoder::new(&mut bytes, width, height);
|
||||||
encoder.set_color(::png::ColorType::Rgba);
|
encoder.set_color(::png::ColorType::Rgba);
|
||||||
encoder.set_depth(::png::BitDepth::Eight);
|
encoder.set_depth(::png::BitDepth::Eight);
|
||||||
let pixels = vec![200; width as usize * height as usize * 4];
|
// Pixels that do not compress to nothing, so cutting the file short
|
||||||
|
// cuts into the picture.
|
||||||
|
let mut seed = 0x2545_f491_u32;
|
||||||
|
let pixels: Vec<u8> = (0..width as usize * height as usize * 4)
|
||||||
|
.map(|_| {
|
||||||
|
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||||
|
(seed >> 24) as u8
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
|
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
|
||||||
bytes
|
bytes
|
||||||
}
|
}
|
||||||
@@ -257,8 +327,13 @@ mod tests {
|
|||||||
let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]);
|
let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]);
|
||||||
assert_eq!(pixels.size(), Size { width: 2, height: 3 });
|
assert_eq!(pixels.size(), Size { width: 2, height: 3 });
|
||||||
assert!(!pixels.is_empty());
|
assert!(!pixels.is_empty());
|
||||||
// The wrong length is no picture.
|
// The wrong length is no picture, and no pixels either.
|
||||||
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
|
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
|
||||||
|
assert!(ImageSource::rgba(2, 3, vec![0u8; 25]).is_empty());
|
||||||
|
assert!(Pixels::new(2, 3, vec![0u8; 23]).is_none());
|
||||||
|
assert!(Pixels::new(u32::MAX, u32::MAX, vec![0u8; 4]).is_none());
|
||||||
|
let ImageSource::Rgba(inner) = &*pixels else { panic!("pixels") };
|
||||||
|
assert_eq!((inner.width(), inner.height(), inner.bytes().len()), (2, 3, 24));
|
||||||
assert_eq!(format!("{pixels:?}"), "Rgba(2x3)");
|
assert_eq!(format!("{pixels:?}"), "Rgba(2x3)");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,6 +359,48 @@ mod tests {
|
|||||||
std::fs::remove_dir_all(dir).unwrap();
|
std::fs::remove_dir_all(dir).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_file_that_does_not_decode_shows_nothing() {
|
||||||
|
let dir = temp("corrupt");
|
||||||
|
let whole = png(32, 32);
|
||||||
|
// The header is fine, the picture is cut short (a download that
|
||||||
|
// stopped, a cache file written halfway).
|
||||||
|
let cut = dir.join("cut");
|
||||||
|
std::fs::write(&cut, &whole[..whole.len() * 2 / 3]).unwrap();
|
||||||
|
assert!(ImageSource::file(&cut).is_empty());
|
||||||
|
// The header is fine, the data is not: flipped bytes in the image
|
||||||
|
// data, from the middle of the file to its end.
|
||||||
|
let mut flipped = whole.clone();
|
||||||
|
let from = flipped.len() / 2;
|
||||||
|
for byte in &mut flipped[from..] {
|
||||||
|
*byte = !*byte;
|
||||||
|
}
|
||||||
|
let garbled = dir.join("garbled");
|
||||||
|
std::fs::write(&garbled, &flipped).unwrap();
|
||||||
|
assert!(ImageSource::file(&garbled).is_empty());
|
||||||
|
// The whole file shows, and the answer is kept while it stays so.
|
||||||
|
let good = dir.join("good");
|
||||||
|
std::fs::write(&good, &whole).unwrap();
|
||||||
|
assert_eq!(ImageSource::file(&good).size(), Size { width: 32, height: 32 });
|
||||||
|
// A file that is made whole shows (another stamp: another answer).
|
||||||
|
std::fs::write(&cut, &whole).unwrap();
|
||||||
|
assert_eq!(ImageSource::file(&cut).size(), Size { width: 32, height: 32 });
|
||||||
|
std::fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_downloaded_picture_is_checked_too() {
|
||||||
|
let whole = png(16, 16);
|
||||||
|
let memory =
|
||||||
|
|key: &str, bytes: &[u8]| ImageSource::Memory { key: key.into(), bytes: bytes.into() };
|
||||||
|
assert_eq!(memory("whole", &whole).size(), Size { width: 16, height: 16 });
|
||||||
|
assert!(memory("cut", &whole[..whole.len() / 2]).is_empty());
|
||||||
|
// The same key with other bytes is another picture.
|
||||||
|
assert!(memory("same", &whole[..whole.len() / 2]).is_empty());
|
||||||
|
assert_eq!(memory("same", &whole).size(), Size { width: 16, height: 16 });
|
||||||
|
assert!(memory("none", b"").is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn vector_pictures() {
|
fn vector_pictures() {
|
||||||
let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size();
|
let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size();
|
||||||
@@ -296,6 +413,24 @@ mod tests {
|
|||||||
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
|
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
|
||||||
.is_empty()
|
.is_empty()
|
||||||
);
|
);
|
||||||
|
// Not an SVG document: cut off, a sibling of the root, other roots,
|
||||||
|
// not text.
|
||||||
|
assert!(size("<svg width=\"8\" height=\"8\"").width == 0);
|
||||||
|
assert!(size("<svg width=\"8\" height=\"8\"><g>").width == 0);
|
||||||
|
assert!(size("<svg width=\"8\" height=\"8\"/><svg/>").width == 0);
|
||||||
|
assert!(size("<html width=\"8\" height=\"8\"/>").width == 0);
|
||||||
|
assert!(size("<svg xmlns='urn:other' width='8' height='8'/>").width == 0);
|
||||||
|
assert_eq!(
|
||||||
|
size("<svg xmlns='http://www.w3.org/2000/svg' width='8' height='9'/>").height,
|
||||||
|
9
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
ImageSource::Svg(b"<svg width='8' height='8'>\xff</svg>".as_slice().into()).is_empty()
|
||||||
|
);
|
||||||
|
// A doctype, as editors write it.
|
||||||
|
let doctype = "<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \
|
||||||
|
\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg width=\"5\" height=\"6\"/>";
|
||||||
|
assert_eq!(size(doctype), Size { width: 5, height: 6 });
|
||||||
// An SVG file with a byte order mark and a prolog, and in memory.
|
// An SVG file with a byte order mark and a prolog, and in memory.
|
||||||
let svg: &[u8] = b"\xef\xbb\xbf<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
|
let svg: &[u8] = b"\xef\xbb\xbf<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
|
||||||
let dir = temp("svg");
|
let dir = temp("svg");
|
||||||
|
|||||||
@@ -23,4 +23,4 @@ pub mod studio_bridge;
|
|||||||
pub mod tree;
|
pub mod tree;
|
||||||
|
|
||||||
pub use color::Rgb;
|
pub use color::Rgb;
|
||||||
pub use image::{ImageRef, ImageSource, Size};
|
pub use image::{ImageRef, ImageSource, Pixels, Size};
|
||||||
@@ -37,8 +37,14 @@ pub(crate) fn image(picture: &ImageRef) -> Image {
|
|||||||
match &**picture {
|
match &**picture {
|
||||||
ImageSource::None => Image::default(),
|
ImageSource::None => Image::default(),
|
||||||
ImageSource::File { path, .. } => crate::images::file(path),
|
ImageSource::File { path, .. } => crate::images::file(path),
|
||||||
ImageSource::Rgba { w, h, bytes } => {
|
// `Pixels` holds `width * height * 4` bytes, which `clone_from_slice`
|
||||||
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(bytes, *w, *h))
|
// needs (it panics otherwise).
|
||||||
|
ImageSource::Rgba(pixels) => {
|
||||||
|
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(
|
||||||
|
pixels.bytes(),
|
||||||
|
pixels.width(),
|
||||||
|
pixels.height(),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(),
|
ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(),
|
||||||
ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes),
|
ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes),
|
||||||
|
|||||||
Reference in new issue
Block a user