Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

X: inline XML tagging and tag markers

Brandon Thomas55af964ea8c4
diff --git a/ROADMAP.md b/ROADMAP.md
index f415fd01e..1d7e3c715 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -75,7 +75,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame.
- Gridify: arrow keys while dragging a frame or shape tool add columns/rows (`frame.grid`), one undo step.
- Gap tool (U, `gap.move`): drag the space between objects (or an object and the page edge) and both sides resize.
-- XML basics (`xml.newTag/deleteTag/tag/mapStyle/structure`, `file.exportXml`, `file.importXml`; Tags panel with structure; View ▸ Show Tagged Frames): tagged frames export in reading order, mapped paragraph styles become elements, imported elements flow into frames with matching tags. Inline text tagging and DTDs aren't there yet.
+- XML basics (`xml.newTag/deleteTag/tag/mapStyle/structure`, `file.exportXml`, `file.importXml`; Tags panel with structure; View ▸ Show Tagged Frames): tagged frames export in reading order, mapped paragraph styles become elements, imported elements flow into frames with matching tags. Inline text tagging (`xml.tagText`, an `xmlTag` character attribute, exported as nested elements) and tag markers (View ▸ Structure ▸ Show Tag Markers) too; DTD validation isn't there yet.
- Adjust Layout / Layout Adjustment (`adjustLayout` on Document Setup and Margins and Columns): objects follow each page's margin box to its new size and position.
- Content Collector and Placer tools (B; `conveyor.collect/place/list/clear`): copies of objects (with stories, styles, images) ride a conveyor between pages and documents; Alt-click keeps them on it.
- Linked stories (Edit ▸ Place and Link, `story.placeAndLink/links/updateLink/unlink`): child stories copy a parent, show out of date in the Links panel and update.
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index b15112dab..cd13dd5e5 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -60,6 +60,8 @@ pub struct RunStyle {
pub condition: Option<String>,
/// Added while tracking changes (marked on screen).
pub inserted: bool,
+ /// XML element the text is tagged with (tag markers on screen).
+ pub xml_tag: Option<String>,
}
/// An underline or strikethrough bar: its top edge `offset` below the baseline (negative =
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index f0fe37a11..8d4b13b86 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -135,6 +135,7 @@ impl StyleTable<'_> {
custom_tracking: p.tracking.abs() > 1e-9 || matches!(p.kerning, designcraft_doc::Kerning::Manual(_)),
condition: p.conditions.first().cloned(),
inserted: p.change == designcraft_doc::ChangeMark::Inserted,
+ xml_tag: (!p.xml_tag.is_empty()).then(|| p.xml_tag.clone()),
};
if let Some(i) = self.styles.iter().rposition(|s| *s == rs) {
return i as u32;
diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rs
index 9948e2d85..8ed6174bd 100644
--- a/crates/doc/src/attrs.rs
+++ b/crates/doc/src/attrs.rs
@@ -485,6 +485,8 @@ attr_set! {
conditions: Vec<String> = Vec::new(),
/// Track Changes: text added or deleted while tracking (deleted text isn't laid out).
change: ChangeMark = ChangeMark::None,
+ /// XML: the element this text is tagged with (Tags panel, inline).
+ xml_tag: String = String::new(),
}
}
diff --git a/crates/engine/src/cmd/xml.rs b/crates/engine/src/cmd/xml.rs
index cfb55205f..59cd83f93 100644
--- a/crates/engine/src/cmd/xml.rs
+++ b/crates/engine/src/cmd/xml.rs
@@ -46,6 +46,33 @@ fn plain(t: &str) -> String {
t.chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).map(|c| if c == '\u{2028}' { '\n' } else { c }).collect()
}
+/// A paragraph's text with inline-tagged runs as elements.
+fn para_xml(st: &designcraft_doc::Story, r: std::ops::Range<usize>) -> String {
+ let mut out = String::new();
+ let mut open: Option<String> = None;
+ for (rr, f) in st.runs() {
+ let (a, b) = (rr.start.max(r.start), rr.end.min(r.end));
+ if a >= b {
+ continue;
+ }
+ let tag = f.over.xml_tag.clone().filter(|t| !t.is_empty());
+ if tag != open {
+ if let Some(t) = open.take() {
+ out.push_str(&format!("</{t}>"));
+ }
+ if let Some(t) = &tag {
+ out.push_str(&format!("<{t}>"));
+ }
+ open = tag;
+ }
+ out.push_str(&esc(&plain(&st.text[a..b])));
+ }
+ if let Some(t) = open {
+ out.push_str(&format!("</{t}>"));
+ }
+ out
+}
+
/// The document's tagged content as XML.
pub fn export_xml(d: &Document) -> String {
let mut out = format!("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<{}>\n", root_name(d));
@@ -56,19 +83,20 @@ pub fn export_xml(d: &Document) -> String {
Content::Text(tf) => {
let Some(st) = d.story(tf.story) else { continue };
let mapped = |style: &str| d.xml.style_map.iter().find(|(s, _)| s == style).map(|(_, t)| t.clone());
+ // Paragraph text with inline tags already escaped.
let paras: Vec<(Option<String>, String)> =
- st.para_ranges().into_iter().enumerate().map(|(i, r)| (mapped(&st.paras[i].style), plain(&st.text[r]))).collect();
+ st.para_ranges().into_iter().enumerate().map(|(i, r)| (mapped(&st.paras[i].style), para_xml(st, r))).collect();
if paras.iter().any(|(m, _)| m.is_some()) {
out.push_str(&format!(" <{tag}>\n"));
for (m, text) in paras {
match m {
- Some(t) => out.push_str(&format!(" <{t}>{}</{t}>\n", esc(&text))),
- None => out.push_str(&format!(" {}\n", esc(&text))),
+ Some(t) => out.push_str(&format!(" <{t}>{text}</{t}>\n")),
+ None => out.push_str(&format!(" {text}\n")),
}
}
out.push_str(&format!(" </{tag}>\n"));
} else {
- out.push_str(&format!(" <{tag}>{}</{tag}>\n", esc(&paras.into_iter().map(|(_, t)| t).collect::<Vec<_>>().join("\n"))));
+ out.push_str(&format!(" <{tag}>{}</{tag}>\n", paras.into_iter().map(|(_, t)| t).collect::<Vec<_>>().join("\n")));
}
}
Content::Graphic(g) => {
@@ -183,6 +211,27 @@ pub fn specs() -> Vec<CommandSpec> {
ok()
})
}),
+ cmd!("xml.tagText", "Tag Text", [], None, "{tag | null (untag)} — the selected text becomes an inline element", super::has_doc, |s, p| {
+ let tag = str_param(p, "tag").map(str::to_string);
+ if let Some(t) = &tag
+ && !valid_name(t)
+ {
+ return Err(bad("xml.tagText", format!("`{t}` isn't a valid XML name")));
+ }
+ if s.doc()?.selection.text.is_none_or(|t| t.range().is_empty()) {
+ return Err(bad("xml.tagText", "select some text"));
+ }
+ if let Some(t) = &tag {
+ s.edit(|d, _| {
+ if !d.xml.tags.iter().any(|x| x.name == *t) {
+ let color = COLORS[d.xml.tags.len() % COLORS.len()];
+ d.xml.tags.push(XmlTag { name: t.clone(), color });
+ }
+ ok()
+ })?;
+ }
+ s.execute("type.char", &json!({"xmlTag": tag.unwrap_or_default()}))
+ }),
cmd!("xml.tag", "Tag Frame", [], None, "{tag (made if new), ids? (default: the selection)} — `tag: null` untags", has_doc, |s, p| {
let tag = str_param(p, "tag").map(str::to_string);
if let Some(t) = &tag
@@ -380,5 +429,31 @@ mod tests {
assert_eq!(sa.paras[0].style, "Head", "mapped tag → paragraph style");
assert_eq!(d.stories[&designcraft_doc::StoryId(b["story"].as_u64().unwrap())].text, "New caption");
assert!(s.execute("xml.tag", &json!({"tag": "1bad", "ids": [b["id"]]})).is_err());
+ // Inline tagging: part of a paragraph becomes an element.
+ let f = s
+ .execute("frame.create", &json!({"rect": [72, 500, 400, 560], "content": "text", "text": "See the glossary entry", "caret": false}))
+ .unwrap();
+ s.execute("xml.tag", &json!({"tag": "note", "ids": [f["id"]]})).unwrap();
+ s.execute("text.select", &json!({"story": f["story"], "anchor": 8, "focus": 16})).unwrap();
+ s.execute("xml.tagText", &json!({"tag": "term"})).unwrap();
+ let x = s.execute("file.exportXml", &json!({})).unwrap()["text"].as_str().unwrap().to_string();
+ assert!(x.contains("<note>See the <term>glossary</term> entry</note>"), "{x}");
+ // Tag markers draw in the tag's colour (screen view only).
+ let d = s.doc().unwrap().doc.clone();
+ let col = d.xml.tags.iter().find(|t| t.name == "term").unwrap().color;
+ let mut rr = designcraft_render::Renderer::new();
+ rr.threads = 0;
+ let count = |opts: &designcraft_render::RenderOptions, rr: &mut designcraft_render::Renderer| {
+ let img = rr.render_page(&d, &s.cache, 0, 2.0, false, opts).unwrap();
+ img.pixels
+ .chunks_exact(4)
+ .filter(|p| {
+ (p[0] as i32 - col[0] as i32).abs() < 30 && (p[1] as i32 - col[1] as i32).abs() < 30 && (p[2] as i32 - col[2] as i32).abs() < 30
+ })
+ .count()
+ };
+ let plain = count(&Default::default(), &mut rr);
+ let marked = count(&designcraft_render::RenderOptions { tag_markers: true, ..Default::default() }, &mut rr);
+ assert!(marked > plain + 10, "{plain} {marked}");
}
}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index 03df7c417..a1e63965f 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -118,6 +118,8 @@ pub struct RenderOptions {
pub note_indicators: bool,
/// Track Changes: added text highlighted (screen view).
pub change_markup: bool,
+ /// View › Structure › Show Tag Markers: brackets around inline-tagged text (screen view).
+ pub tag_markers: bool,
/// View › Display Performance.
pub quality: DisplayQuality,
/// Preferences › Appearance of Black: show 100% K as rich (pure) black instead of the
@@ -156,6 +158,7 @@ impl Default for RenderOptions {
condition_indicators: false,
note_indicators: false,
change_markup: false,
+ tag_markers: false,
quality: DisplayQuality::High,
rich_black: false,
overprint_preview: false,
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
index 301a7a505..3ab7f7f11 100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@ -234,6 +234,39 @@ impl Renderer {
}
}
}
+ if f.opts.tag_markers && cs.styles.iter().any(|s| s.xml_tag.is_some()) {
+ ctx.set_transform(m);
+ let px = 1.0 / m.determinant().abs().sqrt().max(1e-9);
+ for l in &ft.lines {
+ let tag_of = |g: &designcraft_compose::PlacedGlyph| cs.styles.get(g.style as usize).and_then(|s| s.xml_tag.clone());
+ let gs: Vec<_> = l.glyphs.iter().filter(|g| g.len > 0).collect();
+ let mut i = 0;
+ while i < gs.len() {
+ let Some(tag) = tag_of(gs[i]) else {
+ i += 1;
+ continue;
+ };
+ let mut j = i + 1;
+ while j < gs.len() && tag_of(gs[j]).as_deref() == Some(tag.as_str()) {
+ j += 1;
+ }
+ let c = f.doc.xml.tags.iter().find(|t| t.name == tag).map_or([100, 100, 220], |t| t.color);
+ ctx.set_paint(peniko::Color::from_rgb8(c[0], c[1], c[2]));
+ let (x0, x1) = (gs[i].x, gs[j - 1].x + gs[j - 1].adv);
+ let (top, bot) = (l.baseline - l.ascent, l.baseline + l.descent);
+ let (w, t) = (2.5 * px, px.max(0.3));
+ // [ before the element, ] after it.
+ for (x, dir) in [(x0, 1.0), (x1, -1.0)] {
+ ctx.fill_rect(&kurbo::Rect::new(x - t / 2.0, top, x + t / 2.0, bot));
+ for y in [top, bot - t] {
+ let (a, b) = if dir > 0.0 { (x, x + w) } else { (x - w, x) };
+ ctx.fill_rect(&kurbo::Rect::new(a, y, b, y + t));
+ }
+ }
+ i = j;
+ }
+ }
+ }
if f.opts.change_markup && cs.styles.iter().any(|s| s.inserted) {
ctx.set_transform(m);
for l in &ft.lines {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 2019e6718..f649647fc 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -413,6 +413,7 @@ fn render_texture(app: &mut DesignApp, ctx: &egui::Context, rect: Rect, xf: &Xf,
condition_indicators: !preview,
note_indicators: !preview && app.session.prefs.show_note_anchors,
change_markup: !preview && app.session.prefs.show_added_text,
+ tag_markers: !preview && app.ui.tag_markers,
highlight_keeps: !preview && app.session.prefs.highlight_keeps,
highlight_custom_tracking: !preview && app.session.prefs.highlight_custom_tracking,
quality: app.ui.display_quality,
@@ -524,6 +525,7 @@ fn patch_texture(app: &mut DesignApp, layout: &CanvasLayout, ppp: f64, doc_key:
condition_indicators: !preview,
note_indicators: !preview && app.session.prefs.show_note_anchors,
change_markup: !preview && app.session.prefs.show_added_text,
+ tag_markers: !preview && app.ui.tag_markers,
highlight_keeps: !preview && app.session.prefs.highlight_keeps,
highlight_custom_tracking: !preview && app.session.prefs.highlight_custom_tracking,
quality: app.ui.display_quality,
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 2de24547e..b9436be66 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -103,6 +103,8 @@ pub struct UiState {
/// Edit › Menus: hidden menu items (`menu/label`), and Show Full Menus.
pub hidden_menu_items: Vec<String>,
pub show_full_menus: bool,
+ /// View › Structure › Show Tag Markers.
+ pub tag_markers: bool,
/// View › Flattener Preview: objects that involve transparency highlighted in red.
#[serde(skip)]
pub flattener_preview: bool,
@@ -189,6 +191,7 @@ impl Default for UiState {
hidden_menu_items: Vec::new(),
show_full_menus: false,
story_editor_size: 14.0,
+ tag_markers: false,
flattener_preview: false,
hidden_panels: 0,
color_settings: None,
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 85cddcab9..7cb9f5ff4 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -79,6 +79,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("window.nextDocument", "Next Document", Some("Cmd+F6"), "{}"),
("window.previousDocument", "Previous Document", Some("Cmd+Shift+F6"), "{}"),
("app.layerOptions", "Object Layer Options…", None, "{} — show or hide the layers of the selected placed PDF"),
+ ("view.tagMarkers", "Show Tag Markers", None, "{on?: bool} — brackets around inline-tagged text"),
("view.flattenerPreview", "Flattener Preview", None, "{on?: bool} — highlight objects that involve transparency"),
("view.rotateSpread", "Rotate Spread", None, "{angle: 90 (clockwise) | -90 | 180 | 0 (clear)} — turn the view in quarter turns"),
("view.proofColors", "Proof Colors", None, "{on?: bool} — simulate the proof target on screen"),
@@ -356,6 +357,7 @@ pub const MENUS: &[(&str, &[&str])] = &[
"<",
"ui:view.proofColors",
"ui:view.flattenerPreview",
+ "ui:view.tagMarkers",
">Separations Preview",
"ui:view.separations|Off|{\"plate\": null, \"inkLimit\": null}",
"ui:view.separations|Cyan|{\"plate\": \"cyan\"}",
@@ -1179,6 +1181,10 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
}
"window.controlBar" => flag(&mut app.ui.control_bar),
"view.flattenerPreview" => flag(&mut app.ui.flattener_preview),
+ "view.tagMarkers" => {
+ app.canvas.shown = None;
+ flag(&mut app.ui.tag_markers)
+ }
"edit.dynamicSpelling" => flag(&mut app.ui.dynamic_spelling),
"window.split" | "window.newWindow" => {
let on = if id == "window.newWindow" { true } else { p.get("on").and_then(Value::as_bool).unwrap_or(!app.split) };
@@ -1573,6 +1579,7 @@ pub fn checked(app: &DesignApp, id: &str, params: &Value) -> Option<bool> {
"window.split" => app.split,
"view.proofColors" => app.ui.proof_colors,
"view.flattenerPreview" => app.ui.flattener_preview,
+ "view.tagMarkers" => app.ui.tag_markers,
"view.rotateSpread" => match params.get("angle").and_then(Value::as_i64) {
Some(0) => app.view().is_some_and(|v| v.rotation == 0),
_ => return None,
diff --git a/crates/ui-egui/src/panels/interactive.rs b/crates/ui-egui/src/panels/interactive.rs
index 6ef1109de..34d002f96 100644
--- a/crates/ui-egui/src/panels/interactive.rs
+++ b/crates/ui-egui/src/panels/interactive.rs
@@ -120,6 +120,8 @@ pub fn tags(app: &mut DesignApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let Ok(info) = app.session.execute("xml.tags", &json!({})) else { return };
let has_sel = app.session.active().is_some_and(|d| !d.selection.items.is_empty());
+ // Selected text is tagged inline instead of its frame.
+ let text_sel = app.session.active().and_then(|d| d.selection.text).is_some_and(|t| !t.range().is_empty());
let id = egui::Id::new("new_tag_name");
let mut name: String = ui.data(|d| d.get_temp(id)).unwrap_or_default();
ui.horizontal(|ui| {
@@ -140,8 +142,8 @@ pub fn tags(app: &mut DesignApp, ui: &mut egui::Ui) {
if c.len() == 3 {
ui.painter().rect_filled(r, 2.0, egui::Color32::from_rgb(c[0], c[1], c[2]));
}
- if ui.add_enabled(has_sel, egui::Button::new(&n).frame(false)).on_hover_text("Tag the selection").clicked() {
- let _ = app.run("xml.tag", json!({"tag": n}));
+ if ui.add_enabled(has_sel || text_sel, egui::Button::new(&n).frame(false)).on_hover_text("Tag the selection").clicked() {
+ let _ = if text_sel { app.run("xml.tagText", json!({"tag": n})) } else { app.run("xml.tag", json!({"tag": n})) };
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button("Delete").clicked() {
@@ -150,8 +152,12 @@ pub fn tags(app: &mut DesignApp, ui: &mut egui::Ui) {
});
});
}
- if has_sel && ui.small_button("Untag Selection").clicked() {
- let _ = app.run("xml.tag", json!({"tag": null}));
+ if (has_sel || text_sel) && ui.small_button("Untag Selection").clicked() {
+ let _ = if text_sel { app.run("xml.tagText", json!({"tag": null})) } else { app.run("xml.tag", json!({"tag": null})) };
+ }
+ let mut markers = app.ui.tag_markers;
+ if ui.checkbox(&mut markers, "Show Tag Markers").changed() {
+ let _ = app.run("view.tagMarkers", json!({"on": markers}));
}
ui.separator();
ui.label(egui::RichText::new("Structure").strong());
diff --git a/docs/parity.md b/docs/parity.md
index f3c923ae9..58e629aa3 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -5,13 +5,13 @@ The summary is generated by `cargo xtask parity` from the table at the bottom of
Each row of the InDesign feature catalogue is scored **D** (done), **P** (partial: works but lacks options or UI) or **M** (missing), weighted by priority (**P0** core = 3, **P1** = 2, **P2** = 1). Out-of-scope rows (Adobe cloud services, plug-ins, Typekit, Flash) are excluded.
<!-- SUMMARY -->
-**Weighted breadth parity: 97%** over 275 features.
+**Weighted breadth parity: 98%** over 275 features.
| Priority | Features | Done | Partial | Missing | Parity |
|---|---|---|---|---|---|
| P0 | 102 | 100 | 2 | 0 | 99% |
| P1 | 97 | 94 | 3 | 0 | 98% |
-| P2 | 76 | 57 | 19 | 0 | 88% |
+| P2 | 76 | 60 | 16 | 0 | 89% |
| Area | Parity |
|---|---|
@@ -29,9 +29,9 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
| Tables | 98% |
| Long documents | 100% |
| Interactivity & digital | 90% |
-| Output & production | 88% |
-| XML & automation | 83% |
-| View & navigation | 96% |
+| Output & production | 90% |
+| XML & automation | 89% |
+| View & navigation | 98% |
| Undo, history, saving | 100% |
| Accessibility | 100% |
@@ -286,9 +286,9 @@ Open P0 items: Vector/page formats (PDF/AI/SVG/EPS place), Export to PDF (print)
| Output & production | Export IDML | P0 | D |
| Output & production | Export EPUB/HTML | P2 | D |
| Output & production | Export RTF/TXT/Tagged text | P2 | D |
-| Output & production | Export XML | P2 | P |
+| Output & production | Export XML | P2 | D |
| Output & production | Separations / Flattener / Ink limit preview | P2 | D |
-| XML & automation | Tags panel, Structure | P2 | P |
+| XML & automation | Tags panel, Structure | P2 | D |
| XML & automation | Import/Export XML | P2 | P |
| XML & automation | Data Merge | P2 | D |
| XML & automation | Scripts panel | P2 | P |
@@ -303,7 +303,7 @@ Open P0 items: Vector/page formats (PDF/AI/SVG/EPS place), Export to PDF (print)
| View & navigation | Overprint preview | P1 | D |
| View & navigation | Rulers, guides, grids toggles | P0 | D |
| View & navigation | Show/hide frame edges, threads, hidden chars | P0 | D |
-| View & navigation | Structure / tag markers | P2 | P |
+| View & navigation | Structure / tag markers | P2 | D |
| View & navigation | Display performance | P0 | D |
| View & navigation | Navigate pages | P0 | D |
| View & navigation | Split window | P2 | D |