use std::{
io::{self, Write},
path::Path,
sync::Arc,
};
use crate::{
composition::Composite,
errors::{ErrorContext, OperationEffect, OperationFailure, OperationPhase},
operation::{self, OperationOptions},
Canvas, Error, Output, Plot, Result,
};
use super::{
format::Encoding, value::complete_suffix, Format, PixelBuffer, PixelOptions, PixelTarget,
PngOptions, PngSizing,
};
pub(crate) trait Source {
fn frozen(&self) -> Result<Output>;
fn png_default(&self) -> PngSizing {
PngOptions::default().sizing
}
}
impl<K: crate::kind::Marker> Source for Plot<K> {
fn frozen(&self) -> Result<Output> {
self.freeze()
}
}
impl Source for Canvas {
fn frozen(&self) -> Result<Output> {
self.freeze()
}
}
impl Source for crate::recipe::RecipeFigure {
fn frozen(&self) -> Result<Output> {
self.freeze()
}
}
impl Source for Output {
fn frozen(&self) -> Result<Output> {
Ok(self.clone())
}
}
impl Source for Composite {
fn frozen(&self) -> Result<Output> {
Ok(self.output().clone())
}
fn png_default(&self) -> PngSizing {
self.default_png_sizing()
}
}
fn encode(output: &Output, format: &Format, default: PngSizing) -> Result<Arc<[u8]>> {
operation::phase(OperationPhase::Write)?;
let scene = output.scene();
match format.encoding {
Encoding::Svg => scene.publication_svg(
format.region.resolve(scene)?,
!format.retains_text(),
format.transparent,
format.matte,
None,
),
Encoding::Png => Ok(scene
.encode_png(
&format.pixel_options(default),
format.png_options(default).compression,
)?
.into()),
}
}
fn save(
source: &impl Source,
path: impl AsRef<Path>,
format: &Format,
options: &OperationOptions,
) -> Result<Output> {
operation::run(options, || save_inner(source, path, format))
}
pub(crate) fn save_inner(
source: &impl Source,
path: impl AsRef<Path>,
format: &Format,
) -> Result<Output> {
format.validate()?;
let output = source.frozen()?;
let bytes = encode(&output, format, source.png_default())?;
operation::checkpoint()?;
let path = operation::external(|| complete_suffix(path.as_ref(), format.suffix()))?;
crate::orchestrator::write_atomic(&path, &bytes)?;
Ok(output)
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
struct UnconfirmedWrite(io::Error);
#[doc(hidden)]
pub fn unconfirmed_stream_write(cause: io::Error) -> io::Error {
io::Error::other(UnconfirmedWrite(cause))
}
fn stream_failure(cause: Error, confirmed: usize, uncertain: bool) -> Error {
if confirmed == 0 && !uncertain {
return cause;
}
Error::Operation(Box::new(OperationFailure::new(
OperationPhase::Write,
ErrorContext::new().with_operation(OperationPhase::Write),
OperationEffect::StreamPrefix {
confirmed_bytes: u64::try_from(confirmed).expect("addressable stream length"),
may_have_more: uncertain,
},
cause,
)))
}
pub(crate) fn write_stream(writer: &mut dyn Write, bytes: &[u8]) -> Result<()> {
const CHUNK_BYTES: usize = 64 * 1024;
let mut confirmed = 0;
while confirmed < bytes.len() {
operation::checkpoint().map_err(|error| stream_failure(error, confirmed, false))?;
let remaining = &bytes[confirmed..];
let chunk = &remaining[..remaining.len().min(CHUNK_BYTES)];
match operation::external(|| writer.write(chunk)) {
Ok(0) => {
return Err(stream_failure(
io::Error::from(io::ErrorKind::WriteZero).into(),
confirmed,
false,
))
}
Ok(count) if count <= chunk.len() => confirmed += count,
Ok(_) => {
return Err(stream_failure(
io::Error::new(
io::ErrorKind::InvalidData,
"writer reported more bytes than supplied",
)
.into(),
confirmed,
true,
))
}
Err(error)
if error
.get_ref()
.is_some_and(<dyn std::error::Error + Send + Sync>::is::<UnconfirmedWrite>) =>
{
let cause = error
.into_inner()
.expect("checked host I/O cause")
.downcast::<UnconfirmedWrite>()
.expect("checked host write failure");
return Err(stream_failure(cause.0.into(), confirmed, true));
}
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(stream_failure(error.into(), confirmed, false)),
}
}
Ok(())
}
macro_rules! terminals {
() => {
pub fn save_with(
&self,
path: impl AsRef<Path>,
format: impl Into<Format>,
) -> Result<Output> {
self.save_with_operation(path, format, &OperationOptions::default())
}
pub fn save_with_operation(
&self,
path: impl AsRef<Path>,
format: impl Into<Format>,
options: &OperationOptions,
) -> Result<Output> {
save(self, path, &format.into(), options)
}
pub fn encode(&self, format: impl Into<Format>) -> Result<Arc<[u8]>> {
self.encode_with_operation(format, &OperationOptions::default())
}
pub fn encode_with_operation(
&self,
format: impl Into<Format>,
options: &OperationOptions,
) -> Result<Arc<[u8]>> {
let format = format.into();
operation::run(options, || {
format.validate()?;
encode(&self.frozen()?, &format, self.png_default())
})
}
pub fn write_to(
&self,
writer: &mut dyn Write,
format: impl Into<Format>,
) -> Result<Output> {
self.write_to_with_operation(writer, format, &OperationOptions::default())
}
pub fn write_to_with_operation(
&self,
writer: &mut dyn Write,
format: impl Into<Format>,
options: &OperationOptions,
) -> Result<Output> {
let format = format.into();
operation::run(options, || {
format.validate()?;
let output = self.frozen()?;
let bytes = encode(&output, &format, self.png_default())?;
write_stream(writer, &bytes)?;
Ok(output)
})
}
pub fn pixels(&self) -> Result<PixelBuffer> {
self.pixels_with_options(PixelOptions::default())
}
pub fn pixels_with_options(&self, options: PixelOptions) -> Result<PixelBuffer> {
self.pixels_with_options_with_operation(options, &OperationOptions::default())
}
pub fn pixels_with_options_with_operation(
&self,
options: PixelOptions,
operation_options: &OperationOptions,
) -> Result<PixelBuffer> {
operation::run(operation_options, || {
let output = self.frozen()?;
operation::phase(OperationPhase::Write)?;
output.scene().pixels(&options, None)
})
}
pub fn pixels_into(&self, target: PixelTarget<'_>) -> Result<()> {
self.pixels_into_with_options(target, PixelOptions::default())
}
pub fn pixels_into_with_options(
&self,
target: PixelTarget<'_>,
options: PixelOptions,
) -> Result<()> {
self.pixels_into_with_options_with_operation(
target,
options,
&OperationOptions::default(),
)
}
pub fn pixels_into_with_options_with_operation(
&self,
target: PixelTarget<'_>,
options: PixelOptions,
operation_options: &OperationOptions,
) -> Result<()> {
let options = options.for_target(&target)?;
operation::run(operation_options, || {
let output = self.frozen()?;
operation::phase(OperationPhase::Write)?;
let pixels = output.scene().pixels(&options, Some(target.dimensions()))?;
target.copy(&pixels)
})
}
};
}
impl<K: crate::kind::Marker> Plot<K> {
terminals!();
}
impl Canvas {
terminals!();
}
impl crate::recipe::RecipeFigure {
terminals!();
}
impl Output {
terminals!();
}
impl Composite {
terminals!();
}