use std::hash::{Hash, Hasher};
use std::io::Cursor;
use std::sync::Arc;
use crate::paint::RenderProfile;
use super::render_tree::BoundingBox;
mod cropped_window;
use cropped_window::{CacheKey, CACHE, CACHE_BYTES, CACHE_ENTRIES, MAX_PIXELS};
pub(crate) struct PreparedBitmap {
pub bytes: Arc<Vec<u8>>,
pub bbox: BoundingBox,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PrintPaperGrid {
factors: [u64; 2],
origin: [u64; 2],
}
impl PrintPaperGrid {
pub(crate) fn new(paper: [f64; 2], matrix: [f64; 6]) -> Option<Self> {
let [a, b, c, d, e, f] = matrix;
if b != 0.0
|| c != 0.0
|| a <= 0.0
|| d <= 0.0
|| e.fract() != 0.0
|| f.fract() != 0.0
|| !paper.into_iter().chain(matrix).all(f64::is_finite)
|| paper.into_iter().any(|size| size <= 0.0)
{
return None;
}
let extents = [paper[0] * a, paper[1] * d];
if extents.iter().any(|size| !size.is_finite() || *size <= 0.0) {
return None;
}
let factors = extents.map(|size| size.ceil() / size);
if factors.iter().any(|factor| !factor.is_finite()) {
return None;
}
Some(Self {
factors: factors.map(f64::to_bits),
origin: [e.to_bits(), f.to_bits()],
})
}
fn project(self, [x, y, w, h]: [f64; 4]) -> [f64; 4] {
let [sx, sy] = self.factors.map(f64::from_bits);
let [ox, oy] = self.origin.map(f64::from_bits);
[(x - ox) * sx + ox, (y - oy) * sy + oy, w * sx, h * sy]
}
}
pub(crate) fn prepare_bitmap(
bytes: &[u8],
bbox: BoundingBox,
matrix: [f64; 6],
profile: RenderProfile,
paper_grid: Option<PrintPaperGrid>,
) -> Option<PreparedBitmap> {
if super::image_resolver::png_sampling::metafile_surface(bytes) {
return None;
}
let [a, b, c, d, e, f] = matrix;
if !matches!(profile, RenderProfile::Print | RenderProfile::HighQuality)
|| b != 0.0
|| c != 0.0
|| a <= 0.0
|| d <= 0.0
|| bbox.width <= 0.0
|| bbox.height <= 0.0
|| !matrix
.into_iter()
.chain([bbox.x, bbox.y, bbox.width, bbox.height])
.all(f64::is_finite)
{
return None;
}
let print = profile == RenderProfile::Print;
let lower = |x: f64| if print { x.floor() } else { x.round() };
let upper = |x: f64| if print { x.floor() + 1.0 } else { x.round() };
let rectangle = [
a * bbox.x + e,
d * bbox.y + f,
a * bbox.width,
d * bbox.height,
];
let rectangle = if print {
paper_grid.map_or(rectangle, |grid| grid.project(rectangle))
} else {
rectangle
};
let [x, y, w, h] = rectangle;
let left = lower(x);
let right = upper(x + w);
let top = lower(y);
let bottom = upper(y + h);
let (width, height) = (right - left, bottom - top);
if ![left, right, top, bottom, width, height]
.into_iter()
.all(f64::is_finite)
|| width < 1.0
|| height < 1.0
|| width > u32::MAX as f64
|| height > u32::MAX as f64
|| width * height > MAX_PIXELS as f64
{
return None;
}
let (width, height) = (width as u32, height as u32);
let dimensions = image::ImageReader::new(Cursor::new(bytes))
.with_guessed_format()
.ok()?
.into_dimensions()
.ok()?;
if super::image_resolver::png_sampling::print_bitmap_reconstruction(bytes)
&& super::cubic_sampling::modest_reduction(
(f64::from(dimensions.0), f64::from(dimensions.1)),
(w, h),
)
{
return None;
}
if width >= dimensions.0
|| height >= dimensions.1
|| u64::from(dimensions.0) * u64::from(dimensions.1) > MAX_PIXELS
{
return None;
}
let mut hash = std::collections::hash_map::DefaultHasher::new();
bytes.hash(&mut hash);
let device_rect = [x - left, y - top, w, h];
let key = CacheKey {
source_hash: hash.finish(),
source_len: bytes.len(),
width,
height,
print,
device_rect: device_rect.map(f64::to_bits),
source_window: None,
};
let png = CACHE.with(|cache| cache.borrow().entries.get(&key).cloned());
let png = match png {
Some(png) => png,
None => {
let mut reader = image::ImageReader::new(Cursor::new(bytes))
.with_guessed_format()
.ok()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_PIXELS * 4);
reader.limits(limits);
let source = reader.decode().ok()?;
let transparent = source.color().has_alpha()
&& source.to_rgba8().pixels().any(|pixel| pixel.0[3] != 255);
let resized = if transparent {
if !print {
return None;
}
image::DynamicImage::ImageRgba8(transparent_area_downsample(
&source.to_rgba8(),
width,
height,
device_rect,
)?)
} else if print {
image::DynamicImage::ImageRgb8(opaque_area_downsample(
&source.to_rgb8(),
width,
height,
))
} else {
source.resize_exact(width, height, image::imageops::FilterType::Lanczos3)
};
let mut output = Cursor::new(Vec::new());
resized
.write_to(&mut output, image::ImageFormat::Png)
.ok()?;
let png = Arc::new(output.into_inner());
if png.len() <= CACHE_BYTES {
CACHE.with(|cache| {
let mut cache = cache.borrow_mut();
if cache.entries.len() >= CACHE_ENTRIES || cache.bytes + png.len() > CACHE_BYTES
{
cache.entries.clear();
cache.bytes = 0;
}
cache.bytes += png.len();
cache.entries.insert(key, png.clone());
});
}
png
}
};
Some(PreparedBitmap {
bytes: png,
bbox: BoundingBox::new(
(left - e) / a,
(top - f) / d,
f64::from(width) / a,
f64::from(height) / d,
),
})
}
fn area_span(index: u32, source: u32, target: u32) -> impl Iterator<Item = (u32, u64)> + Clone {
let source = u64::from(source);
let target = u64::from(target);
let start = u64::from(index) * source;
let end = start + source;
(start / target..end.div_ceil(target)).map(move |pixel| {
let overlap = end.min((pixel + 1) * target) - start.max(pixel * target);
(pixel as u32, overlap)
})
}
fn opaque_area_downsample(source: &image::RgbImage, width: u32, height: u32) -> image::RgbImage {
let mut horizontal = image::RgbImage::new(width, source.height());
for y in 0..source.height() {
for x in 0..width {
let mut sum = [0u64; 3];
for (source_x, weight) in area_span(x, source.width(), width) {
let pixel = source.get_pixel(source_x, y);
for channel in 0..3 {
sum[channel] += u64::from(pixel[channel]) * weight;
}
}
horizontal.put_pixel(
x,
y,
image::Rgb(sum.map(|value| (value / u64::from(source.width())) as u8)),
);
}
}
let mut result = image::RgbImage::new(width, height);
for y in 0..height {
let span = area_span(y, source.height(), height);
for x in 0..width {
let mut sum = [0u64; 3];
for (source_y, weight) in span.clone() {
let pixel = horizontal.get_pixel(x, source_y);
for channel in 0..3 {
sum[channel] += u64::from(pixel[channel]) * weight;
}
}
result.put_pixel(
x,
y,
image::Rgb(sum.map(|value| (value / u64::from(source.height())) as u8)),
);
}
}
result
}
fn transparent_area_downsample(
source: &image::RgbaImage,
width: u32,
height: u32,
device_rect: [f64; 4],
) -> Option<image::RgbaImage> {
let [x, y, w, h] = device_rect;
let sx = f64::from(source.width()) / w;
let sy = f64::from(source.height()) / h;
let area = sx * sy;
if !device_rect
.into_iter()
.chain([sx, sy, area])
.all(f64::is_finite)
|| w <= 0.0
|| h <= 0.0
|| area <= 0.0
{
return None;
}
let spans = |count: u32, source: u32, origin: f64, scale: f64| {
(0..count)
.map(|i| {
let first = (f64::from(i) - origin) * scale;
let end = first + scale;
(
first.floor().clamp(0.0, f64::from(source)) as u32,
end.ceil().clamp(0.0, f64::from(source)) as u32,
first,
end,
)
})
.collect::<Vec<_>>()
};
let xs = spans(width, source.width(), x, sx);
let ys = spans(height, source.height(), y, sy);
let mut output = image::RgbaImage::new(width, height);
for (y, &(top, bottom, y0, y1)) in ys.iter().enumerate() {
for (x, &(left, right, x0, x1)) in xs.iter().enumerate() {
let mut alpha = 0.0;
let mut color = [0.0; 3];
for iy in top..bottom {
let wy = (f64::from(iy + 1).min(y1) - f64::from(iy).max(y0)).max(0.0);
for ix in left..right {
let wx = (f64::from(ix + 1).min(x1) - f64::from(ix).max(x0)).max(0.0);
let pixel = source.get_pixel(ix, iy);
let weight = wx * wy * f64::from(pixel[3]);
alpha += weight;
for channel in 0..3 {
color[channel] += f64::from(pixel[channel]) * weight;
}
}
}
let rgb = color.map(|value| {
if alpha > 0.0 {
(value / alpha).round().clamp(0.0, 255.0) as u8
} else {
0
}
});
output.put_pixel(
x as u32,
y as u32,
image::Rgba([
rgb[0],
rgb[1],
rgb[2],
(alpha / area).round().clamp(0.0, 255.0) as u8,
]),
);
}
}
Some(output)
}
pub(crate) fn prepare_cropped_bitmap(
bytes: &[u8],
bbox: BoundingBox,
matrix: [f64; 6],
profile: RenderProfile,
paper_grid: Option<PrintPaperGrid>,
source_window: [f64; 4],
) -> Option<PreparedBitmap> {
let [a, b, c, d, e, f] = matrix;
let [sx, sy, sw, sh] = source_window;
if profile != RenderProfile::Print
|| b != 0.0
|| c != 0.0
|| a <= 0.0
|| d <= 0.0
|| bbox.width <= 0.0
|| bbox.height <= 0.0
|| sx < 0.0
|| sy < 0.0
|| sw <= 0.0
|| sh <= 0.0
|| !matrix
.into_iter()
.chain(source_window)
.chain([bbox.x, bbox.y, bbox.width, bbox.height])
.all(f64::is_finite)
|| super::image_resolver::png_sampling::metafile_surface(bytes)
|| super::image_resolver::png_sampling::print_jpeg_transfer(bytes)
|| super::image_resolver::png_sampling::print_bitmap_reconstruction(bytes)
{
return None;
}
let rectangle = [
a * bbox.x + e,
d * bbox.y + f,
a * bbox.width,
d * bbox.height,
];
let [x, y, w, h] = paper_grid.map_or(rectangle, |grid| grid.project(rectangle));
let left = x.floor();
let top = y.floor();
let width = (x + w).floor() + 1.0 - left;
let height = (y + h).floor() + 1.0 - top;
if ![left, top, width, height].into_iter().all(f64::is_finite)
|| width < 1.0
|| height < 1.0
|| width * height > MAX_PIXELS as f64
|| width >= sw
|| height >= sh
|| (sw <= w * 2.0 && sh <= h * 2.0)
{
return None;
}
let (width, height) = (width as u32, height as u32);
let png = cropped_window::prepare(
bytes,
width,
height,
[x - left, y - top, w, h],
source_window,
)?;
Some(PreparedBitmap {
bytes: png,
bbox: BoundingBox::new(
(left - e) / a,
(top - f) / d,
f64::from(width) / a,
f64::from(height) / d,
),
})
}