Merge remote-tracking branch 'origin/main' into review-906

This commit is contained in:
MarekSpodBiedry
2026-10-18 18:37:41 +02:00
59 changed files with 2185 additions and 251 deletions
Generated
+29 -28
View File
@@ -892,7 +892,7 @@ checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
[[package]]
name = "deckcraft"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"arboard",
"cpal",
@@ -911,7 +911,7 @@ dependencies = [
[[package]]
name = "deckcraft-anim"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-geom",
"deckcraft-model",
@@ -920,7 +920,7 @@ dependencies = [
[[package]]
name = "deckcraft-av1"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-bitstream",
"rayon",
@@ -929,30 +929,31 @@ dependencies = [
[[package]]
name = "deckcraft-bitstream"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"proptest",
]
[[package]]
name = "deckcraft-cli"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-engine",
"deckcraft-mcp",
"serde_json",
"zip",
]
[[package]]
name = "deckcraft-color"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"serde",
]
[[package]]
name = "deckcraft-engine"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-anim",
"deckcraft-color",
@@ -977,7 +978,7 @@ dependencies = [
[[package]]
name = "deckcraft-fonts"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"epaint_default_fonts",
"harfrust 0.13.3",
@@ -989,7 +990,7 @@ dependencies = [
[[package]]
name = "deckcraft-format"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-model",
"serde",
@@ -1000,7 +1001,7 @@ dependencies = [
[[package]]
name = "deckcraft-geom"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"kurbo",
"serde",
@@ -1008,7 +1009,7 @@ dependencies = [
[[package]]
name = "deckcraft-h264"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-bitstream",
"rayon",
@@ -1017,7 +1018,7 @@ dependencies = [
[[package]]
name = "deckcraft-hevc"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-bitstream",
"rayon",
@@ -1026,7 +1027,7 @@ dependencies = [
[[package]]
name = "deckcraft-isobmff"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-bitstream",
"thiserror 2.0.21",
@@ -1034,11 +1035,11 @@ dependencies = [
[[package]]
name = "deckcraft-matroska"
version = "0.7.0"
version = "0.8.0"
[[package]]
name = "deckcraft-mcp"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-engine",
"deckcraft-render",
@@ -1048,7 +1049,7 @@ dependencies = [
[[package]]
name = "deckcraft-media"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-av1",
"deckcraft-h264",
@@ -1066,7 +1067,7 @@ dependencies = [
[[package]]
name = "deckcraft-metafile"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"image",
"kurbo",
@@ -1075,7 +1076,7 @@ dependencies = [
[[package]]
name = "deckcraft-model"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-color",
"deckcraft-geom",
@@ -1087,15 +1088,15 @@ dependencies = [
[[package]]
name = "deckcraft-ogg"
version = "0.7.0"
version = "0.8.0"
[[package]]
name = "deckcraft-opus"
version = "0.7.0"
version = "0.8.0"
[[package]]
name = "deckcraft-pdf"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"craft-pdf",
"deckcraft-fonts",
@@ -1113,7 +1114,7 @@ dependencies = [
[[package]]
name = "deckcraft-pptx"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-color",
"deckcraft-engine",
@@ -1129,7 +1130,7 @@ dependencies = [
[[package]]
name = "deckcraft-render"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-anim",
"deckcraft-color",
@@ -1148,7 +1149,7 @@ dependencies = [
[[package]]
name = "deckcraft-text"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"chrono",
"deckcraft-color",
@@ -1162,7 +1163,7 @@ dependencies = [
[[package]]
name = "deckcraft-ui-egui"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-anim",
"deckcraft-color",
@@ -1184,7 +1185,7 @@ dependencies = [
[[package]]
name = "deckcraft-vp9"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-bitstream",
"rayon",
@@ -1193,7 +1194,7 @@ dependencies = [
[[package]]
name = "deckcraft-web"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"deckcraft-engine",
"deckcraft-ui-egui",
@@ -5720,7 +5721,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"serde_json",
]
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/deckcraft", "apps/deckcraft-cli"]
[workspace.package]
version = "0.7.0"
version = "0.8.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
+7 -9
View File
@@ -10,12 +10,12 @@
<h1 align="center">DeckCraft</h1>
<p align="center">
<b>Presentations and slide shows; an open-source, clean-room reimplementation of Microsoft PowerPoint, rebuilt in pure Rust.</b>
<b>Presentations and slide shows; an open-source, modern presentation and slide designer, built in pure Rust.</b>
</p>
<p align="center">
Build decks with themes, layouts, shapes, pictures, tables, charts, transitions and animations,
open and save PowerPoint files, and present them full screen. Native on macOS, Windows, Linux
open and save .pptx presentation files, and present them full screen. Native on macOS, Windows, Linux
and FreeBSD, and in the browser. Every button is also a command that the CLI and AI agents
(through MCP) can drive.
</p>
@@ -74,7 +74,7 @@ Today it can:
audio and video (MP3, AAC, FLAC, ALAC, Ogg, Opus, WAV, AIFF; H.264, HEVC, VP9, AV1).
- **Present**: transitions (including Morph), entrance/emphasis/exit and motion-path animations,
by-paragraph builds, full-screen slide show, presenter view, pen, rehearse timings, media playback.
- **Exchange files**: open and save PowerPoint `.pptx`, export PDF (slides, notes pages, handouts
- **Exchange files**: open and save .pptx presentations, export PDF (slides, notes pages, handouts
with selectable text), PNG/JPEG, an animated GIF of the deck and outlines. Unsaved work is kept by AutoRecover.
- **Automate**: 200+ commands with undo, all scriptable from the CLI, a JSON control channel and an
MCP server for AI agents.
@@ -132,7 +132,7 @@ settings directory, beside `ui.json` and `prefs.json` (Linux `~/.config/deckcraf
`$XDG_CONFIG_HOME/deckcraft/logs/`; macOS `~/Library/Application Support/DeckCraft/logs/`; Windows
`%APPDATA%\DeckCraft\logs\`). A start from a desktop menu or the Dock has no terminal, so this file
is what to attach to a bug report: the crash guard's panic report, a failed crash-recovery save,
PowerPoint parts skipped on import and audio output problems land there. Each launch moves the
Parts skipped on import and audio output problems land there. Each launch moves the
previous log to `deckcraft.1.log` (and that one to `deckcraft.2.log`), so the log of a run that
crashed survives the next start. The file stops growing at 16 MiB. `--version` writes no file.
@@ -158,8 +158,8 @@ deckcraft-cli mcp --automation-read-root DIR --automation-write-root DIR # con
## Roadmap
DeckCraft is in **alpha**. It covers **84% of PowerPoint's features by breadth** (92% of the core
ones, measured) and is about **55% of the way to replacing PowerPoint for real work** (estimated).
DeckCraft is in **alpha**. It covers **84% of the features tracked in [`docs/target-app-parity.md`](docs/target-app-parity.md) by breadth** (92% of the core
ones, measured) and is about **55% ready for real work across all tracked capabilities** (estimated).
See [ROADMAP.md](ROADMAP.md) for the stage, numbers by dimension and what's next,
[docs/target-app-parity.md](docs/target-app-parity.md) for the full assessment,
[docs/gaps.md](docs/gaps.md) for every known shortfall and
@@ -279,15 +279,13 @@ Bundled fonts, icons, images and other assets keep their own open licenses; each
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
DeckCraft's themes, layouts, shape geometry, icons and sample decks are original work, drawn or
generated in code; no Microsoft artwork, fonts, themes or templates are used.
generated in code; no proprietary artwork, fonts, themes or templates are used.
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
part of this repository and DeckCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
<sub>Microsoft and PowerPoint are trademarks of the Microsoft group of companies. Adobe, Photoshop, Illustrator, Premiere Pro, Lightroom, Acrobat, After Effects and InDesign are trademarks or registered trademarks of Adobe Inc. in the United States and/or other countries. DeckCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Microsoft Corporation or Adobe Inc.; these names are used only to describe the workflows it is compatible with.</sub>
<p align="center">
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
+13
View File
@@ -131,7 +131,17 @@ app's JSON control channel (`deckcraft --control PORT`).
| Date | What landed |
|---|---|
| 2026-10-17 | Opening a file caps absurd effect sizes (glow, soft edges, shadows, reflections, on shapes, text and table text) at what Format Shape allows: a glow of 10^18 pt in a .pptx made rendering ask for 34 GB and abort |
| 2026-10-17 | Opening a .deckcraft file whose shapes repeat an id gives the repeats fresh ids (groups, layouts and masters too), so the deck validates and edits by id find one shape |
| 2026-10-17 | Edit Points: turning a shape into a freeform is one undo step, so Undo brings the original shape back (it used to stay a freeform) |
| 2026-10-17 | While a placeholder's text is being edited, a click on a shape in front of it selects that shape instead of moving the caret, as in PowerPoint (#931) |
| 2026-10-15 | PPTX trigger sequences keep separate On Click steps, including paragraph builds; synthetic import/edit/save/reopen and headless show regressions |
| 2026-10-16 | Export: PNG with a transparent background — the slide background is left out, only the slide's content is drawn (Export… dialog, File › Export, web download, `file.export`/`file.render` `transparentBackground`, `deckcraft-cli render --transparent`) (#784) |
| 2026-10-16 | Arrange ▸ Align: Align to Slide and Align Selected Objects, as in PowerPoint. One object aligns to the slide and several to each other until the other choice is ticked; the choice holds for that selection and also drives Distribute |
| 2026-10-15 | CLI: .txt and .md export includes table cell text, which it used to skip silently (#814) |
| 2026-10-15 | A `.pptx` slide that can't be read is reported, not dropped in silence: `lostSlides` from `file.open`, a message and a repaired copy in the app, a warning from `deckcraft-cli` (#203) |
| 2026-10-16 | AutoFormat as you type: ordinals (1st, 22nd, 103rd) get superscript suffixes after a space or punctuation; Tools ▸ AutoCorrect and `text.autocorrect {ordinals}` turn it off |
| 2026-10-16 | A PowerPoint Show (`.ppsx`) opened from the command line or the file association starts its slide show, as in PowerPoint; File › Open still opens it for editing (#862) |
| 2026-10-15 | PDF export and rendering: `anchorCtr` centres the drawn text block — right-aligned text no longer ran past the box edge (#736) |
| 2026-10-14 | connected MCP rejects unrelated, malformed, incomplete and oversized replies without replay; buffered unsolicited bytes force a fresh connection before sending (#718) |
| 2026-10-14 | Empty bulleted and numbered paragraphs show gray markers while editing, including on first click and after Enter. Markers use the list style and stay out of slide shows and exports. |
@@ -227,6 +237,9 @@ app's JSON control channel (`deckcraft --control PORT`).
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | trivial | Progress log: PPTX trigger click-step round trip. Feature scores and milestone names unchanged |
| 2026-10-16 | trivial | Progress log: PNG export with a transparent background (#784) |
| 2026-10-16 | trivial | Progress log: a `.ppsx` from the system starts the slide show (#862) |
| 2026-10-14 | trivial | remote MCP checks reply IDs, envelopes and bounded newline framing (#718) |
| 2026-10-14 | minor | Gray list markers on empty paragraphs while editing; caret keeps the list indent before typing |
| 2026-10-14 | minor | Community PR wave folded: headline breadth 84% over 191 features (P0 92%, P1 82%, P2 55%) and the feature-area breadths from `cargo xtask parity`; one row per area; Upcoming item 2 merged; per-PR count notes dropped from the progress log. Ready stays ~55%, stage alpha |
+3
View File
@@ -17,3 +17,6 @@ path = "src/main.rs"
deckcraft-engine = { workspace = true }
deckcraft-mcp = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
zip = { workspace = true }
+5 -4
View File
@@ -19,15 +19,16 @@ The shapes of one slide, with their ids, boxes and text, come from the slide.ins
},
Subcommand {
name: "render",
usage: "render (FILE | --sample) [--slide N | --all] [--scale S] [--edit] OUT",
usage: "render (FILE | --sample) [--slide N | --all] [--scale S] [--edit] [--transparent] OUT",
summary: "draw slides as PNG images",
details: "Draws slides of FILE, or of the sample presentation with --sample, as PNG images. FILE comes first;
OUT is the image to write. With --all, OUT is a folder that gets one slide-01.png, slide-02.png… per
slide. Prints each image's path and size.
--slide N the slide at index N; indices start at 0, and 0 is the default
--scale S pixels per point, 2 by default: a 960×540 slide becomes 1920×1080
--edit draw what the editor shows: placeholder prompts and their dashed outlines
--slide N the slide at index N; indices start at 0, and 0 is the default
--scale S pixels per point, 2 by default: a 960×540 slide becomes 1920×1080
--edit draw what the editor shows: placeholder prompts and their dashed outlines
--transparent leave the slide background out, so only what is on the slide is drawn
deckcraft-cli render deck.deckcraft --slide 2 slide-3.png",
},
+35 -2
View File
@@ -117,11 +117,27 @@ fn open(s: &mut Session, input: Option<&str>, sample: bool) -> Result<(), String
return deckcraft_engine::sample::open_sample(s).map_err(|e| e.to_string());
}
match input {
Some(p) => s.execute("file.open", &json!({"path": p})).map(|_| ()).map_err(|e| e.to_string()),
Some(p) => {
let opened = s.execute("file.open", &json!({"path": p})).map_err(|e| e.to_string())?;
warn_if_damaged(p, &opened);
Ok(())
}
None => s.execute("file.new", &json!({})).map(|_| ()).map_err(|e| e.to_string()),
}
}
/// Say on stderr what a file lost on opening, so a saved copy doesn't silently miss it (#203).
fn warn_if_damaged(path: &str, opened: &serde_json::Value) {
let count = |key: &str| opened.get(key).and_then(|v| v.as_array()).map_or(0, |a| a.len());
let (slides, media) = (count("lostSlides"), count("damagedMedia"));
if slides > 0 {
eprintln!("deckcraft-cli: warning: {path}: {slides} slide{} couldn't be read and left out", if slides == 1 { "" } else { "s" });
}
if media > 0 {
eprintln!("deckcraft-cli: warning: {path}: {media} picture or media file{} couldn't be read", if media == 1 { "" } else { "s" });
}
}
/// Median and slowest of `runs` timings of `f`, in milliseconds.
fn time_ms(runs: usize, mut f: impl FnMut() -> Result<(), String>) -> Result<(f64, f64), String> {
let mut ms = Vec::with_capacity(runs);
@@ -244,11 +260,13 @@ fn render(args: &[String]) -> Result<(), String> {
let mut all = false;
let mut scale = 2.0;
let mut edit = false;
let mut transparent = false;
let mut out = None;
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--sample" => sample = true,
"--transparent" => transparent = true,
"--slide" => slide = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--slide needs a number")?),
"--all" => all = true,
"--edit" => edit = true,
@@ -281,7 +299,7 @@ fn render(args: &[String]) -> Result<(), String> {
std::fs::create_dir_all(&out).map_err(|e| format!("{out}: {e}"))?;
}
for i in list {
let (png, w, h) = deckcraft_engine::cmd::file::render_png(&st.doc, i, scale, edit);
let (png, w, h) = deckcraft_engine::cmd::file::render_png_with(&st.doc, i, scale, edit, transparent);
let path = if all { format!("{out}/slide-{:02}.png", i + 1) } else { out.clone() };
std::fs::write(&path, png).map_err(|e| format!("{path}: {e}"))?;
outln!("{path} ({w}×{h})");
@@ -680,6 +698,21 @@ mod tests {
}
}
/// `render --transparent` leaves the slide background out (#784): the corner is transparent.
#[test]
fn render_transparent_leaves_the_background_out() {
let dir = std::env::temp_dir().join(format!("deckcraft-cli-transparent-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let alpha = |path: &std::path::Path| deckcraft_engine::render::decode_image(&std::fs::read(path).unwrap()).unwrap().get_pixel(1, 1).0[3];
let opaque = dir.join("opaque.png");
render(&args(&["--sample", "--scale", "0.25", &opaque.to_string_lossy()])).unwrap();
assert_eq!(alpha(&opaque), 255);
let clear = dir.join("clear.png");
render(&args(&["--sample", "--transparent", "--scale", "0.25", &clear.to_string_lossy()])).unwrap();
assert_eq!(alpha(&clear), 0);
let _ = std::fs::remove_dir_all(&dir);
}
/// `run --export OUT.gif --export-params JSON` and `convert IN OUT.gif` write animated GIFs.
#[test]
fn exports_an_animated_gif() {
+53
View File
@@ -0,0 +1,53 @@
//! Opening a `.pptx` that lost slides says so on stderr instead of saving a shorter deck in silence (#203).
use std::io::{Cursor, Read, Write};
use std::path::PathBuf;
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).args(args).output().unwrap()
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("deckcraft-cli-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// `deck` with `ppt/slides/slide2.xml` cut off.
fn without_slide2(deck: &[u8]) -> Vec<u8> {
let mut zin = zip::ZipArchive::new(Cursor::new(deck)).unwrap();
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
let options = zip::write::SimpleFileOptions::default();
for i in 0..zin.len() {
let mut f = zin.by_index(i).unwrap();
let mut data = vec![];
f.read_to_end(&mut data).unwrap();
if f.name() == "ppt/slides/slide2.xml" {
data = b"<p:sld".to_vec();
}
out.start_file(f.name(), options).unwrap();
out.write_all(&data).unwrap();
}
out.finish().unwrap().into_inner()
}
#[test]
fn a_pptx_with_an_unreadable_slide_is_reported_on_stderr() {
let dir = temp_dir("lost-slide");
let good = dir.join("good.pptx");
let made = cli(&["run", "--sample", "--save", good.to_str().unwrap()]);
assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
let broken = dir.join("broken.pptx");
std::fs::write(&broken, without_slide2(&std::fs::read(&good).unwrap())).unwrap();
let ok = cli(&["info", good.to_str().unwrap()]);
assert!(ok.status.success() && !String::from_utf8_lossy(&ok.stderr).contains("warning"), "{}", String::from_utf8_lossy(&ok.stderr));
let bad = cli(&["info", broken.to_str().unwrap()]);
assert!(bad.status.success(), "{}", String::from_utf8_lossy(&bad.stderr));
let err = String::from_utf8_lossy(&bad.stderr);
assert!(err.contains("warning") && err.contains("1 slide couldn't be read and left out"), "{err}");
let _ = std::fs::remove_dir_all(&dir);
}
+97 -15
View File
@@ -1,8 +1,11 @@
//! Loopback JSON-lines control server: one request per line, one reply per line.
//! This is the transport the MCP server (`deckcraft-cli mcp --connect`) wraps.
//!
//! Every resource a client can hold is bounded ([`Limits`]): simultaneous connections, request
//! line length, queued requests, and how long a socket may sit idle or blocked on a write.
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
//! socket may sit idle or blocked on a write.
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::net::{TcpListener, TcpStream};
@@ -120,6 +123,53 @@ fn read_line(r: &mut impl BufRead, max: usize) -> Line {
}
}
/// One request line, parsed.
enum Parsed {
Request {
id: Value,
method: String,
params: Value,
},
Blank,
/// Not a request: reply with this error and close the connection.
Reject(String),
}
fn parse(bytes: &[u8]) -> Parsed {
let Ok(text) = std::str::from_utf8(bytes) else {
return Parsed::Reject("not a control request (invalid UTF-8); closing the connection".into());
};
let text = text.trim();
if text.is_empty() {
return Parsed::Blank;
}
if is_http_request_line(text) {
return Parsed::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into());
}
let msg = match serde_json::from_str::<Value>(text) {
Ok(v) => v,
Err(e) => return Parsed::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")),
};
let Some(obj) = msg.as_object() else {
return Parsed::Reject("not a control request (expected a JSON object); closing the connection".into());
};
let Some(method) = obj.get("method").and_then(Value::as_str) else {
return Parsed::Reject("not a control request (missing string `method`); closing the connection".into());
};
Parsed::Request {
id: obj.get("id").cloned().unwrap_or(Value::Null),
method: method.to_string(),
params: obj.get("params").cloned().unwrap_or(json!({})),
}
}
/// An HTTP/1 request line (`POST / HTTP/1.1`) or the HTTP/2 preface (`PRI * HTTP/2.0`).
fn is_http_request_line(text: &str) -> bool {
const METHODS: [&str; 10] = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"];
text.split_once(' ').is_some_and(|(method, _)| METHODS.contains(&method))
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
}
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits) {
if stream.set_read_timeout(Some(limits.idle_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() {
return;
@@ -136,20 +186,14 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
}
Line::Closed => break,
};
let Ok(line) = String::from_utf8(line) else {
if writeln!(out, "{}", json!({"ok": false, "error": "bad JSON: not UTF-8"})).is_err() {
let reply = match parse(&line) {
Parsed::Blank => continue,
Parsed::Reject(e) => {
// The connection closes either way; a peer that can't read the reason loses nothing.
let _ = writeln!(out, "{}", json!({"ok": false, "error": e}));
break;
}
continue;
};
if line.trim().is_empty() {
continue;
}
let reply = match serde_json::from_str::<Value>(&line) {
Ok(msg) => {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
Parsed::Request { id, method, params } => {
let (req, rrx) = ControlRequest::new(method, params);
let state = Arc::clone(&req.state);
let mut r = match tx.try_send(req) {
@@ -177,7 +221,6 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
}
r
}
Err(e) => json!({"ok": false, "error": format!("bad JSON: {e}")}),
};
if let Err(e) = writeln!(out, "{reply}") {
if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) {
@@ -245,6 +288,45 @@ mod tests {
assert_eq!(v["result"], "ui.inspect");
}
/// Every reply line until the server closes the connection.
fn replies_until_closed(r: &mut BufReader<TcpStream>) -> Vec<Value> {
std::iter::from_fn(|| reply(r)).collect()
}
/// A browser can POST to the port: its request line closes the connection before the JSON
/// line in its body is read, so nothing is dispatched.
#[test]
fn an_http_request_closes_the_connection_before_its_body_is_dispatched() {
let (addr, rx) = server(Limits { max_line: 512, ..small() });
let (mut r, mut w) = client(addr);
w.write_all(
b"POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\n\r\n\
{\"id\":1,\"method\":\"engine.execute\",\"params\":{\"command\":\"slide.new\"}}\n",
)
.unwrap();
let replies = replies_until_closed(&mut r);
assert_eq!(replies.len(), 1, "{replies:?}");
assert!(replies[0]["error"].as_str().unwrap().contains("closing the connection"), "{replies:?}");
assert!(rx.try_recv().is_err(), "the body was dispatched");
}
#[test]
fn a_line_that_is_not_a_request_closes_the_connection() {
let (addr, rx) = server(small());
ui(rx);
for junk in [&b"hello\n"[..], b"[1,2]\n", b"{\"id\":1}\n", b"{\"method\":5}\n", b"\xff\xfe\n", b"GET /x HTTP/1.1\n"] {
let (mut r, mut w) = client(addr);
w.write_all(junk).unwrap();
w.write_all(b"{\"id\":2,\"method\":\"m\"}\n").unwrap();
let replies = replies_until_closed(&mut r);
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], false);
}
assert!(is_http_request_line("OPTIONS * HTTP/1.1"));
assert!(is_http_request_line("PRI * HTTP/2.0"));
assert!(!is_http_request_line("{\"method\":\"GET /\"}"));
}
#[test]
fn oversized_line_closes_connection() {
let (addr, rx) = server(small());
+6 -4
View File
@@ -1,6 +1,7 @@
//! DeckCraft desktop app.
//!
//! Usage: `deckcraft [--control <port>] [--sample] [--show] [files…]`
//! A PowerPoint Show (`.ppsx`) given last starts its slide show, as a double-click does in PowerPoint.
//! `deckcraft --help` prints the flags and exits. `deckcraft --version` prints the version and exits.
//!
//! `--control <port>` (or `DECKCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server:
@@ -134,6 +135,8 @@ Usage: deckcraft [--control PORT] [--sample] [--show] [FILE...]
--show start the slide show
--help, -h print this help and exit
--version, -V print the version and exit
A PowerPoint Show (.ppsx) given last starts its slide show.
";
enum Startup {
@@ -254,10 +257,9 @@ fn main() -> eframe::Result {
if sample && let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session) {
log::error!("sample: {e}");
}
for f in files {
if let Err(e) = app.open_path(&f) {
log::error!("{f}: {e}");
}
// A .ppsx opened last starts its slide show (#862).
for (f, e) in app.open_from_system(&files) {
log::error!("{f}: {e}");
}
if show {
app.start_show(0, false);
+5
View File
@@ -54,3 +54,8 @@ real_name = "Nikita Rakitin"
[people.RCShoemaker]
real_name = "Ryan C. Shoemaker"
[people.marcoarnulfo]
real_name = "Marco Arnulfo"
display_name = "Marco Arnulfo"
sync_github_name = false
+11 -7
View File
@@ -299,7 +299,8 @@ impl ShowState {
ShowAction::FinishStep(n)
}
/// ← / Backspace: undo the last step, else go to the previous slide fully built.
/// ← / Backspace: undo the last step, else go to the previous slide fully built. An automatic
/// first step (With/After Previous) is part of the slide appearing, so it is never undone.
pub fn prev(&mut self, pres: &Presentation) -> ShowAction {
if self.ended {
self.ended = false;
@@ -310,13 +311,16 @@ impl ShowState {
self.playing = false;
return ShowAction::Slide(self.slide);
}
if self.playing {
// #844: undoing the automatic first step left the slide as before it appeared, and the show
// played the step again at once, so Back never got past the slide.
let undo = if self.playing { Some(self.step) } else { self.step.checked_sub(1) };
let auto_first = undo == Some(0) && !pres.show.without_animation && ShowState::timeline(pres, self.slide).step_is_auto(0);
if let Some(k) = undo
&& !auto_first
{
self.playing = false;
return ShowAction::StepBack(self.step);
}
if self.step > 0 {
self.step -= 1;
return ShowAction::StepBack(self.step);
self.step = k;
return ShowAction::StepBack(k);
}
let target = match self.prev_index(pres) {
Some(i) => Some(i),
+24
View File
@@ -808,6 +808,30 @@ fn show_steps_through_builds() {
assert_eq!(s.step, 1);
}
#[test]
fn show_back_leaves_a_slide_whose_first_step_is_automatic() {
// #844: undoing the automatic first step left the slide as before it appeared, and the show
// played that step again at once, so Back never reached the slide before.
for start in [AnimStart::WithPrevious, AnimStart::AfterPrevious] {
let mut p = pres(2);
Arc::make_mut(&mut p.slides[1]).shapes = vec![shape(1, "A"), shape(2, "B")];
Arc::make_mut(&mut p.slides[1]).animations =
vec![anim(1, AnimClass::Entrance, "fade", start), anim(2, AnimClass::Entrance, "fade", AnimStart::OnClick)];
let mut s = ShowState::new(&p);
assert_eq!(s.next(&p), ShowAction::Slide(1));
assert!(s.playing, "{start:?}");
// While the automatic step plays.
assert_eq!(s.prev(&p), ShowAction::Slide(0), "{start:?}");
assert_eq!(s.next(&p), ShowAction::Slide(1));
// Once it has played, the click step is undone first, then Back leaves the slide.
assert_eq!(s.next(&p), ShowAction::PlayStep(1));
assert_eq!(s.step_done(&p), ShowAction::FinishStep(1));
assert_eq!(s.prev(&p), ShowAction::StepBack(1), "{start:?}");
assert_eq!(s.prev(&p), ShowAction::Slide(0), "{start:?}");
assert_eq!((s.step, s.playing), (0, false));
}
}
#[test]
fn show_auto_advance() {
let mut p = pres(2);
+5 -1
View File
@@ -175,7 +175,11 @@ fn copied_html(s: &Session) -> String {
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
let caret = copying_caret(s);
let t = copy_inner(s, p)?;
let html = if caret { String::new() } else { copied_html(s) };
if caret {
// Nothing is selected, so there is nothing to cut; `delete` would remove the next character.
return Ok(json!({"text": t, "html": ""}));
}
let html = copied_html(s);
delete(s, p)?;
Ok(json!({"text": t, "html": html}))
}
+73 -28
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path, format?}", has_doc, save_as),
cmd!(noundo "file.saveTemplate", "Save as Template…", ["File"], None, "{path}", has_doc, save_as),
cmd!(query "file.saveBytes", "Save to Data", [], None, "{format?: deckcraft|pptx} → {data: base64}", has_doc, save_bytes_cmd),
cmd!(noundo "file.export", "Export…", ["File"], None, "{path, format?: png|jpeg|pptx|deckcraft|outline|pdf|gif (else by path), slide?: index, all?: bool, scale?: px per pt, layout?: slides|notes|handouts (pdf), perPage?: 1|2|3|4|6|9, paper?: letter|a4|legal|a3 (pdf), orientation?: portrait|landscape (pdf), dpi?, slides?: [index]|range (\"1-3,5\"), includeHidden?, textLayer?, frame?, width?: px 16-3840|small|medium|large|extraLarge (gif), secondsPerSlide?: 0.1-600 (gif; 5), loop?: bool (gif; true: forever)} → {path, bytes} or {files} (png, jpeg); gif adds frames, width, height, secondsPerSlide", has_doc, export),
cmd!(noundo "file.export", "Export…", ["File"], None, "{path, format?: png|jpeg|pptx|deckcraft|outline|pdf|gif (else by path), slide?: index, all?: bool, scale?: px per pt, layout?: slides|notes|handouts (pdf), perPage?: 1|2|3|4|6|9, paper?: letter|a4|legal|a3 (pdf), orientation?: portrait|landscape (pdf), dpi?, slides?: [index]|range (\"1-3,5\"), includeHidden?, textLayer?, frame?, transparentBackground?: bool (png: leave the slide background out), width?: px 16-3840|small|medium|large|extraLarge (gif), secondsPerSlide?: 0.1-600 (gif; 5), loop?: bool (gif; true: forever)} → {path, bytes} or {files} (png, jpeg); gif adds frames, width, height, secondsPerSlide", has_doc, export),
cmd!(
query "file.info",
"Info",
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
info
),
cmd!(query "file.render", "Render Slide", [], None, "{slide?: index, scale?, edit?: bool} → {png: base64, width, height}", has_doc, render),
cmd!(query "file.render", "Render Slide", [], None, "{slide?: index, scale?, edit?: bool, transparentBackground?: bool} → {png: base64, width, height}", has_doc, render),
cmd!(
query "slide.colorAt",
"Color At",
@@ -128,19 +128,35 @@ pub fn open_presentation(name: &str, bytes: &[u8]) -> Result<Presentation> {
open_checked(name, bytes).map(|(p, _)| p)
}
/// [`open_presentation`], plus the embedded media a `.deckcraft` file had lost or damaged.
pub fn open_checked(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec<String>)> {
if deckcraft_format::sniff(bytes) {
return deckcraft_format::load_checked(bytes).map_err(|e| EngineError::Other(e.to_string()));
}
open_other(name, bytes).map(|p| (p, vec![]))
/// What a file lost on opening.
#[derive(Debug, Default, Clone)]
pub struct Damage {
/// Pictures and media a `.deckcraft` file had lost or damaged.
pub media: Vec<String>,
/// Slides a `.pptx` lists but that couldn't be read, so they are not in the presentation.
pub slides: Vec<String>,
}
fn open_other(name: &str, bytes: &[u8]) -> Result<Presentation> {
impl Damage {
pub fn is_empty(&self) -> bool {
self.media.is_empty() && self.slides.is_empty()
}
}
/// [`open_presentation`], plus what the file had lost or damaged.
pub fn open_checked(name: &str, bytes: &[u8]) -> Result<(Presentation, Damage)> {
if deckcraft_format::sniff(bytes) {
let (p, media) = deckcraft_format::load_checked(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
return Ok((p, Damage { media, slides: vec![] }));
}
open_other(name, bytes).map(|(p, slides)| (p, Damage { media: vec![], slides }))
}
fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec<String>)> {
if deckcraft_pptx::sniff(bytes) {
let mut p = deckcraft_pptx::import(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let (mut p, lost_slides) = deckcraft_pptx::import_checked(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
deckcraft_format::repair(&mut p);
return Ok(p);
return Ok((p, lost_slides));
}
if deckcraft_pptx::is_encrypted(bytes) {
return Err(EngineError::Other(format!("{name} is password-protected. DeckCraft can't open password-protected presentations yet.")));
@@ -157,7 +173,7 @@ fn open_other(name: &str, bytes: &[u8]) -> Result<Presentation> {
if p.slides.is_empty() {
p = defaults::new_presentation(None);
}
return Ok(p);
return Ok((p, vec![]));
}
Err(EngineError::Other(format!("{name}: not a presentation DeckCraft can read")))
}
@@ -180,8 +196,8 @@ pub struct LoadedFile {
pub doc: Presentation,
/// A native or PPTX file (saving goes back to it); an outline import has no file to save to.
pub native: bool,
/// Pictures and media a `.deckcraft` file had lost or damaged.
pub damaged: Vec<String>,
/// What the file had lost or damaged.
pub damaged: Damage,
}
/// Read and parse the presentation at `path`.
@@ -202,7 +218,10 @@ fn adopt_loaded(s: &mut Session, f: LoadedFile) -> Result<Value> {
let i = add_opened(s, &path, keep_path.then(|| path.clone()), doc);
report_damage(s, &damaged)?;
let st = s.doc()?;
Ok(json!({"document": i, "slides": st.doc.slides.len(), "missingFonts": st.missing_fonts, "damagedMedia": damaged}))
Ok(json!({
"document": i, "slides": st.doc.slides.len(), "missingFonts": st.missing_fonts,
"damagedMedia": damaged.media, "lostSlides": damaged.slides,
}))
}
#[cfg(not(target_arch = "wasm32"))]
@@ -236,23 +255,35 @@ fn open_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let (doc, damaged) = open_checked(name, &data)?;
let i = add_opened(s, name, None, doc);
report_damage(s, &damaged)?;
Ok(json!({"document": i, "missingFonts": s.doc()?.missing_fonts, "damagedMedia": damaged}))
Ok(json!({"document": i, "missingFonts": s.doc()?.missing_fonts, "damagedMedia": damaged.media, "lostSlides": damaged.slides}))
}
/// Tell the user which pictures and media a damaged file lost, and mark the copy repaired.
fn report_damage(s: &mut Session, damaged: &[String]) -> Result<()> {
/// Tell the user which pictures, media and slides a damaged file lost, and mark the copy repaired.
fn report_damage(s: &mut Session, damaged: &Damage) -> Result<()> {
if damaged.is_empty() {
return Ok(());
}
let st = s.doc_mut()?;
st.title = format!("{} (Repaired)", st.title);
let n = damaged.len();
let text = format!(
"{n} picture{} or media file{} in this presentation couldn't be read and {} empty. It was opened as a repaired copy; save it under a new name to keep the original file.",
if n == 1 { "" } else { "s" },
if n == 1 { "" } else { "s" },
if n == 1 { "is" } else { "are" },
);
let mut text = String::new();
let n = damaged.media.len();
if n > 0 {
text = format!(
"{n} picture{} or media file{} in this presentation couldn't be read and {} empty. ",
if n == 1 { "" } else { "s" },
if n == 1 { "" } else { "s" },
if n == 1 { "is" } else { "are" },
);
}
let n = damaged.slides.len();
if n > 0 {
text.push_str(&format!(
"{n} slide{} in this file couldn't be read and {} left out. ",
if n == 1 { "" } else { "s" },
if n == 1 { "was" } else { "were" },
));
}
text.push_str("It was opened as a repaired copy; save it under a new name to keep the original file.");
s.ui_requests.push(crate::UiRequest::Message { text });
Ok(())
}
@@ -431,8 +462,14 @@ pub fn image_scale(doc: &Presentation, scale: f64) -> f64 {
/// Render slide `index` (current when absent) to PNG bytes.
pub fn render_png(doc: &Presentation, index: usize, scale: f64, edit: bool) -> (Vec<u8>, u32, u32) {
render_png_with(doc, index, scale, edit, false)
}
/// [`render_png`]; `transparent` leaves the slide background out (#784).
pub fn render_png_with(doc: &Presentation, index: usize, scale: f64, edit: bool, transparent: bool) -> (Vec<u8>, u32, u32) {
let scale = image_scale(doc, scale);
let img = deckcraft_render::render_slide(doc, index, &deckcraft_render::RenderOpts { scale, edit, ..Default::default() });
let opts = deckcraft_render::RenderOpts { scale, edit, transparent_background: transparent, ..Default::default() };
let img = deckcraft_render::render_slide(doc, index, &opts);
(img.to_png_at(deckcraft_render::dpi_for_scale(scale)), img.width, img.height)
}
@@ -451,7 +488,7 @@ fn render(s: &mut Session, p: &Value) -> Result<Value> {
if i >= st.doc.slides.len() {
return Err(bad("file.render", format!("no slide {i}")));
}
let (png, w, h) = render_png(&st.doc, i, f64_or(p, "scale", 1.0), bool_or(p, "edit", false));
let (png, w, h) = render_png_with(&st.doc, i, f64_or(p, "scale", 1.0), bool_or(p, "edit", false), bool_or(p, "transparentBackground", false));
Ok(json!({"png": base64_encode(&png), "width": w, "height": h}))
}
@@ -483,6 +520,10 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
let format = str_param(p, "format").unwrap_or(format_for_path(&path)).to_string();
let st = s.doc()?;
let scale = finite_scale(f64_or(p, "scale", 2.0));
let transparent = bool_or(p, "transparentBackground", false);
if transparent && format != "png" {
return Err(bad("file.export", format!("a transparent background is for PNG export, not {format}")));
}
match format.as_str() {
"png" | "jpeg" | "jpg" => {
let slides: Vec<usize> = match usize_param(p, "slide") {
@@ -497,7 +538,11 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
let scale = image_scale(&st.doc, scale);
let mut written = vec![];
for (k, i) in slides.iter().enumerate() {
let img = deckcraft_render::render_slide(&st.doc, *i, &deckcraft_render::RenderOpts { scale, ..Default::default() });
let img = deckcraft_render::render_slide(
&st.doc,
*i,
&deckcraft_render::RenderOpts { scale, transparent_background: transparent, ..Default::default() },
);
let bytes = picture_bytes(&img, &format, scale);
let out = if slides.len() == 1 {
path.clone()
+23 -13
View File
@@ -698,21 +698,28 @@ fn case(s: &mut Session, p: &Value) -> Result<Value> {
let from = if pi == a.0 { a.1 } else { 0 };
let to = if pi == b.0 { b.1 } else { n };
let mut pos = 0;
for r in &mut para.runs {
let mut pieces = Vec::new();
for (ri, r) in para.runs.iter().enumerate() {
// Breaks and fields are read for context (a break ends a word) but not rewritten.
let len = r.char_len();
if r.kind == deckcraft_model::text::RunKind::Text {
let rs = from.max(pos).saturating_sub(pos);
let re = to.min(pos + len).saturating_sub(pos);
if re > rs {
let chars: Vec<char> = r.text.chars().collect();
let mid: String = chars.get(rs..re).map(|c| c.iter().collect()).unwrap_or_default();
let pre: String = chars.get(..rs).map(|c| c.iter().collect()).unwrap_or_default();
let post: String = chars.get(re..).map(|c| c.iter().collect()).unwrap_or_default();
r.text = format!("{pre}{}{post}", ed::change_case(&mid, &m));
}
let rs = from.max(pos).saturating_sub(pos);
let re = to.min(pos + len).saturating_sub(pos);
if re > rs {
pieces.push((ri, rs, re));
}
pos += len;
}
let mids: Vec<String> = pieces
.iter()
.map(|&(ri, rs, re)| para.runs.get(ri).map(|r| r.content().chars().skip(rs).take(re - rs).collect()).unwrap_or_default())
.collect();
let changed = ed::change_case_parts(&mids.iter().map(String::as_str).collect::<Vec<_>>(), &m);
for (&(ri, rs, re), new) in pieces.iter().zip(changed) {
let Some(r) = para.runs.get_mut(ri).filter(|r| r.kind == deckcraft_model::text::RunKind::Text) else { continue };
let pre: String = r.text.chars().take(rs).collect();
let post: String = r.text.chars().skip(re).collect();
r.text = format!("{pre}{new}{post}");
}
}
if collapsed {
t.anchor = a;
@@ -734,9 +741,12 @@ fn case(s: &mut Session, p: &Value) -> Result<Value> {
edit_shapes(s, &json!({}), "format.case", |sh| {
if let Some(t) = sh.text.as_mut() {
for para in &mut t.paragraphs {
for r in &mut para.runs {
// Breaks and fields are read for context (a break ends a word) but not rewritten.
let texts: Vec<&str> = para.runs.iter().map(|r| r.content()).collect();
let changed = ed::change_case_parts(&texts, &mode);
for (r, new) in para.runs.iter_mut().zip(changed) {
if r.kind == deckcraft_model::text::RunKind::Text {
r.text = ed::change_case(&r.text, &mode);
r.text = new;
}
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ use crate::{Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
noundo "shape.editPoints",
"shape.editPoints",
"Edit Points",
["Shape Format", "Insert Shapes", "Edit Shape"],
None,
+137 -3
View File
@@ -3,11 +3,13 @@
//! The slides take the destination's look by default (each one moves to the destination layout
//! with the same name, else the same kind); with `keepFormatting` the source master and its
//! layouts come along. Pictures, media and sounds are copied under fresh ids, and shape ids are
//! renumbered with animations, triggers and connector ends following them.
//! renumbered with animations, triggers and connector ends following them. Links to another
//! reused slide follow its copy.
use std::collections::HashMap;
use std::sync::Arc;
use deckcraft_model::text::{Action, Hyperlink, RunProps, TextBody};
use deckcraft_model::{LayoutId, MasterId, MediaId, Presentation, ShapeId, ShapeKind, Slide, SlideId};
use serde_json::{Value, json};
@@ -60,6 +62,57 @@ fn remap_connectors(shapes: &mut [deckcraft_model::Shape], map: &HashMap<ShapeId
}
}
/// Point a link to a reused slide at its copy (`map`: source → destination).
fn relink(h: &mut Option<Hyperlink>, map: &HashMap<SlideId, SlideId>) {
let Some(h) = h else { return };
if let Action::Slide { slide } = &mut h.action {
*slide = map.get(slide).copied().unwrap_or(*slide);
}
if let Some(z) = &mut h.zoom_return {
*z = map.get(z).copied().unwrap_or(*z);
}
}
fn relink_run(r: &mut RunProps, map: &HashMap<SlideId, SlideId>) {
relink(&mut r.link, map);
relink(&mut r.hover, map);
}
fn relink_text(t: &mut TextBody, map: &HashMap<SlideId, SlideId>) {
for lv in t.list_style.levels.iter_mut().flatten() {
relink_run(&mut lv.run, map);
}
for p in &mut t.paragraphs {
relink_run(&mut p.def_props, map);
relink_run(&mut p.end_props, map);
for r in &mut p.runs {
relink_run(&mut r.props, map);
}
}
}
/// Point the slide links under `shapes` (click and hover actions, text links) at the copies.
fn relink_shapes(shapes: &mut [deckcraft_model::Shape], map: &HashMap<SlideId, SlideId>, depth: usize) {
if depth > 64 {
return;
}
for sh in shapes {
relink(&mut sh.click, map);
relink(&mut sh.hover, map);
if let Some(t) = &mut sh.text {
relink_text(t, map);
}
if let ShapeKind::Table(t) = &mut sh.kind {
for c in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
relink_text(&mut c.text, map);
}
}
if let Some(ch) = sh.children_mut() {
relink_shapes(ch, map, depth + 1);
}
}
}
/// Fresh shape ids for `shapes`, and the old → new map.
fn renumber(doc: &mut Presentation, shapes: &mut [deckcraft_model::Shape]) -> Result<HashMap<ShapeId, ShapeId>> {
let old = shape_ids(shapes);
@@ -134,8 +187,10 @@ fn reuse(s: &mut Session, p: &Value) -> Result<Value> {
doc.masters.push(Arc::new(m));
}
}
let mut new_ids = vec![];
for (k, &i) in picked.iter().enumerate() {
let mut copies: Vec<Slide> = vec![];
// Source slide → its copy, so links between reused slides follow (forward ones too).
let mut slide_map: HashMap<SlideId, SlideId> = HashMap::new();
for &i in &picked {
let Some(from) = src.slides.get(i) else { continue };
copy_media(doc, &src, &media_refs::slide_media(from), &mut media_map)?;
let mut sl: Slide = from.as_ref().clone();
@@ -154,6 +209,13 @@ fn reuse(s: &mut Session, p: &Value) -> Result<Value> {
matching_layout(doc, &lname, kind)
}
};
slide_map.insert(from.id, sl.id);
copies.push(sl);
}
let mut new_ids = vec![];
for (k, mut sl) in copies.into_iter().enumerate() {
relink_shapes(&mut sl.shapes, &slide_map, 0);
relink_text(&mut sl.notes, &slide_map);
new_ids.push(sl.id);
doc.slides.insert((at + k).min(doc.slides.len()), Arc::new(sl));
}
@@ -263,4 +325,76 @@ mod tests {
want.sort();
assert_eq!(got, want, "every reference resolves to its own copied bytes");
}
fn link_to(slide: SlideId) -> Hyperlink {
Hyperlink {
action: Action::Slide { slide },
tooltip: String::new(),
highlight_click: false,
sound: None,
stop_sound: false,
zoom_return: None,
}
}
fn linked_text(slide: SlideId) -> TextBody {
let mut text = TextBody::from_text("go");
if let Some(r) = text.paragraphs.first_mut().and_then(|p| p.runs.first_mut()) {
r.props.link = Some(link_to(slide));
}
text
}
/// Links to a slide that is reused too follow the copy; links to a slide left behind stay.
#[test]
fn reused_slides_link_to_each_others_copies() {
let mut src = defaults::new_presentation(None);
let template = src.slides.first().map(|s| s.as_ref().clone()).expect("slide");
for _ in 0..2 {
let mut sl = template.clone();
sl.id = SlideId(src.alloc_id().expect("id"));
src.slides.push(Arc::new(sl));
}
let ids: Vec<SlideId> = src.slides.iter().map(|s| s.id).collect();
let id = |i: usize| ids.get(i).copied().unwrap_or_default();
if let Some(sl) = src.slides.first_mut().map(Arc::make_mut) {
sl.shapes = vec![
Shape { id: ShapeId(9001), click: Some(link_to(id(1))), ..Default::default() },
Shape { id: ShapeId(9002), text: Some(linked_text(id(1))), ..Default::default() },
Shape { id: ShapeId(9003), click: Some(link_to(id(2))), ..Default::default() },
];
}
if let Some(sl) = src.slides.get_mut(1).map(Arc::make_mut) {
sl.shapes = vec![Shape { id: ShapeId(9004), click: Some(link_to(id(0))), ..Default::default() }];
}
let bytes = deckcraft_format::save(&src).expect("save");
let reopened = crate::cmd::file::open_presentation("src.deckcraft", &bytes).expect("open");
let left_behind = reopened.slides.get(2).map(|s| s.id).expect("third slide");
let mut s = Session::with_new();
for _ in 0..3 {
s.execute("slide.new", &json!({})).expect("new");
}
let out = s
.execute("slide.reuse", &json!({"data": super::super::base64_encode(&bytes), "name": "src.deckcraft", "slides": [0, 1]}))
.expect("reuse");
let new: Vec<SlideId> = serde_json::from_value(out.get("ids").cloned().unwrap_or_default()).expect("ids");
let doc = &s.doc().expect("doc").doc;
let copy = |i: usize| new.get(i).and_then(|id| doc.slide(*id)).expect("copied slide");
let click = |sh: Option<&Shape>| sh.and_then(|sh| sh.click.as_ref()).map(|h| h.action.clone());
let first = copy(0);
let to = |i: usize| Some(Action::Slide { slide: new.get(i).copied().unwrap_or_default() });
assert_eq!(click(first.shapes.first()), to(1), "shape click follows the copy");
let run_link = first
.shapes
.get(1)
.and_then(|sh| sh.text.as_ref())
.and_then(|t| t.paragraphs.first())
.and_then(|p| p.runs.first())
.and_then(|r| r.props.link.as_ref())
.map(|h| h.action.clone());
assert_eq!(run_link, to(1), "text link follows the copy");
assert_eq!(click(first.shapes.get(2)), Some(Action::Slide { slide: left_behind }), "a slide not reused keeps its link");
assert_eq!(click(copy(1).shapes.first()), to(0), "a link back to an earlier copy follows too");
}
}
+22 -1
View File
@@ -137,7 +137,14 @@ fn reply(s: &mut Session, p: &Value) -> Result<Value> {
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
let all = bool_or(p, "all", false);
let i = usize_param(p, "index");
let i = match p.get("index") {
None | Some(Value::Null) => None,
Some(v) => Some(
v.as_u64()
.and_then(|v| usize::try_from(v).ok())
.ok_or_else(|| bad("comment.delete", format!("`index` is not a valid comment index: {v}")))?,
),
};
s.edit(|doc, sel| {
if all {
for sl in &mut doc.slides {
@@ -793,4 +800,18 @@ mod tests {
s.execute("show.setup", &json!({"custom": ""})).unwrap();
assert!(s.active().unwrap().doc.show.custom_show.is_none());
}
#[test]
fn delete_rejects_an_invalid_index_and_keeps_the_comments() {
let mut s = Session::with_new();
s.execute("comment.add", &json!({"text": "a"})).unwrap();
s.execute("comment.add", &json!({"text": "b"})).unwrap();
for bad_index in [json!(-1), json!("2"), json!(1.5)] {
let r = s.execute("comment.delete", &json!({"index": bad_index}));
assert!(r.is_err(), "index {bad_index} gave {r:?}");
assert_eq!(s.active().unwrap().doc.slides[0].comments.len(), 2, "index {bad_index}");
}
s.execute("comment.delete", &json!({})).unwrap();
assert!(s.active().unwrap().doc.slides[0].comments.is_empty());
}
}
+24 -14
View File
@@ -274,20 +274,22 @@ fn decode_text(raw: &str) -> String {
break;
};
let entity = &rest[1..end];
rest = &rest[end + 1..];
match entity {
"amp" => out.push('&'),
"lt" => out.push('<'),
"gt" => out.push('>'),
"quot" => out.push('"'),
"apos" => out.push('\''),
"nbsp" => out.push(' '),
_ => {
let ch = entity.strip_prefix('#').and_then(numeric_char);
if let Some(c) = ch {
out.push(c);
}
}
let decoded = match entity {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" => Some('\''),
"nbsp" => Some(' '),
_ => entity.strip_prefix('#').and_then(numeric_char),
};
if let Some(c) = decoded {
out.push(c);
rest = &rest[end + 1..];
} else {
// Not a well-formed entity (e.g. a bare "R&D"): keep the '&' as typed.
out.push('&');
rest = &rest[1..];
}
}
if !rest.is_empty() && !rest.starts_with('&') {
@@ -350,6 +352,14 @@ mod tests {
assert!(last.props.underline.is_some());
}
#[test]
fn bare_ampersand_keeps_text_up_to_next_semicolon() {
let text = |html: &str| html_to_body(html).unwrap().text();
assert_eq!(text("<p>R&D costs; up</p>"), "R&D costs; up");
assert_eq!(text("<p>AT&T; Q&A</p>"), "AT&T; Q&A");
assert_eq!(text("<p>A &amp; B &#38; C &#x26; D</p>"), "A & B & C & D");
}
#[test]
fn pages_style_and_escapes() {
let html = "<html><head><style>p{}</style></head><body><p><span style=\"font-weight: bold\">A &amp; B</span></p><p><span style=\"font-style: italic\">C</span></p></body></html>";
+23 -8
View File
@@ -169,13 +169,24 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Keeps a side length in `0..=MAX_PT` so a huge value cannot exhaust memory when rendering.
/// An overflow to infinity lands on the limit; NaN becomes 0.
fn clamp_side(v: f64) -> f64 {
if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_PT) }
}
/// Keeps a coordinate within `±POS_LIMIT`.
fn clamp_pos(v: f64) -> f64 {
if v.is_nan() { 0.0 } else { v.clamp(-POS_LIMIT, POS_LIMIT) }
}
fn move_by(s: &mut Session, p: &Value) -> Result<Value> {
let (dx, dy) = (f64_param(p, "dx"), f64_param(p, "dy"));
let (ax, ay) = (f64_param(p, "x"), f64_param(p, "y"));
edit_geometry(s, p, "shape.move", |sh| {
if let Some(x) = sh.xfrm.as_mut() {
x.x = ax.unwrap_or(x.x) + dx.unwrap_or(0.0);
x.y = ay.unwrap_or(x.y) + dy.unwrap_or(0.0);
x.x = clamp_pos(ax.unwrap_or(x.x) + dx.unwrap_or(0.0));
x.y = clamp_pos(ay.unwrap_or(x.y) + dy.unwrap_or(0.0));
}
Ok(())
})
@@ -202,10 +213,12 @@ fn resize(s: &mut Session, p: &Value) -> Result<Value> {
x.h = h.unwrap_or(x.h);
}
}
x.w = clamp_side(x.w);
x.h = clamp_side(x.h);
// Rotated shapes resize about their centre; others keep the top-left.
if x.rot != 0.0 {
x.x = cx - x.w / 2.0;
x.y = cy - x.h / 2.0;
x.x = clamp_pos(cx - x.w / 2.0);
x.y = clamp_pos(cy - x.h / 2.0);
}
}
Ok(())
@@ -215,10 +228,10 @@ fn resize(s: &mut Session, p: &Value) -> Result<Value> {
fn set_bounds(s: &mut Session, p: &Value) -> Result<Value> {
edit_geometry(s, p, "shape.setBounds", |sh| {
if let Some(x) = sh.xfrm.as_mut() {
x.x = f64_param(p, "x").unwrap_or(x.x);
x.y = f64_param(p, "y").unwrap_or(x.y);
x.w = f64_param(p, "w").unwrap_or(x.w).max(0.0);
x.h = f64_param(p, "h").unwrap_or(x.h).max(0.0);
x.x = clamp_pos(f64_param(p, "x").unwrap_or(x.x));
x.y = clamp_pos(f64_param(p, "y").unwrap_or(x.y));
x.w = clamp_side(f64_param(p, "w").unwrap_or(x.w));
x.h = clamp_side(f64_param(p, "h").unwrap_or(x.h));
}
Ok(())
})
@@ -406,6 +419,8 @@ fn flip(s: &mut Session, p: &Value) -> Result<Value> {
} else {
x.flip_h = !x.flip_h;
}
// `Xfrm::affine` flips first and rotates second; a true mirror also negates the rotation.
x.rot = (360.0 - x.rot_norm()) % 360.0;
}
Ok(())
})
+11
View File
@@ -627,6 +627,17 @@ fn from_outline(s: &mut Session, p: &Value) -> Result<Value> {
for (k, sl) in new.into_iter().enumerate() {
doc.slides.insert(at + k, sl);
}
// Join the section of the slide before, as slide.new does.
let ids: Vec<SlideId> = doc.slides.iter().skip(at).take(n).map(|x| x.id).collect();
let prev = at.checked_sub(1).and_then(|i| doc.slides.get(i)).map(|x| x.id);
let section = prev.and_then(|p| doc.section_of(p));
if let Some(sec) = section.and_then(|si| doc.sections.get_mut(si)) {
let pos = prev.and_then(|p| sec.slides.iter().position(|x| *x == p)).map(|k| k + 1).unwrap_or(sec.slides.len());
let pos = pos.min(sec.slides.len());
sec.slides.splice(pos..pos, ids);
} else if let Some(first) = doc.sections.first_mut() {
first.slides.splice(0..0, ids);
}
Ok(json!({"slides": n}))
})
}
+2 -2
View File
@@ -537,7 +537,7 @@ fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
with_table(s, p, "table.columnWidth", move |t| {
// Keeping the table's width, the column to the right gives or takes the difference (dragging
// an inner border). The last column has none: the table gets wider or narrower.
let pair = t.cols.get(c).zip(t.cols.get(c + 1)).map(|(a, b)| a.max(0.0) + b.max(0.0)).filter(|x| x.is_finite());
let pair = t.cols.get(c).zip(t.cols.get(c.saturating_add(1))).map(|(a, b)| a.max(0.0) + b.max(0.0)).filter(|x| x.is_finite());
match pair {
Some(pair) if keep_total => {
let min = MIN_COLUMN_WIDTH.min(pair / 2.0);
@@ -545,7 +545,7 @@ fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(x) = t.cols.get_mut(c) {
*x = w;
}
if let Some(x) = t.cols.get_mut(c + 1) {
if let Some(x) = t.cols.get_mut(c.saturating_add(1)) {
*x = pair - w;
}
}
+46 -3
View File
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
"AutoCorrect Options",
["Tools"],
None,
"{on?, twoInitials?, sentenceCaps?, days?, capsLock?, fractions?: bool, add?: [from, to], remove?: from} → the options and the replacement list",
"{on?, twoInitials?, sentenceCaps?, days?, capsLock?, fractions?, ordinals?: bool, add?: [from, to], remove?: from} → the options and the replacement list",
always,
autocorrect_options
),
@@ -655,7 +655,12 @@ fn autocorrect(s: &mut Session, typing: bool) -> Result<()> {
} else {
correct_word(&s.prefs, &word, sentence_start, typing)
};
let Some(rep) = rep else { return Ok(()) };
let Some(rep) = rep else {
if typing && s.prefs.ac_ordinals && is_ordinal(&word) {
return superscript_suffix(s, &t, word_end);
}
return Ok(());
};
let delta = rep.chars().count() as isize - word.chars().count() as isize;
let st = s.doc_mut()?;
let mut d = (*st.doc).clone();
@@ -674,6 +679,43 @@ fn autocorrect(s: &mut Session, typing: bool) -> Result<()> {
Ok(())
}
/// `word` is a number with the ordinal suffix it takes (1st, 22nd, 103rd, 11th), as AutoFormat
/// superscripts it.
fn is_ordinal(word: &str) -> bool {
let digits = word.trim_end_matches(|c: char| c.is_ascii_lowercase());
let suffix = word.get(digits.len()..).unwrap_or_default();
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) || suffix.len() != 2 {
return false;
}
let d = digits.as_bytes();
let teen = d.len() >= 2 && d.get(d.len() - 2) == Some(&b'1');
let want = match d.last() {
_ if teen => "th",
Some(b'1') => "st",
Some(b'2') => "nd",
Some(b'3') => "rd",
_ => "th",
};
suffix == want
}
/// Superscript the two letters before `end` in the caret's paragraph (an ordinal's suffix).
fn superscript_suffix(s: &mut Session, t: &crate::TextSel, end: usize) -> Result<()> {
let (a, b) = ((t.caret.0, end.saturating_sub(2)), (t.caret.0, end));
let st = s.doc_mut()?;
if body_of(st, t).is_none_or(|body| ed::props_at(body, b).baseline.unwrap_or(0.0) > 0.0) {
return Ok(());
}
let mut d = (*st.doc).clone();
let sel = st.selection.clone();
if let Some(body) = body_mut(&mut d, &sel, t) {
ed::format(body, a, b, &|r| r.baseline = Some(0.3));
}
st.doc = Arc::new(d);
st.revision += 1;
Ok(())
}
fn autocorrect_options(s: &mut Session, p: &Value) -> Result<Value> {
let pr = &mut s.prefs;
for (key, slot) in [
@@ -683,6 +725,7 @@ fn autocorrect_options(s: &mut Session, p: &Value) -> Result<Value> {
("days", &mut pr.ac_days),
("capsLock", &mut pr.ac_caps_lock),
("fractions", &mut pr.ac_fractions),
("ordinals", &mut pr.ac_ordinals),
] {
if let Some(v) = p.get(key).and_then(Value::as_bool) {
*slot = v;
@@ -729,7 +772,7 @@ fn autocorrect_options(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({
"on": pr.autocorrect, "twoInitials": pr.ac_two_initials, "sentenceCaps": pr.ac_sentence_caps,
"days": pr.ac_days, "capsLock": pr.ac_caps_lock, "fractions": pr.ac_fractions,
"entries": list,
"ordinals": pr.ac_ordinals, "entries": list,
}))
}
+3 -1
View File
@@ -324,12 +324,13 @@ pub struct Prefs {
pub smart_quotes: bool,
/// AutoCorrect options (Tools ▸ AutoCorrect): fix TWo INitial CApitals, capitalize the first
/// letter of sentences and the names of days, fix accidental cAPS lOCK, and replace 1/2, 1/4
/// and 3/4 with fraction characters.
/// and 3/4 with fraction characters; AutoFormat superscripts ordinals (1st) as you type.
pub ac_two_initials: bool,
pub ac_sentence_caps: bool,
pub ac_days: bool,
pub ac_caps_lock: bool,
pub ac_fractions: bool,
pub ac_ordinals: bool,
/// Your own "replace … with …" entries; they win over the built-in list.
pub ac_entries: Vec<(String, String)>,
/// Built-in entries you deleted.
@@ -354,6 +355,7 @@ impl Default for Prefs {
ac_days: true,
ac_caps_lock: true,
ac_fractions: true,
ac_ordinals: true,
ac_entries: Vec::new(),
ac_removed: Vec::new(),
author: "Presenter".into(),
+4 -1
View File
@@ -311,7 +311,10 @@ mod tests {
let opened = open(&mut s2, &dir).unwrap();
assert!(s2.documents().iter().all(|d| d.uid != uid), "{opened:?}");
assert!(lock_path(&dir, other).exists(), "a live owner's lock stays");
// Once the owner is gone, its entry is recovered and its lock file cleaned up.
// Once the owner is gone, its entry is recovered and its lock file cleaned up. Unlock
// rather than only drop: a child spawned meanwhile by a parallel test (mkfifo) shares the
// open file and would keep the lock held until it execs.
lock.unlock().unwrap();
drop(lock);
let mut s3 = Session::new();
open(&mut s3, &dir).unwrap();
+481 -1
View File
@@ -94,6 +94,26 @@ fn text_editing_flow() {
assert_eq!(s.doc().unwrap().selection.shapes.len(), 1);
}
/// Cut with only a caret copies nothing, so it must not delete the character after the caret.
#[test]
fn cut_with_only_a_caret_changes_nothing() {
let mut s = session();
let r = s.execute("insert.textBox", &json!({"text": "Hello"})).unwrap();
let id = r["id"].as_u64().unwrap();
s.execute("text.edit", &json!({"id": id})).unwrap();
s.execute("text.move", &json!({"to": "start"})).unwrap();
let out = s.execute("edit.cut", &json!({})).unwrap();
assert_eq!(out["text"], "");
let t = s.execute("text.get", &json!({"id": id})).unwrap();
assert_eq!(t["text"], "Hello", "cut with only a caret changed the text");
// A real selection is still cut.
s.execute("text.move", &json!({"to": "end", "extend": true})).unwrap();
let out = s.execute("edit.cut", &json!({})).unwrap();
assert_eq!(out["text"], "Hello");
let t = s.execute("text.get", &json!({"id": id})).unwrap();
assert_eq!(t["text"], "");
}
#[test]
fn editing_text_refits_a_saved_shrink() {
use deckcraft_model::text::AutoFit;
@@ -2777,6 +2797,33 @@ fn a_png_export_records_the_slide_resolution() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #784: `transparentBackground` leaves the slide background out of a PNG export, so only the
/// slide's content is opaque; formats without transparency refuse it and write nothing.
#[test]
fn a_png_export_can_leave_the_background_transparent() {
let mut s = session();
s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 200, 100]})).unwrap();
s.execute("design.background", &json!({"color": "#0000C8"})).unwrap();
let dir = std::env::temp_dir().join(format!("deckcraft-transparent-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let read = |path: &std::path::Path| image::load_from_memory(&std::fs::read(path).unwrap()).unwrap().to_rgba8();
let opaque = dir.join("opaque.png");
s.execute("file.export", &json!({"path": opaque.to_str().unwrap(), "scale": 1})).unwrap();
assert_eq!(read(&opaque).get_pixel(5, 5).0, [0, 0, 200, 255], "the background draws by default");
let clear = dir.join("clear.png");
s.execute("file.export", &json!({"path": clear.to_str().unwrap(), "scale": 1, "transparentBackground": true})).unwrap();
let img = read(&clear);
assert_eq!(img.get_pixel(5, 5).0[3], 0, "no background: {:?}", img.get_pixel(5, 5));
assert_eq!(img.get_pixel(200, 150).0[3], 255, "the shape stays opaque: {:?}", img.get_pixel(200, 150));
for (name, format) in [("slide.jpg", "jpeg"), ("deck.pdf", "pdf"), ("deck.gif", "gif"), ("deck.pptx", "pptx")] {
let path = dir.join(name);
let e = s.execute("file.export", &json!({"path": path.to_str().unwrap(), "format": format, "transparentBackground": true})).unwrap_err();
assert!(e.to_string().contains("for PNG export"), "{format}: {e}");
assert!(!path.exists(), "{format}: nothing is written");
}
let _ = std::fs::remove_dir_all(&dir);
}
fn png_size(bytes: &[u8]) -> Option<(u32, u32)> {
let w: [u8; 4] = bytes.get(16..20)?.try_into().ok()?;
let h: [u8; 4] = bytes.get(20..24)?.try_into().ok()?;
@@ -3120,6 +3167,37 @@ fn autocorrect_options_as_you_type() {
assert_eq!(s.execute("text.get", &json!({"id": title})).unwrap()["text"], "monday notes ");
}
#[test]
fn autocorrect_superscripts_ordinals_as_you_type() {
let mut s = session();
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
// The typed text with each superscript run in ^(…).
let typed = |s: &mut Session, text: &str| -> String {
s.execute("text.edit", &json!({"id": title})).unwrap();
s.execute("text.selectAll", &json!({})).ok();
s.execute("text.delete", &json!({"dir": "backward"})).ok();
for c in text.chars() {
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
}
let st = s.doc().unwrap();
let sh = st.current_slide().unwrap().shapes.iter().find(|sh| sh.id.0 == title).unwrap();
sh.text.as_ref().unwrap().paragraphs[0]
.runs
.iter()
.map(|r| if r.props.baseline.unwrap_or(0.0) > 0.0 { format!("^({})", r.text) } else { r.text.clone() })
.collect()
};
assert_eq!(typed(&mut s, "1st, 22nd and 103rd. 4th 11th x"), "1^(st), 22^(nd) and 103^(rd). 4^(th) 11^(th) x");
// Not a word, a number without a suffix it takes, or a suffix not yet followed by a space.
assert_eq!(typed(&mut s, "first x1st 1th 2st 21st"), "First x1st 1th 2st 21st");
assert_eq!(s.execute("text.autocorrect", &json!({})).unwrap()["ordinals"], true);
s.execute("text.autocorrect", &json!({"ordinals": false})).unwrap();
assert_eq!(typed(&mut s, "2nd "), "2nd ");
// AutoCorrect off turns it off too.
s.execute("text.autocorrect", &json!({"ordinals": true, "on": false})).unwrap();
assert_eq!(typed(&mut s, "2nd "), "2nd ");
}
#[test]
fn theme_variants_apply_and_report_the_current_one() {
let mut s = session();
@@ -3517,7 +3595,8 @@ fn background_loads_are_adopted_through_a_command() {
replay.execute(&id, &params).unwrap();
assert_eq!(replay.doc().unwrap().doc.slides.len(), 2);
// A token staged for another path is not taken for this one.
let other = s.stage_loaded(cmd::file::LoadedFile { path: "/elsewhere.pptx".into(), doc: Default::default(), native: true, damaged: vec![] });
let other =
s.stage_loaded(cmd::file::LoadedFile { path: "/elsewhere.pptx".into(), doc: Default::default(), native: true, damaged: Default::default() });
s.execute("file.adopt", &json!({"path": path, "token": other})).unwrap();
assert_eq!(s.doc().unwrap().doc.slides.len(), 2);
assert!(s.execute("file.adopt", &json!({})).is_err());
@@ -3592,3 +3671,404 @@ fn table_insert_below_or_right_of_a_huge_index_appends_at_the_end() {
assert_eq!(t.n_cols(), 3);
assert_eq!(t.cell(0, 1).unwrap().text.text(), "b", "the original columns keep their place");
}
#[test]
fn table_column_width_of_a_huge_column_is_ignored() {
let mut s = session();
let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
for keep_total in [true, false] {
let r = s.execute("table.columnWidth", &json!({"id": id.0, "col": u64::MAX, "width": 50.0, "keepTotal": keep_total}));
assert!(r.is_ok(), "columnWidth must ignore a huge col (keepTotal {keep_total}), got {r:?}");
assert_eq!(table_of(&s, id).cols, vec![100.0, 100.0], "no column changes");
}
}
/// Slides imported from an outline join the section of the slide they follow, like `slide.new`.
#[test]
fn slides_from_outline_join_the_section_of_the_slide_they_follow() {
for markdown in [false, true] {
let mut s = session();
s.execute("slide.new", &json!({"title": "A"})).unwrap();
s.execute("section.add", &json!({"name": "B", "at": 1})).unwrap();
let text = if markdown { "# Imported\n- bullet" } else { "Imported\n\tbullet" };
s.execute("slide.fromOutline", &json!({"text": text, "markdown": markdown})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let orphans: Vec<_> = doc.slides.iter().map(|x| x.id).filter(|id| doc.section_of(*id).is_none()).collect();
assert!(orphans.is_empty(), "markdown={markdown}: slides in no section: {orphans:?}; sections {:?}", doc.sections);
let order: Vec<_> = doc.sections.iter().flat_map(|x| x.slides.iter().copied()).collect();
let slides: Vec<_> = doc.slides.iter().map(|x| x.id).collect();
assert_eq!(order, slides, "markdown={markdown}: sections follow the slide order");
}
}
#[test]
fn opening_a_pptx_with_an_unreadable_slide_says_so() {
use std::io::{Cursor, Read, Write};
let mut s = session();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
assert_eq!(s.doc().unwrap().doc.slides.len(), 2);
let good = deckcraft_pptx::export(s.doc().unwrap().doc.as_ref()).unwrap();
let mut zin = zip::ZipArchive::new(Cursor::new(good.clone())).unwrap();
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
let o = zip::write::SimpleFileOptions::default();
for i in 0..zin.len() {
let mut f = zin.by_index(i).unwrap();
let mut d = vec![];
f.read_to_end(&mut d).unwrap();
if f.name() == "ppt/slides/slide2.xml" {
d = b"<p:sld".to_vec();
}
out.start_file(f.name(), o).unwrap();
out.write_all(&d).unwrap();
}
let broken = out.finish().unwrap().into_inner();
let mut t = session();
let r = t.execute("file.openBytes", &json!({"name": "Broken.pptx", "data": cmd::base64_encode(&broken)})).unwrap();
assert_eq!(r["lostSlides"], json!(["ppt/slides/slide2.xml"]), "{r}");
assert_eq!(t.doc().unwrap().doc.slides.len(), 1);
assert!(t.doc().unwrap().title.ends_with("(Repaired)"), "{}", t.doc().unwrap().title);
assert!(t.ui_requests.iter().any(|u| matches!(u, crate::UiRequest::Message { text } if text.contains("1 slide in this file couldn't be read"))));
// A good file reports nothing.
let mut u = session();
let r = u.execute("file.openBytes", &json!({"name": "Fine.pptx", "data": cmd::base64_encode(&good)})).unwrap();
assert_eq!(r["lostSlides"], json!([]), "{r}");
assert!(u.ui_requests.is_empty());
}
/// A file with absurd effect sizes opens with them capped at what Format Shape allows: drawn as
/// they were, a glow of 10^18 pt made the renderer ask for 34 GB and abort.
#[test]
fn opening_a_file_caps_absurd_effect_sizes() {
use deckcraft_model::style::{Glow, Reflection};
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 200, 100], "text": "Glow"})).unwrap();
s.execute("shape.effects", &json!({"shadow": "outer", "reflection": "tight", "softEdges": 4, "glow": {"radius": 8}})).unwrap();
s.execute("insert.table", &json!({"rows": 1, "cols": 1, "rect": [400, 300, 100, 40]})).unwrap();
let huge = 1e18;
s.edit(|doc, sel| {
let list = crate::shapes_mut(doc, sel).unwrap();
for sh in list.iter_mut() {
if let Some(e) = sh.effects.as_mut() {
e.glow.as_mut().unwrap().radius = huge;
e.soft_edge = Some(f64::NAN);
let sw = e.outer_shadow.as_mut().unwrap();
(sw.blur, sw.dist, sw.sx) = (huge, huge, huge);
*e.reflection.as_mut().unwrap() = Reflection { blur: huge, start_alpha: 0.5, end_alpha: 0.0, end_pos: 0.5, dist: huge };
}
let glow = Some(Glow { color: deckcraft_model::style::ColorRef::rgb(deckcraft_color::Rgba::BLACK), radius: huge });
let runs: Vec<&mut deckcraft_model::text::Run> = match &mut sh.kind {
deckcraft_model::ShapeKind::Table(t) => t
.rows
.iter_mut()
.flat_map(|r| r.cells.iter_mut())
.flat_map(|c| c.text.paragraphs.iter_mut())
.flat_map(|p| p.runs.iter_mut())
.collect(),
_ => sh.text.iter_mut().flat_map(|t| t.paragraphs.iter_mut()).flat_map(|p| p.runs.iter_mut()).collect(),
};
for r in runs {
r.props.glow = glow.clone();
}
}
// Inherited styles too: the deck default, a master's body style, a text box's own list
// style, and the theme's effect styles that shape styles point at.
let level = deckcraft_model::text::LevelStyle {
run: deckcraft_model::text::RunProps {
glow: Some(Glow { color: deckcraft_model::style::ColorRef::rgb(deckcraft_color::Rgba::BLACK), radius: huge }),
..Default::default()
},
..Default::default()
};
doc.default_text_style.set(0, level.clone());
let m = std::sync::Arc::make_mut(&mut doc.masters[0]);
m.body_style.set(0, level.clone());
if let Some(fx) = m.theme.format.effects.first_mut() {
fx.glow = Some(Glow { color: deckcraft_model::style::ColorRef::rgb(deckcraft_color::Rgba::BLACK), radius: huge });
}
let list = crate::shapes_mut(doc, sel).unwrap();
if let Some(t) = list.iter_mut().find_map(|sh| sh.text.as_mut()) {
t.list_style.set(0, level);
}
Ok(())
})
.unwrap();
for format in ["deckcraft", "pptx"] {
let bytes = cmd::file::save_bytes(&s.doc().unwrap().doc, format).unwrap();
let mut t = Session::new();
t.execute("file.openBytes", &json!({"name": format!("fx.{format}"), "data": cmd::base64_encode(&bytes)})).unwrap();
let st = t.doc().unwrap();
let slide = st.doc.slides.last().unwrap();
let mut glows = vec![];
deckcraft_model::walk(&slide.shapes, &mut |sh, _| {
if let Some(e) = &sh.effects {
glows.extend(e.glow.as_ref().map(|g| g.radius));
assert!(e.soft_edge.is_none_or(|v| (0.0..=100.0).contains(&v)), "{format}: {:?}", e.soft_edge);
if let Some(sw) = &e.outer_shadow {
assert!(sw.blur <= 200.0 && sw.dist <= 200.0 && sw.sx <= 10.0, "{format}: {sw:?}");
}
if let Some(r) = &e.reflection {
assert!(r.blur <= 100.0 && r.dist <= 100.0, "{format}: {r:?}");
}
}
for p in sh.text.iter().flat_map(|t| t.paragraphs.iter()) {
glows.extend(p.runs.iter().filter_map(|r| r.props.glow.as_ref().map(|g| g.radius)));
}
if let deckcraft_model::ShapeKind::Table(tb) = &sh.kind {
let cells = tb.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.text.paragraphs.iter());
glows.extend(cells.flat_map(|p| p.runs.iter()).filter_map(|r| r.props.glow.as_ref().map(|g| g.radius)));
}
});
let inherited = |ls: &deckcraft_model::text::ListStyle| {
ls.levels.iter().flatten().filter_map(|l| l.run.glow.as_ref().map(|g| g.radius)).collect::<Vec<_>>()
};
glows.extend(inherited(&st.doc.default_text_style));
let m = &st.doc.masters[0];
for ls in [&m.title_style, &m.body_style, &m.other_style] {
glows.extend(inherited(ls));
}
glows.extend(m.theme.format.effects.iter().filter_map(|e| e.glow.as_ref().map(|g| g.radius)));
deckcraft_model::walk(&slide.shapes, &mut |sh, _| glows.extend(sh.text.iter().flat_map(|t| inherited(&t.list_style))));
assert!(!glows.is_empty(), "{format}: the glows were kept");
assert!(glows.iter().all(|g| (0.0..=150.0).contains(g)), "{format}: {glows:?}");
// Capped, the slide renders (checked last: uncapped, this is what ran out of memory).
let i = st.doc.slides.len() - 1;
t.execute("file.render", &json!({"slide": i, "scale": 0.1})).unwrap();
}
}
/// A .deckcraft file whose shapes repeat an id (groups included) opens with fresh ids for the
/// repeats: the deck passes `validate`, the first shape keeps its id and none is lost.
#[test]
fn opening_a_file_gives_repeated_shape_ids_fresh_ones() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
for x in [0, 100, 200, 300] {
s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, 50, 80, 80]})).unwrap();
}
s.execute("edit.selectAll", &json!({})).unwrap();
s.execute("arrange.group", &json!({})).unwrap();
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [400, 300, 80, 80]})).unwrap();
let first = s.doc().unwrap().shapes()[0].id;
// Every shape, the group's children too, takes the group's id.
s.edit(|doc, sel| {
fn all(shapes: &mut [deckcraft_model::Shape], id: deckcraft_model::ShapeId) {
for sh in shapes {
sh.id = id;
if let deckcraft_model::ShapeKind::Group { children, .. } = &mut sh.kind {
all(children, id);
}
}
}
all(crate::shapes_mut(doc, sel).unwrap(), first);
Ok(())
})
.unwrap();
assert!(!s.doc().unwrap().doc.validate().is_empty(), "the deck repeats ids");
let bytes = cmd::file::save_bytes(&s.doc().unwrap().doc, "deckcraft").unwrap();
let mut t = Session::new();
t.execute("file.openBytes", &json!({"name": "dup.deckcraft", "data": cmd::base64_encode(&bytes)})).unwrap();
let st = t.doc().unwrap();
assert_eq!(st.doc.validate(), Vec::<String>::new());
let slide = st.doc.slides.last().unwrap();
let mut ids = vec![];
deckcraft_model::walk(&slide.shapes, &mut |sh, _| ids.push(sh.id));
assert_eq!(ids.len(), 6, "the group, its four children and the ellipse");
assert_eq!(ids[0], first, "the first shape keeps its id");
assert!(ids.iter().all(|id| id.0 <= st.doc.next_id), "new ids come from the deck's counter");
// Each shape can be selected by its own id now.
let last = *ids.last().unwrap();
t.execute("slide.go", &json!({"index": st.doc.slides.len() - 1})).unwrap();
t.execute("selection.select", &json!({"id": last.0})).unwrap();
assert_eq!(t.doc().unwrap().selected_shapes()[0].id, last);
}
#[test]
fn change_case_spans_formatting_runs() {
let setup = |text: &str, bold_to: usize| {
let mut s = session();
let r = s.execute("shape.insert", &json!({"preset": "rect", "rect": [80.0, 80.0, 420.0, 160.0], "text": text})).unwrap();
let id = r["id"].as_u64().unwrap() as u32;
s.execute("text.edit", &json!({"id": id})).unwrap();
s.execute("text.select", &json!({"anchor": [0, 0], "caret": [0, bold_to]})).unwrap();
s.execute("format.bold", &json!({"on": true})).unwrap();
(s, id)
};
let text_of = |s: &Session, id: u32| s.doc().unwrap().shape(deckcraft_model::ShapeId(id)).unwrap().text.clone().unwrap();
for (mode, input, want) in [("title", "hello world", "Hello World"), ("sentence", "hello world. bye", "Hello world. Bye")] {
// Text range.
let (mut s, id) = setup(input, 3);
let n = input.chars().count();
s.execute("text.select", &json!({"anchor": [0, 0], "caret": [0, n]})).unwrap();
s.execute("format.case", &json!({"mode": mode})).unwrap();
assert_eq!(text_of(&s, id).text(), want, "{mode} range");
// Whole shape.
let (mut s, id) = setup(input, 3);
s.execute("text.exit", &json!({})).unwrap();
s.execute("format.case", &json!({"mode": mode})).unwrap();
assert_eq!(text_of(&s, id).text(), want, "{mode} shape");
assert_eq!(text_of(&s, id).paragraphs[0].runs[0].props.bold, Some(true));
}
// A length-changing mapping keeps each piece in its own run.
let (mut s, id) = setup("straße", 4);
s.execute("text.select", &json!({"anchor": [0, 0], "caret": [0, 6]})).unwrap();
s.execute("format.case", &json!({"mode": "upper"})).unwrap();
let body = text_of(&s, id);
assert_eq!(body.text(), "STRASSE");
assert_eq!(body.paragraphs[0].runs[0].text, "STRA");
assert_eq!(body.paragraphs[0].runs[0].props.bold, Some(true));
}
#[test]
fn flipping_a_rotated_shape_mirrors_its_outline() {
let corners = |s: &Session, id: deckcraft_model::ShapeId| {
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
let a = x.affine();
[(0.0, 0.0), (x.w, 0.0), (x.w, x.h), (0.0, x.h)].map(|(px, py)| {
let p = a * deckcraft_geom::Point::new(px, py);
((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64)
})
};
let sorted = |mut c: [(i64, i64); 4]| {
c.sort_unstable();
c
};
for (cmd, horizontal) in [("arrange.flipHorizontal", true), ("arrange.flipVertical", false)] {
let mut s = session();
let r = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 200, 50]})).unwrap();
let id = deckcraft_model::ShapeId(r["id"].as_u64().unwrap() as u32);
s.execute("shape.rotate", &json!({"deg": 30})).unwrap();
let before = corners(&s, id);
// Mirror about the box's centre line (centre is 200, 125).
let mirrored = before.map(|(x, y)| if horizontal { (40000 - x, y) } else { (x, 25000 - y) });
s.execute(cmd, &json!({})).unwrap();
assert_eq!(sorted(corners(&s, id)), sorted(mirrored), "{cmd} of a 30° rotated rectangle is not its mirror image");
let rot = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap().rot;
assert!((rot - 330.0).abs() < 1e-9, "{cmd} negates the rotation, got {rot}");
s.execute(cmd, &json!({})).unwrap();
assert_eq!(sorted(corners(&s, id)), sorted(before), "{cmd} twice restores the outline");
}
}
#[test]
fn shape_geometry_commands_limit_size_and_position() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("shape.insert", &json!({"preset": "moon", "rect": [100, 100, 200, 100]})).unwrap();
let xfrm = |s: &Session| s.doc().unwrap().selected_shapes()[0].xfrm.unwrap();
let within = |s: &Session| {
let x = xfrm(s);
[x.w, x.h].iter().all(|v| v.is_finite() && (0.0..=15_840.0).contains(v)) && [x.x, x.y].iter().all(|v| v.is_finite() && v.abs() <= 100_000.0)
};
s.execute("shape.setBounds", &json!({"x": 1e100, "y": -1e100, "w": 100000, "h": 1e100})).unwrap();
let x = xfrm(&s);
assert!(within(&s), "setBounds stored {x:?}");
s.execute("shape.resize", &json!({"w": 10, "h": 10})).unwrap();
s.execute("shape.resize", &json!({"h": 1e100})).unwrap();
let x = xfrm(&s);
assert!(within(&s), "resize stored {x:?}");
s.execute("shape.resize", &json!({"h": 1e100, "lockAspect": true})).unwrap();
let x = xfrm(&s);
assert!(within(&s), "locked resize stored {x:?}");
s.execute("shape.move", &json!({"x": 1e100, "y": -1e100})).unwrap();
let x = xfrm(&s);
assert!(within(&s), "move stored {x:?}");
// A move that overflows to infinity lands on the limit, not back at 0.
s.execute("shape.move", &json!({"x": 1e308, "dx": 1e308})).unwrap();
assert_eq!(xfrm(&s).x, 100_000.0);
// A rotated shape resizes about its centre and still stays inside the limit.
s.execute("shape.setBounds", &json!({"x": 99_000, "y": 0, "w": 10, "h": 10})).unwrap();
s.execute("shape.rotate", &json!({"deg": 45})).unwrap();
s.execute("shape.resize", &json!({"w": 1e100})).unwrap();
let x = xfrm(&s);
assert!(within(&s), "rotated resize stored {x:?}");
}
/// Edit Points turns a preset into a freeform: one undo step, so Undo brings the preset back
/// (and leaves Edit Points), Redo the freeform; leaving Edit Points adds no step.
#[test]
fn edit_points_conversion_is_one_undo_step() {
use deckcraft_model::Geom;
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("shape.insert", &json!({"preset": "star5", "rect": [100, 100, 200, 100]})).unwrap();
let preset = |s: &Session| matches!(s.doc().unwrap().selected_shapes()[0].geom, Geom::Preset { .. });
s.execute("shape.editPoints", &json!({"on": true})).unwrap();
assert!(!preset(&s), "Edit Points made a freeform");
assert!(s.tool.editing_points(s.doc().unwrap()).is_some());
s.execute("shape.editPoints", &json!({"on": false})).unwrap();
// Leaving changed nothing, so the next undo is the conversion itself.
s.execute("edit.undo", &json!({})).unwrap();
assert!(preset(&s), "Undo brings the star back");
s.execute("edit.redo", &json!({})).unwrap();
assert!(!preset(&s), "Redo makes it a freeform again");
// Undo while still editing points ends Edit Points: the star has no points to edit.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("shape.editPoints", &json!({"on": true})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(preset(&s));
assert!(s.tool.editing_points(s.doc().unwrap()).is_none());
// A freeform needs no conversion: entering Edit Points again adds no undo step.
s.execute("edit.redo", &json!({})).unwrap();
s.execute("shape.editPoints", &json!({"on": false})).unwrap();
s.execute("shape.editPoints", &json!({"on": true})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(preset(&s), "the only step was the conversion");
}
/// #931: while the text of a placeholder is being edited, a shape in front of it still takes a
/// click (as in PowerPoint); a click on the text where nothing is in front still moves the caret.
#[test]
fn a_shape_in_front_of_edited_text_takes_the_click() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "titleAndContent"})).unwrap();
let square = s.execute("shape.insert", &json!({"preset": "rect", "rect": [380, 260, 200, 120]})).unwrap()["id"].as_u64().unwrap();
s.execute("edit.deselect", &json!({})).unwrap();
let ev = |kind, x: f64, y: f64| tools::PointerEvent { kind, x, y, mods: Default::default(), tol: 4.0, pressure: None };
let click = |s: &mut Session, x: f64, y: f64| {
s.pointer(ev(tools::PointerKind::Down, x, y)).unwrap();
s.pointer(ev(tools::PointerKind::Up, x, y)).unwrap();
};
// The content placeholder's edge: its (empty) text is now being edited.
click(&mut s, 66.0, 300.0);
let body = s.doc().unwrap().selection.text.as_ref().map(|t| t.shape).expect("editing the content placeholder");
assert_ne!(body.0 as u64, square);
// A click on the text away from the square keeps editing it.
click(&mut s, 200.0, 300.0);
assert_eq!(s.doc().unwrap().selection.text.as_ref().map(|t| t.shape), Some(body));
// A click on the square, in front of the text, selects the square.
click(&mut s, 480.0, 320.0);
let st = s.doc().unwrap();
assert_eq!(st.selection.shapes.iter().map(|id| id.0 as u64).collect::<Vec<_>>(), vec![square]);
assert!(st.selection.text.as_ref().is_none_or(|t| t.shape.0 as u64 == square), "{:?}", st.selection.text);
// A shape over the edited box's edge takes the click there too: the edge would otherwise drag
// the box.
let edge = {
let st = s.doc().unwrap();
let x = cmd::xfrm_of(&st.doc, &st.selection, st.shape(body).unwrap());
(x.x, x.y + x.h / 2.0)
};
let corner =
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [edge.0 - 10.0, edge.1 - 10.0, 20, 20]})).unwrap()["id"].as_u64().unwrap();
s.execute("edit.deselect", &json!({})).unwrap();
s.execute("text.edit", &json!({"id": body.0})).unwrap();
// On the box's left edge, inside the band that drags it, clear of its middle handle (handles
// stay on top, as in PowerPoint).
click(&mut s, edge.0 + 1.0, edge.1 - 9.0);
let st = s.doc().unwrap();
assert_eq!(st.selection.shapes.iter().map(|id| id.0 as u64).collect::<Vec<_>>(), vec![corner], "{:?}", st.selection);
// Text inside a group: a member in front of it takes the click instead of the caret.
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
let tb =
s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 300, 150], "text": "Grouped text"})).unwrap()["id"].as_u64().unwrap();
let cover = s.execute("shape.insert", &json!({"preset": "rect", "rect": [200, 150, 60, 40]})).unwrap()["id"].as_u64().unwrap();
s.execute("arrange.group", &json!({"ids": [tb, cover]})).unwrap();
s.execute("text.edit", &json!({"id": tb})).unwrap();
assert_eq!(s.doc().unwrap().selection.text.as_ref().map(|t| t.shape.0 as u64), Some(tb));
click(&mut s, 230.0, 170.0);
let st = s.doc().unwrap();
assert!(st.selection.text.as_ref().is_none_or(|t| t.shape.0 as u64 != tb), "the click on the member in front left the text: {:?}", st.selection);
}
+33 -2
View File
@@ -280,7 +280,12 @@ impl ToolState {
/// The shape in Edit Points, while it is still the one selected shape.
pub fn editing_points(&self, st: &crate::DocState) -> Option<ShapeId> {
self.edit_points.filter(|id| st.selection.shapes.as_slice() == [*id] && st.selection.text.is_none() && st.shape(*id).is_some())
// Only a freeform has points: after Undo takes the conversion back, Edit Points is over.
self.edit_points.filter(|id| {
st.selection.shapes.as_slice() == [*id]
&& st.selection.text.is_none()
&& st.shape(*id).is_some_and(|sh| matches!(sh.geom, deckcraft_model::Geom::Custom { .. }))
})
}
/// A freeform path is being drawn (Enter/Escape/double-click finish it).
@@ -409,10 +414,12 @@ impl Session {
}
}
}
// The frame of the text being edited: grabbing it moves the box.
// The frame of the text being edited: grabbing it moves the box, unless a shape in front
// of the text covers that spot (#931).
if let Some(e) = edited_box(st)
&& e.movable
&& edit_zone(&e.xfrm, p, tol) == EditZone::Frame
&& !shape_in_front(st, st.shapes(), e.id, p, tol, 0)
{
return Some(Hit::Frame { id: e.id });
}
@@ -1228,7 +1235,10 @@ impl Session {
None => edited_box(st).is_some_and(|e| edit_zone(&e.xfrm, p, tol) != EditZone::Outside),
Some(_) => xfrm_of(&st.doc, &st.selection, sh).bounds().inflate(tol, tol).contains(p),
};
// A shape in front of the edited text takes the click, as in PowerPoint (#931).
let in_front = shape_in_front(st, st.shapes(), t.shape, p, tol, 0);
if !inside
|| in_front
|| matches!(
self.hit_test(p, tol),
Some(
@@ -1650,6 +1660,27 @@ struct EditedBox {
movable: bool,
}
/// Whether a visible shape drawn in front of `target` is under `p`: the shapes above it in its
/// list, topmost first, and inside a group that holds it, the members above it.
fn shape_in_front(st: &crate::DocState, shapes: &[Shape], target: ShapeId, p: Point, tol: f64, depth: usize) -> bool {
if depth > 64 {
return false;
}
for s in shapes.iter().rev() {
if s.id == target {
return false;
}
if deckcraft_model::find_shape(std::slice::from_ref(s), target).is_some() {
// The group holding the text: look among its members.
return shape_in_front(st, s.children(), target, p, tol, depth + 1);
}
if !s.hidden && hit_shape(st, s, p, tol).is_some() {
return true;
}
}
false
}
fn edited_box(st: &crate::DocState) -> Option<EditedBox> {
let t = st.selection.text.as_ref()?;
if t.notes || t.cell.is_some() {
+28
View File
@@ -59,6 +59,34 @@ fn start(p: &mut Presentation) {
p.slides.clear();
}
#[test]
fn saved_trigger_reveals_then_hides_on_separate_clicks() {
let mut p = defaults::new_presentation(None);
start(&mut p);
let button = shape(&mut p, "Button", "Toggle", 20.0, 20.0, 100.0, 40.0);
let target = shape(&mut p, "Target", "Answer", 200.0, 100.0, 200.0, 80.0);
let animations = vec![
Animation {
shape: target.id,
trigger: Some(button.id),
effect: "appear".into(),
start: AnimStart::OnClick,
duration_ms: 0,
..Default::default()
},
disappear_on_click(button.id, target.id),
];
add_slide(&mut p, vec![button, target], animations, false);
let mut show = Show::open(&p);
assert!(!show.shown("Target"));
for _ in 0..2 {
assert_eq!(show.click("Button"), Click::Animated);
assert!(show.shown("Target"), "first click reveals the answer until the next click");
assert_eq!(show.click("Button"), Click::Animated);
assert!(!show.shown("Target"), "second click hides the answer");
}
}
/// The slide show window's click handling, on a deck read from a PPTX file.
struct Show {
pres: Presentation,
+150 -1
View File
@@ -197,6 +197,7 @@ pub fn repair(p: &mut Presentation) {
}
}
}
reid_duplicate_shapes(p);
p.slide_size = sane_slide_size(p.slide_size);
// The notes page only lays out notes, but its size divides too.
if !(p.notes_size.width.is_finite() && p.notes_size.width > 0.0 && p.notes_size.height.is_finite() && p.notes_size.height > 0.0) {
@@ -205,6 +206,57 @@ pub fn repair(p: &mut Presentation) {
sane_numbers(p);
}
/// Give a shape that repeats an id already used on its slide, layout or master (groups included)
/// a fresh one, so edits, selection and the Selection Pane find one shape per id. The first keeps
/// its id, and with it what animations and connectors point at. An exhausted id space leaves the
/// rest as they are (#407).
fn reid_duplicate_shapes(p: &mut Presentation) {
fn has_duplicates(shapes: &[deckcraft_model::Shape]) -> bool {
let mut seen = std::collections::HashSet::new();
let mut dup = false;
deckcraft_model::walk(shapes, &mut |sh, _| dup |= !seen.insert(sh.id));
dup
}
fn reid(shapes: &mut [deckcraft_model::Shape], seen: &mut std::collections::HashSet<deckcraft_model::ShapeId>, next: &mut u32, depth: usize) {
if depth > 64 {
return;
}
for sh in shapes {
if !seen.insert(sh.id)
&& let Some(id) = (*next).max(1).checked_add(1)
{
*next = id;
sh.id = deckcraft_model::ShapeId(id);
seen.insert(sh.id);
}
if let deckcraft_model::ShapeKind::Group { children, .. } = &mut sh.kind {
reid(children, seen, next, depth + 1);
}
}
}
let mut next = p.next_id;
let mut fix = |shapes: &mut Vec<deckcraft_model::Shape>| {
if has_duplicates(shapes) {
reid(shapes, &mut std::collections::HashSet::new(), &mut next, 0);
}
};
for s in &mut p.slides {
if has_duplicates(&s.shapes) {
fix(&mut Arc::make_mut(s).shapes);
}
}
for m in p.masters.iter_mut().chain(p.notes_master.iter_mut()).chain(p.handout_master.iter_mut()) {
if has_duplicates(&m.shapes) || m.layouts.iter().any(|l| has_duplicates(&l.shapes)) {
let m = Arc::make_mut(m);
fix(&mut m.shapes);
for l in &mut m.layouts {
fix(&mut l.shapes);
}
}
}
p.next_id = next;
}
/// Smallest and largest slide side, in points: PowerPoint's 1–56 in, as Design › Slide Size allows.
pub const SLIDE_SIDE: std::ops::RangeInclusive<f64> = 72.0..=4032.0;
@@ -350,6 +402,66 @@ fn sane_xfrm(x: &mut deckcraft_model::Xfrm) {
fn sane_run(p: &mut deckcraft_model::text::RunProps) {
p.size = p.size.filter(|v| v.is_finite() && *v > 0.0).map(|v| v.clamp(1.0, 4000.0));
for s in p.shadow.iter_mut().chain(p.inner_shadow.iter_mut()) {
sane_shadow(s);
}
if let Some(g) = p.glow.as_mut() {
g.radius = effect_size(g.radius, MAX_GLOW);
}
if let Some(r) = p.reflection.as_mut() {
sane_reflection(r);
}
p.soft_edge = p.soft_edge.map(|v| effect_size(v, MAX_SOFT_EDGE));
}
/// The largest effect sizes, in points: what Format Shape and `shape.effects` allow. A file can
/// say anything, and the renderer's memory grows with these (a glow of 10^18 pt asked for 34 GB).
const MAX_GLOW: f64 = 150.0;
const MAX_SOFT_EDGE: f64 = 100.0;
const MAX_SHADOW: f64 = 200.0;
const MAX_REFLECTION: f64 = 100.0;
/// `v` within 0..=`max`; not a number is 0.
fn effect_size(v: f64, max: f64) -> f64 {
if v.is_finite() { v.clamp(0.0, max) } else { 0.0 }
}
fn sane_shadow(s: &mut deckcraft_model::style::Shadow) {
s.blur = effect_size(s.blur, MAX_SHADOW);
s.dist = effect_size(s.dist, MAX_SHADOW);
s.dir = if s.dir.is_finite() { s.dir.rem_euclid(360.0) } else { 0.0 };
// Perspective scale (1 = 100%) and skew (degrees).
for v in [&mut s.sx, &mut s.sy] {
*v = if v.is_finite() { v.clamp(-10.0, 10.0) } else { 1.0 };
}
for v in [&mut s.kx, &mut s.ky] {
*v = if v.is_finite() { v.clamp(-89.0, 89.0) } else { 0.0 };
}
}
fn sane_reflection(r: &mut deckcraft_model::style::Reflection) {
r.blur = effect_size(r.blur, MAX_REFLECTION);
r.dist = effect_size(r.dist, MAX_REFLECTION);
}
/// Run properties a list style hands down to the text that inherits it.
fn sane_list_style(ls: &mut deckcraft_model::text::ListStyle) {
for level in ls.levels.iter_mut().flatten() {
sane_run(&mut level.run);
}
}
fn sane_effects(e: &mut deckcraft_model::Effects) {
for s in e.outer_shadow.iter_mut().chain(e.inner_shadow.iter_mut()) {
sane_shadow(s);
}
if let Some(g) = e.glow.as_mut() {
g.radius = effect_size(g.radius, MAX_GLOW);
}
e.soft_edge = e.soft_edge.map(|v| effect_size(v, MAX_SOFT_EDGE));
if let Some(r) = e.reflection.as_mut() {
sane_reflection(r);
}
}
fn sane_shapes(shapes: &mut [deckcraft_model::Shape], depth: usize) {
@@ -363,7 +475,11 @@ fn sane_shapes(shapes: &mut [deckcraft_model::Shape], depth: usize) {
if let Some(l) = sh.line.as_mut() {
l.width = l.width.filter(|v| v.is_finite() && *v >= 0.0).map(|v| v.min(1584.0));
}
if let Some(e) = sh.effects.as_mut() {
sane_effects(e);
}
if let Some(t) = sh.text.as_mut() {
sane_list_style(&mut t.list_style);
for para in &mut t.paragraphs {
sane_run(&mut para.end_props);
for r in &mut para.runs {
@@ -381,6 +497,17 @@ fn sane_shapes(shapes: &mut [deckcraft_model::Shape], depth: usize) {
sane_xfrm(child);
sane_shapes(children, depth + 1);
}
deckcraft_model::ShapeKind::Table(t) => {
for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
sane_list_style(&mut cell.text.list_style);
}
for para in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()).flat_map(|c| c.text.paragraphs.iter_mut()) {
sane_run(&mut para.end_props);
for r in &mut para.runs {
sane_run(&mut r.props);
}
}
}
_ => {}
}
}
@@ -395,12 +522,21 @@ pub fn sane_numbers(p: &mut Presentation) {
*slide = Arc::new(fixed);
}
}
// What text and shapes inherit: the deck's default text style, each master's title, body and
// other styles, and the theme's effect styles that shape styles point at.
sane_list_style(&mut p.default_text_style);
for m in p.masters.iter_mut().chain(p.notes_master.iter_mut()).chain(p.handout_master.iter_mut()) {
let mut fixed = (**m).clone();
sane_shapes(&mut fixed.shapes, 0);
for l in &mut fixed.layouts {
sane_shapes(&mut l.shapes, 0);
}
for ls in [&mut fixed.title_style, &mut fixed.body_style, &mut fixed.other_style] {
sane_list_style(ls);
}
for e in &mut fixed.theme.format.effects {
sane_effects(e);
}
if fixed != **m {
*m = Arc::new(fixed);
}
@@ -492,7 +628,8 @@ pub fn markdown_to_slides(p: &mut Presentation, text: &str) -> usize {
pub fn slides_to_outline(p: &Presentation) -> String {
let mut out = String::new();
for s in &p.slides {
out.push_str(&s.title());
// One line per title: a newline would start another slide on re-import.
out.push_str(&s.title().replace('\n', " "));
out.push('\n');
for sh in &s.shapes {
if sh.ph_type().is_some_and(|k| k.is_title()) {
@@ -832,6 +969,18 @@ mod tests {
assert!(o.contains("-5 °C tonight\n\t--verbose flag\n\t*args and **kwargs\nBullets\n\tPoint\n\tOther"), "{o}");
}
#[test]
fn outline_export_keeps_multi_paragraph_title_on_one_line() {
let mut p = defaults::blank_presentation(defaults::WIDE, Default::default(), false);
assert_eq!(outline_to_slides(&mut p, "Intro\n\tPoint one\nSecond\n\tMore"), 2);
let title = Arc::make_mut(&mut p.slides[0]).shapes.iter_mut().find(|s| s.ph_type().is_some_and(|k| k.is_title())).expect("title placeholder");
title.text = Some(TextBody::from_text("Line one\nLine two"));
let o = slides_to_outline(&p);
assert_eq!(o, "Line one Line two\n\tPoint one\nSecond\n\tMore\n");
let mut q = defaults::blank_presentation(defaults::WIDE, Default::default(), false);
assert_eq!(outline_to_slides(&mut q, &o), 2);
}
#[test]
fn markdown_headings_and_list_items() {
assert_eq!(md_heading("# Intro"), Some("Intro"));
+31 -36
View File
@@ -459,44 +459,39 @@ pub fn next_case(s: &str) -> &'static str {
/// Change case: `upper`, `lower`, `sentence`, `title`, `toggle`.
pub fn change_case(s: &str, mode: &str) -> String {
match mode {
"upper" => s.to_uppercase(),
"lower" => s.to_lowercase(),
"toggle" => s.chars().map(|c| if c.is_uppercase() { c.to_lowercase().collect::<String>() } else { c.to_uppercase().collect() }).collect(),
"title" => {
let mut out = String::new();
let mut start = true;
for c in s.chars() {
if start && c.is_alphabetic() {
out.extend(c.to_uppercase());
start = false;
} else {
out.extend(c.to_lowercase());
}
if c.is_whitespace() {
start = true;
change_case_parts(&[s], mode).concat()
}
/// Change the case of consecutive pieces of text (the runs of a paragraph) as one string, so
/// `title` and `sentence` carry their word/sentence state across piece boundaries. Each output
/// piece is the changed form of the matching input piece, even where a character changes length.
pub fn change_case_parts(parts: &[&str], mode: &str) -> Vec<String> {
let mut start = true;
parts
.iter()
.map(|s| match mode {
"upper" => s.to_uppercase(),
"lower" => s.to_lowercase(),
"toggle" => s.chars().map(|c| if c.is_uppercase() { c.to_lowercase().collect::<String>() } else { c.to_uppercase().collect() }).collect(),
_ => {
// `title` restarts after whitespace, sentence case after sentence punctuation.
let title = mode == "title";
let mut out = String::new();
for c in s.chars() {
if start && c.is_alphabetic() {
out.extend(c.to_uppercase());
start = false;
} else {
out.extend(c.to_lowercase());
}
if (title && c.is_whitespace()) || (!title && matches!(c, '.' | '!' | '?')) {
start = true;
}
}
out
}
out
}
_ => {
// sentence
let mut out = String::new();
let mut start = true;
for c in s.chars() {
if start && c.is_alphabetic() {
out.extend(c.to_uppercase());
start = false;
} else {
out.extend(c.to_lowercase());
}
if matches!(c, '.' | '!' | '?') {
start = true;
}
}
out
}
}
})
.collect()
}
#[cfg(test)]
+43 -17
View File
@@ -398,6 +398,31 @@ fn grey(v: u8, opacity: f32) -> Fill {
}
}
/// Premultiplied RGBA (the renderer's pixels) to the straight RGBA the writer stores.
fn straight(rgba: &mut [u8]) {
for px in rgba.as_chunks_mut::<4>().0 {
let a = px[3] as u32;
if a != 0 && a != 255 {
for c in &mut px[..3] {
*c = (((*c as u32 * 255 + a / 2) / a).min(255)) as u8;
}
}
}
}
/// A backdrop raster as one PDF image, composited onto white (slides are normally opaque). Equal
/// backdrops become equal images, which the writer stores once.
fn backdrop(mut img: deckcraft_render::Image) -> Image {
for px in img.pixels.as_chunks_mut::<4>().0 {
let a = px[3] as u32;
for c in &mut px[..3] {
*c = (*c as u32 + (255 - a)).min(255) as u8;
}
px[3] = 255;
}
Image::from_rgba8(img.pixels, img.width, img.height)
}
impl Exporter<'_> {
fn font(&mut self, face: &deckcraft_fonts::FontFace) -> Result<Font> {
if let Some(font) = self.fonts.get(&face.id()) {
@@ -415,25 +440,26 @@ impl Exporter<'_> {
let k = b.width() / sw;
// Raster at the requested dpi relative to the box size on paper.
let scale = (b.width() / 72.0 * self.opts.dpi.clamp(36.0, 600.0)) / sw;
let img = deckcraft_render::render_slide(pres, i, &RenderOpts { scale, threads: 4, ..Default::default() });
if img.width > 0 && img.height > 0 {
let (w, h) = (img.width, img.height);
let ropts = RenderOpts { scale, threads: 4, ..Default::default() };
// Two rasters per slide: the backdrop (background, master and layout graphics) is the same
// on every slide that shares its layout, so the writer stores it once, and the slide's own
// shapes draw over it (#845).
let back = deckcraft_render::render_slide_part(pres, i, deckcraft_render::SlidePart::Backdrop, &ropts);
let front = deckcraft_render::render_slide_part(pres, i, deckcraft_render::SlidePart::Content, &ropts);
let (w, h) = (back.width, back.height);
if w > 0
&& h > 0
&& let Some(size) = Size::from_wh(b.width() as f32, b.height() as f32)
{
s.push_transform(&Transform::from_translate(b.x0 as f32, b.y0 as f32));
s.draw_image(backdrop(back), size);
// Taken, not copied: a print-resolution slide is ~16 MB.
let mut rgba = img.pixels;
for px in rgba.as_chunks_mut::<4>().0 {
// Composite onto white (slides are normally opaque).
let a = px[3] as u32;
for c in &mut px[..3] {
*c = (*c as u32 + (255 - a)).min(255) as u8;
}
px[3] = 255;
}
let image = Image::from_rgba8(rgba, w, h);
if let Some(size) = Size::from_wh(b.width() as f32, b.height() as f32) {
s.push_transform(&Transform::from_translate(b.x0 as f32, b.y0 as f32));
s.draw_image(image, size);
s.pop();
let mut rgba = front.pixels;
if rgba.as_chunks::<4>().0.iter().any(|px| px[3] != 0) {
straight(&mut rgba);
s.draw_image(Image::from_rgba8(rgba, w, h), size);
}
s.pop();
}
if self.opts.frame_slides && self.opts.layout != PageLayout::Slides {
let p = kurbo::Shape::to_path(&b, 0.1);
+89
View File
@@ -432,6 +432,95 @@ fn master_text_wraps_and_keeps_mixed_formatting() {
assert!(export(&p, &PdfOptions { layout: PageLayout::Notes, ..Default::default() }).unwrap().starts_with(b"%PDF"));
}
/// Slides that share their layout store their backdrop raster once in the exported PDF, over which
/// each slide's own shapes draw as their own raster (#845).
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn slides_share_one_backdrop_raster_and_keep_their_pixels() {
use deckcraft_model::{Shape, ShapeId, Xfrm};
use hayro_syntax::object::{Dict, Number, Stream};
/// The image XObjects the export stores, one entry per distinct object: the pages that draw
/// it, its filters, color channel, alpha channel (the SMask) and pixel size.
fn images(p: &Presentation) -> Vec<(Vec<usize>, Vec<hayro_syntax::Filter>, Vec<u8>, Option<Vec<u8>>, (u32, u32))> {
let bytes = export(p, &opts(PageLayout::Slides)).expect("export");
let pdf = hayro_syntax::Pdf::new(bytes).expect("pdf");
let mut out: Vec<(String, Vec<usize>, Vec<hayro_syntax::Filter>, Vec<u8>, Option<Vec<u8>>, (u32, u32))> = Vec::new();
for (n, page) in pdf.pages().iter().enumerate() {
let resources = page.raw().get::<Dict>(b"Resources").expect("resources");
let xobjects = resources.get::<Dict>(b"XObject").expect("xobjects");
for key in xobjects.keys() {
let stream = xobjects.get::<Stream>(key).expect("stream");
let id = format!("{:?}", stream.obj_id());
match out.iter_mut().find(|(seen, ..)| *seen == id) {
Some(entry) => entry.1.push(n),
None => {
let dict = stream.dict();
let alpha = dict.get::<Stream>(b"SMask").map(|mask| mask.decoded().expect("decoded").into_owned());
let size = (
dict.get::<Number>(b"Width").expect("width").as_f64() as u32,
dict.get::<Number>(b"Height").expect("height").as_f64() as u32,
);
out.push((id, vec![n], stream.filters().into_vec(), stream.decoded().expect("decoded").into_owned(), alpha, size));
}
}
}
}
out.into_iter().map(|(_, pages, filters, rgb, alpha, size)| (pages, filters, rgb, alpha, size)).collect()
}
// The raster scale the exporter uses for one slide per page.
let scale = |p: &Presentation| (p.slide_size.width / 72.0 * opts(PageLayout::Slides).dpi) / p.slide_size.width;
// Three slides without shapes: every page is pure backdrop and shares one raster, which is
// exactly what the renderer draws.
let mut p = deck(3);
for slide in &mut p.slides {
Arc::make_mut(slide).shapes.clear();
}
let stored = images(&p);
assert_eq!(stored.len(), 1, "all three pages must share one backdrop raster");
let (pages, filters, rgb, alpha, size) = stored.into_iter().next().expect("one image");
assert_eq!(pages, [0, 1, 2]);
assert_eq!(filters, [hayro_syntax::Filter::FlateDecode], "backdrop artwork stays lossless");
assert!(alpha.is_none(), "the backdrop is opaque and needs no alpha mask");
let expect = deckcraft_render::render_slide(&p, 0, &RenderOpts { scale: scale(&p), threads: 4, ..Default::default() });
assert_eq!(size, (expect.width, expect.height));
let want: Vec<u8> = expect.pixels.as_chunks::<4>().0.iter().flat_map(|px| px[..3].iter().copied()).collect();
assert_eq!(rgb, want, "the shared raster is exactly what the renderer draws");
// Slides with different text still share the backdrop: one raster on every page plus one per
// slide's own shapes.
let stored = images(&deck(3));
assert_eq!(stored.len(), 4, "one shared backdrop plus three content rasters");
assert_eq!(stored.iter().filter(|(pages, ..)| pages.len() == 3).count(), 1, "the backdrop is the only raster every page draws");
// A slide's own shapes draw over the shared backdrop as a second raster, stored as straight
// RGBA (color channel plus alpha mask), never the renderer's premultiplied pixels.
let mut p = deck(1);
Arc::make_mut(&mut p.slides[0]).shapes.push(Shape {
id: ShapeId(9002),
xfrm: Some(Xfrm::new(20.0, 20.0, 400.0, 300.0)),
fill: Some(deckcraft_model::Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_model::Rgba::rgb(200, 30, 30)))),
..Default::default()
});
let stored = images(&p);
assert_eq!(stored.len(), 2, "shared backdrop plus the slide's content");
let (_, filters, rgb, alpha, _) = stored.into_iter().find(|(_, _, _, alpha, _)| alpha.is_some()).expect("content raster");
assert_eq!(filters, [hayro_syntax::Filter::FlateDecode]);
let expect = deckcraft_render::render_slide_part(
&p,
0,
deckcraft_render::SlidePart::Content,
&RenderOpts { scale: scale(&p), threads: 4, ..Default::default() },
);
let straight = expect.to_straight();
let want_rgb: Vec<u8> = straight.as_chunks::<4>().0.iter().flat_map(|px| px[..3].iter().copied()).collect();
let want_alpha: Vec<u8> = straight.as_chunks::<4>().0.iter().map(|px| px[3]).collect();
assert_eq!(rgb, want_rgb, "content colors are straight, not premultiplied");
assert_eq!(alpha, Some(want_alpha), "content alpha keeps the shape's coverage");
}
#[test]
fn glyph_ranges_follow_shaping_clusters() {
// "fl" ligature: its glyph maps to both characters, the rest stay one to one (#164).
+6
View File
@@ -63,6 +63,12 @@ pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
read::import(bytes)
}
/// [`import`], plus the part names of slides the file lists but that couldn't be read and were
/// left out.
pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>), PptxError> {
read::import_checked(bytes)
}
/// Read the theme of a `.thmx` file, or of a `.pptx` / `.potx`'s first master, with its media.
pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec<deckcraft_model::MediaItem>), PptxError> {
read::import_theme(bytes)
+9 -1
View File
@@ -387,6 +387,13 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec<
}
pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
import_checked(bytes).map(|(p, _)| p)
}
/// [`import`], plus the parts of the slide list the file names but that couldn't be read (a
/// missing or truncated slide): those slides are left out, so a caller can say so (#203).
pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>), PptxError> {
let mut lost_slides: Vec<String> = vec![];
let pkg = Package::open(bytes)?;
let root_rels = pkg.rels("");
let pres_path = root_rels.first_of("officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "ppt/presentation.xml".into());
@@ -447,6 +454,7 @@ pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
for (file_id, path) in &slide_entries {
if !docs.contains_key(&opc::norm(path)) {
log::warn!("pptx: slide {path} is missing or unreadable; skipped");
lost_slides.push(path.clone());
continue;
}
let id = SlideId(imp.alloc());
@@ -677,7 +685,7 @@ pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
p.media = std::mem::take(&mut imp.media);
p.next_id = imp.next;
p.fix_next_id();
Ok(p)
Ok((p, lost_slides))
}
/// Embedded font faces in one file. Past this, further typefaces are dropped.
+4 -15
View File
@@ -655,21 +655,10 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm
w.close("p:seq");
}
for (trig, effs) in triggered {
// Everything a trigger starts plays from its click.
let effs: Vec<Eff> = effs
.into_iter()
.enumerate()
.map(|(i, e)| Eff {
start: if i == 0 {
AnimStart::OnClick
} else if e.start == AnimStart::OnClick {
AnimStart::AfterPrevious
} else {
e.start
},
..e
})
.collect();
// The first step starts with the button's click. Later On Click effects must remain
// separate steps; With/After Previous effects still belong to their preceding step.
let effs: Vec<Eff> =
effs.into_iter().enumerate().map(|(i, e)| Eff { start: if i == 0 { AnimStart::OnClick } else { e.start }, ..e }).collect();
let clicks = group(effs);
let trig_cond = |w: &mut W| {
w.open("p:cond", A::new().a("evt", "onClick").a("delay", 0));
+23
View File
@@ -264,3 +264,26 @@ fn export_of_odd_models_is_valid() {
let q = deckcraft_pptx::import(&deckcraft_pptx::export(&empty).expect("export")).expect("import");
assert!(!q.masters.is_empty());
}
/// A slide the file lists but that can't be read is left out, and `import_checked` names it
/// where `import` would have said nothing (#203).
#[test]
fn unreadable_slide_is_reported() {
let mut p = defaults::new_presentation(None);
let mut second = p.slides.first().expect("a slide").as_ref().clone();
second.id = deckcraft_model::SlideId(second.id.0 + 1000);
p.slides.push(std::sync::Arc::new(second));
let bytes = deckcraft_pptx::export(&p).expect("export");
let (q, lost) = deckcraft_pptx::import_checked(&bytes).expect("import");
assert_eq!((q.slides.len(), lost.len()), (2, 0), "{lost:?}");
let mut es = entries(&bytes);
let slide2 = es.iter_mut().find(|(n, _)| n == "ppt/slides/slide2.xml").expect("slide2");
slide2.1 = b"<p:sld".to_vec();
let broken = rezip(&es);
let (q, lost) = deckcraft_pptx::import_checked(&broken).expect("import");
assert_eq!(q.slides.len(), 1);
assert_eq!(lost, vec!["ppt/slides/slide2.xml".to_string()]);
assert_eq!(deckcraft_pptx::import(&broken).expect("import").slides.len(), 1);
}
+95
View File
@@ -0,0 +1,95 @@
//! Synthetic interactive sequences must keep one step per click across a save.
use std::io::{Cursor, Read};
use std::sync::Arc;
use deckcraft_geom::Xfrm;
use deckcraft_model::anim::{AnimStart, Animation, TextBuild};
use deckcraft_model::text::TextBody;
use deckcraft_model::{Presentation, Shape, ShapeId, defaults};
fn deck() -> Presentation {
let mut p = defaults::new_presentation(None);
let shapes: Vec<_> = ["Button", "Other button", "Content"]
.into_iter()
.map(|name| Shape {
id: ShapeId(p.alloc_id().expect("id")),
name: name.into(),
xfrm: Some(Xfrm::new(40.0, 40.0, 200.0, 100.0)),
text: Some(TextBody::from_text("First\nSecond\nThird")),
..Default::default()
})
.collect();
Arc::make_mut(&mut p.slides[0]).shapes = shapes;
p
}
fn round(p: &Presentation) -> Presentation {
deckcraft_pptx::import(&deckcraft_pptx::export(p).expect("export")).expect("import")
}
fn slide_xml(p: &Presentation) -> String {
let bytes = deckcraft_pptx::export(p).expect("export");
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip");
let mut xml = String::new();
z.by_name("ppt/slides/slide1.xml").expect("slide").read_to_string(&mut xml).expect("xml");
xml
}
#[test]
fn triggered_click_steps_survive_import_edit_save_reopen() {
use AnimStart::{AfterPrevious, OnClick, WithPrevious};
let mut p = deck();
let ids: Vec<_> = p.slides[0].shapes.iter().map(|s| s.id).collect();
let starts = [OnClick, WithPrevious, AfterPrevious, OnClick, WithPrevious, OnClick];
for (i, start) in starts.into_iter().enumerate() {
Arc::make_mut(&mut p.slides[0]).animations.push(Animation {
shape: ids[2],
trigger: Some(ids[0]),
start,
effect: "appear".into(),
delay_ms: i as u32 * 100,
..Default::default()
});
}
// An independent button and the main sequence must not borrow this button's steps.
for trigger in [Some(ids[1]), None] {
for start in [OnClick, AfterPrevious, OnClick] {
Arc::make_mut(&mut p.slides[0]).animations.push(Animation { shape: ids[2], trigger, start, ..Default::default() });
}
}
let mut q = round(&p);
for pass in 0..2 {
for trigger in [Some(ids[0]), Some(ids[1]), None] {
let state = |deck: &Presentation| {
deck.slides[0].animations.iter().filter(|a| a.trigger == trigger).map(|a| (a.start, a.delay_ms)).collect::<Vec<_>>()
};
assert_eq!(state(&q), state(&p), "trigger {trigger:?}, pass {pass}");
}
assert_eq!(q.slides[0].animations.len(), p.slides[0].animations.len());
Arc::make_mut(&mut q.slides[0]).shapes[2].name = "Edited content".into();
q = round(&q);
}
let xml = slide_xml(&p);
assert_eq!(xml.matches("nodeType=\"interactiveSeq\"").count(), 2);
assert_eq!(xml.matches("nodeType=\"clickEffect\"").count(), 7);
// The first step in each interactive sequence begins at zero; subsequent steps wait.
assert_eq!(xml.matches("delay=\"indefinite\"").count(), 5);
}
#[test]
fn triggered_paragraph_build_keeps_a_click_for_each_paragraph() {
let mut p = deck();
let ids: Vec<_> = p.slides[0].shapes.iter().map(|s| s.id).collect();
Arc::make_mut(&mut p.slides[0]).animations =
vec![Animation { shape: ids[2], trigger: Some(ids[0]), text_build: TextBuild::ByParagraph, start: AnimStart::OnClick, ..Default::default() }];
for q in [p.clone(), round(&p)] {
let xml = slide_xml(&q);
assert_eq!(xml.matches("nodeType=\"clickEffect\"").count(), 3);
assert_eq!(xml.matches("delay=\"indefinite\"").count(), 2);
let back = round(&q);
assert_eq!(back.slides[0].animations.len(), 1);
assert_eq!(back.slides[0].animations[0].text_build, TextBuild::ByParagraph);
assert_eq!(back.slides[0].animations[0].trigger, Some(ids[0]));
}
}
+9
View File
@@ -238,6 +238,10 @@ pub struct RenderOpts<'a> {
pub date_text: Option<String>,
/// The local date and time date fields show (`None`: the system clock).
pub now: Option<DateTime>,
/// Leave the slide background out (neither the white underlay nor the background fill), so
/// only what is on the slide is drawn over transparency: PNG export with a transparent
/// background. Shapes filled with the background (`useBgFill`) still show it.
pub transparent_background: bool,
}
impl Default for RenderOpts<'_> {
@@ -257,6 +261,7 @@ impl Default for RenderOpts<'_> {
clear: None,
date_text: None,
now: None,
transparent_background: false,
}
}
}
@@ -794,6 +799,10 @@ impl Renderer {
fn background(&mut self, ctx: &mut RenderContext, f: &Frame, rctx: &Ctx, slide: Option<&Slide>, view: Affine) {
let (fill, ph) = resolve::background(rctx, slide);
if f.opts.transparent_background {
self.bg = Some((fill, ph, view));
return;
}
let r = Rect::new(0.0, 0.0, f.pres.slide_size.width, f.pres.slide_size.height);
ctx.set_transform(view);
let path = r.to_path(0.1);
+27
View File
@@ -992,6 +992,33 @@ fn a_background_is_laid_over_white() {
assert!(g[3] == 255 && (g[0] as i32 - 127).abs() <= 3, "half-transparent black over white is grey: {g:?}");
}
#[test]
fn a_transparent_background_leaves_the_slide_background_out() {
// #784: PNG export with a transparent background draws only what is on the slide. The
// background (a solid colour here) and its white underlay are left out; the shapes, and a
// shape filled with the background (`useBgFill`), still draw.
use deckcraft_model::style::Fill;
let blue = ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 0, 200));
let red = Shape {
id: ShapeId(784),
xfrm: Some(Xfrm::new(100.0, 100.0, 200.0, 100.0)),
fill: Some(Fill::solid(ColorRef::rgb(deckcraft_color::Rgba::rgb(220, 0, 0)))),
..Default::default()
};
let bg_filled = Shape { id: ShapeId(785), xfrm: Some(Xfrm::new(500.0, 100.0, 200.0, 100.0)), fill: Some(Fill::Background), ..Default::default() };
let mut p = deck_with(vec![red, bg_filled]);
std::sync::Arc::make_mut(&mut p.slides[0]).background = Some(deckcraft_model::Background::Fill { fill: Fill::solid(blue) });
let opaque = render_slide(&p, 0, &RenderOpts { scale: 1.0, ..Default::default() });
assert_eq!(opaque.pixel(20, 20), [0, 0, 200, 255], "without the option the background draws");
let img = render_slide(&p, 0, &RenderOpts { scale: 1.0, transparent_background: true, ..Default::default() });
assert_eq!(img.pixel(20, 20), [0, 0, 0, 0], "no background, no white underlay");
assert_eq!(img.pixel(200, 150), [220, 0, 0, 255], "the slide's shapes still draw");
assert_eq!(img.pixel(600, 150), [0, 0, 200, 255], "a background-filled shape still shows the background");
// The default theme background (a style reference) is left out too.
let img = render_slide(&deck_with(vec![]), 0, &RenderOpts { scale: 0.25, transparent_background: true, ..Default::default() });
assert!(img.pixels.as_chunks::<4>().0.iter().all(|px| px[3] == 0), "a blank slide is fully transparent");
}
#[test]
fn colour_glyphs_paint_their_layers() {
// A COLRv0 test font (crates/render/tests/fixtures): U+E000 is a red square with a blue
+1
View File
@@ -113,6 +113,7 @@ fn copy_opts<'a>(o: &RenderOpts<'a>) -> RenderOpts<'a> {
clear: o.clear,
date_text: o.date_text.clone(),
now: o.now,
transparent_background: o.transparent_background,
}
}
+103
View File
@@ -0,0 +1,103 @@
//! Arrange ▸ Align: Align to Slide and Align Selected Objects, as in PowerPoint. One object aligns
//! to the slide and several to each other, until the other choice is picked for that selection.
#![allow(clippy::unwrap_used, clippy::expect_used)]
use deckcraft_engine::Session;
use deckcraft_model::ShapeId;
use egui::accesskit::Toggled;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::{Services, SlideApp};
/// A blank slide with three rectangles at different places; `select` picks which are selected.
fn harness(select: &[usize]) -> (Harness<'static, SlideApp>, Vec<ShapeId>) {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
let ids: Vec<ShapeId> = [[100.0, 100.0], [300.0, 200.0], [500.0, 250.0]]
.iter()
.map(|[x, y]| {
let r = s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 80.0, 60.0]})).unwrap();
ShapeId(r["id"].as_u64().unwrap() as u32)
})
.collect();
let picked: Vec<u32> = select.iter().map(|&i| ids[i].0).collect();
s.execute("selection.select", &json!({"ids": picked})).unwrap();
let mut app = SlideApp::new(s, Services::default());
app.ui.tab = "Shape Format".into();
let mut h = Harness::builder().with_size(egui::vec2(1800.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
(h, ids)
}
fn pick(h: &mut Harness<'_, SlideApp>, item: &str) {
h.get_by_label("Align").click();
h.run_steps(2);
h.get_by_label(item).click();
h.run_steps(2);
}
fn marked(h: &mut Harness<'_, SlideApp>) -> (bool, bool) {
h.get_by_label("Align").click();
h.run_steps(2);
let m = (
h.get_by_label("Align to Slide").accesskit_node().toggled() == Some(Toggled::True),
h.get_by_label("Align Selected Objects").accesskit_node().toggled() == Some(Toggled::True),
);
// Esc would also clear the selection: a second click on Align closes the menu.
h.get_by_label("Align").click();
h.run_steps(2);
m
}
fn pos(h: &Harness<'_, SlideApp>, id: ShapeId) -> (f64, f64) {
let x = h.state().session.active().unwrap().shape(id).unwrap().xfrm.unwrap();
(x.x, x.y)
}
#[test]
fn align_to_slide_moves_align_left_to_the_slide_edge() {
let (mut h, ids) = harness(&[0, 1]);
pick(&mut h, "Align to Slide");
pick(&mut h, "Align Left");
assert_eq!(pos(&h, ids[0]).0, 0.0);
assert_eq!(pos(&h, ids[1]).0, 0.0);
}
#[test]
fn one_object_aligns_to_the_slide_and_two_to_each_other() {
let (mut h, ids) = harness(&[1]);
assert_eq!(marked(&mut h), (true, false));
pick(&mut h, "Align Left");
assert_eq!(pos(&h, ids[1]).0, 0.0);
let (mut h, ids) = harness(&[0, 1]);
assert_eq!(marked(&mut h), (false, true));
pick(&mut h, "Align Left");
assert_eq!(pos(&h, ids[1]).0, 100.0, "the left edge of the selection");
}
#[test]
fn the_choice_stays_until_the_selection_changes() {
let (mut h, ids) = harness(&[0, 1]);
pick(&mut h, "Align to Slide");
pick(&mut h, "Align Left");
pick(&mut h, "Align Top");
assert_eq!(pos(&h, ids[0]), (0.0, 0.0));
assert_eq!(pos(&h, ids[1]), (0.0, 0.0));
assert_eq!(marked(&mut h), (true, false));
// Another selection starts again from its own default.
h.state_mut().run("selection.select", json!({"ids": [ids[1].0, ids[2].0]})).unwrap();
h.run_steps(2);
assert_eq!(marked(&mut h), (false, true));
pick(&mut h, "Align Bottom");
assert_eq!(pos(&h, ids[1]).1, 250.0, "the bottom of the selection, not of the slide");
}
+11 -1
View File
@@ -175,6 +175,8 @@ pub struct Backstage {
pub file_type: &'static str,
pub handouts_per_page: u8,
pub pdf_hidden: bool,
/// Export › Change File Type › PNG: leave the slide background out (#784).
pub png_transparent: bool,
}
impl Backstage {
@@ -197,6 +199,7 @@ impl Backstage {
file_type: "pptx",
handouts_per_page: 3,
pdf_hidden: false,
png_transparent: false,
}
}
@@ -1310,8 +1313,15 @@ fn export(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
}
}
ui.add_space(12.0);
let png = bs.file_type == "png";
if png {
ui.checkbox(&mut bs.png_transparent, "Transparent background")
.on_hover_text("Leave the slide background out: only what is on the slide is drawn");
ui.add_space(8.0);
}
if square_button(ui, Icon::SaveAs, "Save As", true).clicked() {
app.export_as(bs.file_type, json!({}));
let extra = if png && bs.png_transparent { json!({"transparentBackground": true}) } else { json!({}) };
app.export_as(bs.file_type, extra);
}
}
}
+26
View File
@@ -302,6 +302,32 @@ fn save_as_and_export_run_the_file_commands() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Export › Change File Type › PNG offers "Transparent background" (#784): the PNG it saves
/// leaves the slide background out. Other types don't show the option.
#[test]
fn change_file_type_png_can_leave_the_background_transparent() {
let dir = temp_dir("png-clear");
let (services, _) = saving_into(&dir);
let mut h = harness(SlideApp::new(Session::with_new(), services));
h.state_mut().run("app.backstage", json!({"page": "export"})).unwrap();
h.run_steps(3);
click_on_page(&h, "Change File Type");
h.run_steps(3);
assert!(h.query_by_label("Transparent background").is_none(), "only PNG has the option");
click_on_page(&h, "PNG Picture (*.png)");
h.run_steps(2);
h.get_by_label("Transparent background").click();
h.run_steps(2);
assert!(h.state().backstage.as_ref().is_some_and(|b| b.png_transparent));
click_on_page(&h, "Save As");
h.run_steps(3);
let title = h.state().session.active().unwrap().title();
let png = std::fs::read(dir.join(format!("{title}.png"))).unwrap();
let img = deckcraft_render::decode_image(&png).unwrap();
assert_eq!(img.get_pixel(2, 2).0[3], 0, "the background is left out");
let _ = std::fs::remove_dir_all(&dir);
}
/// Close closes a saved presentation at once and asks about unsaved changes first.
#[test]
fn close_closes_and_asks_about_unsaved_changes() {
+55
View File
@@ -1608,6 +1608,18 @@ fn body(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
d.fields.insert("pdfHidden".into(), hidden.to_string());
}
}
let png = matches!(fmt.as_str(), "png" | "pngAll");
if png {
ui.add_space(4.0);
let mut clear = d.get("pngTransparent", "false") == "true";
if ui
.checkbox(&mut clear, "Transparent background")
.on_hover_text("Leave the slide background out: only what is on the slide is drawn")
.changed()
{
d.fields.insert("pngTransparent".into(), clear.to_string());
}
}
let gif_params = if fmt == "gif" { gif_options(app, ui, d) } else { Ok(Value::Null) };
if let Err(e) = &gif_params {
ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim));
@@ -1633,6 +1645,7 @@ fn body(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
let extra = match fmt.as_str() {
"pdf" => pdf_params,
"gif" => gif_params,
_ if png && d.get("pngTransparent", "false") == "true" => json!({"transparentBackground": true}),
_ => json!({}),
};
app.export_as(&fmt, extra);
@@ -2107,6 +2120,7 @@ fn body(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
ui.checkbox(&mut pr.ac_days, "Capitalize names of days");
ui.checkbox(&mut pr.ac_caps_lock, "Correct accidental use of cAPS LOCK key");
ui.checkbox(&mut pr.ac_fractions, "Replace fractions (1/2) with fraction characters (½)");
ui.checkbox(&mut pr.ac_ordinals, "Ordinals (1st) with superscript");
ui.checkbox(&mut pr.autocorrect, "Replace text as you type");
ui.add_space(4.0);
let mut from = d.get("from", "");
@@ -3444,6 +3458,47 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// The Export… dialog offers "Transparent background" for PNG only, and the picture it
/// writes then leaves the slide background out (#784).
#[test]
fn export_dialog_writes_a_png_with_a_transparent_background() {
use egui::vec2;
use egui_kittest::kittest::Queryable as _;
use serde_json::json;
use crate::SlideApp;
let dir = std::env::temp_dir().join(format!("deckcraft-ui-png-clear-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("slide.png");
let picked = path.to_string_lossy().to_string();
let services = crate::Services { pick_save: Some(Box::new(move |_: &str| Some(picked.clone()))), ..Default::default() };
let mut harness = egui_kittest::Harness::builder().with_size(vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(deckcraft_engine::Session::with_new(), services),
);
harness.run_steps(2);
harness.state_mut().run("app.exportDialog", json!({})).unwrap();
harness.run_steps(2);
assert!(harness.query_by_label("Transparent background").is_none(), "PDF has no transparent background");
harness.get_by_label("JPEG image (current slide)").click_accesskit();
harness.run_steps(2);
assert!(harness.query_by_label("Transparent background").is_none(), "nor has JPEG");
harness.get_by_label("PNG images (current slide)").click_accesskit();
harness.run_steps(2);
harness.get_by_label("Transparent background").click_accesskit();
harness.run_steps(2);
assert_eq!(harness.state().dialog.as_ref().and_then(|d| d.fields.get("pngTransparent")).map(String::as_str), Some("true"));
harness.key_press(egui::Key::Enter);
harness.run_steps(2);
assert!(harness.state().dialog.is_none(), "the dialog closes after exporting");
let img = deckcraft_render::decode_image(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(img.get_pixel(2, 2).0[3], 0, "the background is left out");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn no_link_opens_as_a_new_web_address() {
let seed = seed_from(CurrentLink::None, &[]);
+63 -6
View File
@@ -496,6 +496,8 @@ pub struct SlideApp {
pub(crate) thumb_drag: Option<(usize, usize)>,
/// Selection pane: folded groups, renaming, drag and drop.
pub selpane: selpane::State,
/// Arrange ▸ Align: Align to Slide (`true`) or Align Selected Objects, ticked for that selection.
pub(crate) align_to: Option<(Vec<deckcraft_model::ShapeId>, bool)>,
/// View › New Window: a second window on one presentation. `None` when it is closed.
pub doc_window: Option<doc_window::DocWindow>,
/// Slide Sorter: folded sections, inline rename, dragging a whole section.
@@ -572,6 +574,7 @@ impl SlideApp {
ui_fonts: uifonts::UiFonts::default(),
thumb_drag: None,
selpane: selpane::State::default(),
align_to: None,
doc_window: None,
sorter: sorter::State::default(),
slides_focused: false,
@@ -769,7 +772,8 @@ impl SlideApp {
// Every slide for "all slides", one download each, named like the desktop export (#64).
let name = self.session.active().map(|d| d.title()).unwrap_or_else(|| "Presentation".into());
let mut any = false;
for (file, bytes) in web_image_files(&doc, slide, all, &name, ext) {
let transparent = extra.get("transparentBackground").and_then(Value::as_bool).unwrap_or(false);
for (file, bytes) in web_image_files(&doc, slide, all, &name, ext, transparent) {
any = self.download(&file, Ok(bytes)) || any;
}
return any;
@@ -1184,6 +1188,26 @@ impl SlideApp {
Ok(())
}
/// Files the system hands over (the command line, a double-click through the file
/// association), opened in order. When the last one is a PowerPoint Show (`.ppsx`), its slide
/// show starts at once from where Play from Start begins, as PowerPoint does; anything else
/// opens for editing, and File › Open opens a `.ppsx` for editing too. Returns the files that
/// couldn't be opened, with the reason.
pub fn open_from_system(&mut self, paths: &[String]) -> Vec<(String, String)> {
let mut failed = Vec::new();
let mut last = None;
for p in paths {
match self.open_path(p) {
Ok(()) => last = Some(p),
Err(e) => failed.push((p.clone(), e)),
}
}
if last.is_some_and(|p| p.to_ascii_lowercase().ends_with(".ppsx")) {
self.start_show(self.show_start_index(), false);
}
failed
}
/// A presentation was opened from `path`: first in the recent list, shown in Normal view.
pub(crate) fn note_recent(&mut self, path: &str) {
self.status = None; // an older error (a missing file just before this one) must not linger
@@ -1987,8 +2011,16 @@ pub fn now_ms() -> f64 {
}
/// Images for the browser download: the current slide, or every slide (named `<name>1.png`,
/// `<name>2.png`... like the native export) when `all`.
fn web_image_files(doc: &deckcraft_model::Presentation, current: usize, all: bool, name: &str, ext: &str) -> Vec<(String, Vec<u8>)> {
/// `<name>2.png`... like the native export) when `all`. `transparent` leaves the slide
/// background out (PNG only, #784).
fn web_image_files(
doc: &deckcraft_model::Presentation,
current: usize,
all: bool,
name: &str,
ext: &str,
transparent: bool,
) -> Vec<(String, Vec<u8>)> {
let slides: Vec<usize> = if all { (0..doc.slides.len()).collect() } else { vec![current] };
let single = slides.len() == 1;
let scale = 2.0;
@@ -1997,7 +2029,8 @@ fn web_image_files(doc: &deckcraft_model::Presentation, current: usize, all: boo
.into_iter()
.enumerate()
.map(|(k, i)| {
let img = deckcraft_render::render_slide(doc, i, &deckcraft_render::RenderOpts { scale, ..Default::default() });
let opts = deckcraft_render::RenderOpts { scale, transparent_background: transparent && ext == "png", ..Default::default() };
let img = deckcraft_render::render_slide(doc, i, &opts);
let bytes = if ext == "png" { img.to_png_at(dpi) } else { img.to_jpeg_at(92, Some(dpi)) };
let file = if single { format!("{name}.{ext}") } else { format!("{name}{}.{ext}", k + 1) };
(file, bytes)
@@ -2098,14 +2131,38 @@ mod tests {
doc.slides.push(first);
}
assert_eq!(doc.slides.len(), 3);
let all = web_image_files(&doc, 1, true, "Deck", "png");
let all = web_image_files(&doc, 1, true, "Deck", "png", false);
let names: Vec<&str> = all.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["Deck1.png", "Deck2.png", "Deck3.png"]);
let one = web_image_files(&doc, 1, false, "Deck", "png");
let one = web_image_files(&doc, 1, false, "Deck", "png", false);
assert_eq!(one.len(), 1);
assert_eq!(one[0].0, "Deck.png");
}
/// The web PNG download honours "Transparent background" (#784): the slide background is
/// left out, so the corner is transparent; a JPEG download stays opaque.
#[test]
fn web_png_export_can_leave_the_background_transparent() {
use std::cell::RefCell;
use std::rc::Rc;
let got: Rc<RefCell<Vec<(String, Vec<u8>)>>> = Rc::default();
let log = got.clone();
let services = Services {
download: Some(Box::new(move |name: &str, b: &[u8]| log.borrow_mut().push((name.to_string(), b.to_vec())))),
..Default::default()
};
let mut app = SlideApp::new(Session::with_new(), services);
let corner_alpha = |bytes: &[u8]| deckcraft_render::decode_image(bytes).unwrap().get_pixel(2, 2).0[3];
assert!(app.export_as("png", json!({})));
assert!(app.export_as("png", json!({"transparentBackground": true})));
assert!(app.export_as("jpeg", json!({"transparentBackground": true})));
let got = got.borrow();
assert_eq!(got.len(), 3);
assert_eq!(corner_alpha(&got[0].1), 255, "opaque by default");
assert_eq!(corner_alpha(&got[1].1), 0, "transparent background");
assert_eq!(corner_alpha(&got[2].1), 255, "JPEG has no transparency");
}
fn title_text(app: &SlideApp) -> String {
let d = app.session.active().unwrap();
let sh = &d.doc.slides[0].shapes[0];
+89
View File
@@ -199,4 +199,93 @@ mod tests {
assert!(harness.state().opening.is_none());
assert_eq!(harness.state().session.documents().len(), 1);
}
/// A deck of `slides` slides saved as `file` (its extension picks the format).
fn saved_as(file: &str, slides: usize) -> String {
let mut s = Session::with_new();
for _ in 1..slides {
s.execute("slide.new", &serde_json::json!({})).unwrap();
}
let dir = std::env::temp_dir().join(format!("deckcraft-opening-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(file).to_string_lossy().to_string();
s.execute("file.saveAs", &serde_json::json!({"path": path})).unwrap();
path
}
/// #862: a PowerPoint Show handed over by the system (command line, double-click) starts its
/// slide show at once, full screen and from the first slide.
#[test]
fn a_ppsx_from_the_system_starts_the_show() {
let path = saved_as("Talk.PPSX", 3);
let mut app = SlideApp::new(Session::new(), crate::Services::default());
assert!(app.open_from_system(std::slice::from_ref(&path)).is_empty());
assert_eq!(app.session.documents().len(), 1);
let show = app.show.as_ref().expect("the slide show started");
assert_eq!(show.state.slide, 0);
assert!(!show.reading, "full screen, not Reading View");
std::fs::remove_file(&path).ok();
}
/// #862: a `.pptx` from the system opens for editing, and so does a `.ppsx` followed by a
/// `.pptx`: the show would otherwise play the deck opened last.
#[test]
fn a_pptx_from_the_system_opens_for_editing() {
let pptx = saved_as("edit.pptx", 3);
let ppsx = saved_as("first.ppsx", 2);
let mut app = SlideApp::new(Session::new(), crate::Services::default());
assert!(app.open_from_system(std::slice::from_ref(&pptx)).is_empty());
assert!(app.show.is_none());
assert!(app.open_from_system(&[ppsx.clone(), pptx.clone()]).is_empty());
assert_eq!(app.session.documents().len(), 3);
assert!(app.show.is_none(), "the last file is a .pptx");
std::fs::remove_file(&pptx).ok();
std::fs::remove_file(&ppsx).ok();
}
/// #862: File › Open opens a `.ppsx` for editing, as PowerPoint does.
#[test]
fn file_open_opens_a_ppsx_for_editing() {
let path = saved_as("open.ppsx", 2);
let mut app = SlideApp::new(Session::new(), crate::Services::default());
app.open_path_in_background(&path);
wait(&mut app);
assert_eq!(app.session.active().unwrap().doc.slides.len(), 2);
assert!(app.show.is_none());
assert_eq!(app.ui.view, crate::ViewMode::Normal);
std::fs::remove_file(&path).ok();
}
/// #862: Esc, or a click past the end screen, ends the `.ppsx` show and leaves the deck open in
/// the editor (PowerPoint closes it instead).
#[test]
fn leaving_the_ppsx_show_keeps_the_deck_open() {
let path = saved_as("leave.ppsx", 2);
for leave in [egui::Key::Escape, egui::Key::ArrowRight] {
let mut app = SlideApp::new(Session::new(), crate::Services::default());
assert!(app.open_from_system(std::slice::from_ref(&path)).is_empty());
let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
harness.run_steps(3);
assert!(harness.state().show.is_some(), "the show is running");
if leave == egui::Key::ArrowRight {
for _ in 0..2 {
harness.key_press(egui::Key::ArrowRight);
harness.run_steps(2);
}
assert!(harness.state().show.as_ref().is_some_and(|s| s.ended), "the end screen");
}
harness.key_press(leave);
harness.run_steps(2);
assert!(harness.state().show.is_none(), "{leave:?} ends the show");
assert_eq!(harness.state().session.documents().len(), 1, "{leave:?}: the deck stays open");
assert_eq!(harness.state().ui.view, crate::ViewMode::Normal);
}
std::fs::remove_file(&path).ok();
}
}
+28 -4
View File
@@ -1,7 +1,7 @@
//! Title bar, ribbon tabs and the ribbon card with every tab's groups.
use deckcraft_engine::Target;
use deckcraft_model::{ShapeKind, anim::AnimClass};
use deckcraft_model::{ShapeId, ShapeKind, anim::AnimClass};
use egui::{Align2, Color32, CornerRadius, Rect, Sense, Stroke, Ui, pos2, vec2};
use serde_json::{Value, json};
@@ -1134,6 +1134,9 @@ pub fn arrange_menu(app: &mut SlideApp, ui: &mut Ui) {
}
pub fn align_menu(app: &mut SlideApp, ui: &mut Ui) {
let selection = app.session.active().map(|d| d.selection.shapes.clone()).unwrap_or_default();
let to_slide = align_to_slide(app.align_to.as_ref(), &selection);
let to = if to_slide { "slide" } else { "selection" };
for (l, e, ic) in [
("Align Left", "left", Icon::AlignObjLeft),
("Align Center", "center", Icon::AlignObjCenter),
@@ -1142,11 +1145,28 @@ pub fn align_menu(app: &mut SlideApp, ui: &mut Ui) {
("Align Middle", "middle", Icon::AlignObjMiddle),
("Align Bottom", "bottom", Icon::AlignObjBottom),
] {
menu_item(app, ui, ic, l, "arrange.align", json!({"edge": e}));
menu_item(app, ui, ic, l, "arrange.align", json!({"edge": e, "to": to}));
}
ui.separator();
menu_item(app, ui, Icon::DistributeH, "Distribute Horizontally", "arrange.distribute", json!({"dir": "horizontal"}));
menu_item(app, ui, Icon::DistributeV, "Distribute Vertically", "arrange.distribute", json!({"dir": "vertical"}));
menu_item(app, ui, Icon::DistributeH, "Distribute Horizontally", "arrange.distribute", json!({"dir": "horizontal", "to": to}));
menu_item(app, ui, Icon::DistributeV, "Distribute Vertically", "arrange.distribute", json!({"dir": "vertical", "to": to}));
ui.separator();
let en = enabled(app, "arrange.align");
for (l, slide) in [("Align to Slide", true), ("Align Selected Objects", false)] {
if widgets::check_item(ui, l, en, to_slide == slide).clicked() {
app.align_to = Some((selection.clone(), slide));
ui.close();
}
}
}
/// Align to Slide or to the selected objects, as in PowerPoint: one object aligns to the slide and
/// several to each other, unless the other choice was ticked for this same selection.
fn align_to_slide(choice: Option<&(Vec<ShapeId>, bool)>, selection: &[ShapeId]) -> bool {
match choice {
Some((ids, to_slide)) if ids.as_slice() == selection => *to_slide,
_ => selection.len() < 2,
}
}
pub fn menu_item(app: &mut SlideApp, ui: &mut Ui, icon: Icon, label: &str, id: &str, p: Value) {
@@ -3454,6 +3474,10 @@ mod effects_tests;
#[path = "master_layout_tests.rs"]
mod master_layout_tests;
#[cfg(test)]
#[path = "align_tests.rs"]
mod align_tests;
#[cfg(test)]
mod title_bar_tests {
use super::*;
+67 -5
View File
@@ -650,12 +650,12 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) {
show.step_end = now;
}
} else if show.trans.is_none() {
// Auto-advance (After: timings) or autoplay preview.
// Auto-advance (After: timings) or autoplay preview. An automatic first step is started
// by `ShowState` as the slide appears; starting it here too replayed it after Back (#844).
let idle = now - show.step_end.max(show.slide_start);
let cur_step = show.state.step;
let next_auto = show.timeline(&doc).step_is_auto(cur_step);
let n_steps = show.timeline(&doc).steps();
let step_due = cur_step < n_steps && ((show.autoplay && idle > 0.3) || next_auto);
let step_due = show.autoplay && cur_step < n_steps && idle > 0.3;
let holding = show.grid || show.zoom.is_some() || show.zoom_arm;
if !holding && (step_due || (!show.rehearse && show.state.auto_advance_due(&doc, idle) && !show.ended)) {
actions.push(show.state.next(&doc));
@@ -918,10 +918,12 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) {
ctx.set_cursor_icon(egui::CursorIcon::None);
} else if show.zoom_arm || show.grid {
ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
} else if now - show.last_move > 2.5 && !show.reading {
// Idle first: a still pointer hides also over a clickable shape, such as a playing clip.
ctx.set_cursor_icon(egui::CursorIcon::None);
ctx.request_repaint_after(std::time::Duration::from_millis(500));
} else if pointing {
ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
} else if now - show.last_move > 2.5 && !show.reading {
ctx.set_cursor_icon(egui::CursorIcon::None);
ctx.request_repaint_after(std::time::Duration::from_millis(500));
}
let pen_col = theme::to_color32(doc.show.pen_color);
@@ -1881,6 +1883,32 @@ mod tests {
use super::*;
/// #968: over a shape a click acts on (a clip with its play trigger, a link) the pointing hand
/// never gave way to the idle hide, so a still pointer stayed on the playing video.
#[test]
fn a_still_cursor_hides_over_a_clickable_shape() {
let mut session = deckcraft_engine::Session::with_new();
let size = session.active().unwrap().doc.slide_size;
let r = session.execute("shape.insert", &json!({"preset": "rect", "rect": [0.0, 0.0, size.width, size.height]})).unwrap();
session.execute("insert.hyperlink", &json!({"url": "https://example.org", "ids": [r["id"]]})).unwrap();
let app = SlideApp::new(session, crate::Services::default());
let mut harness = egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).with_step_dt(0.25).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
harness.run_steps(3);
harness.state_mut().start_show(0, false);
harness.run_steps(2);
harness.hover_at(pos2(500.0, 350.0));
harness.run_steps(2);
assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand);
harness.run_steps(12);
assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::None, "still for 3 s: hidden");
}
/// Send real egui key events to the presenter UI, without the audience window's handler.
#[test]
fn presenter_navigation_uses_its_own_keyboard_events() {
@@ -2246,4 +2274,38 @@ mod tests {
let doc = s.active().unwrap().doc.clone();
assert_eq!(next_rect(right, &doc).width(), 400.0);
}
#[test]
fn back_leaves_a_slide_whose_first_animation_is_with_previous() {
// #844: Back on such a slide undid its first step, and the next frame played that step
// again by itself, so Back never reached the slide before.
let mut session = deckcraft_engine::Session::with_new();
session.execute("slide.new", &json!({})).unwrap();
let id = session.active().unwrap().doc.slides[1].shapes[0].id;
session
.execute("animation.add", &json!({"effect": "fade", "class": "entrance", "ids": [id.0], "start": "withPrevious", "duration": 500}))
.unwrap();
let app = SlideApp::new(session, crate::Services::default());
let mut harness = egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
harness.run_steps(3);
harness.state_mut().start_show(0, false);
harness.run_steps(2);
harness.key_press(egui::Key::ArrowRight);
// The first step plays by itself and ends (0.5 s; a frame is 0.25 s).
harness.run_steps(8);
let st = &harness.state().show.as_ref().unwrap().state;
assert_eq!((st.slide, st.step, st.playing), (1, 1, false), "on slide 2, fully built");
for _ in 0..5 {
harness.key_press(egui::Key::ArrowLeft);
harness.run_steps(2);
}
let st = &harness.state().show.as_ref().unwrap().state;
assert_eq!(st.slide, 0, "five Backs leave slide 2 (step {}, playing {})", st.step, st.playing);
}
}
+4 -1
View File
@@ -233,7 +233,9 @@ fn notes_menu_language_dialog_and_repeated_words() {
if let (Ok(path), Ok(img)) = (std::env::var("DECKCRAFT_PNG_OUT_NOTES"), h.render()) {
let _ = img.save(path);
}
// Right-click the notes' first word.
// Right-click the notes' first word, once the (background) notes check is in.
assert_eq!(h.state_mut().squiggles.settle_notes("Remmeber the the plan", "xx-NM"), vec![(0, 8), (13, 16)]);
h.run_steps(2);
let notes = h.query_all_by_role(Role::MultilineTextInput).next().map(|n| n.rect()).unwrap();
right_click(&mut h, egui::pos2(notes.left() + 14.0, notes.top() + 8.0));
if let (Ok(path), Ok(img)) = (std::env::var("DECKCRAFT_PNG_OUT_NOTES_MENU"), h.render()) {
@@ -245,6 +247,7 @@ fn notes_menu_language_dialog_and_repeated_words() {
let notes_text = |h: &Harness<'_, SlideApp>| h.state().session.active().unwrap().doc.slides[0].notes_text();
assert_eq!(notes_text(&h), "Remember the the plan");
// The repeated "the": its squiggle starts after "Remember the ".
h.state_mut().squiggles.settle_notes("Remember the the plan", "xx-NM");
h.run_steps(4);
let x = h.query_all_by_role(Role::MultilineTextInput).next().map(|n| n.rect()).unwrap();
let mut found = false;
+19
View File
@@ -152,6 +152,25 @@ pub fn small_button_ex(ui: &mut Ui, icon: Icon, label: &str, enabled: bool, sele
(if split { main_resp } else { resp }, arrow_resp)
}
/// A menu choice ticked in the icon column (Align to Slide…), its text lined up with the
/// [`small_button`] items around it.
pub fn check_item(ui: &mut Ui, label: &str, enabled: bool, on: bool) -> Response {
let t = Tokens::get(ui.ctx());
let font = theme::font(12.0);
let tw = ui.fonts_mut(|f| f.layout_no_wrap(label.to_string(), font.clone(), t.text).size().x) + 5.0;
let (rect, resp) = ui.allocate_exact_size(vec2(24.0 + tw, 22.0), if enabled { Sense::click() } else { Sense::hover() });
resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, enabled, on, label));
let painter = ui.painter_at(rect);
if let Some(c) = bg(ui, &resp, false, &t) {
painter.rect_filled(rect, CornerRadius::same(4), c);
}
if on {
icons::paint(&painter, Rect::from_center_size(pos2(rect.min.x + 12.0, rect.center().y), vec2(17.0, 17.0)), Icon::Check, t.text, !enabled);
}
painter.text(pos2(rect.min.x + 24.0, rect.center().y), Align2::LEFT_CENTER, label, font, if enabled { t.text } else { t.text_faint });
resp
}
/// A square icon toggle (B, I, U, alignment…).
pub fn icon_toggle(ui: &mut Ui, icon: Icon, tip: &str, enabled: bool, on: bool) -> Response {
let t = Tokens::get(ui.ctx());
+2 -1
View File
@@ -67,7 +67,7 @@ In, Wipe, Zoom, Float In, Grow/Shrink, Pulse, Spin, motion lines): weighted, ~85
| Effect Options (direction, sequence by paragraph) | yes | yes |
| Effect dialog: sound, after-animation dim/hide, animate text by word/letter, smooth start/end, bounce end, repeat, rewind | yes | partly; repeat and bounce end round-trip; rewind lost on PPTX save (#77) |
| By-paragraph text builds, sub-bullets follow parents | yes | yes |
| Triggers (on click of a shape) | yes | yes; played in the show: a step per click, the sequence starts over after its last step, a click completes a playing step |
| Triggers (on click of a shape) | yes | yes; played in the show: a step per click, the sequence starts over after its last step, a click completes a playing step. Separate click steps, mixed starts and paragraph builds survive PPTX save (`trigger_steps.rs`) |
| Triggers on a media bookmark | yes | no |
| Animation Painter | yes | yes (#54) |
| Animation Pane: list, reorder, remove | yes | yes |
@@ -94,6 +94,7 @@ In, Wipe, Zoom, Float In, Grow/Shrink, Pulse, Spin, motion lines): weighted, ~85
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | trivial | PPTX interactive sequences preserve later On Click effects and one click per paragraph; no change to playback or feature scores |
| 2026-10-14 | trivial | Community PR wave folded: the Animation Pane timeline row says yes (it landed), preview split into canvas (yes) and from the selected effect (no); estimates drop the timeline and transition sounds (~15–27 h) |
| 2026-10-14 | trivial | Repeat and bounce end round-trip through PPTX; rewind is still lost (#77) |
| 2026-10-13 | minor | Animations ▸ Preview and Animation Pane ▸ Play All play the current slide's animations on the editor canvas; preview from the selected effect is still open |
+5 -1
View File
@@ -3,6 +3,10 @@
Start the app with `--control <port>`. The server listens on `127.0.0.1` only and speaks JSON
lines: one request object per line, one reply per line.
A line that is not a JSON object with a string `method` (an HTTP request, text that isn't JSON,
bytes that aren't UTF-8) gets one error reply and the server closes the connection; nothing sent
after it runs. Blank lines are skipped.
The connected MCP client requires the reply's numeric `id` to match its request, `ok` to be a
boolean, and exactly one of `result` (success) or a string `error` (failure). It caps each reply at
16 MiB including its terminating newline, accepts CRLF, and rejects EOF inside a frame. Invalid
@@ -45,7 +49,7 @@ Coordinates are slide points (1/72 inch; a 16:9 slide is 960 × 540) unless note
| `ui.render` | `{path?, slide?, scale?}` | Render a slide headlessly |
| `ui.resize` / `ui.focus` | | Window control |
| `show.start` / `show.end` | `{from?: slide index, custom?: name, reading?}` | Slide show. `custom` plays that custom show from its first slide and does not change Set Up. With no `from` and no `custom`, playback starts at the first slide of the show order |
| `app.open` / `app.save` / `app.export` / `app.quit` | `{path, …}` | Files (export takes the `file.export` params, e.g. `{"path": "deck.pdf", "layout": "handouts", "perPage": 3}` or `{"path": "deck.gif", "width": "large", "secondsPerSlide": 3, "loop": false}`) |
| `app.open` / `app.save` / `app.export` / `app.quit` | `{path, …}` | Files (export takes the `file.export` params, e.g. `{"path": "deck.pdf", "layout": "handouts", "perPage": 3}` or `{"path": "deck.gif", "width": "large", "secondsPerSlide": 3, "loop": false}`, or `{"path": "slide.png", "transparentBackground": true}` for a PNG without the slide background) |
The MCP server (`deckcraft-cli mcp`, see [mcp.md](mcp.md)) wraps the same methods for Claude
and other agents; `deckcraft-cli app --method METHOD [PARAMS]` sends one request from a shell.
+7 -3
View File
@@ -1,6 +1,6 @@
# File-format parity with PowerPoint
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-14 · **Change:** major (community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-15 · **Change:** major (community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
Every format PowerPoint reads or writes, DeckCraft's support, fidelity and how it is tested.
Gaps are itemized in [gaps.md](gaps.md#file-formats). Dimension score: **~58% ready**
@@ -18,7 +18,7 @@ PowerPoint opens and saves; Viewer = opens only).
|---|---|---|---|---|---|
| `.pptx` presentation | Editor | yes | yes | Broad (see below); an owned corpus of decks we author round-trips tables, charts, animations, media, sections, masters and layouts, comments, links and actions, custom shows, rotated groups, inherited placeholders, text effects and body layout, theme effects, fills, bevels, connectors, 3-D models and animation bounce end. Not measured against PowerPoint renders or decks from outside this repo | `crates/pptx/tests/corpus.rs`, `corpus_kinds.rs`, `corpus_elements.rs`, `corpus_style.rs`, `corpus_themes.rs`, `corpus_charts.rs`, `corpus_media.rs`, `roundtrip.rs`, `sample.rs`, `malformed.rs`, `sniff.rs`; opened in PowerPoint by hand 2026-10-06 |
| `.potx` template | Editor | yes (as a presentation) | no: written with the `.pptx` content type | `file.saveTemplate` is Save As under another name | none |
| `.ppsx` slide show | Editor | yes (as a presentation) | no: written as `.pptx` content | Doesn't start in show mode | none |
| `.ppsx` slide show | Editor | yes (as a presentation) | no: written as `.pptx` content | Handed over by the system (command line, file association) it starts the slide show, as in PowerPoint; File › Open opens it for editing. The macOS Finder event arrives with #432 | `crates/ui-egui/src/opening.rs` tests |
| `.pptm` / `.potm` / `.ppsm` macro-enabled | Editor | no | no | Should open and keep `vbaProject.bin` without running it | none |
| `.ppt` / `.pot` / `.pps` 97–2003 binary | Editor | no | no | Owner decision; import only would be enough | none |
| `.odp` OpenDocument | Editor | no | no | | none |
@@ -26,7 +26,7 @@ PowerPoint opens and saves; Viewer = opens only).
| `.deckcraft` native (zip + JSON) | n/a | yes (also `.slidecraft`) | yes | Lossless for the DeckCraft model, forward compatible | `crates/format` tests |
| PDF | export | no | yes | Slides, notes pages, handouts (1–9); real-text layer with embedded subsets, links, bookmarks. Slide artwork is a raster image at print resolution, not vector | `crates/pdf` tests |
| Outline `.rtf` / `.txt` | export (RTF), import (outline) | `.txt` outline; `.md` as Markdown (headings are slides, list items bullets) (`slide.fromOutline`) | `.txt` outline | No RTF | engine tests |
| PNG / JPEG slide images | export | n/a | yes (`file.export`, `deckcraft-cli render`) | Matches the editor's renderer. PNG `pHYs` and JPEG JFIF density are `scale` × 72 dpi (default scale 2 is 144 dpi), so Preview shows the slide's real size | render and engine tests |
| PNG / JPEG slide images | export | n/a | yes (`file.export`, `deckcraft-cli render`) | Matches the editor's renderer. PNG `pHYs` and JPEG JFIF density are `scale` × 72 dpi (default scale 2 is 144 dpi), so Preview shows the slide's real size. PNG can leave the slide background out (`transparentBackground`, Export… “Transparent background”, `deckcraft-cli render --transparent`), so only the slide's content is opaque (#784) | render, engine, UI and CLI tests |
| TIFF / BMP / GIF slide images | export | n/a | no | Easy (the `image` crate writes them) | none |
| Animated GIF of the deck | export | n/a | yes (`file.export` format `gif`, Export…, `deckcraft-cli`, MCP `export`) | One frame per slide from the slide renderer; size small/medium/large/extra large or 16–3840 px wide, 0.1–600 s per slide, loop forever or play once, slide range, hidden slides skipped; a 256-colour palette per frame (exact, or NeuQuant above 256 colours). Transitions and build animations are not animated | `crates/engine/src/gif_export.rs` tests (decoded frames, size, delay, loop, hidden slides, hostile params), MCP, CLI and export dialog tests |
| MP4 / MOV video of the deck | export | n/a | no | Needs timeline render + H.264 encode | none |
@@ -103,6 +103,10 @@ the round trip even though DeckCraft doesn't model it.
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | trivial | PPTX interactive timing sequences keep later On Click steps and paragraph click builds (`trigger_steps.rs`); mixed starts and independent buttons survive import/edit/save/reopen |
| 2026-10-15 | minor | A `.pptx` slide that can't be read is reported instead of dropped in silence: `file.open` and `file.openBytes` return `lostSlides`, the app shows a message and opens a repaired copy (Save asks for a new name), and `deckcraft-cli` warns on stderr (#203) |
| 2026-10-16 | minor | PNG slide export with a transparent background (#784) |
| 2026-10-16 | trivial | A `.ppsx` opened from the command line or the file association starts the slide show (#862) |
| 2026-10-14 | minor | Community PR wave folded: one row each for `.pptx` (seven owned corpus files), outline, 3-D models, embedded fonts, text, effects, 3-D (extrusion sides draw now), SmartArt (written as a diagram) and VBA (tags and custom XML are kept) |
| 2026-10-12 | minor | SmartArt import lays each shape's text out on its `dsp:txXfrm` text rectangle instead of the shape box |
| 2026-10-13 | minor | EMF/WMF rectangle clip regions limit later drawing; EMF+ records remain |
+8 -7
View File
@@ -212,11 +212,10 @@ of the effect gallery. Detail in [animation-parity.md](animation-parity.md). 8
counters): a click on a shape whose action is "play sound" (`ppaction://media`, 126 and 486
shapes in two decks) does nothing; triggers that start on `onStopAudio` or `begin` conditions are
not read as triggers; click boxes are the shape's bounding box (a hexagon's corners count) and do
not follow a shape that a motion path has moved; the PPTX writer turns every "on click" after the
first effect of a trigger into "after previous", so a trigger with several click steps saved from
DeckCraft plays all of them at once.
- **Impact:** games built around sound effects on buttons, or around a button that counts up with
repeated clicks, lose that part when they are saved from DeckCraft or played in it.
not follow a shape that a motion path has moved. Trigger sequences now keep their separate
click steps on PPTX save, including paragraph builds (`crates/pptx/tests/trigger_steps.rs`).
- **Impact:** games built around sound effects on buttons, audio-triggered effects or moving
clickable shapes do not play as authored.
- **Estimate:** 4–8 h.
### Notes and Handout masters
@@ -258,8 +257,8 @@ of the effect gallery. Detail in [animation-parity.md](animation-parity.md). 8
installed (always on Windows and the web) only a short list of common misspellings is found.
`review.thesaurus` looks up the selected word (checklist row partial). AutoCorrect has
PowerPoint's options (two initial capitals, sentence and day capitals, caps lock, fractions, an
editable replace list); no AutoFormat of ordinals or automatic bulleted lists, no undo of a
single correction.
editable replace list), and AutoFormat superscripts ordinals (1st) as you type; no automatic
bulleted lists, no undo of a single correction.
- **Estimate:** 1–2 h (bundle openly licensed dictionaries); 2–4 h (AutoFormat as you type).
### Equations
@@ -355,6 +354,8 @@ Detail in [localization-parity.md](localization-parity.md).
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | trivial | PPTX trigger sequences keep later On Click steps instead of converting them to After Previous; mixed starts, independent buttons and paragraph builds have synthetic round-trip regressions |
| 2026-10-16 | trivial | AutoFormat superscripts ordinals (1st, 22nd) as you type, with an AutoCorrect option to turn it off; automatic bulleted lists remain |
| 2026-10-14 | trivial | Fixed #718: remote MCP no longer accepts unrelated or buffered stale success; loopback regressions cover invalid envelopes, incomplete and oversized frames |
| 2026-10-14 | minor | Community PR wave folded: one entry each for the soak tests (engine and UI), the PPTX corpus (seven owned corpus files), edit points / text warp / 3-D, proofing (Hunspell spelling, thesaurus, AutoCorrect), the smaller missing rows, dialogs (41 vs ~60; Print and Insert Object left) and pen/trackpad input; ranked rows 3, 4 and 10 de-duplicated (comment threads #70 and the pane timeline are done); the fixed command-palette entry (#79) removed |
| 2026-10-13 | minor | EMF/WMF rectangle clip regions (`INTERSECTCLIPRECT`, `EXCLUDECLIPRECT`, `EXTSELECTCLIPRGN`) limit later drawing. EMF+ records remain |
+1 -1
View File
@@ -206,7 +206,7 @@ Open P0 items: Contextual tabs (Shape Format, Picture Format, Table Design/Layou
| Animations | Effect options, start (on click/with/after), duration, delay | P0 | D |
| Animations | Animation pane (reorder, timing) | P0 | P |
| Animations | By-paragraph text builds | P1 | D |
| Animations | Triggers | P2 | D |
| Animations | Triggers (separate click steps and paragraph builds round-trip; `crates/pptx/tests/trigger_steps.rs`) | P2 | D |
| Animations | Animation Painter | P2 | D |
| Animations | Preview in editor | P1 | D |
| Slide show | Full-screen show from start / current | P0 | D |
+1
View File
@@ -115,6 +115,7 @@ plan above.
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | trivial | PPTX trigger click steps survive save, including by-paragraph builds. Interactive-deck gaps remain media actions, audio triggers and click-box geometry; milestone scope and feature scores unchanged |
| 2026-10-14 | trivial | M13 reliability: remote MCP validates IDs and envelopes, caps replies and rejects incomplete frames; #718 |
| 2026-10-14 | minor | Community PR wave folded: one Review gate row, one Current focus item 2, one beta row each for items 9 and 10 (timeline and timer controls are in), one after-beta paragraph, one M9 and M10 row, one corpus row in the 2026-10-07 history |
| 2026-10-13 | trivial | Beta item 3: embedded fonts are in, except MicroType Express subsets |
+2 -1
View File
@@ -186,7 +186,7 @@ Features row of the dimension table keeps ~62% until the next full re-measure).
| Masters and themes | 7 | 92% | ~70% | 8–14 | Notes/Handout master view polish, effect-scheme depth, Designer suggestions | [parity-checklist.md](parity-checklist.md) |
| Shapes | 7 | 91% | ~75% | 8–14 | Edit points depth, WordArt depth (the Transform gallery and warp adjust handles are in) | [ui-parity.md](ui-parity.md) |
| Format (fill, line, effects) | 6 | 83% | ~65% | 8–14 | Format Shape pane depth, bevel and 3-D, picture/texture fill options | [ui-parity.md](ui-parity.md) |
| Arrange | 3 | 100% | ~90% | 1–2 | Align to slide vs selected as a menu choice, More Rotation Options | [ui-parity.md](ui-parity.md) |
| Arrange | 3 | 100% | ~90% | 1–2 | More Rotation Options | [ui-parity.md](ui-parity.md) |
| Text | 15 | 83% | ~62% | 18–30 | Font weights beyond Regular/Bold/Italic (#69), true vertical CJK, dictionaries, AutoFormat as you type, thesaurus depth, equations (PR #55 open) | [localization-parity.md](localization-parity.md) |
| Tables | 5 | 97% | ~75% | 3–6 | Draw table depth, borders and cell effects depth | [parity-checklist.md](parity-checklist.md) |
| Charts | 7 | 65% | ~45% | 12–20 | Data grid editing, chart elements, the `chartex` types (waterfall, funnel, treemap, sunburst, histogram, box) | [parity-checklist.md](parity-checklist.md) |
@@ -289,6 +289,7 @@ scored done (16 open issues).
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | trivial | Arrange shortfall: Align to Slide and Align Selected Objects are in the Align menu. Percentages unchanged |
| 2026-10-14 | minor | Community PR wave folded: one headline breadth row (84% over 191 features after `cargo xtask parity`; duplicate checklist rows removed), one row per feature area with the latest breadth and shortfalls, one Themes / Slide show / Views / Review / Automation bullet each (320 engine commands). SmartArt ready ~35% (Text Pane, 6e40335) moves the area mean to 62.8%; dimension and headline percentages unchanged |
| 2026-10-13 | minor | Shapes shortfall "text warp" narrowed to adjust handles: the Transform gallery applies a preset |
| 2026-10-14 | minor | Media remainder: Insert › Icons places Lucide stroke icons. 3-D models and stock content remain. Headline percentages unchanged; the checklist row stays missing |
+2 -1
View File
@@ -55,7 +55,7 @@ menu colours taken from the theme tokens (menu `chrome`, page `card`).
| Save As | Places, folder, file name, type, Save, More options | Type (PowerPoint, DeckCraft, PDF, Outline, PNG, JPEG) and Save, which opens the system Save dialog (web: Download). .pptx/.deckcraft take the new file; the others are copies (`file.saveAs`, `file.export`) |
| Print | Print and Copies, Printer, Print All / Selection / Current / Custom Range, Slides box, layout (Full Page Slides, Notes Pages, Outline, Handouts 1–9), sides, collation, colour, Edit Header & Footer; page preview with pager and zoom | Print, Print All Slides / Current Slide / Custom Range, Slides box (`1-3, 5`), Full Page Slides / Notes Pages / Handouts 1–9, Print Hidden Slides, Frame Slides, Edit Header & Footer; preview with pager. DeckCraft prints through a PDF (`file.export`) opened in the system viewer, which has the printers (web: downloaded). No printer list, copies, sides or colour |
| Share | Cloud sharing | Not offered |
| Export | Create PDF/XPS Document, Create a Video, Create an Animated GIF, Package Presentation for CD, Create Handouts, Change File Type | Create PDF Document, Create Handouts (a PDF), Change File Type. No video, GIF or CD package |
| Export | Create PDF/XPS Document, Create a Video, Create an Animated GIF, Package Presentation for CD, Create Handouts, Change File Type | Create PDF Document, Create Handouts (a PDF), Change File Type (PNG with an optional transparent background, #784). No video, GIF or CD package |
| Close | Closes; asks Save / Don't Save / Cancel about unsaved changes | Same (`file.close` after the prompt); Ctrl+W asks too |
| Account | User information, sign-in, Office Background and Office Theme, product information, About | Appearance (light/dark, `view.dark`), product information, About DeckCraft. No accounts to sign in to |
| Options | Opens the PowerPoint Options dialog | Opens Preferences |
@@ -165,6 +165,7 @@ consistency is open (#73, #56).
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | Export › Change File Type › PNG and the Export… dialog offer a transparent background (#784) |
| 2026-10-14 | minor | Gray list markers on empty paragraphs while editing; caret keeps the list indent before typing |
| 2026-10-14 | minor | Community PR wave folded: one row each for Format Shape, Dialogs (41, listed from `dialogs.rs`), Animation Pane (timeline is in), window, Quick Access Toolbar, Format Background, rulers, image paste, context menus, exact size and edit points; estimates re-totalled (~26–46 h) |
| 2026-10-13 | trivial | Eyedropper in the colour menus (#367) |