1use std::{
4 io::{self, Write},
5 path::Path,
6 sync::Arc,
7};
8
9use crate::{
10 composition::Composite,
11 errors::{ErrorContext, OperationEffect, OperationFailure, OperationPhase},
12 operation::{self, OperationOptions},
13 Canvas, Error, Output, Plot, Result,
14};
15
16use super::{
17 format::Encoding, value::complete_suffix, Format, PixelBuffer, PixelOptions, PixelTarget,
18 PngOptions, PngSizing,
19};
20
21pub(crate) trait Source {
22 fn frozen(&self) -> Result<Output>;
23 fn png_default(&self) -> PngSizing {
24 PngOptions::default().sizing
25 }
26}
27
28impl<K: crate::kind::Marker> Source for Plot<K> {
29 fn frozen(&self) -> Result<Output> {
30 self.freeze()
31 }
32}
33impl Source for Canvas {
34 fn frozen(&self) -> Result<Output> {
35 self.freeze()
36 }
37}
38impl Source for crate::recipe::RecipeFigure {
39 fn frozen(&self) -> Result<Output> {
40 self.freeze()
41 }
42}
43impl Source for Output {
44 fn frozen(&self) -> Result<Output> {
45 Ok(self.clone())
46 }
47}
48impl Source for Composite {
49 fn frozen(&self) -> Result<Output> {
50 Ok(self.output().clone())
51 }
52 fn png_default(&self) -> PngSizing {
53 self.default_png_sizing()
54 }
55}
56
57fn encode(output: &Output, format: &Format, default: PngSizing) -> Result<Arc<[u8]>> {
58 operation::phase(OperationPhase::Write)?;
59 let scene = output.scene();
60 match format.encoding {
61 Encoding::Svg => scene.publication_svg(
62 format.region.resolve(scene)?,
63 !format.retains_text(),
64 format.transparent,
65 format.matte,
66 None,
67 ),
68 Encoding::Png => Ok(scene
69 .encode_png(
70 &format.pixel_options(default),
71 format.png_options(default).compression,
72 )?
73 .into()),
74 }
75}
76
77fn save(
78 source: &impl Source,
79 path: impl AsRef<Path>,
80 format: &Format,
81 options: &OperationOptions,
82) -> Result<Output> {
83 operation::run(options, || save_inner(source, path, format))
84}
85
86pub(crate) fn save_inner(
87 source: &impl Source,
88 path: impl AsRef<Path>,
89 format: &Format,
90) -> Result<Output> {
91 format.validate()?;
92 let output = source.frozen()?;
93 let bytes = encode(&output, format, source.png_default())?;
94 operation::checkpoint()?;
95 let path = operation::external(|| complete_suffix(path.as_ref(), format.suffix()))?;
96 crate::orchestrator::write_atomic(&path, &bytes)?;
97 Ok(output)
98}
99
100#[derive(Debug, thiserror::Error)]
103#[error(transparent)]
104struct UnconfirmedWrite(io::Error);
105
106#[doc(hidden)]
110pub fn unconfirmed_stream_write(cause: io::Error) -> io::Error {
111 io::Error::other(UnconfirmedWrite(cause))
112}
113
114fn stream_failure(cause: Error, confirmed: usize, uncertain: bool) -> Error {
115 if confirmed == 0 && !uncertain {
116 return cause;
117 }
118 Error::Operation(Box::new(OperationFailure::new(
119 OperationPhase::Write,
120 ErrorContext::new().with_operation(OperationPhase::Write),
121 OperationEffect::StreamPrefix {
122 confirmed_bytes: u64::try_from(confirmed).expect("addressable stream length"),
123 may_have_more: uncertain,
124 },
125 cause,
126 )))
127}
128
129pub(crate) fn write_stream(writer: &mut dyn Write, bytes: &[u8]) -> Result<()> {
130 const CHUNK_BYTES: usize = 64 * 1024;
131 let mut confirmed = 0;
132 while confirmed < bytes.len() {
133 operation::checkpoint().map_err(|error| stream_failure(error, confirmed, false))?;
134 let remaining = &bytes[confirmed..];
135 let chunk = &remaining[..remaining.len().min(CHUNK_BYTES)];
136 match operation::external(|| writer.write(chunk)) {
137 Ok(0) => {
138 return Err(stream_failure(
139 io::Error::from(io::ErrorKind::WriteZero).into(),
140 confirmed,
141 false,
142 ))
143 }
144 Ok(count) if count <= chunk.len() => confirmed += count,
145 Ok(_) => {
146 return Err(stream_failure(
147 io::Error::new(
148 io::ErrorKind::InvalidData,
149 "writer reported more bytes than supplied",
150 )
151 .into(),
152 confirmed,
153 true,
154 ))
155 }
156 Err(error)
157 if error
158 .get_ref()
159 .is_some_and(<dyn std::error::Error + Send + Sync>::is::<UnconfirmedWrite>) =>
160 {
161 let cause = error
162 .into_inner()
163 .expect("checked host I/O cause")
164 .downcast::<UnconfirmedWrite>()
165 .expect("checked host write failure");
166 return Err(stream_failure(cause.0.into(), confirmed, true));
167 }
168 Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
169 Err(error) => return Err(stream_failure(error.into(), confirmed, false)),
170 }
171 }
172 Ok(())
176}
177
178macro_rules! terminals {
179 () => {
180 pub fn save_with(
183 &self,
184 path: impl AsRef<Path>,
185 format: impl Into<Format>,
186 ) -> Result<Output> {
187 self.save_with_operation(path, format, &OperationOptions::default())
188 }
189
190 pub fn save_with_operation(
192 &self,
193 path: impl AsRef<Path>,
194 format: impl Into<Format>,
195 options: &OperationOptions,
196 ) -> Result<Output> {
197 save(self, path, &format.into(), options)
198 }
199
200 pub fn encode(&self, format: impl Into<Format>) -> Result<Arc<[u8]>> {
202 self.encode_with_operation(format, &OperationOptions::default())
203 }
204
205 pub fn encode_with_operation(
207 &self,
208 format: impl Into<Format>,
209 options: &OperationOptions,
210 ) -> Result<Arc<[u8]>> {
211 let format = format.into();
212 operation::run(options, || {
213 format.validate()?;
214 encode(&self.frozen()?, &format, self.png_default())
215 })
216 }
217
218 pub fn write_to(
221 &self,
222 writer: &mut dyn Write,
223 format: impl Into<Format>,
224 ) -> Result<Output> {
225 self.write_to_with_operation(writer, format, &OperationOptions::default())
226 }
227
228 pub fn write_to_with_operation(
230 &self,
231 writer: &mut dyn Write,
232 format: impl Into<Format>,
233 options: &OperationOptions,
234 ) -> Result<Output> {
235 let format = format.into();
236 operation::run(options, || {
237 format.validate()?;
238 let output = self.frozen()?;
239 let bytes = encode(&output, &format, self.png_default())?;
240 write_stream(writer, &bytes)?;
241 Ok(output)
242 })
243 }
244
245 pub fn pixels(&self) -> Result<PixelBuffer> {
247 self.pixels_with_options(PixelOptions::default())
248 }
249
250 pub fn pixels_with_options(&self, options: PixelOptions) -> Result<PixelBuffer> {
252 self.pixels_with_options_with_operation(options, &OperationOptions::default())
253 }
254
255 pub fn pixels_with_options_with_operation(
257 &self,
258 options: PixelOptions,
259 operation_options: &OperationOptions,
260 ) -> Result<PixelBuffer> {
261 operation::run(operation_options, || {
262 let output = self.frozen()?;
263 operation::phase(OperationPhase::Write)?;
264 output.scene().pixels(&options, None)
265 })
266 }
267
268 pub fn pixels_into(&self, target: PixelTarget<'_>) -> Result<()> {
270 self.pixels_into_with_options(target, PixelOptions::default())
271 }
272
273 pub fn pixels_into_with_options(
275 &self,
276 target: PixelTarget<'_>,
277 options: PixelOptions,
278 ) -> Result<()> {
279 self.pixels_into_with_options_with_operation(
280 target,
281 options,
282 &OperationOptions::default(),
283 )
284 }
285
286 pub fn pixels_into_with_options_with_operation(
288 &self,
289 target: PixelTarget<'_>,
290 options: PixelOptions,
291 operation_options: &OperationOptions,
292 ) -> Result<()> {
293 let options = options.for_target(&target)?;
294 operation::run(operation_options, || {
295 let output = self.frozen()?;
296 operation::phase(OperationPhase::Write)?;
297 let pixels = output.scene().pixels(&options, Some(target.dimensions()))?;
298 target.copy(&pixels)
299 })
300 }
301 };
302}
303
304impl<K: crate::kind::Marker> Plot<K> {
305 terminals!();
306}
307impl Canvas {
308 terminals!();
309}
310impl crate::recipe::RecipeFigure {
311 terminals!();
312}
313impl Output {
314 terminals!();
315}
316impl Composite {
317 terminals!();
318}