Files
designcraft/crates/engine/src/cmd/xml.rs
T
aiongg 18ae8e4761 Merge upstream main a184db6f8 with our 15 PRs (batch-0) into next
Conflicts resolved per file (both sides kept unless noted):
crates/engine/src/atomic.rs | 1 | main's: `write_file` removed (main routes command writes through `crate::io::write_file`); its one caller in file.rs now uses `crate::io::write_file`
crates/engine/src/cmd/datamerge/fill.rs | 1 | next's `Graphic` literal (has `clip` and `wrap`, which next's `Graphic` carries)
crates/engine/src/cmd/datamerge/mod.rs | 1 | main's `read_path_capped` (crate::io metadata/read_capped, roots checked); next's capped read is the same behaviour
crates/engine/src/cmd/datamerge/parse.rs | 1 | main's (`crate::io::metadata`, `crate::io::Metadata`)
crates/engine/src/cmd/edit.rs | 1 | next's `spread_param(p, "edit.paste")` (the second argument is the command id on both sides)
crates/engine/src/cmd/export.rs | 3 | main's: EPUB params doc, `toc_title` once (main's position; next's duplicate dropped)
crates/engine/src/cmd/file.rs | 7 | place doc: next's (lists page/rect/autoflow params #803 checks); next's recent-file functions + main's `foreign_document`; next's open (load_bytes, warnings, non-DesignCraft refusal) with main's checked `crate::io::read_file` for the bytes; main's `check_write` be
crates/engine/src/cmd/find.rs | 7 | main's Find scope (FindContext, scope/selection/story, continuation, UTF-8 repair) on next's `designcraft_compose::grep::Grep` (dialect GREP): find uses `find_all` capped at MAX_MATCHES, change uses `replacements`/`find_all` (literal change text not expanded), fin
crates/engine/src/cmd/fonts.rs | 1 | next's (`has_style`, resolved/replacement face); `has_style` already compares styles ignoring spacing and case, which is main's `same_style` fix; main's test kept
crates/engine/src/cmd/interchange.rs | 1 | next's `import_idml_report_with_previews` (previews for unreadable links)
crates/engine/src/cmd/layout.rs | 8 | pages.insert: main's overflow-safe `after` + next's checked `parent_ref`; main's duplicateSpread doc; layout.section: next's `SectionEdit` (already keeps unnamed settings, #717) with main's `d.repaginate()` moved into `SectionEdit::apply` (remove and set paths),
crates/engine/src/cmd/links.rs | 5 | next's links.list (no doc clone); main's `text_status` via crate::io; `use std::io::Read` dropped (unused after main's read_capped); test literals main's. `link_missing` (next) uses `crate::io::exists` for the file-guard scan
crates/engine/src/cmd/object.rs | 4 | object.fill/stroke tint-alone: main's (23e1680e7; out-of-range tint is an error, which main's test asserts); object.fit doc: next's (lists `axis`)
crates/engine/src/cmd/paths.rs | 1 | next's (shatai transform on outlines)
crates/engine/src/cmd/place_text.rs | 1 | next's `add_flow_frame` (used by autoflow)
crates/engine/src/cmd/preflight.rs | 2 | next's overset/unplacedStory issue (its `overset_location` already applies the parent transform main's #738 fix adds); next's two test modules kept with main's
crates/engine/src/cmd/scripts.rs | 1 | combined: next's `in_undo_step = false` (#406) + main's full rollback of a failed script (#709)
crates/engine/src/cmd/style.rs | 14 | param docs next's (gradient swatch.create, swatch stops, model colours); create_para next's; rename_style main's structure (rename entry, then `redirect_style_refs`), redirect has next's full reference set (cells, defaults, notes, TOC) + main's never-based-on-it
crates/engine/src/cmd/text.rs | 10 | main's selectSentence/Paragraph/Story + select_around; next's selectionAttrs (mixed) + main's openTypeFeatures/type.feature; main's comments; tracked typing: next's `reserve_command_text` + main's `insert_format_at`; empty-paragraph mark formatting main's (with `
crates/engine/src/cmd/thread.rs | 1 | next's `spread_param(p, "text.thread")`
crates/engine/src/dtd.rs | 1 | next's linear, depth-bounded `expand_parameter_entities` with main's budget (input + 1 MiB, `MAX_EXPANDED_BYTES`) and message ("expand the DTD beyond"); 16 MiB constant removed; both sides' tests pass on message
crates/engine/src/guard.rs | 2 | main's whole-transaction snapshot (docs, active, journal; #742) + next's `in_undo_step` restore; tests both
crates/engine/src/lib.rs | 5 | LoadedGraphic doc next's; next's `new_document_preview`; execute: main's `discard_stale_find_scope()` before next's nested-undo run; modules both (tests_autosize, tests_file_guard, tests_params, tests_roots)
crates/engine/src/recovery.rs | 1 | next's test (superset of main's assertion)
crates/engine/src/tests.rs | 4 | moved tests deduplicated (identical on both sides); next's preflight and direct-selection/kerning tests + main's style-delete, locked-frame and baseline-fit tests
crates/engine/src/tests_idml.rs | 3 | main's order (drop cap and margins tests identical on both sides, once each)
crates/ui-egui/src/canvas.rs | 3 | next's screen_options/DisplayKey block and tests kept; two tests that auto-merge had added twice (parent_guides_on_a_page_are_not_picked_there, baseline_grid_lines_are_the_ones_on_the_page) kept once; main's `typing`/`screen_at`/`click` helpers and its tests clicks
crates/ui-egui/src/control.rs | 3 | main's `count` check and pending budget (control queue + synthetic queue); exact-budget test runs both sides' cases (click 255 on 9,492 pending; drag 9492×255)
crates/ui-egui/src/cursors.rs | 1 | main's (same Pen cursor set)
crates/ui-egui/src/dialogs.rs | 14 | dialog body (newDocument … alert match) is next's text, with main's Find/Change scope reset (`set_field`, `reset_find_scope`, `find_change_params`) and main's Create Guides / Margins and Columns arms ported in; `Dialog::new` ruby section (next) + main's `set_fi
crates/ui-egui/src/i18n.rs | 7 | ka and pl modules, languages, statics and lookups both; `category_first` covers uk, ru, pl, ka and `count_label` keeps next's Czech plurals; shared TABLE union; next's duplicate rows for Auto, Number:, Gutter:, Top:, Bottom:, Inside:, Outside:, Left:, Right: dropped
crates/ui-egui/src/i18n/ar.rs | 2 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/it.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/ja.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/pt_br.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/uk.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/icons.rs | 2 | both tests (main's typography icon, next's distribute icons)
crates/ui-egui/src/lib.rs | 11 | UiState: next's tabs_panel + main's last_color/last_gradient; `cursors` field once; next's SVG paste and paste-on-spread-in-view; next's extensionless document open; opens_as_document next's comment; tests both (next's control bar / key-name tests, main's rich black
crates/ui-egui/src/menus.rs | 15 | app.language doc next's text with pl and ka; UI_COMMANDS both (next's Tabs, Toggle Presentation, Apply None text; main's panel commands, Apply Color, Apply Gradient); Edit › Interface Language stays out (next moved it to Preferences); Type menu main's order with
crates/ui-egui/src/panels/glyphs.rs | 1 | next's (already has main's scroll-bar fix); the scroll-bar test module auto-merge had added twice kept once
crates/ui-egui/src/panels/layers.rs | 3 | next's drag-and-drop `object_rows`, with main's features ported into it: selection reveal (layer opens, row scrolls into view once), selected rows highlighted (also a group whose member is selected), double-click rename in place (`object.rename` queued like
crates/ui-egui/src/panels/mod.rs | 6 | tabs + typography modules and color_panel_tests; SelInfo has wrap_side/wrap_contour and wrap_offsets (offsets from the graphic's own wrap when it is selected); next's swatch_picker returning the chip response; next's content_selection_tests
crates/ui-egui/src/panels/pages.rs | 1 | next's (parents dragged by id)
crates/ui-egui/src/panels/properties.rs | 4 | next's swatch popup (Apply To, Tint); main's four wrap offsets then next's Wrap To / Contour Type; test fixtures main's (`..Default::default()`, no unused builder)
crates/ui-egui/src/panels/swatches.rs | 3 | main's Delete Swatch button + next's New Swatch comment; next's draggable rows; click: main's PICKED + fill/stroke in front, with next's no-apply on double-click
crates/ui-egui/src/toolbar.rs | 2 | main's Apply Color / Gradient / None wells and functions; next's apply_none doc line
crates/compose/src/lib.rs | 5 | next's line loop kept (mark_leading + last_line_mark, wrap segments/carry, grid gyoudori); main's mark-chars base_leading block (auto-merged) stays beside it. `fits`: next's #106 rule (baseline fit for horizontal frames, full descent for paths, vertical text, footnote
crates/compose/src/tests.rs | 5 | next's tests (tombstone set, sliver/one-sided/contour/clipping wrap tests, borders, lists, kenten, grid, anchored wrap, balance, shaped frames) plus main's an_empty_last_paragraph_isnt_overset; main's wrap_object_beside_one_narrow_column_leaves_the_other_alone re-ad
crates/doc/src/assets.rs | 1 | main's doc comment (same meaning)
crates/doc/src/build.rs | 3 | parent_page_for: next's parent_page_for_side (RTL-aware); single_sided_page_shows_first_parent_page test kept once, at main's position
crates/doc/src/item.rs | 1 | next's rotated_group_bounds_follow_the_children_outlines test kept
crates/doc/src/lib.rs | 1 | next's kerning_increment field kept; main's "Bulleted & Numbered" wording
crates/doc/src/page.rs | 1 | next's outer_page_indices + parent_page_for_side (integration of parent-margins with rtl-master-sides); main's parent_page_index dropped, its only caller (build.rs) uses parent_page_for_side
crates/doc/src/slice.rs | 5 | extract: next's `marked()` (get-based, fix_notes/fix_endnotes/fix_marks; main's version indexed slices and could panic); insert_story: main's take() limit on endnote/editorial payload copies with next's id comment, redundant `let ne`/`let nn` dropped; main's excess_note
crates/geom/src/corners.rs | 1 | next's box_outline_rounds_only_closed_corners test kept
crates/render/src/damage.rs | 1 | next's wrapping-anchored-object damage test kept
crates/render/src/fx.rs | 2 | feather: next's choke/corners sigma+join inside main's structure (body and clip at device resolution, with_filters(.., None)); inner glow centre: next's blend `mix` with main's clip argument (bp, xf)
crates/render/src/lib.rs | 3 | next's layer comment; next's front baseline grid draw after items; gradient match on g.kind (main's tuple scrutinee did not match the single-pattern arms)
crates/render/src/text.rs | 5 | paint_glyphs: main's paint_stroke closure structure with next's stroke overprint (overprinting helper, stroke `(TextPaint, bool)`); callers pass next's overprint_fill/overprint_stroke
crates/render/tests/placed_pdf.rs | 1 | main's `near` helper version
crates/tools/src/lib.rs | 1 | main's (PenConvert already declared below, avoids a duplicate variant)
crates/tools/src/pen.rs | 1 | main's module doc
crates/tools/src/select.rs | 1 | next's Drag::Corner variant (live corners) kept
crates/tools/src/tests.rs | 4 | next's tests (content drag, live corners, table border drag, eyedropper matchFrom, fitting handles, pen cursors once); eyedropper_ignores_inactive keeps next's samples_image check (main's exact-JSON compare lacks matchFrom) with main's `..Default::default()` Asset lit
crates/tools/src/text.rs | 2 | next's table border drag (BorderDrag, border_at) kept, then main's comment on locked text frames
crates/tools/src/xform.rs | 2 | main's explicit `Vec<&Item>` for shown children; next's eyedropper matchFrom (integration 796e9d713)
Cargo.toml | 2 | main's craft-pdf workspace dep added (craft-print stays once, in next's craft-libs block); [patch.crates-io] keeps next's winit (rust-windowing #4694 backport) and adds main's krilla patch; main's skylartaylor winit left out (see UNSURE 1)
Cargo.lock | 1 | union: next's craft-atomic and craft-cms entries plus main's craft-pdf entry; needs `cargo` normalisation
README.md | 1 | Open bullet combines INDD import via indd-utils (next) and editable PowerPoint export (main); main's paragraph break kept
contributors/people.toml | 1 | both people kept (switch87 from next, Nmarello from main)
apps/designcraft-cli/src/main.rs | 4 | next's `Export` enum dispatch kept; main's .pptx export added as `Export::Pptx` (run prints slides and warnings, script runs file.exportPptx); main's `--pdf-options` null-as-{} parse; usage lines list .pptx
apps/designcraft/src/main.rs | 3 | `startup.leave()` right after `app.ui` (main #380) and next's macOS `sync_movable` kept after the IME discard; next's Apple Events install kept; main's macOS Dock Quit `with_close_requested_on_terminate` block left out (needs the skylartaylor winit; UNSURE 1)
crates/fonts/src/fontdb.rs | 9 | FONT6 aliases (next) combined with #911 WWS names (main): ScannedFace and both CatalogEntry constructors carry `wws` and `aliases`; `canonical_family` falls back to WWS family names; `exact_style_traits` canonicalises then tries typographic, then WWS names (`named_st
crates/format/src/lib.rs | 1 | tests: both sides kept (next's r7a nullable-default tests; main's oversized ZIP entry/asset/entry-count tests)
crates/idml/src/import.rs | 11 | main's bounded `Package` reader under next's `import_idml_report_with_previews` (metadata read through `pkg.part`); next's `tab_list_repaired` kept; ruler origin: next's `settings.ruler_origin`, and main's guide import reads it (main's private `RulerOrigin` enum and
crates/idml/src/tests.rs | 6 | item-level union: all next tests plus main's new ones (ruler guides, package limits, CJK leading model, liquid page rules module, mojikumi); no test dropped
crates/mcp/src/backend.rs | 1 | test comment merged from both
crates/pdf/src/tests.rs | 1 | tests: both sides kept
crates/pdf/src/text.rs | 4 | next's (skew `tan`, cluster `start`, ruby overprint warning); main had no change here beyond base
crates/textimport/src/docx.rs | 5 | next's (ListCounter integration for list levels, page-break test position); main's side was the older form of the same code
crates/epub/src/lib.rs | 30 | non-test code is next's (StoryWriter holds img_src/images/no_alt/heading_ids; covers main's #787/#791/#782 fixes, plus #314 group transforms, anchored images in images_without_alt, endnote story skipped in the TOC); tests: next's set plus main's extra css_weight_style a
docs/control-protocol.md | 2 | next's rows (ui.paste, count 1–255, documentGrid) and wording
docs/file-format-parity.md | 1 | rows combined (next's ICC notes, main's TIFF indexed colour)
docs/gaps.md | 2 | status change notes unioned; Flex Layout removed from missing (main implemented it), next's Parent Options sentence kept
docs/localization-parity.md | 4 | Polish and Georgian rows; 5 languages beyond the twelve; file list includes cs and ka; both history rows
docs/roadmap.md | 1 | M1 next's (#186 fixed on next), M2 main's IME wording
docs/target-app-parity.md | 6 | next's status line; File formats row next's, UI/UX row main's (IME no longer failing); UI line next's plus main's Swatches detail; one Page tool line (main's fuller one); Load styles and main's fuller Pathfinder line both kept, main's duplicate short Pathfinder line r
docs/ui-parity.md | 1 | IME row main's, Font menu row next's

