Merge main preserving RTF safety and PPTX parity fixes

This commit is contained in:
Dylan M. Taylor committed 2026-11-18 21:06:36 -05:00
commit 44aaf2d003
28 files changed
+297 -2352

No files matched your search

+4
View File
@@ -46,6 +46,10 @@ jobs:
# A missing oracle fails the job instead of printing a skip notice that reads as a pass.
linux-env: PDFCRAFT_ORACLES_REQUIRED=1
windows-env: PDFCRAFT_REQUIRE_WINRES=1
# Windows completed its 54m33s gate, then cache save hit the default 60m job cap
# (run 44364342368). Leave bounded room for setup and post-job cleanup.
# This changes no test watchdog or selection; craft-common-actions#60.
timeout-minutes: 90
# Preserve the packaging regression check removed from git-sources in #7042.
command: |
pwsh -NoProfile -File packaging/windows/test-font-notices.ps1
Generated
+56 -8
View File
@@ -1238,7 +1238,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf
dependencies = [
"base64 0.23.1",
"chrono",
"craft-drawingml",
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
"craft-math 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
"craft-offcrypto",
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
@@ -1251,6 +1251,17 @@ dependencies = [
"zeroize",
]
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"kurbo 0.13.1",
"log",
"serde",
]
[[package]]
name = "craft-drawingml"
version = "0.1.0"
@@ -1437,10 +1448,10 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"log",
"thiserror 2.0.21",
]
@@ -1448,10 +1459,10 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
"log",
"thiserror 2.0.21",
]
@@ -1507,6 +1518,21 @@ dependencies = [
"zeroize",
]
[[package]]
name = "craft-pptx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"kurbo 0.13.1",
"log",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-prc"
version = "0.1.0"
@@ -1695,6 +1721,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
@@ -1744,6 +1780,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
@@ -3230,6 +3276,7 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33"
[[package]]
name = "hayro-syntax"
@@ -3864,6 +3911,7 @@ dependencies = [
"arrayvec",
"euclid",
"polycool",
"serde",
"smallvec",
]
@@ -4995,7 +5043,7 @@ dependencies = [
"craft-docx",
"craft-markdown",
"craft-mime",
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
"craft-pptx",
"craft-rtf",
"craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
+3 -3
View File
@@ -48,8 +48,8 @@ craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0
craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" }
craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "010702ee9b030844c852939095b1da0d0656a890" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "010702ee9b030844c852939095b1da0d0656a890" }
craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" }
# internal
pdfcraft-geom = { path = "crates/geom", version = "0.21.0" }
@@ -167,7 +167,7 @@ hayro-interpret = { path = "vendor/hayro-interpret" }
hayro = { path = "vendor/hayro" }
hayro-syntax = { path = "vendor/hayro-syntax" }
hayro-cmap = { path = "vendor/hayro-cmap" }
hayro-postscript = { path = "vendor/hayro-postscript" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" }
hayro-jbig2 = { path = "vendor/hayro-jbig2" }
lopdf = { path = "vendor/lopdf" }
vello_common = { path = "vendor/vello_common" }
-1
View File
@@ -72,7 +72,6 @@ fn renderer_and_security_vendors_remain() {
"vendor/hayro-syntax",
"vendor/hayro-cmap",
"vendor/hayro-jbig2",
"vendor/hayro-postscript",
"vendor/lopdf",
"vendor/vello_common",
] {
+1 -1
View File
@@ -13,11 +13,11 @@ workspace = true
[dependencies]
craft-markdown.workspace = true
craft-mime.workspace = true
craft-opc.workspace = true
craft-rtf = { workspace = true, features = ["doc"] }
craft-wordmodel.workspace = true
craft-docx.workspace = true
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
craft-pptx.workspace = true
craft-xml.workspace = true
craft-zip.workspace = true
-12
View File
@@ -4,18 +4,6 @@
use super::as_word::{Meta, word_doc};
use super::layout::{Image, Page};
use craft_xml::Writer;
pub(crate) fn core_properties_xml(title: &str) -> Vec<u8> {
let mut w = Writer::document();
w.open(
"cp:coreProperties",
&[("xmlns:cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"), ("xmlns:dc", "http://purl.org/dc/elements/1.1/")],
);
w.leaf("dc:title", &[], title);
w.into_bytes()
}
pub(crate) fn image_mime(ext: &str) -> &'static str {
match ext.to_ascii_lowercase().as_str() {
"png" => "image/png",
+152 -253
View File
@@ -2,11 +2,16 @@
//! largest text as slide title, remaining paragraphs as body text, images and tables between them.
use std::collections::HashMap;
use std::sync::Arc;
use crate::as_docx::{core_properties_xml, image_mime, room_for};
use crate::as_docx::{image_mime, room_for};
use crate::{Image, Page, Run, Table, hex};
use craft_opc::{PackageOut, RT_BASE, RelOut, RelsOut};
use craft_xml::{DECL_STANDALONE, esc};
use craft_pptx::table::{Cell, Table as DmlTable};
use craft_pptx::text::{Paragraph, Run as DmlRun, RunKind, RunProps, TextBody};
use craft_pptx::{
ColorBase, ColorRef, Fill, Geom, Line, MediaId, MediaItem, Plain, Presentation, Rgba, Shape, ShapeId, ShapeKind, Size, Slide, SlideId, Xfrm,
style::PictureFill,
};
/// Items on a slide in reading order.
enum SlideBodyItem<'a> {
@@ -16,102 +21,106 @@ enum SlideBodyItem<'a> {
Img(&'a Image),
}
/// Convert points to EMU (English Metric Units: 1 pt = 12700 EMU).
///
/// Clamps to PowerPoint's allowed slide dimensions: 1 inch (914,400 EMU = 72 pt)
/// to 56 inches (51,206,400 EMU = 4032 pt).
fn emu(pt: f64, default_pt: f64) -> i64 {
if pt.is_finite() && pt > 0.0 { (pt * 12700.0).round().clamp(914400.0, 51206400.0) as i64 } else { (default_pt * 12700.0).round() as i64 }
/// Clamp slide dimensions in points to PowerPoint's allowed range: 1 inch (72 pt) to 56 inches (4032 pt).
fn slide_pt(pt: f64, default_pt: f64) -> f64 {
if pt.is_finite() && pt > 0.0 { pt.clamp(72.0, 4032.0) } else { default_pt }
}
/// The largest height one item may take on a slide (about 1,100 inches). Text sizes and image
/// rectangles come from the PDF, so a hostile size (say 1e300 pt) must not push the running
/// vertical position past what an `i64` (or a DrawingML coordinate) holds.
const MAX_ITEM_EMU: i64 = 1_000_000_000;
/// The largest height one item may take on a slide (about 1,100 inches in points).
const MAX_ITEM_PT: f64 = 78_740.0;
/// Points to EMU for a height or gap, clamped to `0..=MAX_ITEM_EMU` (NaN reads as 0).
fn height_emu(pt: f64) -> i64 {
let v = pt * 12700.0;
// Clamped to 0..=MAX_ITEM_EMU before the cast, so it cannot truncate or wrap.
if v.is_finite() {
v.round().clamp(0.0, MAX_ITEM_EMU as f64) as i64
} else if v > 0.0 {
MAX_ITEM_EMU
/// Points for a height or gap, clamped to `0..=MAX_ITEM_PT` (NaN reads as 0).
fn height_pt(pt: f64) -> f64 {
if pt.is_finite() {
pt.clamp(0.0, MAX_ITEM_PT)
} else if pt > 0.0 {
MAX_ITEM_PT
} else {
0
0.0
}
}
/// A formatted DrawingML text run (`<a:r>`).
fn run_drawingml(text: &str, size: f64, bold: bool, italic: bool, color: [f64; 3]) -> String {
let mut rpr = String::new();
let sz = if size.is_finite() { (size * 100.0).round().clamp(100.0, 400000.0) as i64 } else { 1200 };
rpr.push_str(&format!(" sz=\"{sz}\""));
if bold {
rpr.push_str(" b=\"1\"");
/// Parse a 6-digit hex color string into `Rgba`.
fn rgba_from_hex(h: &str) -> Option<Rgba> {
if h.len() != 6 {
return None;
}
if italic {
rpr.push_str(" i=\"1\"");
}
let fill = if let Some(h) = hex(color) { format!("<a:solidFill><a:srgbClr val=\"{h}\"/></a:solidFill>") } else { String::new() };
format!("<a:r><a:rPr{rpr}>{fill}</a:rPr><a:t>{}</a:t></a:r>", esc(text))
let r = u8::from_str_radix(&h[0..2], 16).ok()?;
let g = u8::from_str_radix(&h[2..4], 16).ok()?;
let b = u8::from_str_radix(&h[4..6], 16).ok()?;
Some(Rgba::rgb(r, g, b))
}
/// Generates a DrawingML table inside a `<p:graphicFrame>` with explicit cell borders.
fn pptx_table(shape_id: usize, t: &Table, x: i64, y: i64, content_w: i64) -> (String, i64) {
/// A formatted DrawingML text run.
fn dml_run(text: &str, size: f64, bold: bool, italic: bool, color: [f64; 3]) -> DmlRun {
let sz = if size.is_finite() { size.clamp(1.0, 4000.0) } else { 12.0 };
let fill =
hex(color).and_then(|h| rgba_from_hex(&h)).map(|c| Fill::Solid { color: ColorRef { base: ColorBase::Rgb { rgb: c }, mods: Vec::new() } });
DmlRun {
text: text.to_string(),
props: RunProps {
size: Some(sz),
bold: if bold { Some(true) } else { None },
italic: if italic { Some(true) } else { None },
fill,
..Default::default()
},
kind: RunKind::Text,
}
}
/// Generates a DrawingML table shape with explicit cell borders.
fn pptx_table(shape_id: u32, t: &Table, x: f64, y: f64, content_w: f64) -> (Shape, f64) {
let mut edges = t.cols.clone();
edges.push(t.rect[2]);
let widths_pt: Vec<f64> = edges.windows(2).map(|w| (w[1] - w[0]).max(20.0)).collect();
let total_pt: f64 = widths_pt.iter().sum();
let scale = if total_pt > 0.0 { (content_w as f64 / (total_pt * 12700.0)).min(1.0) } else { 1.0 };
let widths: Vec<i64> = widths_pt.iter().map(|w| (w * scale * 12700.0).round().max(127000.0) as i64).collect();
let table_w: i64 = widths.iter().fold(0i64, |sum, w| sum.saturating_add(*w));
let row_h: i64 = height_emu(24.0);
let table_h: i64 = i64::try_from(t.rows.len()).unwrap_or(i64::MAX).saturating_mul(row_h).min(MAX_ITEM_EMU);
let scale = if total_pt > 0.0 { (content_w / total_pt).min(1.0) } else { 1.0 };
let widths: Vec<f64> = widths_pt.iter().map(|w| (w * scale).max(10.0)).collect();
let table_w: f64 = widths.iter().sum();
let row_h: f64 = 24.0;
let table_h: f64 = (t.rows.len() as f64 * row_h).min(MAX_ITEM_PT);
let mut grid_cols = String::new();
for w in &widths {
grid_cols.push_str(&format!("<a:gridCol w=\"{w}\"/>"));
}
let border = Some(Line {
width: Some(1.0),
fill: Some(Fill::Solid { color: ColorRef { base: ColorBase::Rgb { rgb: Rgba::rgb(0x99, 0x99, 0x99) }, mods: Vec::new() } }),
..Default::default()
});
let borders = [border.clone(), border.clone(), border.clone(), border];
const TC_PR: &str = "<a:tcPr>\
<a:lnL w=\"12700\" cmpd=\"s\"><a:solidFill><a:srgbClr val=\"999999\"/></a:solidFill></a:lnL>\
<a:lnR w=\"12700\" cmpd=\"s\"><a:solidFill><a:srgbClr val=\"999999\"/></a:solidFill></a:lnR>\
<a:lnT w=\"12700\" cmpd=\"s\"><a:solidFill><a:srgbClr val=\"999999\"/></a:solidFill></a:lnT>\
<a:lnB w=\"12700\" cmpd=\"s\"><a:solidFill><a:srgbClr val=\"999999\"/></a:solidFill></a:lnB>\
</a:tcPr>";
let mut rows_xml = String::new();
let mut rows = Vec::with_capacity(t.rows.len());
for row in &t.rows {
rows_xml.push_str(&format!("<a:tr h=\"{row_h}\">"));
let mut cells = Vec::new();
for c in row {
let span = c.span.max(1);
let run = run_drawingml(&c.text, c.size, c.bold, c.italic, c.color);
if span > 1 {
rows_xml.push_str(&format!("<a:tc gridSpan=\"{span}\"><a:txBody><a:bodyPr/><a:lstStyle/><a:p>{run}</a:p></a:txBody>{TC_PR}</a:tc>"));
for _ in 1..span {
rows_xml.push_str(&format!("<a:tc hMerge=\"1\"><a:txBody><a:bodyPr/><a:lstStyle/><a:p/></a:txBody>{TC_PR}</a:tc>"));
}
} else {
rows_xml.push_str(&format!("<a:tc><a:txBody><a:bodyPr/><a:lstStyle/><a:p>{run}</a:p></a:txBody>{TC_PR}</a:tc>"));
let run = dml_run(&c.text, c.size, c.bold, c.italic, c.color);
cells.push(Cell {
text: TextBody { paragraphs: vec![Paragraph { runs: vec![run], ..Default::default() }], ..Default::default() },
grid_span: span as u32,
row_span: 1,
borders: borders.clone(),
..Default::default()
});
for _ in 1..span {
cells.push(Cell { h_merge: true, borders: borders.clone(), ..Default::default() });
}
}
let used: usize = row.iter().map(|c| c.span).sum();
for _ in used..t.cols.len() {
rows_xml.push_str(&format!("<a:tc><a:txBody><a:bodyPr/><a:lstStyle/><a:p/></a:txBody>{TC_PR}</a:tc>"));
cells.push(Cell { borders: borders.clone(), ..Default::default() });
}
rows_xml.push_str("</a:tr>");
rows.push(craft_pptx::table::Row { height: row_h, cells });
}
let frame = format!(
"<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id=\"{shape_id}\" name=\"Table {shape_id}\"/>\
<p:cNvGraphicFramePr><a:graphicFrameLocks noGrp=\"1\"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>\
<p:xfrm><a:off x=\"{x}\" y=\"{y}\"/><a:ext cx=\"{table_w}\" cy=\"{table_h}\"/></p:xfrm>\
<a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/table\">\
<a:tbl><a:tblPr/><a:tblGrid>{grid_cols}</a:tblGrid>{rows_xml}</a:tbl>\
</a:graphicData></a:graphic></p:graphicFrame>"
);
(frame, table_h)
let shape = Shape {
id: ShapeId(shape_id),
name: format!("Table {shape_id}"),
xfrm: Some(Xfrm { x, y, w: table_w, h: table_h, ..Default::default() }),
// PDF cells already carry their formatting; do not invent a themed header or banding.
kind: ShapeKind::Table(DmlTable { cols: widths, rows, style: "none".into(), first_row: false, band_row: false, ..Default::default() }),
..Default::default()
};
(shape, table_h)
}
/// A PowerPoint presentation (.pptx, Office Open XML PresentationML): each page becomes a slide,
@@ -123,18 +132,18 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec<u8> {
let dummy = [Page::default()];
let pages = if pages.is_empty() { &dummy[..] } else { pages };
let (sw, sh) = pages.first().map_or((9144000, 6858000), |p| (emu(p.width, 720.0), emu(p.height, 540.0)));
let mx = (sw / 16).clamp(360000, 914400);
let my = (sh / 16).clamp(360000, 914400);
let content_w = sw - 2 * mx;
let (sw, sh) = pages.first().map_or((720.0, 540.0), |p| (slide_pt(p.width, 720.0), slide_pt(p.height, 540.0)));
let mx = (sw / 16.0).clamp(360000.0 / 12700.0, 72.0);
let my = (sh / 16.0).clamp(360000.0 / 12700.0, 72.0);
let content_w = sw - 2.0 * mx;
let mut global_media: Vec<(String, &Image)> = Vec::new();
// Shared picture bytes remain alive throughout export; only admitted media enter this map.
let mut media_of: HashMap<*const u8, usize> = HashMap::new();
let mut slides: Vec<(String, RelsOut)> = Vec::new(); // (slide_xml, slide_rels)
let mut slides: Vec<Arc<Slide>> = Vec::new();
let body = crate::layout::body_size(pages);
for p in pages {
for (slide_idx, p) in pages.iter().enumerate() {
let (tables, consumed) = crate::tables(&p.blocks, &p.rules);
let title_idx = p
.blocks
@@ -161,52 +170,60 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec<u8> {
let items = crate::reading_order(p, parts);
let mut current_y = my;
let mut shapes = String::new();
let mut shape_id = 2usize;
let mut slide_media_rels: Vec<(String, usize)> = Vec::new();
let mut shapes: Vec<Shape> = Vec::new();
let mut shape_id = 2u32;
if let Some(title_block) = title_idx.and_then(|ti| p.blocks.get(ti)) {
let title_h = height_emu((title_block.size * 1.5).max(36.0));
let title_run = run_drawingml(&title_block.text, title_block.size, title_block.bold, title_block.italic, title_block.color);
shapes.push_str(&format!(
"<p:sp><p:nvSpPr><p:cNvPr id=\"{shape_id}\" name=\"Title {shape_id}\"/><p:cNvSpPr txBox=\"1\"/><p:nvPr/></p:nvSpPr>\
<p:spPr><a:xfrm><a:off x=\"{mx}\" y=\"{current_y}\"/><a:ext cx=\"{content_w}\" cy=\"{title_h}\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom><a:noFill/></p:spPr>\
<p:txBody><a:bodyPr wrap=\"square\" rtlCol=\"0\"><a:spAutoFit/></a:bodyPr><a:lstStyle/><a:p>{title_run}</a:p></p:txBody></p:sp>"
));
let title_h = height_pt((title_block.size * 1.5).max(36.0));
let title_run = dml_run(&title_block.text, title_block.size, title_block.bold, title_block.italic, title_block.color);
shapes.push(Shape {
id: ShapeId(shape_id),
name: format!("Title {shape_id}"),
xfrm: Some(Xfrm { x: mx, y: current_y, w: content_w, h: title_h, ..Default::default() }),
kind: ShapeKind::Shape,
geom: Geom::Preset { name: "rect".into(), adj: Vec::new() },
fill: Some(Fill::None),
text_box: true,
text: Some(TextBody { paragraphs: vec![Paragraph { runs: vec![title_run], ..Default::default() }], ..Default::default() }),
..Default::default()
});
shape_id += 1;
current_y = current_y.saturating_add(title_h).saturating_add(height_emu(18.0));
current_y = (current_y + title_h + 18.0).min(MAX_ITEM_PT);
}
let mut i = 0;
while let Some(item) = items.get(i) {
match item {
SlideBodyItem::Para(_) => {
let mut paras_xml = String::new();
let mut paragraphs = Vec::new();
let mut est_h_pt = 0.0;
while let Some(SlideBodyItem::Para(runs)) = items.get(i) {
paras_xml.push_str("<a:p>");
for r in runs {
paras_xml.push_str(&run_drawingml(&r.text, r.block.size, r.block.bold, r.block.italic, r.block.color));
}
paras_xml.push_str("</a:p>");
let dml_runs = runs.iter().map(|r| dml_run(&r.text, r.block.size, r.block.bold, r.block.italic, r.block.color)).collect();
paragraphs.push(Paragraph { runs: dml_runs, ..Default::default() });
let len = runs.iter().map(|r| r.text.len()).fold(0usize, usize::saturating_add);
let size = runs.iter().map(|r| r.block.size).fold(10.0, f64::max);
let lines = (len as f64 / 60.0).ceil().max(1.0);
est_h_pt += (size * 1.3) * lines + 6.0;
i += 1;
}
let box_h = height_emu(est_h_pt);
shapes.push_str(&format!(
"<p:sp><p:nvSpPr><p:cNvPr id=\"{shape_id}\" name=\"TextBox {shape_id}\"/><p:cNvSpPr txBox=\"1\"/><p:nvPr/></p:nvSpPr>\
<p:spPr><a:xfrm><a:off x=\"{mx}\" y=\"{current_y}\"/><a:ext cx=\"{content_w}\" cy=\"{box_h}\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom><a:noFill/></p:spPr>\
<p:txBody><a:bodyPr wrap=\"square\" rtlCol=\"0\"><a:spAutoFit/></a:bodyPr><a:lstStyle/>{paras_xml}</p:txBody></p:sp>"
));
let box_h = height_pt(est_h_pt);
shapes.push(Shape {
id: ShapeId(shape_id),
name: format!("TextBox {shape_id}"),
xfrm: Some(Xfrm { x: mx, y: current_y, w: content_w, h: box_h, ..Default::default() }),
kind: ShapeKind::Shape,
geom: Geom::Preset { name: "rect".into(), adj: Vec::new() },
fill: Some(Fill::None),
text_box: true,
text: Some(TextBody { paragraphs, ..Default::default() }),
..Default::default()
});
shape_id += 1;
current_y = current_y.saturating_add(box_h).saturating_add(height_emu(12.0));
current_y = (current_y + box_h + 12.0).min(MAX_ITEM_PT);
}
SlideBodyItem::Img(im) => {
let global_img_idx = match media_of.get(&im.bytes.as_ptr()) {
Some(&i) => i,
Some(&idx) => idx,
None if room_for(&global_media, im) => {
let n = global_media.len() + 1;
global_media.push((format!("image{n}.{}", im.ext), *im));
@@ -218,173 +235,55 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec<u8> {
continue;
}
};
let r_id = format!("rIdImg{}", slide_media_rels.len() + 1);
slide_media_rels.push((r_id.clone(), global_img_idx));
let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0));
let max_w = content_w as f64 / 12700.0;
let k = (max_w / w).min(1.0);
let cx = height_emu(w * k).min(content_w);
let cy = height_emu(h * k);
let x = mx + (content_w - cx) / 2;
let k = (content_w / w).min(1.0);
let cx = height_pt(w * k).min(content_w);
let cy = height_pt(h * k);
let x = mx + (content_w - cx) / 2.0;
let y = current_y;
shapes.push_str(&format!(
"<p:pic><p:nvPicPr><p:cNvPr id=\"{shape_id}\" name=\"Picture {shape_id}\"/><p:cNvPicPr><a:picLocks noChangeAspect=\"1\"/></p:cNvPicPr><p:nvPr/></p:nvPicPr>\
<p:blipFill><a:blip r:embed=\"{r_id}\"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>\
<p:spPr><a:xfrm><a:off x=\"{x}\" y=\"{y}\"/><a:ext cx=\"{cx}\" cy=\"{cy}\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></p:spPr></p:pic>"
));
shapes.push(Shape {
id: ShapeId(shape_id),
name: format!("Picture {shape_id}"),
xfrm: Some(Xfrm { x, y, w: cx, h: cy, ..Default::default() }),
kind: ShapeKind::Picture { fill: PictureFill { media: MediaId(global_img_idx as u32), ..Default::default() } },
geom: Geom::Preset { name: "rect".into(), adj: Vec::new() },
..Default::default()
});
shape_id += 1;
current_y = current_y.saturating_add(cy).saturating_add(height_emu(12.0));
current_y = (current_y + cy + 12.0).min(MAX_ITEM_PT);
i += 1;
}
SlideBodyItem::Table(t) => {
let (table_xml, table_h) = pptx_table(shape_id, t, mx, current_y, content_w);
shapes.push_str(&table_xml);
let (table_shape, table_h) = pptx_table(shape_id, t, mx, current_y, content_w);
shapes.push(table_shape);
shape_id += 1;
current_y = current_y.saturating_add(table_h).saturating_add(height_emu(12.0));
current_y = (current_y + table_h + 12.0).min(MAX_ITEM_PT);
i += 1;
}
}
}
let slide_xml = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
<p:sld xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" \
xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"><p:cSld><p:spTree>\
<p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"\"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>\
<p:grpSpPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/><a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"0\" cy=\"0\"/></a:xfrm></p:grpSpPr>\
{shapes}</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>"
);
let mut slide_rels = RelsOut::default();
slide_rels.items.push(RelOut {
id: "rIdLayout".into(),
ty: format!("{RT_BASE}slideLayout"),
target: "../slideLayouts/slideLayout1.xml".into(),
external: false,
});
for (r_id, global_idx) in &slide_media_rels {
if let Some((name, _)) = global_media.get(*global_idx - 1) {
slide_rels.items.push(RelOut {
id: r_id.clone(),
ty: format!("{RT_BASE}image"),
target: format!("../media/{name}"),
external: false,
});
}
}
slides.push((slide_xml, slide_rels));
slides.push(Arc::new(Slide { id: SlideId(256 + slide_idx as u32), shapes, ..Default::default() }));
}
let mut pkg = PackageOut::default();
let mut root_rels = RelsOut::default();
root_rels.add("officeDocument", "ppt/presentation.xml", false);
root_rels.add("metadata/core-properties", "docProps/core.xml", false);
pkg.rels("", &root_rels);
let media: Vec<MediaItem> = global_media
.into_iter()
.enumerate()
.map(|(idx, (name, im))| MediaItem {
id: MediaId((idx + 1) as u32),
name,
content_type: image_mime(im.ext).to_string(),
data: Arc::new(im.bytes.to_vec()),
link: None,
})
.collect();
let mut sld_id_lst = String::new();
let mut pres_rels = RelsOut::default();
pres_rels.items.push(RelOut {
id: "rIdMaster1".into(),
ty: format!("{RT_BASE}slideMaster"),
target: "slideMasters/slideMaster1.xml".into(),
external: false,
});
for i in 1..=slides.len() {
let sld_id = 255 + i;
sld_id_lst.push_str(&format!("<p:sldId id=\"{sld_id}\" r:id=\"rIdSld{i}\"/>"));
pres_rels.items.push(RelOut {
id: format!("rIdSld{i}"),
ty: format!("{RT_BASE}slide"),
target: format!("slides/slide{i}.xml"),
external: false,
});
}
pkg.rels("ppt/presentation.xml", &pres_rels);
let mut pres = Presentation { slide_size: Size::new(sw, sh), slides, media, ..Default::default() };
pres.props.title = title.to_string();
let pres = format!(
"{DECL_STANDALONE}\
<p:presentation xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" \
xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"><p:sldMasterIdLst><p:sldMasterId id=\"2147483648\" r:id=\"rIdMaster1\"/></p:sldMasterIdLst>\
<p:sldIdLst>{sld_id_lst}</p:sldIdLst><p:sldSz cx=\"{sw}\" cy=\"{sh}\"/><p:notesSz cx=\"6858000\" cy=\"9144000\"/></p:presentation>"
);
let slide_master = format!(
"{DECL_STANDALONE}\
<p:sldMaster xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" \
xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"\"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>\
<p:grpSpPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/><a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"0\" cy=\"0\"/></a:xfrm></p:grpSpPr></p:spTree></p:cSld>\
<p:clrMap bg1=\"lt1\" tx1=\"dk1\" bg2=\"lt2\" tx2=\"dk2\" accent1=\"accent1\" accent2=\"accent2\" accent3=\"accent3\" accent4=\"accent4\" accent5=\"accent5\" accent6=\"accent6\" hlink=\"hlink\" folHlink=\"folHlink\"/>\
<p:sldLayoutIdLst><p:sldLayoutId id=\"2147483649\" r:id=\"rIdLayout1\"/></p:sldLayoutIdLst></p:sldMaster>"
);
let mut slide_master_rels = RelsOut::default();
slide_master_rels.items.push(RelOut {
id: "rIdLayout1".into(),
ty: format!("{RT_BASE}slideLayout"),
target: "../slideLayouts/slideLayout1.xml".into(),
external: false,
});
slide_master_rels.items.push(RelOut {
id: "rIdTheme1".into(),
ty: format!("{RT_BASE}theme"),
target: "../theme/theme1.xml".into(),
external: false,
});
pkg.rels("ppt/slideMasters/slideMaster1.xml", &slide_master_rels);
let slide_layout = format!(
"{DECL_STANDALONE}\
<p:sldLayout xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" \
xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" type=\"blank\"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"\"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>\
<p:grpSpPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/><a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"0\" cy=\"0\"/></a:xfrm></p:grpSpPr></p:spTree></p:cSld></p:sldLayout>"
);
let mut slide_layout_rels = RelsOut::default();
slide_layout_rels.add("slideMaster", "../slideMasters/slideMaster1.xml", false);
pkg.rels("ppt/slideLayouts/slideLayout1.xml", &slide_layout_rels);
let theme = format!(
"{DECL_STANDALONE}\
<a:theme xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" name=\"Office Theme\"><a:themeElements>\
<a:clrScheme name=\"Office\"><a:dk1><a:sysClr val=\"windowText\" lastClr=\"000000\"/></a:dk1><a:lt1><a:sysClr val=\"window\" lastClr=\"FFFFFF\"/></a:lt1>\
<a:dk2><a:srgbClr val=\"1F497D\"/></a:dk2><a:lt2><a:srgbClr val=\"EEECE1\"/></a:lt2><a:accent1><a:srgbClr val=\"4F81BD\"/></a:accent1>\
<a:accent2><a:srgbClr val=\"C0504D\"/></a:accent2><a:accent3><a:srgbClr val=\"9BBB59\"/></a:accent3><a:accent4><a:srgbClr val=\"8064A2\"/></a:accent4>\
<a:accent5><a:srgbClr val=\"4BACC6\"/></a:accent5><a:accent6><a:srgbClr val=\"F79646\"/></a:accent6><a:hlink><a:srgbClr val=\"0000FF\"/></a:hlink>\
<a:folHlink><a:srgbClr val=\"800080\"/></a:folHlink></a:clrScheme>\
<a:fontScheme name=\"Office\"><a:majorFont><a:latin typeface=\"Calibri\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:majorFont><a:minorFont><a:latin typeface=\"Calibri\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:minorFont></a:fontScheme>\
<a:fmtScheme name=\"Office\"><a:fillStyleLst><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:fillStyleLst>\
<a:lnStyleLst><a:ln w=\"9525\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln><a:ln w=\"25400\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln><a:ln w=\"38100\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln></a:lnStyleLst>\
<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>\
<a:bgFillStyleLst><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:bgFillStyleLst></a:fmtScheme>\
</a:themeElements></a:theme>"
);
pkg.xml_part("docProps/core.xml", "application/vnd.openxmlformats-package.core-properties+xml", core_properties_xml(title));
pkg.xml_part("ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", pres.into_bytes());
pkg.xml_part(
"ppt/slideMasters/slideMaster1.xml",
"application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml",
slide_master.into_bytes(),
);
pkg.xml_part(
"ppt/slideLayouts/slideLayout1.xml",
"application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml",
slide_layout.into_bytes(),
);
pkg.xml_part("ppt/theme/theme1.xml", "application/vnd.openxmlformats-officedocument.theme+xml", theme.into_bytes());
for (i, (s_xml, s_rels)) in slides.iter().enumerate() {
let num = i + 1;
let path = format!("ppt/slides/slide{num}.xml");
pkg.xml_part(&path, "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", s_xml.as_bytes().to_vec());
pkg.rels(&path, s_rels);
}
for (name, im) in &global_media {
pkg.binary(&format!("ppt/media/{name}"), image_mime(im.ext), im.bytes.to_vec());
}
pkg.finish().unwrap_or_default()
craft_pptx::export(&pres, &Plain).unwrap_or_default()
}
#[cfg(test)]
+46 -6
View File
@@ -2,6 +2,25 @@ use super::*;
use crate::Block;
use crate::tests::part;
fn xml(text: &str) -> craft_xml::El {
craft_xml::parse(text.as_bytes()).expect("valid package XML")
}
fn relationship_target<'a>(rels: &'a craft_xml::El, id: &str) -> &'a str {
rels.children("Relationship").find(|r| r.attr("Id") == Some(id)).and_then(|r| r.attr("Target")).expect("referenced relationship")
}
fn assert_slide_targets(bytes: &[u8], targets: &[&str]) {
let pres = xml(&part(bytes, "ppt/presentation.xml"));
let rels = xml(&part(bytes, "ppt/_rels/presentation.xml.rels"));
let ids: Vec<_> = pres.find("p:sldIdLst").expect("slide list").children("p:sldId").collect();
assert_eq!(ids.len(), targets.len());
for (slide, target) in ids.iter().zip(targets) {
assert!(slide.attr_u32("id").expect("numeric slide id") >= 256);
assert_eq!(relationship_target(&rels, slide.attr("r:id").expect("slide relationship")), *target);
}
}
fn sample_page() -> Page {
Page {
width: 720.0,
@@ -85,7 +104,10 @@ pub fn pptx_slide_has_title_body_and_images_in_order() {
assert!(slide_xml.contains("name=\"TextBox 3\""));
assert!(slide_xml.contains("Revenue grew 25%"));
assert!(slide_xml.contains("<p:pic>"));
assert!(slide_xml.contains("<a:blip r:embed=\"rIdImg1\"/>"));
let slide = xml(&slide_xml);
let rels = xml(&part(&bytes, "ppt/slides/_rels/slide1.xml.rels"));
let id = slide.find("a:blip").and_then(|n| n.attr("r:embed")).expect("embedded picture");
assert_eq!(relationship_target(&rels, id), "../media/image1.png");
assert!(!slide_xml.contains("<p:ph"), "pure text boxes avoid placeholder inheritance repair warnings: {slide_xml}");
let rels_xml = part(&bytes, "ppt/slides/_rels/slide1.xml.rels");
@@ -250,7 +272,7 @@ fn pptx_package_parts_are_complete_and_consistent() {
let inner = theme.split(&format!("<a:{font}>")).nth(1).and_then(|r| r.split(&format!("</a:{font}>")).next()).unwrap_or_default();
assert!(inner.contains("<a:latin ") && inner.contains("<a:ea ") && inner.contains("<a:cs "), "{font}: {inner}");
}
assert!(text("ppt/presentation.xml").contains("r:id=\"rIdSld2\""));
assert_slide_targets(&bytes, &["slides/slide1.xml", "slides/slide2.xml"]);
}
#[test]
@@ -292,8 +314,7 @@ fn hostile_sizes_do_not_overflow_the_slide_position() {
pub fn pptx_empty_pages_produce_valid_slide() {
let bytes = pptx(&[], "Blank");
assert!(bytes.starts_with(b"PK"));
let pres_xml = part(&bytes, "ppt/presentation.xml");
assert!(pres_xml.contains("<p:sldId id=\"256\" r:id=\"rIdSld1\"/>"));
assert_slide_targets(&bytes, &["slides/slide1.xml"]);
let slide_xml = part(&bytes, "ppt/slides/slide1.xml");
assert!(slide_xml.contains("<p:spTree>"));
}
@@ -372,7 +393,20 @@ fn pptx_table_cell_with_largest_font_stays_in_table_and_not_in_title() {
// The table must contain both the cell and explicit borders
assert!(slide_xml.contains("<a:tbl>"));
assert!(slide_xml.contains("+99%"));
assert!(slide_xml.contains("<a:tcPr><a:lnL w=\"12700\" cmpd=\"s\">"));
let slide = xml(&slide_xml);
let table = slide.find("a:tbl").expect("table");
let props = table.child("a:tblPr").expect("table properties");
assert_eq!(props.child_text("a:tableStyleId").as_deref(), Some("{2D5ABB26-0587-4C30-8999-92F81FD0307C}"));
assert!(!props.flag("firstRow", false) && !props.flag("bandRow", false), "no invented header/banding");
let cells: Vec<_> = table.descendants().filter(|n| n.is("a:tcPr")).collect();
assert_eq!(cells.len(), 6);
for cell in cells {
for edge in ["a:lnL", "a:lnR", "a:lnT", "a:lnB"] {
let line = cell.child(edge).expect("explicit border");
assert_eq!(line.attr_u32("w"), Some(12700));
assert_eq!(line.find("a:srgbClr").and_then(|n| n.attr("val")), Some("999999"));
}
}
}
#[test]
@@ -413,7 +447,13 @@ fn pptx_packages_a_repeated_picture_once() {
p.images = std::iter::repeat_n(one, 2 * crate::as_docx::MAX_MEDIA).collect();
let bytes = pptx(&[p], "Deck");
let rels = part(&bytes, "ppt/slides/_rels/slide1.xml.rels");
assert_eq!(rels.matches("relationships/image\"").count(), 2 * crate::as_docx::MAX_MEDIA, "every place refers to the picture");
let relationships = xml(&rels);
let slide = xml(&part(&bytes, "ppt/slides/slide1.xml"));
let blips: Vec<_> = slide.descendants().filter(|n| n.is("a:blip")).collect();
assert_eq!(blips.len(), 2 * crate::as_docx::MAX_MEDIA, "every placement has an image reference");
for blip in blips {
assert_eq!(relationship_target(&relationships, blip.attr("r:embed").expect("picture relationship")), "../media/image1.png");
}
assert!(rels.contains("Target=\"../media/image1.png\"") && !rels.contains("image2."), "one media part");
assert_eq!(part(&bytes, "ppt/slides/slide1.xml").matches("<p:pic>").count(), 2 * crate::as_docx::MAX_MEDIA);
assert_eq!(bytes.windows(20).filter(|w| *w == b"ppt/media/image1.png").count(), 2, "its local header and central directory entry");
+14 -4
View File
@@ -924,10 +924,20 @@ fn an_italic_word_stays_in_its_sentence() {
);
// The longest line is the slide's title; the sentence is one paragraph of the body.
let pxml = part(&pptx(std::slice::from_ref(&p), "Opinion"), "ppt/slides/slide1.xml");
assert!(
pxml.contains("<a:p><a:r><a:rPr sz=\"1200\"></a:rPr><a:t>Before </a:t></a:r><a:r><a:rPr sz=\"1200\" i=\"1\"></a:rPr><a:t>Chevron </a:t></a:r><a:r><a:rPr sz=\"1200\"></a:rPr><a:t>after.</a:t></a:r></a:p>"),
"{pxml}"
);
let slide = craft_xml::parse(pxml.as_bytes()).expect("slide XML");
let paragraph = slide
.descendants()
.filter(|n| n.is("a:p"))
.find(|p| p.children("a:r").any(|r| r.child_text("a:t").as_deref() == Some("Before ")))
.expect("body paragraph");
let actual: Vec<_> = paragraph
.children("a:r")
.map(|r| {
let props = r.child("a:rPr").expect("run properties");
(r.child_text("a:t").expect("run text").into_owned(), props.attr_u32("sz"), props.flag("i", false))
})
.collect();
assert_eq!(actual, vec![("Before ".into(), Some(1200), false), ("Chevron ".into(), Some(1200), true), ("after.".into(), Some(1200), false)]);
}
/// #4158: the runs keep their order along the line whatever order the blocks come in, and the
+21 -4
View File
@@ -2072,11 +2072,28 @@ fn buttons_take_presses_as_the_scripts_show_them() {
app
});
h.run_steps(2);
press_field(&mut h, "shown");
press_field(&mut h, "gone");
let id = h.state().views[0].id;
let pressed = h.state_mut().session.run_javascript(id, "pressed", None).expect("runs").result;
assert_eq!(pressed.as_deref(), Some("shown"));
// Native button actions run on a worker. Frames alone do not ensure it has finished;
// wait for the UI to accept its completion before inspecting the retained realm.
let pressed = |h: &mut Harness<'static, PdfCraftApp>| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(12);
loop {
h.run_steps(1);
let out = h.state_mut().session.run_javascript(id, "pressed", None).expect("runs");
if out.error.as_deref() != Some("another script is active in this document") {
assert_eq!(out.error, None, "reading the completed button's result");
return out.result;
}
assert!(out.execution_refused && out.realm_untouched, "a busy probe must not change the realm");
assert!(std::time::Instant::now() < deadline, "button script did not complete");
std::thread::sleep(std::time::Duration::from_millis(5));
}
};
press_field(&mut h, "shown");
assert_eq!(pressed(&mut h).as_deref(), Some("shown"));
// Do not let a still-busy first click reject the second and conceal a hit-test bug.
press_field(&mut h, "gone");
assert_eq!(pressed(&mut h).as_deref(), Some("shown"));
}
/// A radio group's read-only button can't be chosen by a click, while the group's other button
-7
View File
@@ -1,7 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "hayro-postscript"
version = "0.1.0"
-70
View File
@@ -1,70 +0,0 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
name = "hayro-postscript"
version = "0.1.0"
authors = ["Laurenz Stampfl <laurenz.stampfl@gmail.com>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "A lightweight PostScript scanner."
readme = "README.md"
license = "Apache-2.0 OR MIT"
repository = "https://github.com/LaurenzV/hayro"
resolver = "2"
[lib]
name = "hayro_postscript"
path = "src/lib.rs"
[[example]]
name = "tokenize"
path = "examples/tokenize.rs"
[lints.clippy]
collection_is_never_read = "warn"
dbg_macro = "warn"
debug_assert_with_mut_call = "warn"
default_trait_access = "warn"
doc_markdown = "warn"
fn_to_numeric_cast_any = "warn"
infinite_loop = "warn"
large_stack_arrays = "warn"
mismatching_type_param_order = "warn"
negative_feature_names = "warn"
redundant_feature_names = "warn"
same_functions_in_if_condition = "warn"
semicolon_if_nothing_returned = "warn"
todo = "warn"
too_many_arguments = "allow"
unseparated_literal_suffix = "warn"
use_self = "warn"
wildcard_dependencies = "warn"
[lints.rust]
elided_lifetimes_in_paths = "warn"
keyword_idents_2024 = "forbid"
missing_docs = "warn"
non_ascii_idents = "forbid"
non_local_definitions = "forbid"
trivial_numeric_casts = "warn"
unnameable_types = "warn"
unreachable_pub = "warn"
unsafe_op_in_unsafe_fn = "forbid"
unused_import_braces = "warn"
unused_lifetimes = "warn"
unused_macro_rules = "warn"
unused_qualifications = "warn"
-11
View File
@@ -1,11 +0,0 @@
[package]
name = "hayro-postscript"
version = "0.1.0"
description = "A lightweight PostScript scanner."
authors = { workspace = true }
edition = { workspace = true }
repository = { workspace = true }
license = { workspace = true }
[lints]
workspace = true
-177
View File
@@ -1,177 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-7
View File
@@ -1,7 +0,0 @@
Copyright (c) The Hayro Authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-30
View File
@@ -1,30 +0,0 @@
# hayro-postscript
[![Crates.io](https://img.shields.io/crates/v/hayro-postscript.svg)](https://crates.io/crates/hayro-postscript)
[![Documentation](https://docs.rs/hayro-postscript/badge.svg)](https://docs.rs/hayro-postscript)
<!-- cargo-rdme start -->
A lightweight PostScript scanner.
This crate provides a scanner for tokenizing PostScript programs into typed objects.
It currently only implements a very small subset of the PostScript language,
with the main goal of being enough to parse CMAP files, but the scope _might_
be expanded upon in the future.
The supported types include integers and real numbers, name objects, strings and arrays.
Unsupported is anything else, including dictionaries, procedures, etc. An error
will be returned in case any of these is encountered.
### Safety
This crate forbids unsafe code via a crate-level attribute.
<!-- cargo-rdme end -->
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
at your option.
-74
View File
@@ -1,74 +0,0 @@
//! A small example that shows how to tokenize a PostScript program.
#![allow(missing_docs)]
use hayro_postscript::{Number, Object, Scanner};
use std::env;
use std::fs;
use std::process;
fn main() {
let path = match env::args().nth(1) {
Some(p) => p,
None => {
eprintln!("Usage: tokenize <file>");
process::exit(1);
}
};
let data = match fs::read(&path) {
Ok(d) => d,
Err(e) => {
eprintln!("Error reading {path}: {e}");
process::exit(1);
}
};
let mut scanner = Scanner::new(&data);
while !scanner.at_end() {
match scanner.parse_object() {
Ok(object) => {
print_object(&object);
println!();
}
Err(e) => eprintln!("Error: {e}"),
}
}
}
fn print_object(object: &Object<'_>) {
match object {
Object::Number(Number::Integer(n)) => print!("Integer({n})"),
Object::Number(Number::Real(n)) => print!("Real({n})"),
Object::Name(name) => {
let kind = if name.is_literal() {
"literal"
} else {
"executable"
};
let text = name.as_str().unwrap_or("<non-ascii name>");
print!("Name({text}, {kind})");
}
Object::String(s) => {
let decoded = s.decode().unwrap_or_else(|_| Vec::new());
print!("String({})", String::from_utf8_lossy(&decoded));
}
Object::Array(arr) => {
print!("[");
let mut inner = arr.objects();
let mut first = true;
while !inner.at_end() {
if !first {
print!(" ");
}
first = false;
match inner.parse_object() {
Ok(obj) => print_object(&obj),
Err(e) => print!("Error({e})"),
}
}
print!("]");
}
}
}
-127
View File
@@ -1,127 +0,0 @@
use crate::error::{Error, Result};
use crate::object;
use crate::reader::Reader;
use crate::string;
/// A PostScript array object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Array<'a> {
data: &'a [u8],
}
impl<'a> Array<'a> {
pub(crate) fn new(data: &'a [u8]) -> Self {
Self { data }
}
/// Return a [`Scanner`](crate::Scanner) that iterates over the objects inside
/// this array.
pub fn objects(&self) -> crate::Scanner<'a> {
crate::Scanner::new(self.data)
}
}
pub(crate) fn parse<'a>(r: &mut Reader<'a>) -> Result<&'a [u8]> {
r.forward_tag(b"[").ok_or(Error::SyntaxError)?;
let start = r.offset();
skip_array(r)?;
let end = r.offset() - 1;
r.range(start..end).ok_or(Error::SyntaxError)
}
fn skip_array(r: &mut Reader<'_>) -> Result<()> {
let mut depth = 1_u32;
while depth > 0 {
match r.peek_byte().ok_or(Error::SyntaxError)? {
b'[' => {
r.forward();
depth += 1;
}
b']' => {
r.forward();
depth -= 1;
}
b'(' => {
let _ = string::parse_literal(r).ok_or(Error::SyntaxError)?;
}
b'<' => {
if r.peek_bytes(2) == Some(b"<~") {
let _ = string::parse_ascii85(r).ok_or(Error::SyntaxError)?;
} else if r.peek_bytes(2) == Some(b"<<") {
r.forward();
r.forward();
} else {
let _ = string::parse_hex(r).ok_or(Error::SyntaxError)?;
}
}
b'%' => object::skip_whitespace_and_comments(r),
_ => {
r.forward();
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_array(input: &[u8]) -> Result<&[u8]> {
let mut r = Reader::new(input);
parse(&mut r)
}
#[test]
fn empty() {
assert_eq!(parse_array(b"[]").unwrap(), b"");
}
#[test]
fn simple() {
assert_eq!(parse_array(b"[1 2 3]").unwrap(), b"1 2 3");
}
#[test]
fn nested() {
assert_eq!(parse_array(b"[1 [2 3] 4]").unwrap(), b"1 [2 3] 4");
}
#[test]
fn with_string() {
// The ']' inside the string should not close the array.
assert_eq!(parse_array(b"[1 (str]) 2]").unwrap(), b"1 (str]) 2");
}
#[test]
fn with_hex_string() {
assert_eq!(parse_array(b"[<48> /name]").unwrap(), b"<48> /name");
}
#[test]
fn with_ascii85_string() {
assert_eq!(parse_array(b"[<~87cURDZ~> 1]").unwrap(), b"<~87cURDZ~> 1");
}
#[test]
fn with_comment() {
assert_eq!(
parse_array(b"[1 % comment with ]\n2]").unwrap(),
b"1 % comment with ]\n2"
);
}
#[test]
fn unterminated() {
assert_eq!(parse_array(b"[1 2"), Err(Error::SyntaxError));
}
#[test]
fn not_an_array() {
assert_eq!(parse_array(b"1 2]"), Err(Error::SyntaxError));
}
}
-30
View File
@@ -1,30 +0,0 @@
//! Error types for the PostScript scanner.
use core::fmt;
/// A specialized [`Result`] type for PostScript scanner operations.
pub type Result<T> = core::result::Result<T, Error>;
/// An error encountered while scanning a PostScript token stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
/// A syntax error in the input.
SyntaxError,
/// A numeric value exceeded implementation limits.
LimitCheck,
/// An unsupported PostScript type was encountered (like dictionaries or
/// procedures, which will be added in the future).
UnsupportedType,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SyntaxError => f.write_str("syntaxerror"),
Self::LimitCheck => f.write_str("limitcheck"),
Self::UnsupportedType => f.write_str("unsupported type"),
}
}
}
impl core::error::Error for Error {}
-275
View File
@@ -1,275 +0,0 @@
/*!
A lightweight PostScript scanner.
This crate provides a scanner for tokenizing PostScript programs into typed objects.
It currently only implements a very small subset of the PostScript language,
with the main goal of being enough to parse CMAP files, but the scope _might_
be expanded upon in the future.
The supported types include integers and real numbers, name objects, strings and arrays.
Unsupported is anything else, including dictionaries, procedures, etc. An error
will be returned in case any of these is encountered.
## Safety
This crate forbids unsafe code via a crate-level attribute.
*/
#![no_std]
#![forbid(unsafe_code)]
#![allow(missing_docs)]
extern crate alloc;
mod array;
mod error;
mod name;
mod number;
mod object;
mod reader;
mod string;
pub use array::Array;
pub use error::{Error, Result};
pub use name::Name;
pub use number::Number;
pub use object::Object;
pub use string::String;
use reader::Reader;
/// A PostScript scanner that parses [`Object`]s from a byte stream.
pub struct Scanner<'a> {
reader: Reader<'a>,
}
impl<'a> Scanner<'a> {
/// Create a new scanner over the given bytes of a PostScript program.
pub fn new(data: &'a [u8]) -> Self {
Self {
reader: Reader::new(data),
}
}
/// Returns `true` if there are no more objects to parse.
pub fn at_end(&mut self) -> bool {
object::at_end(&mut self.reader)
}
/// Parse the next object.
pub fn parse_object(&mut self) -> Result<Object<'a>> {
object::read(&mut self.reader)
}
/// PdfCraft patch (2): parse the next object; when it can't be read, read on from where
/// the failed read stopped, or, when it read nothing, from one byte past where its token
/// starts, so a caller can read on past a token it can't parse (a stray `>` in a name, a
/// CMap name with spaces in it) instead of stopping there. Every failure moves forward, one
/// failure per unreadable token, and what a failed read went through (an unclosed string,
/// to the end of the data) is not read again, so a loop over this ends and reads the data
/// about once. A number that can't be read is skipped to the end of its token: its tail
/// (`beginbfchar` in `1beginbfchar`) is not read as a token of its own.
pub fn parse_object_or_skip(&mut self) -> Result<Object<'a>> {
// The whitespace and comments before the token are not the token: skipped first, they
// don't count as progress, so a token after a space fails once, not twice.
object::skip_whitespace_and_comments(&mut self.reader);
let start = self.reader.offset();
// `object::read` reads a token starting with one of these bytes as a number.
let number = matches!(
self.reader.peek_byte(),
Some(b'.' | b'+' | b'-' | b'0'..=b'9')
);
let read = object::read(&mut self.reader);
// A number read stops at the first byte that can't be part of a number, which may be
// inside the token; the rest of the token goes with it.
if read.is_err() && number {
self.reader.forward_while(reader::is_regular);
}
if read.is_err() && self.reader.offset() <= start {
self.reader
.jump(start.saturating_add(1).min(self.reader.data.len()));
}
read
}
/// Parse the next object as a [`Number`].
pub fn parse_number(&mut self) -> Result<Number> {
match self.parse_object()? {
Object::Number(n) => Ok(n),
_ => Err(Error::SyntaxError),
}
}
/// Parse the next object as a [`Name`].
pub fn parse_name(&mut self) -> Result<Name<'a>> {
match self.parse_object()? {
Object::Name(n) => Ok(n),
_ => Err(Error::SyntaxError),
}
}
/// Parse the next object as a [`String`].
pub fn parse_string(&mut self) -> Result<String<'a>> {
match self.parse_object()? {
Object::String(s) => Ok(s),
_ => Err(Error::SyntaxError),
}
}
/// Parse the next object as an [`Array`].
pub fn parse_array(&mut self) -> Result<Array<'a>> {
match self.parse_object()? {
Object::Array(a) => Ok(a),
_ => Err(Error::SyntaxError),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cmap_snippet() {
let input = br#"/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CMapName /Test-H def
1 begincodespacerange
<00> <FF>
endcodespacerange
2 beginbfchar
<03> <0041>
<04> <0042>
endbfchar
endcmap"#;
let mut s = Scanner::new(input);
assert_eq!(s.parse_name().unwrap(), Name::new(b"CIDInit", true));
assert_eq!(s.parse_name().unwrap(), Name::new(b"ProcSet", true));
assert_eq!(s.parse_name().unwrap(), Name::new(b"findresource", false));
assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false));
assert_eq!(s.parse_number().unwrap(), Number::Integer(12));
assert_eq!(s.parse_name().unwrap(), Name::new(b"dict", false));
assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false));
assert_eq!(s.parse_name().unwrap(), Name::new(b"begincmap", false));
assert_eq!(s.parse_name().unwrap(), Name::new(b"CMapName", true));
assert_eq!(s.parse_name().unwrap(), Name::new(b"Test-H", true));
assert_eq!(s.parse_name().unwrap(), Name::new(b"def", false));
assert_eq!(s.parse_number().unwrap(), Number::Integer(1));
assert_eq!(
s.parse_name().unwrap(),
Name::new(b"begincodespacerange", false)
);
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"00"));
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"FF"));
assert_eq!(
s.parse_name().unwrap(),
Name::new(b"endcodespacerange", false)
);
assert_eq!(s.parse_number().unwrap(), Number::Integer(2));
assert_eq!(s.parse_name().unwrap(), Name::new(b"beginbfchar", false));
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"03"));
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0041"));
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"04"));
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0042"));
assert_eq!(s.parse_name().unwrap(), Name::new(b"endbfchar", false));
assert_eq!(s.parse_name().unwrap(), Name::new(b"endcmap", false));
assert!(s.at_end());
}
#[test]
fn array_round_trip() {
let input = b"[123 /abc (xyz)]";
let mut scanner = Scanner::new(input);
let arr = scanner.parse_array().unwrap();
assert!(scanner.at_end());
let mut inner = arr.objects();
assert_eq!(inner.parse_number().unwrap(), Number::Integer(123));
assert_eq!(inner.parse_name().unwrap(), Name::new(b"abc", true));
assert_eq!(inner.parse_string().unwrap(), String::from_literal(b"xyz"));
assert!(inner.at_end());
}
#[test]
fn comments_skipped() {
let input = b"% comment\n42 % another\n/Name";
let mut scanner = Scanner::new(input);
assert_eq!(scanner.parse_number().unwrap(), Number::Integer(42));
assert_eq!(scanner.parse_name().unwrap(), Name::new(b"Name", true));
assert!(scanner.at_end());
}
#[test]
fn wrong_type_is_error() {
let mut scanner = Scanner::new(b"42 ");
assert!(scanner.parse_name().is_err());
}
/// PdfCraft patch (2) test: a token that can't be read fails once and is stepped over,
/// whether or not whitespace or a comment comes before it, and the objects after it read.
#[test]
fn parse_object_or_skip_steps_over_an_unreadable_token() {
let mut s = Scanner::new(b"/A> /B % note\n > /C");
assert_eq!(
s.parse_object_or_skip(),
Ok(Object::Name(Name::new(b"A", true)))
);
assert!(s.parse_object_or_skip().is_err());
assert_eq!(
s.parse_object_or_skip(),
Ok(Object::Name(Name::new(b"B", true)))
);
assert!(s.parse_object_or_skip().is_err());
assert_eq!(
s.parse_object_or_skip(),
Ok(Object::Name(Name::new(b"C", true)))
);
assert!(s.at_end());
}
/// PdfCraft patch (2) test: a number that can't be read fails once with the rest of its
/// token, which is not read as a name of its own; the tokens after it still read.
#[test]
fn parse_object_or_skip_skips_the_rest_of_an_unreadable_number() {
let mut s = Scanner::new(b"1beginbfchar 2.5.3x 16#zz! -x /C");
for _ in 0..4 {
assert!(s.parse_object_or_skip().is_err());
}
assert_eq!(
s.parse_object_or_skip(),
Ok(Object::Name(Name::new(b"C", true)))
);
assert!(s.at_end());
}
/// PdfCraft patch (2) test: what a failed read went through is not read again. An unclosed
/// string reads to the end of the data, so one failure leaves nothing to read; the nested
/// `(` inside it are not each read to the end once more.
#[test]
fn parse_object_or_skip_does_not_read_a_failed_read_again() {
let mut s = Scanner::new(b"/A (((( x");
assert_eq!(
s.parse_object_or_skip(),
Ok(Object::Name(Name::new(b"A", true)))
);
assert!(s.parse_object_or_skip().is_err());
assert!(s.at_end());
}
/// PdfCraft patch (2) test: at the end of the data a read fails and the scanner stays at
/// the end; it never steps past the data.
#[test]
fn parse_object_or_skip_stays_at_the_end() {
for input in [&b""[..], b" ", b">"] {
let mut s = Scanner::new(input);
for _ in 0..3 {
assert!(s.parse_object_or_skip().is_err());
assert!(s.reader.offset() <= input.len());
}
assert!(s.at_end());
}
}
}
-191
View File
@@ -1,191 +0,0 @@
use alloc::vec::Vec;
use crate::error::{Error, Result};
use crate::reader::{Reader, is_regular};
use crate::string::ascii_hex::decode_hex_digit;
/// A PostScript name object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Name<'a> {
data: &'a [u8],
literal: bool,
}
impl<'a> Name<'a> {
pub(crate) fn new(data: &'a [u8], literal: bool) -> Self {
Self { data, literal }
}
/// Returns `true` if this is a literal name.
pub fn is_literal(&self) -> bool {
self.literal
}
/// Returns the name as a string if it is valid UTF-8, or
/// `None` if it contains non-ASCII bytes.
pub fn as_str(&self) -> Option<&'a str> {
core::str::from_utf8(self.data).ok()
}
/// Decode the name into `out`, replacing any previous contents.
pub fn decode_into(&self, out: &mut Vec<u8>) -> Result<()> {
out.clear();
// Fast path: no escape sequences.
if !self.data.contains(&b'#') {
out.extend_from_slice(self.data);
return Ok(());
}
// Slow path: Process escape sequences.
let mut inner = Reader::new(self.data);
while let Some(b) = inner.read_byte() {
if b == b'#' {
let hex = inner.read_bytes(2).ok_or(Error::SyntaxError)?;
let hi = decode_hex_digit(hex[0]).ok_or(Error::SyntaxError)?;
let lo = decode_hex_digit(hex[1]).ok_or(Error::SyntaxError)?;
out.push(hi << 4 | lo);
} else {
out.push(b);
}
}
Ok(())
}
/// Decode the name.
pub fn decode(&self) -> Result<Vec<u8>> {
let mut out = Vec::new();
self.decode_into(&mut out)?;
Ok(out)
}
}
pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
r.forward_tag(b"/")?;
let start = r.offset();
while r.eat(is_regular).is_some() {}
r.range(start..r.offset())
}
pub(crate) fn parse_executable<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
let start = r.offset();
r.forward_while(is_regular);
if r.offset() == start {
return None;
}
r.range(start..r.offset())
}
#[cfg(test)]
mod tests {
use super::*;
fn read_literal(input: &[u8]) -> Option<Name<'_>> {
let mut r = Reader::new(input);
parse_literal(&mut r).map(|d| Name::new(d, true))
}
fn read_executable(input: &[u8]) -> Option<Name<'_>> {
let mut r = Reader::new(input);
parse_executable(&mut r).map(|d| Name::new(d, false))
}
#[test]
fn literal_simple() {
let n = read_literal(b"/Name1").unwrap();
assert_eq!(n.as_str().unwrap(), "Name1");
assert!(n.is_literal());
}
#[test]
fn literal_empty_name() {
let n = read_literal(b"/").unwrap();
assert_eq!(n.as_str().unwrap(), "");
assert!(n.is_literal());
}
#[test]
fn literal_with_hex_escape() {
let n = read_literal(b"/lime#20Green").unwrap();
assert_eq!(n.as_str().unwrap(), "lime#20Green");
assert_eq!(n.decode().unwrap(), b"lime Green");
}
#[test]
fn literal_multiple_hex_escapes() {
let n = read_literal(b"/paired#28#29parentheses").unwrap();
assert_eq!(n.decode().unwrap(), b"paired()parentheses");
}
#[test]
fn literal_special_chars() {
let n = read_literal(b"/A;Name_With-Various***Characters?").unwrap();
assert_eq!(n.as_str().unwrap(), "A;Name_With-Various***Characters?");
}
#[test]
fn literal_stops_at_delimiter() {
let mut r = Reader::new(b"/Name(rest");
let data = parse_literal(&mut r).unwrap();
assert_eq!(data, b"Name");
assert_eq!(r.peek_byte(), Some(b'('));
}
#[test]
fn literal_stops_at_whitespace() {
let mut r = Reader::new(b"/Name rest");
let data = parse_literal(&mut r).unwrap();
assert_eq!(data, b"Name");
assert_eq!(r.peek_byte(), Some(b' '));
}
#[test]
fn literal_not_a_name() {
assert!(read_literal(b"Name").is_none());
}
#[test]
fn executable_simple() {
let n = read_executable(b"beginbfchar ").unwrap();
assert_eq!(n.as_str().unwrap(), "beginbfchar");
assert!(!n.is_literal());
}
#[test]
fn executable_stops_at_delimiter() {
let mut r = Reader::new(b"def/name");
let data = parse_executable(&mut r).unwrap();
assert_eq!(data, b"def");
assert_eq!(r.peek_byte(), Some(b'/'));
}
#[test]
fn executable_at_eof() {
let n = read_executable(b"endcmap").unwrap();
assert_eq!(n.as_str().unwrap(), "endcmap");
}
#[test]
fn executable_empty() {
assert!(read_executable(b"").is_none());
}
#[test]
fn executable_starts_at_delimiter() {
assert!(read_executable(b"(foo)").is_none());
}
#[test]
fn decode_no_escapes() {
let n = Name::new(b"simple", true);
assert_eq!(n.decode().unwrap(), b"simple");
}
#[test]
fn decode_with_escapes() {
let n = Name::new(b"lime#20Green", true);
assert_eq!(n.decode().unwrap(), b"lime Green");
}
}
-177
View File
@@ -1,177 +0,0 @@
use crate::error::{Error, Result};
use crate::reader::{Reader, is_delimiter, is_whitespace};
/// A PostScript number object (integer or real).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Number {
Integer(i32),
Real(f32),
}
impl Number {
/// Return the value as an `i32`. Reals are truncated.
pub fn as_i32(self) -> i32 {
match self {
Self::Integer(v) => v,
Self::Real(v) => v as i32,
}
}
/// Return the value as an `f32`.
pub fn as_f32(self) -> f32 {
match self {
Self::Integer(v) => v as f32,
Self::Real(v) => v,
}
}
/// Return the value as an `f64`.
pub fn as_f64(self) -> f64 {
match self {
Self::Integer(v) => v as f64,
Self::Real(v) => v as f64,
}
}
}
fn is_terminated(r: &Reader<'_>) -> bool {
match r.peek_byte() {
None => true,
Some(b) => is_whitespace(b) || is_delimiter(b),
}
}
pub(crate) fn read(r: &mut Reader<'_>) -> Result<Number> {
let saved = r.offset();
// Optional sign.
let first = r.peek_byte().ok_or(Error::SyntaxError)?;
let has_sign = first == b'+' || first == b'-';
if has_sign {
r.forward();
}
// Consume leading digits.
let digit_start = r.offset();
r.forward_while(|b| b.is_ascii_digit());
let has_digits = r.offset() > digit_start;
// Check if number is a radix number.
if !has_sign && has_digits && r.peek_byte() == Some(b'#') {
let base_bytes = r.range(digit_start..r.offset()).ok_or(Error::SyntaxError)?;
let base_str = core::str::from_utf8(base_bytes).map_err(|_| Error::SyntaxError)?;
let base = base_str.parse::<u32>().map_err(|_| Error::SyntaxError)?;
if !(2..=36).contains(&base) {
return Err(Error::SyntaxError);
}
// Skip `#`.
r.forward();
let num_start = r.offset();
r.forward_while(|b| b.is_ascii_alphanumeric());
if r.offset() == num_start || !is_terminated(r) {
return Err(Error::SyntaxError);
}
let num_bytes = r.range(num_start..r.offset()).ok_or(Error::SyntaxError)?;
let num_str = core::str::from_utf8(num_bytes).map_err(|_| Error::SyntaxError)?;
let value = i32::from_str_radix(num_str, base).map_err(|_| Error::SyntaxError)?;
return Ok(Number::Integer(value));
}
// Check for real number indicators: `.` or `e`/`E`.
let has_dot = r.peek_byte() == Some(b'.');
if has_dot {
r.forward(); // skip '.'
r.forward_while(|b| b.is_ascii_digit());
}
// At this point we need at least some digits (before or after the dot).
if !has_digits && !has_dot {
return Err(Error::SyntaxError);
}
let has_exponent = matches!(r.peek_byte(), Some(b'e' | b'E'));
if has_exponent {
r.forward();
// Optional exponent sign.
if matches!(r.peek_byte(), Some(b'+' | b'-')) {
r.forward();
}
r.forward_while(|b| b.is_ascii_digit());
}
if !is_terminated(r) {
return Err(Error::SyntaxError);
}
let token = r.range(saved..r.offset()).ok_or(Error::SyntaxError)?;
let str = core::str::from_utf8(token).map_err(|_| Error::SyntaxError)?;
if has_dot || has_exponent {
let value = str.parse::<f32>().map_err(|_| Error::SyntaxError)?;
Ok(Number::Real(value))
} else {
if !has_digits {
return Err(Error::SyntaxError);
}
let value = str.parse::<i32>().map_err(|_| Error::SyntaxError)?;
Ok(Number::Integer(value))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn read_num(input: &[u8]) -> Result<Number> {
let mut r = Reader::new(input);
read(&mut r)
}
#[test]
fn signed_integers() {
assert_eq!(read_num(b"123 ").unwrap(), Number::Integer(123));
assert_eq!(read_num(b"-98 ").unwrap(), Number::Integer(-98));
assert_eq!(read_num(b"43445 ").unwrap(), Number::Integer(43445));
assert_eq!(read_num(b"0 ").unwrap(), Number::Integer(0));
assert_eq!(read_num(b"+17 ").unwrap(), Number::Integer(17));
}
#[test]
fn real_numbers() {
assert_eq!(read_num(b"-.002 ").unwrap(), Number::Real(-0.002));
assert_eq!(read_num(b"34.5 ").unwrap(), Number::Real(34.5));
assert_eq!(read_num(b"-3.62 ").unwrap(), Number::Real(-3.62));
assert_eq!(read_num(b"123.6e10 ").unwrap(), Number::Real(123.6e10));
assert_eq!(read_num(b"1.0E-5 ").unwrap(), Number::Real(1.0E-5));
assert_eq!(read_num(b"1E6 ").unwrap(), Number::Real(1E6));
assert_eq!(read_num(b"-1. ").unwrap(), Number::Real(-1.0));
assert_eq!(read_num(b"0.0 ").unwrap(), Number::Real(0.0));
}
#[test]
fn radix_numbers() {
assert_eq!(read_num(b"8#1777 ").unwrap(), Number::Integer(0o1777));
assert_eq!(read_num(b"16#FFFE ").unwrap(), Number::Integer(0xFFFE));
assert_eq!(read_num(b"2#1000 ").unwrap(), Number::Integer(0b1000));
}
#[test]
fn invalid() {
assert!(read_num(b"abc").is_err());
assert!(read_num(b"+abc").is_err());
assert!(read_num(b"1a").is_err());
}
}
-226
View File
@@ -1,226 +0,0 @@
use crate::array::{self, Array};
use crate::error::{Error, Result};
use crate::name::{self, Name};
use crate::number::{self, Number};
use crate::reader::Reader;
use crate::string::{self, String};
/// A PostScript object.
#[derive(Debug, Clone, PartialEq)]
pub enum Object<'a> {
/// A number object.
Number(Number),
/// A name object.
Name(Name<'a>),
/// A string object.
String(String<'a>),
/// An array object.
Array(Array<'a>),
}
pub(crate) fn read<'a>(r: &mut Reader<'a>) -> Result<Object<'a>> {
// PdfCraft patch: `<<` and `>>` are skipped by looping instead of
// recursing once per delimiter, so a long run cannot overflow the stack.
loop {
skip_whitespace_and_comments(r);
let b = r.peek_byte().ok_or(Error::SyntaxError)?;
return match b {
b'(' => string::parse_literal(r)
.map(|s| Object::String(String::from_literal(s)))
.ok_or(Error::SyntaxError),
b'<' => {
if r.peek_bytes(2) == Some(b"<~") {
string::parse_ascii85(r)
.map(|s| Object::String(String::from_ascii85(s)))
.ok_or(Error::SyntaxError)
} else if r.peek_bytes(2) == Some(b"<<") {
// TODO: Proper dict support. For now, skip `<<` and return
// the next object so callers see the inner tokens.
r.forward();
r.forward();
continue;
} else {
string::parse_hex(r)
.map(|s| Object::String(String::from_hex(s)))
.ok_or(Error::SyntaxError)
}
}
b'/' => name::parse_literal(r)
.map(|s| Object::Name(Name::new(s, true)))
.ok_or(Error::SyntaxError),
b'[' => array::parse(r).map(|d| Object::Array(Array::new(d))),
b'>' => {
if r.peek_bytes(2) == Some(b">>") {
// TODO: Proper dict support. Skip `>>` closing delimiter.
r.forward();
r.forward();
continue;
} else {
Err(Error::SyntaxError)
}
}
b'{' => {
r.forward();
Err(Error::UnsupportedType)
}
b'.' | b'+' | b'-' | b'0'..=b'9' => number::read(r).map(Object::Number),
_ => name::parse_executable(r)
.map(|s| Object::Name(Name::new(s, false)))
.ok_or(Error::SyntaxError),
};
}
}
pub(crate) fn at_end(r: &mut Reader<'_>) -> bool {
skip_whitespace_and_comments(r);
r.peek_byte().is_none()
}
pub(crate) fn skip_whitespace_and_comments(r: &mut Reader<'_>) {
loop {
match r.peek_byte() {
Some(b) if crate::reader::is_whitespace(b) => {
r.forward();
}
Some(b'%') => {
r.forward();
r.forward_while(|b| !crate::reader::is_eol(b));
}
_ => return,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn read_one(input: &[u8]) -> Result<Object<'_>> {
let mut r = Reader::new(input);
read(&mut r)
}
fn read_ok(input: &[u8]) -> Object<'_> {
read_one(input).unwrap()
}
fn read_err(input: &[u8]) -> Error {
read_one(input).unwrap_err()
}
#[test]
fn integer() {
assert_eq!(read_ok(b"42 "), Object::Number(Number::Integer(42)));
}
#[test]
fn negative_integer() {
assert_eq!(read_ok(b"-7 "), Object::Number(Number::Integer(-7)));
}
#[test]
fn literal_name() {
assert_eq!(
read_ok(b"/CMapName "),
Object::Name(Name::new(b"CMapName", true))
);
}
#[test]
fn executable_name() {
let obj = read_ok(b"beginbfchar ");
assert_eq!(obj, Object::Name(Name::new(b"beginbfchar", false)));
}
#[test]
fn literal_string() {
assert_eq!(
read_ok(b"(Hello)"),
Object::String(String::from_literal(b"Hello"))
);
}
#[test]
fn hex_string() {
assert_eq!(
read_ok(b"<48656C6C6F>"),
Object::String(String::from_hex(b"48656C6C6F"))
);
}
#[test]
fn ascii85_string() {
assert_eq!(
read_ok(b"<~87cURDZ~>"),
Object::String(String::from_ascii85(b"87cURDZ"))
);
}
#[test]
fn array_simple() {
let obj = read_ok(b"[1 2 3]");
assert_eq!(obj, Object::Array(Array::new(b"1 2 3")));
}
#[test]
fn stray_close_bracket() {
assert_eq!(read_err(b"]"), Error::SyntaxError);
}
#[test]
fn stray_gt() {
assert_eq!(read_err(b">x"), Error::SyntaxError);
}
#[test]
fn skips_whitespace() {
assert_eq!(read_ok(b" \t\n 42 "), Object::Number(Number::Integer(42)));
}
#[test]
fn skips_comments() {
assert_eq!(
read_ok(b"% this is a comment\n42 "),
Object::Number(Number::Integer(42))
);
}
#[test]
fn eof() {
assert!(read_one(b"").is_err());
assert!(read_one(b" ").is_err());
assert!(read_one(b"% comment only\n").is_err());
}
// PdfCraft patch: `<<` and `>>` runs are skipped without recursion.
#[test]
fn long_open_dict_run_does_not_overflow() {
let input = alloc::vec![b'<'; 1_000_000];
assert_eq!(read_err(&input), Error::SyntaxError);
}
#[test]
fn long_close_dict_run_does_not_overflow() {
let input = b">>".repeat(500_000);
assert_eq!(read_err(&input), Error::SyntaxError);
}
#[test]
fn dict_delimiters_are_skipped() {
let mut r = Reader::new(b"<< /A 1 >>");
assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"A", true))));
assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(1))));
assert_eq!(read(&mut r), Err(Error::SyntaxError));
}
#[test]
fn nested_dict_delimiters_are_skipped() {
let mut r = Reader::new(b"<<<< /X >>>> 7 <<\n% c\n<< >> 8");
assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"X", true))));
assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(7))));
assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(8))));
assert!(at_end(&mut r));
}
}
-136
View File
@@ -1,136 +0,0 @@
use core::ops::Range;
#[derive(Clone, Debug)]
pub(crate) struct Reader<'a> {
pub(crate) data: &'a [u8],
pub(crate) offset: usize,
}
impl<'a> Reader<'a> {
#[inline]
pub(crate) fn new(data: &'a [u8]) -> Self {
Self { data, offset: 0 }
}
#[inline]
pub(crate) fn jump(&mut self, offset: usize) {
self.offset = offset;
}
#[inline]
pub(crate) fn range(&self, range: Range<usize>) -> Option<&'a [u8]> {
self.data.get(range)
}
#[inline]
pub(crate) fn offset(&self) -> usize {
self.offset
}
#[inline]
pub(crate) fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
let v = self.peek_bytes(len)?;
self.offset += len;
Some(v)
}
#[inline]
pub(crate) fn read_byte(&mut self) -> Option<u8> {
let v = self.peek_byte()?;
self.offset += 1;
Some(v)
}
#[inline]
pub(crate) fn peek_bytes(&self, len: usize) -> Option<&'a [u8]> {
self.data.get(self.offset..self.offset + len)
}
#[inline]
pub(crate) fn peek_byte(&self) -> Option<u8> {
self.data.get(self.offset).copied()
}
#[inline]
pub(crate) fn eat(&mut self, f: impl Fn(u8) -> bool) -> Option<u8> {
let val = self.peek_byte()?;
if f(val) {
self.forward();
Some(val)
} else {
None
}
}
#[inline]
pub(crate) fn forward(&mut self) {
self.offset += 1;
}
#[inline]
pub(crate) fn forward_while(&mut self, f: impl Fn(u8) -> bool) {
while let Some(b) = self.peek_byte() {
if f(b) {
self.forward();
} else {
break;
}
}
}
#[inline]
pub(crate) fn forward_tag(&mut self, tag: &[u8]) -> Option<()> {
self.peek_tag(tag)?;
self.offset += tag.len();
Some(())
}
#[inline]
pub(crate) fn peek_tag(&self, tag: &[u8]) -> Option<()> {
let mut cloned = self.clone();
for b in tag.iter().copied() {
if cloned.peek_byte() == Some(b) {
cloned.forward();
} else {
return None;
}
}
Some(())
}
#[inline]
pub(crate) fn skip_eol(&mut self) {
while let Some(b) = self.peek_byte() {
if is_eol(b) {
self.forward();
} else {
return;
}
}
}
}
#[inline(always)]
pub(crate) fn is_whitespace(b: u8) -> bool {
matches!(b, 0x00 | 0x09 | 0x0a | 0x0c | 0x0d | 0x20)
}
#[inline(always)]
pub(crate) fn is_delimiter(b: u8) -> bool {
matches!(
b,
b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'
)
}
#[inline(always)]
pub(crate) fn is_regular(b: u8) -> bool {
!is_whitespace(b) && !is_delimiter(b)
}
#[inline(always)]
pub(crate) fn is_eol(b: u8) -> bool {
matches!(b, 0x0a | 0x0d)
}
-288
View File
@@ -1,288 +0,0 @@
mod ascii_85;
pub(crate) mod ascii_hex;
mod literal;
use alloc::vec::Vec;
use crate::error::{Error, Result};
use crate::reader::Reader;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StringInner<'a> {
Literal(&'a [u8]),
Hex(&'a [u8]),
Ascii85(&'a [u8]),
}
/// A PostScript string object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct String<'a> {
inner: StringInner<'a>,
}
impl<'a> String<'a> {
pub(crate) const fn from_literal(data: &'a [u8]) -> Self {
Self {
inner: StringInner::Literal(data),
}
}
pub(crate) const fn from_hex(data: &'a [u8]) -> Self {
Self {
inner: StringInner::Hex(data),
}
}
pub(crate) const fn from_ascii85(data: &'a [u8]) -> Self {
Self {
inner: StringInner::Ascii85(data),
}
}
/// Decode the string content into `out`, replacing any previous contents.
pub fn decode_into(&self, out: &mut Vec<u8>) -> Result<()> {
out.clear();
match self.inner {
StringInner::Literal(data) => literal::decode_into(data, out),
StringInner::Hex(data) => ascii_hex::decode_into(data, out),
StringInner::Ascii85(data) => ascii_85::decode_into(data, out),
}
.ok_or(Error::SyntaxError)
}
/// Decode the string content.
pub fn decode(&self) -> Result<Vec<u8>> {
let mut out = Vec::new();
self.decode_into(&mut out)?;
Ok(out)
}
}
pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
let start = r.offset();
skip_literal(r)?;
let end = r.offset();
// Exclude outer parentheses.
r.range(start + 1..end - 1)
}
pub(crate) fn parse_hex<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
r.forward_tag(b"<")?;
let start = r.offset();
while let Some(b) = r.read_byte() {
if b == b'>' {
return r.range(start..r.offset() - 1);
}
}
None
}
pub(crate) fn parse_ascii85<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
r.forward_tag(b"<~")?;
let start = r.offset();
loop {
let b = r.read_byte()?;
if b == b'~' {
let end = r.offset() - 1;
r.forward_tag(b">")?;
return r.range(start..end);
}
}
}
fn skip_literal(r: &mut Reader<'_>) -> Option<()> {
r.forward_tag(b"(")?;
let mut depth = 1_u32;
while depth > 0 {
let byte = r.read_byte()?;
match byte {
b'\\' => {
let _ = r.read_byte()?;
}
b'(' => depth += 1,
b')' => depth -= 1,
_ => {}
}
}
Some(())
}
#[cfg(test)]
mod tests {
use super::*;
fn decode_literal(input: &[u8]) -> Result<Vec<u8>> {
let mut r = Reader::new(input);
let data = parse_literal(&mut r).ok_or(Error::SyntaxError)?;
String::from_literal(data).decode()
}
#[test]
fn literal_empty() {
assert_eq!(decode_literal(b"()").unwrap(), b"");
}
#[test]
fn literal_simple() {
assert_eq!(decode_literal(b"(Hello)").unwrap(), b"Hello");
}
#[test]
fn literal_nested_parens() {
assert_eq!(
decode_literal(b"(Hi (()) there)").unwrap(),
b"Hi (()) there"
);
}
#[test]
fn literal_escape_n() {
assert_eq!(decode_literal(b"(a\\nb)").unwrap(), b"a\nb");
}
#[test]
fn literal_escape_r() {
assert_eq!(decode_literal(b"(a\\rb)").unwrap(), b"a\rb");
}
#[test]
fn literal_escape_t() {
assert_eq!(decode_literal(b"(a\\tb)").unwrap(), b"a\tb");
}
#[test]
fn literal_escape_b() {
assert_eq!(decode_literal(b"(a\\bb)").unwrap(), &[b'a', 0x08, b'b']);
}
#[test]
fn literal_escape_f() {
assert_eq!(decode_literal(b"(a\\fb)").unwrap(), &[b'a', 0x0C, b'b']);
}
#[test]
fn literal_escape_backslash() {
assert_eq!(decode_literal(b"(a\\\\b)").unwrap(), b"a\\b");
}
#[test]
fn literal_escape_parens() {
assert_eq!(decode_literal(b"(Hi \\()").unwrap(), b"Hi (");
}
#[test]
fn literal_octal_three_digits() {
assert_eq!(decode_literal(b"(\\053)").unwrap(), b"+");
}
#[test]
fn literal_octal_two_digits() {
assert_eq!(decode_literal(b"(\\36)").unwrap(), b"\x1e");
}
#[test]
fn literal_octal_one_digit() {
assert_eq!(decode_literal(b"(\\3)").unwrap(), b"\x03");
}
#[test]
fn literal_line_continuation_lf() {
assert_eq!(decode_literal(b"(Hi \\\nthere)").unwrap(), b"Hi there");
}
#[test]
fn literal_line_continuation_cr() {
assert_eq!(decode_literal(b"(Hi \\\rthere)").unwrap(), b"Hi there");
}
#[test]
fn literal_line_continuation_crlf() {
assert_eq!(decode_literal(b"(Hi \\\r\nthere)").unwrap(), b"Hi there");
}
#[test]
fn literal_bare_eol_lf() {
assert_eq!(decode_literal(b"(a\nb)").unwrap(), b"a\nb");
}
#[test]
fn literal_bare_eol_cr() {
assert_eq!(decode_literal(b"(a\rb)").unwrap(), b"a\nb");
}
#[test]
fn literal_bare_eol_crlf() {
assert_eq!(decode_literal(b"(a\r\nb)").unwrap(), b"a\nb");
}
fn decode_hex(input: &[u8]) -> Result<Vec<u8>> {
let mut r = Reader::new(input);
let data = parse_hex(&mut r).ok_or(Error::SyntaxError)?;
String::from_hex(data).decode()
}
#[test]
fn hex_simple() {
assert_eq!(decode_hex(b"<48656C6C6F>").unwrap(), b"Hello");
}
#[test]
fn hex_with_whitespace() {
assert_eq!(decode_hex(b"<48 65 6C 6C 6F>").unwrap(), b"Hello");
}
#[test]
fn hex_odd_nibble() {
assert_eq!(decode_hex(b"<ABC>").unwrap(), &[0xAB, 0xC0]);
}
#[test]
fn hex_empty() {
assert_eq!(decode_hex(b"<>").unwrap(), b"");
}
#[test]
fn hex_lowercase() {
assert_eq!(decode_hex(b"<abcd>").unwrap(), &[0xAB, 0xCD]);
}
#[test]
fn hex_mixed_case() {
assert_eq!(decode_hex(b"<aB3E>").unwrap(), &[0xAB, 0x3E]);
}
fn decode_a85(input: &[u8]) -> Result<Vec<u8>> {
let mut r = Reader::new(input);
let data = parse_ascii85(&mut r).ok_or(Error::SyntaxError)?;
String::from_ascii85(data).decode()
}
#[test]
fn ascii85_simple() {
// "Hello" in ASCII85 is "87cURDZ"
assert_eq!(decode_a85(b"<~87cURDZ~>").unwrap(), b"Hello");
}
#[test]
fn ascii85_empty() {
assert_eq!(decode_a85(b"<~~>").unwrap(), b"");
}
#[test]
fn ascii85_z_shorthand() {
assert_eq!(decode_a85(b"<~z~>").unwrap(), &[0, 0, 0, 0]);
}
#[test]
fn ascii85_partial_group() {
let result = decode_a85(b"<~87~>").unwrap();
assert_eq!(result.len(), 1);
}
#[test]
fn ascii85_with_whitespace() {
assert_eq!(decode_a85(b"<~87cU RDZ~>").unwrap(), b"Hello");
}
}
-90
View File
@@ -1,90 +0,0 @@
// Keep in sync with `hayro-syntax/src/filter/ascii_85.rs`.
use crate::reader::{Reader, is_whitespace};
use alloc::vec::Vec;
pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
const POW_85: [u32; 5] = [52200625, 614125, 7225, 85, 1];
let mut reader = Reader::new(data);
let mut read_byte = || -> Option<u8> {
loop {
let b = reader.read_byte()?;
// White space characters should be ignored.
if !is_whitespace(b) {
return Some(b);
}
}
};
let flush_group = |group: &mut Vec<u8>, decoded: &mut Vec<u8>| -> Option<()> {
let (digits, output_len): ([u32; 5], usize) = match group.len() {
0 => return Some(()),
1 => return None, // A single character is not valid.
2 => (
[group[0], group[1], b'u', b'u', b'u'].map(|b| (b - b'!') as u32),
1,
),
3 => (
[group[0], group[1], group[2], b'u', b'u'].map(|b| (b - b'!') as u32),
2,
),
4 => (
[group[0], group[1], group[2], group[3], b'u'].map(|b| (b - b'!') as u32),
3,
),
5 => (
[group[0], group[1], group[2], group[3], group[4]].map(|b| (b - b'!') as u32),
4,
),
_ => unreachable!(),
};
let value = digits[0]
.checked_mul(POW_85[0])?
.checked_add(digits[1].checked_mul(POW_85[1])?)?
.checked_add(digits[2].checked_mul(POW_85[2])?)?
.checked_add(digits[3].checked_mul(POW_85[3])?)?
.checked_add(digits[4])?;
decoded.extend_from_slice(&value.to_be_bytes()[..output_len]);
group.clear();
Some(())
};
out.reserve(data.len() * 4 / 5);
let mut group = Vec::with_capacity(5);
loop {
let Some(b) = read_byte() else {
// Be lenient and accept what we have (see PDFBOX-5910).
flush_group(&mut group, out)?;
return Some(());
};
match b {
b'!'..=b'u' => {
group.push(b);
if group.len() == 5 {
flush_group(&mut group, out)?;
}
}
b'z' => {
flush_group(&mut group, out)?;
out.extend_from_slice(&[0, 0, 0, 0]);
}
b'~' => {
// Technically requires a '>', but there is a PDF where it isn't
// appended and decodes fine in other viewers.
flush_group(&mut group, out)?;
return Some(());
}
_ => return None, // Invalid character.
}
}
}
-59
View File
@@ -1,59 +0,0 @@
// Keep in sync with `hayro-syntax/src/filter/ascii_hex.rs`.
use crate::reader::is_whitespace;
use alloc::vec::Vec;
pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
let has_whitespace = data.iter().any(|&b| is_whitespace(b));
out.reserve(data.len().div_ceil(2));
if !has_whitespace {
// Fast path, don't need to worry about white spaces.
let mut i = 0;
while i + 1 < data.len() {
out.push(decode_hex_digit(data[i])? << 4 | decode_hex_digit(data[i + 1])?);
i += 2;
}
if i < data.len() {
out.push(decode_hex_digit(data[i])? << 4);
}
} else {
// Slow path, need to strip white spaces.
let mut iter = data.iter().copied();
let mut read_byte = || -> Option<u8> {
loop {
let b = iter.next()?;
if !is_whitespace(b) {
return Some(b);
}
}
};
loop {
match (read_byte(), read_byte()) {
(Some(hi), Some(lo)) => {
out.push(decode_hex_digit(hi)? << 4 | decode_hex_digit(lo)?);
}
(Some(hi), None) => {
out.push(decode_hex_digit(hi)? << 4);
break;
}
(None, _) => break,
}
}
}
Some(())
}
#[inline(always)]
pub(crate) fn decode_hex_digit(c: u8) -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'A'..=b'F' => Some(c - b'A' + 10),
b'a'..=b'f' => Some(c - b'a' + 10),
_ => None,
}
}
-85
View File
@@ -1,85 +0,0 @@
// Keep in sync with `hayro-syntax/src/object/string.rs` (`read_literal`).
use alloc::vec::Vec;
use crate::reader::Reader;
pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
let mut r = Reader::new(data);
while let Some(byte) = r.read_byte() {
match byte {
b'\\' => {
let next = r.read_byte()?;
if is_octal_digit(next) {
let second = r.read_byte();
let third = r.read_byte();
let bytes = match (second, third) {
(Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) {
(true, true) => [next, n1, n2],
(true, _) => {
r.jump(r.offset() - 1);
[b'0', next, n1]
}
_ => {
r.jump(r.offset() - 2);
[b'0', b'0', next]
}
},
(Some(n1), None) => {
if is_octal_digit(n1) {
[b'0', next, n1]
} else {
r.jump(r.offset() - 1);
[b'0', b'0', next]
}
}
_ => [b'0', b'0', next],
};
let str = core::str::from_utf8(&bytes).unwrap();
if let Ok(num) = u8::from_str_radix(str, 8) {
out.push(num);
}
} else {
match next {
b'n' => out.push(0xA),
b'r' => out.push(0xD),
b't' => out.push(0x9),
b'b' => out.push(0x8),
b'f' => out.push(0xC),
b'(' => out.push(b'('),
b')' => out.push(b')'),
b'\\' => out.push(b'\\'),
b'\n' | b'\r' => {
// "If the \ is followed immediately by a newline
// (CR, LF, or CR-LF pair), the scanner ignores
// both the initial \ and the newline; this breaks
// a string into multiple lines without including
// the newline character as part of the string."
r.skip_eol();
}
_ => out.push(next),
}
}
}
b'(' | b')' => out.push(byte),
// "But if a newline appears without a preceding \, the result is
// equivalent to \n."
b'\n' | b'\r' => {
out.push(b'\n');
r.skip_eol();
}
other => out.push(other),
}
}
Some(())
}
fn is_octal_digit(byte: u8) -> bool {
matches!(byte, b'0'..=b'7')
}