Files
craft-libs/crates/pptx/src/write/chart.rs
T
Dylan M. TaylorandJordi Altayó d6e3a6c438 craft-pptx: the writer (from DeckCraft) (#1065)
* Add craft-drawingml: units, colours, preset shapes, custom geometry and text warps

The parts of DrawingML that need no document model, moved from DeckCraft
(60f91f78): crates/color, crates/geom (preset, warp, Xfrm and the EMU
conversions) and crates/pptx/src/custgeom.rs with CustomPath from
crates/model.

The code is unchanged except that custgeom reads craft-xml trees and writes
to a craft-xml Writer instead of DeckCraft's own XML helper, and matches
elements by local name. The 59 tests of the moved code come with it; six
more cover the custom geometry limits.

* drawingml: evaluate a custom geometry's guide lists once per coordinate space

read_cust_geom rebuilt Guides and evaluated avLst and gdLst again for every
path: up to 1,000 paths times up to 10,000 guides, each name copied and
hashed.

Guides are now cached per path coordinate space (w, h). At most 16 spaces
and 4 MiB of guide names are kept per geometry; paths in further spaces are
left out. The first space is always kept, and a geometry without guides is
not capped.

Ported from storytold/deckcraft#1789. A list counts as having guides only
when it has gd children, as that PR's review asked.

* drawingml: the model types for fills, lines, text, tables, charts and diagrams

Moved from DeckCraft (60f91f78) crates/model/src: style.rs, text.rs,
table.rs, chart.rs, numfmt.rs and trendline.rs, plus Diagram, DiagramNode
and the MediaId and SlideId newtypes from lib.rs.

The files are unchanged except that deckcraft_color:: is crate::color:: and
Fill and TableBorder allow clippy::large_enum_variant. Their 60 tests come
with them. Readers and writers follow.

* drawingml: the theme model (colour, font and format schemes)

Moved from DeckCraft crates/model/src/theme.rs at 60f91f78: FontSet, ScriptFont, FontScheme,
FormatScheme, Theme and default_format. The app's theme gallery, its variants and its own default
theme stay in the app. Theme::default() is a plain theme built in place, so nothing here depends
on a gallery.

* drawingml: readers and writers for fills, lines, text, charts, themes, table styles and diagrams

Moved from DeckCraft crates/pptx/src at 60f91f78: read/dml.rs, write/dml.rs, read/chart.rs,
read/chartex.rs, write/chart.rs, read/theme.rs, write/theme.rs, tables.rs and dgm.rs, onto
craft-xml. Package lookups (Imp, Part, Exp, Out) are the caller's part::Source and part::Sink.
The chart frame budget and kept-part capture stay with the presentation reader.

* drawingml: what WordCraft and GridCraft read that DeckCraft's copy did not

Every ST_PresetColorVal name has its colour, in any case and with the dk/lt/med abbreviations;
a sysClr without lastClr takes the usual value of its name; a Strict percentage (50%) reads
anywhere a percentage does; a chart series keeps its c:f formulas and the writer uses them.

* craft-drawingml: extra named theme colours and explicit tint rows

Ported from the format part of storytold/deckcraft#1746 by @jagjordi: ColorScheme::{extra, tints,
computed_tints}, ExtraColor, GalleryVariant, variants_of, and the a:clrScheme extension that
keeps them in a file.

* drawingml xmlx: copy only used, bounded namespace declarations onto kept fragments and mc branches

From storytold/deckcraft#1740 (988a4920), which landed after the extraction commit 60f91f78.

* Add craft-pptx: the PresentationML model (from DeckCraft)

Presentation, masters, layouts, slides, shapes, placeholders, media,
comments, sections, show settings, properties, embedded fonts, kept parts
and drawing guides from DeckCraft's crates/model/src/lib.rs, and
transitions and animations from anim.rs. The DrawingML types come from
craft-drawingml. The placeholder matching from DeckCraft's resolve.rs
moves as placeholder::parents, without the rest of resolve.

Presentation::default() is now an empty 16:9 deck with no masters; the
starting deck stays with the application.

* craft-pptx: the reader (from DeckCraft), on craft-opc and craft-drawingml

DeckCraft's crates/pptx reader (read.rs, read/shapes.rs and the chart
frame code of read/chart.rs) moved onto craft-opc's Package and
craft-xml trees, with the DrawingML readers of craft-drawingml behind a
part::Source over the import state. What DeckCraft took from its own
defaults (a master for a file without one, the theme of a master that
names none) comes from a caller-supplied Defaults; Plain is the neutral
one. Placeholder geometry inheritance uses placeholder::parents.

Transitions, animations, notes and comments follow in later changes.

* craft-pptx: drop DeckCraft issue numbers from reader comments

* craft-pptx: link the package budgets from the tag budget's doc

* craft-pptx: the writer (from DeckCraft)

