use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use super::asset::{AssetView, Intrinsics};
use super::ImageAsset;
use crate::layout::{Anchor, InkExtent, PositionComponent, Rect};
use crate::{Error, Output, Result};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ObjectFit {
#[default]
Contain,
Cover,
Fill,
None,
ScaleDown,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ObjectPosition {
pub(super) x: PositionComponent,
pub(super) y: PositionComponent,
}
impl ObjectPosition {
pub const fn new(x: PositionComponent, y: PositionComponent) -> Self {
Self { x, y }
}
const fn aligned(x: f64, y: f64) -> Self {
Self::new(PositionComponent::aligned(x), PositionComponent::aligned(y))
}
pub const fn center() -> Self {
Self::aligned(0.5, 0.5)
}
pub const fn left() -> Self {
Self::aligned(0., 0.5)
}
pub const fn right() -> Self {
Self::aligned(1., 0.5)
}
pub const fn top() -> Self {
Self::aligned(0.5, 0.)
}
pub const fn bottom() -> Self {
Self::aligned(0.5, 1.)
}
pub const fn top_left() -> Self {
Self::aligned(0., 0.)
}
pub const fn top_right() -> Self {
Self::aligned(1., 0.)
}
pub const fn bottom_left() -> Self {
Self::aligned(0., 1.)
}
pub const fn bottom_right() -> Self {
Self::aligned(1., 1.)
}
fn offset(self, spare: (f64, f64)) -> (f64, f64) {
(self.x.resolve(spare.0), self.y.resolve(spare.1))
}
}
impl Default for ObjectPosition {
fn default() -> Self {
Self::center()
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ImageRendering {
#[default]
Auto,
CrispEdges,
}
impl ImageRendering {
pub(crate) const fn svg(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::CrispEdges => "crisp-edges",
}
}
}
#[derive(Debug, Clone)]
pub(crate) enum FixedSource {
Image(ImageAsset),
Frozen(Output),
}
impl FixedSource {
pub(super) fn intrinsics(&self) -> Intrinsics {
match self {
Self::Image(asset) => asset.intrinsics(),
Self::Frozen(output) => Intrinsics::sized(output.width(), output.height()),
}
}
pub(super) fn is_frozen(&self) -> bool {
matches!(self, Self::Frozen(_))
}
}
#[derive(Debug, Clone)]
enum PanelSource {
Path(PathBuf),
Ready(FixedSource),
}
#[derive(Debug, Clone)]
#[must_use]
pub struct PanelImage {
source: PanelSource,
requested: [Option<f64>; 2],
fit: ObjectFit,
position: ObjectPosition,
rendering: ImageRendering,
}
impl PanelImage {
pub fn new(source: impl Into<Self>) -> Self {
source.into()
}
fn from_source(source: PanelSource) -> Self {
Self {
source,
requested: [None; 2],
fit: ObjectFit::Contain,
position: ObjectPosition::default(),
rendering: ImageRendering::Auto,
}
}
pub fn width(mut self, width: f64) -> Self {
self.requested[0] = Some(width);
self
}
pub fn height(mut self, height: f64) -> Self {
self.requested[1] = Some(height);
self
}
pub fn size(mut self, width: f64, height: f64) -> Self {
self.requested = [Some(width), Some(height)];
self
}
pub fn fit(mut self, fit: ObjectFit) -> Self {
self.fit = fit;
self
}
pub fn position(mut self, position: ObjectPosition) -> Self {
self.position = position;
self
}
pub fn image_rendering(mut self, rendering: ImageRendering) -> Self {
self.rendering = rendering;
self
}
pub(crate) fn admit(self) -> Result<FixedPanel> {
let source = match self.source {
PanelSource::Path(path) => FixedSource::Image(ImageAsset::read_path(&path)?),
PanelSource::Ready(source) => source,
};
let intrinsic = source.intrinsics();
let frame = match self.requested {
[None, None] => None,
[Some(w), Some(h)] => Some((w, h)),
[Some(w), None] => Some((w, w / required_ratio(intrinsic)?)),
[None, Some(h)] => Some((h * required_ratio(intrinsic)?, h)),
};
if let Some((w, h)) = frame {
positive_size((w, h))?;
}
Ok(FixedPanel {
source,
frame,
requested: self.requested,
fit: self.fit,
position: self.position,
rendering: self.rendering,
})
}
}
impl From<ImageAsset> for PanelImage {
fn from(asset: ImageAsset) -> Self {
Self::from_source(PanelSource::Ready(FixedSource::Image(asset)))
}
}
impl From<&ImageAsset> for PanelImage {
fn from(asset: &ImageAsset) -> Self {
Self::from(asset.clone())
}
}
impl From<Output> for PanelImage {
fn from(output: Output) -> Self {
Self::from_source(PanelSource::Ready(FixedSource::Frozen(output)))
}
}
impl From<&Output> for PanelImage {
fn from(output: &Output) -> Self {
Self::from(output.clone())
}
}
impl From<super::Composite> for PanelImage {
fn from(value: super::Composite) -> Self {
Self::from(value.output())
}
}
impl From<&super::Composite> for PanelImage {
fn from(value: &super::Composite) -> Self {
Self::from(value.output())
}
}
impl From<PathBuf> for PanelImage {
fn from(path: PathBuf) -> Self {
Self::from_source(PanelSource::Path(path))
}
}
impl From<&Path> for PanelImage {
fn from(path: &Path) -> Self {
Self::from(path.to_path_buf())
}
}
impl From<&PathBuf> for PanelImage {
fn from(path: &PathBuf) -> Self {
Self::from(path.as_path())
}
}
impl From<String> for PanelImage {
fn from(path: String) -> Self {
Self::from(PathBuf::from(path))
}
}
impl From<&str> for PanelImage {
fn from(path: &str) -> Self {
Self::from(PathBuf::from(path))
}
}
impl std::str::FromStr for ObjectFit {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
match value {
"contain" => Ok(Self::Contain),
"cover" => Ok(Self::Cover),
"fill" => Ok(Self::Fill),
"none" => Ok(Self::None),
"scale-down" => Ok(Self::ScaleDown),
_ => Err(Error::Data(format!("unknown object-fit {value:?}").into())),
}
}
}
impl std::str::FromStr for ImageRendering {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
match value {
"auto" => Ok(Self::Auto),
"crisp-edges" => Ok(Self::CrispEdges),
_ => Err(Error::Data(
format!("unknown image-rendering {value:?}").into(),
)),
}
}
}
impl std::str::FromStr for ObjectPosition {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
let keyword = value.replace('_', " ");
let parts: Vec<_> = keyword.split_whitespace().collect();
let center = PositionComponent::aligned(0.5);
let horizontal = |value: &str| -> Result<PositionComponent> {
match value {
"left" => Ok(PositionComponent::aligned(0.)),
"right" => Ok(PositionComponent::aligned(1.)),
"center" => Ok(center),
_ => parse_position_component(value),
}
};
let vertical = |value: &str| -> Result<PositionComponent> {
match value {
"top" => Ok(PositionComponent::aligned(0.)),
"bottom" => Ok(PositionComponent::aligned(1.)),
"center" => Ok(center),
_ => parse_position_component(value),
}
};
match parts.as_slice() {
["top" | "bottom"] => Ok(Self::new(center, vertical(parts[0])?)),
[x] => Ok(Self::new(horizontal(x)?, center)),
[y @ ("top" | "bottom"), x] | [y @ "center", x @ ("left" | "right")] | [x, y] => {
Ok(Self::new(horizontal(x)?, vertical(y)?))
}
_ => Err(Error::Data(
format!("unsupported object position {value:?}").into(),
)),
}
}
}
fn parse_position_component(value: &str) -> Result<PositionComponent> {
let (number, percent) = if let Some(number) = value.strip_suffix('%') {
(number, true)
} else if let Some(number) = value.strip_suffix("px") {
(number, false)
} else if value == "0" {
(value, false)
} else {
return Err(Error::Data(
format!("object position needs a keyword, percentage or CSS-pixel value: {value:?}")
.into(),
));
};
let number = number
.parse::<f64>()
.map_err(|_| Error::Data(format!("invalid object position {value:?}").into()))?;
if percent {
PositionComponent::percent(number)
} else {
PositionComponent::px(number)
}
}
fn required_ratio(intrinsic: Intrinsics) -> Result<f64> {
intrinsic.ratio.ok_or_else(|| {
Error::Data("image has no intrinsic aspect ratio; specify both dimensions".into())
})
}
fn positive_size(size: (f64, f64)) -> Result<()> {
if ![size.0, size.1]
.into_iter()
.all(|value| value > 0. && value.is_finite())
{
return Err(Error::Data(
"image frame dimensions must be finite and positive".into(),
));
}
Ok(())
}
#[derive(Debug, Clone)]
pub(crate) struct FixedPanel {
pub(super) source: FixedSource,
frame: Option<(f64, f64)>,
pub(super) requested: [Option<f64>; 2],
pub(super) fit: ObjectFit,
pub(super) position: ObjectPosition,
pub(super) rendering: ImageRendering,
}
impl FixedPanel {
pub(crate) fn is_frozen(&self) -> bool {
self.source.is_frozen()
}
pub(crate) fn minimum(&self) -> (f64, f64) {
self.frame.unwrap_or((1. / 1024., 1. / 1024.))
}
pub(crate) fn preferred_width(&self, natural: bool) -> Result<f64> {
if let Some(frame) = self.frame {
return Ok(frame.0);
}
let intrinsic = self.source.intrinsics();
if let Some(width) = intrinsic
.complete()
.map(|size| size.0)
.or(intrinsic.size[0])
{
return Ok(width);
}
if natural {
return Err(Error::Data(
"image has no intrinsic CSS width; specify a panel dimension or canvas width"
.into(),
));
}
Ok(self.minimum().0)
}
pub(crate) fn preferred_height(&self, width: f64) -> Result<f64> {
if let Some(frame) = self.frame {
return Ok(frame.1);
}
let intrinsic = self.source.intrinsics();
intrinsic
.ratio
.map(|ratio| width / ratio)
.or(intrinsic.size[1])
.ok_or_else(|| {
Error::Data(
"image has no intrinsic height; specify a panel dimension or canvas height"
.into(),
)
})
}
pub(crate) fn place(&self, allocation: Rect) -> Result<PlacedContent> {
let frame = if let Some((w, h)) = self.frame {
if w > allocation.width() || h > allocation.height() {
return Err(Error::Render(
"explicit image frame does not fit its allocated panel".into(),
));
}
Rect::new(
allocation.left() + (allocation.width() - w) / 2.,
allocation.top() + (allocation.height() - h) / 2.,
w,
h,
)?
} else {
allocation
};
PlacedContent::boxed(
self.source.clone(),
frame,
self.fit,
self.position,
self.rendering,
)
}
}
fn contain(frame: (f64, f64), ratio: f64) -> (f64, f64) {
let width = frame.0.min(frame.1 * ratio);
(width, width / ratio)
}
fn object_sizes(
intrinsic: Intrinsics,
frame: (f64, f64),
fit: ObjectFit,
) -> Result<((f64, f64), (f64, f64))> {
let natural = intrinsic.complete().unwrap_or_else(|| {
intrinsic.ratio.map_or(
(
intrinsic.size[0].unwrap_or(frame.0),
intrinsic.size[1].unwrap_or(frame.1),
),
|ratio| contain(frame, ratio),
)
});
positive_size(natural)?;
let ratio = intrinsic.ratio.unwrap_or(natural.0 / natural.1);
let fit_size = match fit {
ObjectFit::Contain => contain(frame, ratio),
ObjectFit::Cover => {
let width = frame.0.max(frame.1 * ratio);
(width, width / ratio)
}
ObjectFit::Fill => frame,
ObjectFit::None => natural,
ObjectFit::ScaleDown => contain((frame.0.min(natural.0), frame.1.min(natural.1)), ratio),
};
positive_size(fit_size)?;
Ok((natural, fit_size))
}
#[derive(Debug, Clone)]
pub(crate) struct PlacedContent {
source: FixedSource,
pub(crate) frame: Rect,
pub(crate) object: Rect,
viewport: (f64, f64),
pub(crate) rendering: ImageRendering,
view: Arc<OnceLock<AssetView>>,
}
impl PlacedContent {
pub(crate) fn at(
source: FixedSource,
point: (f64, f64),
requested: [Option<f64>; 2],
anchor: Anchor,
rendering: ImageRendering,
) -> Result<Self> {
let intrinsic = source.intrinsics();
let missing = || {
Error::Data("fixed content needs enough dimensions to determine its source viewport; specify a size or use a box".into())
};
let size = match requested {
[Some(w), Some(h)] => (w, h),
[Some(w), None] => (
w,
intrinsic
.ratio
.map(|ratio| w / ratio)
.or(intrinsic.size[1])
.ok_or_else(missing)?,
),
[None, Some(h)] => (
intrinsic
.ratio
.map(|ratio| h * ratio)
.or(intrinsic.size[0])
.ok_or_else(missing)?,
h,
),
[None, None] => intrinsic.complete().ok_or_else(missing)?,
};
positive_size(size)?;
let (viewport, _) = object_sizes(intrinsic, size, ObjectFit::Fill)?;
let (x, y) = if let Anchor::Local(x, y) = anchor {
(x * size.0 / viewport.0, y * size.1 / viewport.1)
} else {
anchor.point(Rect::new(0., 0., size.0, size.1)?)?
};
Self::boxed(
source,
Rect::new(point.0 - x, point.1 - y, size.0, size.1)?,
ObjectFit::Fill,
ObjectPosition::top_left(),
rendering,
)
}
pub(crate) fn exact_ink(&self, clip: Rect) -> Result<InkExtent> {
let Some(clip) = self
.frame
.intersection(clip)
.and_then(|clip| self.object.intersection(clip))
else {
return Ok(InkExtent::Empty);
};
match &self.source {
FixedSource::Image(asset) => asset.exact_ink(
self.viewport,
self.object,
clip,
self.rendering,
self.view.get(),
),
FixedSource::Frozen(output) => {
let source = Rect::new(0., 0., output.width(), output.height())?;
let local_clip = super::ink::map_rect(clip, self.object, source)?;
super::ink::map_ink(output.scene().exact_ink(local_clip)?, source, self.object)
}
}
}
pub(crate) fn boxed(
source: FixedSource,
frame: Rect,
fit: ObjectFit,
position: ObjectPosition,
rendering: ImageRendering,
) -> Result<Self> {
let frame_size = (frame.width(), frame.height());
positive_size(frame_size)?;
let (viewport, size) = object_sizes(source.intrinsics(), frame_size, fit)?;
let (dx, dy) = position.offset((frame_size.0 - size.0, frame_size.1 - size.1));
let object = Rect::new(frame.left() + dx, frame.top() + dy, size.0, size.1)?;
Ok(Self {
source,
frame,
object,
viewport,
rendering,
view: Arc::new(OnceLock::new()),
})
}
pub(crate) fn is_frozen(&self) -> bool {
self.source.is_frozen()
}
pub(crate) fn native_output(&self) -> Option<&Output> {
match &self.source {
FixedSource::Frozen(output) => Some(output),
FixedSource::Image(_) => None,
}
}
pub(crate) fn prepare(&self) -> Result<()> {
if self.view.get().is_some() {
return Ok(());
}
let FixedSource::Image(asset) = &self.source else {
return Ok(());
};
let view = asset.prepare(self.viewport)?;
crate::operation::checkpoint()?;
let _ = self.view.set(view);
Ok(())
}
pub(crate) fn href(&self, outline: bool) -> Result<&str> {
let view = self
.view
.get()
.ok_or_else(|| Error::Render("fixed image was not prepared by capture".into()))?;
view.href(outline)
}
pub(crate) fn validate_preserve_text(&self) -> Result<()> {
if let Some(native) = self.native_output() {
return native.scene().validate_preserve_text();
}
if let Some(error) = self
.view
.get()
.and_then(|view| view.preserve_error.as_ref())
{
return Err(Error::Render(error.clone()));
}
Ok(())
}
pub(crate) fn font_substitutions(&self, output: &mut Vec<super::ImageFontSubstitution>) {
if let Some(native) = self.native_output() {
native.scene().collect_image_font_substitutions(output);
} else if let Some(view) = self.view.get() {
output.extend_from_slice(&view.substitutions);
}
}
pub(crate) fn ink(&self) -> InkExtent {
if let FixedSource::Image(asset) = &self.source {
if asset.known_empty() {
return InkExtent::Empty;
}
}
if let FixedSource::Frozen(output) = &self.source {
if output.scene().composition().is_none() {
if let Ok(report) = output.layout_report() {
if report.nodes()[0].ink() == InkExtent::Empty {
return InkExtent::Empty;
}
}
}
}
self.object
.intersection(self.frame)
.map_or(InkExtent::Empty, InkExtent::Bounds)
}
}