i18n/fr.rs: five rows dropped that main's shared table now has (Row, Open Path, Flex Layout, Current Page Number, Rulers).
2026-10-16 03:09:22 +00:00

547 lines
25 KiB
Rust

//! Structure and XML: tags on frames (Tags panel), paragraph styles mapped to tags, the structure
//! tree, XML export and import (content flows into the frames with matching tags).
use designcraft_doc::{Content, Document, Item, ItemId, ParaFormat, Story, StoryId, XmlTag};
use serde_json::{Value, json};
use super::{CommandSpec, bad, cmd, has_doc, ids_param, ok, str_param};
use crate::{Result, Session};
const COLORS: [[u8; 3]; 6] = [[230, 120, 40], [60, 140, 220], [70, 170, 90], [200, 70, 160], [150, 110, 220], [200, 170, 40]];
fn root_name(d: &Document) -> String {
if d.xml.root.is_empty() { "Root".into() } else { d.xml.root.clone() }
}
fn valid_name(n: &str) -> bool {
let mut c = n.chars();
c.next().is_some_and(|f| f.is_alphabetic() || f == '_') && n.chars().all(|ch| ch.is_alphanumeric() || matches!(ch, '_' | '-' | '.'))
}
/// Tagged objects in reading order (pages, then top to bottom, left to right), nested ones included.
fn tagged(d: &Document) -> Vec<ItemId> {
let mut keyed: Vec<((usize, i64, i64), ItemId)> = Vec::new();
for (si, sp) in d.spreads.iter().enumerate() {
let first = d.first_page_of_spread(si);
for top in &sp.items {
top.walk(&mut |it: &Item| {
if !it.xml_tag.is_empty() {
let b = it.bounds();
let page = first + sp.page_at_x(b.center().x).unwrap_or(0);
keyed.push(((page, (b.y0 * 10.0) as i64, (b.x0 * 10.0) as i64), it.id));
}
});
}
}
keyed.sort_by_key(|(k, _)| *k);
keyed.into_iter().map(|(_, i)| i).collect()
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
/// Plain text of a story (markers dropped, forced breaks as newlines).
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));
for id in tagged(d) {
let Some(it) = d.item(id) else { continue };
let tag = &it.xml_tag;
match &it.content {
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), 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}>{text}</{t}>\n")),
None => out.push_str(&format!(" {text}\n")),
}
}
out.push_str(&format!(" </{tag}>\n"));
} else {
out.push_str(&format!(" <{tag}>{}</{tag}>\n", paras.into_iter().map(|(_, t)| t).collect::<Vec<_>>().join("\n")));
}
}
Content::Graphic(g) => {
let name = d.assets.get(&g.asset).map(|a| a.link.clone().unwrap_or_else(|| a.name.clone())).unwrap_or_default();
out.push_str(&format!(" <{tag} href=\"file://{}\"/>\n", esc(&name)));
}
_ => out.push_str(&format!(" <{tag}/>\n")),
}
}
out.push_str(&format!("</{}>\n", root_name(d)));
out
}
/// One element under the root: its name and either text or (child name, text) paragraphs.
struct Element {
name: String,
text: String,
children: Vec<(String, String)>,
}
fn parse(xml: &str) -> std::result::Result<Vec<Element>, String> {
use quick_xml::events::Event;
let mut r = quick_xml::Reader::from_str(xml);
let mut depth = 0usize;
let mut out: Vec<Element> = Vec::new();
let mut child: Option<(String, String)> = None;
loop {
match r.read_event().map_err(|e| e.to_string())? {
Event::Start(e) => {
depth += 1;
let name = String::from_utf8_lossy(e.local_name().as_ref()).to_string();
match depth {
2 => out.push(Element { name, text: String::new(), children: vec![] }),
3 => child = Some((name, String::new())),
_ => {}
}
}
Event::Empty(e) if depth == 1 => {
out.push(Element { name: String::from_utf8_lossy(e.local_name().as_ref()).to_string(), text: String::new(), children: vec![] });
}
ev @ (Event::Text(_) | Event::GeneralRef(_) | Event::CData(_)) => {
let s = match ev {
Event::Text(t) => t.decode().map_err(|e| e.to_string())?.to_string(),
Event::CData(t) => String::from_utf8_lossy(&t).to_string(),
Event::GeneralRef(g) => match g.resolve_char_ref().map_err(|e| e.to_string())? {
Some(c) => c.to_string(),
None => match g.decode().map_err(|e| e.to_string())?.as_ref() {
"amp" => "&".into(),
"lt" => "<".into(),
"gt" => ">".into(),
"quot" => "\"".into(),
"apos" => "'".into(),
_ => String::new(),
},
},
_ => String::new(),
};
match (depth, child.as_mut(), out.last_mut()) {
(3, Some(c), _) => c.1.push_str(&s),
(2, _, Some(el)) => el.text.push_str(&s),
_ => {}
}
}
Event::End(_) => {
if depth == 3
&& let (Some(c), Some(el)) = (child.take(), out.last_mut())
{
el.children.push(c);
}
depth = depth.saturating_sub(1);
}
Event::Eof => break,
_ => {}
}
}
Ok(out)
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "xml.tags", "Tags", [], None, "{} → {root, tags: [{name, color}], styleMap: [[style, tag]], dtd: bool}", has_doc, |s, _| {
let d = &s.doc()?.doc;
Ok(json!({"root": root_name(d), "tags": d.xml.tags, "styleMap": d.xml.style_map, "dtd": !d.xml.dtd.is_empty()}))
}),
cmd!("xml.newTag", "New Tag", ["Window", "Utilities", "Tags"], None, "{name, color?: [r, g, b]}", has_doc, |s, p| {
let name = str_param(p, "name").unwrap_or("").trim().to_string();
if !valid_name(&name) {
return Err(bad("xml.newTag", format!("`{name}` isn't a valid XML name")));
}
s.edit(|d, _| {
if !d.xml.tags.iter().any(|t| t.name == name) {
let color = COLORS[d.xml.tags.len() % COLORS.len()];
d.xml.tags.push(XmlTag { name: name.clone(), color });
}
Ok(json!({"name": name}))
})
}),
cmd!("xml.deleteTag", "Delete Tag", [], None, "{name} — tagged objects are untagged", has_doc, |s, p| {
let name = str_param(p, "name").unwrap_or("").to_string();
let ids: Vec<ItemId> = {
let d = &s.doc()?.doc;
tagged(d).into_iter().filter(|i| d.item(*i).is_some_and(|it| it.xml_tag == name)).collect()
};
s.edit(|d, _| {
d.xml.tags.retain(|t| t.name != name);
d.xml.style_map.retain(|(_, t)| *t != name);
for id in &ids {
if let Some(it) = d.item_mut(*id) {
it.xml_tag.clear();
}
}
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
&& !valid_name(t)
{
return Err(bad("xml.tag", format!("`{t}` isn't a valid XML name")));
}
let ids = ids_param(p, "ids").unwrap_or_else(|| s.active().map(|d| d.selection.items.clone()).unwrap_or_default());
if ids.is_empty() {
return Err(bad("xml.tag", "select objects to tag"));
}
s.edit(|d, _| {
if let Some(t) = &tag
&& !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 });
}
for id in &ids {
if let Some(it) = d.item_mut(*id) {
it.xml_tag = tag.clone().unwrap_or_default();
}
}
ok()
})
}),
cmd!(
"xml.mapStyle",
"Map Styles to Tags",
[],
None,
"{style: paragraph style, tag | null} — that style's paragraphs export as `<tag>` elements and import back with it",
has_doc,
|s, p| {
let style = str_param(p, "style").unwrap_or("").to_string();
let tag = str_param(p, "tag").map(str::to_string);
if s.doc()?.doc.styles.para(&style).is_none() {
return Err(bad("xml.mapStyle", format!("no paragraph style `{style}`")));
}
s.edit(|d, _| {
d.xml.style_map.retain(|(st, _)| *st != style);
if let Some(t) = tag {
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 });
}
d.xml.style_map.push((style.clone(), t));
}
ok()
})
}
),
cmd!(query "xml.structure", "Structure", [], None, "{} → {root, elements: [{tag, id, kind, text?}]} in reading order", has_doc, |s, _| {
let d = &s.doc()?.doc;
let elements: Vec<Value> = tagged(d)
.into_iter()
.filter_map(|id| d.item(id))
.map(|it| {
let (kind, text) = match &it.content {
Content::Text(tf) => ("text", d.story(tf.story).map(|st| plain(&st.text))),
Content::Graphic(_) => ("graphic", None),
_ => ("object", None),
};
json!({"tag": it.xml_tag, "id": it.id.0, "kind": kind, "text": text})
})
.collect();
Ok(json!({"root": root_name(d), "elements": elements}))
}),
cmd!(noundo "file.exportXml", "Export XML…", ["File"], None, "{path?} — the tagged content in reading order → {path, bytes} (no path: {text})", has_doc, |s, p| {
let text = export_xml(&s.doc()?.doc);
match str_param(p, "path") {
Some(path) => {
#[cfg(not(target_arch = "wasm32"))]
crate::io::write_file(path, text.as_bytes()).map_err(crate::EngineError::Other)?;
Ok(json!({"path": path, "bytes": text.len()}))
}
None => Ok(json!({"text": text, "bytes": text.len()})),
}
}),
cmd!(
"xml.loadDtd",
"Load DTD…",
["Window", "Utilities", "Tags"],
None,
"{path | text} — keep the DTD for validation and add a tag for each declared element; the root takes the first element's name unless already named → {elements}",
has_doc,
|s, p| {
let text = text_or_path(p, "xml.loadDtd")?;
let dtd = crate::dtd::parse(&text).map_err(|e| bad("xml.loadDtd", e))?;
let names: Vec<String> = dtd.element_names().map(str::to_string).collect();
s.edit(|d, _| {
for n in &names {
if valid_name(n) && !d.xml.tags.iter().any(|t| t.name == *n) {
let color = COLORS[d.xml.tags.len() % COLORS.len()];
d.xml.tags.push(XmlTag { name: n.clone(), color });
}
}
if d.xml.root.is_empty()
&& let Some(first) = names.first()
{
d.xml.root = first.clone();
}
d.xml.dtd = text.clone();
Ok(json!({"elements": names.len()}))
})
}
),
cmd!(
"xml.deleteDtd",
"Delete DTD",
[],
None,
"{}",
|s: &Session| { if s.doc().is_ok_and(|d| !d.doc.xml.dtd.is_empty()) { Ok(()) } else { Err("no DTD loaded".into()) } },
|s, _| s.edit(|d, _| {
d.xml.dtd.clear();
ok()
})
),
cmd!(
query "xml.validate",
"Validate from Root Element",
[],
None,
"{} — check the structure (as exported) against the loaded DTD → {valid, problems: [{path, message}]}",
|s: &Session| {
if s.doc().is_ok_and(|d| !d.doc.xml.dtd.is_empty()) { Ok(()) } else { Err("load a DTD first".into()) }
},
|s, _| {
let d = &s.doc()?.doc;
let dtd = crate::dtd::parse(&d.xml.dtd).map_err(|e| bad("xml.validate", e))?;
let problems = crate::dtd::validate(&dtd, &export_xml(d));
Ok(json!({"valid": problems.is_empty(), "problems": problems}))
}
),
cmd!(
"file.importXml",
"Import XML…",
["File"],
None,
"{path | text} — each element's content goes into the next text frame with that tag (child elements of mapped tags become paragraphs in their style) → {placed, unmatched}",
has_doc,
import_xml
),
]
}
/// The `text` parameter, or the file at `path`.
fn text_or_path(p: &Value, id: &str) -> Result<String> {
Ok(match (str_param(p, "text"), str_param(p, "path")) {
(Some(t), _) => t.to_string(),
(None, Some(path)) => {
#[cfg(not(target_arch = "wasm32"))]
let t = crate::io::read_to_string(path).map_err(crate::EngineError::Other)?;
#[cfg(target_arch = "wasm32")]
let t = {
let _ = path;
String::new()
};
t
}
_ => return Err(bad(id, "`path` or `text` required")),
})
}
fn import_xml(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "file.importXml";
let text = text_or_path(p, ID)?;
let elements = parse(&text).map_err(|e| bad(ID, format!("not well-formed XML: {e}")))?;
let d = &s.doc()?.doc;
// Frames by tag, in reading order; each element takes the next free one.
let mut slots: Vec<(String, StoryId, bool)> =
tagged(d).into_iter().filter_map(|id| d.item(id)).filter_map(|it| it.text_frame().map(|tf| (it.xml_tag.clone(), tf.story, false))).collect();
let reverse: Vec<(String, String)> = d.xml.style_map.iter().map(|(st, t)| (t.clone(), st.clone())).collect();
let mut fills: Vec<(StoryId, Vec<(Option<String>, String)>)> = Vec::new();
let mut unmatched = 0;
for el in elements {
let Some(slot) = slots.iter_mut().find(|(t, _, used)| *t == el.name && !used) else {
unmatched += 1;
continue;
};
slot.2 = true;
let paras: Vec<(Option<String>, String)> = if el.children.is_empty() {
el.text.trim().split('\n').map(|l| (None, l.trim().to_string())).collect()
} else {
el.children
.into_iter()
.map(|(t, txt)| (reverse.iter().find(|(tag, _)| *tag == t).map(|(_, st)| st.clone()), txt.trim().to_string()))
.collect()
};
fills.push((slot.1, paras));
}
let placed = fills.len();
s.edit(|d, _| {
for (sid, paras) in fills {
let Some(st) = d.story_mut(sid) else { continue };
let base = st.paras.first().cloned().unwrap_or_default();
let text = paras.iter().map(|(_, t)| t.as_str()).collect::<Vec<_>>().join("\n");
let frames = std::mem::take(&mut st.frames);
let mut fresh = Story::with_text(sid, &text, ParaFormat { table: None, ..base.clone() });
for (i, (style, _)) in paras.iter().enumerate() {
if let (Some(sty), Some(pf)) = (style, fresh.paras.get_mut(i)) {
pf.style = sty.clone();
}
}
fresh.frames = frames;
fresh.rev = st.rev.wrapping_add(1);
*st = fresh;
}
Ok(json!({"placed": placed, "unmatched": unmatched}))
})
}
#[cfg(test)]
mod tests {
use serde_json::json;
use crate::Session;
#[test]
fn dtd_loads_tags_and_validates_the_structure() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
assert!(s.execute("xml.validate", &json!({})).is_err(), "no DTD yet");
let dtd = "<!ELEMENT article (headline, story+)><!ELEMENT headline (#PCDATA)><!ELEMENT story (#PCDATA | term)*><!ELEMENT term (#PCDATA)>";
let r = s.execute("xml.loadDtd", &json!({"text": dtd})).unwrap();
assert_eq!(r["elements"], 4);
let tags = s.execute("xml.tags", &json!({})).unwrap();
assert_eq!(tags["root"], "article");
assert_eq!(tags["tags"].as_array().unwrap().len(), 4);
let a = s.execute("frame.create", &json!({"rect": [72, 72, 400, 150], "content": "text", "text": "Body", "caret": false})).unwrap();
s.execute("xml.tag", &json!({"tag": "story", "ids": [a["id"]]})).unwrap();
let v = s.execute("xml.validate", &json!({})).unwrap();
assert_eq!(v["valid"], false);
assert!(v["problems"][0]["message"].as_str().unwrap().contains("the DTD asks for (headline, story+)"), "{v}");
let h = s.execute("frame.create", &json!({"rect": [72, 20, 400, 60], "content": "text", "text": "Head", "caret": false})).unwrap();
s.execute("xml.tag", &json!({"tag": "headline", "ids": [h["id"]]})).unwrap();
assert_eq!(s.execute("xml.validate", &json!({})).unwrap()["valid"], true);
assert!(s.execute("xml.loadDtd", &json!({"text": "<!ELEMENT a (b,|c)>"})).is_err());
s.execute("xml.deleteDtd", &json!({})).unwrap();
assert!(s.execute("xml.validate", &json!({})).is_err());
}
#[test]
fn tag_export_and_import_xml() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();
let a = s
.execute("frame.create", &json!({"rect": [72, 72, 400, 150], "content": "text", "text": "Title A\nBody & more", "caret": false}))
.unwrap();
s.execute("text.select", &json!({"story": a["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("style.paragraph.apply", &json!({"name": "Head"})).unwrap();
let b = s.execute("frame.create", &json!({"rect": [72, 300, 400, 350], "content": "text", "text": "Caption", "caret": false})).unwrap();
s.execute("xml.tag", &json!({"tag": "story", "ids": [a["id"]]})).unwrap();
s.execute("xml.tag", &json!({"tag": "caption", "ids": [b["id"]]})).unwrap();
s.execute("xml.mapStyle", &json!({"style": "Head", "tag": "title"})).unwrap();
let x = s.execute("file.exportXml", &json!({})).unwrap()["text"].as_str().unwrap().to_string();
assert!(
x.contains("<story>")
&& x.contains("<title>Title A</title>")
&& x.contains("Body &amp; more")
&& x.contains("<caption>Caption</caption>"),
"{x}"
);
assert!(x.find("<story>").unwrap() < x.find("<caption>").unwrap(), "reading order");
let st = s.execute("xml.structure", &json!({})).unwrap();
assert_eq!(st["elements"].as_array().unwrap().len(), 2);
// Import new content into the same structure.
let r = s
.execute(
"file.importXml",
&json!({"text": "<Root><story><title>New title</title><p>New body</p></story><caption>New caption</caption><extra/></Root>"}),
)
.unwrap();
assert_eq!((r["placed"].as_u64(), r["unmatched"].as_u64()), (Some(2), Some(1)));
let d = &s.doc().unwrap().doc;
let sa = d.stories[&designcraft_doc::StoryId(a["story"].as_u64().unwrap())].clone();
assert_eq!(sa.text, "New title\nNew body");
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
.as_chunks::<4>()
.0
.iter()
.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}");
}
}