mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-16 19:09:59 -06:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e4235c85b | ||
|
|
ef87aaa590 | ||
|
|
4ebc9a5127 | ||
|
|
fc7698eb11 | ||
|
|
058ea183ec | ||
|
|
faef1a06c8 | ||
|
|
8d8716cdc0 | ||
|
|
496c13e7b4 |
Generated
+24
-6
@@ -932,6 +932,17 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
@@ -998,11 +1009,6 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bc358686389892a3827e64fc26bedc278ef1e299#bc358686389892a3827e64fc26bedc278ef1e299"
|
||||
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
@@ -1132,6 +1138,18 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
"craft-sheet",
|
||||
"craft-xml",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -2311,7 +2329,6 @@ dependencies = [
|
||||
name = "gridcraft-pdf"
|
||||
version = "0.19.1"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"craft-stream-codecs",
|
||||
"harfrust",
|
||||
"sha2 0.11.1",
|
||||
@@ -2385,6 +2402,7 @@ dependencies = [
|
||||
"craft-offcrypto",
|
||||
"craft-opc",
|
||||
"craft-xls",
|
||||
"craft-xlsx",
|
||||
"craft-xml",
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
|
||||
+2
-1
@@ -32,7 +32,6 @@ gridcraft-math = { path = "crates/math" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "=0.1.0", features = ["egui"] }
|
||||
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bc358686389892a3827e64fc26bedc278ef1e299", version = "0.1.0", default-features = false }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
|
||||
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
@@ -45,6 +44,8 @@ craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0
|
||||
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
|
||||
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
|
||||
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
|
||||
# SpreadsheetML string encoding/decoding; workbook model mapping stays in gridcraft-xlsx.
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
|
||||
|
||||
@@ -53,6 +53,11 @@ pub struct PrintSettings {
|
||||
/// sheet is more than one page wide and tall.
|
||||
#[serde(default)]
|
||||
pub page_order: PageOrder,
|
||||
/// Page Setup › Page › First page number: the number the sheet's first printed page takes,
|
||||
/// or `None` for Automatic (XLSX `pageSetup firstPageNumber` with `useFirstPageNumber`). Left
|
||||
/// out of a JSON workbook when Automatic, so files without it are written as before.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub first_page_number: Option<u32>,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
@@ -187,6 +192,7 @@ impl Default for PrintSettings {
|
||||
hf_scale_with_doc: true,
|
||||
hf_align_with_margins: true,
|
||||
page_order: PageOrder::DownThenOver,
|
||||
first_page_number: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -281,4 +287,17 @@ mod tests {
|
||||
p = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(p, PrintSettings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_page_number_is_saved_only_when_set() {
|
||||
// Automatic writes nothing, so a JSON workbook without a first page number is unchanged and
|
||||
// one saved before the field existed loads as Automatic.
|
||||
let saved = serde_json::to_value(PrintSettings::default()).unwrap();
|
||||
assert!(saved.get("first_page_number").is_none(), "{saved}");
|
||||
assert_eq!(serde_json::from_value::<PrintSettings>(saved).unwrap().first_page_number, None);
|
||||
let p = PrintSettings { first_page_number: Some(7), ..Default::default() };
|
||||
let saved = serde_json::to_value(&p).unwrap();
|
||||
assert_eq!(saved["first_page_number"], 7);
|
||||
assert_eq!(serde_json::from_value::<PrintSettings>(saved).unwrap(), p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ readme = "README.md"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-pdf.workspace = true
|
||||
craft-stream-codecs.workspace = true
|
||||
harfrust = "=0.12.0"
|
||||
skrifa = { workspace = true }
|
||||
|
||||
@@ -10,7 +10,7 @@ use skrifa::{
|
||||
};
|
||||
use unicode_bidi::BidiInfo;
|
||||
|
||||
use crate::{CID_FONT, Error, Font, TextDirection, n, needs_cid, pdf_string, pdf_utf16_string};
|
||||
use crate::{CID_FONT, Error, Font, TextDirection, dict_obj, n, needs_cid, pdf_string, pdf_utf16_string, stream_obj};
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/arabic_fonts.rs"));
|
||||
|
||||
@@ -490,7 +490,7 @@ impl Subset {
|
||||
}
|
||||
|
||||
/// Writes the subset fonts into `out` and returns their page resource entries.
|
||||
pub(crate) fn write_objects(&self, next: &mut u32, out: &mut craft_pdf::classic::Writer) -> Result<String, Error> {
|
||||
pub(crate) fn write_objects(&self, next: &mut u32, out: &mut Vec<u8>, offsets: &mut Vec<usize>) -> String {
|
||||
let mut resources = String::new();
|
||||
for (batch, glyphs) in self.glyphs.chunks(255).enumerate() {
|
||||
let id = *next;
|
||||
@@ -507,7 +507,7 @@ impl Subset {
|
||||
let _ = write!(names, "/g{code} ");
|
||||
let _ = write!(widths, "{} ", n(glyph.width));
|
||||
let body = glyph_procedure(glyph);
|
||||
out.stream(*next, "", body.as_bytes())?;
|
||||
stream_obj(out, offsets, *next, "", body.as_bytes());
|
||||
*next += 1;
|
||||
bounds[0] = bounds[0].min(glyph.bounds[0]);
|
||||
bounds[1] = bounds[1].min(glyph.bounds[1]);
|
||||
@@ -526,8 +526,11 @@ impl Subset {
|
||||
cmap.push_str("endbfchar\n");
|
||||
}
|
||||
cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
|
||||
out.stream(cmap_id, "", cmap.as_bytes())?;
|
||||
out.object(id,
|
||||
stream_obj(out, offsets, cmap_id, "", cmap.as_bytes());
|
||||
dict_obj(
|
||||
out,
|
||||
offsets,
|
||||
id,
|
||||
&format!(
|
||||
"<< /Type /Font /Subtype /Type3 /Name /GridCraftArabic /FontBBox [{} {} {} {}] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << {procs}>> /Encoding << /Type /Encoding /Differences [1 {names}] >> /FirstChar 1 /LastChar {} /Widths [{widths}] /Resources << >> /ToUnicode {cmap_id} 0 R >>",
|
||||
n(bounds[0]),
|
||||
@@ -536,10 +539,10 @@ impl Subset {
|
||||
n(bounds[3]),
|
||||
glyphs.len()
|
||||
),
|
||||
)?;
|
||||
);
|
||||
let _ = write!(resources, "/A{} {id} 0 R ", batch + 1);
|
||||
}
|
||||
Ok(resources)
|
||||
resources
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+88
-29
@@ -1,4 +1,4 @@
|
||||
//! PDF 1.7 drawing for GridCraft print/export, with shared object and xref framing.
|
||||
//! A tiny, self-contained PDF 1.7 writer for GridCraft's print and PDF export.
|
||||
//!
|
||||
//! - The 14 standard fonts (no embedding) with WinAnsiEncoding, plus approximate width tables
|
||||
//! ([`text_width`]) so callers can measure, align and wrap text. Characters outside
|
||||
@@ -52,7 +52,7 @@ impl TextDirection {
|
||||
}
|
||||
}
|
||||
|
||||
/// A PDF export could not preserve the requested text or serialize its object envelope.
|
||||
/// A PDF export could not preserve the requested text.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Error(String);
|
||||
|
||||
@@ -63,12 +63,6 @@ impl std::fmt::Display for Error {
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
impl From<craft_pdf::classic::Error> for Error {
|
||||
fn from(error: craft_pdf::classic::Error) -> Self {
|
||||
Self(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::fmt::Write as _;
|
||||
@@ -1007,6 +1001,49 @@ fn pdf_text_string(text: &str) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// Starts object `id` at the current end of `out` and records its offset for the xref table.
|
||||
fn begin_obj(out: &mut Vec<u8>, offsets: &mut Vec<usize>, id: u32) {
|
||||
let i = id as usize;
|
||||
if offsets.len() <= i {
|
||||
offsets.resize(i + 1, 0);
|
||||
}
|
||||
if let Some(slot) = offsets.get_mut(i) {
|
||||
*slot = out.len();
|
||||
}
|
||||
let _ = writeln!(Utf8(out), "{id} 0 obj");
|
||||
}
|
||||
|
||||
/// Writes `id 0 obj <body> endobj`.
|
||||
fn dict_obj(out: &mut Vec<u8>, offsets: &mut Vec<usize>, id: u32, body: &str) {
|
||||
begin_obj(out, offsets, id);
|
||||
out.extend_from_slice(body.as_bytes());
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
|
||||
/// Writes a stream object: `dict` (the dictionary entries without `<<`, `>>` and `/Length`, may be
|
||||
/// empty) and `data` as the stream body.
|
||||
fn stream_obj(out: &mut Vec<u8>, offsets: &mut Vec<usize>, id: u32, dict: &str, data: &[u8]) {
|
||||
begin_obj(out, offsets, id);
|
||||
out.extend_from_slice(b"<<");
|
||||
if !dict.is_empty() {
|
||||
out.push(b' ');
|
||||
out.extend_from_slice(dict.as_bytes());
|
||||
}
|
||||
let _ = write!(Utf8(out), " /Length {} >>\nstream\n", data.len());
|
||||
out.extend_from_slice(data);
|
||||
out.extend_from_slice(b"\nendstream\nendobj\n");
|
||||
}
|
||||
|
||||
/// Lets `write!` append text to a byte buffer.
|
||||
struct Utf8<'a>(&'a mut Vec<u8>);
|
||||
|
||||
impl std::fmt::Write for Utf8<'_> {
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
self.0.extend_from_slice(s.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl PdfDoc {
|
||||
pub fn new() -> PdfDoc {
|
||||
PdfDoc::default()
|
||||
@@ -1060,8 +1097,7 @@ impl PdfDoc {
|
||||
/// numbered during writing (fonts, then per page its new images, content stream and page
|
||||
/// dictionary), with the catalog, page tree and info dictionary last.
|
||||
///
|
||||
/// Returns an error if the Arabic font is unusable, text exceeds a size limit, or the
|
||||
/// shared envelope writer refuses object counts, offsets or an allocation.
|
||||
/// Returns an error if the Arabic font is unusable or Arabic text exceeds a size limit.
|
||||
pub fn finish(mut self) -> Result<Vec<u8>, Error> {
|
||||
if let Some(error) = self.pages.iter().find_map(|page| page.error.clone()) {
|
||||
return Err(error);
|
||||
@@ -1095,7 +1131,9 @@ impl PdfDoc {
|
||||
let contents: Vec<String> = self.pages.iter_mut().map(|p| std::mem::take(&mut p.content)).collect();
|
||||
let page_links: Vec<Vec<LinkAnnotation>> = self.pages.iter_mut().map(|p| std::mem::take(&mut p.links)).collect();
|
||||
let reserve = contents.iter().fold(4096usize, |acc, c| acc.saturating_add(c.len()).saturating_add(1024));
|
||||
let mut out = craft_pdf::classic::Writer::with_capacity(reserve)?;
|
||||
let mut out: Vec<u8> = Vec::with_capacity(reserve);
|
||||
out.extend_from_slice(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
|
||||
let mut offsets: Vec<usize> = vec![0; 4];
|
||||
let mut kids = Vec::new();
|
||||
let mut annotations = Vec::new();
|
||||
let page_count = self.pages.len();
|
||||
@@ -1105,34 +1143,42 @@ impl PdfDoc {
|
||||
let _ = write!(font_dict, "/F{} {} 0 R ", i + 1, id);
|
||||
if i == CID_FONT {
|
||||
let (cid_id, desc_id) = (id + 1, id + 2);
|
||||
out.object(
|
||||
dict_obj(
|
||||
&mut out,
|
||||
&mut offsets,
|
||||
*id,
|
||||
&format!(
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /{CID_BASE_FONT} /Encoding /UniGB-UTF16-H /DescendantFonts [{cid_id} 0 R] >>"
|
||||
),
|
||||
)?;
|
||||
out.object(cid_id,
|
||||
);
|
||||
dict_obj(
|
||||
&mut out,
|
||||
&mut offsets,
|
||||
cid_id,
|
||||
&format!(
|
||||
"<< /Type /Font /Subtype /CIDFontType0 /BaseFont /{CID_BASE_FONT} /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 4 >> /FontDescriptor {desc_id} 0 R /DW {CID_WIDTH} >>"
|
||||
),
|
||||
)?;
|
||||
out.object(desc_id,
|
||||
);
|
||||
dict_obj(
|
||||
&mut out,
|
||||
&mut offsets,
|
||||
desc_id,
|
||||
&format!(
|
||||
"<< /Type /FontDescriptor /FontName /{CID_BASE_FONT} /Flags 6 /FontBBox [-25 -254 1000 880] /ItalicAngle 0 /Ascent 880 /Descent -120 /CapHeight 880 /StemV 93 >>"
|
||||
),
|
||||
)?;
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let name = Font::ALL.get(i).copied().unwrap_or_default().base_name();
|
||||
let enc = if name.starts_with("Symbol") { "" } else { " /Encoding /WinAnsiEncoding" };
|
||||
out.object(*id, &format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name}{enc} >>"))?;
|
||||
dict_obj(&mut out, &mut offsets, *id, &format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name}{enc} >>"));
|
||||
}
|
||||
}
|
||||
// Images already written, by content hash: (page, image, object id). A hash match is
|
||||
// confirmed by comparing the pixels before an object is shared.
|
||||
let mut written: HashMap<u64, Vec<(usize, usize, u32)>> = HashMap::new();
|
||||
for (pi, ((page, content), links)) in self.pages.iter().zip(contents).zip(page_links).enumerate() {
|
||||
let arabic_fonts = page.arabic.write_objects(&mut next, &mut out)?;
|
||||
let arabic_fonts = page.arabic.write_objects(&mut next, &mut out, &mut offsets);
|
||||
let page_fonts = format!("{font_dict}{arabic_fonts}");
|
||||
let mut xobjects = String::new();
|
||||
for (k, img) in page.images.iter().enumerate() {
|
||||
@@ -1158,13 +1204,13 @@ impl PdfDoc {
|
||||
let _ = write!(dict, " /SMask {id} 0 R");
|
||||
}
|
||||
dict.push_str(" /Filter /RunLengthDecode");
|
||||
out.stream(img_id, &dict, &run_length(&img.rgb))?;
|
||||
stream_obj(&mut out, &mut offsets, img_id, &dict, &run_length(&img.rgb));
|
||||
if let (Some(id), Some(a)) = (smask_id, &img.alpha) {
|
||||
let dict = format!(
|
||||
"/Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /RunLengthDecode",
|
||||
img.width, img.height
|
||||
);
|
||||
out.stream(id, &dict, &run_length(a))?;
|
||||
stream_obj(&mut out, &mut offsets, id, &dict, &run_length(a));
|
||||
}
|
||||
written.entry(img.hash).or_default().push((pi, k, img_id));
|
||||
img_id
|
||||
@@ -1175,7 +1221,7 @@ impl PdfDoc {
|
||||
let content_id = next;
|
||||
let page_id = next + 1;
|
||||
next += 2;
|
||||
out.stream(content_id, "", content.as_bytes())?;
|
||||
stream_obj(&mut out, &mut offsets, content_id, "", content.as_bytes());
|
||||
drop(content);
|
||||
let xo = if xobjects.is_empty() { String::new() } else { format!(" /XObject << {xobjects}>>") };
|
||||
let mut link_refs = String::new();
|
||||
@@ -1189,7 +1235,9 @@ impl PdfDoc {
|
||||
annotations.push((id, link));
|
||||
}
|
||||
let annots = if link_refs.is_empty() { String::new() } else { format!(" /Annots [{link_refs}]") };
|
||||
out.object(
|
||||
dict_obj(
|
||||
&mut out,
|
||||
&mut offsets,
|
||||
page_id,
|
||||
&format!(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources << /Font << {}>>{} >> /Contents {} 0 R{} >>",
|
||||
@@ -1200,7 +1248,7 @@ impl PdfDoc {
|
||||
content_id,
|
||||
annots
|
||||
),
|
||||
)?;
|
||||
);
|
||||
kids.push(page_id);
|
||||
}
|
||||
for (id, link) in annotations {
|
||||
@@ -1213,11 +1261,16 @@ impl PdfDoc {
|
||||
format!("/Dest [{page_id} 0 R /XYZ {} {} null]", n(x), n(height - y))
|
||||
}
|
||||
};
|
||||
out.object(id, &format!("<< /Type /Annot /Subtype /Link /Rect [{} {} {} {}] /Border [0 0 0] {action} >>", n(x0), n(y0), n(x1), n(y1)))?;
|
||||
dict_obj(
|
||||
&mut out,
|
||||
&mut offsets,
|
||||
id,
|
||||
&format!("<< /Type /Annot /Subtype /Link /Rect [{} {} {} {}] /Border [0 0 0] {action} >>", n(x0), n(y0), n(x1), n(y1)),
|
||||
);
|
||||
}
|
||||
out.object(1, "<< /Type /Catalog /Pages 2 0 R >>")?;
|
||||
dict_obj(&mut out, &mut offsets, 1, "<< /Type /Catalog /Pages 2 0 R >>");
|
||||
let kids_s: Vec<String> = kids.iter().map(|k| format!("{k} 0 R")).collect();
|
||||
out.object(2, &format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids_s.join(" "), kids.len()))?;
|
||||
dict_obj(&mut out, &mut offsets, 2, &format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids_s.join(" "), kids.len()));
|
||||
let creator = if self.info.creator.is_empty() { "GridCraft" } else { &self.info.creator };
|
||||
let mut info = format!("<< /Producer {} /Creator {}", pdf_text_string("GridCraft PDF"), pdf_text_string(creator));
|
||||
if !self.info.title.is_empty() {
|
||||
@@ -1227,9 +1280,15 @@ impl PdfDoc {
|
||||
let _ = write!(info, " /Author {}", pdf_text_string(&self.info.author));
|
||||
}
|
||||
info.push_str(" >>");
|
||||
out.object(3, &info)?;
|
||||
dict_obj(&mut out, &mut offsets, 3, &info);
|
||||
|
||||
out.finish(1, Some(3)).map_err(Error::from)
|
||||
let xref = out.len();
|
||||
let _ = write!(Utf8(&mut out), "xref\n0 {}\n0000000000 65535 f \n", next);
|
||||
for off in offsets.iter().skip(1) {
|
||||
let _ = writeln!(Utf8(&mut out), "{off:010} 00000 n ");
|
||||
}
|
||||
let _ = write!(Utf8(&mut out), "trailer\n<< /Size {} /Root 1 0 R /Info 3 0 R >>\nstartxref\n{}\n%%EOF\n", next, xref);
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1136,10 +1136,7 @@ fn explicit_rtl_standard_text_reorders_without_an_arabic_font() {
|
||||
let page = doc.add_page(300.0, 100.0);
|
||||
page.text_with_direction(Point::new(10.0, 30.0), 12.0, Font::Helvetica, [0, 0, 0], source, TextDirection::RightToLeft);
|
||||
assert!(page.content.contains("(! ABC) Tj"), "{}", page.content);
|
||||
let mut objects = craft_pdf::classic::Writer::with_capacity(0).unwrap();
|
||||
let mut next = 4;
|
||||
assert!(page.arabic.write_objects(&mut next, &mut objects).unwrap().is_empty());
|
||||
assert_eq!(next, 4, "Latin-only RTL text must not allocate Arabic font objects");
|
||||
assert!(page.arabic.write_objects(&mut 4, &mut Vec::new(), &mut Vec::new()).is_empty());
|
||||
assert_eq!(text_width_with_direction(Font::Helvetica, 12.0, source, TextDirection::RightToLeft), text_width(Font::Helvetica, 12.0, source));
|
||||
let pdf = doc.finish().unwrap();
|
||||
assert_eq!(utf16_entry(&pdf, "/ActualText").unwrap(), source);
|
||||
|
||||
@@ -24,6 +24,7 @@ craft-offcrypto = { workspace = true }
|
||||
craft-opc = { workspace = true }
|
||||
craft-xls = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
craft-xlsx = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
@@ -267,6 +267,8 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
}
|
||||
// `downThenOver` when absent (ECMA-376's default); an unknown value reads as that too.
|
||||
sheet.print.page_order = e.attr("pageOrder").and_then(PageOrder::parse).unwrap_or_default();
|
||||
// The number counts only when `useFirstPageNumber` says so; otherwise it's Automatic.
|
||||
sheet.print.first_page_number = e.flag("useFirstPageNumber", false).then(|| e.attr_u32("firstPageNumber")).flatten();
|
||||
if let Some(p) = e.attr_u32("paperSize").and_then(paper_name) {
|
||||
sheet.print.paper = p.to_string();
|
||||
}
|
||||
|
||||
@@ -409,6 +409,9 @@ fn write_sheet_printing<'a>(s: &mut String, sheet: &'a Sheet, rels: &mut Rels, o
|
||||
if p.scale != 100 && (10..=400).contains(&p.scale) {
|
||||
let _ = write!(s, " scale=\"{}\"", p.scale);
|
||||
}
|
||||
if let Some(n) = p.first_page_number {
|
||||
let _ = write!(s, " firstPageNumber=\"{n}\"");
|
||||
}
|
||||
if let Some((w, h)) = p.fit_to {
|
||||
let _ = write!(s, " fitToWidth=\"{w}\" fitToHeight=\"{h}\"");
|
||||
}
|
||||
@@ -417,6 +420,10 @@ fn write_sheet_printing<'a>(s: &mut String, sheet: &'a Sheet, rels: &mut Rels, o
|
||||
let _ = write!(s, " pageOrder=\"{}\"", p.page_order.id());
|
||||
}
|
||||
let _ = write!(s, " orientation=\"{}\"", if p.orientation == Orientation::Landscape { "landscape" } else { "portrait" });
|
||||
// In the schema's attribute order, as Excel writes it: after the orientation.
|
||||
if p.first_page_number.is_some() {
|
||||
s.push_str(" useFirstPageNumber=\"1\"");
|
||||
}
|
||||
if let Some(id) = kept.page_setup_id() {
|
||||
let _ = write!(s, " r:id=\"{id}\"");
|
||||
}
|
||||
|
||||
@@ -142,27 +142,27 @@ pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, out: &m
|
||||
}
|
||||
let _ = write!(s, " name=\"{}\"", esc_attr(&encode_xstring(name)));
|
||||
let totals = col.map(|c| c.totals).unwrap_or_default();
|
||||
if t.totals_row {
|
||||
let f = match totals {
|
||||
TotalsFn::None => None,
|
||||
TotalsFn::Average => Some("average"),
|
||||
TotalsFn::Count => Some("count"),
|
||||
TotalsFn::CountNums => Some("countNums"),
|
||||
TotalsFn::Max => Some("max"),
|
||||
TotalsFn::Min => Some("min"),
|
||||
TotalsFn::Sum => Some("sum"),
|
||||
TotalsFn::StdDev => Some("stdDev"),
|
||||
TotalsFn::Var => Some("var"),
|
||||
TotalsFn::Custom => Some("custom"),
|
||||
};
|
||||
if let Some(f) = f {
|
||||
let _ = write!(s, " totalsRowFunction=\"{f}\"");
|
||||
} else if let Some(l) = col.and_then(|c| c.totals_label.as_ref()) {
|
||||
let _ = write!(s, " totalsRowLabel=\"{}\"", esc_attr(l));
|
||||
}
|
||||
// A hidden Total Row keeps each column's calculation, as Excel's files do: turning the row
|
||||
// back on restores it (#4296). The reader takes them whether the row is shown or not.
|
||||
let f = match totals {
|
||||
TotalsFn::None => None,
|
||||
TotalsFn::Average => Some("average"),
|
||||
TotalsFn::Count => Some("count"),
|
||||
TotalsFn::CountNums => Some("countNums"),
|
||||
TotalsFn::Max => Some("max"),
|
||||
TotalsFn::Min => Some("min"),
|
||||
TotalsFn::Sum => Some("sum"),
|
||||
TotalsFn::StdDev => Some("stdDev"),
|
||||
TotalsFn::Var => Some("var"),
|
||||
TotalsFn::Custom => Some("custom"),
|
||||
};
|
||||
if let Some(f) = f {
|
||||
let _ = write!(s, " totalsRowFunction=\"{f}\"");
|
||||
} else if let Some(l) = col.and_then(|c| c.totals_label.as_ref()) {
|
||||
let _ = write!(s, " totalsRowLabel=\"{}\"", esc_attr(l));
|
||||
}
|
||||
let calc = col.and_then(|c| c.formula.as_ref()).filter(|f| !f.is_empty());
|
||||
let custom = if t.totals_row && totals == TotalsFn::Custom { col.and_then(|c| c.totals_label.as_ref()) } else { None };
|
||||
let custom = if totals == TotalsFn::Custom { col.and_then(|c| c.totals_label.as_ref()) } else { None };
|
||||
let xml = col.and_then(|c| c.xml.as_ref());
|
||||
if calc.is_none() && custom.is_none() && xml.is_none() {
|
||||
s.push_str("/>");
|
||||
|
||||
@@ -73,3 +73,39 @@ fn page_margins_are_written_as_their_decimals() {
|
||||
let xml = sheet_xml(&write_xlsx(&Workbook::new()).unwrap());
|
||||
assert!(xml.contains(r#"<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>"#), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_page_number_is_read_and_written_back() {
|
||||
// #4293: Excel writes Page Setup's First page number 7 as these two attributes; both were lost.
|
||||
let body = r#"<sheetData/><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/><pageSetup paperSize="9" firstPageNumber="7" orientation="portrait" useFirstPageNumber="1"/>"#;
|
||||
let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().print.first_page_number, Some(7));
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let xml = sheet_xml(&bytes);
|
||||
assert_eq!(page_setup(&xml), r#"<pageSetup paperSize="9" firstPageNumber="7" orientation="portrait" useFirstPageNumber="1"/>"#);
|
||||
let (back, _) = read_xlsx(&bytes).unwrap();
|
||||
assert_eq!(back.sheet(0).unwrap().print.first_page_number, Some(7));
|
||||
// In the schema's order with the other attributes: after the scale, before Fit To.
|
||||
let mut wb = back;
|
||||
wb.sheet_mut(0).unwrap().print.scale = 80;
|
||||
wb.sheet_mut(0).unwrap().print.fit_to = Some((1, 2));
|
||||
let xml = sheet_xml(&write_xlsx(&wb).unwrap());
|
||||
assert!(page_setup(&xml).contains(r#"scale="80" firstPageNumber="7" fitToWidth="1""#), "{xml}");
|
||||
// Automatic: no number, a number Excel keeps without using it, and `useFirstPageNumber="0"`.
|
||||
for body in [
|
||||
r#"<sheetData/><pageSetup paperSize="9" orientation="portrait"/>"#,
|
||||
r#"<sheetData/><pageSetup paperSize="9" firstPageNumber="5" orientation="portrait"/>"#,
|
||||
r#"<sheetData/><pageSetup paperSize="9" firstPageNumber="5" orientation="portrait" useFirstPageNumber="0"/>"#,
|
||||
"<sheetData/>",
|
||||
] {
|
||||
let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().print.first_page_number, None, "{body}");
|
||||
let xml = sheet_xml(&write_xlsx(&wb).unwrap());
|
||||
assert!(!xml.contains("irstPageNumber"), "{body}: {xml}");
|
||||
}
|
||||
// 1 is a number of its own (Excel's field shows 1, not Automatic) and is kept too.
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheet_mut(0).unwrap().print.first_page_number = Some(1);
|
||||
let xml = sheet_xml(&write_xlsx(&wb).unwrap());
|
||||
assert!(xml.contains(r#"firstPageNumber="1""#) && xml.contains(r#"useFirstPageNumber="1""#), "{xml}");
|
||||
}
|
||||
|
||||
@@ -310,6 +310,7 @@ fn sample() -> Workbook {
|
||||
hf_scale_with_doc: false,
|
||||
hf_align_with_margins: true,
|
||||
page_order: PageOrder::OverThenDown,
|
||||
first_page_number: Some(7),
|
||||
};
|
||||
s.sparklines.push(Sparkline { cell: at("J2"), source: "B2:B3".into(), kind: SparklineKind::WinLoss, color: Color::Rgb(0x112233), markers: true });
|
||||
s.tables.push(Table {
|
||||
@@ -1406,6 +1407,76 @@ fn table_newline_column_and_backslash_name_survive() {
|
||||
assert!(gridcraft_formula::parse("COUNTA(\\_Prime.1[Name])").is_ok(), "backslash table name parses as a structured reference");
|
||||
}
|
||||
|
||||
/// #4296: a table whose Total Row is turned off keeps each column's calculation in the file, as
|
||||
/// Excel writes it, so turning the row back on in Excel restores a custom formula or Average.
|
||||
#[test]
|
||||
fn hidden_total_row_keeps_its_calculations() {
|
||||
let col = |name: &str, totals: TotalsFn, label: Option<&str>| TableColumn {
|
||||
name: name.into(),
|
||||
totals,
|
||||
totals_label: label.map(str::to_string),
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
xml: None,
|
||||
};
|
||||
let mut wb = Workbook::new();
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
s.tables.push(Table {
|
||||
id: 1,
|
||||
name: "Table1".into(),
|
||||
range: rr("A1:C3"),
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![
|
||||
col("Group", TotalsFn::None, Some("Total")),
|
||||
col("Amount", TotalsFn::Custom, Some("SUM(B2:B3)+10")),
|
||||
col("Mean", TotalsFn::Average, None),
|
||||
],
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: true,
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
});
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let mut xml = String::new();
|
||||
zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("xl/tables/table1.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
// Still a table without a total row: no totalsRowCount, and its range unchanged.
|
||||
assert!(xml.contains(r#"ref="A1:C3""#) && xml.contains(r#"totalsRowShown="0""#) && !xml.contains("totalsRowCount"), "{xml}");
|
||||
for part in [
|
||||
r#"name="Group" totalsRowLabel="Total"/>"#,
|
||||
r#"name="Amount" totalsRowFunction="custom"><totalsRowFormula>SUM(B2:B3)+10</totalsRowFormula></tableColumn>"#,
|
||||
r#"name="Mean" totalsRowFunction="average"/>"#,
|
||||
] {
|
||||
assert!(xml.contains(part), "{part}: {xml}");
|
||||
}
|
||||
let (back, report) = read_xlsx(&bytes).unwrap();
|
||||
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
|
||||
let t = &back.sheet(0).unwrap().tables[0];
|
||||
assert!(!t.totals_row);
|
||||
assert_eq!(t.range.a1(), "A1:C3");
|
||||
let got: Vec<_> = t.columns.iter().map(|c| (c.totals, c.totals_label.clone())).collect();
|
||||
assert_eq!(got, vec![(TotalsFn::None, Some("Total".into())), (TotalsFn::Custom, Some("SUM(B2:B3)+10".into())), (TotalsFn::Average, None)]);
|
||||
// A table that never had a total row writes no calculation.
|
||||
let mut plain = wb.clone();
|
||||
plain.sheet_mut(0).unwrap().tables[0].columns =
|
||||
vec![col("Group", TotalsFn::None, None), col("Amount", TotalsFn::None, None), col("Mean", TotalsFn::None, None)];
|
||||
let mut xml = String::new();
|
||||
zip::ZipArchive::new(std::io::Cursor::new(write_xlsx(&plain).unwrap()))
|
||||
.unwrap()
|
||||
.by_name("xl/tables/table1.xml")
|
||||
.unwrap()
|
||||
.read_to_string(&mut xml)
|
||||
.unwrap();
|
||||
for attr in ["totalsRowFunction", "totalsRowLabel", "totalsRowFormula"] {
|
||||
assert!(!xml.contains(attr), "{attr}: {xml}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A table that is only a header row and a totals row (Insert Table on one row, then Total
|
||||
/// Row) is written like the header-only and one-data-row shapes, not dropped on save.
|
||||
#[test]
|
||||
|
||||
+30
-68
@@ -359,11 +359,10 @@ pub fn parse_streaming(xml: &[u8], split: &[&str], cb: &mut dyn FnMut(El) -> Res
|
||||
|
||||
// ---------------------------------------------------------------- writing helpers
|
||||
|
||||
// XML 1.0 byte escaping is shared; spreadsheet string and phonetic policy stays here.
|
||||
use craft_xml::is_xml_char;
|
||||
#[cfg(test)]
|
||||
use craft_xml::push_esc;
|
||||
// XML escaping and SpreadsheetML strings are shared; phonetic/model mapping stays here.
|
||||
pub use craft_xml::{esc, esc_attr};
|
||||
#[cfg(test)]
|
||||
use craft_xml::{is_xml_char, push_esc};
|
||||
|
||||
/// Appends `n` in decimal.
|
||||
pub fn push_u64(o: &mut String, mut n: u64) {
|
||||
@@ -402,70 +401,8 @@ pub fn push_a1(o: &mut String, c: gridcraft_core::CellRef) {
|
||||
push_u64(o, u64::from(c.row) + 1);
|
||||
}
|
||||
|
||||
/// ST_Xstring encoding for cell text: characters XML can't carry and carriage returns become
|
||||
/// `_xHHHH_`, and literal `_xHHHH_` sequences are protected with `_x005F_`. The result still needs
|
||||
/// [`esc`].
|
||||
pub fn encode_xstring(s: &str) -> String {
|
||||
let mut o = String::with_capacity(s.len());
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
if c == '_' && looks_like_escape(&chars, i) {
|
||||
o.push_str("_x005F_");
|
||||
} else if !is_xml_char(c) || (c.is_control() && !matches!(c, '\t' | '\n')) {
|
||||
o.push_str(&format!("_x{:04X}_", c as u32 & 0xFFFF));
|
||||
} else {
|
||||
o.push(c);
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
fn looks_like_escape(chars: &[char], i: usize) -> bool {
|
||||
chars.get(i + 1) == Some(&'x') && chars.get(i + 6) == Some(&'_') && (i + 2..i + 6).all(|k| chars.get(k).is_some_and(char::is_ascii_hexdigit))
|
||||
}
|
||||
|
||||
fn escape_unit(chars: &[char], i: usize) -> Option<u32> {
|
||||
let hex: String = chars.get(i + 2..i + 6)?.iter().collect();
|
||||
u32::from_str_radix(&hex, 16).ok()
|
||||
}
|
||||
|
||||
/// The character for a high surrogate escape at `i` (value `high`) followed directly by a low surrogate escape.
|
||||
fn surrogate_pair(chars: &[char], i: usize, high: u32) -> Option<char> {
|
||||
if !(0xD800..=0xDBFF).contains(&high) || chars.get(i + 7) != Some(&'_') || !looks_like_escape(chars, i + 7) {
|
||||
return None;
|
||||
}
|
||||
let low = escape_unit(chars, i + 7).filter(|l| (0xDC00..=0xDFFF).contains(l))?;
|
||||
char::from_u32(0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00))
|
||||
}
|
||||
|
||||
/// Inverse of [`encode_xstring`].
|
||||
pub fn decode_xstring(s: &str) -> String {
|
||||
if !s.contains("_x") {
|
||||
return s.to_string();
|
||||
}
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
let mut o = String::with_capacity(s.len());
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
if chars[i] == '_' && looks_like_escape(&chars, i) {
|
||||
let unit = escape_unit(&chars, i);
|
||||
if let Some(ch) = unit.and_then(char::from_u32) {
|
||||
o.push(ch);
|
||||
i += 7;
|
||||
continue;
|
||||
}
|
||||
// A high surrogate escape followed by a low surrogate escape is one UTF-16 pair.
|
||||
if let Some(ch) = unit.and_then(|high| surrogate_pair(&chars, i, high)) {
|
||||
o.push(ch);
|
||||
i += 14;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
o.push(chars[i]);
|
||||
i += 1;
|
||||
}
|
||||
o
|
||||
}
|
||||
// Existing call sites and regression coverage use the production shared codec.
|
||||
pub use craft_xlsx::{decode_xstring, encode_xstring};
|
||||
|
||||
/// `<t>` element with `xml:space="preserve"` when needed.
|
||||
pub fn t_el(s: &str) -> String {
|
||||
@@ -778,3 +715,28 @@ mod shared_escape_parity {
|
||||
assert_eq!(decode_xstring(&encode_xstring("_x000D_\r\0😀")), "_x000D_\r\0😀");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_xstring_parity {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn xstring_preserves_controls_unicode_and_literal_escapes() {
|
||||
// XML-invalid scalars, C1 controls and literal escapes survive save/reopen.
|
||||
for c in (0..=0xffff).filter_map(char::from_u32) {
|
||||
let text = format!("left{c}right_x0041_");
|
||||
assert_eq!(decode_xstring(&encode_xstring(&text)), text);
|
||||
}
|
||||
for (encoded, decoded) in [
|
||||
("_x005F_x000D_", "_x000D_"),
|
||||
("_xD83D__xDE00_", "😀"),
|
||||
("_xD83D__x0041_", "_xD83D_A"),
|
||||
("_xD83D__x005F_xDE00_", "_xD83D__xDE00_"),
|
||||
("_X0041_", "_X0041_"),
|
||||
("_xZZZZ_", "_xZZZZ_"),
|
||||
] {
|
||||
assert_eq!(decode_xstring(encoded), decoded);
|
||||
}
|
||||
assert_eq!(encode_xstring("\r\n\t\0"), "_x000D_\n\t_x0000_");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user