DeckCraft's crates/pptx writer (write.rs, write/shapes.rs and the kept
chart parts of write/chart.rs) moved onto craft-opc's PackageOut and
craft-xml's Writer, with craft-drawingml's DrawingML writers behind a
part::Sink over the export state. What DeckCraft took from its own
defaults (a master for a deck without one, master and default text
styles, its name in docProps/app.xml and in table style names) comes
from Defaults. export and export_as take the defaults.

Transitions, animations, notes slides and comments follow in later
changes.

---------

Co-authored-by: Jordi Altayó <jordiag@kth.se>
2026-11-11 21:53:02 -05:00

94 lines
4.3 KiB
Rust

//! Charts: the parts an unchanged chart carried (workbook, styles, colours), written back under
//! fresh names.
use craft_drawingml::chart::write::sidecar_part;
pub(crate) use craft_drawingml::chart::write::{chart_xml, chartex_part};
use crate::chart::Chart;
/// A fresh name for a kept part: `ppt/<folder>/keptN.<ext>`. The writer generates no `kept…`
/// names and `n` is unique within the package, so a kept part never lands on (or duplicates) a
/// part the writer makes, whatever the source file called it.
fn kept_name(original: &str, n: u32) -> String {
let norm = craft_opc::normalize(original);
let area = norm.split('/').nth(1).unwrap_or("embeddings");
let area = if matches!(area, "embeddings" | "charts" | "drawings" | "media") { area } else { "embeddings" };
let file = craft_opc::file_of(&norm);
let ext = file
.rsplit_once('.')
.map(|(_, e)| e)
.filter(|e| !e.is_empty() && e.len() <= 8 && e.chars().all(|c| c.is_ascii_alphanumeric()))
.unwrap_or("bin");
format!("ppt/{area}/kept{n}.{ext}")
}
/// Write an unchanged chart's own relationships and the parts they reach. Each kept part is
/// written under a fresh name ([`kept_name`]) and the relationships between kept parts are
/// rewritten to those names; a relationship to anything that was not kept is dropped.
/// `n_kept` numbers kept parts across the package.
pub fn write_kept(pkg: &mut craft_opc::PackageOut, chart_name: &str, c: &Chart, n_kept: &mut u32) {
use std::collections::HashMap;
use craft_opc::{RelOut, RelsOut, normalize as norm, relative, rels_path};
if c.kept.rels.is_empty() {
return;
}
// Original part name (normalized) → the name written.
let mut names: HashMap<String, String> = HashMap::new();
for p in c.kept.parts.iter().filter(|p| kept_payload(&p.name)) {
let key = norm(&p.name);
if names.contains_key(&key) {
continue;
}
*n_kept += 1;
let new = kept_name(&p.name, *n_kept);
let ct = if !p.content_type.is_empty() { p.content_type.clone() } else { crate::mime_for(&p.name).to_string() };
// An override per part: a kept part never sets the package-wide default for its extension.
pkg.xml_part(&new, &ct, p.bytes.clone());
names.insert(key, new);
}
let mut rels = RelsOut::default();
for r in &c.kept.rels {
if r.external {
rels.items.push(RelOut { id: r.id.clone(), ty: r.rel_type.clone(), target: r.target.clone(), external: true });
} else if let Some(new) = names.get(&norm(&r.part)) {
rels.items.push(RelOut { id: r.id.clone(), ty: r.rel_type.clone(), target: relative(chart_name, new), external: false });
} else {
log::warn!("pptx: chart relationship {} has no kept part; dropped", r.id);
}
}
pkg.rels(chart_name, &rels);
let mut parts_by_norm = std::collections::HashMap::new();
for p in &c.kept.parts {
parts_by_norm.entry(norm(&p.name)).or_insert(p);
}
let mut seen_payloads = std::collections::HashSet::new();
// The kept parts' own relationships, pointed at the new names.
for p in c.kept.parts.iter().filter(|p| kept_payload(&p.name)) {
let norm_name = norm(&p.name);
if !seen_payloads.insert(norm_name.clone()) {
continue;
}
let Some(new_source) = names.get(&norm_name) else { continue };
let rp = norm(&rels_path(&p.name));
let Some(rels_part) = parts_by_norm.get(&rp) else { continue };
let mut out = RelsOut::default();
for r in craft_opc::Rels::parse(&rels_part.bytes, &p.name).list {
if r.external {
out.items.push(RelOut { id: r.id, ty: r.ty, target: r.target_raw, external: true });
} else if let Some(new) = names.get(&norm(&r.target)) {
out.items.push(RelOut { id: r.id, ty: r.ty, target: relative(new_source, new), external: false });
} else {
log::warn!("pptx: relationship {} of kept chart part {} has no kept target; dropped", r.id, p.name);
}
}
pkg.rels(new_source, &out);
}
}
/// A kept part to write itself (relationships parts are rewritten from the relationships).
fn kept_payload(name: &str) -> bool {
!name.to_ascii_lowercase().ends_with(".rels") && sidecar_part(name)
}