DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
I: place Excel workbooks as tables
Brandon Thomasdd68539cb069
diff --git a/ROADMAP.md b/ROADMAP.mdindex 150140083..ff642f582 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -51,6 +51,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- File ▸ Print Booklet (`file.printBooklet`): saddle-stitch or 2-up consecutive printer spreads as PDF, padded with blanks, with a gap between pages.- Edit ▸ Transparency Blend Space (`edit.transparencyBlendSpace`; RGB for web/mobile documents; IDML TransparencyPreference) — stored; compositing is still RGB on screen and in PDF.- High Contrast interface theme (fifth Interface Color Theme: black chrome, white text, yellow selection).+- Place Excel workbooks (.xlsx): the first worksheet's used range becomes a table (shared/inline strings, numbers, booleans).- Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).- Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rsindex 90b54bcaa..fc7f2d4ed 100644--- a/apps/designcraft-web/src/web.rs+++ b/apps/designcraft-web/src/web.rs@@ -5,7 +5,8 @@ use designcraft_ui_egui::{DesignApp, Inbox, Services};use wasm_bindgen::JsCast as _;const DOC_EXTS: &[&str] = &["designcraft", "idml"];-const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "psd", "svg", "pdf", "ai", "txt", "docx", "rtf", "md"];+const IMAGE_EXTS: &[&str] =+ &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "psd", "svg", "pdf", "ai", "txt", "docx", "rtf", "md", "xlsx"];const CANVAS_ID: &str = "designcraft_canvas";const LOADING_ID: &str = "designcraft_loading";diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rsindex 6c4582981..a1d753c6a 100644--- a/apps/designcraft/src/main.rs+++ b/apps/designcraft/src/main.rs@@ -86,10 +86,10 @@ fn services() -> Services {} else if purpose == "place" {d.add_filter("Graphics and text",- &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "psd", "svg", "pdf", "ai", "txt", "docx", "rtf", "md"],+ &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "psd", "svg", "pdf", "ai", "txt", "docx", "rtf", "md", "xlsx"],).add_filter("Graphics", &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "psd", "svg", "pdf", "ai"])- .add_filter("Text (Word, RTF, plain)", &["docx", "rtf", "txt", "md"])+ .add_filter("Text (Word, RTF, plain, Excel)", &["docx", "rtf", "txt", "md", "xlsx"])} else {d.add_filter("DesignCraft or IDML", &["designcraft", "idml"]).add_filter("DesignCraft", &["designcraft"])diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rsindex 616f0ae32..14e798cff 100644--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {"Place…",["File"],Some("Cmd+D"),- "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?}",+ "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?}",has_doc,file_place),diff --git a/crates/textimport/src/docx.rs b/crates/textimport/src/docx.rsindex a7f2139b2..048529574 100644--- a/crates/textimport/src/docx.rs+++ b/crates/textimport/src/docx.rs@@ -11,8 +11,8 @@ use crate::{ImportError, Imported, ImportedStyle};/// A minimal element tree (local names, attributes by local name).#[derive(Debug, Default, Clone)]-struct El {- name: String,+pub(crate) struct El {+ pub(crate) name: String,attrs: Vec<(String, String)>,kids: Vec<Node>,}@@ -24,16 +24,16 @@ enum Node {}impl El {- fn attr(&self, k: &str) -> Option<&str> {+ pub(crate) fn attr(&self, k: &str) -> Option<&str> {self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str())}- fn els(&self) -> impl Iterator<Item = &El> {+ pub(crate) fn els(&self) -> impl Iterator<Item = &El> {self.kids.iter().filter_map(|n| if let Node::El(e) = n { Some(e) } else { None })}- fn child(&self, name: &str) -> Option<&El> {+ pub(crate) fn child(&self, name: &str) -> Option<&El> {self.els().find(|e| e.name == name)}- fn text(&self) -> String {+ pub(crate) fn text(&self) -> String {self.kids.iter().map(|n| match n {@@ -56,7 +56,7 @@ fn local(n: &[u8]) -> String {s.rsplit(':').next().unwrap_or(&s).to_string()}-fn parse(xml: &str) -> Result<El, ImportError> {+pub(crate) fn parse(xml: &str) -> Result<El, ImportError> {let mut r = quick_xml::Reader::from_str(xml);let mut stack: Vec<El> = vec![El::default()];loop {@@ -125,7 +125,7 @@ fn parse(xml: &str) -> Result<El, ImportError> {Ok(root.kids.drain(..).find_map(|n| if let Node::El(e) = n { Some(e) } else { None }).unwrap_or_default())}-fn part(zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>, name: &str) -> Option<String> {+pub(crate) fn part(zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>, name: &str) -> Option<String> {let mut f = zip.by_name(name).ok()?;let mut s = String::new();f.read_to_string(&mut s).ok()?;diff --git a/crates/textimport/src/lib.rs b/crates/textimport/src/lib.rsindex b45653ae1..55527decf 100644--- a/crates/textimport/src/lib.rs+++ b/crates/textimport/src/lib.rs@@ -10,6 +10,7 @@mod docx;pub mod export;mod rtf;+mod xlsx;use designcraft_doc::{CharAttrs, ParaAttrs, Story};@@ -50,12 +51,15 @@ impl std::fmt::Display for ImportError {/// Text files this crate reads, by extension.pub fn is_text_file(name: &str) -> bool {let l = name.to_ascii_lowercase();- l.ends_with(".txt") || l.ends_with(".text") || l.ends_with(".md") || l.ends_with(".docx") || l.ends_with(".rtf")+ l.ends_with(".txt") || l.ends_with(".text") || l.ends_with(".md") || l.ends_with(".docx") || l.ends_with(".rtf") || l.ends_with(".xlsx")}/// Import `bytes` (format from the file name, else sniffed).pub fn import(name: &str, bytes: &[u8]) -> Result<Imported, ImportError> {let l = name.to_ascii_lowercase();+ if l.ends_with(".xlsx") {+ return xlsx::import(bytes);+ }if l.ends_with(".docx") || bytes.starts_with(b"PK\x03\x04") {return docx::import(bytes);}diff --git a/crates/textimport/src/xlsx.rs b/crates/textimport/src/xlsx.rsnew file mode 100644index 000000000..f6d0c80a5--- /dev/null+++ b/crates/textimport/src/xlsx.rs@@ -0,0 +1,138 @@+//! Excel workbooks (`.xlsx`) → a story holding one table: the first worksheet's used range, cell+//! values as shown text (shared and inline strings, numbers, booleans).++use designcraft_doc::{CharFormat, ParaFormat, Story, StoryId, Table};++use crate::docx::{El, parse, part};+use crate::{ImportError, Imported};++/// "B12" → (row 11, column 1).+fn cell_ref(r: &str) -> Option<(usize, usize)> {+ let letters: String = r.chars().take_while(|c| c.is_ascii_alphabetic()).collect();+ let row: usize = r[letters.len()..].parse().ok()?;+ let col = letters.chars().try_fold(0usize, |acc, c| Some(acc * 26 + (c.to_ascii_uppercase() as u8).checked_sub(b'A')? as usize + 1))?;+ Some((row.checked_sub(1)?, col.checked_sub(1)?))+}++/// The worksheet part of the first sheet (workbook order), via the workbook relationships.+fn first_sheet(zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>) -> Option<String> {+ let wb = parse(&part(zip, "xl/workbook.xml")?).ok()?;+ let rid = wb.child("sheets")?.els().find(|e| e.name == "sheet")?.attr("id")?.to_string();+ let rels = parse(&part(zip, "xl/_rels/workbook.xml.rels")?).ok()?;+ let target = rels.els().find(|r| r.attr("Id") == Some(rid.as_str()))?.attr("Target")?.trim_start_matches('/').to_string();+ Some(if target.starts_with("xl/") { target } else { format!("xl/{target}") })+}++fn value(c: &El, shared: &[String]) -> String {+ let v = || c.child("v").map(El::text).unwrap_or_default();+ match c.attr("t") {+ Some("s") => v().trim().parse::<usize>().ok().and_then(|i| shared.get(i).cloned()).unwrap_or_default(),+ Some("inlineStr") => c.child("is").map(El::text).unwrap_or_default(),+ Some("b") => {+ if v().trim() == "1" {+ "TRUE".into()+ } else {+ "FALSE".into()+ }+ }+ _ => {+ let raw = v();+ // Whole numbers without the trailing ".0" Excel never shows.+ match raw.trim().parse::<f64>() {+ Ok(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{}", f as i64),+ Ok(f) => format!("{}", (f * 1e10).round() / 1e10),+ Err(_) => raw,+ }+ }+ }+}++pub fn import(bytes: &[u8]) -> Result<Imported, ImportError> {+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| ImportError::Corrupt(e.to_string()))?;+ let sheet_part = first_sheet(&mut zip).unwrap_or_else(|| "xl/worksheets/sheet1.xml".into());+ let sheet = parse(&part(&mut zip, &sheet_part).ok_or_else(|| ImportError::Corrupt(format!("no {sheet_part} (not an Excel workbook)")))?)?;+ let shared: Vec<String> = part(&mut zip, "xl/sharedStrings.xml")+ .map(|x| parse(&x))+ .transpose()?+ .map(|sst| sst.els().filter(|e| e.name == "si").map(El::text).collect())+ .unwrap_or_default();+ let mut cells: Vec<((usize, usize), String)> = Vec::new();+ if let Some(data) = sheet.child("sheetData") {+ for (ri, row) in data.els().filter(|e| e.name == "row").enumerate() {+ for (ci, c) in row.els().filter(|e| e.name == "c").enumerate() {+ let at = c.attr("r").and_then(cell_ref).unwrap_or((ri, ci));+ let v = value(c, &shared);+ if !v.is_empty() {+ cells.push((at, v));+ }+ }+ }+ }+ let mut warnings = Vec::new();+ if cells.is_empty() {+ warnings.push("the worksheet is empty".into());+ }+ // The used range, from the first used row/column.+ let (r0, c0) = cells.iter().fold((usize::MAX, usize::MAX), |(r, c), ((a, b), _)| (r.min(*a), c.min(*b)));+ let (r1, c1) = cells.iter().fold((0, 0), |(r, c), ((a, b), _)| (r.max(*a), c.max(*b)));+ let mut rows: Vec<Vec<String>> = if cells.is_empty() { vec![vec![String::new()]] } else { vec![vec![String::new(); c1 - c0 + 1]; r1 - r0 + 1] };+ for ((r, c), v) in cells {+ rows[r - r0][c - c0] = v;+ }+ const MAX_CELLS: usize = 100_000;+ if rows.len() * rows[0].len() > MAX_CELLS {+ let keep = (MAX_CELLS / rows[0].len()).max(1);+ warnings.push(format!("only the first {keep} rows were placed"));+ rows.truncate(keep);+ }+ let mut story = Story::new(StoryId(0));+ let width = 72.0 * rows[0].len() as f64;+ let t = Table::from_strings(1, &rows, width, &ParaFormat::default(), &CharFormat::default());+ story.insert_table(0, t);+ Ok(Imported { story, para_styles: vec![], char_styles: vec![], warnings })+}++#[cfg(test)]+mod tests {+ use std::io::Write;++ use super::*;++ fn workbook() -> Vec<u8> {+ let mut buf = std::io::Cursor::new(Vec::new());+ {+ let mut z = zip::ZipWriter::new(&mut buf);+ let o = zip::write::SimpleFileOptions::default();+ for (name, body) in [+ (+ "xl/workbook.xml",+ r#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Prices" sheetId="1" r:id="rId1"/></sheets></workbook>"#,+ ),+ (+ "xl/_rels/workbook.xml.rels",+ r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="x" Target="worksheets/sheet1.xml"/></Relationships>"#,+ ),+ ("xl/sharedStrings.xml", r#"<sst><si><t>Item</t></si><si><t>Price</t></si><si><r><t>Te</t></r><r><t>a</t></r></si></sst>"#),+ (+ "xl/worksheets/sheet1.xml",+ r#"<worksheet><sheetData><row r="2"><c r="B2" t="s"><v>0</v></c><c r="C2" t="s"><v>1</v></c></row><row r="3"><c r="B3" t="s"><v>2</v></c><c r="C3"><v>3.5</v></c></row><row r="4"><c r="B4" t="inlineStr"><is><t>Cake</t></is></c><c r="C4"><v>12.0</v></c></row></sheetData></worksheet>"#,+ ),+ ] {+ z.start_file(name, o).unwrap();+ z.write_all(body.as_bytes()).unwrap();+ }+ z.finish().unwrap();+ }+ buf.into_inner()+ }++ #[test]+ fn first_sheet_used_range_becomes_a_table() {+ let imp = import(&workbook()).unwrap();+ let t = imp.story.tables.values().next().expect("a table");+ assert_eq!((t.nrows(), t.ncols()), (3, 2), "the used range B2:C4");+ let cell = |r, c| t.cell(r, c).unwrap().text.text.clone();+ assert_eq!([cell(0, 0), cell(0, 1), cell(1, 0), cell(1, 1), cell(2, 0), cell(2, 1)], ["Item", "Price", "Tea", "3.5", "Cake", "12"]);+ assert_eq!(cell_ref("AA10"), Some((9, 26)));+ }+}diff --git a/docs/parity.md b/docs/parity.mdindex 1b60b89b3..cb57ad02a 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -11,7 +11,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia|---|---|---|---|---|---|| P0 | 102 | 99 | 3 | 0 | 99% || P1 | 97 | 75 | 21 | 1 | 88% |-| P2 | 76 | 20 | 13 | 43 | 35% |+| P2 | 76 | 21 | 13 | 42 | 36% || Area | Parity ||---|---|@@ -26,7 +26,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia| Type & text frames | 92% || Typography | 88% || Styles | 92% |-| Tables | 88% |+| Tables | 92% || Long documents | 88% || Interactivity & digital | 45% || Output & production | 75% |@@ -258,7 +258,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t| Tables | Overset cells | P1 | D || Tables | Tables spanning frames | P1 | D || Tables | Sort table rows | P2 | D |-| Tables | Excel import | P2 | M |+| Tables | Excel import | P2 | D || Tables | Drag to move rows/columns | P2 | M || Long documents | Table of contents | P1 | D || Long documents | Index | P2 | D |