Compare commits

..
Author SHA1 Message Date
FredApps f17e0582dc Keep DeckCraft print job feedback after leaving the printer settings 2026-12-03 00:03:06 +01:00
FredApps 16cb262983 Install desktop printing through an explicit host capability
Keep PDF viewer fallback for other hosts even when they can pick files, and exercise an unsuccessful printer job with the test spool.
2026-12-02 20:47:24 +01:00
FredApps cf091013e6 Use shared desktop print jobs and the Windows helper
Keep DeckCraft job options and viewer fallback. Discover queues on host jobs, report lost results as uncertain, and shut down the spool on exit.
2026-12-02 20:43:04 +01:00
Dejan Kocić c29124a389 Web: use the shared browser print dialog
Adapt the browser intent from DeckCraft #66 to the existing Print page and its PDF composition. Retain the explicit PDF export and stage adoption until craft-libs includes the browser lifecycle update.

(cherry picked from commit 68ad9af8e3)
2026-12-02 20:38:49 +01:00
Larry e4c99e2d6f Print: list queues without the driver query; report the printer the job went to
Review: printer_queues() avoids a PrintCapabilities wait on Windows when the
Print page opens, and the status names the printer captured at submission,
not the current selection.

(cherry picked from commit b81c420308)
2026-12-02 20:34:37 +01:00
Larry c33deedb94 Print: send to a printer directly on the desktop
File › Print now has a printer list and copies, and the Print button sends the
job straight to the chosen printer through craft-print, as PowerPoint does,
instead of opening a PDF in the system viewer. On macOS craft-print goes
through the system print path (storytold/craft-libs#4624), so sign-in queues
such as PaperCut use the keychain. "Open as PDF instead" keeps the old route;
the web build is unchanged.

(cherry picked from commit 6ad54311b3)
2026-12-02 20:34:35 +01:00
189 changed files with 1653 additions and 6985 deletions
-1
View File
@@ -1 +0,0 @@
craft-i18n.rev text eol=lf
-10
View File
@@ -73,16 +73,6 @@ families excluded by `crates/fonts/build.rs`:
Web (wasm32) builds embed only Inter Regular/Bold (and a Variable face where the Latin manifest
provides one) and BIZ UDPGothic Regular.
## Embedded at build time from craft-i18n (`CRAFT_I18N_DIR`)
Builds with a craft-i18n checkout (at the commit in `craft-i18n.rev`) embed its interface
catalogs for the languages DeckCraft offers (`locales/<locale>/common.tsv` and `deckcraft.tsv`).
They are text, not files in this repository; without the checkout the interface is English only.
| Asset | Author | Source | Licence | Use |
|---|---|---|---|---|
| craft-i18n interface catalogs | craft-i18n translators, credited in its [ATTRIBUTION.md](https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md) | https://github.com/storytold/craft-i18n at `craft-i18n.rev` | MIT OR Apache-2.0 | Interface languages other than English (German first); clean-room translations from the English interface labels |
## PDF writer colour profiles
`craft-pdf` is used with only its `write` feature and default features disabled. Krilla
Generated
-17
View File
@@ -1185,7 +1185,6 @@ dependencies = [
"craft-behavior",
"craft-browse",
"craft-color-ui",
"craft-control",
"craft-dialogs",
"craft-draw",
"craft-drawingml",
@@ -2470,7 +2469,6 @@ name = "deckcraft-engine"
version = "0.20.0"
dependencies = [
"chrono",
"craft-metafile",
"craft-mime",
"deckcraft-anim",
"deckcraft-color",
@@ -2488,7 +2486,6 @@ dependencies = [
"image",
"js-sys",
"log",
"memory-stats",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -2659,7 +2656,6 @@ version = "0.20.0"
dependencies = [
"chrono",
"craft",
"craft-i18n",
"craft-update",
"deckcraft-anim",
"deckcraft-color",
@@ -2674,11 +2670,9 @@ dependencies = [
"egui",
"egui_kittest",
"log",
"memory-stats",
"serde",
"serde_json",
"skrifa 0.47.0",
"sys-locale",
"toml",
"ttf-parser",
"web-time",
@@ -2698,7 +2692,6 @@ dependencies = [
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test",
"web-sys",
]
@@ -4955,16 +4948,6 @@ dependencies = [
"autocfg",
]
[[package]]
name = "memory-stats"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c73f5c649995a115e1a0220b35e4df0a1294500477f97a91d0660fb5abeb574a"
dependencies = [
"libc",
"windows-sys 0.52.0",
]
[[package]]
name = "mime"
version = "0.3.18"
-6
View File
@@ -81,12 +81,6 @@ craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "82ae596934
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "82ae5969349f2f70175011e01983eea32e4ae905", features = ["ui"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" }
# Interface translations: lookup, fallback, plurals and system-locale matching over the craft-i18n
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n,
# pinned in `craft-i18n.rev`). Same craft-libs rev as craft-ui.
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "82ae5969349f2f70175011e01983eea32e4ae905", version = "=0.1.0" }
# The system's preferred interface languages (#15). Native: OS APIs; wasm: the browser's (`js`).
sys-locale = { version = "0.3", features = ["js"] }
i_overlay = "9"
quick-xml = "0.41"
zip = { version = "3", default-features = false, features = ["deflate"] }
+1 -5
View File
@@ -236,7 +236,7 @@ DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcom
| Build | File | Notes |
|---|---|---|
| App, universal (Apple silicon + Intel) | `deckcraft-<ver>-macos-universal.dmg` | Signed and notarized; `DeckCraft.app/Contents/MacOS/deckcraft-cli` is the command-line tool |
| App, universal (Apple silicon + Intel) | `deckcraft-<ver>-macos-universal.dmg` | Signed and notarized |
| Command-line tool, universal | `deckcraft-cli-<ver>-macos-universal.zip` | Signed and notarized |
### Linux
@@ -288,13 +288,9 @@ ALSA headers).
### FreeBSD
Prebuilt FreeBSD archives require FreeBSD 15.1 or later. They are built against
FreeBSD 15.1-STABLE; older FreeBSD releases are not supported by these binaries.
| Build | File |
|---|---|
| x86_64 | `deckcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 (ARM64) | `deckcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+4 -8
View File
@@ -15,8 +15,6 @@
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** trivial (File › About replaces Account; product links, credits and appearance retained; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** trivial (progress log: fix for a workflow-breaking regression: Ctrl+C/X/V use the system clipboard again, broken for all text and objects from 0.11.1 to 0.15.0; pasted and duplicated placeholders keep their look; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** trivial (locked No Fill and no-outline click-through regression coverage added; No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-28 · **Change:** minor (interface languages from craft-i18n: language setting and German, #15; localization ~8% → ~15%; previous: trivial, progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-30 · **Change:** trivial (print-preview tests use egui's emitted URL, and macOS removes its previews before exit; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-30 · **Change:** trivial (progress log: read-only `slide.actions` lists shape and table text actions; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-27 · **Change:** trivial (progress log: Set Up Slide Show ▸ Keep mouse cursor visible, #1445; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-26 · **Change:** trivial (progress log: dragging several selected slides moves them all; previous: trivial, progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type; previous: trivial, progress log: scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
@@ -80,7 +78,7 @@ EMF/SVG pictures, the data-loss and startup-crash bugs (#60, #40, #59) and the b
| UI/UX fidelity | ~60% | 30–50 | [docs/ui-parity.md](docs/ui-parity.md) |
| File formats (PPTX, PDF, legacy, export) | ~58% | 60–110 | [docs/file-format-parity.md](docs/file-format-parity.md) |
| Hardware (GPU raster, video decode, displays, pens) | ~40% | 25–45 | [docs/hardware-parity.md](docs/hardware-parity.md) |
| Localization | ~15% | 45–80 + native review | [docs/localization-parity.md](docs/localization-parity.md) |
| Localization | ~8% | 55–90 + native review | [docs/localization-parity.md](docs/localization-parity.md) |
| Performance (unmeasured) | ~55% | 10–20 | [docs/hardware-parity.md](docs/hardware-parity.md#performance) |
| Stability | ~60% | 10–20 | [docs/gaps.md](docs/gaps.md#stability) |
| Platforms | ~80% | 5–10 | [Downloads in README](README.md#downloads) |
@@ -115,7 +113,7 @@ EMF/SVG pictures, the data-loss and startup-crash bugs (#60, #40, #59) and the b
## Languages
English and German. Interface text comes from the shared [craft-i18n](https://github.com/storytold/craft-i18n) catalogs (`locales/<lang>/deckcraft.tsv`); the interface follows the system language, or Preferences › Interface language (#15). Detail:
English only today; no string catalog yet (Ukrainian is in review as PR #34). Detail:
[docs/localization-parity.md](docs/localization-parity.md).
| Language | Code | UI strings | Status | Hours to full |
@@ -129,11 +127,11 @@ English and German. Interface text comes from the shared [craft-i18n](https://gi
| Portuguese | pt | 0% | none | 3–5 |
| Indonesian | id | 0% | none | 3–5 |
| Japanese | ja | 0% | none | 4–7 |
| German | de | ~80% | partial | 1–3 |
| German | de | 0% | none | 3–5 |
| Korean | ko | 0% | none | 4–7 |
| Vietnamese | vi | 0% | none | 3–5 |
The catalog infrastructure is in place: a new language is a `deckcraft.tsv` in craft-i18n plus one entry in `LANGUAGES` (`crates/ui-egui/src/i18n.rs`). PowerPoint for Mac
Plus 8–14 h once for the catalog infrastructure. Other languages shipped: none. PowerPoint for Mac
ships 26.
## Upcoming
@@ -187,7 +185,6 @@ app's JSON control channel (`deckcraft --control PORT`).
| 2026-11-01 | Copy, Cut, Paste, Duplicate and Alt+drag of a title, body or other placeholder on a slide keep its look: the copy is a regular shape that takes the size, font, bullets, indents, autofit and box its layout and master gave it, instead of 18 pt unbulleted text |
| 2026-11-01 | Clipboard: Ctrl+C, Ctrl+X and Ctrl+V use the system clipboard again, so text and pictures paste from other apps and in-app copies paste back. Since the egui 0.37 migration (#1350) the desktop build had a clipboard that only worked inside the app. On native Wayland, text goes through egui's Wayland clipboard; HTML stays on X11, macOS and Windows |
| 2026-10-31 | No Fill shape interiors allow selection and editing of underlying objects, even when a quick style remains; hit-testing uses the renderer’s fill resolution. Outlines, rotation, text targets and actual fills keep their hit behaviour (#1621) |
| 2026-10-28 | Interface languages (#15): DeckCraft reads the craft-i18n catalogs (`CRAFT_I18N_DIR`, pinned in `craft-i18n.rev`), follows the system language and has Preferences › Interface language and `app.language`. German is the first language: ribbon, menus, command palette, status bar, File tab, dialogs and panes |
| 2026-10-30 | Print-preview tests use the URL emitted by egui and its exact file path; previews are explicitly removed before the macOS process exits |
| 2026-10-30 | `slide.actions` lists shape click and hover actions and text-run hyperlinks (including table cells and grouped shapes) for audit; listing never runs an action. The UI pane is a follow-up |
| 2026-10-29 | Slide Show: going back to the previous slide plays the transition of the slide being left, reversed, as PowerPoint does, instead of the previous slide's own entrance transition (#1531); a jump (Go to Slide, links) still plays the target slide's transition |
@@ -373,7 +370,6 @@ app's JSON control channel (`deckcraft --control PORT`).
| 2026-11-02 | trivial | Progress log: tiled picture fills keep their size in scaled groups. Scores and milestone names unchanged |
| 2026-11-01 | trivial | Workflow-breaking regression fixed: the desktop build uses the system clipboard again (eframe `clipboard` feature) |
| 2026-10-31 | trivial | No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged |
| 2026-10-28 | minor | Interface languages from craft-i18n with German (#15): Localization ~8% → ~15%, German row partial |
| 2026-10-30 | trivial | Progress log: read-only slide action inspection; parity scores unchanged |
| 2026-10-29 | trivial | Progress log: going back in the slide show reverses the left slide's transition (#1531). Scores and milestone names unchanged |
| 2026-10-29 | trivial | Progress log: the Picture Styles row leaves room for Crop and Size (#1232). Scores and milestone names unchanged |
-5
View File
@@ -19,10 +19,5 @@ deckcraft-engine = { workspace = true }
deckcraft-mcp = { workspace = true }
serde_json = { workspace = true }
# Plain `mcp`: the agent settings (the shared `../deckcraft/src/agent_settings.rs`) and the desktop app to start
# while DeckCraft is closed.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft = { workspace = true, features = ["automation", "automation-agents", "font-catalog"] }
[dev-dependencies]
zip = { workspace = true }
+8 -15
View File
@@ -141,24 +141,17 @@ Start the app with --control-token-file PATH to have it create or read that file
},
Subcommand {
name: "mcp",
usage: "mcp [--headless] [--when-closed launch|headless|error] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...",
usage: "mcp [--connect PORT [--control-token TOKEN | --control-token-file PATH]] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...",
summary: "serve the commands to an agent over MCP on stdio",
details: "Runs a Model Context Protocol server on stdin and stdout. Every tool call goes to the open DeckCraft
window while AI agents may use it (ArtCraft Launcher > Settings > AI agents), found through the
connection file the window publishes in its settings folder: no port or token to configure, and a
window opened after the session started is found too. Otherwise the call runs on a presentation
without a window, and the session stays there, so its documents don't move under the agent: a
window opened after a call ran without one is not used by that session. While agents may use DeckCraft but it is closed, the choice in Preferences > AI
Integrations applies (open DeckCraft, work without a window in the agent folders, or an error);
--when-closed overrides it. Files the open window opens and saves for agents stay in the agent
folders set there (Documents/ArtCraft/Agents/DeckCraft when none is set); the agent_folders tool
names them. --headless always works without a window. --sample opens the sample presentation
without a window.
details: "Runs a Model Context Protocol server on stdin and stdout. It works on its own presentation without a
window, or with --connect PORT (or host:port) on the DeckCraft app started with --control PORT.
--sample opens the sample presentation.
--connect PORT (or host:port; deprecated, removed in a later release) drives the DeckCraft app
started with --control PORT. It requires the app's per-launch token: --control-token-file PATH
reads its token file, or --control-token TOKEN supplies it directly. DECKCRAFT_CONTROL_TOKEN and
Connected mode requires the app's per-launch token: --control-token-file PATH reads its token file,
or --control-token TOKEN supplies it directly. DECKCRAFT_CONTROL_TOKEN and
DECKCRAFT_CONTROL_TOKEN_FILE supply fallbacks when their corresponding flags are absent.
Start the app with --control-token-file PATH to have it create or read that file.
Headless mode does not resolve these credentials.
--automation-read-root DIR and --automation-write-root DIR confine every file the agent's commands read
(open, pictures, audio, video) and write (save, export, PDF) to those folders, links followed. Repeat either
-67
View File
@@ -2,16 +2,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the
/// closed-app choice and the agent folders the app saved.
#[cfg(not(target_arch = "wasm32"))]
#[path = "../../deckcraft/src/agent_settings.rs"]
mod agent_settings;
mod automation_args;
/// The desktop app's settings folder, shared: the open window publishes its agent connection there.
#[cfg(not(target_arch = "wasm32"))]
#[path = "../../deckcraft/src/platform_dir.rs"]
mod platform_dir;
mod help;
@@ -739,25 +730,6 @@ fn app(args: &[String]) -> Result<(), String> {
Ok(())
}
/// The stderr line `mcp --connect` prints: the flag works for one more release.
#[cfg(not(target_arch = "wasm32"))]
const CONNECT_DEPRECATED: &str = "deckcraft-cli: --connect is deprecated and will be removed in a later release; plain `deckcraft-cli mcp` finds the open DeckCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
/// Plain `mcp`'s window lookup: the agent settings in the app's settings folder `dir`, the
/// closed-app choice (`--when-closed` overrides the saved one) and the desktop app beside this CLI
/// to start.
#[cfg(not(target_arch = "wasm32"))]
fn live_backend(dir: std::path::PathBuf, when_closed: Option<craft::automation::agents::WhenAppClosed>) -> deckcraft_mcp::agents::LiveBackend {
let mut cfg = deckcraft_mcp::agents::LiveConfig::new(dir, agent_settings::read_settings);
cfg.when_closed = when_closed;
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, deckcraft_mcp::agents::APP_EXE));
deckcraft_mcp::agents::LiveBackend::new(cfg)
}
/// `mcp`: the open DeckCraft window while the person lets agents use it (the ArtCraft Launcher's
/// switch), found through its connection file on every tool call, otherwise a headless session
/// (`deckcraft_mcp::agents`). `--headless`, `--sample` and the automation roots always run headless.
/// `--connect PORT` drives an app started with `deckcraft --control PORT` (deprecated).
fn mcp(args: &[String]) -> Result<(), String> {
use deckcraft_engine::file_access::{self, AutomationRoots};
use deckcraft_mcp::{Backend, Headless, Server};
@@ -765,8 +737,6 @@ fn mcp(args: &[String]) -> Result<(), String> {
use deckcraft_mcp::{Remote, control_addr};
let mut connect: Option<String> = None;
let mut sample = false;
let mut headless = false;
let mut when_closed: Option<String> = None;
#[cfg(not(target_arch = "wasm32"))]
let mut tokens = ControlOptions::default();
let mut roots_args = automation_args::AutomationArgs::new(None, None);
@@ -783,9 +753,6 @@ fn mcp(args: &[String]) -> Result<(), String> {
match a.as_str() {
"--connect" => connect = Some(it.next().ok_or("--connect needs a port or host:port")?),
"--sample" => sample = true,
"--headless" => headless = true,
"--when-closed" => when_closed = Some(it.next().ok_or("--when-closed needs launch, headless or error")?),
flag if flag.starts_with("--when-closed=") => when_closed = flag.strip_prefix("--when-closed=").map(str::to_owned),
"--help" | "-h" => {
outln!("{}", help_page("mcp"));
return Ok(());
@@ -799,46 +766,12 @@ fn mcp(args: &[String]) -> Result<(), String> {
so drop --connect (or use --connect without the roots)"
.into());
}
if headless && connect.is_some() {
return Err("--headless runs without a window and --connect drives one: give one of them".into());
}
#[cfg(not(target_arch = "wasm32"))]
let when_closed = match when_closed.as_deref() {
None => None,
Some(choice) => {
let parsed = craft::automation::agents::WhenAppClosed::parse(choice)
.ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?;
if connect.is_some() || headless || sample || roots.is_some() {
return Err(
"--when-closed is for the open window of plain `mcp`; --connect, --headless, --sample and the automation roots never use it"
.into(),
);
}
Some(parsed)
}
};
#[cfg(target_arch = "wasm32")]
if when_closed.is_some() {
return Err("--when-closed needs a native build of deckcraft-cli".into());
}
// Plain `mcp`: the open window while agents may use it, found through the settings folder.
#[cfg(not(target_arch = "wasm32"))]
if connect.is_none() && !headless && !sample && roots.is_none() {
let dir = platform_dir::platform_dir(|key| std::env::var_os(key));
if let Some(dir) = dir {
let mut server = Server::new(Box::new(live_backend(dir, when_closed)));
let stdin = std::io::stdin();
return server.serve(stdin.lock(), std::io::stdout()).map_err(|e| e.to_string());
}
// No settings folder (no home folder): no window can be found either.
}
let backend: Box<dyn Backend> = match connect {
Some(c) => {
#[cfg(target_arch = "wasm32")]
return Err(format!("can't connect to the app at {c}: connected MCP requires a native build of deckcraft-cli"));
#[cfg(not(target_arch = "wasm32"))]
{
eprintln!("{CONNECT_DEPRECATED}");
let token = control_token(tokens)?;
Box::new(Remote::connect(&control_addr(&c), &token).map_err(|e| format!("can't reach the app at {c}: {e}"))?)
}
-20
View File
@@ -157,23 +157,3 @@ fn mcp_automation_root_flags_are_checked_up_front() {
fails(&["--automation-write-root", base.join("f.txt").to_str().unwrap()], "cannot open the automation write root");
let _ = std::fs::remove_dir_all(base);
}
/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one
/// release but says it is deprecated before it connects.
#[test]
fn mcp_when_closed_and_the_deprecated_connect() {
let fails = |args: &[&str], why: &str| {
let mut full = vec!["mcp"];
full.extend_from_slice(args);
let out = run(&full);
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
err
};
fails(&["--when-closed", "later"], "--when-closed must be launch, headless or error");
fails(&["--when-closed", "launch", "--headless"], "--when-closed is for the open window");
fails(&["--when-closed=error", "--sample"], "--when-closed is for the open window");
fails(&["--headless", "--connect", "7979"], "give one of them");
let err = fails(&["--connect", "127.0.0.1:1"], "--connect is deprecated");
assert!(err.contains("token") || err.contains("can't reach"), "{err}");
}
+1 -4
View File
@@ -22,13 +22,10 @@ log = { workspace = true }
serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
craft = { workspace = true, features = ["web-api", "web-host", "platform-browser"] }
craft = { workspace = true, features = ["web-api", "web-host", "platform-browser", "print"] }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "UrlSearchParams"] }
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = "0.3"
+3 -8
View File
@@ -108,14 +108,11 @@ impl PopupApp {
fn page(&mut self, ui: &mut egui::Ui, cx: &mut craft::ui::contract::BodyCx<'_>) {
let notice = if self.peer.state() == LinkState::Closed {
Some((deckcraft_ui_egui::tl!("The audience window has closed."), ""))
Some(("The audience window has closed.", ""))
} else if js_sys::Date::now() - self.peer.last_heard() > 10_000.0 {
Some((
deckcraft_ui_egui::tl!("The audience window is not responding."),
deckcraft_ui_egui::tl!("Return to the audience window to resume the connection."),
))
Some(("The audience window is not responding.", "Return to the audience window to resume the connection."))
} else if self.snapshot.is_none() {
Some((deckcraft_ui_egui::tl!("Waiting for the audience window…"), ""))
Some(("Waiting for the audience window…", ""))
} else {
None
};
@@ -188,8 +185,6 @@ impl eframe::App for PopupApp {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.receive(ui.ctx());
// The popup is its own program: it draws in the audience window's language (the system's before the first snapshot).
deckcraft_ui_egui::presenter::apply_language(self.snapshot.as_ref());
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
AppShell::new(WindowKey::main()).page(true, SHOW_SCOPE, |_| None, |ui, cx, app: &mut Self| app.page(ui, cx)).show(ui, self);
}
+1 -26
View File
@@ -72,7 +72,6 @@ pub fn start() {
let files = if app_bridge.is_some() { files.page_saves(craft::web_host::files::page_save) } else { files };
let host = Host::builder(AppInfo { id: "deckcraft", name: "DeckCraft", version: env!("CARGO_PKG_VERSION") })
.files(Arc::new(files))
.i18n(deckcraft_ui_egui::i18n::host_i18n())
.build();
let wake = cc.egui_ctx.clone();
let (intake, drops) = FileIntake::new(Wake::new(move || wake.request_repaint()));
@@ -91,6 +90,7 @@ pub fn start() {
}
let mut app = SlideApp::new(&cc.egui_ctx, platform).map_err(|error| std::io::Error::other(error.to_string()))?;
app.services.presenter = crate::presenter::opener(&cc.egui_ctx);
app.services.browser_print = Some(Box::new(craft::print::browser::print_pdf));
// In host mode the parent sends the presentation to edit; no sample meanwhile.
if app_bridge.is_some() {
if let Err(e) = app.start_for_host() {
@@ -215,28 +215,3 @@ impl eframe::App for WebShell {
self.app.ui(ui);
}
}
#[cfg(test)]
mod wasm_smoke_tests {
use deckcraft_engine::Session;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
// Run with wasm-bindgen-test-runner in a real browser. wasm panic=abort means a panic here
// would stop the test process; the hostile requests below must return Results instead.
#[wasm_bindgen_test::wasm_bindgen_test]
fn malformed_commands_return_errors_and_the_session_remains_usable() {
let mut session = Session::new();
assert!(session.execute("file.new", &serde_json::json!({})).is_ok(), "a presentation must be active before shape commands");
let bad_font = session.execute("font.add", &serde_json::json!({"data": "AAAA"}));
assert!(bad_font.is_err(), "invalid font data must return an error");
let bad_geometry = session.execute("shape.insert", &serde_json::json!({"preset": "not-a-shape"}));
assert!(bad_geometry.is_err(), "unknown geometry must return an error");
let valid = session.execute("shape.insert", &serde_json::json!({"preset": "rect", "rect": [0, 0, 10, 10]}));
assert!(valid.is_ok(), "a valid command must still work after malformed requests");
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ craft-nightly = { workspace = true }
deckcraft-engine = { workspace = true }
deckcraft-ui-egui = { workspace = true }
deckcraft-media = { workspace = true }
craft = { workspace = true, features = ["ui-app", "window", "gpu-startup", "quit", "dialogs", "platform", "platform-clipboard-system", "automation", "settings", "font-catalog"] }
craft = { workspace = true, features = ["ui-app", "window", "gpu-startup", "quit", "dialogs", "platform", "platform-clipboard-system", "automation", "settings", "font-catalog", "print"] }
# `clipboard` is the OS clipboard (Ctrl+C/X/V with other apps). Without it egui simulates one inside
# the app; the egui 0.37 migration (#1350) dropped it from this list.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "links", "wayland", "x11"] }
-68
View File
@@ -1,68 +0,0 @@
//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder
//! (`app_dirs.rs`). The desktop app writes them when they change (`app.agents`, `main.rs`); `deckcraft-cli`
//! (which shares this file) reads them on every tool call of plain `mcp`, for the closed-app choice
//! and the agent folders.
use std::io::Read as _;
use std::path::Path;
use craft::automation::agents::AgentSettings;
use serde_json::Value;
/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed",
/// "allowAgentControl"}`, the framework's `AgentSettings`.
pub const SETTINGS_FILE: &str = "agents.json";
/// The largest settings file read; the settings are a few short strings.
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read,
/// so neither the app nor the CLI fails over them. One bad value resets only itself.
pub fn read_settings(dir: &Path) -> AgentSettings {
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
let mut text = String::new();
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
return AgentSettings::default();
}
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
let mut settings = AgentSettings::default();
for (key, value) in saved {
let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue };
if one.contains_key(&key) {
one.insert(key, value);
if let Ok(next) = serde_json::from_value(Value::Object(one)) {
settings = next;
}
}
}
settings
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use craft::automation::agents::WhenAppClosed;
// Settings saved by the app read back in the CLI, and a damaged file or value never fails it.
#[test]
fn saved_settings_read_back_and_bad_values_reset_alone() {
let dir = std::env::temp_dir().join(format!("dc-agent-settings-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(read_settings(&dir), AgentSettings::default());
let mut settings = AgentSettings::default();
settings.read_root = "/in".into();
settings.when_app_closed = WhenAppClosed::Headless;
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(SETTINGS_FILE), serde_json::to_vec(&settings).unwrap()).unwrap();
assert_eq!(read_settings(&dir), settings);
std::fs::write(dir.join(SETTINGS_FILE), "not json").unwrap();
assert_eq!(read_settings(&dir), AgentSettings::default());
std::fs::write(dir.join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap();
let read = read_settings(&dir);
assert_eq!(read.when_app_closed, WhenAppClosed::Error);
assert_eq!(read.read_root, "");
let _ = std::fs::remove_dir_all(&dir);
}
}
+11 -2
View File
@@ -11,6 +11,7 @@
//! is exactly the one `main.rs` used before the Nightly channel; the `craft-nightly` fence
//! ([`crate::profile_root`]) still refuses a `portable.txt` marker beside a nightly executable.
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::OnceLock;
@@ -45,7 +46,16 @@ pub fn config_dir() -> Option<PathBuf> {
current().dir.clone()
}
pub use crate::platform_dir::platform_dir;
/// The platform's settings directory. Read from the environment every call, so tests can vary it.
pub fn platform_dir(env: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
if cfg!(target_os = "macos") {
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/DeckCraft"))
} else if cfg!(windows) {
env("APPDATA").map(|a| PathBuf::from(a).join("DeckCraft"))
} else {
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("deckcraft"))
}
}
/// The crash-recovery folder: inside the profile for Nightly, the platform's own folder for stable
/// (`deckcraft_engine::recovery::default_dir`, which keeps autosaves out of the synced config).
@@ -79,7 +89,6 @@ pub fn user_dictionary() -> Option<PathBuf> {
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::ffi::OsString;
fn env(pairs: &[(&str, &str)]) -> BTreeMap<String, OsString> {
pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect()
+6 -44
View File
@@ -16,7 +16,6 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod agent_settings;
mod app_dirs;
mod audio;
#[cfg(test)]
@@ -26,7 +25,6 @@ mod build_flavor;
mod display;
mod launch_profile;
mod nightly_session;
mod platform_dir;
mod process_identity;
mod profile_root;
@@ -95,48 +93,12 @@ fn desktop_platform(install: InstallSpec, settings: Location, wake: Wake, at_exi
version: env!("CARGO_PKG_VERSION"),
})
.icon_png(ICON_128)
// An agent's request in the open window reaches only the agent folders, also through the window's own reads and writes.
.files(Arc::new(deckcraft_ui_egui::confined_files::ConfinedFiles::new(Arc::new(service))))
.i18n(deckcraft_ui_egui::i18n::host_i18n())
.files(Arc::new(service))
.build();
let frame = install.frame.as_ref().map_or(Frame::Native, |decision| decision.frame.clone());
(Platform { install, host, settings, intake: None, audio_out: None, control: None, frame, at_exit }, panels)
}
/// Saves the agent settings in `dir` (created when missing), replacing the file in one step, so a
/// `deckcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
fn write_agent_settings(dir: &std::path::Path, settings: &craft::automation::agents::AgentSettings) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
let partial = dir.join(format!("{}.{}.tmp", agent_settings::SETTINGS_FILE, std::process::id()));
std::fs::write(&partial, text)?;
std::fs::rename(&partial, dir.join(agent_settings::SETTINGS_FILE)).inspect_err(|_| {
let _ = std::fs::remove_file(&partial);
})
}
/// Agents in the open window (`deckcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
/// names DeckCraft, the window serves agents on loopback and publishes the connection in its
/// settings folder `dir`, where `deckcraft-cli mcp` finds it. A connection file a crashed run left
/// is removed first. With `--control` (`launched`, the server it started, or `None` when it
/// couldn't listen) that channel serves the whole run and the link stays off.
fn agents_link(ctx: &egui::Context, dir: std::path::PathBuf, control: bool, launched: Option<&Listening>) -> deckcraft_ui_egui::agents::Agents {
use craft::automation::agents::{AgentSwitch, remove_stale_connection};
use deckcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn};
remove_stale_connection(&dir);
let switch = AgentSwitch::watch(LAUNCHER_APP_ID, {
let ctx = ctx.clone();
move || ctx.request_repaint()
});
let save_dir = dir.clone();
let save: SaveFn = Box::new(move |settings| {
write_agent_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display()))
});
let version = format!("DeckCraft {}", deckcraft_ui_egui::flavor::version());
let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save);
if control { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents }
}
fn decode_png(bytes: &[u8]) -> Option<ClipboardImage> {
let rgba = image::load_from_memory_with_format(bytes, image::ImageFormat::Png).ok()?.into_rgba8();
Some(ClipboardImage { width: rgba.width(), height: rgba.height(), rgba: rgba.into_raw() })
@@ -306,6 +268,10 @@ fn report_launch_profile_error(error: &str) {
pub(crate) const LOG_DIR: &str = "logs";
fn main() -> eframe::Result {
#[cfg(windows)]
if let Some(code) = craft::print::spool::isolated::helper_main() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
let nightly = launch_profile::current().is_nightly();
// Nightly session health: the record names this window's owner and survives an abnormal end.
@@ -448,7 +414,6 @@ fn main() -> eframe::Result {
} else {
app_dirs::config_dir().map_or(Location::Memory, Location::Dir)
};
let settings_location = settings.clone();
let (mut platform, panels) = desktop_platform(install, settings, wake, at_exit);
platform.intake = Some(intake);
// The output device clocks media; disabling audio leaves playback silent.
@@ -472,10 +437,7 @@ fn main() -> eframe::Result {
}
}
let mut app = SlideApp::new(ctx, platform)?;
// A nightly and a run without preferences let no agents into the window.
if !nightly && let Location::Dir(dir) = &settings_location {
app.with_agents(agents_link(ctx, dir.clone(), control.port.is_some(), listening.as_ref()));
}
app.enable_direct_print();
if !nightly {
// Nightly is managed by ArtCraft Launcher: no self-update prompt or stable feed.
app.enable_update_checks();
-22
View File
@@ -1,22 +0,0 @@
//! The stable settings folder by the platform's convention, shared with `deckcraft-cli`, which
//! finds the open window's agent connection and the agent settings there (`app_dirs.rs` has the
//! whole resolution, Nightly profiles included).
use std::ffi::OsString;
use std::path::PathBuf;
/// The platform's settings directory. Read from the environment every call, so tests can vary it.
pub fn platform_dir(env: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
if cfg!(target_os = "macos") {
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/DeckCraft"))
} else if cfg!(windows) {
env("APPDATA").map(|a| PathBuf::from(a).join("DeckCraft"))
} else {
// An empty or relative XDG_CONFIG_HOME is ignored, as the XDG Base Directory spec says.
env("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|c| c.is_absolute())
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("deckcraft"))
}
}
-1
View File
@@ -1 +0,0 @@
bfed1eb8df6f6fa9afe6e1c6b4683e110fd9560d
+2 -19
View File
@@ -21,12 +21,6 @@ pub(crate) struct EffectSpec {
pub amount: Option<f64>,
pub color: Option<Rgba>,
pub path: Option<MotionPath>,
/// The shape shows text (a text box, or a text body with content as in a title or body
/// placeholder or an autoshape), so Desaturate grays the text.
pub has_text: bool,
/// A shape other than a text box with a solid fill of its own, which Desaturate grays even
/// when it shows text. A text box keeps its fill.
pub grays_own_fill: bool,
/// Shape box in points (sanitized).
pub xf: Xfrm,
pub slide_w: f64,
@@ -286,13 +280,8 @@ impl EffectSpec {
}
}
"desaturate" => {
if self.has_text {
st.text_desaturation = e;
}
// Otherwise text gets no tint: without a fill it would paint a box behind the words.
if !self.has_text || self.grays_own_fill {
st.tint = Some(desaturate_color(cur, e));
}
let l = (0.299 * cur.r as f64 + 0.587 * cur.g as f64 + 0.114 * cur.b as f64).round().clamp(0.0, 255.0) as u8;
st.tint = Some(cur.lerp(Rgba::rgba(l, l, l, cur.a), e));
}
"darken" => st.tint = Some(cur.lerp(Rgba::rgba(0, 0, 0, cur.a), 0.4 * e)),
"lighten" => st.tint = Some(cur.lerp(Rgba::rgba(255, 255, 255, cur.a), 0.4 * e)),
@@ -329,12 +318,6 @@ impl EffectSpec {
}
}
/// Interpolate toward a gray of the same luma, retaining the source alpha.
pub fn desaturate_color(color: Rgba, amount: f64) -> Rgba {
let gray = (0.299 * color.r as f64 + 0.587 * color.g as f64 + 0.114 * color.b as f64).round() as u8;
color.lerp(Rgba::rgba(gray, gray, gray, color.a), amount)
}
/// The path for a motion-path animation: its own, or the preset default.
pub(crate) fn motion_path(effect: &str, option: &str, own: Option<&str>) -> MotionPath {
match own {
+3 -19
View File
@@ -36,12 +36,11 @@ pub use deckcraft_model::Rgba;
use serde::{Deserialize, Serialize};
pub use easing::ease;
pub use effects::desaturate_color;
pub use interact::{Click, HitShape, Target};
pub use mesh::{MeshVertex, layer_mesh};
pub use morph::{MorphFrame, MorphPath, MorphText, morph_crop, morph_frame, morph_pairs, morph_xfrm};
pub use path::{MotionPath, default_path};
pub use show::{LinkJump, ShowAction, ShowState, looping, safe_url, show_order};
pub use show::{LinkJump, ShowAction, ShowState, safe_url, show_order};
pub use timeline::{EffectTiming, Sequence, StepStamp, Timeline, TriggerPlay};
pub use transition::{DEFAULT_ASPECT, Layer, Source, transition_frame, transition_layers, uses_slide_parts};
@@ -49,7 +48,7 @@ pub use transition::{DEFAULT_ASPECT, Layer, Source, transition_frame, transition
///
/// Same meaning as the renderer's `ShapeState`: translation in points, scale and rotation (degrees)
/// around the shape's centre, a reveal clip in shape-local unit space `[l, t, r, b]`, and a fill
/// colour override or a reduction in the saturation of text colours.
/// colour override.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnimState {
pub visible: bool,
@@ -61,24 +60,11 @@ pub struct AnimState {
pub rotate: f64,
pub clip: Option<[f64; 4]>,
pub tint: Option<Rgba>,
#[serde(default)]
pub text_desaturation: f64,
}
impl Default for AnimState {
fn default() -> Self {
AnimState {
visible: true,
opacity: 1.0,
offset_x: 0.0,
offset_y: 0.0,
scale_x: 1.0,
scale_y: 1.0,
rotate: 0.0,
clip: None,
tint: None,
text_desaturation: 0.0,
}
AnimState { visible: true, opacity: 1.0, offset_x: 0.0, offset_y: 0.0, scale_x: 1.0, scale_y: 1.0, rotate: 0.0, clip: None, tint: None }
}
}
@@ -109,14 +95,12 @@ impl AnimState {
rotate: self.rotate + d.rotate,
clip,
tint: d.tint.or(self.tint),
text_desaturation: self.text_desaturation + (1.0 - self.text_desaturation) * d.text_desaturation,
}
}
/// Replace any non-finite number with its neutral value and clamp opacity and clip.
pub fn sanitized(mut self) -> AnimState {
let f = |v: f64, d: f64| if v.is_finite() { v } else { d };
self.opacity = f(self.opacity, 1.0).clamp(0.0, 1.0);
self.text_desaturation = f(self.text_desaturation, 0.0).clamp(0.0, 1.0);
self.offset_x = f(self.offset_x, 0.0);
self.offset_y = f(self.offset_y, 0.0);
self.scale_x = f(self.scale_x, 1.0);
+12 -178
View File
@@ -1,7 +1,6 @@
//! Morph: matching shapes between two slides, interpolating their boxes and building the frames.
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::{DefaultHasher, Hash, Hasher};
use deckcraft_model::resolve::{self, Ctx};
use deckcraft_model::{ColorRef, Fill, Geom, Presentation, Rgba, Shape, ShapeId, ShapeKind, Slide, Xfrm, walk};
@@ -13,45 +12,14 @@ fn text_of(s: &Shape) -> String {
s.text.as_ref().map(|t| t.text()).unwrap_or_default()
}
fn content_hash(s: &Shape) -> u64 {
shape_hash(&content(s))
}
fn geom_hash(s: &Shape) -> u64 {
shape_hash(&Shape { geom: Geom::default(), ..content(s) })
}
fn crop_hash(s: &Shape) -> u64 {
shape_hash(&uncropped(s))
}
fn shape_hash(s: &Shape) -> u64 {
let mut h = DefaultHasher::new();
// `PartialEq` treats -0.0 and 0.0 as equal; Debug does not, so normalise it before hashing.
format!("{s:?}").replace("-0.0", "0.0").hash(&mut h);
h.finish()
}
fn outlined(s: &Shape) -> bool {
matches!(s.kind, ShapeKind::Shape | ShapeKind::Picture { .. } | ShapeKind::Connector { .. })
}
fn picture(s: &Shape) -> bool {
matches!(s.kind, ShapeKind::Picture { .. })
}
/// Pairs of (shape on `a`, shape on `b`) that Morph animates from one to the other: first by
/// `!!name` (forced match), then by exact name when the two are the same object, then by the same
/// kind and text, then by the same kind and preset geometry if neither carries text and they are
/// the same object. The same object means the same content, or a difference only in what Morph
/// interpolates (a geometry or a picture's crop): different text, pictures or kinds fade in place
/// unless the name starts with `!!` (#2467). A text box with neither a name nor its text on the
/// other slide stays unpaired and fades in place, as in PowerPoint (#119). Each shape is used
/// `!!name` (forced match), then by exact name, then by the same kind and text, then by the same
/// kind and preset geometry if neither carries text. A text box with neither a name nor its text on
/// the other slide stays unpaired and fades in place, as in PowerPoint (#119). Each shape is used
/// once; top-level shapes only (groups move whole).
///
/// Each pass compares a key of the two shapes, so the shapes of `b` are indexed by key once per
/// pass. A strict pass also indexes the exact content and the two properties Morph can interpolate,
/// so a candidate that differs in anything else never shares a queue; matching stays linear.
/// pass: matching costs the sum of the two shape lists, not their product.
pub fn morph_pairs(a: &Slide, b: &Slide) -> Vec<(ShapeId, ShapeId)> {
let mut pairs: Vec<(ShapeId, ShapeId)> = Vec::new();
let mut used_a = vec![false; a.shapes.len()];
@@ -66,17 +34,17 @@ pub fn morph_pairs(a: &Slide, b: &Slide) -> Vec<(ShapeId, ShapeId)> {
Some(g) if t.trim().is_empty() => Some(MorphKey::Geom(s.kind_name(), g.to_string())),
_ => None,
};
// Forced names pair anything; ordinary names and the geometry fallback pair only the same
// object; the text pass keeps pairing shapes that share their text (#316).
let passes: [(&dyn Fn(&Shape, &str) -> Option<MorphKey>, bool); 4] = [(&forced, false), (&named, true), (&same_text, false), (&same_geom, true)];
for (key, strict) in passes {
let mut index = MatchIndex::new(strict);
let passes: [&dyn Fn(&Shape, &str) -> Option<MorphKey>; 4] = [&forced, &named, &same_text, &same_geom];
for key in passes {
// Unused shapes of `b` by key, in slide order: the front of each queue is the first unused
// match, which is the one a search through `b` would find.
let mut index: HashMap<MorphKey, VecDeque<usize>> = HashMap::new();
for (j, sb) in b.shapes.iter().enumerate() {
if used_b.get(j).copied().unwrap_or(true) {
continue;
}
if let Some(k) = key(sb, text_b.get(j).map_or("", String::as_str)) {
index.insert(k, j, sb);
index.entry(k).or_default().push_back(j);
}
}
if index.is_empty() {
@@ -87,7 +55,7 @@ pub fn morph_pairs(a: &Slide, b: &Slide) -> Vec<(ShapeId, ShapeId)> {
continue;
}
let Some(k) = key(sa, text_a.get(i).map_or("", String::as_str)) else { continue };
let Some(j) = index.take(k, sa, b, &used_b) else { continue };
let Some(j) = index.get_mut(&k).and_then(VecDeque::pop_front) else { continue };
let Some(sb) = b.shapes.get(j) else { continue };
if let Some(u) = used_a.get_mut(i) {
*u = true;
@@ -109,84 +77,6 @@ enum MorphKey {
Geom(&'static str, String),
}
/// The indexed `b` shapes for one pass. A strict pass can pair exact content, a geometry-only
/// change or a crop-only change, so it keeps three queues; any other difference is a different
/// content hash and can never be scanned.
enum MatchIndex {
Plain(HashMap<MorphKey, VecDeque<usize>>),
Strict {
exact: HashMap<(MorphKey, u64), VecDeque<usize>>,
geom: HashMap<(MorphKey, u64), VecDeque<usize>>,
crop: HashMap<(MorphKey, u64), VecDeque<usize>>,
},
}
impl MatchIndex {
fn new(strict: bool) -> Self {
if strict { Self::Strict { exact: HashMap::new(), geom: HashMap::new(), crop: HashMap::new() } } else { Self::Plain(HashMap::new()) }
}
fn is_empty(&self) -> bool {
match self {
Self::Plain(map) => map.is_empty(),
Self::Strict { exact, geom, crop } => exact.is_empty() && geom.is_empty() && crop.is_empty(),
}
}
fn insert(&mut self, k: MorphKey, j: usize, sb: &Shape) {
match self {
Self::Plain(map) => map.entry(k).or_default().push_back(j),
Self::Strict { exact, geom, crop } => {
exact.entry((k.clone(), content_hash(sb))).or_default().push_back(j);
if outlined(sb) {
geom.entry((k.clone(), geom_hash(sb))).or_default().push_back(j);
}
if picture(sb) {
crop.entry((k, crop_hash(sb))).or_default().push_back(j);
}
}
}
}
fn take(&mut self, k: MorphKey, sa: &Shape, b: &Slide, used: &[bool]) -> Option<usize> {
match self {
Self::Plain(map) => {
let q = map.get_mut(&k)?;
first_plain(q, used)
}
Self::Strict { exact, geom, crop } => {
let exact_key = (k.clone(), content_hash(sa));
let geom_key = outlined(sa).then(|| (k.clone(), geom_hash(sa)));
let crop_key = picture(sa).then(|| (k.clone(), crop_hash(sa)));
first(exact.get_mut(&exact_key), sa, b, used)
.into_iter()
.chain(geom_key.as_ref().and_then(|k| first(geom.get_mut(k), sa, b, used)))
.chain(crop_key.as_ref().and_then(|k| first(crop.get_mut(k), sa, b, used)))
.min()
}
}
}
}
/// The first candidate in a hash bucket that is actually the same object. Candidates already used
/// by an earlier shape are popped from the front and skipped, so a sibling queue never rescans
/// them; incompatible candidates stay in place for another source or pass.
fn first(q: Option<&mut VecDeque<usize>>, sa: &Shape, b: &Slide, used: &[bool]) -> Option<usize> {
let q = q?;
while q.front().is_some_and(|&j| used.get(j).copied().unwrap_or(true)) {
q.pop_front();
}
q.iter().copied().find(|&j| !used.get(j).copied().unwrap_or(true) && b.shapes.get(j).is_some_and(|sb| morph_match(sa, sb)))
}
/// The non-strict queues hold only matching keys, so the first unused candidate is the pick.
fn first_plain(q: &mut VecDeque<usize>, used: &[bool]) -> Option<usize> {
while q.front().is_some_and(|&j| used.get(j).copied().unwrap_or(true)) {
q.pop_front();
}
q.front().copied()
}
fn lerp(a: f64, b: f64, t: f64) -> f64 {
let v = a + (b - a) * t;
if v.is_finite() {
@@ -296,56 +186,7 @@ fn box_of(ctx: Option<&Ctx>, s: &Shape) -> Option<Xfrm> {
/// The content of a shape apart from what Morph interpolates (identity, box and fill).
fn content(s: &Shape) -> Shape {
let mut c = Shape { id: ShapeId(0), name: String::new(), xfrm: None, fill: None, ..s.clone() };
if matches!(c.kind, ShapeKind::Group { .. } | ShapeKind::Connector { .. }) {
let mut ids = HashMap::new();
let mut next = 0u32;
normalize_ids(&mut c, &mut next, &mut ids, 0);
remap_refs(&mut c, &ids, 0);
}
c
}
/// Gives a shape and its descendants deterministic ids in traversal order. `slide.duplicate`
/// reallocates every descendant id, so the duplicated group must compare equal to its source.
fn normalize_ids(s: &mut Shape, next: &mut u32, ids: &mut HashMap<ShapeId, ShapeId>, depth: u32) {
if depth > 64 {
return;
}
let old = s.id;
let new = ShapeId(*next);
*next += 1;
ids.insert(old, new);
s.id = new;
if let ShapeKind::Group { children, .. } = &mut s.kind {
for child in children {
normalize_ids(child, next, ids, depth + 1);
}
}
}
/// Rewrites a connector's endpoints through the normalized id map; a reference outside the walked
/// subtree (an external shape) becomes `ShapeId(0)`, as `reid` would leave it outside this group.
fn remap_refs(s: &mut Shape, ids: &HashMap<ShapeId, ShapeId>, depth: u32) {
if depth > 64 {
return;
}
match &mut s.kind {
ShapeKind::Group { children, .. } => {
for child in children {
remap_refs(child, ids, depth + 1);
}
}
ShapeKind::Connector { start, end } => {
if let Some((id, _)) = start {
*id = ids.get(id).copied().unwrap_or(ShapeId(0));
}
if let Some((id, _)) = end {
*id = ids.get(id).copied().unwrap_or(ShapeId(0));
}
}
_ => {}
}
Shape { id: ShapeId(0), name: String::new(), xfrm: None, fill: None, ..s.clone() }
}
/// Whether two shapes differ in their geometry only, and it is drawn as an outline (shapes,
@@ -376,13 +217,6 @@ fn recropped(a: &Shape, b: &Shape) -> bool {
matches!(a.kind, ShapeKind::Picture { .. }) && crop_of(a) != crop_of(b) && uncropped(a) == uncropped(b)
}
/// Whether two shapes are the same object for Morph matching: their content matches, or differs
/// only in a property Morph interpolates (a geometry or a picture's crop). A different text,
/// picture or kind is another object; it fades in place unless its name starts with `!!` (#2467).
fn morph_match(a: &Shape, b: &Shape) -> bool {
content(a) == content(b) || reshaped(a, b) || recropped(a, b)
}
/// The crop (left, top, right, bottom) of a picture morphing from box `xa` cropped by `ca` to box
/// `xb` cropped by `cb`, when its box is `x` at progress `t`: the whole image moves and scales
/// linearly between where it lies on either slide, and the crop is what of it `x` shows. Falls back
+10 -45
View File
@@ -117,7 +117,7 @@ fn custom_indices(pres: &Presentation, name: &str) -> Option<Vec<usize>> {
if order.is_empty() { None } else { Some(order) }
}
pub fn looping(pres: &Presentation) -> bool {
fn looping(pres: &Presentation) -> bool {
pres.show.loop_until_esc || pres.show.show_type == "kiosk"
}
@@ -236,54 +236,19 @@ impl ShowState {
}
fn next_index(&self, pres: &Presentation) -> Option<usize> {
self.visible_step(pres, self.slide, true, 1)
let order = self.visit(pres);
match order.iter().position(|&i| i == self.slide) {
Some(p) => order.get(p + 1).copied(),
None => order.iter().copied().find(|&i| i > self.slide),
}
}
fn prev_index(&self, pres: &Presentation) -> Option<usize> {
self.visible_step(pres, self.slide, false, 1)
}
/// Show the end screen without advancing a step (the pointer wheel past the last visible
/// slide). A later forward input leaves the show through the end screen's own handling.
pub fn end(&mut self) {
self.ended = true;
self.playing = false;
}
/// `steps` slides after (`forward`) or before `from` in this show's visible order (the custom
/// show or range, hidden slides skipped), without entering them; `None` when the order ends
/// first. The pointer wheel turns slides through this, so it skips hidden slides as ←/→ do.
pub fn visible_step(&self, pres: &Presentation, from: usize, forward: bool, steps: usize) -> Option<usize> {
self.visible_step_in(pres, from, forward, steps, false)
}
/// Like [`Self::visible_step`], but stops at the first/last visible slide instead of running
/// past it: one fast wheel gesture lands on the end slide rather than leaving the order.
pub fn visible_step_clamped(&self, pres: &Presentation, from: usize, forward: bool, steps: usize) -> Option<usize> {
self.visible_step_in(pres, from, forward, steps, true)
}
fn visible_step_in(&self, pres: &Presentation, from: usize, forward: bool, steps: usize, clamp: bool) -> Option<usize> {
if steps == 0 {
return None;
}
let order = self.visit(pres);
// A `from` that is not in the order (a hidden slide opened by number) reaches the
// nearest visible slide in the direction, which counts as the first step.
let (start, used) = match order.iter().position(|&i| i == from) {
Some(p) => (p, 0),
None if forward => (order.iter().position(|&i| i > from)?, 1),
None => (order.iter().rposition(|&i| i < from)?, 1),
};
let rest = steps.saturating_sub(used);
let q = if forward {
if clamp { start.saturating_add(rest).min(order.len().checked_sub(1)?) } else { start.checked_add(rest)? }
} else if clamp {
start.saturating_sub(rest)
} else {
start.checked_sub(rest)?
};
order.get(q).copied()
match order.iter().position(|&i| i == self.slide) {
Some(p) => p.checked_sub(1).and_then(|q| order.get(q).copied()),
None => order.iter().copied().rev().find(|&i| i < self.slide),
}
}
/// Click / → / Space: finish the playing step, else play the next step, else go to the next slide.
+11 -269
View File
@@ -4,8 +4,7 @@ use std::sync::Arc;
use deckcraft_model::anim::{ANIMATIONS, TRANSITIONS, TextBuild};
use deckcraft_model::{
AnimClass, AnimStart, Animation, ColorRef, CustomShow, Fill, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, Slide, SlideId, TextBody,
Transition, Xfrm,
AnimClass, AnimStart, Animation, ColorRef, CustomShow, Presentation, Rgba, Shape, ShapeId, Slide, SlideId, TextBody, Transition, Xfrm,
};
use crate::{
@@ -172,45 +171,6 @@ fn color_emphasis_tints() {
assert_eq!(tl.state(ShapeId(1), None, 1, 0.0).tint, Some(Rgba::rgb(255, 0, 0)));
}
#[test]
fn desaturate_grays_the_text_of_a_placeholder_or_a_shape_with_text() {
// #2740: text outside a `txBox` (a title placeholder, an autoshape with text) desaturates that
// text; the fill branch used to tint it instead, painting a gray box behind a placeholder that
// has no fill.
let title = Shape {
ph: Some(Placeholder { kind: PhType::Title, ..Default::default() }),
text: Some(TextBody::from_text("Title")),
..shape(1, "Title 1")
};
let labelled = Shape { text: Some(TextBody::from_text("Hi")), ..shape(2, "Box") };
let plain = shape(3, "Plain");
// Placeholders with nothing to gray: a picture placeholder with no body at all and a body
// placeholder holding an empty body.
let picture = Shape { ph: Some(Placeholder { kind: PhType::Picture, ..Default::default() }), ..shape(4, "Picture") };
let empty = Shape { ph: Some(Placeholder { kind: PhType::Body, ..Default::default() }), text: Some(TextBody::from_text("")), ..shape(5, "Body") };
let red = Rgba::rgb(255, 0, 0);
let filled = Shape { fill: Some(Fill::solid(ColorRef::rgb(red))), text: Some(TextBody::from_text("Hi")), ..shape(6, "Red box") };
let animations = [1, 2, 3, 4, 5, 6].map(|id| anim(id, AnimClass::Emphasis, "desaturate", AnimStart::OnClick)).to_vec();
let slide = Slide { shapes: vec![title, labelled, plain, picture, empty, filled], animations, ..Default::default() };
let tl = Timeline::new(&slide, W, H);
let done = |id| tl.state(ShapeId(id), None, 6, 0.0);
for id in [1, 2] {
let s = done(id);
assert!((s.text_desaturation - 1.0).abs() < 1e-9, "shape {id} grays its text: {s:?}");
assert!(s.tint.is_none(), "shape {id} keeps its fill: {s:?}");
}
// A shape with text and a solid fill of its own grays both.
let s = done(6);
assert!((s.text_desaturation - 1.0).abs() < 1e-9, "the filled shape grays its text: {s:?}");
assert!(s.tint.is_some_and(|c| c != red && c.r == c.g && c.g == c.b), "the filled shape grays its fill: {s:?}");
// A shape or placeholder with no text still desaturates its fill.
for id in [3, 4, 5] {
let s = done(id);
assert_eq!(s.text_desaturation, 0.0, "shape {id} has no text to gray: {s:?}");
assert!(s.tint.is_some(), "shape {id} with no text desaturates its fill: {s:?}");
}
}
#[test]
fn every_animation_evaluates_finite() {
for (id, _, class, _, _, opts) in ANIMATIONS {
@@ -615,161 +575,11 @@ fn morph_pairs_leaves_unrelated_text_boxes_alone() {
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
let xs: Vec<(&str, f64)> = f.shapes.iter().map(|(s, _)| (s.name.as_str(), s.xfrm.map_or(f64::NAN, |x| x.x))).collect();
assert_eq!(xs, [("TextBox 1", 0.0), ("TextBox 2", 400.0)]);
// Empty shapes of one kind and geometry still pair. A shared name is not enough when the
// text differs: the text boxes fade in place and only the rectangles pair (#2467).
// Empty shapes of one kind and geometry still pair, and a named text box keeps its partner.
a.shapes.push(shape(3, "Rect A"));
b.shapes.push(shape(4, "Rect B"));
b.shapes[0].name = "TextBox 1".into();
assert_eq!(morph_pairs(&a, &b), [(ShapeId(3), ShapeId(4))]);
}
#[test]
fn same_name_changed_text_fades_in_place() {
// #2467: the same name is not enough when the text changed; only `!!` forces a pair.
let p = deckcraft_model::defaults::new_presentation(None);
let tb = |id, x, text| Shape { xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)), text: Some(TextBody::from_text(text)), ..shape(id, "Text Box 1") };
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![tb(1, 0.0, "Before")];
b.shapes = vec![tb(2, 400.0, "After")];
assert!(morph_pairs(&a, &b).is_empty(), "a changed text must not pair");
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
let s = f.mix;
assert_eq!(f.shapes.len(), 2);
// The old box fades out where it was and the new one fades in where it is: no travel to 200.
assert_eq!(f.shapes[0].0.text.as_ref().map(|t| t.text()).as_deref(), Some("Before"));
assert!(f.shapes[0].1);
assert_eq!(f.shapes[0].0.xfrm.unwrap().x, 0.0);
assert_eq!(f.shapes[1].0.text.as_ref().map(|t| t.text()).as_deref(), Some("After"));
assert!(!f.shapes[1].1);
assert_eq!(f.shapes[1].0.xfrm.unwrap().x, 400.0);
assert!((f.opacity_of(f.shapes[0].0.id) - (1.0 - s)).abs() < 1e-9);
assert!((f.opacity_of(f.shapes[1].0.id) - s).abs() < 1e-9);
}
#[test]
fn same_name_skips_an_incompatible_candidate() {
// #2467 review: a `Box` that changed its text must not block a later empty `Box` ellipse
// from pairing with the empty `Box` rectangle of the old slide.
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![Shape { geom: deckcraft_model::Geom::preset("rect"), ..shape(1, "Box") }];
b.shapes = vec![
Shape { text: Some(TextBody::from_text("Hi")), ..shape(2, "Box") },
Shape { geom: deckcraft_model::Geom::preset("ellipse"), ..shape(3, "Box") },
];
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(3))], "the empty ellipse is the same object");
let p = deckcraft_model::defaults::new_presentation(None);
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
// One morphing shape (the ellipse) plus the text-bearing rectangle fading in.
assert_eq!(f.shapes.iter().filter(|(_, old)| !old).count(), 2);
assert_eq!(f.paths.len(), 1, "the rectangle turns into the ellipse");
assert_eq!(f.paths[0].from, deckcraft_model::Geom::preset("rect"));
}
#[test]
fn a_geometry_match_does_not_leave_the_candidate_for_another_shape() {
let geo = |id, g| Shape { geom: deckcraft_model::Geom::preset(g), ..shape(id, "Box") };
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![geo(1, "ellipse"), geo(2, "rect")];
b.shapes = vec![geo(3, "rect")];
let pairs = morph_pairs(&a, &b);
assert_eq!(pairs, [(ShapeId(1), ShapeId(3))], "the candidate is paired once");
let mut b_ids: Vec<_> = pairs.iter().map(|p| p.1).collect();
b_ids.sort();
b_ids.dedup();
assert_eq!(b_ids.len(), pairs.len(), "no b shape is used twice");
}
#[test]
fn same_name_pairs_a_picture_after_an_incompatible_same_media_candidate() {
let mut a = Slide::default();
let mut b = Slide::default();
let pic = |id, geom: &str, crop, x| Shape {
xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)),
geom: deckcraft_model::Geom::preset(geom),
kind: deckcraft_model::ShapeKind::Picture {
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(10), crop, ..Default::default() },
},
..shape(id, "Picture 1")
};
a.shapes = vec![pic(1, "rect", [0.0; 4], 0.0)];
b.shapes = vec![
pic(2, "ellipse", [0.5, 0.0, 0.0, 0.0], 200.0), // same name and media, but geometry and crop both changed
pic(3, "rect", [0.0; 4], 400.0), // the same object
];
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(3))], "the later compatible picture pairs");
}
#[test]
fn a_moved_group_on_a_duplicated_slide_still_pairs() {
// #2467 review: slide.duplicate gives every descendant a new id; the group is still the same
// object and must morph as one unit after the move.
let p = deckcraft_model::defaults::new_presentation(None);
let group = |root: u32, child: u32, x: f64| Shape {
id: ShapeId(root),
name: "Group 1".into(),
xfrm: Some(Xfrm::new(x, 100.0, 300.0, 200.0)),
kind: deckcraft_model::ShapeKind::Group {
children: vec![Shape { id: ShapeId(child), ..shape(child, "Child 1") }, Shape { id: ShapeId(child + 1), ..shape(child + 1, "Child 2") }],
child: Xfrm::new(0.0, 0.0, 1.0, 1.0),
},
..Default::default()
};
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![group(1, 2, 100.0)];
b.shapes = vec![group(10, 11, 250.0)];
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
assert_eq!(f.shapes.len(), 1, "the duplicated group morphs as one unit");
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(10))]);
}
#[test]
fn repeated_same_named_pictures_pair_in_slide_order() {
let n = 1000u32;
let pic = |id, x, crop| Shape {
xfrm: Some(Xfrm::new(x, 100.0, 100.0, 100.0)),
kind: deckcraft_model::ShapeKind::Picture {
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(1), crop, ..Default::default() },
},
..shape(id, "Logo")
};
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = (0..n).map(|i| pic(i + 1, f64::from(i) * 10.0, [0.0; 4])).collect();
b.shapes = (0..n).map(|i| pic(n + i + 1, f64::from(i) * 10.0, [0.1, 0.0, 0.0, 0.0])).collect();
let pairs = morph_pairs(&a, &b);
assert_eq!(pairs.len(), n as usize);
assert!(pairs.windows(2).all(|w| w[0].1.0 < w[1].1.0), "targets keep slide order");
assert_eq!(pairs[0], (ShapeId(1), ShapeId(n + 1)));
}
#[test]
fn same_name_pictures_with_different_images_fade_in_place() {
// #2467: the same name is not enough when the picture changed; the geometry fallback must not
// pair them either.
let p = deckcraft_model::defaults::new_presentation(None);
let pic = |id, media, x| Shape {
xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)),
kind: deckcraft_model::ShapeKind::Picture {
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(media), ..Default::default() },
},
..shape(id, "Picture 1")
};
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![pic(1, 10, 0.0)];
b.shapes = vec![pic(2, 11, 400.0)];
assert!(morph_pairs(&a, &b).is_empty(), "a different picture must not pair");
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
let s = f.mix;
assert_eq!(f.shapes.len(), 2);
assert_eq!(f.shapes[0].0.xfrm.unwrap().x, 0.0);
assert_eq!(f.shapes[1].0.xfrm.unwrap().x, 400.0);
assert!((f.opacity_of(f.shapes[0].0.id) - (1.0 - s)).abs() < 1e-9);
assert!((f.opacity_of(f.shapes[1].0.id) - s).abs() < 1e-9);
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2)), (ShapeId(3), ShapeId(4))]);
}
#[test]
@@ -798,7 +608,6 @@ fn morph_frame_morphs_a_picture_crop() {
let mut b = Slide::default();
a.shapes = vec![pic(1, [0.0, 0.0, 0.5, 0.0])];
b.shapes = vec![pic(2, [0.5, 0.0, 0.0, 0.0])];
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2))], "a crop change still pairs");
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
assert_eq!(f.shapes.len(), 1);
assert!(f.opacity.is_empty());
@@ -859,14 +668,12 @@ fn morph_frame_moves_blends_and_fades() {
}
#[test]
fn forced_name_cross_fades_changed_content() {
// #2467: `!!` forces a pair even when the text changed; the two cross-fade on the moving box.
fn morph_frame_cross_fades_changed_content() {
let p = deckcraft_model::defaults::new_presentation(None);
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![Shape { text: Some(TextBody::from_text("Before")), ..shape(1, "!!T") }];
b.shapes = vec![Shape { text: Some(TextBody::from_text("After")), ..shape(1, "!!T") }];
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(1))]);
a.shapes = vec![Shape { text: Some(TextBody::from_text("Before")), ..shape(1, "T") }];
b.shapes = vec![Shape { text: Some(TextBody::from_text("After")), ..shape(1, "T") }];
let f = morph_frame(&p, &a, &b, 0.25, &|_| false);
// The new text under the fading old one, both on the moving box.
assert_eq!(f.shapes.len(), 2);
@@ -882,8 +689,8 @@ fn morph_frame_lists_texts_for_words_and_characters() {
let p = deckcraft_model::defaults::new_presentation(None);
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![Shape { text: Some(TextBody::from_text("The Science")), ..shape(1, "!!T") }];
b.shapes = vec![Shape { text: Some(TextBody::from_text("Science rocks")), ..shape(1, "!!T") }];
a.shapes = vec![Shape { text: Some(TextBody::from_text("The Science")), ..shape(1, "T") }];
b.shapes = vec![Shape { text: Some(TextBody::from_text("Science rocks")), ..shape(1, "T") }];
for (option, want) in [("objects", None), ("words", Some(false)), ("characters", Some(true))] {
b.transition = Some(Transition { kind: "morph".into(), option: option.into(), ..Default::default() });
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
@@ -906,7 +713,6 @@ fn morph_frame_morphs_the_outline_of_a_changed_geometry() {
let geo = |s: Shape, g: &str| Shape { geom: deckcraft_model::Geom::preset(g), ..s };
a.shapes = vec![solid(geo(shape(1, "Form"), "ellipse"), 0)];
b.shapes = vec![solid(Shape { xfrm: Some(Xfrm::new(300.0, 100.0, 100.0, 100.0)), ..geo(shape(1, "Form"), "star5") }, 200)];
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(1))], "a geometry change still pairs");
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
// One shape: the new one, on the moving box, its colour blending and its outline listed to morph.
assert_eq!(f.shapes.len(), 1);
@@ -957,21 +763,6 @@ fn show_skips_hidden_slides() {
assert_eq!(s.goto(&p, 99), ShowAction::None);
}
#[test]
fn a_wheel_step_from_a_hidden_slide_counts_its_first_visible_neighbour() {
// A hidden slide opened by number is not in the show order; the nearest visible slide in the
// direction is the first step, and the rest of the notches still apply.
let mut p = pres(5);
Arc::make_mut(&mut p.slides[1]).hidden = true;
let s = ShowState::new(&p);
assert_eq!(s.visible_step_clamped(&p, 1, true, 2), Some(3));
assert_eq!(s.visible_step_clamped(&p, 1, false, 2), Some(0));
assert_eq!(s.visible_step(&p, 1, true, 2), Some(3));
// Clamped steps stop at the ends of the visible order.
assert_eq!(s.visible_step_clamped(&p, 4, true, 3), Some(4));
assert_eq!(s.visible_step_clamped(&p, 0, false, 3), Some(0));
}
#[test]
fn show_remembers_a_slide_was_reached_by_going_back() {
// #1531: the UI plays the left slide's transition reversed only for Back.
@@ -1310,7 +1101,6 @@ fn same_text_morphs_even_by_objects() {
let mut b = Slide::default();
a.shapes = vec![titled(1, 100.0, 60.0, "TEST")];
b.shapes = vec![titled(2, 40.0, 44.0, "TEST")];
assert_eq!(morph_pairs(&a, &b).len(), 1, "the shapes with the shared text pair");
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
assert_eq!(f.text.len(), 1, "the shared text morphs");
assert!(!f.text[0].chars);
@@ -1438,64 +1228,16 @@ fn morph_of_large_slides_stays_linear() {
// Text no shape on the other slide shares: every pass looks for a partner and finds none.
a.shapes = (0..n).map(|i| Shape { text: text(i, "a"), ..shape(i + 1, "") }).collect();
b.shapes = (0..n).map(|i| Shape { text: text(i, "b"), ..shape(n + i + 1, "") }).collect();
// One named pair at opposite ends with the same content.
// One named pair at opposite ends.
a.shapes[0].name = "Logo".into();
b.shapes[n as usize - 1].name = "Logo".into();
b.shapes[n as usize - 1].text = a.shapes[0].text.clone();
// No wall-clock bound (it would flake on a loaded runner): at this size a quadratic pairing
// takes minutes, so a regression shows as a test that hangs rather than a failed assertion.
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2 * n))]);
let p = deckcraft_model::defaults::new_presentation(None);
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
// Every other shape fades in place; the named pair has the same content and moves as one.
assert_eq!(f.shapes.len(), 2 * n as usize - 1);
}
#[test]
fn many_same_name_shapes_with_distinct_text_stay_linear() {
let n = 20_000u32;
let mut a = Slide::default();
let mut b = Slide::default();
// Every shape shares the name but no text: the strict name pass must look up one text key
// per shape, not scan all 20,000 same-name candidates.
a.shapes = (0..n).map(|i| Shape { text: Some(TextBody::from_text(&format!("a {i}"))), ..shape(i + 1, "Box") }).collect();
b.shapes = (0..n).map(|i| Shape { text: Some(TextBody::from_text(&format!("b {i}"))), ..shape(n + i + 1, "Box") }).collect();
assert!(morph_pairs(&a, &b).is_empty());
}
#[test]
fn negative_zero_content_still_pairs() {
let pic = |id, alpha| Shape {
kind: deckcraft_model::ShapeKind::Picture {
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(1), alpha: Some(alpha), ..Default::default() },
},
..shape(id, "Picture 1")
};
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![pic(1, -0.0)];
b.shapes = vec![pic(2, 0.0)];
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2))], "-0.0 and 0.0 are equal content");
}
#[test]
fn many_same_name_pictures_with_distinct_alpha_stay_linear() {
let n = 20_000u32;
let pic = |id, alpha, x| Shape {
xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)),
geom: deckcraft_model::Geom::preset("rect"),
kind: deckcraft_model::ShapeKind::Picture {
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(10), alpha: Some(alpha), ..Default::default() },
},
..shape(id, "Picture 1")
};
let mut a = Slide::default();
let mut b = Slide::default();
// Same name, media, geometry and crop; only the alpha differs, so no pair exists and the
// named and geometry passes must not scan all 20,000 candidates.
a.shapes = (0..n).map(|i| pic(i + 1, 0.5, 0.0)).collect();
b.shapes = (0..n).map(|i| pic(n + i + 1, 1.0, 400.0)).collect();
assert!(morph_pairs(&a, &b).is_empty());
// Every shape fades in place; the named pair differs in text, so it cross-fades as two.
assert_eq!(f.shapes.len(), 2 * n as usize);
}
#[test]
+21 -117
View File
@@ -1,6 +1,5 @@
//! A slide's animation sequence: click steps, effect start times and per-shape state over time.
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -106,15 +105,13 @@ pub struct Timeline {
groups: Vec<(ShapeId, usize, usize)>,
/// Lookups built with the timeline, so evaluating a shape or paragraph costs its own effects
/// rather than a scan of every effect, group and colour on the slide.
index: Arc<TimelineIndex>,
index: TimelineIndex,
}
#[derive(Clone, Debug, Default)]
struct TimelineIndex {
/// Effects in Animation Pane order by target shape and paragraph.
/// Effects (indices into `effects`, in order) by target shape and paragraph.
by_target: HashMap<(ShapeId, Option<usize>), Vec<usize>>,
/// Main-sequence media cues in start-time order, with pane order breaking ties.
media_by_step: HashMap<usize, Vec<EffectTiming>>,
/// Effects (indices into `effects`, in order) by target shape.
by_shape: HashMap<ShapeId, Vec<usize>>,
/// Owner paragraph of each member paragraph (the first group recorded wins).
@@ -131,15 +128,6 @@ impl TimelineIndex {
for (i, e) in effects.iter().enumerate() {
ix.by_target.entry((e.timing.shape, e.timing.paragraph)).or_default().push(i);
ix.by_shape.entry(e.timing.shape).or_default().push(i);
if e.timing.class == AnimClass::Media && e.timing.sequence == Sequence::Main {
ix.media_by_step.entry(e.timing.step).or_default().push(e.timing.clone());
}
}
for indices in ix.by_target.values_mut() {
indices.sort_by_key(|&i| effects.get(i).map(|effect| effect.timing.anim));
}
for cues in ix.media_by_step.values_mut() {
cues.sort_by(|a, b| a.start.total_cmp(&b.start));
}
for &(shape, member, owner) in groups {
ix.owner.entry((shape, member)).or_insert(owner);
@@ -279,8 +267,7 @@ impl Timeline {
};
let xf = xfrm_of(a.shape).or_else(|| shape.and_then(|s| s.xfrm)).unwrap_or(Xfrm::new(sw / 4.0, sh / 4.0, sw / 2.0, sh / 2.0));
let xf = sanitize_xfrm(xf, sw, sh);
let grays_own_fill = shape.is_some_and(|s| !s.text_box && matches!(s.fill, Some(Fill::Solid { .. })));
let spec = Arc::new(build_spec(a, xf, sw, sh, carries_text(shape), grays_own_fill, &resolve));
let spec = Arc::new(build_spec(a, xf, sw, sh, &resolve));
let dur = secs(a.duration_ms);
let delay = secs(a.delay_ms);
let until_next_click = a.repeat == u32::MAX;
@@ -372,7 +359,7 @@ impl Timeline {
};
tl.colors.push((id, c));
}
tl.index = Arc::new(TimelineIndex::build(&tl.effects, &tl.groups, &tl.colors));
tl.index = TimelineIndex::build(&tl.effects, &tl.groups, &tl.colors);
tl
}
@@ -395,13 +382,15 @@ impl Timeline {
/// Media effects (Play, Pause, Stop) of main step `step` that start after `from` and by `to`
/// seconds into it, in order: what a show running the step from `from` to `to` sets off.
pub fn media_cues(&self, step: usize, from: f64, to: f64) -> Vec<EffectTiming> {
let Some(cues) = self.index.media_by_step.get(&step) else { return Vec::new() };
if from.partial_cmp(&to) != Some(std::cmp::Ordering::Less) {
return Vec::new();
}
let first = cues.partition_point(|cue| cue.start <= from);
let past_last = cues.partition_point(|cue| cue.start <= to);
cues.get(first..past_last).unwrap_or_default().to_vec()
let mut v: Vec<EffectTiming> = self
.effects
.iter()
.map(|e| &e.timing)
.filter(|e| e.class == AnimClass::Media && e.sequence == Sequence::Main && e.step == step && e.start > from && e.start <= to)
.cloned()
.collect();
v.sort_by(|a, b| a.start.total_cmp(&b.start));
v
}
/// Total duration of the main sequence played without pauses.
@@ -503,27 +492,28 @@ impl Timeline {
stamps: &[StepStamp],
) -> AnimState {
let para = para.map(|p| self.index.owner.get(&(shape, p)).copied().unwrap_or(p));
let mine = self.index.by_target.get(&(shape, para)).map_or(&[][..], Vec::as_slice);
let mine = self.index.by_target.get(&(shape, para)).map_or(&[][..], Vec::as_slice).iter().filter_map(|&i| self.effects.get(i));
let base_color = self.index.color.get(&shape).copied().unwrap_or(Rgba::rgb(0x15, 0x60, 0x82));
let mut st = AnimState::default();
// Initial visibility comes from the first effect in the Animation Pane order.
if let Some(e0) = mine.first().and_then(|&i| self.effects.get(i))
let mut ordered: Vec<&Effect> = mine.collect();
ordered.sort_by_key(|e| e.timing.anim);
if let Some(e0) = ordered.first()
&& e0.timing.class == AnimClass::Entrance
{
st.visible = false;
}
// Then play in time order: main sequence first, then triggered sequences as they were clicked.
let mut ordered = Cow::Borrowed(mine);
if !stamps.is_empty() && mine.iter().filter_map(|&i| self.effects.get(i)).any(|effect| effect.timing.sequence != Sequence::Main) {
if !stamps.is_empty() {
let when = |e: &Effect| match e.timing.sequence {
Sequence::Main => 0,
Sequence::Trigger(tr) => {
stamps.iter().find(|s| s.trigger == tr && s.step == e.timing.step).map_or(u64::MAX, |s| s.at.saturating_add(1))
}
};
ordered.to_mut().sort_by_key(|&i| self.effects.get(i).map(|effect| (when(effect), effect.timing.anim)));
ordered.sort_by_key(|e| (when(e), e.timing.anim));
}
for e in ordered.iter().filter_map(|&i| self.effects.get(i)) {
for e in &ordered {
let (pstep, pt) = match e.timing.sequence {
Sequence::Main => (step, t),
Sequence::Trigger(tr) => triggers.iter().find(|p| p.trigger == tr).map(|p| (p.step, p.t)).unwrap_or((0, 0.0)),
@@ -613,23 +603,7 @@ fn shape_index(shapes: &[Shape]) -> HashMap<ShapeId, &Shape> {
out
}
/// Does the shape show text? A text box, or any shape whose text body has content (a title or body
/// placeholder, a field's saved value in a run, an autoshape holding text): Desaturate grays that
/// text, and tints the fill only if a shape other than a text box has a solid fill of its own
/// (#2740). A placeholder with no text has its fill tinted (there is no text to gray).
fn carries_text(shape: Option<&Shape>) -> bool {
shape.is_some_and(|s| s.text_box || s.text.as_ref().is_some_and(|t| !t.is_empty()))
}
fn build_spec(
a: &Animation,
xf: Xfrm,
sw: f64,
sh: f64,
has_text: bool,
grays_own_fill: bool,
resolve: &dyn Fn(&deckcraft_model::ColorRef) -> Rgba,
) -> EffectSpec {
fn build_spec(a: &Animation, xf: Xfrm, sw: f64, sh: f64, resolve: &dyn Fn(&deckcraft_model::ColorRef) -> Rgba) -> EffectSpec {
let effect = if a.class == AnimClass::Exit { exit_base(&a.effect).to_string() } else { a.effect.clone() };
let path = if a.class == AnimClass::Path { Some(motion_path(&a.effect, &a.option, a.path.as_deref())) } else { None };
EffectSpec {
@@ -643,78 +617,8 @@ fn build_spec(
amount: a.amount,
color: a.color.as_ref().map(resolve),
path,
has_text,
grays_own_fill,
xf,
slide_w: sw,
slide_h: sh,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn indexes_keep_pane_order_and_media_cue_boundaries() {
let shape = ShapeId(1);
let trigger = ShapeId(2);
let fade = Animation { shape, class: AnimClass::Entrance, effect: "fade".into(), duration_ms: 1000, ..Default::default() };
let play = Animation { shape, class: AnimClass::Media, effect: "play".into(), duration_ms: 1000, ..Default::default() };
let slide = Slide {
animations: vec![
Animation { trigger: Some(trigger), ..fade.clone() },
fade,
Animation { start: AnimStart::WithPrevious, ..play.clone() },
Animation { start: AnimStart::WithPrevious, delay_ms: 250, ..play.clone() },
Animation { start: AnimStart::WithPrevious, ..play.clone() },
Animation { trigger: Some(trigger), ..play.clone() },
play,
],
..Default::default()
};
let timeline = Timeline::new(&slide, 960.0, 540.0);
assert!(Arc::ptr_eq(&timeline.index, &timeline.clone().index));
let pane_order: Vec<_> = timeline.index.by_target[&(shape, None)].iter().map(|&i| timeline.effects[i].timing.anim).collect();
assert_eq!(pane_order, (0..7).collect::<Vec<_>>());
assert_eq!(timeline.index.media_by_step[&0].iter().map(|cue| cue.anim).collect::<Vec<_>>(), [2, 4, 3]);
let cues = |step, from, to| timeline.media_cues(step, from, to).into_iter().map(|cue| cue.anim).collect::<Vec<_>>();
assert_eq!(cues(0, f64::NEG_INFINITY, 0.0), [2, 4]);
assert_eq!(cues(0, 0.0, 0.25), [3]);
assert!(cues(0, 0.25, f64::INFINITY).is_empty());
assert!(cues(0, f64::NAN, 1.0).is_empty());
assert_eq!(cues(1, f64::NEG_INFINITY, f64::INFINITY), [6]);
}
#[test]
fn playback_follows_pane_order_and_the_order_triggers_were_clicked() {
let shape = ShapeId(1);
let (first_trigger, second_trigger) = (ShapeId(2), ShapeId(3));
let fade = Animation { shape, effect: "fade".into(), duration_ms: 1000, ..Default::default() };
let slide = Slide {
animations: vec![
Animation { class: AnimClass::Exit, trigger: Some(first_trigger), ..fade.clone() },
Animation { class: AnimClass::Entrance, trigger: Some(second_trigger), ..fade.clone() },
Animation { class: AnimClass::Entrance, ..fade },
],
..Default::default()
};
let timeline = Timeline::new(&slide, 960.0, 540.0);
// The first effect in the Animation Pane is an exit, so the shape starts out visible even though
// the main sequence, which the index lists first, enters it.
assert!(timeline.state_at(shape, None, 0.0).visible);
let entering = timeline.state_at(shape, None, 0.5);
assert!(entering.visible && entering.opacity > 0.0 && entering.opacity < 1.0);
// Both triggered steps are played: the click that came later decides if the shape stays.
let played = [TriggerPlay { trigger: first_trigger, step: 1, t: 0.0 }, TriggerPlay { trigger: second_trigger, step: 1, t: 0.0 }];
let visible_after = |first_click, second_click| {
let stamps =
[StepStamp { trigger: first_trigger, step: 0, at: first_click }, StepStamp { trigger: second_trigger, step: 0, at: second_click }];
timeline.state_ordered(shape, None, 1, 0.0, &played, &stamps).visible
};
assert!(visible_after(0, 1));
assert!(!visible_after(1, 0));
}
}
+5 -7
View File
@@ -39,14 +39,12 @@ mod tests {
#[test]
fn hsl_roundtrip() {
for color in [Rgba::rgb(10, 200, 30), Rgba::rgb(255, 0, 0), Rgba::rgb(128, 128, 128), Rgba::rgb(21, 96, 130)] {
let (hue, saturation, lightness) = color.to_hsl();
let converted = Rgba::from_hsl(hue, saturation, lightness, 255);
for c in [Rgba::rgb(10, 200, 30), Rgba::rgb(255, 0, 0), Rgba::rgb(128, 128, 128), Rgba::rgb(21, 96, 130)] {
let (h, s, l) = c.to_hsl();
let d = Rgba::from_hsl(h, s, l, 255);
assert!(
(i32::from(converted.r) - i32::from(color.r)).abs() <= 1
&& (i32::from(converted.g) - i32::from(color.g)).abs() <= 1
&& (i32::from(converted.b) - i32::from(color.b)).abs() <= 1,
"{color:?} {converted:?}"
(d.r as i32 - c.r as i32).abs() <= 1 && (d.g as i32 - c.g as i32).abs() <= 1 && (d.b as i32 - c.b as i32).abs() <= 1,
"{c:?} {d:?}"
);
}
}
-4
View File
@@ -10,8 +10,6 @@ workspace = true
[dependencies]
craft-mime = { workspace = true }
# Tells EMF from WMF when a picture is inserted (#2392).
craft-metafile = { workspace = true }
deckcraft-geom = { workspace = true }
deckcraft-color = { workspace = true }
deckcraft-model = { workspace = true }
@@ -33,9 +31,7 @@ chrono = { workspace = true }
[dev-dependencies]
deckcraft-anim = { workspace = true }
memory-stats = "1.2.0"
zip = { workspace = true }
craft-metafile = { workspace = true, features = ["write"] }
# The browser clock for comment timestamps (wasm has no std::time::SystemTime).
[target.'cfg(target_arch = "wasm32")'.dependencies]
+3 -49
View File
@@ -26,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Animation",
["Animations", "Advanced Animation"],
None,
"{effect, class?, option?, path?: [[x,y],…] or OOXML string, closed?: bool, start?: onClick|withPrevious|afterPrevious, duration?: ms, delay?: ms, smoothStart?: number (0–1), smoothEnd?: number (0–1), bounceEnd?: number (0–1), ids?} → {count, path?}",
"{effect, class?, option?, path?: [[x,y],…] or OOXML string, closed?: bool, start?: onClick|withPrevious|afterPrevious, duration?: ms, delay?: ms, ids?} → {count, path?}",
has_selection,
add
),
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Timing",
["Animations", "Timing"],
None,
"{index? (else selected shapes), start?: onClick|withPrevious|afterPrevious, duration?: ms, delay?: ms, repeat?: n, rewind?: bool, trigger?: shape id | null, smoothStart?: number (0–1), smoothEnd?: number (0–1), bounceEnd?: number (0–1)}",
"{index? (else selected shapes), start?: onClick|withPrevious|afterPrevious, duration?: ms, delay?: ms, repeat?: n, rewind?: bool, trigger?: shape id | null}",
has_slide,
timing
),
@@ -314,20 +314,9 @@ fn slide_extent(s: &mut Session) -> Result<(f64, f64)> {
Ok((size.width, size.height))
}
fn easing_fraction(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
p.get(key)
.map(|value| value.as_f64().filter(|v| (0.0..=1.0).contains(v)).ok_or_else(|| bad(cmd, format!("`{key}` must be a number between 0 and 1"))))
.transpose()
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
let ids = targets(s, p)?;
let a = Animation {
smooth_start: easing_fraction(p, "smoothStart", "animation.add")?.unwrap_or_default(),
smooth_end: easing_fraction(p, "smoothEnd", "animation.add")?.unwrap_or_default(),
bounce_end: easing_fraction(p, "bounceEnd", "animation.add")?.unwrap_or_default(),
..build(p, slide_extent(s)?)?
};
let a = build(p, slide_extent(s)?)?;
let path = a.path.clone();
s.edit(|doc, sel| {
let sl = Arc::make_mut(doc.slides.get_mut(sel.slide).ok_or_else(|| bad("animation.add", "no slide"))?);
@@ -404,9 +393,6 @@ fn timing(s: &mut Session, p: &Value) -> Result<Value> {
let repeat = p.get("repeat").and_then(Value::as_u64).map(|v| v.min(u32::MAX as u64) as u32);
let rewind = bool_param(p, "rewind");
let trigger = p.get("trigger").map(|v| v.as_u64().and_then(|x| u32::try_from(x).ok()).map(deckcraft_model::ShapeId));
let smooth_start = easing_fraction(p, "smoothStart", "animation.timing")?;
let smooth_end = easing_fraction(p, "smoothEnd", "animation.timing")?;
let bounce_end = easing_fraction(p, "bounceEnd", "animation.timing")?;
each_target(s, p, |a| {
if let Some(x) = start {
a.start = x;
@@ -426,15 +412,6 @@ fn timing(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(t) = trigger {
a.trigger = t;
}
if let Some(x) = smooth_start {
a.smooth_start = x;
}
if let Some(x) = smooth_end {
a.smooth_end = x;
}
if let Some(x) = bounce_end {
a.bounce_end = x;
}
})
}
@@ -575,29 +552,6 @@ mod tests {
use super::*;
#[test]
fn add_and_timing_set_animation_easing_without_resetting_omitted_values() {
let mut s = Session::with_new();
let id = shape(&mut s);
s.execute("animation.add", &json!({"effect": "float", "ids": [id], "smoothStart": 0.25, "smoothEnd": 0.5, "bounceEnd": 0.1})).unwrap();
let anims = s.execute("animation.get", &json!({})).unwrap();
assert_eq!(anims[0]["smoothStart"], 0.25);
assert_eq!(anims[0]["smoothEnd"], 0.5);
assert_eq!(anims[0]["bounceEnd"], 0.1);
s.execute("animation.timing", &json!({"index": 0, "smoothEnd": 0, "bounceEnd": 0.75})).unwrap();
assert!(s.execute("animation.timing", &json!({"index": 0, "smoothStart": 0.5, "bounceEnd": 1.1})).is_err());
let anims = s.execute("animation.get", &json!({})).unwrap();
assert_eq!(anims[0]["smoothStart"], 0.25);
assert_eq!(anims[0]["smoothEnd"], 0.0);
assert_eq!(anims[0]["bounceEnd"], 0.75);
let bytes = deckcraft_pptx::export(&s.doc().unwrap().doc).unwrap();
let reopened = deckcraft_pptx::import(&bytes).unwrap();
let effect = &reopened.slides[0].animations[0];
assert_eq!((effect.smooth_start, effect.smooth_end, effect.bounce_end), (0.25, 0.0, 0.75));
}
#[test]
fn an_armed_animation_painter_can_disarm_without_a_source_but_cannot_rearm() -> crate::Result<()> {
let mut s = Session::with_new();
+4 -25
View File
@@ -37,7 +37,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|txt|rtf|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!(noundo "file.export", "Export…", ["File"], None, "{path, format?: png|jpeg|pptx|deckcraft|outline|rtf|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",
@@ -390,12 +390,11 @@ fn report_damage(s: &mut Session, damaged: &Damage) -> Result<()> {
Ok(())
}
/// Encode the presentation in `format` (`deckcraft`, `pptx`, `potx`, `ppsx`, `outline`, `txt`, `pdf`, `gif`).
/// Encode the presentation in `format` (`deckcraft`, `pptx`, `potx`, `ppsx`, `outline`, `pdf`, `gif`).
pub fn save_bytes(doc: &Presentation, format: &str) -> Result<Vec<u8>> {
match format {
f @ ("pptx" | "potx" | "ppsx") => deckcraft_pptx::export_as(doc, f).map_err(|e| EngineError::Other(e.to_string())),
"outline" => Ok(deckcraft_format::slides_to_outline(doc).into_bytes()),
"txt" => Ok(outline_txt_bytes(&deckcraft_format::slides_to_outline(doc))),
"outline" | "txt" => Ok(deckcraft_format::slides_to_outline(doc).into_bytes()),
"rtf" => Ok(deckcraft_format::rtf::slides_to_rtf(doc).into_bytes()),
"pdf" => deckcraft_pdf::export(doc, &Default::default()).map_err(|e| EngineError::Other(e.to_string())),
"gif" => gif_bytes(doc, &Value::Null),
@@ -405,16 +404,6 @@ pub fn save_bytes(doc: &Presentation, format: &str) -> Result<Vec<u8>> {
}
}
/// The `.txt` outline bytes: CRLF for the reference app, without doubling a CR that is
/// already in the text. A lone CR is an in-paragraph character, not a line break, so it becomes
/// a space (as `slides_to_outline` does for a vertical tab): writing it as CRLF would split the
/// paragraph into an unindented line on re-import. `TextBody::from_text` normalizes CR and CRLF
/// (`text.rs:739`), but imported text can still carry one, so normalize before adding CRLF.
/// Crate-visible so the regression test can feed it a CRLF string directly.
pub(crate) fn outline_txt_bytes(text: &str) -> Vec<u8> {
text.replace("\r\n", "\n").replace('\r', " ").replace('\n', "\r\n").into_bytes()
}
/// Paper sizes for notes and handouts, for the UI's Print page.
pub use deckcraft_pdf::{PAPERS, paper_size};
@@ -526,12 +515,6 @@ fn same_save_format(path: &str, path_format: &str, format: &str) -> bool {
|| matches!((path_format, format), ("jpeg", "jpg") | ("jpg", "jpeg"))
}
/// `.txt` needs CRLF for the reference app's outline importer; every other outline target
/// keeps LF.
fn outline_format<'a>(path: &str, format: &'a str) -> &'a str {
if format == "outline" && path.to_ascii_lowercase().ends_with(".txt") { "txt" } else { format }
}
/// Animated GIF bytes for `doc` with the options in `p` (see [`crate::gif_export::GifOptions::from_params`]).
pub fn gif_bytes(doc: &Presentation, p: &Value) -> Result<Vec<u8>> {
Ok(crate::gif_export::encode(doc, &crate::gif_export::GifOptions::from_params(p)?)?.bytes)
@@ -553,9 +536,7 @@ pub fn format_for_path(path: &str) -> &'static str {
"pdf"
} else if l.ends_with(".gif") {
"gif"
} else if l.ends_with(".txt") {
"txt"
} else if l.ends_with(".md") {
} else if l.ends_with(".txt") || l.ends_with(".md") {
"outline"
} else if l.ends_with(".rtf") {
"rtf"
@@ -590,7 +571,6 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
"{path}: format `{format}` does not match the file type; save as {path_format} or choose a matching extension"
)));
}
let format = outline_format(&path, format);
let bytes = save_bytes(&s.doc()?.doc, format)?;
write_file(&path, &bytes)?;
mark_saved(s, Some(path.clone()))?;
@@ -681,7 +661,6 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
Some(f) => f.to_string(),
None => writable_format(&path)?.to_string(),
};
let format = outline_format(&path, &format).to_string();
let st = s.doc()?;
let scale = finite_scale(f64_or(p, "scale", 2.0));
let transparent = bool_or(p, "transparentBackground", false);
+2 -10
View File
@@ -287,16 +287,8 @@ fn current_run(s: &Session) -> RunProps {
}
None => {
let Some(sh) = st.selected_shapes().first().map(|x| (*x).clone()) else { return RunProps::default() };
// A selected table reads its first selected cell (the whole table without a range: its first cell).
let body = match &sh.kind {
deckcraft_model::ShapeKind::Table(tb) => {
let first = super::table::selected_range(st.selection.cells, sh.id, tb).map_or((0, 0), |(a, _)| a);
tb.cell(first.0, first.1).map(|c| &c.text)
}
_ => sh.text.as_ref(),
};
let para = body.and_then(|t| t.paragraphs.first().cloned()).unwrap_or_default();
let rp = para.runs.first().map(|r| r.props.clone()).unwrap_or_else(|| para.end_props.clone());
let para = sh.text.as_ref().and_then(|t| t.paragraphs.first().cloned()).unwrap_or_default();
let rp = para.runs.first().map(|r| r.props.clone()).unwrap_or_default();
(sh, para, rp)
}
};
-7
View File
@@ -344,13 +344,6 @@ fn album_items(p: &Value) -> Result<Vec<AlbumItem>> {
}
fn image_px(bytes: &[u8]) -> (f64, f64) {
// A metafile's frame gives its aspect; the raster reader can't size it.
if craft_metafile::is_metafile(bytes)
&& let Ok(pic) = craft_metafile::parse(bytes)
&& pic.has_size()
{
return (f64::from(pic.width), f64::from(pic.height));
}
image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.ok()
-6
View File
@@ -33,12 +33,6 @@ pub fn content_type(name: &str, bytes: &[u8]) -> &'static str {
"image/bmp"
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
"image/tiff"
} else if let Some(kind) = craft_metafile::sniff(bytes) {
// The MIME types the PPTX writer saves as `.emf` / `.wmf` parts (#2392).
match kind {
craft_metafile::Kind::Emf => "image/x-emf",
craft_metafile::Kind::Wmf => "image/x-wmf",
}
} else if bytes.starts_with(b"fLaC") {
"audio/flac"
} else if bytes.starts_with(b"OggS") {
+14 -365
View File
@@ -247,133 +247,25 @@ fn neighbour(s: &mut Session, p: &Value, forward: bool) -> Result<Value> {
}
/// Whether alternative text is a picture's file name and nothing else: one word ending in a
/// picture file's extension (`IMG_2041.png`, `C:\\photos\\a.JPG`), a spaced name with a file
/// name's shape (`Screenshot 2024 at 10.00.png`), or the exact name of the file the picture
/// came from, spaces and all.
const PICTURE_EXTENSIONS: [&str; 15] = ["png", "jpg", "jpeg", "jpe", "gif", "bmp", "tif", "tiff", "webp", "svg", "emf", "wmf", "heic", "avif", "ico"];
/// Containers Insert Video and Insert Audio take, so a clip's default alt text (its file name,
/// `clip.mp4`) is reported the way a picture's is (#2549). The MP4 family is wider than `.mp4` and
/// `.mov`: `content_type` types any `ftyp` file as video/mp4 unless it is `.m4a`, `.m4b` or `.mov`.
/// The list can't name every file the commands take — bytes that probe as video pass under any
/// extension — and the picture list has the same kind of gap (`.jfif`), which is a separate issue.
const MEDIA_EXTENSIONS: [&str; 28] = [
"mp4", "m4v", "m4p", "mov", "3gp", "3g2", "f4v", "ogv", "webm", "mkv", "avi", "wmv", "asf", "mp3", "m4a", "m4b", "aac", "wav", "aif", "aiff",
"flac", "ogg", "oga", "opus", "wma", "mka", "weba", "caf",
];
/// picture file's extension (`IMG_2041.png`, `C:\\photos\\a.JPG`), or the name of the file the
/// picture came from, which may have spaces (`Screenshot 2024 at 10.00.png`).
fn is_file_name(alt: &str, file: Option<&str>) -> bool {
is_file_name_with(alt, file, &PICTURE_EXTENSIONS, &[&PICTURE_EXTENSIONS])
}
/// Whether a clip's alt text is its media file's name. Media shapes keep the picture rule as well,
/// so an image file name in their alt text stays reported, and a description inside a clip's alt
/// text may name an image as well as the clip.
fn is_media_file_name(alt: &str, file: Option<&str>) -> bool {
is_file_name_with(alt, file, &MEDIA_EXTENSIONS, &[&PICTURE_EXTENSIONS, &MEDIA_EXTENSIONS])
}
/// `extensions` are the containers that may end the alt text; `mentioned` are the lists a file
/// named inside a longer description may end in, which is wider for a clip's alt text.
fn is_file_name_with(alt: &str, file: Option<&str>, extensions: &[&str], mentioned: &[&[&str]]) -> bool {
const PICTURE_EXTENSIONS: [&str; 15] =
["png", "jpg", "jpeg", "jpe", "gif", "bmp", "tif", "tiff", "webp", "svg", "emf", "wmf", "heic", "avif", "ico"];
let alt = alt.trim();
if alt.is_empty() {
return false;
}
if file.is_some_and(|f| f.trim().eq_ignore_ascii_case(alt)) {
return true;
}
let Some((stem, ext)) = alt.rsplit_once('.') else {
return false;
};
if stem.is_empty() || !extensions.iter().any(|e| ext.eq_ignore_ascii_case(e)) {
return false;
}
!alt.contains(char::is_whitespace) || is_spaced_file_name(stem, mentioned)
let one_word = !alt.is_empty() && !alt.contains(char::is_whitespace);
(one_word && alt.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && PICTURE_EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))))
|| file.is_some_and(|f| !alt.is_empty() && f.trim().eq_ignore_ascii_case(alt))
}
/// Whether a stem that ends in a known file extension has a file name's shape rather than a
/// sentence's. A path is a name even when a folder has spaces. Otherwise a stem of three words or
/// fewer is a name, and a longer stem must have at least two name parts: digits, `_`, `-`, an
/// internal `.`, an uppercase after the first letter, or a multi-letter all-caps word.
fn is_spaced_file_name(stem: &str, mentioned: &[&[&str]]) -> bool {
// A path is a file name even when a folder has spaces; a slash inside a descriptive clause is
// not, so the clause check still follows for non-path stems.
if is_path_shaped(stem) {
return true;
}
// A description that mentions a file inside a sentence is prose, not a file name.
if mentions_a_file(stem, mentioned) {
return false;
}
// Clause punctuation introduces a description: "A red square, from IMG_2041.png".
if stem.contains([',', ';', ':', '!', '?']) {
return false;
}
let words: Vec<&str> = stem.split_whitespace().collect();
if words.len() <= 3 {
return !words.is_empty();
}
words.iter().filter(|word| is_name_part(word)).count() >= 2
}
/// Whether the stem starts like a path: a root (`/`, `\`, `~`), a drive letter, or one unspaced
/// first segment followed by a separator. `"A red square, from photos/IMG_2041"` is a clause, not a
/// path, while `C:\Users\Jane, Doe\...` and `photos/IMG 2041` are paths.
fn is_path_shaped(stem: &str) -> bool {
let Some(at) = stem.find(['/', '\\']) else {
return false;
};
let head = &stem[..at];
head.is_empty()
|| head == "~"
|| (head.len() == 2 && head.as_bytes()[0].is_ascii_alphabetic() && head.as_bytes()[1] == b':')
|| !head.contains(char::is_whitespace)
}
/// Whether a word names a file inside a longer description: a known extension follows its last
/// dot (`IMG_2041.png`). A trailing dot (`Dr.`) has no extension after it.
fn mentions_a_file(stem: &str, extension_lists: &[&[&str]]) -> bool {
stem.split_whitespace().any(|word| {
let Some((before, ext)) = word.rsplit_once('.') else {
return false;
};
!before.is_empty() && extension_lists.iter().any(|list| list.iter().any(|e| ext.eq_ignore_ascii_case(e)))
})
}
/// Whether one word looks like part of a file name rather than ordinary prose: a digit, a
/// separator, an internal dot, an uppercase after the first letter, or a multi-letter all-caps word.
fn is_name_part(word: &str) -> bool {
let mut chars = word.chars();
let Some(first) = chars.next() else {
return false;
};
let internal_dot = word.split('.').count() > 1 && !word.starts_with('.') && !word.ends_with('.');
word.chars().any(|c| c.is_ascii_digit() || matches!(c, '_' | '-'))
|| internal_dot
|| chars.any(char::is_uppercase)
|| (word.len() > 1 && first.is_uppercase() && word.chars().all(|c| c.is_uppercase() || c.is_ascii_digit()))
}
/// The name of the file a shape's picture or clip came from, if it has one.
fn shape_file<'a>(doc: &'a deckcraft_model::Presentation, sh: &deckcraft_model::Shape) -> Option<&'a str> {
/// The name of the file a picture shape's picture came from, if it has one.
fn picture_file<'a>(doc: &'a deckcraft_model::Presentation, sh: &deckcraft_model::Shape) -> Option<&'a str> {
match &sh.kind {
deckcraft_model::ShapeKind::Picture { fill } => doc.media(fill.media).map(|m| m.name.as_str()),
deckcraft_model::ShapeKind::Media(clip) => doc.media(clip.media).map(|m| m.name.as_str()),
_ => None,
}
}
/// Whether the alt text says nothing a screen reader can use: the name of the file behind the
/// shape. Insert Picture and Insert Video/Audio name a shape after its file (#2224); a clip's alt
/// text is checked for media containers as well, since Insert Video/Audio uses that file name
/// (#2549). A picture's own file name and image names stay reported by the picture rule.
fn alt_is_file_name(doc: &deckcraft_model::Presentation, sh: &deckcraft_model::Shape) -> bool {
let file = shape_file(doc, sh);
is_file_name(&sh.descr, file) || (matches!(sh.kind, deckcraft_model::ShapeKind::Media(_)) && is_media_file_name(&sh.descr, file))
}
fn accessibility(s: &mut Session, _p: &Value) -> Result<Value> {
let st = s.doc()?;
let mut out = vec![];
@@ -391,9 +283,9 @@ fn accessibility(s: &mut Session, _p: &Value) -> Result<Value> {
);
if sh.descr.trim().is_empty() && !sh.decorative && (needs_alt || crate::icons::is_inserted_icon(sh)) {
out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Missing alternative text"}));
} else if needs_alt && !sh.decorative && alt_is_file_name(&st.doc, sh) {
// Insert Picture and Insert Video/Audio name a shape after its file, which is all
// a screen reader would then say (#2224, #2549).
} else if needs_alt && !sh.decorative && is_file_name(&sh.descr, picture_file(&st.doc, sh)) {
// Insert Picture names a picture after its file, which is all a screen reader
// would then say (#2224).
out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Alternative text is a file name"}));
}
});
@@ -1210,251 +1102,8 @@ mod accessibility_contrast_tests {
assert!(!is_file_name("Version 2.0", None), "a version number is not a picture's extension");
assert!(!is_file_name(".png", None));
assert!(!is_file_name("A red square, from IMG_2041.png", None));
// A file name with spaces counts by its shape, with or without the picture's own name.
// The picture's own file name counts, spaces and all.
assert!(is_file_name("Screenshot 2024 at 10.00.png", Some("Screenshot 2024 at 10.00.png")));
assert!(is_file_name("Screenshot 2024 at 10.00.png", None), "a spaced name is recognised after the media item is renamed");
}
fn test_png() -> Vec<u8> {
vec![
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 8, 0, 0, 0, 8, 8, 2, 0, 0, 0, 75, 109, 41, 220, 0, 0, 0, 17, 73,
68, 65, 84, 120, 156, 99, 184, 163, 161, 129, 21, 49, 12, 45, 9, 0, 123, 123, 75, 1, 251, 162, 81, 240, 0, 0, 0, 0, 73, 69, 78, 68, 174,
66, 96, 130,
]
}
fn file_name_issue_count(s: &mut Session) -> usize {
s.execute("review.accessibility", &json!({}))
.unwrap()
.as_array()
.unwrap()
.iter()
.filter(|issue| issue["issue"] == "Alternative text is a file name")
.count()
}
fn pptx_round_trip(s: &mut Session) {
let saved = s.execute("file.saveBytes", &json!({"format": "pptx"})).unwrap();
s.execute("file.openBytes", &json!({"name": "deck.pptx", "data": saved["data"]})).unwrap();
}
#[test]
fn spaced_file_names_are_recognised_by_shape() {
for name in [
"Screenshot 2024 at 10.00.png",
"rough draft preview.png",
"Screen Shot 2024-11-30 at 09.41.12.png",
r"C:\Users\Me\My Pictures\holiday.png",
r"C:\Users\Jane, Doe\Pictures\holiday.png",
] {
assert!(is_file_name(name, None), "{name:?} is a file name");
}
assert!(
is_file_name("Screenshot 2024 at 10.00.png", Some("image1.png")),
"the shape rule works when the media item was renamed by the round trip"
);
for text in [
"A red square, from IMG_2041.png",
"A red square, from photos/IMG_2041.png",
"A red square from IMG_2041.png",
"A Red Square From IMG_2041.png",
"A comparison of IMG_2041.png and IMG_2042.png",
"Portrait of Dr. A. Smith.png",
"Three markers in the upper corner of caption alt.png",
"The chart shows revenue in 2024.png",
"Version 2.0",
".png",
"A red square",
] {
assert!(!is_file_name(text, None), "{text:?} is not a file name");
}
for name in ["IMG_2041.png", "photo.JPEG", r"C:\Users\me\Pictures\holiday.png"] {
assert!(is_file_name(name, None), "{name:?} is still a file name");
}
assert!(is_file_name("Screenshot 2024 at 10.00.png", Some("Screenshot 2024 at 10.00.png")));
}
#[test]
fn a_spaced_picture_file_name_is_still_reported_after_a_pptx_round_trip() {
let png = test_png();
let mut s = Session::with_new();
s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "Screenshot 2024 at 10.00.png"})).unwrap();
assert_eq!(file_name_issue_count(&mut s), 1, "reported before the save");
pptx_round_trip(&mut s);
let doc = s.execute("document.inspect", &json!({})).unwrap();
assert!(doc["media"].as_array().unwrap().iter().any(|m| m["name"] == "image1.png"), "the round trip renamed the media item: {doc}");
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
assert!(
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == "Screenshot 2024 at 10.00.png"),
"the alt text survives the round trip: {slide}"
);
assert_eq!(file_name_issue_count(&mut s), 1, "reported after the save and reopen");
}
#[test]
fn a_description_that_mentions_a_file_is_not_reported_after_a_pptx_round_trip() {
let png = test_png();
let mut s = Session::with_new();
let id = s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "IMG_2041.png"})).unwrap()["id"].clone();
s.execute("shape.altText", &json!({"text": "A red square, from IMG_2041.png", "ids": [id]})).unwrap();
assert_eq!(file_name_issue_count(&mut s), 0, "a description that mentions a file is clear");
pptx_round_trip(&mut s);
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
assert!(
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == "A red square, from IMG_2041.png"),
"the description survives the round trip: {slide}"
);
assert_eq!(file_name_issue_count(&mut s), 0, "the description stays clear after the round trip");
}
#[test]
fn a_decorative_picture_with_a_spaced_file_name_is_not_reported_after_a_pptx_round_trip() {
let png = test_png();
let mut s = Session::with_new();
let id =
s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "Screenshot 2024 at 10.00.png"})).unwrap()["id"]
.clone();
s.execute("shape.altText", &json!({"text": "Screenshot 2024 at 10.00.png", "decorative": true, "ids": [id]})).unwrap();
assert_eq!(file_name_issue_count(&mut s), 0, "a decorative picture is exempt");
pptx_round_trip(&mut s);
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
assert!(
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == "Screenshot 2024 at 10.00.png"),
"the alt text survives, so only decorative suppresses the finding: {slide}"
);
assert_eq!(file_name_issue_count(&mut s), 0, "the decorative picture stays exempt after the round trip");
}
#[test]
fn one_word_names_and_paths_are_still_reported_after_a_pptx_round_trip() {
let png = test_png();
let mut s = Session::with_new();
let id = s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "IMG_2041.png"})).unwrap()["id"].clone();
assert_eq!(file_name_issue_count(&mut s), 1, "the inserted file name is reported");
s.execute("shape.altText", &json!({"text": r"C:\Users\me\Pictures\holiday.png", "ids": [id]})).unwrap();
assert_eq!(file_name_issue_count(&mut s), 1, "a one-word path is reported");
pptx_round_trip(&mut s);
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
assert!(
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == r"C:\Users\me\Pictures\holiday.png"),
"the path survives the round trip: {slide}"
);
assert_eq!(file_name_issue_count(&mut s), 1, "the one-word path is still reported after the round trip");
}
/// The file-name findings for one shape.
fn named(s: &mut Session, id: &Value) -> usize {
s.execute("review.accessibility", &json!({}))
.unwrap()
.as_array()
.unwrap()
.iter()
.filter(|issue| issue["shape"] == *id && issue["issue"] == "Alternative text is a file name")
.count()
}
/// #2549: Insert Video and Insert Audio set the clip's alt text to its file name, the way
/// Insert Picture does, and a clip's alt text keeps the image names the picture rule caught.
#[test]
fn a_clip_named_after_its_file_is_reported() {
let mut s = Session::with_new();
let video = s
.execute(
"insert.video",
&json!({"name": "clip.mp4", "data": crate::cmd::base64_encode(include_bytes!("../../../media/tests/fixtures/clip-h264.mp4"))}),
)
.unwrap()["id"]
.clone();
let audio = s
.execute(
"insert.audio",
&json!({"name": "tone.wma", "data": crate::cmd::base64_encode(include_bytes!("../../../media/tests/fixtures/tone.wma"))}),
)
.unwrap()["id"]
.clone();
assert_eq!(named(&mut s, &video), 1, "a video named after its file");
assert_eq!(named(&mut s, &audio), 1, "an audio clip named after its file");
// A spaced media name is caught by the media rule: three words and a media container.
s.execute("shape.altText", &json!({"text": "Podcast Episode 12.wma", "ids": [audio]})).unwrap();
assert_eq!(named(&mut s, &audio), 1, "a spaced media name is reported");
s.execute("shape.altText", &json!({"text": "tone.wma", "ids": [audio]})).unwrap();
// A description that only mentions the file is prose, as it is for a picture.
s.execute("shape.altText", &json!({"text": "A clip of traffic, from clip.mp4", "ids": [video]})).unwrap();
assert_eq!(named(&mut s, &video), 0, "a description that mentions the file is clear");
// A description that names an image as well as the clip is prose too: the image name is a
// file, so the sentence is not a file name (#2549).
s.execute("shape.altText", &json!({"text": "A comparison of IMG_2041.png and Clip_2.mp4", "ids": [video]})).unwrap();
assert_eq!(named(&mut s, &video), 0, "a description that names an image and the clip is clear");
// An image file name in a clip's alt text was reported before and stays reported.
for text in ["diagram.png", "IMG 2041.png"] {
s.execute("shape.altText", &json!({"text": text, "ids": [video]})).unwrap();
assert_eq!(named(&mut s, &video), 1, "{text:?} in a clip's alt text is still reported");
}
// The MP4 family is wider than `.mp4`, `.m4a`, `.m4b` and `.mov`: Insert Video types any
// `ftyp` file as video/mp4, so its other container names are media file names too (#2549).
for text in ["clip.3g2", "clip.f4v", "clip.m4p"] {
s.execute("shape.altText", &json!({"text": text, "ids": [video]})).unwrap();
assert_eq!(named(&mut s, &video), 1, "{text:?} is a media file name");
}
// A media container is a clip's file name, not a picture's.
let picture =
s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&test_png()), "name": "IMG_2041.png"})).unwrap()["id"].clone();
assert_eq!(named(&mut s, &picture), 1, "the picture's own file name is reported");
s.execute("shape.altText", &json!({"text": "clip.mp4", "ids": [picture, video]})).unwrap();
assert_eq!(named(&mut s, &picture), 0, "a video file name is not a picture's");
assert_eq!(named(&mut s, &video), 1, "the clip is still reported");
}
/// #2549: Insert Audio takes the `.mka` and `.weba` containers as `audio/webm`, and a spaced
/// media file name is still reported once the PPTX round trip has renamed the clip's media item,
/// so only the extension rule can find it.
#[test]
fn a_spaced_media_file_name_is_still_reported_after_a_pptx_round_trip() {
let mut s = Session::with_new();
// An embedded Matroska header, which the extension types as audio/webm.
let mka = vec![0x1A, 0x45, 0xDF, 0xA3, 0x01, 0x00, 0x00, 0x00];
let id =
s.execute("insert.audio", &json!({"name": "Podcast Episode 12.mka", "data": crate::cmd::base64_encode(&mka)})).unwrap()["id"].clone();
assert_eq!(named(&mut s, &id), 1, "the inserted file name is reported");
s.execute("shape.altText", &json!({"text": "Podcast Episode 12.weba", "ids": [id]})).unwrap();
assert_eq!(named(&mut s, &id), 1, "a `.weba` name is a media file name");
s.execute("shape.altText", &json!({"text": "Podcast Episode 12.wma", "ids": [id]})).unwrap();
assert_eq!(file_name_issue_count(&mut s), 1, "a spaced media name is reported");
pptx_round_trip(&mut s);
let doc = s.execute("document.inspect", &json!({})).unwrap();
let media_names: Vec<&str> = doc["media"].as_array().unwrap().iter().filter_map(|m| m["name"].as_str()).collect();
assert!(
media_names.iter().all(|name| !name.eq_ignore_ascii_case("Podcast Episode 12.mka")),
"the round trip renamed the media item, as it does a picture's: {doc}"
);
assert!(
media_names.iter().all(|name| !name.eq_ignore_ascii_case("Podcast Episode 12.wma")),
"no media item carries the alt text, so the exact-name rule cannot report it: {doc}"
);
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
assert!(
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == "Podcast Episode 12.wma"),
"the alt text survives the round trip: {slide}"
);
assert_eq!(file_name_issue_count(&mut s), 1, "the spaced media name is still reported after the round trip");
assert!(!is_file_name("Screenshot 2024 at 10.00.png", None));
}
}
@@ -68,8 +68,6 @@ pub(super) fn change(s: &mut Session, p: &Value) -> Result<Value> {
let info = deckcraft_geom::preset::info(name).ok_or_else(|| bad("shape.change", format!("unknown preset `{name}`")))?;
edit_geometry(s, p, "shape.change", |sh| {
sh.geom = Geom::preset(info.name);
let (tag, value) = crate::icons::INSERTED_ICON_TAG;
sh.tags.retain(|(key, tag_value)| key != tag || tag_value != value);
Ok(())
})
}
+1 -57
View File
@@ -262,13 +262,6 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("slide.delete", "no such slide"));
}
s.edit(|doc, sel| {
// Count only slides that are in the deck, each once: an id that names no slide, or a
// repeat, deletes nothing and must not be reported as deleted.
let mut seen = HashSet::new();
let ids: Vec<SlideId> = ids.iter().copied().filter(|id| doc.slide_index(*id).is_some() && seen.insert(*id)).collect();
if ids.is_empty() {
return Err(bad("slide.delete", "no such slide"));
}
let first = ids.iter().filter_map(|id| doc.slide_index(*id)).min().unwrap_or(0);
doc.slides.retain(|x| !ids.contains(&x.id));
for sec in &mut doc.sections {
@@ -696,24 +689,13 @@ fn section_remove(s: &mut Session, p: &Value) -> Result<Value> {
}
let sec = doc.sections.remove(i);
if with_slides {
let current = doc.slides.get(sel.slide).map(|x| x.id);
let first = sec.slides.iter().filter_map(|id| doc.slide_index(*id)).min().unwrap_or(0);
doc.slides.retain(|x| !sec.slides.contains(&x.id));
// As in slide.delete: the deleted slides leave every custom show and the selection.
for show in &mut doc.custom_shows {
show.slides.retain(|x| !sec.slides.contains(x));
}
sel.slides.retain(|x| !sec.slides.contains(x));
// The current slide keeps its place by id. When it was deleted, the slide that takes its
// place becomes current and the selection, as after slide.delete.
if let Some(at) = current.and_then(|id| doc.slide_index(id)) {
sel.slide = at;
} else {
sel.slide = first.min(doc.slides.len().saturating_sub(1));
sel.slides = doc.slides.get(sel.slide).map(|x| vec![x.id]).unwrap_or_default();
sel.shapes.clear();
sel.text = None;
}
sel.slide = sel.slide.min(doc.slides.len().saturating_sub(1));
} else if let Some(prev) = i.checked_sub(1).and_then(|k| doc.sections.get_mut(k)) {
prev.slides.extend(sec.slides);
} else if let Some(next) = doc.sections.get_mut(0) {
@@ -1005,44 +987,6 @@ mod tests {
assert_eq!(selected(&s), (0, vec![ids[2]]));
}
#[test]
fn removing_an_earlier_section_with_its_slides_keeps_the_current_slide() {
let (mut s, ids) = deck(5);
s.execute("section.add", &json!({"name": "First", "at": 0})).expect("First");
s.execute("section.add", &json!({"name": "Second", "at": 2})).expect("Second");
s.execute("slide.selectSlides", &json!({"ids": [ids[2]]})).expect("select C");
s.execute("section.remove", &json!({"index": 0, "slides": true})).expect("remove First and its slides");
let (cur, sel) = selected(&s);
assert_eq!(order(&s).get(cur), Some(&ids[2]), "C stays the current slide after the slides before it go");
assert_eq!(sel, [ids[2]], "the selection still names C");
}
#[test]
fn removing_the_current_slides_section_moves_the_selection_to_the_new_current_slide() {
let (mut s, ids) = deck(5);
s.execute("section.add", &json!({"name": "First", "at": 0})).expect("First");
s.execute("section.add", &json!({"name": "Second", "at": 2})).expect("Second");
s.execute("slide.selectSlides", &json!({"ids": [ids[3]]})).expect("select D");
s.execute("section.remove", &json!({"index": 1, "slides": true})).expect("remove Second and its slides");
assert_eq!(order(&s), [ids[0], ids[1]]);
let (cur, sel) = selected(&s);
let current = *order(&s).get(cur).expect("a current slide");
assert_eq!(sel, [current], "as after slide.delete, the selection names the new current slide");
}
#[test]
fn delete_reports_only_slides_it_deleted() {
let (mut s, ids) = deck(3);
assert!(s.execute("slide.delete", &json!({"ids": [999_999]})).is_err(), "an id that names no slide deletes nothing");
assert_eq!(order(&s), ids);
let r = s.execute("slide.delete", &json!({"ids": [ids[1], ids[1], 999_999]})).expect("delete");
assert_eq!(order(&s), [ids[0], ids[2]]);
assert_eq!(r["deleted"], 1, "{r}");
assert_eq!(r["remaining"], 2, "{r}");
}
#[test]
fn removing_a_section_with_its_slides_prunes_them_from_custom_shows() {
let (mut s, ids) = deck(4);
+3 -3
View File
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Change Layout",
["Diagram Design", "Layouts"],
None,
"{id?, kind: list|blockList|hBulletList|process|chevron|verticalProcess|stepUp|cycle|blockCycle|radial|hierarchy|pyramid|invertedPyramid|matrix|titledMatrix|pictureList|pictureCaption|pictureProcess|pictureHList|timeline|venn|target|textCycle|continuousCycle|horizontalHierarchy|gridMatrix|gear|funnel|segmentedCycle|multidirectionalCycle|orgChart|halfCircleOrgChart|cycleMatrix|segmentedPyramid|pie|nameTitleOrgChart|verticalBoxList|trapezoidList|tableList|accentProcess|continuousBlockProcess|bendingProcess|linearVenn|stackedVenn|nestedTarget} → {id, ids: the regenerated shapes}",
"{id?, kind: list|blockList|hBulletList|process|chevron|verticalProcess|stepUp|cycle|blockCycle|radial|hierarchy|pyramid|invertedPyramid|matrix|titledMatrix|pictureList|pictureCaption|pictureProcess|pictureHList|timeline|venn|target|textCycle|continuousCycle|horizontalHierarchy|gridMatrix|gear|funnel|segmentedCycle|multidirectionalCycle|orgChart|halfCircleOrgChart|cycleMatrix|segmentedPyramid|pie|nameTitleOrgChart|verticalBoxList|trapezoidList|tableList|accentProcess|continuousBlockProcess|bendingProcess|linearVenn|stackedVenn|nestedTarget}",
has_diagram,
change_layout
),
@@ -279,7 +279,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Diagram Styles",
["Diagram Design", "Diagram Styles"],
None,
"{id?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick} → {id, ids: the regenerated shapes}",
"{id?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick}",
has_diagram,
change_style
),
@@ -288,7 +288,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Change Colors",
["Diagram Design", "Diagram Styles"],
None,
"{id?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad} → {id, ids: the regenerated shapes}",
"{id?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad}",
has_diagram,
change_colors
),
+3 -18
View File
@@ -339,47 +339,33 @@ pub(super) fn set_picture(s: &mut Session, p: &Value) -> Result<Value> {
})
}
/// The answer of a command that regenerated a graphic's shapes: the group's id and its new children's ids.
fn regenerated(s: &Session, gid: ShapeId) -> Value {
let kids: Vec<u32> = match s.doc().ok().and_then(|st| st.shape(gid).map(|g| g.kind.clone())) {
Some(ShapeKind::Group { children, .. }) => children.iter().map(|c| c.id.0).collect(),
_ => vec![],
};
json!({"id": gid.0, "ids": kids})
}
pub(super) fn change_style(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "smartArt.style";
let v = str_param(p, "style").filter(|k| STYLES.iter().any(|(id, _)| id == k)).ok_or_else(|| bad(CMD, "unknown style"))?.to_string();
let gid = target_group(s, p, CMD)?;
edit_diagram(s, p, CMD, |d| {
if d.style != v {
d.style_xml = None;
}
d.style = v;
Ok(Value::Null)
})?;
Ok(regenerated(s, gid))
})
}
pub(super) fn change_colors(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "smartArt.colors";
let v = str_param(p, "colors").filter(|k| COLORS.iter().any(|(id, _)| id == k)).ok_or_else(|| bad(CMD, "unknown colours"))?.to_string();
let gid = target_group(s, p, CMD)?;
edit_diagram(s, p, CMD, |d| {
if d.colors != v {
d.colors_xml = None;
}
d.colors = v;
Ok(Value::Null)
})?;
Ok(regenerated(s, gid))
})
}
pub(super) fn change_layout(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "smartArt.layout";
let kind = str_param(p, "kind").filter(|k| is_kind(k)).ok_or_else(|| bad(CMD, "unknown layout"))?.to_string();
let gid = target_group(s, p, CMD)?;
edit_diagram(s, p, CMD, |d| {
if d.kind != kind {
// PowerPoint's own layout no longer applies.
@@ -388,6 +374,5 @@ pub(super) fn change_layout(s: &mut Session, p: &Value) -> Result<Value> {
}
d.kind = kind;
Ok(Value::Null)
})?;
Ok(regenerated(s, gid))
})
}
+9 -41
View File
@@ -267,31 +267,12 @@ fn cell_param(p: &Value, key: &str, cmd: &str) -> Result<Option<(usize, usize)>>
}
}
enum TableIndex {
Explicit(usize),
Selected(usize),
Default,
}
impl TableIndex {
fn value(&self) -> usize {
match *self {
Self::Explicit(i) | Self::Selected(i) => i,
Self::Default => 0,
}
}
}
/// Resolve each axis from its parameter, the edited or selected cell, then index zero.
/// Invalid parameters are rejected before any fallback.
fn at(s: &Session, p: &Value, cmd: &str) -> Result<(TableIndex, TableIndex)> {
/// The table's row/col to act on: params, the edited cell, or the selected cells.
/// A present but invalid `row`/`col` is an error; only an absent one falls back.
fn at(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> {
let st = s.active();
let cell = st.and_then(|d| d.selection.text.as_ref().and_then(|t| t.cell)).or_else(|| st.and_then(|d| d.selection.cells.map(|c| c.1)));
let resolve = |key, selected: Option<usize>| -> Result<TableIndex> {
let explicit = opt_usize_param(p, key, cmd)?;
Ok(explicit.map(TableIndex::Explicit).or(selected.map(TableIndex::Selected)).unwrap_or(TableIndex::Default))
};
Ok((resolve("row", cell.map(|c| c.0))?, resolve("col", cell.map(|c| c.1))?))
Ok((opt_usize_param(p, "row", cmd)?.or(cell.map(|c| c.0)).unwrap_or(0), opt_usize_param(p, "col", cmd)?.or(cell.map(|c| c.1)).unwrap_or(0)))
}
fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> Result<()>) -> Result<Value> {
@@ -347,7 +328,6 @@ fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> R
fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result<Value> {
let (r, c) = at(s, p, name)?;
let (r, c) = (r.value(), c.value());
// Absent: the table grows, as in PowerPoint; present, it must be a bool, so a mistyped value is refused
// rather than silently taken as the default.
let keep_width = match (op, p.get("keepWidth")) {
@@ -485,10 +465,7 @@ fn merge(s: &mut Session, p: &Value) -> Result<Value> {
fn split(s: &mut Session, p: &Value) -> Result<Value> {
let cell = match cell_param(p, "cell", "table.split")? {
Some(c) => c,
None => {
let (r, c) = at(s, p, "table.split")?;
(r.value(), c.value())
}
None => at(s, p, "table.split")?,
};
with_table(s, p, "table.split", move |t| if t.split(cell.0, cell.1) { Ok(()) } else { Err(bad("table.split", "that cell isn't merged")) })
}
@@ -750,17 +727,8 @@ fn distribute(s: &mut Session, p: &Value, rows: bool) -> Result<Value> {
/// A row or column the table doesn't have is an error, like a malformed index (#2260): checked
/// inside the edit, so a refused resize changes nothing and adds no undo step.
fn index_in_table(cmd: &str, key: &str, index: &TableIndex, n: usize, axis: &str) -> Result<usize> {
let i = index.value();
if i < n {
return Ok(i);
}
let source = match index {
TableIndex::Explicit(_) => format!("`{key}` {i}"),
TableIndex::Selected(_) => format!("the selected cell's {axis} {i}"),
TableIndex::Default => format!("the default {axis} {i}"),
};
Err(bad(cmd, format!("{source} is out of range: the table has {n} {axis}s")))
fn index_in_table(cmd: &str, key: &str, i: usize, n: usize, what: &str) -> Result<()> {
if i < n { Ok(()) } else { Err(bad(cmd, format!("`{key}` {i} is out of range: the table has {n} {what}"))) }
}
fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
@@ -768,7 +736,7 @@ fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
let w = f64_param(p, "width").ok_or_else(|| bad("table.columnWidth", "missing `width`"))?.clamp(4.0, 4000.0);
let keep_total = bool_or(p, "keepTotal", false);
with_table(s, p, "table.columnWidth", move |t| {
let c = index_in_table("table.columnWidth", "col", &c, t.n_cols(), "column")?;
index_in_table("table.columnWidth", "col", c, t.n_cols(), "columns")?;
// 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.saturating_add(1))).map(|(a, b)| a.max(0.0) + b.max(0.0)).filter(|x| x.is_finite());
@@ -797,7 +765,7 @@ fn row_height(s: &mut Session, p: &Value) -> Result<Value> {
let (r, _) = at(s, p, "table.rowHeight")?;
let h = f64_param(p, "height").ok_or_else(|| bad("table.rowHeight", "missing `height`"))?.clamp(4.0, 4000.0);
with_table(s, p, "table.rowHeight", move |t| {
let r = index_in_table("table.rowHeight", "row", &r, t.n_rows(), "row")?;
index_in_table("table.rowHeight", "row", r, t.n_rows(), "rows")?;
if let Some(x) = t.rows.get_mut(r) {
x.height = h;
}
+2 -4
View File
@@ -168,9 +168,9 @@ pub(super) fn autocorrect(s: &mut Session, typing: bool) -> Result<()> {
while start > 0 && line.get(start - 1).is_some_and(|c| !c.is_whitespace()) {
start -= 1;
}
// "word," and "word." also count when the text came in one piece; a typed punctuation mark already ran AutoCorrect on the word, and an Undo of that correction stays (#2184).
// "word," and "word." also count: the punctuation was typed before the space.
let mut word: String = line.get(start..word_end).map(|w| w.iter().collect()).unwrap_or_default();
if !typing && replacement(&s.prefs, &word).is_none() {
if replacement(&s.prefs, &word).is_none() {
let trimmed = word.trim_end_matches(|c: char| ".,;:!?".contains(c));
if !trimmed.is_empty() && trimmed.len() < word.len() && !word.ends_with("...") {
word_end -= word.chars().count() - trimmed.chars().count();
@@ -195,7 +195,6 @@ pub(super) fn autocorrect(s: &mut Session, typing: bool) -> Result<()> {
};
let delta = rep.chars().count() as isize - word.chars().count() as isize;
let st = s.doc_mut()?;
st.autocorrected = Some((st.doc.clone(), st.selection.clone()));
let mut d = (*st.doc).clone();
let sel = st.selection.clone();
if let Some(b) = body_mut(&mut d, &sel, &t) {
@@ -316,7 +315,6 @@ fn superscript_suffix(s: &mut Session, t: &crate::TextSel, end: usize) -> Result
if body_of(st, t).is_none_or(|body| ed::props_at(body, b).baseline.unwrap_or(0.0) > 0.0) {
return Ok(());
}
st.autocorrected = Some((st.doc.clone(), st.selection.clone()));
let mut d = (*st.doc).clone();
let sel = st.selection.clone();
if let Some(body) = body_mut(&mut d, &sel, t) {
+1 -9
View File
@@ -338,10 +338,7 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
_ => Some(sh.text.get_or_insert_with(TextBody::default)),
};
let Some(body) = target else { return Err(bad("text.set", "no text here (tables need `cell`)")) };
// The first run's formatting, or for text that is still empty the formatting its end
// mark holds (format.* before any text lands there), so a size set before text.set survives.
let keep =
body.paragraphs.first().map(|p| p.runs.first().map(|r| r.props.clone()).unwrap_or_else(|| p.end_props.clone())).unwrap_or_default();
let keep = body.paragraphs.first().and_then(|p| p.runs.first()).map(|r| r.props.clone()).unwrap_or_default();
let levels: Vec<(u8, deckcraft_model::text::ParaProps)> = body.paragraphs.iter().map(|p| (p.level, p.props.clone())).collect();
let mut nb = TextBody::from_text(&text);
for (i, para) in nb.paragraphs.iter_mut().enumerate() {
@@ -356,11 +353,6 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
for r in &mut para.runs {
r.props = keep.clone();
}
// The end mark keeps it too, so an empty `text` (no runs) carries the formatting to
// the text set next.
para.end_props = keep.clone();
// A run emptied by stripping leading tabs would shadow the end mark for the text typed next.
para.normalize();
}
body.paragraphs = nb.paragraphs;
Ok(())
-12
View File
@@ -25,10 +25,6 @@ pub(crate) fn format_run_levels(
// Only the levels of the paragraphs the selected range touches.
let levels = if a == b { Vec::new() } else { master_levels(st, &t, t.ordered()) };
edit_text(s, |body, _| {
// A body with no paragraph has no end mark to hold the formatting of the text typed next.
if body.paragraphs.is_empty() {
body.paragraphs.push(Default::default());
}
if levels.is_empty() {
ed::format(body, a, b, f);
} else {
@@ -69,9 +65,6 @@ pub(crate) fn format_run_levels(
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
if crate::cmd::table::in_range(range, r, c) {
if cell.text.paragraphs.is_empty() {
cell.text.paragraphs.push(Default::default());
}
ed::format_all(&mut cell.text, f);
}
}
@@ -79,11 +72,6 @@ pub(crate) fn format_run_levels(
}
_ => {
let body = sh.text.get_or_insert_with(TextBody::default);
// Text that is still empty keeps the formatting on an end mark, so a size set
// before the text lands survives it; a body with no paragraph has none.
if body.paragraphs.is_empty() {
body.paragraphs.push(Default::default());
}
let eff = effective.iter().find(|(i, _)| *i == id).map(|(_, e)| e);
match eff {
Some(eff) => {
-6
View File
@@ -73,12 +73,6 @@ impl AutomationRoots {
Ok(Some(Arc::new(Self { read, write })))
}
/// Roots that grant nothing: every read and write is refused. What an agent in the open window
/// may use when it has no agent folder.
pub fn none() -> Arc<Self> {
Arc::new(Self { read: Vec::new(), write: Vec::new() })
}
/// The read roots, absolute with their links followed.
pub fn read_roots(&self) -> impl Iterator<Item = &Path> {
self.read.iter().map(|r| r.shown.as_path())
-48
View File
@@ -255,54 +255,6 @@ mod tests {
}
}
#[test]
fn change_shape_clears_icon_identity_until_undone() {
let mut s = Session::with_new();
let insert_icon = |s: &mut Session| s.execute("insert.icon", &json!({"name": "star"})).unwrap()["id"].as_u64().unwrap();
let missing = insert_icon(&mut s);
let described = insert_icon(&mut s);
let untouched = insert_icon(&mut s);
let targets = json!({"ids": [missing, described]});
crate::cmd::edit_shapes(&mut s, &targets, "shape.change", |shape| {
shape.tags.push(("CUSTOM_TAG".into(), "kept".into()));
Ok(())
})
.unwrap();
s.execute("shape.altText", &json!({"ids": [described], "text": "Five-point outline"})).unwrap();
let missing_alt = |s: &mut Session| {
s.execute("review.accessibility", &json!({}))
.unwrap()
.as_array()
.unwrap()
.iter()
.filter(|issue| issue["issue"] == "Missing alternative text")
.map(|issue| issue["shape"].as_u64().unwrap())
.collect::<Vec<_>>()
};
let shapes = |s: &Session| [missing, described].map(|id| s.doc().unwrap().shape(ShapeId(id as u32)).unwrap().clone());
assert_eq!(missing_alt(&mut s), [missing, untouched]);
let original = shapes(&s);
let selection = s.doc().unwrap().selection.shapes.clone();
let converted = original.clone().map(|mut shape| {
shape.geom = Geom::preset("ellipse");
shape.tags = vec![("CUSTOM_TAG".into(), "kept".into())];
shape
});
s.execute("shape.change", &json!({"ids": [missing, described], "preset": "ellipse"})).unwrap();
assert_eq!(shapes(&s), converted);
assert_eq!(s.doc().unwrap().selection.shapes, selection);
assert_eq!(missing_alt(&mut s), [untouched]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(shapes(&s), original);
assert_eq!(missing_alt(&mut s), [missing, untouched]);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(shapes(&s), converted);
assert_eq!(missing_alt(&mut s), [untouched]);
}
fn ink_in(img: &deckcraft_render::Image, x: f64, y: f64, w: f64, h: f64, scale: f64) -> usize {
let x0 = (x * scale).floor().max(0.0) as u32;
let y0 = (y * scale).floor().max(0.0) as u32;
-2
View File
@@ -168,8 +168,6 @@ impl Session {
"end" => "End",
"tab" => "Tab",
"space" | " " => "Space",
// Ctrl+Shift+= reaches us as the shifted character, `+`; shortcuts are written with `=`.
"+" if mods.shift => "=",
_ => k,
};
let found = crate::command_specs().iter().find(|c| c.shortcut.is_some_and(|s| shortcut_matches(s, key_name, mods))).map(|c| c.id);
+1 -13
View File
@@ -237,9 +237,6 @@ pub struct DocState {
/// The list AutoFormat just started from a typed `* ` or `1. `, so Backspace right after
/// can put the typed text back.
pub auto_list: Option<cmd::text::AutoList>,
/// The presentation and selection between a typed character and the AutoCorrect it set off,
/// so the command's undo step splits in two and Undo takes back only the correction (#2184).
pub autocorrected: Option<(Arc<Presentation>, Selection)>,
/// The slide whose editor's consecutive notes changes share one undo step.
pub notes_run: Option<SlideId>,
notes_before: Option<Arc<Presentation>>,
@@ -272,7 +269,6 @@ impl DocState {
compare: None,
last_duplicate: None,
auto_list: None,
autocorrected: None,
notes_run: None,
notes_before: None,
}
@@ -733,9 +729,6 @@ impl Session {
}
if outer {
self.tool.vertex_kind = vertex_kind;
if let Some(st) = self.active_mut() {
st.autocorrected = None;
}
}
return Err(e);
}
@@ -743,7 +736,6 @@ impl Session {
if let Some(st) = self.active_mut() {
clamp_selection(st);
}
let autocorrected = if outer { self.active_mut().and_then(|st| st.autocorrected.take()) } else { None };
if let (Some((uid, old, sel)), Some(st)) = (before, self.active_mut())
&& st.uid == uid
&& !Arc::ptr_eq(&old, &st.doc)
@@ -761,12 +753,8 @@ impl Session {
}
} else {
let notes_before = (id == "slide.notes" && st.notes_run.is_some()).then(|| old.clone());
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind: vertex_kind.clone() });
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind });
st.notes_before = notes_before;
// The text as typed, before AutoCorrect changed it: its own step, undone first.
if let Some((doc, selection)) = autocorrected.filter(|(doc, _)| !Arc::ptr_eq(doc, &st.doc)) {
push_undo(st, HistoryEntry { label: "AutoCorrect".into(), doc, selection, vertex_kind });
}
}
}
if spec.journal && outer {
+1 -54
View File
@@ -64,42 +64,6 @@ fn params(r: &mut Rng, s: &Session) -> Value {
}
}
/// Physical memory in use, in bytes: the resident set size on Linux and macOS, the working set on
/// Windows. `None` where the platform cannot say.
fn rss_bytes() -> Option<u64> {
memory_stats::memory_stats().map(|m| m.physical_mem as u64)
}
/// Whether this process may run the named soak itself, so its memory reading is its own.
///
/// The reading is for the whole process, and plain `cargo test` runs every test of the crate on
/// threads of one process, so other tests' allocations would count against the budget. nextest
/// runs each test in its own process (and sets `NEXTEST`). Anywhere else the test runs itself again
/// in a child process of its own, which takes this branch, and fails if the child does.
fn alone(test: &str) -> bool {
const MARK: &str = "DECKCRAFT_SOAK_ALONE";
if std::env::var_os("NEXTEST").is_some() || std::env::var_os(MARK).is_some() {
return true;
}
let path = module_path!().split_once("::").map_or(module_path!(), |(_, rest)| rest);
let out = std::process::Command::new(std::env::current_exe().expect("test binary path"))
.args(["--exact", &format!("{path}::{test}"), "--include-ignored", "--test-threads=1", "--nocapture"])
.env(MARK, "1")
.output()
.expect("run the soak in its own process");
assert!(
out.status.success(),
"soak {test} failed in its own process:\n{}\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
false
}
/// RSS growth allowed between the warmed-up start and the end of a soak, with the test alone in
/// its process (see `alone`).
const MAX_RSS_GROWTH: u64 = 256 << 20;
fn doc(s: &Session) -> Option<deckcraft_model::Presentation> {
s.active().map(|d| (*d.doc).clone())
}
@@ -127,12 +91,7 @@ fn soak(seed: u64, steps: usize) {
let mut r = Rng(seed | 1);
let mut log: VecDeque<String> = VecDeque::new();
let mut edits = 0usize;
let mut rss_start = None;
for step in 0..steps {
// Sample after a quarter of the run so one-off caches and allocator arenas are warm.
if step == steps / 4 {
rss_start = rss_bytes();
}
let id = *r.pick(&ids).unwrap();
let p = params(&mut r, &s);
log.push_back(format!("{id} {p}"));
@@ -181,13 +140,7 @@ fn soak(seed: u64, steps: usize) {
}
// The soak must really edit, not just bounce off disabled commands.
assert!(edits * 10 >= steps, "only {edits} of {steps} steps changed the document; seed {seed}");
if let (Some(start), Some(end)) = (rss_start, rss_bytes()) {
let grew = end.saturating_sub(start);
eprintln!("soak seed {seed}: {edits} of {steps} steps edited, memory {} -> {} MiB", start >> 20, end >> 20);
assert!(grew <= MAX_RSS_GROWTH, "memory grew {} MiB over {} MiB; seed {seed}", grew >> 20, MAX_RSS_GROWTH >> 20);
} else {
eprintln!("soak seed {seed}: {edits} of {steps} steps edited");
}
eprintln!("soak seed {seed}: {edits} of {steps} steps edited");
}
fn steps(default: usize) -> usize {
@@ -196,9 +149,6 @@ fn steps(default: usize) -> usize {
#[test]
fn soak_random_edits_keep_the_document_valid() {
if !alone("soak_random_edits_keep_the_document_valid") {
return;
}
for seed in [1, 0xDEC0_C2AF, 42, 7_777_777] {
soak(seed, steps(400));
}
@@ -207,9 +157,6 @@ fn soak_random_edits_keep_the_document_valid() {
#[test]
#[ignore = "long soak; set DECKCRAFT_SOAK_STEPS"]
fn soak_long() {
if !alone("soak_long") {
return;
}
let seed = std::env::var("DECKCRAFT_SOAK_SEED").ok().and_then(|v| v.parse().ok()).unwrap_or(0x5EED);
soak(seed, steps(20_000));
}
+2 -278
View File
@@ -1399,107 +1399,13 @@ fn writable_format_for_path_rejects_formats_deckcraft_does_not_write() {
assert_eq!(f("dir/A.PPTX"), Some("pptx"));
assert_eq!(f("a.pdf"), Some("pdf"));
assert_eq!(f("a.jpg"), Some("jpeg"));
assert_eq!(f("a.txt"), Some("txt"));
assert_eq!(f("a.md"), Some("outline"));
assert_eq!(f("a.txt"), Some("outline"));
assert_eq!(f("a.gif"), Some("gif"));
for path in ["a.odp", "a.bmp", "a.svg", "a.outline", "a", "dir.v2/a"] {
assert_eq!(f(path), None, "{path}");
}
}
#[test]
fn txt_export_uses_crlf_even_with_explicit_outline() {
let dir = std::env::temp_dir().join(format!("deckcraft-txt-export-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new();
sample::open_sample(&mut s).unwrap();
let path = dir.join("outline.txt").to_string_lossy().to_string();
s.execute("file.export", &json!({"path": path, "format": "outline"})).unwrap();
let bytes = std::fs::read(&path).unwrap();
let text = String::from_utf8(bytes).unwrap();
assert!(text.contains("\r\n"), "TXT must use CRLF: {text:?}");
assert!(!text.replace("\r\n", "").contains('\n'), "no bare LF: {text:?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn md_export_keeps_lf() {
let dir = std::env::temp_dir().join(format!("deckcraft-md-export-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new();
sample::open_sample(&mut s).unwrap();
let path = dir.join("outline.md").to_string_lossy().to_string();
s.execute("file.export", &json!({"path": path, "format": "outline"})).unwrap();
let bytes = std::fs::read(&path).unwrap();
assert!(!bytes.windows(2).any(|w| w == b"\r\n"), "Markdown must stay LF");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn txt_outline_export_round_trips_two_slides() {
let mut p = deckcraft_model::defaults::new_presentation(None);
p.slides.clear();
let n = deckcraft_format::outline_to_slides(&mut p, "Alpha heading\n\tFirst body\nBeta heading\n\tSecond body\n");
assert_eq!(n, 2);
let bytes = crate::cmd::file::save_bytes(&p, "txt").unwrap();
let text = String::from_utf8(bytes).unwrap();
assert!(text.contains("\r\n"), "{text:?}");
assert!(!text.contains("\r\r\n"), "a CRLF input must not double the CR: {text:?}");
let mut q = deckcraft_model::defaults::new_presentation(None);
q.slides.clear();
assert_eq!(deckcraft_format::outline_to_slides(&mut q, &text), 2);
assert_eq!(q.slides[0].title(), "Alpha heading");
assert_eq!(q.slides[1].title(), "Beta heading");
let bodies: Vec<String> =
q.slides.iter().map(|s| s.shapes.iter().filter_map(|sh| sh.text.as_ref()).map(|t| t.text()).collect::<Vec<_>>().join(" ")).collect();
assert!(bodies[0].contains("First body"), "{:?}", bodies[0]);
assert!(bodies[1].contains("Second body"), "{:?}", bodies[1]);
}
#[test]
fn txt_export_does_not_double_existing_crlf() {
let text = String::from_utf8(crate::cmd::file::outline_txt_bytes("Alpha\r\nBeta\r\n")).unwrap();
assert_eq!(text, "Alpha\r\nBeta\r\n");
assert!(!text.contains("\r\r\n"), "{text:?}");
}
#[test]
fn txt_export_replaces_a_lone_cr_with_a_space() {
// A `.txt` import can leave a lone CR inside a body paragraph (`str::lines` splits on LF only).
let mut p = deckcraft_model::defaults::new_presentation(None);
p.slides.clear();
assert_eq!(deckcraft_format::outline_to_slides(&mut p, "Title\n\tGamma\rDelta\n"), 1);
let text = String::from_utf8(crate::cmd::file::save_bytes(&p, "txt").unwrap()).unwrap();
assert!(!text.replace("\r\n", "").contains('\r'), "a bare CR is a line terminator: {text:?}");
assert!(text.contains("\tGamma Delta\r\n"), "{text:?}");
// The paragraph must stay one line: the CR is not turned into a second outline line.
let mut q = deckcraft_model::defaults::new_presentation(None);
q.slides.clear();
assert_eq!(deckcraft_format::outline_to_slides(&mut q, &text), 1);
assert_eq!(q.slides[0].title(), "Title");
let body: String = q.slides[0].shapes.iter().filter_map(|sh| sh.text.as_ref()).map(|t| t.text()).collect::<Vec<_>>().join(" ");
assert!(body.contains("Gamma Delta"), "{body:?}");
}
#[test]
fn save_as_txt_uses_crlf() {
let dir = std::env::temp_dir().join(format!("deckcraft-save-txt-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new();
sample::open_sample(&mut s).unwrap();
let path = dir.join("outline.txt").to_string_lossy().to_string();
s.execute("file.saveAs", &json!({"path": path})).unwrap();
let text = String::from_utf8(std::fs::read(&path).unwrap()).unwrap();
assert!(text.contains("\r\n"), "TXT must use CRLF");
assert!(!text.replace("\r\n", "").contains('\n'), "no bare LF");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn save_and_reopen_native() {
let mut s = Session::new();
@@ -5453,51 +5359,6 @@ fn autocorrect_options_as_you_type() {
assert_eq!(s.execute("text.get", &json!({"id": title})).unwrap()["text"], "monday notes ");
}
/// #2184: Undo right after AutoCorrect takes back only the correction; the space that set it off
/// stays, and typing on does not correct the word again. A second Undo removes the space.
#[test]
fn undo_takes_back_only_the_autocorrect() {
let mut s = session();
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
let text = |s: &Session| {
s.doc().unwrap().current_slide().unwrap().shapes.iter().find(|sh| sh.id.0 == title).unwrap().text.as_ref().unwrap().paragraphs[0].text()
};
s.execute("text.edit", &json!({"id": title})).unwrap();
for c in "hello ".chars() {
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
}
assert_eq!(text(&s), "Hello ");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s), "hello ", "the correction is undone, the space stays");
assert_eq!(s.doc().unwrap().selection.text.as_ref().map(|t| t.caret), Some((0, 6)), "the caret stays after the space");
// Redo brings the correction back.
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(text(&s), "Hello ");
s.execute("edit.undo", &json!({})).unwrap();
for c in "world ".chars() {
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
}
assert_eq!(text(&s), "hello world ", "typing on leaves the word as it is");
for _ in 0.."world ".len() {
s.execute("edit.undo", &json!({})).unwrap();
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s), "hello", "the next Undo removes the space");
// Typing that AutoCorrect leaves alone is still one step per character.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s), "hell");
// A typed comma sets AutoCorrect off too; the space after it leaves the undone word alone.
s.execute("text.selectAll", &json!({})).ok();
s.execute("text.delete", &json!({"dir": "backward"})).ok();
for c in "hello,".chars() {
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
}
assert_eq!(text(&s), "Hello,");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("text.insert", &json!({"text": " "})).unwrap();
assert_eq!(text(&s), "hello, ", "the space after the comma leaves the undone word alone");
}
#[test]
fn autocorrect_superscripts_ordinals_as_you_type() {
let mut s = session();
@@ -5998,30 +5859,15 @@ fn a_long_ink_stroke_is_extended_in_place_and_capped() {
fn double_clicking_a_capped_freeform_keeps_its_vertices() {
let mut s = session();
let ev = |kind, x: f64, y: f64| tools::PointerEvent { kind, x, y, mods: Default::default(), tol: 3.0, pressure: None };
let point_cap = 16;
s.set_tool(tools::ToolKind::Shape { preset: "freeform".into() });
assert_eq!(s.tool.press_point_cap(), tools::MAX_GESTURE_POINTS);
s.tool.freeform_press_point_cap = Some(point_cap);
s.pointer(ev(tools::PointerKind::Down, 100.0, 100.0)).unwrap();
// Densely clicked vertices, each within the double-click tolerance of the last.
// The first press counts toward the cap, so 11 of these presses add no point.
for i in 0..point_cap + 10 {
for i in 0..tools::MAX_GESTURE_POINTS + 10 {
s.pointer(ev(tools::PointerKind::Down, 300.0 + i as f64 * 0.001, 100.0)).unwrap();
}
s.pointer(ev(tools::PointerKind::DoubleClick, 300.0, 100.0)).unwrap();
let st = s.doc().unwrap();
let deckcraft_model::Geom::Custom { paths } = &st.shapes().last().unwrap().geom else { panic!("no freeform") };
assert_eq!(paths[0].d.matches(" L ").count(), point_cap - 1);
}
#[test]
fn freeform_command_keeps_points_up_to_the_gesture_cap() {
let mut s = session();
// Send one point beyond the real cap to check that the command keeps as many as the tool can draw.
let points: Vec<_> = (0..=tools::MAX_GESTURE_POINTS).map(|i| [i % 500, i / 500]).collect();
let r = s.execute("shape.freeform", &json!({"points": points, "closed": false, "smooth": false})).unwrap();
let id = ShapeId(r["id"].as_u64().unwrap() as u32);
let deckcraft_model::Geom::Custom { paths } = &s.doc().unwrap().shape(id).unwrap().geom else { panic!("no freeform") };
assert_eq!(paths[0].d.matches(" L ").count(), tools::MAX_GESTURE_POINTS - 1);
}
@@ -6282,8 +6128,6 @@ fn table_resize_rejects_a_row_or_column_past_the_table() {
let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len());
let e = s.execute(cmd, &params).expect_err(&format!("{cmd} {params} should be rejected"));
assert!(e.to_string().contains(cmd), "the error should name {cmd}: {e}");
let key = if params.get("row").is_some() { "row" } else { "col" };
assert!(e.to_string().contains(&format!("`{key}`")), "the error should name the explicit parameter: {e}");
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "{cmd} {params} must leave the presentation unchanged");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params} must not add an undo step");
assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{cmd} {params} must keep the redo step");
@@ -6293,40 +6137,6 @@ fn table_resize_rejects_a_row_or_column_past_the_table() {
assert_eq!(table_of(&s, id).rows.first().map(|r| r.height), Some(30.0), "the redo step is still the row height");
}
#[test]
fn table_resize_names_the_source_of_an_out_of_range_implicit_index() {
let mut s = session();
let source = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
let target = table_at(&mut s, &[100.0], json!([["e"]]));
let check = |s: &mut Session, row_error: &str, column_error: &str| {
let before = s.doc().unwrap();
let doc = before.doc.clone();
let history = (before.history.undo.len(), before.history.redo.len());
for (cmd, params, expected) in [
("table.rowHeight", json!({"id": target.0, "height": 50.0}), row_error),
("table.columnWidth", json!({"id": target.0, "width": 50.0}), column_error),
] {
let err = s.execute(cmd, &params).unwrap_err().to_string();
assert!(err.contains(expected), "{cmd}: {err}");
let after = s.doc().unwrap();
assert!(std::sync::Arc::ptr_eq(&after.doc, &doc), "{cmd} must leave the presentation unchanged");
assert_eq!((after.history.undo.len(), after.history.redo.len()), history);
}
};
s.execute("table.selectCells", &json!({"id": source.0, "from": [1, 1]})).unwrap();
check(&mut s, "the selected cell's row 1 is out of range", "the selected cell's column 1 is out of range");
s.execute("edit.deselect", &json!({})).unwrap();
// A table without rows or columns has no index zero to fall back to.
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let slide = std::sync::Arc::make_mut(&mut doc.slides[0]);
let deckcraft_model::ShapeKind::Table(table) = &mut slide.shape_mut(target).unwrap().kind else { panic!("not a table") };
table.rows.clear();
table.cols.clear();
check(&mut s, "the default row 0 is out of range", "the default column 0 is out of range");
}
#[test]
fn table_resize_in_range_still_works() {
let mut s = session();
@@ -7614,67 +7424,6 @@ fn style_commands_refuse_only_nulls_and_take_one_key() {
}
}
/// A size (or colour, bold…) set on a shape before it has any text survives the text that is
/// then set: text.set keeps the first run's properties, and an empty paragraph keeps them on its
/// end mark, which is what the agent's format.size then set_text sequence relies on.
#[test]
fn text_set_keeps_the_formatting_of_an_empty_shape() {
let mut s = session();
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 300, 60]})).unwrap()["id"].as_u64().unwrap();
s.execute("format.size", &json!({"size": 30})).unwrap();
s.execute("format.bold", &json!({"on": true})).unwrap();
s.execute("text.set", &json!({"id": id, "text": "Hello"})).unwrap();
let props =
|s: &Session| s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().text.as_ref().unwrap().paragraphs[0].runs[0].props.clone();
let run = props(&s);
assert_eq!((run.size, run.bold), (Some(30.0), Some(true)), "{run:?}");
// Emptied and filled again: the empty paragraph's end mark carried the formatting.
s.execute("text.set", &json!({"id": id, "text": ""})).unwrap();
s.execute("text.set", &json!({"id": id, "text": "Again"})).unwrap();
let run = props(&s);
assert_eq!((run.size, run.bold), (Some(30.0), Some(true)), "after an empty text.set: {run:?}");
}
/// The same while editing the text: a bold set in the text editor of a shape with an empty body
/// (no paragraph at all) is what the next typed text gets.
#[test]
fn text_insert_keeps_the_formatting_set_in_an_empty_editor() {
let mut s = session();
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 300, 60]})).unwrap()["id"].as_u64().unwrap();
s.edit(|doc, sel| {
let sh = deckcraft_model::find_shape_mut(crate::shapes_mut(doc, sel).unwrap(), deckcraft_model::ShapeId(id as u32)).unwrap();
sh.text = Some(deckcraft_model::text::TextBody::default());
Ok(())
})
.unwrap();
s.execute("text.edit", &json!({"id": id})).unwrap();
s.execute("format.bold", &json!({"on": true})).unwrap();
s.execute("text.insert", &json!({"text": "Hi"})).unwrap();
let run = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().text.as_ref().unwrap().paragraphs[0].runs[0].props.clone();
assert_eq!(run.bold, Some(true), "{run:?}");
}
/// Font toggles on a selected table read the first selected cell, so the second Bold turns it off
/// again, also for a cell whose empty text got its paragraph from the first toggle.
#[test]
fn bold_toggles_on_a_selected_table_cell() {
let mut s = session();
let id = table_at(&mut s, &[100.0, 100.0], json!([["", "b"], ["c", "d"]]));
let bold = |s: &Session, r: usize, c: usize| {
let st = s.doc().unwrap();
let deckcraft_model::ShapeKind::Table(t) = &st.shape(id).unwrap().kind else { panic!("table") };
let p = &t.cell(r, c).unwrap().text.paragraphs[0];
p.runs.first().map_or(p.end_props.bold, |r| r.props.bold)
};
s.execute("table.selectCells", &json!({"id": id, "from": [0, 0], "to": [0, 1]})).unwrap();
s.execute("format.bold", &json!({})).unwrap();
assert_eq!((bold(&s, 0, 0), bold(&s, 0, 1)), (Some(true), Some(true)));
assert_eq!(s.execute("format.state", &json!({})).unwrap()["bold"], json!(true));
s.execute("format.bold", &json!({})).unwrap();
assert_eq!((bold(&s, 0, 0), bold(&s, 0, 1)), (Some(false), Some(false)));
assert_eq!(bold(&s, 1, 0), None, "cells outside the range keep their formatting");
}
#[test]
fn highlight_with_an_invalid_colour_is_rejected_and_keeps_the_highlight() {
let mut s = session();
@@ -8471,28 +8220,3 @@ fn editor_replacements_report_autocorrection_and_cancel_only_the_open_session()
assert!(std::sync::Arc::ptr_eq(&restored, &s.doc().unwrap().doc));
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn smartart_colors_layout_and_style_answer_the_regenerated_ids() {
let mut s = session();
let r = s.execute("insert.smartArt", &json!({"kind": "process"})).unwrap();
let gid = r["id"].clone();
for (cmd, params) in [
("smartArt.colors", json!({"id": gid, "colors": "colorful"})),
("smartArt.layout", json!({"id": gid, "kind": "cycle"})),
("smartArt.style", json!({"id": gid, "style": "intense"})),
] {
let a = s.execute(cmd, &params).unwrap();
assert_eq!(a["id"], gid, "{cmd}: {a}");
let st = s.doc().unwrap();
let g = st
.doc
.slides
.iter()
.find_map(|sl| deckcraft_model::find_shape(&sl.shapes, deckcraft_model::ShapeId(gid.as_u64().unwrap() as u32)))
.unwrap();
let deckcraft_model::ShapeKind::Group { children, .. } = &g.kind else { panic!("group") };
let kids: Vec<u32> = children.iter().map(|c| c.id.0).collect();
assert_eq!(a["ids"], json!(kids), "{cmd}: {a}");
}
}
-12
View File
@@ -274,9 +274,6 @@ pub struct ToolState {
pub path_closing: bool,
/// Whether the last freeform press added a vertex (it adds none at the point cap).
pub press_added_vertex: bool,
/// A smaller cap for tests that exercise freeform presses.
#[cfg(test)]
pub(crate) freeform_press_point_cap: Option<usize>,
/// The shape in Edit Points: its vertices are handles instead of the box's.
pub edit_points: Option<ShapeId>,
/// The vertex (path, index) whose control handles show in Edit Points.
@@ -313,15 +310,6 @@ impl ToolState {
pub fn drawing_freeform(&self) -> bool {
matches!(self.drag, Some(Drag::Freeform { .. }))
}
/// Most vertices freeform presses place: [`MAX_GESTURE_POINTS`], or a smaller cap a test sets.
pub(crate) fn press_point_cap(&self) -> usize {
#[cfg(test)]
if let Some(cap) = self.freeform_press_point_cap {
return cap;
}
MAX_GESTURE_POINTS
}
}
/// Handle positions in slide coordinates for a box (8 resize + rotate).
+1 -1
View File
@@ -262,7 +262,7 @@ impl Session {
self.tool.drag = Some(Drag::Freeform { mode, points, pressed: false });
return self.finish_freeform(true);
}
self.tool.press_added_vertex = points.len() < self.tool.press_point_cap();
self.tool.press_added_vertex = points.len() < super::MAX_GESTURE_POINTS;
if self.tool.press_added_vertex {
points.push(p);
}
-79
View File
@@ -1,79 +0,0 @@
//! Standalone EMF and WMF files inserted as pictures (#2392).
use std::io::{Cursor, Read};
use craft_metafile::write::{Op, emf, wmf};
use deckcraft_engine::Session;
use deckcraft_engine::cmd::base64_encode;
use deckcraft_geom::{KurboShape as _, Rect};
use deckcraft_model::{ShapeId, ShapeKind};
use serde_json::json;
/// Two solid rectangles, red at the top left and blue at the bottom right, on a 200 x 100 pt
/// picture.
fn two_rects() -> (Vec<Op>, Rect) {
let fill = |r: Rect, rgb: [u8; 3]| Op::Fill { path: r.to_path(0.1), even_odd: false, rgb };
(
vec![fill(Rect::new(0.0, 0.0, 100.0, 50.0), [0xC7, 0x30, 0x40]), fill(Rect::new(100.0, 50.0, 200.0, 100.0), [0x20, 0x70, 0xD0])],
Rect::new(0.0, 0.0, 200.0, 100.0),
)
}
#[test]
fn standalone_emf_and_wmf_files_insert_as_pictures_and_save_as_metafile_parts() {
let (ops, region) = two_rects();
let emf = emf(&ops, region, "DeckCraft", "two rects").expect("EMF");
let wmf = wmf(&ops, region).expect("WMF").bytes;
for (name, bytes, ext) in [("source.emf", emf, "emf"), ("source.wmf", wmf, "wmf")] {
let mut s = Session::with_new();
let rect = [200.0, 120.0, 480.0, 270.0];
let r = s.execute("insert.picture", &json!({"data": base64_encode(&bytes), "name": name, "rect": rect})).expect(name);
let id = ShapeId(r["id"].as_u64().expect("id") as u32);
let doc = &s.doc().expect("doc").doc;
let sh = doc.slides.iter().flat_map(|sl| &sl.shapes).find(|sh| sh.id == id).expect("inserted shape");
let ShapeKind::Picture { fill } = &sh.kind else { panic!("{name} is a picture: {:?}", sh.kind) };
let x = sh.xfrm.expect("xfrm");
assert_eq!([x.x, x.y, x.w, x.h], rect, "{name} sits at the requested bounds");
assert_eq!(doc.media(fill.media).expect("media").data.as_slice(), bytes.as_slice(), "{name} is embedded as given");
// Saved as a metafile part, and read back as the same picture.
let pptx = deckcraft_pptx::export(doc).expect("export");
let mut z = zip::ZipArchive::new(Cursor::new(&pptx)).expect("zip");
let part = z.file_names().find(|n| n.starts_with("ppt/media/") && n.ends_with(&format!(".{ext}"))).map(str::to_string);
let part = part.unwrap_or_else(|| panic!("{name} is saved as a .{ext} part: {:?}", z.file_names().collect::<Vec<_>>()));
let mut saved = Vec::new();
z.by_name(&part).expect("part").read_to_end(&mut saved).expect("read");
assert_eq!(saved, bytes, "{part} holds the file's bytes");
let back = deckcraft_pptx::import(&pptx).expect("import");
let reopened = back
.slides
.iter()
.flat_map(|sl| &sl.shapes)
.find(|sh| matches!(&sh.kind, ShapeKind::Picture { fill } if back.media(fill.media).is_some_and(|m| *m.data == bytes)));
let reopened = reopened.unwrap_or_else(|| panic!("{name} reopens as a picture"));
let x = reopened.xfrm.expect("reopened xfrm");
let near = |a: f64, b: f64| (a - b).abs() < 0.01;
assert!(
near(x.x, rect[0]) && near(x.y, rect[1]) && near(x.w, rect[2]) && near(x.h, rect[3]),
"{name} reopens at the requested bounds: {:?}",
[x.x, x.y, x.w, x.h]
);
}
}
#[test]
fn a_photo_album_lays_out_a_metafile_with_its_own_aspect() {
let (ops, region) = two_rects();
let emf = emf(&ops, region, "DeckCraft", "two rects").expect("EMF");
let wmf = wmf(&ops, region).expect("WMF").bytes;
for (name, bytes) in [("wide.emf", emf), ("wide.wmf", wmf)] {
let mut s = Session::with_new();
let item = json!({"data": base64_encode(&bytes), "name": name});
s.execute("insert.photoAlbum", &json!({"pictures": [item], "layout": "1"})).expect(name);
let doc = &s.doc().expect("doc").doc;
let sh = doc.slides.iter().flat_map(|sl| &sl.shapes).find(|sh| matches!(sh.kind, ShapeKind::Picture { .. })).expect("album picture");
let x = sh.xfrm.expect("xfrm");
let aspect = x.w / x.h;
assert!((aspect - 2.0).abs() < 0.05, "{name} keeps its 2:1 frame in the album, got {aspect}");
}
}
-1
View File
@@ -1,3 +1,2 @@
mod chart_native;
mod insert_metafile;
mod show_clicks;
+9 -57
View File
@@ -113,9 +113,9 @@ struct Outline {
/// non-ASCII `Token::Symbol`.
skip_cont: usize,
line: String,
/// The document's code page for `\'hh` bytes (Windows-1252 unless `\ansicpg` names a supported page).
/// The document's code page (`\ansicpg`), which `\'hh` bytes are in: Windows-1252 until it
/// names another single-byte one (#2394).
code_page: u16,
hex_decoder: craft_rtf::TextDecoder,
/// Paragraphs so far: outline level and text (empty only for an empty level-0 title).
out: Vec<(usize, String)>,
}
@@ -203,7 +203,6 @@ fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
skip_cont: 0,
line: String::new(),
code_page: 1252,
hex_decoder: craft_rtf::TextDecoder::new(),
out: vec![],
};
p.run(rtf);
@@ -215,10 +214,6 @@ impl Outline {
fn run(&mut self, rtf: &str) {
let mut tokens = craft_rtf::Tokens::new(rtf.as_bytes());
while let Some(token) = tokens.next() {
// Text and escaped literals can supply trail bytes. Structural and semantic tokens end the run.
if !matches!(token, craft_rtf::Token::Hex(_) | craft_rtf::Token::Text(_) | craft_rtf::Token::Symbol(b'\\' | b'{' | b'}')) {
self.hex_decoder.finish(&mut self.line);
}
match token {
craft_rtf::Token::Open => self.open_group(),
craft_rtf::Token::Close => self.close_group(),
@@ -240,7 +235,6 @@ impl Outline {
craft_rtf::Token::Bin(_) => self.skip_cont = 0,
}
}
self.hex_decoder.finish(&mut self.line);
}
fn open_group(&mut self) {
@@ -283,10 +277,9 @@ impl Outline {
self.style_level = arg.filter(|a| (1..=9).contains(a) && self.headings[*a as usize]).map(|a| a as u32 - 1);
}
"li" => self.indent = i64::from(arg.unwrap_or(0)),
// A code page read a byte at a time; any other (East Asian multibyte, unknown) keeps Windows-1252.
"ansicpg" => {
use craft_rtf::codepage::{is_byte_code_page, multibyte_encoding_name};
let cp = arg.and_then(|a| u16::try_from(a).ok());
if let Some(cp) = cp.filter(|&cp| is_byte_code_page(cp) || multibyte_encoding_name(cp).is_some()) {
if let Some(cp) = arg.and_then(|a| u16::try_from(a).ok()).filter(|cp| craft_rtf::codepage::is_byte_code_page(*cp)) {
self.code_page = cp;
}
}
@@ -318,7 +311,7 @@ impl Outline {
return;
}
if !self.st.skip && h != 0 {
self.hex_decoder.byte(h, self.code_page, &mut self.line);
self.line.push(craft_rtf::codepage::code_page_byte(self.code_page, h));
}
}
@@ -338,7 +331,7 @@ impl Outline {
return;
}
match n {
b'\\' | b'{' | b'}' => self.hex_decoder.byte(n, self.code_page, &mut self.line),
b'\\' | b'{' | b'}' => self.line.push(n as char),
b'~' => self.line.push('\u{a0}'),
b'_' => self.line.push('\u{2011}'),
b'\n' | b'\r' => self.flush(true),
@@ -365,15 +358,6 @@ impl Outline {
}
}
if !self.st.skip {
// The decoder consumes the first ASCII byte as a trail only when the code page allows it.
// Any remaining text is already UTF-8.
if craft_rtf::codepage::multibyte_encoding_name(self.code_page).is_some()
&& let Some(&first) = s.as_bytes().first().filter(|b| b.is_ascii())
{
self.hex_decoder.byte(first, self.code_page, &mut self.line);
s = &s[1..];
}
self.hex_decoder.finish(&mut self.line);
self.line.push_str(s);
}
}
@@ -647,7 +631,9 @@ mod tests {
assert_eq!(crate::slides_to_outline(&reopened), expected);
}
/// `\ansicpg` names the code page of the escapes, including pages with multibyte letters.
/// A writer on a non-Western Windows locale names its code page with `\ansicpg` and writes
/// non-ASCII letters as `\'hh` bytes of that page (#2394); `\ansicpg1252` and no `\ansicpg`
/// both stay Windows-1252.
#[test]
fn hex_escapes_decode_in_the_code_page_ansicpg_names() {
let outline = |cpg: &str, title: &str, body: &str| {
@@ -665,40 +651,6 @@ mod tests {
assert_eq!(outline(r"\ansicpg1251", r"\'cf\'f0\'e8\'e2\'e5\'f2", r"\'ec\'e8\'f0"), "Привет\n\tмир\nPlain\n");
assert_eq!(outline(r"\ansicpg1252", r"Caf\'e9", r"\'93a\'94"), "Café\n\t“a”\nPlain\n");
assert_eq!(outline("", r"Caf\'e9", r"\'93a\'94"), "Café\n\t“a”\nPlain\n");
assert_eq!(outline(r"\ansicpg932", r"\'93\'fa\'96\'7b", r"\'8c\'ea"), "日本\n\t語\nPlain\n");
assert_eq!(outline(r"\ansicpg936", r"\'d6\'d0\'ce\'c4", r"\'bc\'f2\'cc\'e5"), "中文\n\t简体\nPlain\n");
assert_eq!(outline(r"\ansicpg949", r"\'c7\'d1\'b1\'b9", r"\'be\'ee"), "한국\n\t어\nPlain\n");
assert_eq!(outline(r"\ansicpg950", r"\'a4\'a4\'a4\'e5", r"\'a4\'e5"), "中文\n\t文\nPlain\n");
}
#[test]
fn raw_ascii_trail_bytes_match_hex_escaped_trail_bytes() {
for (cp, lead) in [(932, "83"), (936, "81"), (949, "81"), (950, "a4")] {
let mixed = format!(r"{{\rtf1\ansi\ansicpg{cp} \'{lead}A\par}}");
let escaped = format!(r"{{\rtf1\ansi\ansicpg{cp} \'{lead}\'41\par}}");
let decoded = rtf_to_outline(&mixed);
assert_eq!(decoded, rtf_to_outline(&escaped), "CP{cp}");
assert!(!decoded.contains('\u{fffd}'), "CP{cp}: {decoded:?}");
}
assert_eq!(rtf_to_outline(r"{\rtf1\ansi\ansicpg932 \'83AB界\par}"), "アB界\n");
assert_eq!(rtf_to_outline(r"{\rtf1\ansi\ansicpg932 \'83!\'83界\par}"), "\u{fffd}!\u{fffd}界\n");
}
#[test]
fn escaped_literals_match_hex_escaped_trail_bytes() {
let mixed = r"{\rtf1\ansi\ansicpg932 \'95\\\'93\{\'93\}\par}";
let escaped = r"{\rtf1\ansi\ansicpg932 \'95\'5c\'93\'7b\'93\'7d\par}";
assert_eq!(rtf_to_outline(mixed), "表怒党\n");
assert_eq!(rtf_to_outline(mixed), rtf_to_outline(escaped));
let literals = r"{\rtf1\ansi\ansicpg932 \{\}\\{\*\ignored \'95\\}\uc1\u65\{\'83\b B\par}";
assert_eq!(rtf_to_outline(literals), "{}\\A\u{fffd}B\n");
}
#[test]
fn multibyte_escapes_respect_unicode_fallback_and_group_boundaries() {
let rtf = r"{\rtf1\ansi\ansicpg932\outlinelevel0 \'93\'fa{\uc2\u26412\'96A}\'8c\'ea\par\pard\outlinelevel1 {\'93}A\'93\{\b \'93\'fa\par}";
assert_eq!(rtf_to_outline(rtf), "日本語\n\t\u{fffd}A怒日\n");
}
#[test]
-5
View File
@@ -15,8 +15,3 @@ deckcraft-engine = { workspace = true }
deckcraft-render = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# Plain `mcp` finds the open window through the ArtCraft Launcher's switch and the connection file, with the
# shared live client (`automation-agents`) and the default agent folder (`control-agents`): `src/agents.rs`.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft = { workspace = true, features = ["automation", "automation-agents", "control-agents"] }
-291
View File
@@ -1,291 +0,0 @@
//! Agents in the open window: the CLI's side of the ArtCraft Launcher's switch.
//!
//! While the launcher's *Settings › AI agents* switch names DeckCraft (behind the suite's `AI-MCP`
//! flag), the desktop app serves its control channel on loopback and publishes where in its
//! settings folder (`craft::automation::agents::AgentLink`, `deckcraft_ui_egui::agents`). Plain
//! `deckcraft-cli mcp` reads that file on every tool call ([`LiveBackend`], over the shared
//! `craft::automation::agents::Live`), so an MCP client's configuration holds no port and no token,
//! and the app may start, quit or move to another port while the client stays connected. Adding
//! DeckCraft to MCP clients is the launcher's job (one entry for every Craft app); DeckCraft
//! writes no client configuration.
//!
//! What is DeckCraft's here: its launcher id, its window client ([`Window`], which makes the app
//! prove it holds the token before the client proves it holds it too) and its headless session
//! ([`Headless`] with the agent folders as automation roots).
use std::cell::RefCell;
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use craft::automation::agents::{self as shared, AgentSettings, Consent, HeadlessFolders, Route, WhenAppClosed};
use craft::automation::client::{CALL_TIMEOUT, CONNECT_TIMEOUT, MAX_REPLY_BYTES};
use craft::automation::security::{self, ProofRole};
use craft::control::agents::{AgentFolders, folders_answer};
use deckcraft_engine::file_access::AutomationRoots;
use serde_json::{Value, json};
use crate::backend::Backend;
use crate::headless::Headless;
/// The id the ArtCraft Launcher's app list names DeckCraft by (its catalog id).
pub const LAUNCHER_APP_ID: &str = "deckcraft";
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/DeckCraft`).
pub const APP_NAME: &str = "DeckCraft";
/// The desktop app's file name beside the CLI (without `.exe`).
pub const APP_EXE: &str = "deckcraft";
pub use crate::headless::{FOLDERS_METHOD, NEEDS_WINDOW};
/// Whether the person lets agents use DeckCraft now: with the suite's `AI-MCP` flag, the
/// launcher's switch. DeckCraft had no agent consent of its own before the switch, so without the
/// flag agents get a session without a window.
pub fn allowed_now() -> bool {
shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false)
}
/// The automation roots for `folders`: what a session with these folders may open and save. A kind
/// without a folder is refused, and so is everything when there is no folder at all.
pub fn roots_for(folders: &AgentFolders) -> Result<Arc<AutomationRoots>, String> {
let read: Vec<PathBuf> = folders.read.iter().cloned().collect();
let write: Vec<PathBuf> = folders.write.iter().cloned().collect();
Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
}
// ---- The open window ---------------------------------------------------------------------------
/// One authenticated connection to the open window. The app proves it holds the token first
/// (`auth.challenge`), then the client answers with its own proof: the token never crosses the
/// wire, and a program that took a stale port learns nothing derived from it.
pub struct Window {
addr: SocketAddr,
token: String,
conn: Option<(BufReader<TcpStream>, TcpStream)>,
next_id: u64,
}
impl Window {
/// A client for the window on `127.0.0.1:port` with `token`; connects on the first call.
pub fn new(port: u16, token: String) -> Self {
Self { addr: SocketAddr::from(([127, 0, 0, 1], port)), token, conn: None, next_id: 1 }
}
/// Connects and runs the challenge handshake.
pub fn connect(&mut self) -> Result<(), String> {
self.conn = None;
let stream = TcpStream::connect_timeout(&self.addr, CONNECT_TIMEOUT).map_err(|e| e.to_string())?;
stream.set_nodelay(true).ok();
stream.set_write_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
let mut conn = (BufReader::new(stream.try_clone().map_err(|e| e.to_string())?), stream);
let client_nonce = security::generate_nonce().map_err(|e| e.to_string())?;
let challenge = round_trip(&mut conn, 0, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))?
.map_err(|e| format!("{} refused challenge authentication ({e}); the agent token was not used", self.addr))?;
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned);
let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else {
return Err(format!("{} answered the challenge without a proof; the agent token was not used", self.addr));
};
if !security::proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
return Err(format!("{} could not prove it holds DeckCraft's agent token; nothing was sent to it", self.addr));
}
let proof = security::handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| e.to_string())?;
round_trip(&mut conn, 0, security::AUTH_METHOD, json!({"proof": proof}))?.map_err(|e| format!("DeckCraft refused the agent token: {e}"))?;
self.conn = Some(conn);
Ok(())
}
}
/// Sends one request and reads the reply with its `id` (lines for other ids are skipped): `Err`
/// when the connection failed, `Ok(Err)` when the app answered with an error.
fn round_trip(conn: &mut (BufReader<TcpStream>, TcpStream), id: u64, method: &str, params: Value) -> Result<Result<Value, String>, String> {
let (reader, writer) = conn;
let line = json!({"id": id, "method": method, "params": params}).to_string();
writer.write_all(line.as_bytes()).and_then(|()| writer.write_all(b"\n")).and_then(|()| writer.flush()).map_err(|e| e.to_string())?;
let deadline = Instant::now() + CALL_TIMEOUT;
loop {
let reply = read_line(reader, deadline)?;
let v: Value = serde_json::from_slice(&reply).map_err(|e| format!("bad reply from the window: {e}"))?;
if v.get("id").and_then(Value::as_u64) != Some(id) {
continue;
}
return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned())
});
}
}
/// One reply line, at most [`MAX_REPLY_BYTES`] before its newline, read by `deadline`. One read at
/// a time, so the deadline holds between reads: a peer that trickles bytes can't stretch it.
fn read_line(reader: &mut BufReader<TcpStream>, deadline: Instant) -> Result<Vec<u8>, String> {
let mut line = Vec::new();
loop {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err("the window did not answer in time".into());
}
reader.get_ref().set_read_timeout(Some(left)).map_err(|e| e.to_string())?;
let (used, done) = match reader.fill_buf() {
Ok([]) => return Err("the window closed the connection".into()),
Ok(buf) => {
let end = buf.iter().position(|&b| b == b'\n').map_or((buf.len(), false), |i| (i + 1, true));
line.extend_from_slice(&buf[..end.0]);
end
}
Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut | ErrorKind::Interrupted) => continue,
Err(e) => return Err(e.to_string()),
};
// What follows the newline stays buffered for the next line.
reader.consume(used);
let body = line.len() as u64 - u64::from(done);
if body > MAX_REPLY_BYTES {
return Err("the window's reply is too long".into());
}
if done {
return Ok(line);
}
}
}
impl Backend for Window {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
if self.conn.is_none() {
self.connect().map_err(|e| format!("the DeckCraft window is not reachable: {e}; `{method}`: nothing was sent"))?;
}
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1).max(1);
let Some(conn) = self.conn.as_mut() else { return Err("not connected".into()) };
match round_trip(conn, id, method, params) {
Ok(answer) => answer,
// Never sent again: the request may have run. The next call reconnects.
Err(e) => {
self.conn = None;
Err(format!(
"lost the connection to the DeckCraft window ({e}); `{method}` may or may not have run: check the document before retrying"
))
}
}
}
fn has_ui(&self) -> bool {
true
}
fn describe(&self) -> String {
format!("the open DeckCraft window ({})", self.addr)
}
}
// ---- The live backend --------------------------------------------------------------------------
type SharedWindow = Arc<Mutex<Window>>;
/// The headless session stays on the server's thread, as the backend does.
type SharedHeadless = Rc<RefCell<Headless>>;
/// Makes each new headless session from its automation roots.
pub type HeadlessMaker = Box<dyn Fn(Option<Arc<AutomationRoots>>) -> Headless + Send + Sync>;
/// What plain `deckcraft-cli mcp` needs to find the window.
pub struct LiveConfig {
/// The app's settings folder: connection file, token file and agent settings.
pub config_dir: PathBuf,
/// Reads the agent settings saved in a settings folder (`agents.json`).
pub read_settings: fn(&Path) -> AgentSettings,
/// Overrides the app's closed-app choice (`--when-closed`).
pub when_closed: Option<WhenAppClosed>,
/// Starts the app; `None` when this install can't.
pub launch: Option<shared::LaunchFn>,
pub launch_timeout: Duration,
/// Whether agents may use the app now ([`allowed_now`]); tests replace it.
pub allowed: fn() -> bool,
/// The default agent folder for an empty folder setting; tests replace it.
pub default_folder: Option<PathBuf>,
/// Makes each new headless session.
pub headless: HeadlessMaker,
}
impl LiveConfig {
/// The settings in `config_dir` as `read_settings` reads them, the launcher's switch, the
/// default agent folder, and a headless session with a new presentation.
pub fn new(config_dir: PathBuf, read_settings: fn(&Path) -> AgentSettings) -> Self {
Self {
config_dir,
read_settings,
when_closed: None,
launch: None,
launch_timeout: shared::LAUNCH_TIMEOUT,
allowed: allowed_now,
default_folder: craft::control::agents::default_folder(APP_NAME),
headless: Box::new(|roots| Headless::with_document().with_automation_roots(roots)),
}
}
}
/// Plain `deckcraft-cli mcp`: every call goes to the open window while the person lets agents use
/// it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup is
/// the shared `craft::automation::agents::Live`; a session that went headless stays headless.
pub struct LiveBackend {
live: shared::Live<SharedWindow, SharedHeadless>,
config_dir: PathBuf,
read_settings: fn(&Path) -> AgentSettings,
default_folder: Option<PathBuf>,
}
impl LiveBackend {
pub fn new(cfg: LiveConfig) -> Self {
let LiveConfig { config_dir, read_settings, when_closed, launch, launch_timeout, allowed, default_folder, headless } = cfg;
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
let connect = |w: &shared::Window| -> Result<SharedWindow, String> {
let mut window = Window::new(w.port, w.token.clone());
window.connect()?;
Ok(Arc::new(Mutex::new(window)))
};
let settings_dir = config_dir.clone();
let make_headless = move |wanted: &HeadlessFolders| -> Result<SharedHeadless, String> {
// No folders: unconfined only for plain `mcp` as it always ran, with agents not let in.
// A session for agents the person let in that has no agent folder may use no files.
let agents_in = || allowed() && read_settings(&settings_dir).allow_agent_control;
let roots = if wanted.read.is_empty() && wanted.write.is_none() {
agents_in().then(AutomationRoots::none)
} else {
let write: Vec<PathBuf> = wanted.write.iter().cloned().collect();
Some(AutomationRoots::new(&wanted.read, &write)?.unwrap_or_else(AutomationRoots::none))
};
Ok(Rc::new(RefCell::new(headless(roots))))
};
let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, make_headless);
shared_cfg.when_closed = when_closed;
shared_cfg.launch = launch;
shared_cfg.launch_timeout = launch_timeout;
shared_cfg.default_folder = default_folder.clone();
Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder }
}
/// The folders the open window lets agents use, as the window opens them.
fn window_folders(&self) -> Value {
folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref()))
}
}
impl Backend for LiveBackend {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
match self.live.resolve()? {
Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()),
Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
Route::Headless(h) => h.borrow_mut().call(method, params),
}
}
fn has_ui(&self) -> bool {
matches!(self.live.resolve(), Ok(Route::Window(_)))
}
fn describe(&self) -> String {
"the open DeckCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window".into()
}
}
#[cfg(test)]
mod tests;
-195
View File
@@ -1,195 +0,0 @@
//! Plain `mcp` in front of the open window: the window gets the calls only while agents are allowed
//! and it proves it holds the token; otherwise the closed-app choice applies.
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use craft::automation::agents::{AgentSettings, Connection, TOKEN_FILE, WhenAppClosed, write_connection};
use craft::automation::security::{AuthStep, ServerHandshake};
use serde_json::{Value, json};
use super::{FOLDERS_METHOD, LiveBackend, LiveConfig};
use crate::Backend;
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
/// A fresh folder for one test, removed when dropped.
struct TempFolder(PathBuf);
impl TempFolder {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("dc-mcp-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn file(&self, name: &str) -> PathBuf {
self.0.join(name)
}
}
impl Drop for TempFolder {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A stand-in for the window's control server holding `token`: it authenticates as the shared
/// server does and answers every request with `{"window": true, "method"}`. The count is of the
/// requests it got after authentication.
fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let served = Arc::new(AtomicUsize::new(0));
let count = served.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { return };
let count = count.clone();
std::thread::spawn(move || {
let mut writer = stream.try_clone().unwrap();
let mut handshake = ServerHandshake::new();
let mut signed_in = false;
for line in BufReader::new(stream).lines() {
let Ok(line) = line else { return };
let reply = if signed_in {
count.fetch_add(1, Ordering::SeqCst);
let req: Value = serde_json::from_str(&line).unwrap();
json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}})
} else {
let (reply, step) = handshake.reply(&line, token);
signed_in = matches!(step, AuthStep::Authenticated);
reply
};
if writeln!(writer, "{reply}").is_err() {
return;
}
}
});
}
});
(port, served)
}
/// Publishes a window on `port` in the settings folder `dir`, as the app's agents link does, with
/// [`TOKEN`] in its token file, readable by its owner only (the client refuses it otherwise).
fn publish(dir: &Path, port: u16) {
let token_file = dir.join(TOKEN_FILE);
std::fs::write(&token_file, TOKEN).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap();
}
write_connection(dir, &Connection::new(port, token_file, "DeckCraft test")).unwrap();
}
/// A port nothing listens on.
fn closed_port() -> u16 {
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
fn settings_headless(_: &Path) -> AgentSettings {
let mut s = AgentSettings::default();
s.when_app_closed = WhenAppClosed::Headless;
s
}
fn settings_error(_: &Path) -> AgentSettings {
let mut s = AgentSettings::default();
s.when_app_closed = WhenAppClosed::Error;
s
}
fn live(dir: &TempFolder, allowed: fn() -> bool, read_settings: fn(&Path) -> AgentSettings) -> LiveBackend {
let mut cfg = LiveConfig::new(dir.0.clone(), read_settings);
cfg.allowed = allowed;
cfg.default_folder = Some(dir.file("Agents"));
LiveBackend::new(cfg)
}
/// A canonical path as the automation roots show it: without Windows' `\\?\` prefix.
fn shown(p: PathBuf) -> String {
let s = p.to_string_lossy().into_owned();
s.strip_prefix(r"\\?\").map_or(s.clone(), str::to_owned)
}
#[test]
fn plain_mcp_reaches_the_window_while_agents_are_allowed() {
let dir = TempFolder::new("agents-window");
let (port, served) = fake_window(TOKEN);
publish(&dir.0, port);
let mut b = live(&dir, || true, settings_headless);
assert!(b.has_ui());
let r = b.call("document.inspect", json!({})).unwrap();
assert_eq!(r["window"], true, "{r}");
assert!(served.load(Ordering::SeqCst) >= 1);
// The window's folders are the agent folders as the window opens them: the default one here.
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy()));
assert_eq!(folders["write_folder"], folders["read_folder"]);
}
// With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless:
// the closed-app choice (an error here) is for agents the person let in.
#[test]
fn with_agents_off_plain_mcp_runs_headless() {
let dir = TempFolder::new("agents-off");
let mut b = live(&dir, || false, settings_error);
assert!(!b.has_ui());
let r = b.call("document.inspect", json!({}));
assert!(r.as_ref().is_ok_and(|r| r["window"] != true), "{r:?}");
assert_eq!(b.call(FOLDERS_METHOD, json!({})).unwrap()["unrestricted"], true);
assert!(!dir.file("Agents").exists(), "the agent folder is made only for agents the person let in");
}
#[test]
fn a_window_that_cannot_prove_the_token_gets_nothing() {
let dir = TempFolder::new("agents-bad-token");
let (port, served) = fake_window("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
publish(&dir.0, port);
let mut b = live(&dir, || true, settings_headless);
let e = b.call("document.inspect", json!({})).unwrap_err();
assert!(e.contains("could not prove"), "{e}");
assert_eq!(served.load(Ordering::SeqCst), 0);
}
#[test]
fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() {
let dir = TempFolder::new("agents-stale");
publish(&dir.0, closed_port());
let mut b = live(&dir, || true, settings_error);
let e = b.call("document.inspect", json!({})).unwrap_err();
assert!(e.contains("isn't running"), "{e}");
// Headless: a session without a window, confined to the agent folders.
let mut b = live(&dir, || true, settings_headless);
assert!(!b.has_ui());
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
assert_eq!(folders["read_folder"], json!(std::fs::canonicalize(dir.file("Agents")).map(shown).unwrap()));
let outside = dir.file("outside.deckcraft");
std::fs::write(&outside, b"not a deck").unwrap();
let e = b.call("engine.execute", json!({"command": "file.open", "params": {"path": outside.to_string_lossy()}})).unwrap_err();
assert!(e.contains("outside the read roots"), "{e}");
}
// Agents the person let in never get an unconfined session: with no agent folder at all (no
// default one either), the headless session may use no files.
#[test]
fn an_agent_session_without_any_folder_may_use_no_files() {
let dir = TempFolder::new("agents-no-folder");
let mut cfg = LiveConfig::new(dir.0.clone(), settings_headless);
cfg.allowed = || true;
cfg.default_folder = None;
let mut b = LiveBackend::new(cfg);
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
assert_ne!(folders["unrestricted"], true, "{folders}");
let outside = dir.file("outside.deckcraft");
std::fs::write(&outside, b"not a deck").unwrap();
let e = b.call("engine.execute", json!({"command": "file.open", "params": {"path": outside.to_string_lossy()}})).unwrap_err();
assert!(e.contains("not granted"), "{e}");
}
-6
View File
@@ -57,12 +57,6 @@ impl Remote {
#[cfg(not(target_arch = "wasm32"))]
impl Backend for Remote {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
if method == crate::headless::FOLDERS_METHOD {
return Err(format!(
"the app at {} was started with --control, so agent folders don't apply: nothing confines the files it opens and saves",
self.addr
));
}
// Replacing an unusable connection before sending cannot replay a mutation.
if self.client.as_ref().is_none_or(|client| !client.is_usable()) {
self.client = None;
+5 -33
View File
@@ -20,36 +20,9 @@ impl Default for Headless {
}
}
/// The method the `agent_folders` tool calls: the folders this session's file commands may use.
pub const FOLDERS_METHOD: &str = "agent.folders";
/// What a tool that needs the window says in a session without one.
pub const NEEDS_WINDOW: &str = "it needs the open DeckCraft window: open DeckCraft with AI agents on (ArtCraft Launcher › Settings › AI agents) \
and run `deckcraft-cli mcp` without --headless";
/// The `agent_folders` answer of a headless session confined to `roots` (`None`: not confined):
/// `read_folder` and `write_folder`, each a path or `null`. With more than one folder of a kind
/// (`--automation-read-root` given twice), `read_folders` / `write_folders` list them all.
pub(crate) fn headless_folders(roots: Option<&AutomationRoots>) -> Value {
let Some(roots) = roots else {
// A session started without automation roots (`--headless` without them, or with the
// agents switch off) isn't confined: say so rather than claim it has no folders.
return json!({
"read_folder": null,
"write_folder": null,
"unrestricted": true,
"note": "This session was started without automation roots: its file commands open and save wherever the user can.",
});
};
let shown = |p: &std::path::Path| p.to_string_lossy().into_owned();
let (read, write): (Vec<String>, Vec<String>) = (roots.read_roots().map(shown).collect(), roots.write_roots().map(shown).collect());
let mut answer = json!({"read_folder": read.first(), "write_folder": write.first()});
for (key, all) in [("read_folders", &read), ("write_folders", &write)] {
if all.len() > 1 {
answer[key] = json!(all);
}
}
answer
}
/// Hint appended to errors for methods that need a window.
pub(crate) const NEEDS_APP: &str = "it needs the desktop app: start `deckcraft --control 7979 --control-token-file PATH` and run the MCP server \
with `deckcraft-cli mcp --connect 7979 --control-token-file PATH`";
fn s<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
p.get(k).and_then(Value::as_str)
@@ -108,7 +81,7 @@ impl Headless {
fn exec(&mut self, id: &str, params: &Value) -> Result<Value, String> {
let r = self.session.execute(id, params).map_err(|e| {
let ui_only = ["app.", "view.", "window.", "ui."].iter().any(|p| id.starts_with(p));
if ui_only && deckcraft_engine::find_command(id).is_none() { format!("`{id}` is a UI command; {NEEDS_WINDOW}") } else { e.to_string() }
if ui_only && deckcraft_engine::find_command(id).is_none() { format!("`{id}` is a UI command; {NEEDS_APP}") } else { e.to_string() }
});
self.session.ui_requests.clear();
r
@@ -200,8 +173,7 @@ impl Headless {
"app.save" => self.exec("file.save", p),
"app.export" => self.exec("file.export", p),
"ui.inspect" => Ok(json!({"headless": true, "tool": serde_json::to_value(&self.session.tool.kind).unwrap_or_default()})),
FOLDERS_METHOD => Ok(headless_folders(self.roots.as_deref())),
m if m.starts_with("ui.") || m.starts_with("app.") => Err(format!("`{m}`: {NEEDS_WINDOW}")),
m if m.starts_with("ui.") || m.starts_with("app.") => Err(format!("`{m}`: {NEEDS_APP}")),
other => Err(format!("unknown method `{other}`")),
}
}
+3 -9
View File
@@ -4,13 +4,9 @@
//! JSON-RPC 2.0, hand-written (no async runtime). The server exposes DeckCraft as a set of MCP
//! tools and resources and forwards everything to a [`Backend`]:
//!
//! - `agents::LiveBackend` (plain `deckcraft-cli mcp`) sends each call to the open window while the
//! ArtCraft Launcher's switch lets agents use DeckCraft, through the connection file the window
//! publishes (`agents::Window`), and otherwise to a [`Headless`] session.
//! - `Remote` authenticates with a running desktop app's per-launch token through the framework's
//! JSON-lines control client (`deckcraft-cli mcp --connect`, deprecated). Start the app with
//! `deckcraft --control 7979 --control-token-file PATH` and pass that file to the client with
//! `--control-token-file PATH` (see `docs/control-protocol.md`).
//! JSON-lines control client. Start the app with `deckcraft --control 7979 --control-token-file PATH`
//! and pass that file to the client with `--control-token-file PATH` (see `docs/control-protocol.md`).
//! - [`Headless`] hosts an in-process [`deckcraft_engine::Session`] and implements the
//! engine-level control-channel methods itself (rendering pages with `deckcraft-render`), so
//! agents can build layouts and look at them without a window.
@@ -19,8 +15,6 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(not(target_arch = "wasm32"))]
pub mod agents;
mod backend;
mod headless;
mod server;
@@ -29,7 +23,7 @@ mod tools;
pub use backend::Backend;
#[cfg(not(target_arch = "wasm32"))]
pub use backend::Remote;
pub use headless::{FOLDERS_METHOD, Headless, NEEDS_WINDOW};
pub use headless::Headless;
pub use server::{PROTOCOL_VERSION, Server};
pub use tools::{ToolResult, call_tool, tool_definitions};
-30
View File
@@ -271,36 +271,6 @@ fn export_tool_lists_pdf_and_its_options() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn export_tool_lists_txt_and_writes_crlf() {
let mut s = Server::new(Box::new(Headless::new()));
let tools = call(&mut s, 1, "tools/list", json!({}));
let export = tools["result"]["tools"].as_array().unwrap().iter().find(|t| t["name"] == "export").unwrap().clone();
let props = &export["inputSchema"]["properties"];
let formats = props["format"]["enum"].as_array().unwrap();
for f in ["outline", "txt"] {
assert!(formats.iter().any(|x| x == f), "format {f}: {export}");
}
// What the schema lists is accepted: `txt` is the outline with CRLF line ends.
let dir = std::env::temp_dir().join(format!("deckcraft-mcp-txt-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
tool(&mut s, "new_presentation", json!({}));
tool(&mut s, "add_slide", json!({"layout": "titleAndContent", "title": "Alpha heading", "body": "First body"}));
let path = dir.join("deck.txt");
tool(&mut s, "export", json!({"path": path.to_string_lossy(), "format": "txt"}));
let text = String::from_utf8(std::fs::read(&path).unwrap()).unwrap();
assert!(text.contains("\r\n"), "txt must use CRLF: {text:?}");
assert!(!text.replace("\r\n", "").contains('\n'), "no bare LF: {text:?}");
assert!(text.contains("Alpha heading"), "{text:?}");
// The outline reads back into the slides it was written from.
tool(&mut s, "open_presentation", json!({"path": path.to_string_lossy()}));
let reopened = tool(&mut s, "inspect_document", json!({}));
let titles: Vec<&str> = reopened["slides"].as_array().unwrap().iter().filter_map(|sl| sl["title"].as_str()).collect();
assert!(titles.contains(&"Alpha heading"), "{titles:?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn export_rejects_unknown_format() {
let mut s = Server::new(Box::new(Headless::new()));
+5 -13
View File
@@ -4,7 +4,7 @@
use serde_json::{Value, json};
use crate::backend::Backend;
use crate::headless::NEEDS_WINDOW;
use crate::headless::NEEDS_APP;
/// The result of `tools/call`: MCP content blocks plus the `isError` flag.
#[derive(Clone, Debug, PartialEq)]
@@ -60,13 +60,7 @@ fn tool(name: &str, title: &str, desc: &str, schema: Value, read_only: bool) ->
json!({"name": name, "title": title, "description": desc, "inputSchema": schema, "annotations": {"title": title, "readOnlyHint": read_only, "openWorldHint": false}})
}
/// The `agent_folders` tool's description: the suite's own words on the desktop.
#[cfg(not(target_arch = "wasm32"))]
const FOLDERS_DESCRIPTION: &str = craft::control::agents::FOLDERS_TOOL_DESCRIPTION;
#[cfg(target_arch = "wasm32")]
const FOLDERS_DESCRIPTION: &str = "Where this session opens and saves files for agents (read_folder, write_folder; null for none).";
const APP_ONLY: &str = " Needs the open DeckCraft window (AI agents on in ArtCraft Launcher › Settings › AI agents).";
const APP_ONLY: &str = " Desktop app only (`deckcraft-cli mcp --connect PORT`).";
pub fn tool_definitions() -> Vec<Value> {
vec![
@@ -121,11 +115,11 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"export",
"Export",
"Export slides: png/jpeg (one slide, or all with all:true), pptx, deckcraft, outline text (outline, or txt with CRLF), pdf (slides, notes pages or handouts), or an animated gif of the deck (one frame per slide).",
"Export slides: png/jpeg (one slide, or all with all:true), pptx, deckcraft, outline text, pdf (slides, notes pages or handouts), or an animated gif of the deck (one frame per slide).",
obj(
json!({
"path": string("Output path"),
"format": {"type": "string", "enum": ["png", "jpeg", "pptx", "deckcraft", "outline", "txt", "rtf", "pdf", "gif"], "description": "Output format (default: from the path's extension)"},
"format": {"type": "string", "enum": ["png", "jpeg", "pptx", "deckcraft", "outline", "rtf", "pdf", "gif"], "description": "Output format (default: from the path's extension)"},
"slide": int("Slide index for images"),
"all": boolean("All slides (images)"),
"scale": num("Pixels per point for images (default 2)"),
@@ -293,7 +287,6 @@ pub fn tool_definitions() -> Vec<Value> {
obj(json!({"method": string("Method"), "params": {"type": "object"}}), &["method"]),
false,
),
tool("agent_folders", "Agent folders", FOLDERS_DESCRIPTION, obj(json!({}), &[]), true),
]
}
@@ -488,7 +481,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, a: &Value) -> ToolResult {
"type_text" => wrap(b.call("engine.text", a)),
"screenshot" => {
if !b.has_ui() {
return ToolResult::error(format!("screenshot: {NEEDS_WINDOW}. Use render_slide to see a slide headlessly."));
return ToolResult::error(format!("screenshot: {NEEDS_APP}. Use render_slide to see a slide headlessly."));
}
match b.call("ui.screenshot", json!({})) {
Ok(v) => match v.get("base64").and_then(Value::as_str) {
@@ -502,7 +495,6 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, a: &Value) -> ToolResult {
let Some(m) = a.get("method").and_then(Value::as_str) else { return ToolResult::error("missing `method`") };
wrap(b.call(m, a.get("params").cloned().unwrap_or(json!({}))))
}
"agent_folders" => wrap(b.call(crate::headless::FOLDERS_METHOD, json!({}))),
other => ToolResult::error(format!("unknown tool `{other}`")),
}
}
+4 -5
View File
@@ -81,10 +81,10 @@ pub fn decode(bytes: &Bytes) -> Result<Pcm> {
Some(r) => r,
None => contained(|| decode_symphonia(bytes, "mkv")),
},
c => {
crate::mp4guard::check(c, bytes)?;
contained(|| decode_symphonia(bytes, c.name()))
Container::Mp4 | Container::Unknown | Container::Mp3 if !crate::mp4guard::probe_fits(bytes) => {
Err(MediaError::Corrupt("the MP4's sample tables do not fit the file".into()))
}
c => contained(|| decode_symphonia(bytes, c.name())),
}
}
@@ -297,8 +297,7 @@ pub(crate) fn probe_symphonia(bytes: &Bytes, ext: &str) -> Option<(String, u32,
}
/// Length in milliseconds of the track playback decodes, summed from its packet durations: the
/// file is demuxed but not decoded. `None` when the demuxer reports no durations. Callers must
/// pass [`crate::mp4guard::check`] first: the demuxer reads each sample whole at its `stsz` size.
/// file is demuxed but not decoded. `None` when the demuxer reports no durations.
pub(crate) fn demux_duration_ms(bytes: &Bytes, ext: &str) -> Option<u64> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default());
-11
View File
@@ -35,17 +35,6 @@ pub(crate) fn probe_fits(b: &[u8]) -> bool {
}
}
/// The check every path into symphonia's demuxer runs first: `Corrupt` when symphonia would read
/// `b` (sniffed as `c`) as an MP4 whose tables do not fit the file. Other known containers skip
/// it (a WAV's audio bytes can spell an `ftyp`, but symphonia opens it as a WAV).
pub(crate) fn check(c: crate::Container, b: &[u8]) -> crate::Result<()> {
use crate::Container;
if matches!(c, Container::Mp4 | Container::Unknown | Container::Mp3) && !probe_fits(b) {
return Err(crate::MediaError::Corrupt("the MP4's sample tables do not fit the file".into()));
}
Ok(())
}
use craft_media::isobmff::boxes::BoxIter;
fn be32(b: &[u8], at: usize) -> Option<u64> {
+5 -7
View File
@@ -52,11 +52,7 @@ pub fn probe(bytes: &Bytes) -> Result<MediaInfo> {
if info.duration_ms == 0 && info.audio.as_ref().is_some_and(|a| a.decodable) && info.video.is_none() {
// No length in the header (raw MP3 / ADTS without an index): add up the packet
// lengths. This only demuxes, so a long file neither allocates its PCM nor stalls the caller.
// Our MP4 parser can describe a track whose `stsz` claims a sample symphonia would read
// whole, so the tables are checked first here too.
let c = Container::sniff(bytes);
crate::mp4guard::check(c, bytes)?;
if let Some(d) = crate::audio::demux_duration_ms(bytes, c.name()) {
if let Some(d) = crate::audio::demux_duration_ms(bytes, Container::sniff(bytes).name()) {
info.duration_ms = d;
}
}
@@ -76,8 +72,10 @@ pub fn probe_headers(bytes: &Bytes) -> Result<MediaInfo> {
};
if info.audio.is_none() && info.video.is_none() || info.audio.as_ref().is_some_and(|a| a.sample_rate == 0) {
// Plain audio files (and anything our demuxers didn't describe): symphonia's probe.
// Symphonia opens an MP4 wherever its probe finds an `ftyp` (after leading ID3v2 tags too).
crate::mp4guard::check(c, bytes)?;
// Symphonia opens an MP4 wherever its probe finds an `ftyp` (after leading ID3v2 tags too); other known containers (a WAV's audio bytes can spell an `ftyp`) skip the check.
if matches!(c, Container::Mp4 | Container::Unknown | Container::Mp3) && !crate::mp4guard::probe_fits(bytes) {
return Err(MediaError::Corrupt("the MP4's sample tables do not fit the file".into()));
}
let (codec, rate, channels, frames) = std::panic::catch_unwind(|| crate::audio::probe_symphonia(bytes, c.name()))
.ok()
.flatten()
-26
View File
@@ -434,29 +434,3 @@ fn mp4_sample_tables_that_overrun_the_file_are_corrupt() {
assert!(audio::decode(&fixture(name)).is_ok() || name.starts_with("clip"), "{name} still decodes");
}
}
/// `stsz-size.m4a` with its mvhd, tkhd and mdhd durations zeroed: `probe_headers` describes the
/// AAC track but finds no length, so `probe` demuxes it. The 4 GB sample must not reach symphonia.
#[test]
fn probe_rejects_damaged_stsz_without_header_duration() {
let mut b = fixture("damaged/stsz-size.m4a").to_vec();
// The duration fields of mvhd, tkhd and mdhd (all version 0).
for at in [4538, 4658, 4790] {
b[at..at + 4].copy_from_slice(&[0; 4]);
}
let b: Bytes = Arc::new(b);
let head = probe::probe_headers(&b).expect("our MP4 parser still accepts the file");
assert_eq!(head.duration_ms, 0);
assert!(head.audio.as_ref().is_some_and(|a| a.decodable && a.sample_rate > 0));
assert!(matches!(probe::probe(&b), Err(MediaError::Corrupt(_))), "probe must reject the damaged sample table");
// Control: the intact file with the same fields zeroed takes the same demux path, and the
// table check must let it through, with the length coming from the demux.
let mut intact = fixture("tone.m4a").to_vec();
for at in [4538, 4658, 4790] {
intact[at..at + 4].copy_from_slice(&[0; 4]);
}
let intact: Bytes = Arc::new(intact);
assert_eq!(probe::probe_headers(&intact).expect("headers parse").duration_ms, 0, "the header gives no length");
let info = probe::probe(&intact).expect("an intact MP4 without a header duration still probes");
assert!(info.duration_ms > 0, "the demux still finds a length");
}
+15 -39
View File
@@ -376,15 +376,18 @@ Then wave"
);
}
/// A text box holding `n` one-character formatting runs (a character and a line break, alternating),
/// as a legacy .ppt file.
fn file_with_character_runs(n: usize) -> Vec<u8> {
let text: String = (0..n).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect();
/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to
/// scan the run starts from the beginning, so the cost grew with runs²: in a debug build these 640k
/// one-character runs (about 6 MB of file) took 75 s that way, and take about 2 s with binary search.
#[test]
fn many_character_runs_are_not_quadratic() {
const N: usize = 640_000;
let text: String = (0..N).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect();
let mut style = vec![];
style.extend_from_slice(&(n as u32 + 1).to_le_bytes());
style.extend_from_slice(&(N as u32 + 1).to_le_bytes());
style.extend_from_slice(&0u16.to_le_bytes());
style.extend_from_slice(&0u32.to_le_bytes()); // a paragraph exception with no fields
for _ in 0..=n {
for _ in 0..=N {
style.extend_from_slice(&1u32.to_le_bytes());
style.extend_from_slice(&0u32.to_le_bytes()); // a character exception with no fields
}
@@ -395,39 +398,12 @@ fn file_with_character_runs(n: usize) -> Vec<u8> {
);
let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[shape])]);
let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None);
crate::cfb::build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])
}
/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to
/// scan the run starts from the beginning, so the cost grew with runs²: 640k one-character runs
/// (about 6 MB of file) took 75 s that way in a debug build, and about 2 s with binary search.
///
/// The test compares two sizes in the same process instead of timing one against a fixed limit, so
/// a slow or busy host (the FreeBSD CI VM took 20 to 31 s for the 640k file, mostly in the kernel,
/// where a quiet one takes 2 s) slows both alike. Four times the runs take about four times as long
/// when the work is linear and sixteen times as long when it is quadratic. Each size is the best of
/// three imports, so a stall in one of them doesn't decide the result.
#[test]
fn many_character_runs_are_not_quadratic() {
const SMALL: usize = 40_000;
const LARGE: usize = 4 * SMALL;
let best_of_three = |n: usize| {
let bytes = file_with_character_runs(n);
let mut best = std::time::Duration::MAX;
let mut breaks = 0;
for _ in 0..3 {
let t = std::time::Instant::now();
let p = crate::import(&bytes).unwrap();
best = best.min(t.elapsed());
let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs;
breaks = runs.iter().filter(|r| r.kind == RunKind::Break).count();
}
(best, breaks)
};
let (small, small_breaks) = best_of_three(SMALL);
let (large, large_breaks) = best_of_three(LARGE);
assert_eq!((small_breaks, large_breaks), (SMALL / 2, LARGE / 2));
assert!(large < small * 10, "{LARGE} runs took {large:?}, {SMALL} runs took {small:?}: more than 10x for 4x the runs");
let bytes = crate::cfb::build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]);
let t = std::time::Instant::now();
let p = crate::import(&bytes).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());
let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs;
assert_eq!(runs.iter().filter(|r| r.kind == RunKind::Break).count(), N / 2);
}
/// A slide naming a master that doesn't exist falls back to the first main master, every time. The
-69
View File
@@ -1175,72 +1175,3 @@ mod shape_owner_scoping_tests {
assert!(patched.contains(r#"fmla="val 3000000000""#), "child id=11 should be patched: {patched}");
}
}
#[cfg(test)]
mod group_fill_roundtrip_tests {
use std::io::Read;
use deckcraft_model::style::{Fill, PictureFill, PictureMode};
use deckcraft_model::{Shape, ShapeId, ShapeKind, Xfrm, defaults};
use std::sync::Arc;
#[test]
fn group_picture_fill_survives_a_pptx_round_trip() {
// Regression coverage for #1798: the group's own picture fill (a:blipFill in its p:grpSpPr)
// and its members' grpFill markers (a:grpFill in each member's p:spPr) must survive a
// save/reload unchanged. The media bytes are opaque to the round trip; the PNG signature
// is enough for the content type.
let mut p = defaults::new_presentation(None);
let png = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
let media = p.add_media("t.png", "image/png", png.clone()).expect("media");
let member =
|id: u32, x: f64| Shape { id: ShapeId(id), xfrm: Some(Xfrm::new(x, 0.0, 120.0, 60.0)), fill: Some(Fill::Group), ..Default::default() };
let group = Shape {
id: ShapeId(21),
xfrm: Some(Xfrm::new(100.0, 100.0, 240.0, 60.0)),
fill: Some(Fill::Picture(PictureFill { media, mode: PictureMode::Stretch { fill_rect: [0.0; 4] }, ..Default::default() })),
kind: ShapeKind::Group { children: vec![member(22, 0.0), member(23, 120.0)], child: Xfrm::new(0.0, 0.0, 240.0, 60.0) },
..Default::default()
};
Arc::make_mut(&mut p.slides[0]).shapes.push(group);
let bytes = crate::export(&p).expect("export");
// The markers themselves must be in the exported slide XML, not only in the
// reimported model: an exporter writing a:noFill for the members could still
// pass the round trip below if the importer reconstructed Fill::Group for them.
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).expect("exported package");
let mut xml = String::new();
z.by_name("ppt/slides/slide1.xml").expect("slide part").read_to_string(&mut xml).expect("slide xml");
// Inspect the markers through the parsed XML tree, scoped to the group's
// direct children: string splitting on exact tag spellings would miss a
// member whose p:sp tag gained an attribute, and a slice running to the
// end of the slide would count a later sibling shape as a member. The
// slide's own root grpSpPr and its layout placeholders are not inside
// the group element, so they cannot be mistaken for its fills.
let doc = crate::parse_xml(xml.as_bytes()).expect("the slide XML parses");
let sp_tree = doc.root.path(&["cSld", "spTree"]).expect("the slide has a spTree");
let grp = sp_tree.children_named("grpSp").next().expect("the group is written as a grpSp child of the spTree");
let grp_sp_pr = grp.child("grpSpPr").expect("the group's grpSpPr");
assert!(grp_sp_pr.child("blipFill").is_some(), "the group's picture fill is a:blipFill in its grpSpPr: {}", grp_sp_pr.to_xml());
assert!(grp_sp_pr.child("grpFill").is_none(), "the group's grpSpPr carries no a:grpFill: {}", grp_sp_pr.to_xml());
let members: Vec<_> = grp.children_named("sp").collect();
assert_eq!(members.len(), 2, "both members are direct p:sp children of the group: {xml}");
for m in &members {
let sp_pr = m.child("spPr").expect("a member's spPr");
assert!(sp_pr.child("grpFill").is_some(), "each member's spPr carries a:grpFill: {}", sp_pr.to_xml());
}
let rt = crate::import(&bytes).expect("import");
let g = rt.slides[0].shapes.iter().find(|s| matches!(s.kind, ShapeKind::Group { .. })).expect("the group survives");
let Some(Fill::Picture(pic)) = &g.fill else { panic!("the group keeps its picture fill, got {:?}", g.fill) };
assert!(matches!(pic.mode, PictureMode::Stretch { .. }), "the fill stays a stretch, not a tile");
let item = rt.media.iter().find(|m| m.id == pic.media).expect("the media the fill names");
assert_eq!(*item.data, png, "the media bytes survive the round trip");
if let ShapeKind::Group { children, .. } = &g.kind {
assert_eq!(children.len(), 2, "both members survive");
assert!(
children.iter().all(|c| c.fill == Some(Fill::Group)),
"the members keep grpFill: {:?}",
children.iter().map(|c| &c.fill).collect::<Vec<_>>()
);
}
}
}
+5 -18
View File
@@ -14,35 +14,22 @@ const MAX_DEPTH: usize = 64;
/// Fills and gradient stops one colour glyph may paint; the rest of a hostile glyph is skipped.
const MAX_WORK: usize = 100_000;
pub(super) struct Colors {
/// Text colour (palette index 0xFFFF), already desaturated if needed.
pub foreground: Rgba,
pub opacity: f64,
/// Desaturate the embedded palette colours by the same amount as the text colour.
pub desaturation: f64,
}
/// Paint `gid` of `face` as a colour glyph, its origin mapped by `at` (y down, points) at `scale`
/// points per font unit.
/// points per font unit. `fg` is the text colour (palette index 0xFFFF) and `alpha` fades it all.
/// False when the glyph has no colour version, so the caller draws the plain outline.
pub(super) fn paint(ctx: &mut RenderContext, face: &FontFace, gid: u32, at: Affine, scale: f64, colors: Colors) -> bool {
pub fn paint(ctx: &mut RenderContext, face: &FontFace, gid: u32, at: Affine, scale: f64, fg: Rgba, alpha: f64) -> bool {
let Some(font) = face.skrifa() else { return false };
let glyphs = font.color_glyphs();
let Some(glyph) = glyphs.get(GlyphId::new(gid)) else { return false };
let mut palette: Vec<Rgba> = font
let palette: Vec<Rgba> = font
.color_palettes()
.get(0)
.map(|p| p.colors().iter().map(|c| Rgba { r: c.red, g: c.green, b: c.blue, a: c.alpha }).collect())
.unwrap_or_default();
if colors.desaturation > 0.0 {
for color in &mut palette {
*color = deckcraft_anim::desaturate_color(*color, colors.desaturation);
}
}
// Font units are y up; the slide is y down.
let base = at * Affine::scale(scale) * Affine::scale_non_uniform(1.0, -1.0);
let mut p = Painter { ctx, face, base, stack: vec![Affine::IDENTITY], palette, fg: colors.foreground, opened: Vec::new(), work: 0 };
p.ctx.push_layer(None, None, Some(colors.opacity.clamp(0.0, 1.0) as f32), None, None);
let mut p = Painter { ctx, face, base, stack: vec![Affine::IDENTITY], palette, fg, opened: Vec::new(), work: 0 };
p.ctx.push_layer(None, None, Some(alpha.clamp(0.0, 1.0) as f32), None, None);
let ok = glyph.paint(face.location(), &mut p).is_ok();
// A malformed glyph may leave layers open: close them all.
while let Some(open) = p.opened.pop() {
+2 -42
View File
@@ -13,41 +13,13 @@ pub struct ShapeState {
pub clip: Option<[f64; 4]>,
/// Colour override for emphasis effects (fill).
pub tint: Option<Rgba>,
/// Fraction by which to reduce the saturation of the text colours.
pub text_desaturation: f64,
/// Per-paragraph states of by-paragraph text builds (paragraph index, state).
pub paras: Vec<(usize, ParaState)>,
}
impl Default for ShapeState {
fn default() -> Self {
ShapeState {
visible: true,
opacity: 1.0,
offset: Vec2::ZERO,
scale: (1.0, 1.0),
rotate: 0.0,
clip: None,
tint: None,
text_desaturation: 0.0,
paras: vec![],
}
}
}
impl From<deckcraft_anim::AnimState> for ShapeState {
fn from(state: deckcraft_anim::AnimState) -> Self {
ShapeState {
visible: state.visible,
opacity: state.opacity,
offset: Vec2::new(state.offset_x, state.offset_y),
scale: (state.scale_x, state.scale_y),
rotate: state.rotate,
clip: state.clip,
tint: state.tint,
text_desaturation: state.text_desaturation,
paras: Vec::new(),
}
ShapeState { visible: true, opacity: 1.0, offset: Vec2::ZERO, scale: (1.0, 1.0), rotate: 0.0, clip: None, tint: None, paras: vec![] }
}
}
@@ -58,23 +30,11 @@ pub struct ParaState {
pub opacity: f64,
/// Translation in shape-local points.
pub offset: Vec2,
pub text_desaturation: f64,
}
impl Default for ParaState {
fn default() -> Self {
ParaState { visible: true, opacity: 1.0, offset: Vec2::ZERO, text_desaturation: 0.0 }
}
}
impl From<deckcraft_anim::AnimState> for ParaState {
fn from(state: deckcraft_anim::AnimState) -> Self {
ParaState {
visible: state.visible,
opacity: state.opacity,
offset: Vec2::new(state.offset_x, state.offset_y),
text_desaturation: state.text_desaturation,
}
ParaState { visible: true, opacity: 1.0, offset: Vec2::ZERO }
}
}
+2 -5
View File
@@ -5,9 +5,7 @@ use super::opts::{RenderOpts, ShapeState, SlideFields};
use super::raster::Image;
use super::slide::{SlidePart, needs_filters, output_size};
use super::stroke::{arrowheads, head_trims, stroke, trim_ends};
use super::text_draw::{
desaturate_layout, draw_animated_layout, draw_text, line_bounds, preview_empty_bullets, prompt_body, text_transform, text_warp,
};
use super::text_draw::{draw_layout_with, draw_text, line_bounds, preview_empty_bullets, prompt_body, text_transform, text_warp};
use super::*;
pub struct Renderer {
@@ -1094,7 +1092,6 @@ impl Renderer {
if editing {
preview_empty_bullets(&mut l);
}
desaturate_layout(&mut l, st, rctx);
let tm = text_transform(m, tr, l.rotation);
for b in l.lines.iter().filter_map(line_bounds) {
// Glyphs reach a little past their carets and line box (italics, swashes).
@@ -1103,7 +1100,7 @@ impl Renderer {
}
match text_warp(rctx, s, tr).filter(|_| l.rotation == 0.0) {
Some(w) => warp::draw(ctx, &l, tr, m, &st.paras, &w),
None => draw_animated_layout(ctx, &l, tr, m, &st.paras, st.text_desaturation),
None => draw_layout_with(ctx, &l, tr, m, &st.paras),
}
} else if f.opts.edit && s.ph.is_some() {
let kind = s.ph_type().unwrap_or(PhType::Body);
-50
View File
@@ -686,48 +686,6 @@ fn text_shape(id: u32, text: &str, x: f64, y: f64) -> Shape {
Shape { id: ShapeId(id), xfrm: Some(Xfrm::new(x, y, 600.0, 120.0)), text_box: true, text: Some(t), ..Default::default() }
}
#[test]
fn desaturate_grays_text_box_runs_without_recoloring_the_fill() {
use deckcraft_model::{AnimClass, Animation};
let mut sh = text_shape(2, "MM", 80.0, 80.0);
let id = sh.id;
let yellow = Rgba::rgb(255, 212, 32);
sh.fill = Some(Fill::solid(ColorRef::rgb(yellow)));
let runs = &mut sh.text.as_mut().unwrap().paragraphs[0].runs;
let mut next = runs[0].clone();
next.text = "M".into();
next.props.fill = Some(Fill::solid(ColorRef::rgb(Rgba::rgb(0, 0, 220))));
runs[0].text = "M".into();
runs[0].props.fill = Some(Fill::solid(ColorRef::rgb(Rgba::rgb(220, 0, 0))));
runs.push(next);
let mut p = deck_with(vec![sh]);
std::sync::Arc::make_mut(&mut p.slides[0]).animations.push(Animation {
shape: id,
class: AnimClass::Emphasis,
effect: "desaturate".into(),
duration_ms: 500,
..Default::default()
});
let timeline = deckcraft_anim::Timeline::new(&p.slides[0], p.slide_size.width, p.slide_size.height);
let at_end = |id| ShapeState::from(timeline.state_at(id, None, 1.0));
let before = render_slide(&p, 0, &RenderOpts::default());
let after = render_slide(&p, 0, &RenderOpts { state: Some(&at_end), ..Default::default() });
assert_eq!(after.pixel(400, 140), before.pixel(400, 140), "text-box fill");
let gray = |ink| {
before
.pixels
.as_chunks::<4>()
.0
.iter()
.zip(after.pixels.as_chunks::<4>().0)
.find_map(|(source, target)| (source[..3] == ink && target[0] == target[1] && target[1] == target[2]).then_some(target[0]))
};
let red = gray([220, 0, 0]).expect("the red glyph is gray");
let blue = gray([0, 0, 220]).expect("the blue glyph is gray");
assert!(red > blue, "the two glyphs keep their relative luminance");
}
#[test]
fn morph_text_tokens_are_words_or_characters() {
let p = Presentation::default();
@@ -1222,14 +1180,6 @@ fn colour_glyphs_paint_their_layers() {
assert!((share - 0.16).abs() < 0.03, "blue share {share}");
// The text-colour glyph is as big as the other square.
assert!((green as f64 / (red + blue) as f64 - 1.0).abs() < 0.1, "green {green} vs {}", red + blue);
let desaturate = |_: ShapeId| ShapeState { text_desaturation: 1.0, ..Default::default() };
let gray = render_slide(&p, 0, &RenderOpts { state: Some(&desaturate), ..Default::default() });
let layers = img.pixels.as_chunks::<4>().0.iter().zip(gray.pixels.as_chunks::<4>().0);
for rgb in [[255, 0, 0], [0, 0, 255], [0, 160, 0]] {
let (before, after) = layers.clone().find(|(px, _)| px[..3] == rgb).expect("the source colour is visible");
assert!(after[0] == after[1] && after[1] == after[2] && after[0] < 255, "the glyph colour {before:?} becomes gray: {after:?}");
}
}
#[test]
-32
View File
@@ -339,38 +339,6 @@ fn children_filled_with_the_group_fill_show_one_fill_across_the_group() {
assert!(close(img.pixel(200, 150), WHITE, 5), "the gap between the children stays empty");
}
#[test]
fn a_stretched_picture_on_a_group_spans_the_group_not_each_member() {
use deckcraft_model::style::{PictureFill, PictureMode};
// Regression coverage for #1798: a picture fill set on the group itself is resolved once
// against the group's bounds, and members filled with grpFill show their slice of that one
// image — not a copy of the whole picture in each member.
let mut p = Presentation::default();
let media = p.add_media("t.png", "image/png", half_red_half_blue()).expect("media");
let member = |id: u32, x: f64| Shape {
id: ShapeId(id),
xfrm: Some(Xfrm::new(x, 0.0, 120.0, 60.0)),
fill: Some(Fill::Group),
line: no_line(),
..Default::default()
};
let g = Shape {
id: ShapeId(31),
xfrm: Some(Xfrm::new(100.0, 100.0, 240.0, 60.0)),
fill: Some(Fill::Picture(PictureFill { media, mode: PictureMode::Stretch { fill_rect: [0.0; 4] }, ..Default::default() })),
kind: ShapeKind::Group { children: vec![member(32, 0.0), member(33, 120.0)], child: Xfrm::new(0.0, 0.0, 240.0, 60.0) },
..Default::default()
};
std::sync::Arc::make_mut(&mut p.slides[0]).shapes = vec![g];
let img = render_slide(&p, 0, &RenderOpts { scale: 1.0, ..Default::default() });
let blue = Rgba::rgb(0, 0, 255);
// The samples sit where the two readings disagree: had each member stretched its own
// copy, the left member would turn blue at x=160 and the right member would start red
// until x=280; under one mapping across the group, the turn is at the group's middle.
assert!(close(img.pixel(190, 130), RED, 30), "the left member is still in the picture's left half: {:?}", img.pixel(190, 130));
assert!(close(img.pixel(250, 130), blue, 30), "the right member is already in the picture's right half: {:?}", img.pixel(250, 130));
}
#[test]
fn open_freeforms_take_arrowheads_even_when_filled() {
// An open custom path with a fill and a tail arrow: PowerPoint draws the arrow.
+5 -58
View File
@@ -1,5 +1,5 @@
use super::geometry::{blur, color, pre_translate, scale_of};
use super::opts::{ParaState, ShapeState};
use super::opts::ParaState;
use super::{
Affine, Arc, BezPath, Ctx, FontDb, HashMap, Opts, PhType, Rect, RenderContext, Rgba, Shape, TextBody, Vec2, colr, paint, peniko, resolve,
};
@@ -109,55 +109,8 @@ pub fn draw_layout(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout, tr:
draw_layout_with(ctx, l, tr, m, &[]);
}
/// Apply Desaturate after layout, where every run already has its own resolved colours.
pub(crate) fn desaturate_layout(layout: &mut deckcraft_text::TextLayout, state: &ShapeState, ctx: &Ctx) {
use deckcraft_anim::desaturate_color;
if state.text_desaturation <= 0.0 && state.paras.iter().all(|(_, p)| p.text_desaturation <= 0.0) {
return;
}
let amount = |para| {
let extra = state.paras.iter().find(|(i, _)| *i == para).map_or(0.0, |(_, p)| p.text_desaturation);
combined_desaturation(state.text_desaturation, extra)
};
for run in &mut layout.runs {
let amount = amount(run.para);
if amount <= 0.0 {
continue;
}
run.color = desaturate_color(run.color, amount);
if let Some((color, _)) = &mut run.outline {
*color = desaturate_color(*color, amount);
}
if let Some(gradient) = &mut run.gradient {
for stop in &mut Arc::make_mut(gradient).stops {
stop.color = deckcraft_model::ColorRef::rgb(desaturate_color(ctx.color(&stop.color, None), amount));
}
}
}
for deco in layout.decos.iter_mut().filter(|d| !d.behind) {
deco.color = desaturate_color(deco.color, amount(deco.para));
}
}
fn combined_desaturation(shape: f64, paragraph: f64) -> f64 {
shape + (1.0 - shape) * paragraph
}
/// Draw a laid-out text block with per-paragraph animation states.
pub fn draw_layout_with(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout, tr: Rect, m: Affine, paras: &[(usize, ParaState)]) {
draw_animated_layout(ctx, l, tr, m, paras, 0.0);
}
/// The layout already carries animated text colours; pass the same amount to any glyph's own palette.
pub(crate) fn draw_animated_layout(
ctx: &mut RenderContext,
l: &deckcraft_text::TextLayout,
tr: Rect,
m: Affine,
paras: &[(usize, ParaState)],
text_desaturation: f64,
) {
let para = |i: usize| paras.iter().find(|(p, _)| *p == i).map(|(_, s)| *s).unwrap_or_default();
let m = text_transform(m, tr, l.rotation);
let lines_of = LineIndex::new(l);
@@ -191,14 +144,13 @@ pub(crate) fn draw_animated_layout(
continue;
}
let m = m * Affine::translate(ps.offset);
let desaturation = combined_desaturation(text_desaturation, ps.text_desaturation);
// A gradient fill starts over on every line and spans that line's text (from its top to
// its bottom, from its first to its last character), as in PowerPoint.
let mut grads: Vec<(usize, peniko::Gradient)> = Vec::new();
for (gid, x, y) in &run.glyphs {
let at = m * glyph_place(run, *gid, *x, *y);
let Some(g) = run.gradient.as_ref().filter(|g| !g.stops.is_empty()) else {
draw_glyph_with(ctx, run, *gid, at, ps.opacity, None, desaturation);
draw_glyph(ctx, run, *gid, at, ps.opacity);
continue;
};
let li = lines_of.line_at(run.para, *y);
@@ -209,7 +161,7 @@ pub(crate) fn draw_animated_layout(
grads.push((li, paint::gradient(&g.shape, stops, bounds, run.alpha * ps.opacity)));
}
let fill = grads.iter().find(|(i, _)| *i == li).map(|(_, g)| (g, Affine::translate((-*x, -*y))));
draw_glyph_with(ctx, run, *gid, at, ps.opacity, fill, desaturation);
draw_glyph_with(ctx, run, *gid, at, ps.opacity, fill);
}
}
for d in l.decos.iter().filter(|d| !d.behind) {
@@ -395,7 +347,7 @@ fn text_effect(ctx: &mut RenderContext, run: &deckcraft_text::GlyphRun, which: T
/// Draw glyph `gid` of `run` with its origin (on the baseline) mapped by `at`, faded by `opacity`.
pub(crate) fn draw_glyph(ctx: &mut RenderContext, run: &deckcraft_text::GlyphRun, gid: u32, at: Affine, opacity: f64) {
draw_glyph_with(ctx, run, gid, at, opacity, None, 0.0);
draw_glyph_with(ctx, run, gid, at, opacity, None);
}
/// [`draw_glyph`], filled with `fill` (a gradient laid out in the text's space, and the map from
@@ -407,7 +359,6 @@ fn draw_glyph_with(
at: Affine,
opacity: f64,
fill: Option<(&peniko::Gradient, Affine)>,
desaturation: f64,
) {
let alpha = run.alpha * opacity;
if (alpha <= 0.0 || run.color.a == 0) && run.outline.is_none() {
@@ -416,11 +367,7 @@ fn draw_glyph_with(
let k = run.size / run.face.upem.max(1.0);
// Colour glyphs (emoji) paint their own colours; an outline (text outline effect) still
// strokes the plain glyph below.
if alpha > 0.0
&& run.outline.is_none()
&& run.face.is_color()
&& colr::paint(ctx, &run.face, gid, at, k, colr::Colors { foreground: run.color, opacity: alpha, desaturation })
{
if alpha > 0.0 && run.outline.is_none() && run.face.is_color() && colr::paint(ctx, &run.face, gid, at, k, run.color, alpha) {
return;
}
let path = glyph(&run.face, gid);
+38 -112
View File
@@ -181,12 +181,11 @@ pub(crate) fn break_lines(p: &ParaShaped, params: &BreakParams) -> Vec<RawLine>
next = i + 1;
break;
}
let (adv, seg) = if c == '\t' {
let seg = tab_segment(&p.cells, i);
let adv = if c == '\t' {
// The implicit stop is for the first line only: later lines start at the margin.
(tab_advance(x0 + x, tab_stops, default_tab, seg, if lines.is_empty() { hang_stop } else { None }, x0 + avail), seg)
tab_advance(x0 + x, tab_stops, default_tab, tab_segment(&p.cells, i), if lines.is_empty() { hang_stop } else { None }, x0 + avail)
} else {
(p.cells.get(i).map(|c| c.adv).unwrap_or(0.0), (0.0, 0.0, 0.0))
p.cells.get(i).map(|c| c.adv).unwrap_or(0.0)
};
let breakable = |j: usize| p.cells.get(j).is_none_or(|c| c.breakable(j));
if i > start && allowed.get(i).copied().unwrap_or(false) && breakable(i) {
@@ -199,22 +198,8 @@ pub(crate) fn break_lines(p: &ParaShaped, params: &BreakParams) -> Vec<RawLine>
next = i + 1;
break;
}
// A tab that runs past the end moves to the next line. For a right, centre or
// decimal stop only (left and default tabs wrap between the words after them as
// usual), also keep it with its following segment when x + adv + seg.2 overflows here but fresh_tab_adv + seg.2
// fits within rest_w: a clamped tab can have zero advance while its text still
// overflows, and moving only the text would lose its tab alignment. The fresh-line
// check includes the tab advance, not just the text width. seg.2 excludes trailing
// whitespace so spaces alone cannot move visible text; an oversized segment that
// cannot fit with its tab on a fresh line uses the ordinary wrapping rules.
let tab_overflow = wrap
&& c == '\t'
&& (x + adv > avail + 0.01
|| (seg.2 > 0.0
&& takes_aligned_stop(x0 + x, tab_stops)
&& x + adv + seg.2 > avail + 0.01
&& tab_advance(x0_rest, tab_stops, default_tab, seg, None, x0_rest + rest_w) + seg.2 <= rest_w + 0.01));
if tab_overflow && i > start {
// A tab that would run past the end moves to the next line (and to its first stop there).
if wrap && c == '\t' && x + adv > avail + 0.01 && i > start {
end = i;
next = i;
while end > start && p.cells.get(end - 1).is_some_and(|c| c.ch == ' ') {
@@ -304,12 +289,11 @@ pub(crate) fn tabs_of(props: &ParaProps) -> Vec<Tab> {
tabs
}
/// Width of the text after the tab at cell `i` up to the next tab or line break, the width of
/// that text before its first ".", and the width excluding trailing whitespace.
pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64, f64) {
/// Width of the text after the tab at cell `i` up to the next tab or line break, and the width of
/// that text before its first ".".
pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64) {
let mut w = 0.0;
let mut dec = None;
let mut last_non_ws = 0.0;
for c in cells.iter().skip(i + 1) {
if matches!(c.ch, '\t'..='\u{b}') {
break;
@@ -318,78 +302,47 @@ pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64, f64) {
dec = Some(w);
}
w += c.adv;
if !c.ch.is_whitespace() {
last_non_ws = w;
}
}
(w, dec.unwrap_or(w), last_non_ws)
(w, dec.unwrap_or(w))
}
/// The configured stop a tab at `x` takes, by configured position. `stops` is in position order
/// (`tabs_of`). A NaN `x` has none.
fn next_stop(x: f64, stops: &[Tab]) -> Option<&Tab> {
if x.is_nan() { None } else { stops.get(stops.partition_point(|s| s.pos <= x + 0.5)) }
}
/// Whether a tab at `x` takes a right, centre or decimal stop: the stops whose following text
/// is placed relative to the stop, so the tab and that text belong together.
fn takes_aligned_stop(x: f64, stops: &[Tab]) -> bool {
next_stop(x, stops).is_some_and(|s| s.align != TabAlign::Left)
}
/// Advance of a tab at `x` to the next stop, aligning the following text without moving back;
/// past the last explicit stop, advance to the next default stop.
/// Advance of a tab at `x` (from the start edge) to the next stop, placing the text after it
/// (`seg`: its width, and its width before the decimal point) as the stop aligns it but never
/// moving back, as PowerPoint does; past the last stop, to the next default stop.
/// `hang` is the hanging-indent implicit stop (`marL`): the first tab on a first line that
/// starts left of the margin goes there instead, as PowerPoint does. The nearer of the
/// implicit and the regular stops wins; an explicit stop within 0.5 pt of it keeps its
/// own alignment.
///
/// `x`, stop positions and `right` are distances from the same text-column start edge, not
/// from the current line's indented start. `right` is the right-margin coordinate, not the
/// remaining width: both breaking and layout pass the line's `x0 + avail`. Nonfinite or
/// nonpositive edges disable clamping.
///
/// `seg` is `(total_width, width_before_first_decimal_point, width_without_trailing_whitespace)`,
/// from [`tab_segment`]; the second value equals the total width when no "." occurs.
/// Alignment uses the first two values; breaking uses the third for its visible-segment fit
/// check, including the fresh line's tab advance (without its first-line-only implicit stop).
///
/// Stops are selected by their configured position before clamping. Beyond a positive finite
/// `right`, left and right stops take effect at the edge; center and decimal stops subtract
/// the width after their alignment point so the whole segment fits. Stops at or inside the
/// edge and default stops retain their configured positions. Advances never move backward.
///
/// `hang` is the hanging-indent implicit stop (`marL`): on a first line that starts left of
/// the margin, the nearer implicit or regular stop wins. An explicit stop taking effect
/// within 0.5 pt of it keeps its own alignment.
pub(crate) fn tab_advance(x: f64, stops: &[Tab], default_tab: f64, seg: (f64, f64, f64), hang: Option<f64>, right: f64) -> f64 {
let effective_pos = |s: &Tab| {
if right.is_finite() && right > 0.0 && s.pos > right {
match s.align {
TabAlign::Left | TabAlign::Right => right,
TabAlign::Center => (right - seg.0 / 2.0).max(0.0),
TabAlign::Decimal => (right - (seg.0 - seg.1).max(0.0)).max(0.0),
}
} else {
s.pos
}
};
// `stops` is in position order (`tabs_of`): select by the configured position, not the
// clamped one. A NaN `x` skips the lookup and takes the finite default-stop path.
let explicit = next_stop(x, stops);
/// `right` is the line's right edge in the same coordinate space as `x` (the text area's left
/// edge plus the line's start offset and width): a stop set past that edge acts as one at the
/// edge, as PowerPoint treats it (a right-aligned stop there ends the text at the margin).
pub(crate) fn tab_advance(x: f64, stops: &[Tab], default_tab: f64, seg: (f64, f64), hang: Option<f64>, right: f64) -> f64 {
// `stops` is in position order (`tabs_of`): the next stop is the first past x.
// A NaN `x` (a NaN spacing upstream) skips the lookup and takes the finite default-stop path.
if !x.is_nan()
&& let Some(h) = hang
&& h.is_finite()
&& x < h - 0.5
{
let explicit = stops.get(stops.partition_point(|s| s.pos <= x + 0.5));
let d = if default_tab > 1.0 { default_tab } else { 72.0 };
let default_next = ((x / d).floor() + 1.0) * d;
let explicit_wins = match explicit {
Some(s) => effective_pos(s) <= h + 0.5,
// Compared where the stop takes effect: one past the line's edge ends there (below).
Some(s) => {
let pos = if right.is_finite() && right > 0.0 { s.pos.min(right) } else { s.pos };
pos < h - 0.5 || (pos - h).abs() <= 0.5
}
None => h >= default_next - 0.5,
};
if !explicit_wins {
return (h - x).max(1.0);
}
}
if let Some(s) = explicit {
let to = (effective_pos(s) - x).max(0.0);
if let Some(s) = stops.get(stops.partition_point(|s| s.pos <= x + 0.5)).filter(|_| !x.is_nan()) {
let pos = if right.is_finite() && right > 0.0 { s.pos.min(right) } else { s.pos };
let to = (pos - x).max(0.0);
return match s.align {
TabAlign::Left => to,
TabAlign::Right => (to - seg.0).max(0.0),
@@ -409,8 +362,8 @@ mod tab_tests {
#[test]
fn a_nan_position_takes_the_finite_default_stop() {
let stops = [Tab { pos: 100.0, align: TabAlign::Left }];
assert!(tab_advance(f64::NAN, &stops, 72.0, (0.0, 0.0, 0.0), None, 600.0).is_finite());
assert_eq!(tab_advance(10.0, &stops, 72.0, (0.0, 0.0, 0.0), None, 600.0), 90.0);
assert!(tab_advance(f64::NAN, &stops, 72.0, (0.0, 0.0), None, 600.0).is_finite());
assert_eq!(tab_advance(10.0, &stops, 72.0, (0.0, 0.0), None, 600.0), 90.0);
}
#[test]
@@ -418,16 +371,16 @@ mod tab_tests {
// The 700 pt stop takes effect at the 60 pt edge, which comes before the 80 pt hang: it
// wins, and right-aligned text after it ends at the edge (60 - 20), not at the hang.
let stops = [Tab { pos: 700.0, align: TabAlign::Right }];
assert_eq!(tab_advance(0.0, &stops, 72.0, (20.0, 20.0, 20.0), Some(80.0), 60.0), 40.0);
assert_eq!(tab_advance(0.0, &stops, 72.0, (20.0, 20.0), Some(80.0), 60.0), 40.0);
}
#[test]
fn a_stop_past_the_line_ends_at_its_edge() {
let stops = [Tab { pos: 700.0, align: TabAlign::Right }];
// Right-aligned text after the tab ends at the line's right edge, not 700.
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0, 100.0), None, 600.0), 500.0);
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0), None, 600.0), 500.0);
// A stop inside the line keeps its own position.
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0, 100.0), None, 800.0), 600.0);
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0), None, 800.0), 600.0);
}
#[test]
@@ -435,35 +388,8 @@ mod tab_tests {
// The stop and the edge are absolute coordinates: a 100 pt start offset does not move the
// edge in to 500 pt, so an inside stop at 550 stays there and one past 600 ends at 600.
let inside = [Tab { pos: 550.0, align: TabAlign::Right }];
assert_eq!(tab_advance(100.0, &inside, 72.0, (100.0, 100.0, 100.0), None, 600.0), 350.0);
assert_eq!(tab_advance(100.0, &inside, 72.0, (100.0, 100.0), None, 600.0), 350.0);
let past = [Tab { pos: 700.0, align: TabAlign::Right }];
assert_eq!(tab_advance(100.0, &past, 72.0, (100.0, 100.0, 100.0), None, 600.0), 400.0);
}
#[test]
fn a_wide_centered_segment_keeps_its_configured_stop() {
// Eligibility uses the configured stop, even when clamping puts its center at x.
let stops = [Tab { pos: 550.0, align: TabAlign::Center }];
assert_eq!(tab_advance(0.0, &stops, 72.0, (1100.0, 1100.0, 1100.0), None, 500.0), 0.0);
}
#[test]
fn inside_center_and_decimal_stops_keep_their_alignment_points() {
let center = [Tab { pos: 490.0, align: TabAlign::Center }];
assert_eq!(tab_advance(0.0, &center, 72.0, (40.0, 40.0, 40.0), None, 500.0), 470.0);
let decimal = [Tab { pos: 490.0, align: TabAlign::Decimal }];
assert_eq!(tab_advance(0.0, &decimal, 72.0, (40.0, 20.0, 40.0), None, 500.0), 470.0);
}
#[test]
fn clamped_aligned_stops_compete_with_the_hang_at_their_effective_position() {
for align in [TabAlign::Center, TabAlign::Decimal] {
let stops = [Tab { pos: 700.0, align }];
// The alignment point moves to 50; its text ends at the 60 pt edge.
assert_eq!(tab_advance(0.0, &stops, 72.0, (20.0, 10.0, 20.0), Some(55.0), 60.0), 40.0);
}
// Keep main's edge clamp for left stops as well.
let left = [Tab { pos: 700.0, align: TabAlign::Left }];
assert_eq!(tab_advance(0.0, &left, 72.0, (20.0, 20.0, 20.0), Some(80.0), 60.0), 60.0);
assert_eq!(tab_advance(100.0, &past, 72.0, (100.0, 100.0), None, 600.0), 400.0);
}
}
-100
View File
@@ -1477,106 +1477,6 @@ fn a_tab_past_the_end_moves_to_the_next_line() {
assert!((l.lines[1].edges[1].0 - l.inner.x0 - 72.0).abs() < 0.01);
}
/// #1663: a right-aligned tab stop past the right edge of the text area clamps to the edge
/// and right-aligns the text there, instead of wrapping.
#[test]
fn right_tab_stop_past_right_edge_aligns_at_margin_without_wrapping() {
let l = tabbed("\tCorrie Ten Boom", &[(550.0, "r")], 500.0);
assert_eq!(l.lines.len(), 1, "must not wrap to a second line");
assert!((l.lines[0].extent.1 - l.inner.x1).abs() < 1.0, "text right edge {:?} should align with inner.x1 {}", l.lines[0].extent.1, l.inner.x1);
}
/// #1663: center and decimal tab stops beyond the text area right edge clamp so their content
/// remains bounded by the margin without wrapping onto a new line.
#[test]
fn center_and_decimal_tab_stops_past_right_edge_align_without_wrapping() {
let l_ctr = tabbed("\tCentered", &[(550.0, "ctr")], 500.0);
assert_eq!(l_ctr.lines.len(), 1, "center stop must not wrap to a second line");
assert!(
(l_ctr.lines[0].extent.1 - l_ctr.inner.x1).abs() < 1.0,
"text right edge {:?} should align with inner.x1 {}",
l_ctr.lines[0].extent.1,
l_ctr.inner.x1
);
let l_dec = tabbed("\t123.45", &[(550.0, "dec")], 500.0);
assert_eq!(l_dec.lines.len(), 1, "decimal stop must not wrap to a second line");
assert!(
(l_dec.lines[0].extent.1 - l_dec.inner.x1).abs() < 1.0,
"text right edge {:?} should align with inner.x1 {}",
l_dec.lines[0].extent.1,
l_dec.inner.x1
);
// Stops inside the margin remain untouched:
let l_inside = tabbed("\tCentered", &[(300.0, "ctr")], 500.0);
assert_eq!(l_inside.lines.len(), 1);
let (s, e) = (l_inside.lines[0].edges[1].0, l_inside.lines[0].edges[8].1);
assert!(((s + e) / 2.0 - l_inside.inner.x0 - 300.0).abs() < 1.0, "center stop inside margin must stay at 300.0");
}
/// #1663: a tab whose following word fits on a fresh line but not in the remaining space
/// moves to the next line with its word so alignment is preserved.
#[test]
fn tab_moves_to_next_line_with_word_when_word_does_not_fit_remaining_space() {
for (align, suffix) in [("r", "Aligned"), ("ctr", "Aligned"), ("dec", "123.45")] {
let l = tabbed(&format!("leading text here\t{suffix}"), &[(250.0, align)], 200.0);
assert_eq!(l.lines.len(), 2, "{align}");
assert_eq!(l.lines[1].start, 17, "tab must start line 2 for {align}");
assert!((l.lines[1].extent.1 - l.inner.x1).abs() < 1.0, "suffix should end at the margin on line 2 for {align}");
}
}
/// #1663: trailing spaces after a tabbed word do not force the tab to wrap to a new line
/// if the visible word fits in the remaining space.
#[test]
fn trailing_spaces_after_tab_do_not_force_line_break() {
let l = tabbed("a\tWord ", &[(150.0, "r")], 200.0);
assert_eq!(l.lines.len(), 1, "trailing spaces do not force a line break; fits on one line");
}
#[test]
fn trailing_spaces_cannot_move_a_zero_advance_tab_with_visible_text_that_fits() {
// Derive the width from the active font so only the trailing spaces exceed the margin.
let probe = tabbed("leading text hereWord", &[], 1000.0);
let width = probe.lines[0].extent.1 - probe.lines[0].extent.0 + 5.0;
let insets = 1000.0 - probe.inner.width();
for align in ["r", "ctr", "dec"] {
let l = tabbed("leading text here\tWord ", &[(width + 50.0, align)], width + insets);
assert_eq!(l.lines.len(), 1, "only trailing spaces overflow for {align}");
assert!(l.lines[0].edges[21].1 <= l.inner.x1 + 0.01, "visible text fits for {align}");
}
}
#[test]
fn a_tab_does_not_move_with_a_segment_that_cannot_fit_at_the_fresh_default_stop() {
let probe = tabbed("Word", &[], 1000.0);
let word_w = probe.lines[0].extent.1 - probe.lines[0].extent.0;
let insets = 1000.0 - probe.inner.width();
// The word fits alone, but not after the 72 pt default tab on a fresh line.
let l = tabbed("Word\tWord", &[], 72.0 + word_w / 2.0 + insets);
assert_eq!(l.lines.len(), 2, "do not add a line for a tab whose segment still cannot fit");
assert_eq!(l.lines[1].start, 5, "the tab stays on the first line");
}
#[test]
fn left_and_default_tabs_still_wrap_between_the_words_after_them() {
// Only right, centre and decimal stops keep their tab with the text after it. After a left or
// default tab, words that fit on the first line stay there and the rest wraps between words.
let tab_at = "Label text:".chars().count();
for w in [200.0, 250.0] {
for stops in [&[][..], &[(100.0, "l")][..]] {
let l = tabbed("Label text:\tone two three four", stops, w);
assert!(l.lines.len() >= 2, "{w}");
assert!(
l.lines[1].start > tab_at + 1,
"the tab and a word after it stay on line 1 at {w}: {:?}",
l.lines.iter().map(|x| (x.start, x.end)).collect::<Vec<_>>()
);
}
}
}
/// One paragraph `text` with a hanging indent (`marL`/`indent`), no bullet or explicit stops.
fn hanging_tabbed(text: &str, margin: f64, indent: f64, w: f64) -> TextLayout {
let (p, mut sh) = setup(text, w, 300.0);
+1 -6
View File
@@ -22,17 +22,13 @@ deckcraft-engine = { workspace = true }
deckcraft-media = { workspace = true }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
ttf-parser = "0.25"
craft-i18n = { workspace = true }
sys-locale = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
web-time = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Agents in the open window (`src/agents.rs`): the ArtCraft Launcher's switch, the link host with its control
# server and the Agents page of Preferences (`automation-agents`), and the default agent folder (`control-agents`).
craft = { workspace = true, features = ["update", "automation-agents", "control-agents"] }
craft = { workspace = true, features = ["update", "print"] }
craft-update = { workspace = true }
[dev-dependencies]
@@ -42,7 +38,6 @@ skrifa = { workspace = true }
# kittest's own dev-dependencies do not propagate; tests need both font features explicitly.
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }
memory-stats = "1.2.0"
[build-dependencies]
serde_json = { workspace = true }
+1 -84
View File
@@ -1,5 +1,4 @@
//! Bake the contributor credits into the binary as static Rust tables, and embed the craft-i18n
//! interface catalogs. Nothing is read at run time.
//! Bake the contributor credits into the binary as static Rust tables. Nothing is read at run time.
//!
//! - contributors/contributors.json: commit stats per GitHub username, with a mark for whose
//! people.toml entry is verified.
@@ -7,12 +6,6 @@
//! JSON says the entry was verified (`people_entry`).
//!
//! A missing or malformed file gives empty tables (or no names) and a warning.
//!
//! - `CRAFT_I18N_DIR`, a craft-i18n checkout (storytold/craft-i18n, at the SHA in
//! `craft-i18n.rev`): `craft_i18n.rs` holds `CRAFT_I18N`, one (locale, shared catalog, DeckCraft
//! catalog) entry per locale that has a `deckcraft.tsv`. Unset, or not a checkout (a warning),
//! it is empty and the interface is English only; with `CRAFT_I18N_REQUIRED=1` (releases) that
//! is an error instead. Recipe: craft-i18n's `docs/integration.md`.
use std::fmt::Write as _;
@@ -60,82 +53,6 @@ fn main() {
if let Err(e) = std::fs::write(&out, generate(&json, &people)) {
println!("cargo::warning=writing {}: {e}", out.display());
}
let out = out.with_file_name("craft_i18n.rs");
if let Err(e) = std::fs::write(&out, craft_i18n()) {
println!("cargo::error=writing {}: {e}", out.display());
}
}
/// The catalog this app reads in each locale: `locales/<locale>/deckcraft.tsv`.
const APP_CATALOG: &str = "deckcraft.tsv";
/// `CRAFT_I18N` from `CRAFT_I18N_DIR`: the `Embedded` list the craft-i18n crate reads.
fn craft_i18n() -> String {
println!("cargo::rerun-if-env-changed=CRAFT_I18N_DIR");
println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED");
let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v.trim() == "1");
let entries = match std::env::var_os("CRAFT_I18N_DIR").filter(|d| !d.is_empty()) {
// Not canonicalized: on Windows that gives `\\?\C:\…`, which `include_str!` can't read.
Some(dir) => match locales(&std::path::PathBuf::from(dir).join("locales")) {
Ok(entries) => entries,
Err(e) => {
let level = if required { "error" } else { "warning" };
println!("cargo::{level}=CRAFT_I18N_DIR: {e}; the interface is English only");
Vec::new()
}
},
None => {
if required {
println!("cargo::error=CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR is unset: a release must embed the translations");
}
Vec::new()
}
};
let mut o = String::from("/// (locale, shared catalog, DeckCraft's catalog), one entry per locale; `\"\"` for a missing file.\n");
o.push_str("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n");
for (code, shared, app) in entries {
// `{:?}` escapes the path (Windows backslashes) as a Rust string literal.
let shared = shared.map_or_else(|| "\"\"".to_string(), |p| format!("include_str!({p:?})"));
let _ = writeln!(o, " ({code:?}, {shared}, include_str!({app:?})),");
}
o.push_str("];\n");
o
}
/// A locale's code, its `common.tsv` if any, and its app catalog.
type Locale = (String, Option<std::path::PathBuf>, std::path::PathBuf);
/// Every locale under `dir` with this app's catalog, by code: (code, its `common.tsv` if any, its
/// app catalog). An error when `dir` isn't a craft-i18n `locales/` directory.
fn locales(dir: &std::path::Path) -> Result<Vec<Locale>, String> {
// Build scripts run in the crate's directory and `include_str!` resolves against `OUT_DIR`, so
// a relative path would mean two different places.
if !dir.is_absolute() {
return Err(format!("{} is not an absolute path", dir.display()));
}
// Track even a missing directory: a later checkout must replace the English-only output.
println!("cargo::rerun-if-changed={}", dir.display());
let list = std::fs::read_dir(dir).map_err(|e| format!("{} is not a craft-i18n checkout ({e})", dir.display()))?;
let mut out = Vec::new();
for entry in list.flatten() {
let path = entry.path();
let Some(code) = path.file_name().and_then(std::ffi::OsStr::to_str).map(str::to_string) else { continue };
let app = path.join(APP_CATALOG);
if !app.is_file() {
continue;
}
println!("cargo::rerun-if-changed={}", app.display());
let shared = Some(path.join("common.tsv")).filter(|p| p.is_file());
if let Some(p) = &shared {
println!("cargo::rerun-if-changed={}", p.display());
}
out.push((code, shared, app));
}
if out.is_empty() {
return Err(format!("{} has no locale with a {APP_CATALOG}", dir.display()));
}
out.sort();
Ok(out)
}
fn read<T>(path: &std::path::Path, fallback: &str, parse: impl Fn(&str) -> Result<T, String>) -> Option<T> {
-183
View File
@@ -1,183 +0,0 @@
//! Agents in the open window: while the ArtCraft Launcher's *Settings › AI agents* switch names
//! DeckCraft, the window serves its control channel to agents on loopback.
//!
//! The switch, the control server, its token and the connection file `deckcraft-cli mcp` finds the
//! window by are the framework's (`craft::automation::agents::AgentSwitch` and `AgentLink`).
//! DeckCraft supplies its agent settings (saved by `app.agents`), answers the requests with its own
//! control methods ([`crate::control`]) and confines every file they open or save to the agent
//! folders: those set in Preferences › AI Integrations, or `Documents/ArtCraft/Agents/DeckCraft`
//! for an empty one. Without a folder of a kind, that kind of access is refused.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem};
use craft::automation::control::ControlChannel;
use craft::ui::runtime::windows::WindowHost;
use deckcraft_engine::file_access::{self, AutomationRoots};
use serde_json::{Value, json};
use crate::SlideApp;
/// The id the ArtCraft Launcher's app list names DeckCraft by (its catalog id).
pub const LAUNCHER_APP_ID: &str = "deckcraft";
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/DeckCraft`).
pub const APP_NAME: &str = "DeckCraft";
/// The id of the Preferences page of the agent settings, and the key they sit under in its draft.
pub const PAGE: &str = "integrations";
/// The page's title in Preferences, as PhotoCraft names it.
pub const PAGE_TITLE: &str = "AI Integrations";
/// Saves the agent settings where `deckcraft-cli mcp` reads them; `Err` says why it couldn't.
pub type SaveFn = Box<dyn Fn(&AgentSettings) -> Result<(), String>>;
/// The agents link of the open window.
pub struct Agents {
/// The link; `None` while the launch options (`--control`) manage the control channel.
link: Option<AgentLink>,
/// The status shown while the launch options manage the control channel.
launch: AgentLinkStatus,
switch: AgentSwitch,
settings: AgentSettings,
save: SaveFn,
default_folder: Option<PathBuf>,
}
impl Agents {
/// The link for the window, keeping its token and connection file in `settings_dir` and naming
/// `app` (the version string) in the connection file, following `switch` with the saved
/// `settings`; `save` stores the settings when `app.agents` changes them.
pub fn new(settings_dir: Option<PathBuf>, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn) -> Self {
Self {
link: Some(AgentLink::new(settings_dir, app)),
launch: AgentLinkStatus::default(),
switch,
settings,
save,
default_folder: craft::control::agents::default_folder(APP_NAME),
}
}
/// The window was started with `--control`, listening on `port` (none when it couldn't): that
/// channel serves the whole run, the link stays off and Preferences says the launch options
/// manage it.
pub fn launched_with_control(mut self, port: Option<u16>) -> Self {
self.link = None;
self.launch.port = port;
self.launch.launch_flags = true;
self
}
/// `default` replaces the default agent folder (tests).
pub fn with_default_folder(mut self, default: Option<PathBuf>) -> Self {
self.default_folder = default;
self
}
/// The saved agent settings.
pub fn settings(&self) -> &AgentSettings {
&self.settings
}
/// Where the link stands, for Preferences and `ui.inspect`.
pub fn status(&self) -> &AgentLinkStatus {
self.link.as_ref().map_or(&self.launch, AgentLink::status)
}
/// The suite's `AI-MCP` flag: the launcher's switch decides, and Preferences shows its state.
pub fn mcp_flag(&self) -> bool {
self.switch.mcp_flag()
}
/// Whether the launcher's switch lets agents use DeckCraft now.
pub fn allowed(&self) -> bool {
// DeckCraft had no agent consent of its own before the switch.
self.switch.allows(false)
}
/// Saves `settings`; the link applies them on the next pass.
fn set(&mut self, settings: AgentSettings) -> Result<(), String> {
(self.save)(&settings)?;
self.settings = settings;
Ok(())
}
}
/// What agent requests may open and save with `settings`: the agent folders (`default` for an empty
/// setting), or nothing. `Err` says why a folder can't be used.
fn roots_for(settings: &AgentSettings, default: Option<&Path>) -> Result<Arc<AutomationRoots>, String> {
let folders = settings.folders_with(default);
let read: Vec<PathBuf> = folders.read.into_iter().collect();
let write: Vec<PathBuf> = folders.write.into_iter().collect();
Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
}
/// Once a frame, before the control requests are drained: brings the link in line with the
/// launcher's switch and the saved settings. The control server starts, moves or stops; while it
/// runs, its requests are the app's control channel and run inside the agent folders
/// ([`SlideApp::drain_control`]).
pub(crate) fn sync(app: &mut SlideApp, ctx: &egui::Context) {
let Some(agents) = app.agents.as_mut() else { return };
let allowed = agents.allowed();
let Some(link) = agents.link.as_mut() else { return };
let update = link.sync(allowed.then_some(&agents.settings), &WindowHost::of(ctx));
if update.stopped {
app.control = None;
}
if let Some(requests) = update.requests {
app.control = Some(ControlChannel::new(requests));
}
if !update.changed {
return;
}
app.control_roots = Some(if link.status().port.is_none() {
AutomationRoots::none()
} else {
// Opened only when something changed: the default folder is created on the way.
roots_for(&agents.settings, agents.default_folder.as_deref()).unwrap_or_else(|e| {
link.note(LinkProblem::App(format!("Agents can't open or save files: {e}")));
AutomationRoots::none()
})
});
}
/// The keys `app.agents` takes.
const KEYS: [&str; 4] = ["controlPort", "readRoot", "writeRoot", "whenAppClosed"];
/// `app.agents`: the agent settings of Preferences › AI Integrations, the link's status and the
/// launcher's switch. `{controlPort?, readRoot?, writeRoot?, whenAppClosed?}` changes and saves those
/// settings first. Agents can't change them: their requests run confined to the agent folders, and
/// widening those is the person's choice.
pub(crate) fn command(app: &mut SlideApp, p: &Value) -> Result<Value, String> {
let Some(agents) = app.agents.as_mut() else {
return Err("agents can't use this window: it keeps no preferences (DECKCRAFT_NO_PREFS), or it is a nightly".into());
};
if let Some(given) = p.as_object().filter(|o| !o.is_empty()) {
if let Some(unknown) = given.keys().find(|k| !KEYS.contains(&k.as_str())) {
return Err(format!("unknown agent setting `{unknown}` ({})", KEYS.join(", ")));
}
if file_access::current().is_some() {
return Err(format!("agents can't change the agent settings: the person sets them in Preferences › {PAGE_TITLE}"));
}
let mut next = serde_json::to_value(agents.settings()).map_err(|e| e.to_string())?;
if let Some(next) = next.as_object_mut() {
next.extend(given.clone());
}
let next: AgentSettings = serde_json::from_value(next).map_err(|e| format!("bad agent setting: {e}"))?;
if next.control_port > u32::from(u16::MAX) {
return Err(format!("controlPort must be 0 to {}, not {}", u16::MAX, next.control_port));
}
agents.set(next)?;
}
Ok(json!({"settings": agents.settings(), "status": agents.status(), "allowed": agents.allowed(), "mcpFlag": agents.mcp_flag()}))
}
/// What Preferences' Agents page needs: the saved settings, the link's status and the suite's
/// `AI-MCP` flag; `None` when the window lets no agents in.
pub(crate) fn page_state(app: &SlideApp) -> Option<(AgentSettings, AgentLinkStatus, bool)> {
let agents = app.agents.as_ref()?;
Some((agents.settings().clone(), agents.status().clone(), agents.mcp_flag()))
}
#[cfg(test)]
mod tests;
-168
View File
@@ -1,168 +0,0 @@
//! Agents in the open window: the link follows the launcher's switch, agent requests and the input
//! they queue stay inside the agent folders, and agents can't change the agent settings.
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use craft::automation::agents::{AgentSettings, AgentSwitch, CONNECTION_FILE, read_connection};
use craft::automation::client::ControlClient;
use craft::host::NoPickFiles;
use deckcraft_engine::file_access::{self, AutomationRoots};
use serde_json::{Value, json};
use super::Agents;
use crate::SlideApp;
use crate::confined_files::ConfinedFiles;
use crate::test_harness::harness_with;
type Harness = egui_kittest::Harness<'static, SlideApp>;
/// A test's folder with `settings` (the app's settings folder), `in` (the read folder, with
/// `a.deckcraft`), `out` (the write folder) and `outside` (with `b.deckcraft`).
fn folders(tag: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("dc-ui-agents-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
for d in ["settings", "in", "out", "outside"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
let mut session = deckcraft_engine::Session::with_new();
for path in [base.join("in/a.deckcraft"), base.join("outside/b.deckcraft")] {
session.execute("file.save", &json!({"path": s(path)})).unwrap();
}
base
}
fn s(p: PathBuf) -> String {
p.to_string_lossy().into_owned()
}
/// A window with the desktop's (confined) file service whose agents link follows `switch`, with
/// `in` and `out` as the agent folders; the settings it saves land in the returned list.
fn window_with_agents(base: &Path, switch: AgentSwitch) -> (Harness, Arc<Mutex<Vec<AgentSettings>>>) {
let mut harness = harness_with(
deckcraft_engine::Session::new(),
crate::Services::default(),
egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0),
|platform| platform.host = platform.host.clone().with_files(Arc::new(ConfinedFiles::new(Arc::new(NoPickFiles::default())))),
);
let mut settings = AgentSettings::default();
settings.read_root = s(base.join("in"));
settings.write_root = s(base.join("out"));
let saved = Arc::new(Mutex::new(Vec::new()));
let into = saved.clone();
let save: super::SaveFn = Box::new(move |settings| {
into.lock().unwrap().push(settings.clone());
Ok(())
});
let agents = Agents::new(Some(base.join("settings")), "DeckCraft test".into(), switch, settings, save).with_default_folder(None);
harness.state_mut().with_agents(agents);
harness.run_steps(2);
(harness, saved)
}
/// An agent's client of the window's link, authenticated with the token the connection file names.
fn agent_client(base: &Path, harness: &Harness) -> ControlClient {
let port = harness.state().agents.as_ref().and_then(|a| a.status().port).expect("the link listens while the switch allows it");
let connection = read_connection(&base.join("settings")).unwrap().expect("the connection file is published");
assert_eq!(connection.port, port);
let token = std::fs::read_to_string(&connection.token_file).unwrap();
ControlClient::connect(([127, 0, 0, 1], port).into(), token.trim()).unwrap()
}
/// One request from an agent's client through the link's server, answered by the window's frames.
fn agent_request(harness: &mut Harness, client: &mut Option<ControlClient>, method: &str, params: Value) -> Result<Value, String> {
let mut c = client.take().expect("a connected client");
let method = method.to_owned();
let call = std::thread::spawn(move || {
let r = c.call(&method, params);
(c, r)
});
for _ in 0..2000 {
if call.is_finished() {
break;
}
harness.step();
std::thread::sleep(std::time::Duration::from_millis(2));
}
let (c, r) = call.join().unwrap();
*client = Some(c);
r
}
// With the launcher's switch naming DeckCraft, the window serves agents on loopback and publishes
// where; their requests open and save only inside the agent folders, the window's own file
// service included, while the person is not confined.
#[test]
fn agents_reach_the_window_only_inside_the_agent_folders() {
let base = folders("on");
let (mut harness, _) = window_with_agents(&base, AgentSwitch::fixed(true, true));
let mut client = Some(agent_client(&base, &harness));
let inside = agent_request(&mut harness, &mut client, "app.open", json!({"path": s(base.join("in/a.deckcraft"))}));
assert!(inside.is_ok(), "{inside:?}");
let outside = agent_request(&mut harness, &mut client, "app.open", json!({"path": s(base.join("outside/b.deckcraft"))}));
assert!(outside.as_ref().is_err_and(|e| e.contains("outside the read roots")), "{outside:?}");
let exported = agent_request(&mut harness, &mut client, "app.export", json!({"path": s(base.join("outside/a.pdf"))}));
assert!(exported.as_ref().is_err_and(|e| e.contains("outside the write roots")), "{exported:?}");
// `ui.render` writes through the window's file service, not an engine command.
let rendered = agent_request(&mut harness, &mut client, "ui.render", json!({"path": s(base.join("outside/a.png"))}));
assert!(rendered.is_err(), "{rendered:?}");
let rendered = agent_request(&mut harness, &mut client, "ui.render", json!({"path": s(base.join("out/a.png"))}));
assert!(rendered.is_ok(), "{rendered:?}");
assert!(!base.join("outside/a.pdf").exists() && !base.join("outside/a.png").exists());
// The person at the keyboard opens what they like.
assert!(harness.state_mut().run("file.open", json!({"path": s(base.join("outside/b.deckcraft"))})).is_ok());
let _ = std::fs::remove_dir_all(&base);
}
// A shortcut an agent presses fires its command in a later pass, still held to the agent folders:
// Save on a presentation the person opened from elsewhere is refused and leaves its file alone.
#[test]
fn input_an_agent_queues_stays_inside_the_agent_folders() {
let base = folders("input");
let (mut harness, _) = window_with_agents(&base, AgentSwitch::fixed(true, true));
let theirs = base.join("outside/b.deckcraft");
let before = std::fs::read(&theirs).unwrap();
harness.state_mut().run("file.open", json!({"path": s(theirs.clone())})).unwrap();
harness.state_mut().run("slide.new", json!({})).unwrap();
harness.run_steps(2);
let mut client = Some(agent_client(&base, &harness));
let pressed = agent_request(&mut harness, &mut client, "ui.key", json!({"key": "S", "command": true}));
assert!(pressed.is_ok(), "{pressed:?}");
harness.run_steps(4);
assert_eq!(std::fs::read(&theirs).unwrap(), before, "the agent's Save must not write outside the agent folders");
assert!(harness.state().agent_scope().is_none(), "once the input is handled, the person's own input is not confined");
let _ = std::fs::remove_dir_all(&base);
}
// With the switch off, nothing listens and no connection file is published.
#[test]
fn with_the_switch_off_nothing_listens() {
let base = folders("off");
let (harness, _) = window_with_agents(&base, AgentSwitch::fixed(true, false));
assert!(harness.state().control.is_none());
assert_eq!(harness.state().agents.as_ref().and_then(|a| a.status().port), None);
assert!(!base.join("settings").join(CONNECTION_FILE).exists());
let _ = std::fs::remove_dir_all(&base);
}
// `app.agents` saves the person's settings, refuses unknown keys, and refuses every change from a
// confined request: agents can't widen their own folders.
#[test]
fn app_agents_saves_and_agents_cannot_change_it() {
let base = folders("prefs");
let (mut harness, saved) = window_with_agents(&base, AgentSwitch::fixed(true, false));
let app = harness.state_mut();
let r = super::command(app, &json!({"whenAppClosed": "headless"})).unwrap();
assert_eq!(r["settings"]["whenAppClosed"], "headless");
assert_eq!(saved.lock().unwrap().len(), 1);
assert!(super::command(app, &json!({"port": 7})).is_err());
assert!(super::command(app, &json!({"controlPort": 70000})).is_err());
let roots = AutomationRoots::new(&[base.join("in")], &[base.join("out")]).unwrap().unwrap();
let widened = file_access::confine(Some(&roots), || super::command(app, &json!({"readRoot": s(base.clone())})));
assert!(widened.is_err_and(|e| e.contains("can't change the agent settings")));
assert_eq!(saved.lock().unwrap().len(), 1, "nothing more was saved");
// Reading them is fine.
assert!(file_access::confine(Some(&roots), || super::command(app, &json!({}))).is_ok());
let _ = std::fs::remove_dir_all(&base);
}
+35 -34
View File
@@ -26,7 +26,6 @@ mod keys;
mod playback;
pub(crate) use commands::GRID_SPACING_RANGE;
pub(crate) use control::AgentInput;
pub(crate) use files::FileOperation;
#[cfg(test)]
pub(crate) use files::web_image_files;
@@ -141,10 +140,6 @@ impl SlideApp {
let mut app = Self {
host,
control,
control_roots: None,
agent_input: None,
#[cfg(not(target_arch = "wasm32"))]
agents: None,
autosave: None,
notices,
palette_open: false,
@@ -200,6 +195,10 @@ impl SlideApp {
#[cfg(not(target_arch = "wasm32"))]
print_previews: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
print_spool: None,
#[cfg(not(target_arch = "wasm32"))]
print_receipt: None,
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
selpane: Default::default(),
align_to: None,
@@ -225,6 +224,12 @@ impl SlideApp {
self.print_previews.cleanup();
}
/// Installs the system print spool for the native desktop shell.
#[cfg(not(target_arch = "wasm32"))]
pub fn enable_direct_print(&mut self) {
self.print_spool = Some(craft::print::spool::Spool::new(self.host.jobs_shared().clone()));
}
/// Holds the close request until dirty presentations have passed the closing guard.
pub fn close_decision(&mut self) -> embed::CloseDecision {
let dirty: Vec<_> = self.session.documents().iter().filter(|doc| doc.is_dirty()).map(|doc| doc.uid).collect();
@@ -253,11 +258,32 @@ impl SlideApp {
}
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(spool) = self.print_spool.take() {
spool.shutdown();
}
self.start_pending_update();
self.cleanup_print_previews();
}
}
#[cfg(not(target_arch = "wasm32"))]
fn poll_print_receipt(&mut self, ctx: &egui::Context) {
use std::sync::mpsc::TryRecvError;
let Some((printer, receipt)) = &self.print_receipt else { return };
let status = match receipt.try_recv() {
Ok(Ok(message)) => format!("Sent to {printer}: {message}"),
Ok(Err(error)) => format!("Couldn't print: {error}"),
Err(TryRecvError::Disconnected) => "Couldn't confirm whether the print job reached the printer".into(),
Err(TryRecvError::Empty) => {
ctx.request_repaint_after(std::time::Duration::from_millis(200));
return;
}
};
self.print_receipt = None;
self.set_status(status);
}
/// Displays a transient message in the status bar.
pub fn set_status(&mut self, msg: impl Into<String>) {
self.status = Some((msg.into(), self.clock.now() * 1000.0));
@@ -326,12 +352,6 @@ impl SlideApp {
/// Supplies commands and root values once before the frame's first input pass.
/// Additional layout passes read that input and apply only their own events.
pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// Commands the keys and clicks an agent queued fire here, held to its folders.
let roots = self.agent_scope();
deckcraft_engine::file_access::confine(roots.as_ref(), || self.input_pass(ctx, raw));
}
fn input_pass(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.withdraw_if_retargeted(ctx);
if !Self::root_viewport_admitted(ctx) {
return;
@@ -383,14 +403,11 @@ impl SlideApp {
/// Pumps background work even while the window is hidden, then runs its one close path.
pub fn logic(&mut self, ctx: &egui::Context) {
let roots = self.agent_scope();
deckcraft_engine::file_access::confine(roots.as_ref(), || self.logic_pass(ctx));
}
fn logic_pass(&mut self, ctx: &egui::Context) {
if !Self::root_viewport_admitted(ctx) {
return;
}
#[cfg(not(target_arch = "wasm32"))]
self.poll_print_receipt(ctx);
self.tick_hidden_show(ctx, web_time::Instant::now());
if WindowHost::of(ctx).injected_idle() {
self.drain_intake(ctx);
@@ -399,8 +416,7 @@ impl SlideApp {
updates_ui::tick(self, ctx);
self.take_file_answers();
}
// AutoRecover writes the app's own folder, also while an agent's input is handled.
deckcraft_engine::file_access::unconfined(|| self.autosave_if_due(ctx));
self.autosave_if_due(ctx);
self.tick_media_clock(ctx);
// Exit work must finish before the platform quits inside this callback.
embed::logic(ctx, || {
@@ -414,25 +430,10 @@ impl SlideApp {
/// Lays out the title, ribbon, status and document, or the one active full-window page.
pub fn ui(&mut self, ui: &mut egui::Ui) {
let roots = self.agent_scope();
deckcraft_engine::file_access::confine(roots.as_ref(), || self.ui_pass(ui));
self.settle_agent_input(ui.ctx());
}
fn ui_pass(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
if !Self::root_viewport_admitted(&ctx) {
return;
}
// The language every label this pass draws is looked up in (Preferences › Language).
let lang = crate::i18n::Lang::from_pref(&self.ui.language);
crate::i18n::set_current(lang);
// craft-ui draws its own words and `Word` labels in the host's language: a new host on a switch.
let host_lang = crate::i18n::host_lang(lang);
if self.host.i18n().is_some() && self.host.lang() != host_lang {
self.host = self.host.with_lang(host_lang);
self.host.clone().install(&ctx);
}
let started = craft::platform::clock::monotonic_ms();
self.media.sync_video_textures(&ctx);
self.sync_backstage();
@@ -500,7 +501,7 @@ impl SlideApp {
&entries,
&craft::ui::menu::search::Synonyms::of(&view.words::<craft::ui::menu::search::SearchWords>()),
);
let out = craft::ui::patterns::panels::CommandPalette::new(tl!("Command Palette"), &entries, &index, Bind::bound(&mut self.palette_open))
let out = craft::ui::patterns::panels::CommandPalette::new("Command Palette", &entries, &index, Bind::bound(&mut self.palette_open))
.state(Bind::bound(&mut self.palette_state))
.recents(Bind::bound(&mut self.palette_recents))
.show(ui);
+1 -19
View File
@@ -58,13 +58,12 @@ pub static UI_COMMANDS: &[UiCommand] = &[
UiCommand {
id: "app.print",
label: "Print",
params: "{layout?, perPage?, slides?, includeHidden?, frame?, paper?: letter|a4|legal|a3, orientation?: portrait|landscape}",
params: "{layout?, perPage?, slides?, includeHidden?, frame?, paper?: letter|a4|legal|a3, orientation?: portrait|landscape} (no options opens desktop print settings when a system spooler is installed)",
},
UiCommand { id: "app.about", label: "About DeckCraft", params: "{}" },
UiCommand { id: "app.checkUpdates", label: "Check for Updates…", params: "{}" },
UiCommand { id: "app.palette", label: "Command Palette", params: "{}" },
UiCommand { id: "app.preferences", label: "Preferences…", params: "{}" },
UiCommand { id: "app.language", label: "Interface Language", params: "{language?: auto|en|de} → {language, current, available}" },
UiCommand { id: "app.openDialog", label: "Open…", params: "{purpose?}" },
UiCommand { id: "app.forgetRecent", label: "Remove from Recent", params: "{path} → {recent: [paths]}" },
UiCommand { id: "app.insertPictureDialog", label: "Picture from File…", params: "{}" },
@@ -261,25 +260,8 @@ pub(crate) fn command_states(app: &mut SlideApp) -> CommandStates {
states.set(def.command.clone(), CommandState::new().enabled(enabled));
}
crate::ribbon::states::publish(app, &mut states);
translate_labels(app, &mut states);
states
}
/// Gives every catalogue command its label in the interface language for this frame. The catalogue keeps the
/// English labels (its ids and the palette's search use them), so a language switch shows at once.
fn translate_labels(app: &SlideApp, states: &mut CommandStates) {
if crate::i18n::current() == crate::i18n::Lang::EN {
return;
}
for def in app.catalog.defs() {
let shown = crate::i18n::t_flat(&def.label);
if shown == def.label {
continue;
}
let state = states.get(&def.command).cloned().unwrap_or_else(CommandState::new);
states.set(def.command.clone(), state.title(shown));
}
}
/// Commands admitted while no document is open.
pub(crate) const START_SCREEN: &[&str] = &["app.openDialog", "app.palette", "app.preferences", "app.backstage", "file.new"];
+11 -29
View File
@@ -3,7 +3,6 @@ use super::files::SaveOutcome;
#[cfg(not(target_arch = "wasm32"))]
use super::updates_ui;
use super::{SlideApp, Value, ViewMode, backstage, doc_window, json, media, qat};
use crate::i18n;
use craft::ui::patterns::panels::CommandPalette;
use craft::ui::runtime::commands::{FirePhase, FireSource, Fired};
@@ -35,7 +34,12 @@ impl SlideApp {
match self.session.active() {
Some(d) => {
let uid = d.uid;
let (name, _, _) = super::files::save_target(d.path.as_deref(), &d.title());
let name = d
.path
.as_deref()
.and_then(|path| std::path::Path::new(path).file_name())
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| format!("{}.deckcraft", d.title()));
match self.save_document(uid) {
SaveOutcome::Saved | SaveOutcome::Downloaded => Ok(json!({"path": name})),
SaveOutcome::Pending => Ok(json!({"path": name, "pending": true})),
@@ -71,13 +75,6 @@ impl SlideApp {
r
}
/// The `language` setting, the language the interface is drawn in, and every one it can be
/// (`app.language`).
fn language_state(&self) -> Value {
let available: Vec<Value> = i18n::Lang::all().map(|l| json!({"code": l.code(), "name": l.name()})).collect();
json!({"language": self.ui.language, "current": i18n::Lang::from_pref(&self.ui.language).code(), "available": available})
}
fn flag(&mut self, params: &Value, cur: bool) -> bool {
params.get("on").and_then(Value::as_bool).unwrap_or(!cur)
}
@@ -278,6 +275,11 @@ impl SlideApp {
if self.session.active().is_none() {
return Err("nothing to print: no presentation is open".into());
}
#[cfg(not(target_arch = "wasm32"))]
if self.print_spool.is_some() && (p.is_null() || p.as_object().is_some_and(|args| args.is_empty())) {
self.open_backstage(backstage::Page::Print);
return Ok(json!({"printed": false, "page": "print"}));
}
return Ok(json!({"printed": self.print_pdf(p.clone())}));
}
"app.about" => self.open_dialog("about", p.clone()),
@@ -295,16 +297,6 @@ impl SlideApp {
self.palette_open = true;
}
"app.preferences" => self.open_dialog("preferences", p.clone()),
"app.language" => {
if let Some(v) = p.get("language") {
let code = v.as_str().and_then(i18n::normalize_pref).ok_or_else(|| {
let offered: Vec<&str> = std::iter::once(i18n::AUTO).chain(i18n::Lang::all().map(i18n::Lang::code)).collect();
format!("`language` must be one of {}", offered.join(", "))
})?;
self.ui.language = code.to_string();
}
return Ok(self.language_state());
}
"app.openDialog" => self.pick_and_open(),
"app.forgetRecent" => {
let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?;
@@ -394,16 +386,6 @@ impl SlideApp {
if fired.source == FireSource::Palette {
CommandPalette::remember(&mut self.palette_recents, fired.command.clone());
}
// Ctrl+= and Ctrl+Shift+= are also Subscript and Superscript: the key formats while text or shapes are
// selected and zooms only with nothing to format. Buttons keep zooming.
let id = if id == "view.zoomIn"
&& fired.source == FireSource::Key
&& self.session.active().is_some_and(|d| d.selection.text.is_some() || !d.selection.shapes.is_empty())
{
if fired.mods.shift || ctx.input(|i| i.modifiers.shift) { "format.superscript" } else { "format.subscript" }
} else {
id
};
match id {
"edit.paste" => self.paste(ctx, fired.pasted.clone()),
"edit.copy" | "edit.cut" if fired.command.key_text().as_ref() == fired.command.id.as_str() => {
+1 -55
View File
@@ -1,41 +1,21 @@
use std::sync::Arc;
use craft::automation::screenshot::settle_ms;
use craft::ui::runtime::{frame, windows::WindowHost};
use deckcraft_engine::file_access::{self, AutomationRoots};
use super::SlideApp;
use crate::control;
/// The agent folders an agent's request leaves in force while the input it queued is handled.
pub(crate) struct AgentInput {
roots: Arc<AutomationRoots>,
/// The frame the window host was first seen with no queued input left, once it was.
idle_since: Option<u64>,
}
impl SlideApp {
/// Drains requests between injected gestures, once a frame before its input: a request is input, which enters a
/// frame's first pass only, and the command states the frame's passes show are taken after it ran.
/// The agents link's requests run with the agent folders in force ([`crate::agents`]).
pub(crate) fn drain_control(&mut self, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
crate::agents::sync(self, ctx);
let Some(mut channel) = self.control.take() else { return };
let host = WindowHost::of(ctx);
if host.injected_idle() {
channel.poll_access_trees(ctx);
}
let roots = self.control_roots.clone();
while host.injected_idle() {
let Some(request) = channel.next_request() else { break };
let reply = file_access::confine(roots.as_ref(), || control::handle(self, ctx, &request));
// The keys and clicks it queued fire their commands in later passes: they stay held to the folders.
if let Some(roots) = &roots
&& !host.injected_idle()
{
self.agent_input = Some(AgentInput { roots: roots.clone(), idle_since: None });
}
let reply = control::handle(self, ctx, &request);
channel.settle(request, reply, control::document_id(self), settle_ms(ctx.global_style().animation_time));
}
let document = control::document_id(self);
@@ -45,40 +25,6 @@ impl SlideApp {
self.control = Some(channel);
}
/// The folders in force for this pass: the agent folders while input an agent queued is still
/// to be handled, otherwise none (the person's own input).
pub(crate) fn agent_scope(&self) -> Option<Arc<AutomationRoots>> {
self.agent_input.as_ref().map(|input| input.roots.clone())
}
/// After a UI pass: once the window host has handled all the queued input, and one more frame
/// has passed (a shortcut fires its command in the next frame's input), the agent folders are
/// no longer in force.
pub(crate) fn settle_agent_input(&mut self, ctx: &egui::Context) {
let Some(input) = self.agent_input.as_mut() else { return };
if !WindowHost::of(ctx).injected_idle() {
input.idle_since = None;
return;
}
let frame = ctx.cumulative_frame_nr();
match input.idle_since {
None => {
input.idle_since = Some(frame);
ctx.request_repaint();
}
Some(since) if frame > since => self.agent_input = None,
Some(_) => {}
}
}
/// Lets agents into this window while the ArtCraft Launcher's switch names DeckCraft
/// ([`crate::agents`]): their requests, the input they queue and the files the window opens and
/// saves for them stay inside the agent folders.
#[cfg(not(target_arch = "wasm32"))]
pub fn with_agents(&mut self, agents: crate::agents::Agents) {
self.agents = Some(Box::new(agents));
}
/// Polls input after each pass and issues captures only after the accepted layout.
/// A rerun contributes no capture settling pass or issue.
pub(crate) fn issue_captures(&mut self, ui: &mut egui::Ui) {
+42 -62
View File
@@ -4,7 +4,7 @@ use std::rc::Rc;
use std::sync::Arc;
use craft::host::{PickId, PickRequest, Picked, WriteIntent};
use deckcraft_engine::cmd::file::{WRITABLE_EXTENSIONS, format_for_path, mark_saved_snapshot, save_bytes, writable_format_for_path};
use deckcraft_engine::cmd::file::{format_for_path, mark_saved_snapshot, save_bytes};
use deckcraft_model::Presentation;
use super::{FilePlace, FilePurpose, FileTarget, LocatedPlace, RECENT_MAX, SlideApp, Target, UiRequest, Value, ViewMode, json, media};
@@ -257,14 +257,24 @@ impl SlideApp {
self.submit_save(uid, None, files, &suggested, false, instance)
}
/// File › Print: DeckCraft prints through a PDF. On the desktop the PDF (with the Print page's
/// layout, slides and options) is written to the temporary folder and opened in the system's
/// PDF viewer, which has the printers; on the web it downloads.
/// File › Print: use the same PDF layout, slides and options with the host's available route.
/// The browser opens its print dialog when installed. Other hosts open their viewer or export.
pub fn print_pdf(&mut self, params: Value) -> bool {
if self.session.active().is_none() {
return false;
}
let Some(active) = self.session.active() else { return false };
let params = if params.is_object() { params } else { json!({}) };
if let Some(print) = self.services.browser_print.as_mut() {
let result = deckcraft_engine::cmd::file::pdf_bytes(&active.doc, &params).map_err(|e| e.to_string()).and_then(|bytes| print(&bytes));
match result {
Ok(()) => {
self.set_status("Opening the browser print dialog");
return true;
}
Err(error) => {
self.set_status(format!("Couldn't open the browser print dialog: {error}"));
return false;
}
}
}
#[cfg(not(target_arch = "wasm32"))]
if !self.host.files().browser_saves() {
return self.print_preview(params);
@@ -272,6 +282,13 @@ impl SlideApp {
self.export_as("pdf", params)
}
/// The Print page's "Open as PDF instead": the print PDF in the system's PDF viewer.
#[cfg(not(target_arch = "wasm32"))]
pub fn print_pdf_viewer(&mut self, params: Value) -> bool {
let params = if params.is_object() { params } else { json!({}) };
self.print_preview(params)
}
/// Writes the print PDF to a private temporary file and opens it in the system's PDF viewer.
#[cfg(not(target_arch = "wasm32"))]
fn print_preview(&mut self, mut params: Value) -> bool {
@@ -310,9 +327,6 @@ impl SlideApp {
}
pub fn open_path(&mut self, path: &str) -> Result<(), String> {
if self.show_if_open(path) {
return Ok(());
}
let files = self.host.files();
let loaded = deckcraft_engine::cmd::file::read_presentation_file_with(
path,
@@ -481,10 +495,9 @@ impl SlideApp {
/// It opens as File › Open opens it on the desktop: a presentation as itself, an outline
/// (.txt, .md, .rtf) as a new untitled presentation. The name is the presentation's file only
/// when the page sent one with a presentation extension and the file is an intact
/// presentation, so Save hands it back under that name and format (except a type DeckCraft
/// can't write, such as a legacy .slidecraft, which Save writes as a new .deckcraft); anything
/// else (no name, an outline, a damaged file opened as a repaired copy) is untitled, and its
/// first Save is a new file. The first presentation that opens takes the place of the empty one host mode started
/// presentation, so Save hands it back under that name and format; anything else (no name, an
/// outline, a damaged file opened as a repaired copy) is untitled, and its first Save is a new
/// file. The first presentation that opens takes the place of the empty one host mode started
/// with ([`Self::start_for_host`]), if that one is still open, untitled and unchanged; later
/// files open beside the others.
pub fn open_from_host(&mut self, name: Option<&str>, bytes: &[u8]) {
@@ -829,17 +842,13 @@ impl SlideApp {
return outcome;
};
let snapshot = d.doc.clone();
let mut own = d.path.clone();
let title = d.title();
let (name, format, refused) = save_target(own.as_deref(), &title);
if let Some(original) = refused {
// A file DeckCraft can't write (.pptm, a legacy .slidecraft …) is never written in
// place: Save asks for a new file instead, as an untitled document's Save does.
let ext = Path::new(&name).extension().unwrap_or_default().to_string_lossy();
self.set_status(format!("DeckCraft can't save {original} in its file type; choose a name to save a copy as .{ext}"));
own = None;
}
let bytes = match save_bytes(&snapshot, format) {
let own = d.path.clone();
let name = own
.as_deref()
.and_then(|p| Path::new(p).file_name())
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| format!("{}.deckcraft", d.title()));
let bytes = match save_bytes(&snapshot, format_for_path(&name)) {
Ok(bytes) => bytes,
Err(e) => {
let outcome = self.file_failure(e.to_string());
@@ -1020,22 +1029,14 @@ impl SlideApp {
path.to_path_buf()
};
let encoded;
let bytes = match &transfer.snapshot {
Some(snapshot) => {
// A document is never written under a name whose type DeckCraft can't write
// (a Save As typed back to .pptm): its bytes would not be that type.
let format = writable_format_for_path(&out.to_string_lossy()).ok_or_else(|| {
format!("DeckCraft can't save the file type of {}; it saves as .{}", out.display(), WRITABLE_EXTENSIONS.join(", ."))
})?;
if format == format_for_path(name) {
bytes
} else {
// The picker may choose a different writable extension; the captured snapshot stays fixed.
encoded = save_bytes(snapshot, format).map_err(|e| e.to_string())?;
&encoded
}
}
None => bytes,
let bytes = if let Some(snapshot) = &transfer.snapshot
&& format_for_path(name) != format_for_path(&out.to_string_lossy())
{
// The picker may choose a different writable extension; the captured snapshot stays fixed.
encoded = save_bytes(snapshot, format_for_path(&out.to_string_lossy())).map_err(|e| e.to_string())?;
&encoded
} else {
bytes
};
self.host.files().write(&out, bytes, intent).map_err(|e| e.to_string())?;
}
@@ -1043,27 +1044,6 @@ impl SlideApp {
}
}
/// The file name Save writes or suggests for a document at `path` titled `title`, the format it
/// is written in, and, when the file at `path` is of a type DeckCraft can't write, that file's
/// name: Save never writes it in place but asks for `<title>.pptx` (`<title>.deckcraft` for a
/// legacy `.slidecraft`) instead. An untitled document is suggested `<title>.deckcraft`.
pub(crate) fn save_target(path: Option<&str>, title: &str) -> (String, &'static str, Option<String>) {
let Some(current) = path.and_then(|p| Path::new(p).file_name()).map(|n| n.to_string_lossy().into_owned()) else {
let name = format!("{title}.deckcraft");
let format = format_for_path(&name);
return (name, format, None);
};
match writable_format_for_path(&current) {
Some(format) => (current, format, None),
None => {
let ext = if current.to_ascii_lowercase().ends_with(".slidecraft") { "deckcraft" } else { "pptx" };
let name = format!("{title}.{ext}");
let format = format_for_path(&name);
(name, format, Some(current))
}
}
}
fn image_file_name(stem: &str, ext: &str, index: usize, single: bool) -> String {
if single { format!("{stem}.{ext}") } else { format!("{stem}{}.{ext}", index + 1) }
}
+8 -4
View File
@@ -206,6 +206,9 @@ pub struct Backstage {
pub print_landscape: bool,
/// Zero-based page displayed by the print preview.
pub preview_page: usize,
/// Desktop: printing straight to a printer from the Print page.
#[cfg(not(target_arch = "wasm32"))]
pub direct_print: print::DirectPrint,
/// The selected export task.
pub export: ExportTask,
/// Export › Change File Type / Save As: the chosen type (an [`SAVE_TYPES`] id).
@@ -237,6 +240,8 @@ impl Backstage {
print_paper: "letter",
print_landscape: false,
preview_page: 0,
#[cfg(not(target_arch = "wasm32"))]
direct_print: print::DirectPrint::default(),
export: ExportTask::Pdf,
file_type: "pptx",
handouts_per_page: 3,
@@ -290,13 +295,12 @@ fn act(app: &mut SlideApp, nav: Nav, current: Page) -> Option<Page> {
}
}
/// The side menu's entries, captioned in the interface language each pass (the [`Nav`] keys stay English).
fn view_entries(group: Vec<Nav>) -> Vec<BackstageEntry<'static, Nav>> {
group
.into_iter()
.map(|nav| match nav {
Nav::Page(_) => BackstageEntry::page(nav, tl!(nav.label()), nav.icon().id()),
_ => BackstageEntry::action(nav, tl!(nav.label()), nav.icon().id()),
Nav::Page(_) => BackstageEntry::page(nav, nav.label(), nav.icon().id()),
_ => BackstageEntry::action(nav, nav.label(), nav.icon().id()),
})
.collect()
}
@@ -324,7 +328,7 @@ pub(crate) fn page(app: &mut SlideApp, ui: &mut Ui, cx: &mut BodyCx<'_>) {
.bottom(&bottom)
.focus_shown(focus_shown);
if bs.page != Page::Home {
view = view.heading(tl!(bs.page.label()));
view = view.heading(bs.page.label());
}
let mut out = Outcome::default();
let shown = view.show(ui, cx, |ui, cx| {
+25 -28
View File
@@ -36,7 +36,7 @@ struct NewTile {
impl NewTile {
fn blank() -> Self {
Self { key: NewChoice::Blank, label: tl!("Blank Presentation").into(), detail: String::new(), theme: None }
Self { key: NewChoice::Blank, label: "Blank Presentation".into(), detail: String::new(), theme: None }
}
}
@@ -56,7 +56,7 @@ fn theme_tiles(query: &str, limit: usize, blank: bool) -> Vec<NewTile> {
if (query.is_empty() || "sample deck northern lights".contains(&query)) && tiles.len() - usize::from(blank) < limit {
tiles.push(NewTile {
key: NewChoice::Sample,
label: tl!("Sample deck: Northern Lights").into(),
label: "Sample deck: Northern Lights".into(),
detail: String::new(),
theme: themes.into_iter().find(|theme| theme.name == "DeckCraft"),
});
@@ -88,7 +88,7 @@ const BLANK_ZOOM: f64 = 1.5625;
/// scales the card thumbnail.
fn show_tiles(app: &mut SlideApp, ui: &mut Ui, label: &'static str, tiles: &[NewTile], zoom: f64) {
let source = keyed(tiles, |tile: &NewTile| tile.key.clone()).with_text(|tile| Cow::Borrowed(tile.label.as_str()));
let grid = TileGrid::<NewChoice>::new(tl!(label))
let grid = TileGrid::<NewChoice>::new(label)
.select(SelectMode::Single)
.activate(ActivateOn::Click)
.caption(CaptionPlace::BelowWrapped)
@@ -153,16 +153,16 @@ fn recent_files(app: &mut SlideApp, query: &str) -> Vec<RecentFile> {
.into_iter()
.map(|path| {
let file = RecentFile::new(&path, split_path(&path).0);
if app.recent_exists(&path) { file } else { file.note(tl!("(missing)")) }
if app.recent_exists(&path) { file } else { file.note("(missing)") }
})
.collect()
}
fn recent_empty(query: &str) -> String {
if query.trim().is_empty() {
tl!("Presentations you open show up here. Use Open to browse for one.").into()
"Presentations you open show up here. Use Open to browse for one.".into()
} else {
crate::i18n::fmt(tl!("No recent presentations match “{query}”."), &[("query", query.trim())])
format!("No recent presentations match “{}”.", query.trim())
}
}
@@ -188,23 +188,23 @@ fn recent_actions(app: &mut SlideApp, actions: Vec<StartAction>) {
pub(super) fn home(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &mut Backstage, out: &mut Outcome) {
Row::new().show(ui, |ui, _| {
// PLAN: assumed assets/app-icon/deckcraft-mark.svg (dialogs-w18)
let _ = Picture::svg(tl!("DeckCraft"), include_bytes!("../../../../assets/app-icon/deckcraft-mark.svg"))
let _ = Picture::svg("DeckCraft", include_bytes!("../../../../assets/app-icon/deckcraft-mark.svg"))
.extent(PictureSize::Thumb(ThumbSize::Medium))
.show(ui);
let _ = Text::new(tl!("DeckCraft")).role(TypeRole::Display).show(ui);
let _ = Text::new("DeckCraft").role(TypeRole::Display).show(ui);
});
// Plain page headings, as the New page's, with the link to the rest at their end.
let heading = |title: &'static str| Section::fixed(tl!(title)).strength(HeaderStrength::Heading).quiet_header();
let heading = |title: &'static str| Section::fixed(title).strength(HeaderStrength::Heading).quiet_header();
heading("New")
.controls(|ui, _| {
if clicked(&Link::new(tl!("More themes")).show(ui)) {
if clicked(&Link::new("More themes").show(ui)) {
out.page = Some(Page::New);
}
})
.show(ui, |ui, _| show_tiles(app, ui, "New presentations", &theme_tiles("", 5, true), THEME_ZOOM));
heading("Templates")
.controls(|ui, _| {
if clicked(&Link::new(tl!("More templates")).show(ui)) {
if clicked(&Link::new("More templates").show(ui)) {
out.page = Some(Page::New);
}
})
@@ -216,33 +216,30 @@ pub(super) fn home(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &m
.max_recent(8)
.empty(empty)
.controls(|ui, _| {
let _ = TextField::search(tl!("Search for a file"), Bind::bound(&mut bs.query)).placeholder(tl!("Search for a file")).show(ui);
let _ = TextField::search("Search for a file", Bind::bound(&mut bs.query)).placeholder("Search for a file").show(ui);
})
.show(ui);
recent_actions(app, shown.actions);
if app.ui.recent.len() > 8 && clicked(&Link::new(tl!("More presentations")).show(ui)) {
if app.ui.recent.len() > 8 && clicked(&Link::new("More presentations").show(ui)) {
out.page = Some(Page::Open);
}
let _ = Link::new(tl!("Join the ArtCraft community on Discord")).url(deckcraft_engine::links::DISCORD).show(ui);
let _ = Link::new("Join the ArtCraft community on Discord").url(deckcraft_engine::links::DISCORD).show(ui);
}
/// A blank presentation, every matching theme and the starter templates.
pub(super) fn new_page(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &mut Backstage) {
show_tiles(app, ui, "Blank presentation", &[NewTile::blank()], BLANK_ZOOM);
let _ = Divider::horizontal().show(ui);
let _ = TextField::search(tl!("Search for themes and templates"), Bind::bound(&mut bs.query))
.placeholder(tl!("Search for themes and templates"))
.show(ui);
let _ = TextField::search("Search for themes and templates", Bind::bound(&mut bs.query)).placeholder("Search for themes and templates").show(ui);
let themes = theme_tiles(&bs.query, usize::MAX, false);
let templates = template_tiles(&bs.query, usize::MAX);
show_tiles(app, ui, "Themes", &themes, THEME_ZOOM);
if bs.query.trim().is_empty() || !templates.is_empty() {
let _ = Text::new(tl!("Templates")).role(TypeRole::Heading).show(ui);
let _ = Text::new("Templates").role(TypeRole::Heading).show(ui);
show_tiles(app, ui, "Starter templates", &templates, THEME_ZOOM);
}
if themes.is_empty() && templates.is_empty() {
let _ =
Text::new(crate::i18n::fmt(tl!("No themes or templates match “{query}”."), &[("query", bs.query.trim())])).shade(Shade::Muted).show(ui);
let _ = Text::new(format!("No themes or templates match “{}”.", bs.query.trim())).shade(Shade::Muted).show(ui);
}
}
@@ -271,15 +268,15 @@ pub(super) fn open_page(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, b
let places = [Place::Recent, Place::Browse];
let source = keyed(&places, |place: &Place| *place);
let shown = in_places(ui, |ui| {
List::new(tl!("Open from"))
List::new("Open from")
.select(SelectMode::Single)
.selection(Bind::given(Selection::single(Place::Recent)))
.activate(ActivateOn::Click)
.sizing(Sizing::FillWidth)
.natural_height(true)
.show_items(ui, &source, &mut |place, _| match place {
Place::Recent => ListRow::new(tl!("Recent")).icon(Icon::Recent.id().into()),
Place::Browse => ListRow::new(tl!("Browse")).icon(Icon::OpenFolder.id().into()),
Place::Recent => ListRow::new("Recent").icon(Icon::Recent.id().into()),
Place::Browse => ListRow::new("Browse").icon(Icon::OpenFolder.id().into()),
})
});
for event in shown.events {
@@ -287,10 +284,10 @@ pub(super) fn open_page(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, b
let _ = app.run("app.openDialog", json!({}));
}
}
if app.session.recovery_dir.is_some() && clicked(&Button::new(tl!("Recover Unsaved Presentations")).show(ui)) {
if app.session.recovery_dir.is_some() && clicked(&Button::new("Recover Unsaved Presentations").show(ui)) {
match app.run("file.recovery.open", json!({})) {
Ok(value) if value.get("opened").and_then(Value::as_array).is_some_and(|opened| opened.is_empty()) => {
app.set_status(tl!("There are no unsaved presentations to recover"));
app.set_status("There are no unsaved presentations to recover");
}
_ => {}
}
@@ -301,8 +298,8 @@ pub(super) fn open_page(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, b
// A search box keeps one width while its query changes, as production's does, not its text's.
Row::new().show(ui, |ui, _| {
Stack::new().least_width(LeastWidth::Palette).show(ui, |ui, _| {
let _ = TextField::search(tl!("Search for a file"), Bind::bound(&mut bs.query))
.placeholder(tl!("Search for a file"))
let _ = TextField::search("Search for a file", Bind::bound(&mut bs.query))
.placeholder("Search for a file")
.sizing(Sizing::FillWidth)
.show(ui);
});
@@ -310,7 +307,7 @@ pub(super) fn open_page(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, b
let files = recent_files(app, &bs.query);
let shown = RecentList::new(&files)
.remove(RecentRemove::Always)
.heading(tl!("Presentations"))
.heading("Presentations")
.heading_sections()
.empty(recent_empty(&bs.query))
.show(ui);
+19 -19
View File
@@ -50,7 +50,7 @@ pub(super) fn task_row(ui: &mut Ui, icon: Icon, label: &'static str, title: &'st
let pressed = Button::new(label).icon(icon.id()).arrangement(Arrangement::Stacked).enabled(enabled).show(ui).clicked();
Stack::new().wrap_width(WrapWidth::Column).show(ui, |ui, _| {
Text::new(title).role(TypeRole::Heading).show(ui);
Text::new(tl!(detail)).shade(Shade::Muted).show(ui);
Text::new(detail).shade(Shade::Muted).show(ui);
});
pressed
})
@@ -61,24 +61,24 @@ pub(super) fn task_row(ui: &mut Ui, icon: Icon, label: &'static str, title: &'st
/// The presentation's location, inspection actions and editable document properties.
pub(super) fn info(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &mut Backstage) {
let Ok(v) = app.session.execute("file.info", &json!({})) else {
Text::new(tl!("No presentation is open.")).shade(Shade::Muted).show(ui);
Text::new("No presentation is open.").shade(Shade::Muted).show(ui);
return;
};
let path = v.get("path").and_then(Value::as_str).map(str::to_string);
let title = v.get("title").and_then(Value::as_str).unwrap_or("");
let dirty = v.get("dirty").and_then(Value::as_bool).unwrap_or(false);
Text::new(title.to_string()).role(TypeRole::Display).tone(Tone::Accent).show(ui);
Text::new(path.as_deref().unwrap_or(tl!("Not saved yet")).to_string()).shade(Shade::Muted).show(ui);
Text::new(path.as_deref().unwrap_or("Not saved yet").to_string()).shade(Shade::Muted).show(ui);
if let Some(path) = &path {
Row::new().wrap(true).show(ui, |ui, _| {
if Button::new(tl!("Copy path")).show(ui).clicked() {
if Button::new("Copy path").show(ui).clicked() {
match ClipboardHandle::of(ui.ctx()).offer(&[ClipItem::Text(path.as_str().into())]) {
Ok(_) => app.set_status("Copied the path"),
Err(reason) => app.set_status(reason.to_string()),
}
}
#[cfg(not(target_arch = "wasm32"))]
if Button::new(tl!("Open file location")).show(ui).clicked() {
if Button::new("Open file location").show(ui).clicked() {
app.reveal_file(std::path::PathBuf::from(path));
}
});
@@ -105,14 +105,14 @@ pub(super) fn info(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &m
}
});
Stack::new().show(ui, |ui, _| {
Text::new(tl!("Properties")).role(TypeRole::Heading).show(ui);
Text::new("Properties").role(TypeRole::Heading).show(ui);
let props = v.get("properties").cloned().unwrap_or_default();
// The values stand in their own column, apart from the longest name ("Hidden slides").
let wide = |overrides: &mut Overrides| {
overrides.values.set(LabelGap::Section);
};
with_env(ui, wide, |ui| {
FieldGroup::new(tl!("Properties")).labels(LabelScheme::Inspector).show(ui, |ui, _| {
FieldGroup::new("Properties").labels(LabelScheme::Inspector).show(ui, |ui, _| {
let readout = |ui: &mut Ui, label: &'static str, value: String| {
Field::new(label).layout(FieldLayout::Beside).value(value.clone()).show(ui, |ui, _| {
Text::new(value.clone()).show(ui);
@@ -139,7 +139,7 @@ pub(super) fn info(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &m
}
});
}
readout(ui, "Location", path.clone().unwrap_or_else(|| tl!("Not saved yet").into()));
readout(ui, "Location", path.clone().unwrap_or_else(|| "Not saved yet".into()));
})
});
});
@@ -177,10 +177,10 @@ pub fn format_bytes(b: u64) -> String {
pub(super) fn save_as(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &mut Backstage, out: &mut Outcome) {
let (title, path) = app.session.active().map(|doc| (doc.title(), doc.path.clone())).unwrap_or_default();
Text::new(title).role(TypeRole::Heading).show(ui);
Text::new(path.as_deref().unwrap_or(tl!("Not saved yet")).to_string()).shade(Shade::Muted).show(ui);
Text::new(path.as_deref().unwrap_or("Not saved yet").to_string()).shade(Shade::Muted).show(ui);
let entries: Vec<_> = SAVE_TYPES.iter().map(|(id, label, _)| Entry::new(*id, *label)).collect();
Field::new(tl!("Save as type")).show(ui, |ui, _| {
Select::new(tl!("Save as type"), Bind::bound(&mut bs.file_type), &entries).show(ui);
Field::new("Save as type").show(ui, |ui, _| {
Select::new("Save as type", Bind::bound(&mut bs.file_type), &entries).show(ui);
});
let files = app.host.files();
let download = files.browser_saves() && !files.saves_to_page();
@@ -205,7 +205,7 @@ pub(super) fn save_as(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs:
}
}
if let Some((_, _, detail)) = SAVE_TYPES.iter().find(|entry| entry.0 == bs.file_type) {
Text::new(tl!(*detail)).shade(Shade::Muted).show(ui);
Text::new(*detail).shade(Shade::Muted).show(ui);
}
}
@@ -213,27 +213,27 @@ pub(super) fn save_as(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs:
pub(super) fn about(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>) {
Row::new().wrap(true).show(ui, |ui, _| {
Stack::new().wrap_width(WrapWidth::Column).show(ui, |ui, _| {
Text::new(tl!("Product Information")).role(TypeRole::Heading).show(ui);
Text::new("Product Information").role(TypeRole::Heading).show(ui);
Row::new().show(ui, |ui, _| {
Picture::svg(tl!("DeckCraft"), include_bytes!("../../../../assets/app-icon/deckcraft-mark.svg")).show(ui);
Text::styled(vec![Span::new(tl!("DeckCraft")).strong()]).role(TypeRole::Display).show(ui);
Picture::svg("DeckCraft", include_bytes!("../../../../assets/app-icon/deckcraft-mark.svg")).show(ui);
Text::styled(vec![Span::new("DeckCraft").strong()]).role(TypeRole::Display).show(ui);
});
Text::new(crate::dialogs::version_line()).shade(Shade::Muted).show(ui);
Text::new(tl!("Open source under MIT OR Apache-2.0. Not affiliated with Microsoft.")).shade(Shade::Muted).show(ui);
Text::new("Open source under MIT OR Apache-2.0. Not affiliated with Microsoft.").shade(Shade::Muted).show(ui);
if task_row(ui, Icon::Help, "Credits", "Credits", "The people and models who built DeckCraft.", true) {
let _ = app.run("app.about", json!({}));
}
for (label, url) in
[("Join our community on Discord", deckcraft_engine::links::DISCORD), ("Source on GitHub", deckcraft_engine::links::GITHUB)]
{
Link::new(tl!(label)).url(url).show(ui);
Link::new(label).url(url).show(ui);
}
});
Stack::new().sizing(Sizing::Content).show(ui, |ui, _| {
Text::new(tl!("Appearance")).role(TypeRole::Heading).show(ui);
Text::new("Appearance").role(TypeRole::Heading).show(ui);
let dark = app.ui.brightness == crate::state::Brightness::Dark;
let entries = [Entry::new(false, "Light"), Entry::new(true, "Dark")];
if let Some(on) = Select::new(tl!("Appearance"), Bind::given(dark), &entries).show(ui).value() {
if let Some(on) = Select::new("Appearance", Bind::given(dark), &entries).show(ui).value() {
let _ = app.run("view.dark", json!({"on": on}));
}
});
+147 -43
View File
@@ -21,6 +21,8 @@ use craft::ui::primitives::{ContentPainterCx, DocRun, DocText, PaintShape};
use craft::ui::style::{Corners, DataColor, SurfaceKind, TypeRole};
use craft::ui::text::TextField;
use egui::{Color32, Rect, Shape, Stroke, StrokeKind, pos2, vec2};
#[cfg(not(target_arch = "wasm32"))]
use std::rc::Rc;
use std::sync::Arc;
/// The slides the Print page prints, in order (0-based).
@@ -85,7 +87,7 @@ pub(crate) const LAYOUTS: [(&str, &str); 8] = [
/// Print settings and a preview of the filtered pages, in their print order.
pub(super) fn print(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &mut Backstage) {
let Some((doc, current)) = app.session.active().map(|state| (state.doc.clone(), state.selection.slide)) else {
Text::new(tl!("No presentation is open.")).shade(Shade::Muted).show(ui);
Text::new("No presentation is open.").shade(Shade::Muted).show(ui);
return;
};
const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)];
@@ -94,50 +96,66 @@ pub(super) fn print(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &
let mut range_changed = false;
Stack::new().wrap_width(WrapWidth::Column).show(ui, |ui, _| {
let good_range = slides.as_ref().is_ok_and(|slides| !slides.is_empty());
let detail = if app.host.files().can_pick() {
"DeckCraft prints through a PDF: it opens in your PDF viewer, where you choose the printer."
} else {
"DeckCraft prints through a PDF: it downloads, ready to print from your browser or PDF viewer."
};
if task_row(ui, Icon::Print, "Print", "Print", detail, good_range)
&& let Ok(slides) = &slides
{
app.print_pdf(print_params(bs, slides));
#[cfg(not(target_arch = "wasm32"))]
let direct = app.print_spool.is_some();
#[cfg(target_arch = "wasm32")]
let direct = false;
#[cfg(not(target_arch = "wasm32"))]
if direct {
direct_print(app, ui, bs, &doc, slides.as_ref().ok().filter(|slides| !slides.is_empty()));
}
Text::new(tl!("Settings")).role(TypeRole::Heading).show(ui);
FieldGroup::new(tl!("Settings")).show(ui, |ui, _| {
if !direct {
let browser = app.services.browser_print.is_some();
let detail = if browser {
"Opens the browser print dialog for the selected slides."
} else {
"DeckCraft prints through a PDF, ready to open in your browser or PDF viewer."
};
if task_row(ui, Icon::Print, "Print", "Print", detail, good_range)
&& let Ok(slides) = &slides
{
app.print_pdf(print_params(bs, slides));
}
if browser
&& let Ok(slides) = &slides
&& !slides.is_empty()
&& Link::new("Export PDF instead").show(ui).clicked()
{
app.export_as("pdf", print_params(bs, slides));
}
}
Text::new("Settings").role(TypeRole::Heading).show(ui);
FieldGroup::new("Settings").show(ui, |ui, _| {
let scopes = [
Entry::new(PrintScope::All, "Print All Slides"),
Entry::new(PrintScope::Current, "Print Current Slide"),
Entry::new(PrintScope::Custom, "Custom Range"),
];
Field::new(tl!("Print range")).show(ui, |ui, _| {
range_changed |= Select::new(tl!("Print range"), Bind::bound(&mut bs.print_scope), &scopes).show(ui).value().is_some();
Field::new("Print range").show(ui, |ui, _| {
range_changed |= Select::new("Print range", Bind::bound(&mut bs.print_scope), &scopes).show(ui).value().is_some();
});
Field::new(tl!("Slides")).show(ui, |ui, _| {
let edit = TextField::new(tl!("Slides"), Bind::bound(&mut bs.print_range)).placeholder(tl!("e.g. 1-3, 5")).show(ui);
Field::new("Slides").show(ui, |ui, _| {
let edit = TextField::new("Slides", Bind::bound(&mut bs.print_range)).placeholder("e.g. 1-3, 5").show(ui);
if edit.value().is_some() {
bs.print_scope = if bs.print_range.trim().is_empty() { PrintScope::All } else { PrintScope::Custom };
range_changed = true;
}
});
let layouts: Vec<_> = LAYOUTS.iter().map(|(id, label)| Entry::new(*id, *label)).collect();
Field::new(tl!("Print layout")).show(ui, |ui, _| {
Select::new(tl!("Print layout"), Bind::bound(&mut bs.print_layout), &layouts).show(ui);
Field::new("Print layout").show(ui, |ui, _| {
Select::new("Print layout", Bind::bound(&mut bs.print_layout), &layouts).show(ui);
});
let paper: Vec<_> = deckcraft_engine::cmd::file::PAPERS.iter().map(|(id, label, _)| Entry::new(*id, *label)).collect();
Field::new(tl!("Paper size")).show(ui, |ui, _| {
Select::new(tl!("Paper size"), Bind::bound(&mut bs.print_paper), &paper).enabled(bs.print_layout != "slides").show(ui);
Field::new("Paper size").show(ui, |ui, _| {
Select::new("Paper size", Bind::bound(&mut bs.print_paper), &paper).enabled(bs.print_layout != "slides").show(ui);
});
let orientations = [Entry::new(false, "Portrait Orientation"), Entry::new(true, "Landscape Orientation")];
Field::new(tl!("Orientation")).show(ui, |ui, _| {
Select::new(tl!("Orientation"), Bind::bound(&mut bs.print_landscape), &orientations)
.enabled(bs.print_layout != "slides")
.show(ui);
Field::new("Orientation").show(ui, |ui, _| {
Select::new("Orientation", Bind::bound(&mut bs.print_landscape), &orientations).enabled(bs.print_layout != "slides").show(ui);
});
});
range_changed |= Checkbox::new(Bind::bound(&mut bs.print_hidden)).label(tl!("Print Hidden Slides")).show(ui).value().is_some();
Checkbox::new(Bind::bound(&mut bs.print_frame)).label(tl!("Frame Slides")).show(ui);
range_changed |= Checkbox::new(Bind::bound(&mut bs.print_hidden)).label("Print Hidden Slides").show(ui).value().is_some();
Checkbox::new(Bind::bound(&mut bs.print_frame)).label("Frame Slides").show(ui);
if Link::new("Edit Header & Footer").show(ui).clicked() {
let _ = app.run("app.dialog", json!({"id": "headerFooter"}));
}
@@ -147,12 +165,12 @@ pub(super) fn print(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs: &
}
Stack::new().sizing(Sizing::FillWidth).show(ui, |ui, _| match &slides {
Err(reason) => {
Text::new(crate::i18n::t(reason).to_string()).shade(Shade::Muted).show(ui);
Text::new(reason.clone()).shade(Shade::Muted).show(ui);
preview(ui, bs, doc.clone(), &[]);
}
Ok(slides) => {
if slides.is_empty() {
Text::new(tl!("Nothing to print: every slide in the range is hidden.")).shade(Shade::Muted).show(ui);
Text::new("Nothing to print: every slide in the range is hidden.").shade(Shade::Muted).show(ui);
}
preview(ui, bs, doc.clone(), slides);
}
@@ -280,7 +298,7 @@ fn choose(
current: &'static str,
) -> &'static str {
let source = keyed(rows, |row| row.0).with_text(|row| std::borrow::Cow::Borrowed(row.1));
let output = List::new(tl!(label))
let output = List::new(label)
.select(SelectMode::Single)
.sizing(Sizing::Content)
.natural_height(true)
@@ -334,20 +352,20 @@ pub(super) fn export(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs:
let _ = Divider::vertical().show(ui);
Stack::new().wrap_width(WrapWidth::Column).show(ui, |ui, _| match bs.export {
ExportTask::Pdf => {
Text::new(tl!("Create a PDF Document")).role(TypeRole::Heading).show(ui);
Text::new(format!("• {}", tl!("Keeps the layout, fonts and pictures"))).show(ui);
Text::new(format!("• {}", tl!("Opens on any device with a PDF viewer"))).show(ui);
Text::new(format!("• {}", tl!("The presentation keeps its own file"))).show(ui);
Checkbox::new(Bind::bound(&mut bs.pdf_hidden)).label(tl!("Include hidden slides")).show(ui);
Text::new("Create a PDF Document").role(TypeRole::Heading).show(ui);
Text::new("• Keeps the layout, fonts and pictures").show(ui);
Text::new("• Opens on any device with a PDF viewer").show(ui);
Text::new("• The presentation keeps its own file").show(ui);
Checkbox::new(Bind::bound(&mut bs.pdf_hidden)).label("Include hidden slides").show(ui);
if Button::new("Create PDF").icon(Icon::File.id()).arrangement(Arrangement::Stacked).show(ui).clicked() {
app.export_as("pdf", json!({"includeHidden": bs.pdf_hidden}));
}
}
ExportTask::Handouts => {
Text::new(tl!("Create Handouts")).role(TypeRole::Heading).show(ui);
Text::new(format!("• {}", tl!("Several slides on each page of a PDF"))).show(ui);
Text::new(format!("• {}", tl!("Three a page leaves lines for notes"))).show(ui);
Text::new(format!("• {}", tl!("Print them for your audience"))).show(ui);
Text::new("Create Handouts").role(TypeRole::Heading).show(ui);
Text::new("• Several slides on each page of a PDF").show(ui);
Text::new("• Three a page leaves lines for notes").show(ui);
Text::new("• Print them for your audience").show(ui);
let entries: Vec<_> = LAYOUTS
.iter()
.filter(|(id, _)| id.starts_with('h'))
@@ -357,23 +375,23 @@ pub(super) fn export(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs:
Entry::new(per as u8, label)
})
.collect();
Field::new(tl!("Slides per page")).show(ui, |ui, _| {
Select::new(tl!("Slides per page"), Bind::bound(&mut bs.handouts_per_page), &entries).show(ui);
Field::new("Slides per page").show(ui, |ui, _| {
Select::new("Slides per page", Bind::bound(&mut bs.handouts_per_page), &entries).show(ui);
});
if Button::new("Create Handouts").icon(Icon::Notes.id()).arrangement(Arrangement::Stacked).show(ui).clicked() {
app.export_as("pdf", json!({"layout": "handouts", "perPage": bs.handouts_per_page}));
}
}
ExportTask::FileType => {
Text::new(tl!("Change File Type")).role(TypeRole::Heading).show(ui);
Text::new("Change File Type").role(TypeRole::Heading).show(ui);
let types: Vec<_> =
SAVE_TYPES.iter().copied().filter(|entry| entry.0 != "pdf").map(|(id, label, detail)| (id, label, detail, None)).collect();
bs.file_type = choose(ui, "File type", &types, bs.file_type);
let png = matches!(bs.file_type, "png" | "pngAll");
if png {
Checkbox::new(Bind::bound(&mut bs.png_transparent))
.label(tl!("Transparent background"))
.tooltip(tl!("Leave the slide background out: only what is on the slide is drawn"))
.label("Transparent background")
.tooltip("Leave the slide background out: only what is on the slide is drawn")
.show(ui);
}
if Button::new("Save As")
@@ -390,3 +408,89 @@ pub(super) fn export(app: &mut SlideApp, ui: &mut Ui, _cx: &mut BodyCx<'_>, bs:
});
});
}
/// Printing straight to a printer: the spooler's printers, the chosen one, copies, and the job
/// being sent on a worker thread.
#[cfg(not(target_arch = "wasm32"))]
type PrinterDiscovery = Rc<std::sync::mpsc::Receiver<Vec<craft::print::Printer>>>;
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug)]
pub struct DirectPrint {
printers: Option<Vec<craft::print::Printer>>,
discovery: Option<PrinterDiscovery>,
printer: String,
copies: String,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for DirectPrint {
fn default() -> Self {
DirectPrint { printers: None, discovery: None, printer: String::new(), copies: "1".into() }
}
}
/// Desktop Print sends the prepared PDF to the shared spooler. "Open as PDF instead" keeps the
/// PDF viewer route, including queues whose sign-in requires the system viewer.
#[cfg(not(target_arch = "wasm32"))]
fn direct_print(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, doc: &deckcraft_model::Presentation, slides: Option<&Vec<usize>>) {
let Some(spool) = app.print_spool.clone() else { return };
let dp = &mut bs.direct_print;
if dp.printers.is_none() {
let discovery = dp.discovery.get_or_insert_with(|| Rc::new(spool.discover()));
match discovery.try_recv() {
Ok(printers) => {
dp.printer = printers.iter().find(|p| p.default).or(printers.first()).map(|p| p.name.clone()).unwrap_or_default();
dp.printers = Some(printers);
dp.discovery = None;
}
Err(std::sync::mpsc::TryRecvError::Empty) => ui.ctx().request_repaint_after(std::time::Duration::from_millis(200)),
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
dp.printers = Some(Vec::new());
dp.discovery = None;
app.set_status("Couldn't find printers");
}
}
}
let copies = dp.copies.trim().parse::<u32>().ok().filter(|c| (1..=999).contains(c));
let sending = app.print_receipt.is_some();
let ready = slides.is_some() && !sending && !dp.printer.is_empty() && copies.is_some();
let detail = if sending { "Sending the job to the printer…" } else { "Sends the slides straight to the printer chosen below." };
if task_row(ui, Icon::Print, "Print", "Print", detail, ready)
&& let (Some(slides), Some(copies)) = (slides, copies)
{
match deckcraft_engine::cmd::file::pdf_bytes(doc, &print_params(bs, slides)) {
Ok(bytes) => {
let dp = &mut bs.direct_print;
let title = app.session.active().map(|d| d.title()).unwrap_or_else(|| "DeckCraft".into());
let job = craft::print::Job { printer: Some(dp.printer.clone()), copies, collate: true, title, ..Default::default() };
app.print_receipt = Some((dp.printer.clone(), spool.submit(bytes, job)));
ui.ctx().request_repaint();
app.set_status(format!("Sending to {}…", dp.printer));
}
Err(e) => app.set_status(format!("Couldn't make the pages to print: {e}")),
}
}
let dp = &mut bs.direct_print;
let names: Vec<String> = dp.printers.iter().flatten().map(|p| p.name.clone()).collect();
FieldGroup::new("Printer").show(ui, |ui, _| {
if dp.discovery.is_some() {
Text::new("Finding printers…").shade(Shade::Muted).show(ui);
} else if names.is_empty() {
Text::new("No printers found.").shade(Shade::Muted).show(ui);
} else {
let entries: Vec<_> = names.iter().map(|n| Entry::new(n.clone(), n.clone())).collect();
Field::new("Printer").show(ui, |ui, _| {
Select::new("Printer", Bind::bound(&mut dp.printer), &entries).show(ui);
});
}
Field::new("Copies").show(ui, |ui, _| {
TextField::new("Copies", Bind::bound(&mut dp.copies)).show(ui);
});
});
if Link::new("Open as PDF instead").show(ui).clicked()
&& let Some(slides) = slides
{
app.print_pdf_viewer(print_params(bs, slides));
}
}
+55 -50
View File
@@ -249,56 +249,6 @@ fn save_as_and_export_run_the_file_commands() {
assert_eq!(files.requests().len(), picks, "saving in place asks for no path");
}
/// The bug this prevents: Save of an opened .pptm (Open XML bytes, so it keeps its path) wrote
/// native DeckCraft bytes over it in place.
#[test]
fn save_of_an_opened_pptm_asks_for_a_new_file_and_leaves_it_alone() {
let original = deckcraft_engine::cmd::file::save_bytes(&Session::with_new().doc().unwrap().doc, "pptx").unwrap();
let pptm = Path::new("deck.pptm");
let files = Arc::new(ScriptedFiles::new().saving_suggested().with_file(pptm, original.clone()));
let mut h = harness(Session::new(), files.clone());
h.state_mut().open_path("deck.pptm").unwrap();
assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("deck.pptm"));
h.state_mut().run("slide.new", json!({})).unwrap();
let slides = h.state().session.active().unwrap().doc.slides.len();
h.state_mut().save();
assert_eq!(files.file(pptm), Some(original), "the macro-enabled file is never written");
let requests = files.requests();
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].kind, PickKind::Save);
assert!(requests[0].save_as);
let copy = saved_path(&files, "pptx");
assert_ne!(copy.as_path(), pptm);
let doc = h.state().session.active().unwrap();
assert_eq!(doc.path.as_deref(), copy.to_str());
assert!(!doc.is_dirty());
let mut reopened = Session::new();
reopened
.execute("file.openBytes", &json!({"name": "copy.pptx", "data": deckcraft_engine::cmd::base64_encode(&files.file(&copy).unwrap())}))
.unwrap();
assert_eq!(reopened.doc().unwrap().doc.slides.len(), slides, "the copy is a PowerPoint file with the edit");
}
#[test]
fn save_as_to_an_unwritable_extension_is_refused() {
let files = Arc::new(ScriptedFiles::answering([Picked::Saved { path: PathBuf::from("other.pptm"), file_type: None }]));
let mut h = harness(Session::with_new(), files.clone());
h.state_mut().run("slide.new", json!({})).unwrap();
let before = h.state().session.active().unwrap().path.clone();
h.state_mut().save_as_dialog("deckcraft");
assert!(files.file(Path::new("other.pptm")).is_none(), "nothing is written under a type DeckCraft can't write");
assert!(files.written().is_empty());
let status = h.state().status.as_ref().map(|(msg, _)| msg.clone()).unwrap_or_default();
assert!(status.contains("file type"), "the status says why: {status}");
let doc = h.state().session.active().unwrap();
assert!(doc.is_dirty());
assert_eq!(doc.path, before);
}
#[test]
fn change_file_type_exports_all_slides_as_pictures() {
let files = Arc::new(ScriptedFiles::new().saving_suggested());
@@ -668,6 +618,61 @@ fn print_previews_pages_and_prints_a_pdf() {
assert!(std::fs::read(printed).unwrap().starts_with(b"%PDF"));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn direct_print_reports_the_spooler_failure_and_keeps_the_viewer() {
use craft::print::spool::{Pending, Spool, SpoolBackend};
use craft::print::{Error, Job, Printer};
struct RejectingPrinter;
impl SpoolBackend for RejectingPrinter {
fn printers(&self) -> Option<Vec<Printer>> {
Some(vec![Printer { name: "Test printer".into(), default: true, description: String::new(), two_sided: None }])
}
fn prepare(&self, pdf: Vec<u8>, job: Job) -> Pending {
assert!(pdf.starts_with(b"%PDF"));
assert_eq!(job.printer.as_deref(), Some("Test printer"));
Pending {
cancel: Box::new(|| true),
run: Box::new(|| Err(Error::Spool("test queue refused the print job".into()))),
waits_after_cancel: false,
}
}
}
let mut h = new_app();
h.state_mut().print_spool = Some(Spool::with_backend(Arc::new(craft::host::InlineJobs), Arc::new(RejectingPrinter)));
h.key_press_modifiers(Modifiers::COMMAND, Key::P);
h.run_steps(3);
page_button(&h, "Print").click();
h.run_steps(3);
assert!(h.state().status.as_ref().is_some_and(|(message, _)| message.contains("test queue refused the print job")));
assert!(h.query_by_label("Open as PDF instead").is_some());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn print_from_quick_access_opens_settings_and_job_feedback_survives_leaving() {
let mut h = new_app();
h.state_mut().enable_direct_print();
h.state_mut().run("app.qat", json!({"add": "app.print", "label": "Print"})).unwrap();
let index = h.state().ui.qat.iter().position(|q| q.id == "app.print").unwrap();
assert!(crate::qat::run_index(h.state_mut(), index));
assert_eq!(page(&h), Some(Page::Print));
assert!(h.state().print_receipt.is_none());
let (sender, receiver) = std::sync::mpsc::channel();
h.state_mut().print_receipt = Some(("Studio printer".into(), receiver));
h.state_mut().run("app.backstage", json!({"on": false})).unwrap();
assert_eq!(page(&h), None);
sender.send(Err("queue rejected these sheets".into())).unwrap();
h.run_steps(3);
assert!(h.state().print_receipt.is_none());
assert!(h.state().status.as_ref().is_some_and(|(message, _)| message.contains("queue rejected these sheets")));
}
#[test]
fn print_slides_follow_the_settings() {
let mut s = Session::with_new();
+34 -36
View File
@@ -28,7 +28,7 @@ pub(crate) fn show(app: &mut SlideApp, ui: &mut Ui, canvas: &Response, ask: Opti
let Some(menu) = &app.canvas_menu else { return };
let at = menu.at;
let mut open = true;
Menu::context(tl!("Canvas"), canvas).anchor(Anchor::Point(at)).open(Bind::bound(&mut open)).show(ui, |ui, _| {
Menu::context("Canvas", canvas).anchor(Anchor::Point(at)).open(Bind::bound(&mut open)).show(ui, |ui, _| {
let editing = app.session.active().and_then(|st| app.session.tool.editing_points(st).and_then(|id| st.shape(id).cloned()));
if let Some(shape) = editing {
edit_points_menu(app, ui, &shape);
@@ -38,7 +38,7 @@ pub(crate) fn show(app: &mut SlideApp, ui: &mut Ui, canvas: &Response, ask: Opti
spelling_menu(app, ui, &word);
}
for (label, id) in [("Cut", "edit.cut"), ("Copy", "edit.copy"), ("Paste", "edit.paste")] {
MenuItem::command(id).label(tl!(label)).show(ui);
MenuItem::command(id).label(label).show(ui);
}
Divider::horizontal().show(ui);
let editing = app.session.active().is_some_and(|st| st.selection.text.as_ref().is_some_and(|text| !text.notes));
@@ -61,17 +61,15 @@ fn edit_points_menu(app: &SlideApp, ui: &mut Ui, shape: &deckcraft_model::Shape)
let current = deckcraft_engine::cmd::points::segment_kind_of(shape, path, index);
for (label, kind) in [("Straight Segment", "straight"), ("Curved Segment", "curved")] {
MenuItem::command(CommandRef::with_params("shape.segmentType", json!({"path": path, "segment": index, "type": kind})))
.label(tl!(label))
.label(label)
.radio_mark(current == Some(kind))
.show(ui);
}
let t = app.session.tool.edit_segment_t.unwrap_or(0.5);
MenuItem::command(CommandRef::with_params("shape.addPoint", json!({"path": path, "segment": index, "t": t})))
.label(tl!("Add Point"))
.show(ui);
MenuItem::command(CommandRef::with_params("shape.addPoint", json!({"path": path, "segment": index, "t": t}))).label("Add Point").show(ui);
let closed = deckcraft_engine::cmd::points::closed_at(shape, path, index);
MenuItem::command(CommandRef::with_params("shape.deleteSegment", json!({"path": path, "segment": index})))
.label(tl!("Delete Segment"))
.label("Delete Segment")
.enabled(closed == Some(true))
.show(ui);
// Segments are indexed by their end vertex; opening cuts at the other end.
@@ -79,25 +77,25 @@ fn edit_points_menu(app: &SlideApp, ui: &mut Ui, shape: &deckcraft_model::Shape)
Some(false) => ("Close Path", "shape.closePath", index),
_ => ("Open Path", "shape.openPath", deckcraft_engine::cmd::points::segment_start_of(shape, path, index).unwrap_or(index)),
};
MenuItem::command(CommandRef::with_params(id, json!({"path": path, "index": at}))).label(tl!(label)).show(ui);
MenuItem::command(CommandRef::with_params(id, json!({"path": path, "index": at}))).label(label).show(ui);
Divider::horizontal().show(ui);
} else if let Some((path, index)) = app.session.tool.edit_vertex {
let current = deckcraft_engine::cmd::points::kind_of(shape, path, index);
for (label, kind) in [("Smooth Point", "smooth"), ("Straight Point", "straight"), ("Corner Point", "corner")] {
MenuItem::command(CommandRef::with_params("shape.pointType", json!({"path": path, "index": index, "type": kind})))
.label(tl!(label))
.label(label)
.radio_mark(current == Some(kind))
.show(ui);
}
MenuItem::command(CommandRef::with_params("shape.deletePoint", json!({"path": path, "index": index}))).label(tl!("Delete Point")).show(ui);
MenuItem::command(CommandRef::with_params("shape.deletePoint", json!({"path": path, "index": index}))).label("Delete Point").show(ui);
let (label, id) = match deckcraft_engine::cmd::points::closed_at(shape, path, index) {
Some(false) => ("Close Path", "shape.closePath"),
_ => ("Open Path", "shape.openPath"),
};
MenuItem::command(CommandRef::with_params(id, json!({"path": path, "index": index}))).label(tl!(label)).show(ui);
MenuItem::command(CommandRef::with_params(id, json!({"path": path, "index": index}))).label(label).show(ui);
Divider::horizontal().show(ui);
}
MenuItem::command(CommandRef::with_params("shape.editPoints", json!({"on": false}))).label(tl!("Exit Edit Points")).show(ui);
MenuItem::command(CommandRef::with_params("shape.editPoints", json!({"on": false}))).label("Exit Edit Points").show(ui);
}
fn spelling_menu(app: &mut SlideApp, ui: &mut Ui, word: &MenuWord) {
@@ -119,10 +117,10 @@ fn spelling_menu(app: &mut SlideApp, ui: &mut Ui, word: &MenuWord) {
.unwrap_or_else(|| " ".repeat(word.start - from));
let cut = format!("{gap}{}", word.word);
MenuItem::command(CommandRef::with_params("review.spellingChange", spelling_params(word, from, &cut, "")))
.label(tl!("Delete Repeated Word"))
.label("Delete Repeated Word")
.show(ui);
} else if word.suggestions.is_empty() {
MenuItem::heading(tl!("(no spelling suggestions)")).show(ui);
MenuItem::heading("(no spelling suggestions)").show(ui);
}
for suggestion in &word.suggestions {
MenuItem::command(CommandRef::with_params("review.spellingChange", spelling_params(word, word.start, &word.word, suggestion)))
@@ -130,10 +128,10 @@ fn spelling_menu(app: &mut SlideApp, ui: &mut Ui, word: &MenuWord) {
.show(ui);
}
Divider::horizontal().show(ui);
if MenuItem::new(tl!("Ignore All")).show(ui).ran {
if MenuItem::new("Ignore All").show(ui).ran {
app.squiggles.ignore(&word.word);
}
MenuItem::command(CommandRef::with_params("review.addToDictionary", json!({"word": word.word}))).label(tl!("Add to Dictionary")).show(ui);
MenuItem::command(CommandRef::with_params("review.addToDictionary", json!({"word": word.word}))).label("Add to Dictionary").show(ui);
Divider::horizontal().show(ui);
}
@@ -147,56 +145,56 @@ fn spelling_params(word: &MenuWord, start: usize, cut: &str, to: &str) -> Value
fn text_items(app: &mut SlideApp, ui: &mut Ui) {
for (label, id) in [("Paragraph…", "format.paragraphDialog"), ("Bullets", "format.bullets"), ("Numbering", "format.numbering")] {
MenuItem::command(id).label(tl!(label)).show(ui);
MenuItem::command(id).label(label).show(ui);
}
if MenuItem::new(tl!("Link…")).show(ui).ran {
if MenuItem::new("Link…").show(ui).ran {
app.open_dialog("hyperlink", json!({}));
}
Divider::horizontal().show(ui);
MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "format"}))).label(tl!("Format Shape…")).show(ui);
MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "format"}))).label("Format Shape…").show(ui);
}
fn shape_items(app: &mut SlideApp, ui: &mut Ui) {
MenuItem::command("text.edit").label(tl!("Edit Text")).show(ui);
MenuItem::command("text.edit").label("Edit Text").show(ui);
if app.session.active().is_some_and(|st| st.selection.shapes.len() == 1 && st.selected_shapes().iter().all(|shape| !shape.is_line())) {
MenuItem::command(CommandRef::with_params("shape.editPoints", json!({"on": true}))).label(tl!("Edit Points")).show(ui);
MenuItem::command(CommandRef::with_params("shape.editPoints", json!({"on": true}))).label("Edit Points").show(ui);
}
for (label, id) in [("Font…", "format.fontDialog"), ("Paragraph…", "format.paragraphDialog")] {
MenuItem::command(id).label(tl!(label)).show(ui);
MenuItem::command(id).label(label).show(ui);
}
for (label, rows) in [
("Bring to Front", [("Bring to Front", "arrange.bringToFront"), ("Bring Forward", "arrange.bringForward")]),
("Send to Back", [("Send to Back", "arrange.sendToBack"), ("Send Backward", "arrange.sendBackward")]),
("Group", [("Group", "arrange.group"), ("Ungroup", "arrange.ungroup")]),
] {
Menu::submenu_row(ui, tl!(label), |ui, _| {
Menu::submenu_row(ui, label, |ui, _| {
for (label, id) in rows {
MenuItem::command(id).label(tl!(label)).show(ui);
MenuItem::command(id).label(label).show(ui);
}
});
}
let locked = app.session.active().is_some_and(|st| st.selected_shapes().iter().all(|shape| shape.locked));
MenuItem::command(CommandRef::with_params("shape.lock", json!({"locked": !locked}))).label(tl!(if locked { "Unlock" } else { "Lock" })).show(ui);
MenuItem::command(CommandRef::with_params("shape.lock", json!({"locked": !locked}))).label(if locked { "Unlock" } else { "Lock" }).show(ui);
let picture = app
.session
.active()
.is_some_and(|st| st.selected_shapes().iter().any(|shape| matches!(shape.kind, deckcraft_model::ShapeKind::Picture { .. })));
if picture {
MenuItem::command("app.changePictureDialog").label(tl!("Change Picture…")).show(ui);
MenuItem::command("app.changePictureDialog").label("Change Picture…").show(ui);
}
for (label, id) in [("Link…", "hyperlink"), ("Edit Alt Text…", "altText")] {
if MenuItem::new(tl!(label)).show(ui).ran {
if MenuItem::new(label).show(ui).ran {
app.open_dialog(id, json!({}));
}
}
for (label, id) in [("Set as Default Shape", "shape.setDefault"), ("Size and Position…", "shape.sizePosition")] {
MenuItem::command(id).label(tl!(label)).show(ui);
MenuItem::command(id).label(label).show(ui);
}
MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "format"}))).label(tl!("Format Shape…")).show(ui);
MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "format"}))).label("Format Shape…").show(ui);
}
fn slide_items(app: &mut SlideApp, ui: &mut Ui) {
Menu::submenu_row(ui, tl!("Layout"), |ui, _| {
Menu::submenu_row(ui, "Layout", |ui, _| {
let layouts: Vec<(String, u32)> = app
.session
.active()
@@ -206,22 +204,22 @@ fn slide_items(app: &mut SlideApp, ui: &mut Ui) {
MenuItem::command(CommandRef::with_params("slide.layout", json!({"layout": id}))).label(name).show(ui);
}
});
Menu::submenu_row(ui, tl!("Grid and Guides"), |ui, _| {
Menu::submenu_row(ui, "Grid and Guides", |ui, _| {
MenuItem::command(CommandRef::with_params("view.guides", json!({"on": !app.ui.guides})))
.label(tl!("Guides"))
.label("Guides")
.check(app.ui.guides)
.keep_open(true)
.show(ui);
for (label, vertical) in [("Add Vertical Guide", true), ("Add Horizontal Guide", false)] {
if MenuItem::command(CommandRef::with_params("guide.add", json!({"vertical": vertical}))).label(tl!(label)).show(ui).ran {
if MenuItem::command(CommandRef::with_params("guide.add", json!({"vertical": vertical}))).label(label).show(ui).ran {
// Queue visibility after addition, before Guides can seed defaults.
let _ = commands::fire(ui.ctx(), CommandRef::with_params("view.guides", json!({"on": true})), FireSource::Menu);
}
}
});
MenuItem::command("slide.reset").label(tl!("Reset Slide")).show(ui);
MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "background"}))).label(tl!("Format Background…")).show(ui);
if MenuItem::new(tl!("New Comment")).show(ui).ran {
MenuItem::command("slide.reset").label("Reset Slide").show(ui);
MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "background"}))).label("Format Background…").show(ui);
if MenuItem::new("New Comment").show(ui).ran {
app.open_dialog("comment", json!({}));
}
}
+2 -2
View File
@@ -36,7 +36,7 @@ pub(crate) fn show_grid(app: &mut SlideApp, ui: &mut egui::Ui, space: &CanvasSpa
let size = st.doc.slide_size;
let spacing = app.session.prefs.grid_spacing;
let [r, g, b, a] = GRID_INK.0;
let _ = CanvasGrid::new(tl!("Grid"))
let _ = CanvasGrid::new("Grid")
.spacing(Vec2::new(spacing, spacing))
.origin(Point::ZERO)
.bounds(Rect::new(0.0, 0.0, size.width, size.height))
@@ -75,7 +75,7 @@ pub(crate) fn show_guides(app: &mut SlideApp, ui: &mut egui::Ui, space: &CanvasS
value
})
.collect();
let output = Guides::new(tl!("Guides"), canvas, Bind::given(guides))
let output = Guides::new("Guides", canvas, Bind::given(guides))
.interactive(interactive)
.selected_guides(&selected)
.bounds(Rect::new(0.0, 0.0, size.width, size.height))
+1 -1
View File
@@ -105,7 +105,7 @@ pub(super) fn selection_box(st: &deckcraft_engine::DocState, sh: &deckcraft_mode
let state = BoxState::new(BoxState::from_rect(start).quad.map(|q| a * q), a * start.center());
let rules = BoxRules::default().with_allow(BoxAllow::new(!sh.locked && !editing, false, false));
// Shown boxes declare no gesture parts: the engine is the sole owner of transforms.
let control = TransformBox::new(tl!("Selection"), Bind::given(state), start, 0.0)
let control = TransformBox::new("Selection", Bind::given(state), start, 0.0)
.reach(TransformReach::Shown)
.rotate_zone(if editing { RotateZone::Band } else { RotateZone::Handle })
.look(if editing { BoxLook::DocumentEditing } else { BoxLook::Document })
+1 -1
View File
@@ -104,7 +104,7 @@ pub(crate) fn gif_buttons(app: &mut SlideApp, ui: &mut Ui, space: &CanvasSpace,
let mut button = IconButton::new(IconId::new(if g.paused { "play" } else { "pause" }))
.id_salt(("gif_button", g.id.0))
.variant(IconButton::OVER_PICTURE)
.label(tl!(if g.paused { "Play animated GIF" } else { "Pause animated GIF" }));
.label(if g.paused { "Play animated GIF" } else { "Pause animated GIF" });
if rect.width() < button.measure_in(ui, Proposal::Ideal).x {
button = button.size(ControlSize::Sm);
}
+16 -2
View File
@@ -2,6 +2,7 @@
//! (Animations ▸ Preview, Animation Pane ▸ Play All). The slide show uses the same mapping.
use deckcraft_anim::Timeline;
use deckcraft_geom::Vec2;
use deckcraft_model::ShapeId;
use deckcraft_render::{ParaState, ShapeState};
@@ -12,8 +13,21 @@ pub const HOLD_SECS: f64 = 0.45;
pub fn shape_state(tl: &Timeline, id: ShapeId, step: usize, t: f64) -> ShapeState {
let a = tl.state(id, None, step, t);
ShapeState {
paras: tl.paragraph_targets(id).into_iter().map(|p| (p, ParaState::from(tl.state(id, Some(p), step, t)))).collect(),
..ShapeState::from(a)
visible: a.visible,
opacity: a.opacity,
offset: Vec2::new(a.offset_x, a.offset_y),
scale: (a.scale_x, a.scale_y),
rotate: a.rotate,
clip: a.clip,
tint: a.tint,
paras: tl
.paragraph_targets(id)
.into_iter()
.map(|p| {
let a = tl.state(id, Some(p), step, t);
(p, ParaState { visible: a.visible, opacity: a.opacity, offset: Vec2::new(a.offset_x, a.offset_y) })
})
.collect(),
}
}
+2 -2
View File
@@ -49,7 +49,7 @@ pub(crate) fn doc_unit(unit: Unit) -> DocUnit {
/// Builds display-only rulers whose origin stays at the slide origin.
pub(crate) fn rulers(app: &SlideApp) -> Option<Rulers<'static>> {
app.ui.ruler.then(|| Rulers::new(tl!("Rulers"), Bind::given(Point::ZERO)).origin_locked(true).interactive(false))
app.ui.ruler.then(|| Rulers::new("Rulers", Bind::given(Point::ZERO)).origin_locked(true).interactive(false))
}
/// Hosts the paragraph ruler over the full canvas's top strip. The body is clipped to the view inside the strips, so
@@ -79,7 +79,7 @@ pub(crate) fn show_text_ruler(app: &mut SlideApp, ui: &mut egui::Ui, space: &Can
let unit = app.session.prefs.units;
let body_clip = ui.clip_rect();
ui.set_clip_rect(strips_clip);
let output = TextRuler::new(tl!("Text ruler"), Bind::given(values.clone()), number("width") as f32)
let output = TextRuler::new("Text ruler", Bind::given(values.clone()), number("width") as f32)
.model(ParagraphModel::TextBox)
.corner(corner)
.scale(space.view.zoom as f32)
+1 -1
View File
@@ -407,7 +407,7 @@ pub(crate) fn show_editor(app: &mut crate::SlideApp, ui: &mut Ui, space: &Canvas
let mut host = EngineTextHost::new(&mut app.session, target);
let bounds = host.bounds(space)?;
let mut selection = host.offsets.selection(&host.target);
let mut editor = TextEditor::new(tl!("Text"), &mut host, Bind::bound(&mut selection)).id(id).click_runs(ClickRuns::Paragraphs);
let mut editor = TextEditor::new("Text", &mut host, Bind::bound(&mut selection)).id(id).click_runs(ClickRuns::Paragraphs);
if hosted != Some(id) {
editor = editor.request_focus(FocusRequest::Take);
}
-147
View File
@@ -1,147 +0,0 @@
//! The window's file service, held to the automation roots in force.
//!
//! The engine checks the paths its commands open and save ([`deckcraft_engine::file_access`]), but
//! the window also reads and writes through the host's file service itself: opening a presentation,
//! a file a pick answered, `ui.render` and screenshots with a `path`, saving to a document's own
//! path. [`ConfinedFiles`] puts every such read and write through the same check, so a request from
//! an agent in the open window (run with the agent folders in force, [`crate::agents`]) reaches only
//! those folders. Outside a confined request nothing changes: no roots are in force.
use std::path::Path;
use std::sync::Arc;
use craft::host::{FileError, Files, PendingPick, PickId, PickRequest, Picked, WriteIntent};
use deckcraft_engine::file_access::{self, Access};
/// `inner`, with every path checked against the automation roots in force on the calling thread.
pub struct ConfinedFiles {
inner: Arc<dyn Files>,
}
impl ConfinedFiles {
/// Wraps the window's file service.
pub fn new(inner: Arc<dyn Files>) -> Self {
Self { inner }
}
}
/// `Err` when the roots in force refuse `access` to `path`.
fn check(path: &Path, access: Access) -> Result<(), FileError> {
match file_access::current() {
Some(roots) => roots.check_path(path, access).map_err(FileError::Other),
None => Ok(()),
}
}
impl Files for ConfinedFiles {
fn pick(&self, request: PickRequest) -> PickId {
self.inner.pick(request)
}
fn take_answer(&self, id: PickId) -> Option<Picked> {
self.inner.take_answer(id)
}
fn forget(&self, id: PickId) {
self.inner.forget(id)
}
fn pending_pick(&self) -> Option<PendingPick> {
self.inner.pending_pick()
}
fn read_metadata(&self, path: &Path) -> Result<(bool, u64), FileError> {
check(path, Access::Read)?;
self.inner.read_metadata(path)
}
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
check(path, Access::Read)?;
self.inner.read(path)
}
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
check(path, Access::Write)?;
self.inner.write(path, bytes, intent)
}
fn exists(&self, path: &Path) -> bool {
// A file the roots keep from the request isn't there for it either.
check(path, Access::Read).is_ok() && self.inner.exists(path)
}
fn last_folder(&self, purpose: &str) -> Option<std::path::PathBuf> {
self.inner.last_folder(purpose)
}
fn save(&self, request: PickRequest, bytes: Vec<u8>) -> PickId {
self.inner.save(request, bytes)
}
fn can_pick(&self) -> bool {
self.inner.can_pick()
}
fn browser_saves(&self) -> bool {
self.inner.browser_saves()
}
fn saves_to_page(&self) -> bool {
self.inner.saves_to_page()
}
fn answer_next(&self, picked: Picked) -> Result<(), FileError> {
// The service would open or save the answered path itself, past this check.
if file_access::current().is_some() {
return Err(FileError::Other(
"a request held to the agent folders can't answer a file picker: give the path to the command instead".into(),
));
}
self.inner.answer_next(picked)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use craft::host::NoPickFiles;
use deckcraft_engine::file_access::AutomationRoots;
fn temp(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("dc-confined-files-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
// The window's own reads and writes reach only the agent folders while they are in force, and
// everything as before outside them.
#[test]
fn reads_and_writes_follow_the_roots_in_force() {
let base = temp("rw");
let (inside, outside) = (base.join("agents"), base.join("elsewhere"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("secret.pptx"), b"secret").unwrap();
std::fs::write(inside.join("deck.pptx"), b"deck").unwrap();
let files = ConfinedFiles::new(Arc::new(NoPickFiles::default()));
let roots = AutomationRoots::new(std::slice::from_ref(&inside), std::slice::from_ref(&inside)).unwrap().unwrap();
file_access::confine(Some(&roots), || {
assert_eq!(files.read(&inside.join("deck.pptx")).unwrap(), b"deck");
assert!(files.read(&outside.join("secret.pptx")).is_err(), "a read outside the folders is refused");
assert!(files.read_metadata(&outside.join("secret.pptx")).is_err());
assert!(!files.exists(&outside.join("secret.pptx")), "nor is it there for the request");
assert!(files.write(&inside.join("out.png"), b"png", WriteIntent::SaveAs).is_ok());
assert!(files.write(&outside.join("out.png"), b"png", WriteIntent::SaveAs).is_err(), "a write outside is refused");
assert!(files.answer_next(Picked::Paths(vec![outside.join("secret.pptx")])).is_err());
});
assert!(!outside.join("out.png").exists());
// The person at the keyboard: no roots in force.
assert_eq!(files.read(&outside.join("secret.pptx")).unwrap(), b"secret");
assert!(files.write(&outside.join("mine.png"), b"png", WriteIntent::SaveAs).is_ok());
let _ = std::fs::remove_dir_all(base);
}
}
-11
View File
@@ -291,10 +291,6 @@ pub fn handle(app: &mut SlideApp, ctx: &egui::Context, req: &ControlRequest) ->
wrap(crate::updates_ui::offer(app, tag).map(|()| Value::Null))
}
"ui.prefs" => wrap(set_prefs(app, p)),
#[cfg(not(target_arch = "wasm32"))]
"app.agents" => wrap(crate::agents::command(app, p)),
#[cfg(target_arch = "wasm32")]
"app.agents" => err("agents in the open window need the desktop app"),
"ui.iconSheet" => wrap(icon_sheet(app, ctx, p)),
"ui.contextMenu" => wrap(open_context_menu(app, ctx, p)),
"ui.paneState" => wrap(set_pane_state(app, ctx, p)),
@@ -392,13 +388,6 @@ fn window_input(app: &mut SlideApp, ctx: &egui::Context, host: &WindowHost, meth
Ok(params) => params,
Err(error) => return Some(err(error)),
};
// The image is written passes later, with no agent folders in force: its destination is
// checked now, against the folders this request runs under.
if let Some(path) = &params.path
&& let Err(error) = deckcraft_engine::file_access::check_write(path)
{
return Some(err(error));
}
let Ok(token) = CAPTURE_SERIAL.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)) else {
return Some(err("screenshot token space exhausted"));
};
-3
View File
@@ -95,9 +95,6 @@ pub(crate) struct DialogState {
pub closing: Option<closing::Closing>,
/// Settings restored when Preferences closes with Cancel.
pub preferences_opening: Option<preferences::PrefDraft>,
/// The agent settings restored when Preferences closes with Cancel.
#[cfg(not(target_arch = "wasm32"))]
pub agents_opening: Option<craft::automation::agents::AgentSettings>,
}
/// An opener's dialog key and seed parameters.
+5 -6
View File
@@ -9,17 +9,16 @@ use crate::SlideApp;
fn about_info() -> AboutInfo {
AboutInfo::new(
crate::flavor::app_name(),
format!(
"{}\n{}",
tl!("Presentations and slide shows, rebuilt from scratch in pure Rust."),
tl!("An open-source, clean-room project. Not affiliated with Microsoft.")
concat!(
"Presentations and slide shows, rebuilt from scratch in pure Rust.\n",
"An open-source, clean-room project. Not affiliated with Microsoft."
),
build_version(),
)
.mark(AboutImage::svg(crate::flavor::app_name(), include_bytes!("../../../../assets/app-icon/deckcraft-mark.svg")))
.community(AboutLink::new(tl!("Join our community on Discord"), links::DISCORD))
.community(AboutLink::new("Join our community on Discord", links::DISCORD))
.links([AboutLink::new("getartcraft.com/apps/deckcraft", links::APP_PAGE), AboutLink::new("Source on GitHub", links::GITHUB)])
.built_with(tl!("MIT OR Apache-2.0 · © 2026 ArtCraft Team and the DeckCraft contributors"))
.built_with("MIT OR Apache-2.0 · © 2026 ArtCraft Team and the DeckCraft contributors")
}
/// "Version X.Y.Z", with the build of [`build_version`].
+2 -2
View File
@@ -36,10 +36,10 @@ impl StackDialog for AccessibilityDialog {
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let shown = FormDialog::<bool>::own(tl!("Accessibility Checker")).buttons(FormButtons::Close).show(ui, |ui, _, _| {
let shown = FormDialog::<bool>::own("Accessibility Checker").buttons(FormButtons::Close).show(ui, |ui, _, _| {
let source = Findings::new(&self.findings);
let events = FindingsList::new("Accessibility issues")
.empty(tl!("No accessibility issues found. People with disabilities should not have difficulty reading this document."))
.empty("No accessibility issues found. People with disabilities should not have difficulty reading this document.")
.max_rows(12)
.show_items(ui, &source, &mut |key, icx| self.findings[*key as usize].row(&icx.words::<FindingsWords>()))
.events;

Some files were not shown because too many files have changed in this diff Show More