diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index 3dc9662bdf..cada27219a 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -76,14 +76,28 @@ fn flate(raw: &[u8]) -> Res<(Vec, usize)> { /// LZW data (`EarlyChange` 1) decoded, and how many bytes of `raw` it took. fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { + let mut out = vec![]; + let used = lzw_into(raw, &mut |bytes| { + out.extend_from_slice(bytes); + if out.len() > MAX_DATA { + return Err(PsError::Limit("decoded data is too large")); + } + Ok(()) + })?; + Ok((out, used)) +} + +/// LZW data (`EarlyChange` 1) decoded into `sink` as it goes, and how many bytes of `raw` it +/// took. +fn lzw_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res { let mut table: Vec> = (0..=255u8).map(|b| vec![b]).collect(); table.push(vec![]); table.push(vec![]); - let (mut out, mut prev): (Vec, Option>) = (vec![], None); + let mut prev: Option> = None; let (mut acc, mut bits, mut width, mut i) = (0u32, 0u32, 9u32, 0usize); loop { while bits < width { - let Some(&b) = raw.get(i) else { return Ok((out, i)) }; + let Some(&b) = raw.get(i) else { return Ok(i) }; i += 1; acc = (acc << 8) | u32::from(b); bits += 8; @@ -96,7 +110,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { width = 9; prev = None; } - 257 => return Ok((out, i)), + 257 => return Ok(i), _ => { let entry = match (table.get(code), &prev) { (Some(e), _) if !e.is_empty() => e.clone(), @@ -107,7 +121,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { } _ => return io("LZWDecode"), }; - out.extend_from_slice(&entry); + sink(&entry)?; if let Some(mut p) = prev.take() && table.len() < 4096 { @@ -121,14 +135,78 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { _ => 9, }; prev = Some(entry); - if out.len() > MAX_DATA { - return Err(PsError::Limit("decoded data is too large")); - } } } } } +/// zlib data inflated into `sink` as it goes (64 KiB at a time), and how many bytes of `raw` it +/// took. +fn flate_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res { + let mut z = flate2::Decompress::new(true); + let mut scratch = vec![0u8; 64 * 1024]; + loop { + let before = (z.total_in(), z.total_out()); + let input = raw.get(usize::try_from(z.total_in()).unwrap_or(usize::MAX)..).unwrap_or_default(); + let status = z.decompress(input, &mut scratch, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?; + let made = usize::try_from(z.total_out() - before.1).unwrap_or(0); + sink(scratch.get(..made).unwrap_or_default())?; + match status { + flate2::Status::StreamEnd => break, + _ if (z.total_in(), z.total_out()) == before => break, + _ => {} + } + } + Ok(usize::try_from(z.total_in()).unwrap_or(raw.len())) +} + +/// Data compressed with filter `f` (`FlateDecode` or `LZWDecode` without a predictor) decoded +/// into `sink` as it goes, and how many bytes of `raw` it took; `None` for other filters. +pub(super) fn decode_into(f: &Filter, raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Option> { + match &*f.name { + _ if f.predictor.is_some() => None, + "FlateDecode" => Some(flate_into(raw, sink)), + "LZWDecode" => Some(lzw_into(raw, sink)), + _ => None, + } +} + +/// How many bytes of `raw` filter `f` would read, found without keeping what it decodes, for +/// data whose decoded form is too large to hold: compressed data (`FlateDecode`, `LZWDecode`, +/// `RunLengthDecode`) is decoded and dropped as it goes, a JPEG ends at its end-of-image +/// marker, as [`dct`] reads it. `None` for other filters, data that can't be decoded, or data +/// that decodes to more than `most` bytes (what the caller's operation budget still pays for). +/// With it, how many bytes were decoded on the way, for the caller to charge: measuring costs +/// the work of decoding, so a program that measures the same data in a loop has to end. +pub(super) fn encoded_len(f: &Filter, raw: &[u8], most: usize) -> (Option, usize) { + let mut decoded = 0usize; + let mut count = |bytes: &[u8]| -> Res { + decoded = decoded.saturating_add(bytes.len()); + if decoded > most { + return Err(PsError::Limit("the program runs too long")); + } + Ok(()) + }; + let used = match &*f.name { + "FlateDecode" => flate_into(raw, &mut count).ok(), + "LZWDecode" => lzw_into(raw, &mut count).ok(), + "RunLengthDecode" => { + let mut i = 0usize; + while let Some(&n) = raw.get(i) { + i += match n { + 128 => return (Some(i + 1), 0), + 0..=127 => 2 + usize::from(n), + _ => 2, + }; + } + Some(raw.len()) + } + "DCTDecode" => Some(find(raw, &[0xFF, 0xD9]).map_or(raw.len(), |e| e + 2)), + _ => None, + }; + (used, decoded) +} + /// Most pixels a DCTDecode JPEG may have: twice the most an image is read with, so every image that /// was read before is still read. const MAX_DCT_PIXELS: u64 = 1 << 27; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index cca8bb50ea..f5d45449f2 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -1,4 +1,4 @@ -use super::filters::{Filter, Predictor, Stream, decode, fax_settings, io}; +use super::filters::{Filter, Predictor, Stream, decode, decode_into, encoded_len, fax_settings, io}; use super::pixels::{Pixels, Spec, by_rows, by_samples, masked, source}; use super::{ Affine, Color, DictRef, HashMap, ImageBlob, ImageObject, Inks, Interp, Key, Lexer, Node, NodeId, NodeKind, Obj, Op, OpacityMask, Paint, PsError, @@ -18,6 +18,8 @@ const MAX_PIXELS: usize = 1 << 26; /// Why an image is missing. const TOO_LARGE: &str = "images too large to read were left out"; +/// Why an image is at a lower resolution than the file's. +const REDUCED: &str = "images of more than 67 million pixels were read at a lower resolution"; /// Most distinct colours an image converts through a tint transform. const MAX_TINTS: usize = 1 << 16; @@ -479,25 +481,184 @@ impl Interp<'_> { /// their own end without decompressing (`ASCIIHexDecode`, `ASCII85Decode`, `SubFileDecode`) /// read the file up to it, the way the image reading all its data would leave it; the /// filters over them, which would only decode what those pass, aren't run. When the first - /// filter decompresses, it is run alone, and a failure (data too large to hold) leaves the - /// data where it was, as before. - fn skip_data(&mut self, src: &Source) { + /// filter decompresses, it is run alone; when it can't hold what it decompresses, it measures + /// its data instead. Unfiltered data is read past by its `n` bytes. A failure that read + /// nothing leaves the data where it was; one after a filter read its data leaves the file + /// past it, with nothing more to read. + fn skip_data(&mut self, src: &Source, n: usize) { + // A procedure (`{ currentfile buf readhexstring pop }`) reads the data itself: it is + // called, and what it gives dropped, until it has given the image's `n` bytes or ends. + if let Source::Proc(p) = src { + let mut given = 0usize; + while given < n { + let Ok(len) = self.call(p.clone()).and_then(|()| self.pop_str()).map(|s| s.len()) else { return }; + if len == 0 { + return; + } + given = given.saturating_add(len); + } + return; + } let Source::File(f) = src else { return }; - let (chain, from) = match &*f.borrow() { + let (chain, from) = match &mut *f.borrow_mut() { Stream::Pending { chain, from } => (chain.clone(), from.clone()), - _ => return, + // The data unfiltered: its `n` bytes are read past, as reading them would. + Stream::Current => { + let k = n.min(self.lex.data().len()); + self.lex.advance(k); + return; + } + Stream::Buf { data, pos, .. } => { + *pos = pos.saturating_add(n).min(data.len()); + return; + } }; let delimited = chain.iter().take_while(|c| matches!(&*c.name, "ASCIIHexDecode" | "ASCII85Decode" | "SubFileDecode")).count(); let head = chain.get(..delimited.max(1)).unwrap_or_default().to_vec(); *f.borrow_mut() = Stream::Pending { chain: head, from: from.clone() }; - // A failure leaves the file as it was; the import goes on without the image either way. + // How much of the file the filters are over is left. + let left = |me: &mut Self| match &from { + None => Some(me.lex.data().len()), + Some(r) => match &*r.borrow() { + Stream::Buf { data, pos, .. } => Some(data.len().saturating_sub(*pos)), + Stream::Current => Some(me.lex.data().len()), + Stream::Pending { .. } => None, + }, + }; + let before = left(self); if self.materialize(f).is_err() { - *f.borrow_mut() = Stream::Pending { chain, from }; - return; + // A filter that read its data before a later one failed has the file past that data, + // where reading the image would leave it: the file is empty from there. + if left(self) != before { + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + return; + } + // Decompressed data too large to hold: the first filter only measures it instead, + // and the file is read past it. Data that can't be decoded at all leaves the file as + // it was; the import goes on without the image either way. + let Some(first) = chain.first() else { return }; + // Measuring decompresses the data, which is charged by the bytes decoded (one operation + // per 256, as `spend_bytes` charges) and stops at what the budget still pays for: + // data measured again and again (a reusable stream reset in a loop) runs out of the + // budget instead of being decoded in full on every pass. + let most = usize::try_from(self.ops_left().saturating_mul(256)).unwrap_or(usize::MAX); + let (used, decoded) = match &from { + Some(r) => match &*r.borrow() { + Stream::Buf { data, pos, .. } => encoded_len(first, data.get(*pos..).unwrap_or_default(), most), + _ => (None, 0), + }, + None => encoded_len(first, self.lex.data(), most), + }; + let paid = self.spend_bytes(decoded).is_ok(); + let Some(used) = used.filter(|_| paid) else { + *f.borrow_mut() = Stream::Pending { chain, from }; + return; + }; + match &from { + Some(r) => { + if let Stream::Buf { pos, .. } = &mut *r.borrow_mut() { + *pos = pos.saturating_add(used); + } + } + None => self.lex.advance(used), + } } *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; } + /// The rows image `s` reads at `step` (rows of `row` bytes), when its one source is the + /// program's data with Flate or LZW last among its filters (and no predictor): the filters + /// before it are decoded as usual, and it decodes into the rows read alone, dropping the + /// others as it goes. `None` (nothing read) for other data, or rows read that would still be + /// more than the reader holds. + fn read_rows(&mut self, s: &Spec, row: usize, step: usize) -> Res>> { + let ([Source::File(f)], oh) = (s.sources.as_slice(), s.h.div_ceil(step)) else { return Ok(None) }; + let (chain, from) = match &*f.borrow() { + Stream::Pending { chain, from } => (chain.clone(), from.clone()), + _ => return Ok(None), + }; + let Some((last, head)) = chain.split_last() else { return Ok(None) }; + if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") { + return Ok(None); + } + let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) }; + self.alloc(kept)?; + // The compressed data: what the filters before the last one decode, or the file itself. + let compressed = if head.is_empty() { + None + } else { + *f.borrow_mut() = Stream::Pending { chain: head.to_vec(), from: from.clone() }; + if let Err(e) = self.materialize(f) { + *f.borrow_mut() = Stream::Pending { chain, from }; + return Err(e); + } + match std::mem::replace(&mut *f.borrow_mut(), Stream::Buf { data: vec![], pos: 0, rgb: None }) { + Stream::Buf { data, pos, .. } => Some(data.get(pos..).unwrap_or_default().to_vec()), + _ => Some(vec![]), + } + }; + let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize); + // Past the image's data and as much again the data is not an image's: it stops there. + let most = row.saturating_mul(s.h).saturating_add(MAX_DATA); + let mut sink = |mut chunk: &[u8]| -> Res { + while !chunk.is_empty() { + let (r, off) = (seen / row.max(1), seen % row.max(1)); + let take = (row - off).min(chunk.len()); + if r < s.h && picked(r / step, step, s.h) == r { + rows.extend_from_slice(chunk.get(..take).unwrap_or_default()); + } + seen += take; + chunk = chunk.get(take..).unwrap_or_default(); + } + if seen > most { + return Err(PsError::Limit("decoded data is too large")); + } + Ok(()) + }; + let used = match &compressed { + Some(data) => decode_into(last, data, &mut sink), + None => match &from { + Some(r) => { + let b = r.borrow(); + let Stream::Buf { data, pos, .. } = &*b else { return io("filter") }; + let used = decode_into(last, data.get(*pos..).unwrap_or_default(), &mut sink); + drop(b); + if let (Some(Ok(n)), Stream::Buf { pos, .. }) = (&used, &mut *r.borrow_mut()) { + *pos = pos.saturating_add(*n); + } + used + } + None => { + let used = decode_into(last, self.lex.data(), &mut sink); + if let Some(Ok(n)) = &used { + self.lex.advance(*n); + } + used + } + }, + }; + drop(sink); + let Some(used) = used else { return Ok(None) }; + // What was decoded is charged whether or not the data decoded to its end. + self.spend_bytes(seen)?; + used?; + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + rows.resize(kept, 0); + Ok(Some(rows)) + } + + /// Leave out image `s` (too large to read), skipping its data: `None`, the image it gives. + fn leave_out(&mut self, s: &Spec) -> Option { + self.out.warn(TOO_LARGE); + let n = if s.stencil.is_some() { 1 } else { s.space.n() }; + let per_source = if s.sources.len() > 1 { 1 } else { n }; + let bytes = (s.w.saturating_mul(per_source).saturating_mul(usize::from(s.bpc))).div_ceil(8).saturating_mul(s.h); + for src in &s.sources { + self.skip_data(src, bytes); + } + None + } + /// The bytes a data procedure gives, called until it gives an empty string or `n` bytes. fn gather(&mut self, p: &Obj, n: usize) -> Res> { Ok(self.read_sources(&[Source::Proc(p.clone())], n, n)?.pop().unwrap_or_default()) @@ -640,13 +801,6 @@ impl Interp<'_> { let mut stencil = self.image_dict(&mask, false)?; stencil.space = Space::Gray; let n = image.space.n(); - if image.w.saturating_mul(image.h) > MAX_PIXELS || stencil.w.saturating_mul(stencil.h) > MAX_PIXELS { - self.out.warn(TOO_LARGE); - for src in image.sources.iter().chain(&stencil.sources) { - self.skip_data(src); - } - return Ok(None); - } // Interleaved data is read into this decoder's own buffers, split into the two images' // samples: those stop counting once both are decoded (their pixels still count). let mut charged = 0; @@ -655,18 +809,19 @@ impl Interp<'_> { let (pixels, samples) = if interleave == 2.0 { let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n)); let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h)); - self.alloc(total)?; - charged = total; - let raw = self.source_bytes(&src, total.min(MAX_DATA))?; + // What is read: an image past the pixel cap is reduced from the samples read. + charged = total.min(MAX_DATA); + self.alloc(charged)?; + let raw = self.source_bytes(&src, charged)?; by_rows(&raw, (mrow, stencil.h), (drow, image.h)) } else { // Each sample: the mask's value, then the colour's, as many bits each. stencil.bpc = image.bpc; (stencil.w, stencil.h) = (image.w, image.h); let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8); - charged = row.saturating_mul(image.h); + charged = row.saturating_mul(image.h).min(MAX_DATA); self.alloc(charged)?; - let raw = self.source_bytes(&src, charged.min(MAX_DATA))?; + let raw = self.source_bytes(&src, charged)?; by_samples(&raw, image.w, image.h, n, image.bpc) }; stencil.sources = vec![Source::Str(pixels)]; @@ -674,7 +829,12 @@ impl Interp<'_> { } let decoded = match self.decode_image(image) { Ok(Some(img)) => self.decode_image(stencil).map(|m| Some((img, m))), - other => other.map(|_| None), + Ok(None) => { + // The mask's own data (`InterleaveType` 3) is skipped with the image's. + let _ = self.leave_out(&stencil); + Ok(None) + } + Err(e) => Err(e), }; self.unalloc(charged); let Some((mut img, m)) = decoded? else { return Ok(None) }; @@ -755,25 +915,53 @@ impl Interp<'_> { Ok(Spec { w, h, bpc, space, decode: vec![], matrix, sources, mask_color: None, stencil }) } + /// Decode the filters image source `f` waits to run. `false` when the decoded data is past + /// what the reader holds and the image is `reduced` (read at a lower resolution): a decode that + /// fails leaves the file empty (`materialize`), but such an image is left out with its data + /// still to skip, so its filters are put back for that. + fn decode_source(&mut self, f: &Rc>, reduced: bool) -> Res { + let pending = match &*f.borrow() { + Stream::Pending { chain, from } => Some((chain.clone(), from.clone())), + _ => None, + }; + match self.materialize(f) { + Ok(()) => Ok(true), + Err(PsError::Limit(_)) if reduced => { + if let Some((chain, from)) = pending { + *f.borrow_mut() = Stream::Pending { chain, from }; + } + Ok(false) + } + Err(e) => Err(e), + } + } + /// The image's pixels, straight RGBA, rows from the first one read, and a CMYK image's ink /// amounts. fn decode_image(&mut self, s: Spec) -> Res> { if !matches!(s.bpc, 1 | 2 | 4 | 8 | 12 | 16) { return ps_err("rangecheck", "BitsPerComponent"); } - if s.w.saturating_mul(s.h) > MAX_PIXELS { - self.out.warn(TOO_LARGE); - for src in &s.sources { - self.skip_data(src); - } - return Ok(None); - } - self.alloc(s.w * s.h * 4)?; + // An image of more pixels than the cap is read at a lower resolution: every `step`th + // sample of every `step`th row (the middle one of each `step` × `step` block). + let step = reduction(s.w, s.h); + let (ow, oh) = (s.w.div_ceil(step), s.h.div_ceil(step)); let n = if s.stencil.is_some() { 1 } else { s.space.n() }; let bpc = usize::from(s.bpc); - for src in &s.sources { - if let Source::File(f) = src { - self.materialize(f)?; + // A reduced image compressed last with Flate or LZW keeps only the rows it reads, as they + // are decoded: its whole data can be more than the reader holds. + let streamed = match if step > 1 { self.read_rows(&s, (s.w * n * bpc).div_ceil(8), step) } else { Ok(None) } { + Ok(rows) => rows, + Err(PsError::Limit(_)) => return Ok(self.leave_out(&s)), + Err(e) => return Err(e), + }; + for src in s.sources.iter().filter(|_| streamed.is_none()) { + // Decoded data past the cap: a reduced image is left out (its data skipped) rather + // than failing the file, as an image too large to read at all is. + if let Source::File(f) = src + && !self.decode_source(f, step > 1)? + { + return Ok(self.leave_out(&s)); } } // A decoded JPEG gives 8-bit gray, RGB or CMYK samples whatever the color space says. @@ -798,15 +986,39 @@ impl Interp<'_> { if sources.len() > n { return ps_err("rangecheck", "DataSource"); } - let plane = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA).ok_or(PsError::Limit("decoded data is too large"))?; - // The sample planes are this decoder's own and live only while the image is decoded: they - // stop counting once it is (the pixels made from them still count). What the data source - // procedures allocate is the program's and stays counted. - let plane_bytes = plane.saturating_mul(sources.len()); - self.alloc(plane_bytes)?; - let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?; - for p in &mut planes { - p.resize(row * s.h, 0); + // With only the rows read kept, row `i` of the plane is the `i`th row read. + let rows_kept = streamed.is_some(); + // The sample planes (or the rows kept) are this decoder's own and live only while the + // image is decoded: they stop counting once it is (the pixels made from them still + // count). What the data source procedures allocate is the program's and stays counted. + let (planes, plane_bytes) = match streamed { + Some(rows) => { + let kept = rows.len(); + (vec![rows], kept) + } + None => { + // More samples than the reader holds: a reduced image is left out (its data + // skipped), while one within the pixel cap whose samples are still too much data + // (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane + // is refused). + let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else { + if step > 1 { + return Ok(self.leave_out(&s)); + } + return Err(PsError::Limit("decoded data is too large")); + }; + let plane_bytes = plane.saturating_mul(sources.len()); + self.alloc(plane_bytes)?; + let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?; + for p in &mut planes { + p.resize(row * s.h, 0); + } + (planes, plane_bytes) + } + }; + self.alloc(ow * oh * 4)?; + if step > 1 { + self.out.warn(REDUCED); } let max = ((1u32 << bpc.min(16)) - 1) as f64; let sample = |plane: &[u8], y: usize, i: usize| -> u32 { @@ -830,19 +1042,19 @@ impl Interp<'_> { // with the default Decode array. let decode = if s.decode.len() >= 2 * n && jpeg.is_none_or(|c| c == 4) { s.decode.clone() } else { default_decode }; let paint = self.g.paint.color().map(|c| c.to_rgba8(1.0)); - let mut rgba = Vec::with_capacity(s.w * s.h * 4); + let mut rgba = Vec::with_capacity(ow * oh * 4); // CMYK samples keep their ink amounts, as the Decode array reads them. let mut inks = if matches!(space, Space::Cmyk) && s.stencil.is_none() { - self.alloc(s.w * s.h * 4)?; - Some(Vec::with_capacity(s.w * s.h * 4)) + self.alloc(ow * oh * 4)?; + Some(Vec::with_capacity(ow * oh * 4)) } else { None }; let mut cache: HashMap, [u8; 3]> = HashMap::new(); let mut raw = vec![0u32; n]; let mut comps = vec![0f64; n]; - for y in 0..s.h { - for x in 0..s.w { + for y in (0..oh).map(|y| if rows_kept { y } else { picked(y, step, s.h) }) { + for x in (0..ow).map(|x| picked(x, step, s.w)) { for (c, slot) in raw.iter_mut().enumerate() { *slot = match planes.as_slice() { [one] => sample(one, y, x * n + c), @@ -882,7 +1094,9 @@ impl Interp<'_> { } drop(planes); self.unalloc(plane_bytes); - Ok(Some(Pixels { w: s.w as u32, h: s.h as u32, rgba, inks, matrix: s.matrix })) + // The reduced samples cover the image's area: image space scaled to them. + let matrix = Affine::scale_non_uniform(ow as f64 / s.w as f64, oh as f64 / s.h as f64) * s.matrix; + Ok(Some(Pixels { w: ow as u32, h: oh as u32, rgba, inks, matrix })) } /// One pixel's colour in `space` as display RGB. @@ -959,3 +1173,19 @@ impl Interp<'_> { Some(OpacityMask::new(Node::new(self.out.doc.alloc_id(), NodeKind::Image(Box::new(im))), true)) } } + +/// The sample (or row) of `len` a reduced image reads as its `i`th at `step`: the middle one of +/// its block of `step`, the last one in a short last block. +fn picked(i: usize, step: usize, len: usize) -> usize { + (i * step + step / 2).min(len.saturating_sub(1)) +} + +/// The step [`Interp::decode_image`] reads a `w` × `h` image at: 1 (every sample) within +/// [`MAX_PIXELS`], else the least that brings the samples it reads within it. +fn reduction(w: usize, h: usize) -> usize { + let mut step = 1; + while w.div_ceil(step).saturating_mul(h.div_ceil(step)) > MAX_PIXELS { + step += 1; + } + step +} diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index ac3b5a369a..a9385f8eff 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -552,29 +552,153 @@ fn tiff_predicted_rows_at_every_depth() { assert!(wrong.is_empty(), "{wrong:#?}"); } -/// An image too large to read is left out, and its data is skipped, as reading it would leave -/// the program: the art after it is read, not the data as PostScript. Here the data ends at its -/// `~>` (an inline image of a content stream run as a file, as PDF-reading prologs write it), at -/// a `SubFileDecode` end string, and at the end of compressed data that is read whole. +/// An image over the reader's pixel cap is read at a lower resolution, or when its data is too +/// large to hold left out with its data skipped; either way the program goes on after the data, +/// as reading the whole image would leave it: the art after it is read, not the data as +/// PostScript. Here the data ends at its `~>` (an inline image of a content stream run as a file, +/// as PDF-reading prologs write it), at a `SubFileDecode` end string, and at the end of +/// compressed data that is read whole. #[test] fn the_data_of_an_image_too_large_to_read_is_skipped() { let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let packed = crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64])); for program in [ format!( "/ID {{ << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] \ - /DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /LZWDecode filter >> \ + /DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter >> \ /DeviceRGB setcolorspace image }} def\n\ - currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\nJ1_V7fG\"r'\"b]2#:hXAd)~>\n{after}\nendstream\n" + currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\n{packed}\n{after}\nendstream\n" ), format!("10000 10000 8 [1 0 0 1 0 0] currentfile /ASCIIHexDecode filter false 3 colorimage\n0a1b 2c3d 4e5f>\n{after}"), format!( - "10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /FlateDecode filter image\n\ - x\u{9c}garbage\n%%EndData\n{after}" + "10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter image\n\ + {packed}\n%%EndData\n{after}" ), + format!("10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{packed}\n{after}"), + ] { + let r = read(&program); + assert!(r.warnings.iter().any(|w| w.contains("too large to read") || w.contains("lower resolution")), "{program}: {:?}", r.warnings); + let o = super::tests::objects(&r.document); + let last = o.last().expect("the art after the image"); + assert_eq!(super::tests::fill(last), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}"); + } +} + +/// An image of more pixels than the reader's cap (2^26) is read at a lower resolution, every +/// second sample of every second row here, over the same area, with a note; not left out. +#[test] +fn an_image_over_the_pixel_cap_is_read_at_a_lower_resolution() { + // 9000 × 8000 one-bit samples, every row the same: its left half ones, painted. + let row = format!("{}{}", "ff".repeat(563), "00".repeat(562)); + let r = read(&format!("0 0 1 setrgbcolor 90 80 scale 9000 8000 true [9000 0 0 -8000 0 8000] <{row}> imagemask")); + assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings); + let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else { + panic!("an image") + }; + assert_eq!((im.width, im.height), (4500, 4000)); + // Its 4500 × 4000 pixels cover the 90 × 80 points the image does. + let corner = im.xf * kurbo::Point::new(4500.0, 4000.0); + let origin = im.xf * kurbo::Point::ZERO; + assert!(((corner - origin).x.abs() - 90.0).abs() < 1e-6 && ((corner - origin).y.abs() - 80.0).abs() < 1e-6, "{:?}", im.xf); + // Left half painted, right half clear. + assert_eq!(pixel(&r.document, 100, 2000)[3], 255); + assert_eq!(pixel(&r.document, 4400, 2000)[3], 0); +} + +/// An image over the pixel cap whose samples are more data than the reader holds (9500 × 9500 +/// RGB is 270 MB) is read at a lower resolution too when Flate or LZW compresses it last: only +/// the rows it reads are kept as they are decoded. +#[test] +fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { + let (w, h) = (9500usize, 9500usize); + let mut samples = Vec::with_capacity(w * h * 3); + for y in 0..h { + let px: [u8; 3] = if y < h / 2 { [255, 0, 0] } else { [0, 0, 255] }; + samples.extend(std::iter::repeat_n(px, w).flatten()); + } + let data = crate::ps::ascii85(&crate::ps::deflate(&samples)); + drop(samples); + let r = read(&format!( + "95 95 scale {w} {h} 8 [{w} 0 0 -{h} 0 {h}] currentfile /ASCII85Decode filter /FlateDecode filter false 3 colorimage\n{data}\n\ + 0 1 0 setrgbcolor 0 0 0.1 0.1 rectfill" + )); + assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings); + let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else { + panic!("an image") + }; + assert_eq!((im.width, im.height), (4750, 4750)); + // The rows read from the top half are red, from the bottom half blue. + assert_eq!(pixel(&r.document, 10, 10), [255, 0, 0, 255]); + assert_eq!(pixel(&r.document, 10, 4740), [0, 0, 255, 255]); + // The art after the data is read. + assert_eq!(super::tests::objects(&r.document).len(), 2); +} + +/// An image too large to read even at a lower resolution (its samples are more data than the +/// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure +/// is called until the data ends; when its first filter decompresses to more than the reader +/// holds (and can't be read a row at a time), the compressed data is measured without keeping it. +#[test] +fn the_data_of_an_image_too_large_to_hold_is_skipped() { + let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]); + // Predicted rows aren't decoded a row at a time: such an image is left out. + let mut flate = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); + flate.extend(&zeros); + flate.extend(format!("\n{after}").as_bytes()); + for program in [ format!( - "10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{}\n{after}", - crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64])) - ), + "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ + 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" + ) + .into_bytes(), + flate, + ] { + let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); + let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + file.extend(&program); + file.extend(b"\nshowpage\n%%EOF\n"); + let r = import(&file).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings); + let o = super::tests::objects(&r.document); + assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings); + assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{text}"); + } +} + +/// Measuring the data of an image too large to hold decompresses it, and that is charged to the +/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed +/// zeros is left out and measured again each time a loop runs the stream from its start, runs out +/// of the budget. +#[test] +fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() { + let mut program = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); + program.extend(crate::ps::deflate(&vec![0u8; 300 << 20])); + let hex: String = program.iter().map(|b| format!("{b:02x}")).collect(); + super::tests::runs_out_of_budget(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); +} + +/// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is +/// skipped too: unfiltered from the program's own file by its byte count, and through a filter +/// shared with later reads, which then find the file past the data (here the second filter fails +/// on what the first decoded) rather than decoding the program after it. +#[test] +fn the_mask_data_of_an_image_left_out_is_skipped() { + let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let masked = |source: &str| { + format!( + "<< /ImageType 3 /InterleaveType 3 /DataDict << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 \ + /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] /DataSource (x) >> \ + /MaskDict << /ImageType 1 /Width 10 /Height 10 /BitsPerComponent 1 /Decode [0 1] /ImageMatrix [1 0 0 1 0 0] \ + /DataSource {source} >> >> /DeviceRGB setcolorspace image" + ) + }; + for program in [ + // 10 rows of 2 bytes, not PostScript. + format!("{}\n{}\n{after}", masked("currentfile"), "@".repeat(20)), + format!("/F currentfile /ASCIIHexDecode filter /ASCII85Decode filter def {}\n7676>\nF read {{ pop }} if {after}", masked("F")), ] { let r = read(&program); assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{program}: {:?}", r.warnings); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 932138e226..dc7bde0aca 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (EPS import: images over 67 million pixels are read at a lower resolution; `.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > **File-font integration status (2026-11-19, #4569):** 56 focused PDF/native-reopen, file-font, stroked-text and font-binding tests passed on the current-main integration candidate. Full workspace CI and hardening paths outside those suites remain pending. Scores and estimates unchanged. > @@ -354,7 +354,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | | PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X; the document language as the catalog's `/Lang` and XMP `dc:language`, #3644) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | -| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | +| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); an image of more than 2^26 pixels is read at a lower resolution (every second, third… sample of every second, third… row), not left out, with a note; when its data is more than the reader holds, Flate or LZW compressing it last (without a predictor) is decoded keeping only the rows read; sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`) | @@ -447,6 +447,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | | 2026-11-11 | minor | Newly imported SVG/SVGZ titles use the imported-text rules: generated Untitled names and control-only titles give the filename fallback, other control characters are removed, and titles are limited to 65,536 characters. Native and Preserve Editing titles remain unchanged (#3626). | | 2026-11-11 | minor | Native and Preserve Editing restores keep an existing File Info title exactly, including repeated spaces; imported-text fallback titles alone are normalized (#3626). | +| 2026-11-07 | minor | EPS import: an image of more than 2^26 pixels (the reader's cap) was left out, so a page that is one large scan or photo came in empty. It is now read at a lower resolution: the least whole step that brings it within the cap, the middle sample of each step × step block, over the image's whole area, with the note *images of more than 67 million pixels were read at a lower resolution*. When its samples are more data than the reader holds (256 MB), an image whose last filter is Flate or LZW without a predictor is decoded a row at a time, keeping only the rows read (an 11903 × 8423 RGB page, 300 MB, comes in at 5952 × 4212). An image left out still has its data skipped (#6003), now also when a procedure reads it (called until it has given the image's data or ends) and when its first filter decompresses to more than the reader holds (the compressed data is measured without keeping it). Tests `an_image_over_the_pixel_cap_is_read_at_a_lower_resolution`, `an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads`, `the_data_of_an_image_too_large_to_hold_is_skipped`; scores unchanged | | 2026-11-03 | minor | An imported document's own title goes into File Info only (#3626): an SVG's root `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` else its Info `Title` is File Info's title (`metadata.title` in the native format, left out when unset so other documents save unchanged and older versions ignore it; written by exports); the document's name, which the tab, Save As and the default export names use, stays the file's name. | | 2026-11-11 | minor | `.ai` and EPS import, and what the canvas, every export and `.ai` save draw: type's strokes in an envelope (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them (used locally, never committed: there the drawn art keeps those strokes as stroked paths at the type's own weights, and its ring is as wide wherever the grid squeezes or stretches the type). With Distort Appearance, VectorCraft bent them with the art, as their filled outlines, so an envelope of stroked type in a squeezed or stretched grid didn't draw as its drawn art and kept it. The same holds in an envelope inside an envelope. Paths' strokes, geometry effects, opacity masks, linear gradients and pattern fills bend as before. On 224 of our own files: envelopes of type that open live go from 135 in 37 files to 154 in 45, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 31 files, by at most 2.3% of their pixels, 19 closer to the file's own page and 12 further, 11 of those where an envelope of type now opens live in place of its drawn art (the page's own art) and one by 4 pixels. Tests `envelope_distort::type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope`, `a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope`, `a_paths_stroke_still_bends_in_a_squeezed_envelope`, `tests_native::an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live` (#6644) | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. |