DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
X: Export Text — Text Only and RTF from a story; EPUB/Text export dialogs
Brandon Thomas286823eb9625
diff --git a/ROADMAP.md b/ROADMAP.mdindex 7d4bedd33..8c77e9d87 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -32,6 +32,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Place text files: Word (.docx: styles by name with their attributes, bold/italic/underline/size/font, footnotes, tables, tabs, breaks), RTF and plain text, into the insertion point, the selected frame or a new frame; autoflow adds pages and threaded frames until the text fits; Remove Styles option (`designcraft-textimport`).- Gradient Feather (⇧G tool, `object.gradientFeather`): objects fade along a linear or radial opacity gradient, on screen and as a soft mask in PDF.- Script Label (`object.label`, `object.findByLabel`), alt text (`object.altText`), Isolate Blending / Knockout Group (`object.transparencyGroup`; on screen, PDF isolates), Table ▸ Sort (`table.sortRows`, numeric-aware, header/footer fixed).+- File ▸ Export Text (`file.exportText`): a story as Text Only or RTF (fonts, styles, alignment, indents, tables as tab-separated rows); Export EPUB now asks for a path in the UI.- 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/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rsindex bf24a52cb..f18225f93 100644--- a/crates/engine/src/cmd/export.rs+++ b/crates/engine/src/cmd/export.rs@@ -14,9 +14,39 @@ pub fn specs() -> Vec<CommandSpec> {cmd!(noundo "file.exportEpub", "Export EPUB (Reflowable)…", ["File"], None,"{path?, title?, author?, language?: \"en\"} → {path, bytes} (no path: {base64, bytes})",has_doc, export_epub),+ cmd!(noundo "file.exportText", "Export Text…", ["File"], None,+ "{path?, format?: \"txt\"|\"rtf\" (default from the path, else txt), story?, frame?} — the story being edited or of the selected frame → {path, bytes} (no path: {text, bytes})",+ has_story_target, export_text),]}+fn has_story_target(s: &Session) -> std::result::Result<(), String> {+ super::text::story_of(s, &Value::Null).map(|_| ()).ok_or_else(|| "edit text or select a text frame".into())+}++fn export_text(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "file.exportText";+ let sid = super::text::story_of(s, p).ok_or_else(|| bad(ID, "edit text or select a text frame"))?;+ let doc = &s.doc()?.doc;+ let story = doc.stories.get(&sid).ok_or_else(|| bad(ID, format!("no story {}", sid.0)))?;+ let path = str_param(p, "path");+ let rtf = match str_param(p, "format") {+ Some("rtf") => true,+ Some("txt") | Some("text") => false,+ Some(f) => return Err(bad(ID, format!("unknown format `{f}` (txt, rtf)"))),+ None => path.is_some_and(|x| x.to_ascii_lowercase().ends_with(".rtf")),+ };+ let text = if rtf { designcraft_textimport::export::rtf(doc, story) } else { designcraft_textimport::export::plain_text(story) };+ match path {+ Some(path) => {+ #[cfg(not(target_arch = "wasm32"))]+ std::fs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ Ok(json!({"path": path, "bytes": text.len()}))+ }+ None => Ok(json!({"bytes": text.len(), "text": text})),+ }+}+fn export_epub(s: &mut Session, p: &Value) -> Result<Value> {let st = s.doc()?;let opts = designcraft_epub::EpubOptions {@@ -110,3 +140,26 @@ fn write_file(path: &str, bytes: &[u8]) -> Result<()> {fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {Err(EngineError::Other(format!("{path}: no file system on the web; omit `path` to get the bytes")))}++#[cfg(test)]+mod text_tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn export_story_as_text_and_rtf() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "One\nTwo"})).unwrap();+ assert!(s.execute("file.exportText", &json!({"frame": r["id"]})).unwrap()["text"] == "One\r\nTwo");+ let rtf = s.execute("file.exportText", &json!({"frame": r["id"], "format": "rtf"})).unwrap();+ assert!(rtf["text"].as_str().unwrap().starts_with("{\\rtf1"));+ let dir = std::env::temp_dir().join(format!("dc-export-text-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("story.rtf");+ s.execute("file.exportText", &json!({"frame": r["id"], "path": path.to_string_lossy()})).unwrap();+ assert!(std::fs::read_to_string(&path).unwrap().starts_with("{\\rtf1"));+ std::fs::remove_dir_all(&dir).ok();+ }+}diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rsindex ecc8e5ad3..cd3dfa1e0 100644--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {]}-fn story_of(s: &Session, p: &Value) -> Option<StoryId> {+pub(crate) fn story_of(s: &Session, p: &Value) -> Option<StoryId> {let st = s.active()?;if let Some(v) = p.get("story").and_then(Value::as_u64) {return Some(StoryId(v));diff --git a/crates/textimport/src/export.rs b/crates/textimport/src/export.rsnew file mode 100644index 000000000..f814c1e14--- /dev/null+++ b/crates/textimport/src/export.rs@@ -0,0 +1,208 @@+//! Story → text files (File › Export of a story): Text Only and Rich Text Format.+//!+//! Text Only keeps paragraphs (CRLF), tabs and forced line breaks; tables become tab-separated+//! rows; markers (footnote references, anchors, index marks) are dropped and page-number markers+//! become `#`. RTF also keeps fonts, size, bold/italic, underline, strikethrough,+//! superscript/subscript, alignment, indents and paragraph spacing.++use std::fmt::Write;++use designcraft_doc::story::{FORCED_LINE_BREAK, NEXT_PAGE_NUMBER, PAGE_NUMBER, PREV_PAGE_NUMBER, TABLE_ANCHOR};+use designcraft_doc::{Align, Document, Position, Story};++/// Characters of a run as plain text (`None`: dropped).+fn plain_char(c: char) -> Option<&'static str> {+ match c {+ PAGE_NUMBER | NEXT_PAGE_NUMBER | PREV_PAGE_NUMBER => Some("#"),+ FORCED_LINE_BREAK => Some("\u{2028}"),+ '\u{E000}'..='\u{E0FF}' => None,+ _ => Some(""),+ }+}++fn table_text(story: &Story, id: u64, nl: &str) -> String {+ let Some(t) = story.tables.get(&id) else { return String::new() };+ (0..t.nrows())+ .map(|r| (0..t.ncols()).map(|c| t.cell(r, c).map(|x| x.text.text.replace('\n', " ")).unwrap_or_default()).collect::<Vec<_>>().join("\t"))+ .collect::<Vec<_>>()+ .join(nl)+}++/// Text Only: the story's text, CRLF between paragraphs.+pub fn plain_text(story: &Story) -> String {+ let mut out = String::with_capacity(story.text.len() + 16);+ for (i, r) in story.para_ranges().into_iter().enumerate() {+ if i > 0 {+ out.push_str("\r\n");+ }+ for c in story.text[r].chars() {+ match (c, plain_char(c)) {+ (TABLE_ANCHOR, _) => {+ if let Some(id) = story.paras.get(i).and_then(|p| p.table) {+ out.push_str(&table_text(story, id, "\r\n"));+ }+ }+ (_, Some("")) => out.push(c),+ (_, Some("\u{2028}")) => out.push('\n'),+ (_, Some(s)) => out.push_str(s),+ (_, None) => {}+ }+ }+ }+ out+}++fn rtf_escape(out: &mut String, c: char) {+ match c {+ '\\' | '{' | '}' => {+ out.push('\\');+ out.push(c);+ }+ '\t' => out.push_str("\\tab "),+ FORCED_LINE_BREAK => out.push_str("\\line "),+ c if (c as u32) < 0x80 => out.push(c),+ c => {+ // \uN with a `?` fallback; N is a signed 16-bit value, astral characters as surrogates.+ let mut buf = [0u16; 2];+ for u in c.encode_utf16(&mut buf) {+ let _ = write!(out, "\\u{}?", *u as i16);+ }+ }+ }+}++fn twips(pt: f64) -> i64 {+ (pt * 20.0).round() as i64+}++/// Rich Text Format, with the story's resolved formatting.+pub fn rtf(doc: &Document, story: &Story) -> String {+ let styles = &doc.styles;+ // Resolve every run first so the font table can be written up front.+ let ranges = story.para_ranges();+ let mut paras = Vec::with_capacity(ranges.len());+ let mut fonts: Vec<String> = Vec::new();+ for (i, r) in ranges.iter().enumerate() {+ let pf = story.paras.get(i).cloned().unwrap_or_default();+ let (pp, base) = styles.resolve_para(&pf);+ let mut runs = Vec::new();+ for (rr, f) in story.runs() {+ let (a, b) = (rr.start.max(r.start), rr.end.min(r.end));+ if a >= b {+ continue;+ }+ let cp = styles.resolve_char(&base, f);+ if !fonts.contains(&cp.font_family) {+ fonts.push(cp.font_family.clone());+ }+ runs.push((a..b, cp));+ }+ if runs.is_empty() && !fonts.contains(&base.font_family) {+ fonts.push(base.font_family.clone());+ }+ paras.push((pp, base, pf.table, runs));+ }+ let mut out = String::from("{\\rtf1\\ansi\\ansicpg1252\\uc1\\deff0\n{\\fonttbl");+ for (i, f) in fonts.iter().enumerate() {+ let _ = write!(out, "{{\\f{i}\\fnil ");+ for c in f.chars() {+ rtf_escape(&mut out, c);+ }+ out.push_str(";}");+ }+ out.push_str("}\n");+ for (pp, base, table, runs) in ¶s {+ let q = match pp.align {+ Align::Center => "\\qc",+ Align::Right => "\\qr",+ Align::Left => "\\ql",+ _ => "\\qj",+ };+ let _ = write!(+ out,+ "\\pard{q}\\li{}\\ri{}\\fi{}\\sb{}\\sa{}",+ twips(pp.left_indent),+ twips(pp.right_indent),+ twips(pp.first_line_indent),+ twips(pp.space_before),+ twips(pp.space_after)+ );+ if runs.is_empty() {+ let f = fonts.iter().position(|x| *x == base.font_family).unwrap_or(0);+ let _ = write!(out, "\\plain\\f{f}\\fs{} ", (base.size * 2.0).round() as i64);+ }+ for (r, cp) in runs {+ let f = fonts.iter().position(|x| *x == cp.font_family).unwrap_or(0);+ let st = cp.font_style.to_ascii_lowercase();+ let _ = write!(out, "{{\\plain\\f{f}\\fs{}", (cp.size * 2.0).round() as i64);+ if st.contains("bold") || st.contains("black") || st.contains("heavy") || st.contains("semibold") {+ out.push_str("\\b");+ }+ if st.contains("italic") || st.contains("oblique") {+ out.push_str("\\i");+ }+ if cp.underline {+ out.push_str("\\ul");+ }+ if cp.strikethrough {+ out.push_str("\\strike");+ }+ match cp.position {+ Position::Superscript | Position::OtSuperscript => out.push_str("\\super"),+ Position::Subscript | Position::OtSubscript => out.push_str("\\sub"),+ _ => {}+ }+ out.push(' ');+ for c in story.text[r.clone()].chars() {+ match c {+ TABLE_ANCHOR => {+ if let Some(id) = table {+ for ch in table_text(story, *id, "\u{2028}").chars() {+ rtf_escape(&mut out, ch);+ }+ }+ }+ PAGE_NUMBER | NEXT_PAGE_NUMBER | PREV_PAGE_NUMBER => out.push('#'),+ '\u{E000}'..='\u{E0FF}' => {}+ c => rtf_escape(&mut out, c),+ }+ }+ out.push('}');+ }+ out.push_str("\\par\n");+ }+ out.push('}');+ out+}++#[cfg(test)]+mod tests {+ use designcraft_doc::build::NewDocument;+ use designcraft_doc::{CharAttrs, ParaAttrs, StoryId};++ use super::*;++ fn story() -> Story {+ let mut st = Story::with_text(StoryId(1), "Plain bold {x}\nCafé\u{2028}two\u{E00A}", Default::default());+ let b = st.text.find("bold").unwrap();+ st.format_chars(b..b + 4, |f| f.over = CharAttrs { font_style: Some("Bold".into()), ..Default::default() });+ st.format_paras(0..1, |p| p.para = ParaAttrs { align: Some(Align::Center), ..Default::default() });+ st+ }++ #[test]+ fn text_only() {+ assert_eq!(plain_text(&story()), "Plain bold {x}\r\nCafé\ntwo");+ }++ #[test]+ fn rtf_round_trips_through_the_importer() {+ let doc = Document::new(&NewDocument::default());+ let r = rtf(&doc, &story());+ assert!(r.starts_with("{\\rtf1") && r.contains("\\qc") && r.contains("\\{x\\}") && r.contains("Caf\\u233?"), "{r}");+ let back = crate::rtf::import(r.as_bytes()).unwrap().story;+ assert_eq!(back.text.trim_end_matches('\n'), "Plain bold {x}\nCafé\u{2028}two");+ assert_eq!(back.format_after(back.text.find("bold").unwrap()).over.font_style.as_deref(), Some("Bold"));+ assert_ne!(back.format_after(1).over.font_style.as_deref(), Some("Bold"));+ }+}diff --git a/crates/textimport/src/lib.rs b/crates/textimport/src/lib.rsindex 7cc5aa670..b45653ae1 100644--- a/crates/textimport/src/lib.rs+++ b/crates/textimport/src/lib.rs@@ -8,6 +8,7 @@#![forbid(unsafe_code)]mod docx;+pub mod export;mod rtf;use designcraft_doc::{CharAttrs, ParaAttrs, Story};diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 62006771a..5bb16fb28 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -17,6 +17,8 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[("app.saveSwatches", "Save Swatches for Exchange…", None, "{path?} — write the colour swatches as .ase"),("app.exportPng", "Export Page as PNG…", Some("Cmd+E"), "{}"),("app.exportIdml", "Export IDML…", None, "{path?} — InDesign Markup (IDML) package"),+ ("app.exportEpub", "Export EPUB…", None, "{path?} — reflowable EPUB 3"),+ ("app.exportText", "Export Text…", None, "{path?} — the story being edited, as Text Only (.txt) or Rich Text Format (.rtf)"),("app.exportPdf", "Export PDF…", None, "{path?, …file.exportPdf options} — asks for a path when none is given"),("app.palette", "Quick Apply…", Some("Cmd+Return"), "{} — search styles and commands"),("app.preferences", "Preferences…", Some("Cmd+K"), "{}"),@@ -102,7 +104,8 @@ pub const MENUS: &[(&str, &[&str])] = &["ui:app.packageDialog","ui:app.exportPng","ui:app.exportIdml",- "cmd:file.exportEpub",+ "ui:app.exportEpub",+ "ui:app.exportText",">Export","cmd:snippet.export","<",@@ -492,6 +495,8 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,}"app.exportPng" => export_png(app, p),"app.exportIdml" => export_idml(app, p),+ "app.exportEpub" => export_bytes(app, p, "epub", "file.exportEpub"),+ "app.exportText" => export_bytes(app, p, "rtf", "file.exportText"),"app.packageDialog" => {let name = app.session.active().map(|d| format!("{} Folder", d.doc.title)).unwrap_or_default();match app.services.pick_save.as_mut().and_then(|f| f(&name)) {@@ -892,6 +897,34 @@ fn export_idml(app: &mut DesignApp, p: &Value) -> Result<Value, String> {}}+/// Export EPUB / Text: ask for a path (default extension `ext`), run `cmd` without one and write+/// what it returns (`base64` or `text`) with the platform writer.+fn export_bytes(app: &mut DesignApp, p: &Value, ext: &str, cmd: &str) -> Result<Value, String> {+ let st = app.session.active().ok_or("no document")?;+ let path = match p.get("path").and_then(Value::as_str) {+ Some(s) => Some(s.to_string()),+ None => {+ let name = format!("{}.{ext}", st.doc.title);+ app.services.pick_save.as_mut().and_then(|f| f(&name))+ }+ };+ let Some(path) = path else { return Ok(Value::Null) };+ let mut params = json!({});+ if cmd == "file.exportText" {+ let txt = path.to_ascii_lowercase().ends_with(".txt");+ params["format"] = json!(if txt { "txt" } else { "rtf" });+ }+ let r = app.run(cmd, params)?;+ let bytes = match r["text"].as_str() {+ Some(t) => t.as_bytes().to_vec(),+ None => designcraft_engine::cmd::base64_decode(r["base64"].as_str().unwrap_or_default()),+ };+ match app.services.write.as_mut() {+ Some(w) => w(&path, &bytes).map(|_| json!({"path": path, "bytes": bytes.len()})),+ None => Err("no writer".into()),+ }+}+/// File › Export PDF…: ask for a path, export through `file.exportPdf` and write the bytes with the/// platform writer (a download on the web).fn export_pdf(app: &mut DesignApp, p: &Value) -> Result<Value, String> {diff --git a/docs/parity.md b/docs/parity.mdindex 093ce78ff..3a821cce4 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 | 67 | 26 | 4 | 82% |-| P2 | 76 | 10 | 9 | 57 | 19% |+| P2 | 76 | 10 | 10 | 56 | 20% || Area | Parity ||---|---|@@ -29,7 +29,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia| Tables | 85% || Long documents | 75% || Interactivity & digital | 30% |-| Output & production | 68% |+| Output & production | 70% || XML & automation | 50% || View & navigation | 82% || Undo, history, saving | 100% |@@ -285,7 +285,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t| Output & production | Export JPEG/PNG | P1 | D || Output & production | Export IDML | P0 | D || Output & production | Export EPUB/HTML | P2 | P |-| Output & production | Export RTF/TXT/Tagged text | P2 | M |+| Output & production | Export RTF/TXT/Tagged text | P2 | P || Output & production | Export XML | P2 | M || Output & production | Separations / Flattener / Ink limit preview | P2 | M || XML & automation | Tags panel, Structure | P2 | M |