mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-05 20:17:58 -06:00
Compare commits
137
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
053061d820 | ||
|
|
04e809e7a7 | ||
|
|
e3b6e501ed | ||
|
|
616d5645cc | ||
|
|
11f10a857a | ||
|
|
669aa15c83 | ||
|
|
8667029fb1 | ||
|
|
6a1e891e06 | ||
|
|
3142bbcf79 | ||
|
|
e1e0e010f5 | ||
|
|
882a5aa2e8 | ||
|
|
644a4b32f2 | ||
|
|
6fc7c0a783 | ||
|
|
108ee6be28 | ||
|
|
2c11c1e08a | ||
|
|
1d699e7ba1 | ||
|
|
c2e9cb6466 | ||
|
|
078493b2ad | ||
|
|
65debf460c | ||
|
|
c6484283e9 | ||
|
|
4dbcf0e653 | ||
|
|
0091d8c95e | ||
|
|
b5758001aa | ||
|
|
bf9717fb5b | ||
|
|
d606418f11 | ||
|
|
c397003ac5 | ||
|
|
37949a580d | ||
|
|
8f551eac19 | ||
|
|
258db944e9 | ||
|
|
073ccb5a6f | ||
|
|
b309f6c3f3 | ||
|
|
1cf8191390 | ||
|
|
e08af8eaca | ||
|
|
0f8b63636e | ||
|
|
120812fdc5 | ||
|
|
d89ad70d81 | ||
|
|
383e7d2f55 | ||
|
|
fa0201d76d | ||
|
|
98988563ea | ||
|
|
df1adf5aa2 | ||
|
|
209c343a12 | ||
|
|
35095e8f90 | ||
|
|
6d0cf8e5d3 | ||
|
|
89273445e1 | ||
|
|
be6c83acf4 | ||
|
|
10a319f002 | ||
|
|
1ab2766576 | ||
|
|
e74f1101dc | ||
|
|
b495f9ddd5 | ||
|
|
ef4a4f4fd5 | ||
|
|
f51dc225a6 | ||
|
|
0458818244 | ||
|
|
7df135e8ec | ||
|
|
29f90a373f | ||
|
|
b6c8adbaff | ||
|
|
218bf7fa7d | ||
|
|
e1738a5b1d | ||
|
|
2ad78ddb19 | ||
|
|
cae5964ad8 | ||
|
|
d1b9662e9f | ||
|
|
865198fdc1 | ||
|
|
881517624d | ||
|
|
97ca37727f | ||
|
|
a43846ddb5 | ||
|
|
20012e35ca | ||
|
|
a01bc8f89e | ||
|
|
9152ba1e7e | ||
|
|
a6f0cacc0a | ||
|
|
6c1eb280af | ||
|
|
910f4e86d1 | ||
|
|
bbf4ecdfb3 | ||
|
|
46b8dfa222 | ||
|
|
1fdc52ce76 | ||
|
|
6b766e8d37 | ||
|
|
d4bfc8c87a | ||
|
|
c8b0ea548e | ||
|
|
3e221ccb50 | ||
|
|
9e73fef158 | ||
|
|
239f293ca7 | ||
|
|
5cc5d9b8c3 | ||
|
|
e3781b10eb | ||
|
|
d7702e7420 | ||
|
|
6dfad5678f | ||
|
|
ad49f99bfe | ||
|
|
0cc4e2ab3d | ||
|
|
cc634de30a | ||
|
|
58e0aa3a4a | ||
|
|
5ee6022a10 | ||
|
|
2092cc975b | ||
|
|
d2a4dd03cb | ||
|
|
82c2bf3315 | ||
|
|
069f783c25 | ||
|
|
700d4dbb1a | ||
|
|
39fd7ed90f | ||
|
|
9b2c47f3ca | ||
|
|
82ce5caf85 | ||
|
|
bed4db6fbb | ||
|
|
886ba4b755 | ||
|
|
7ebc2cb906 | ||
|
|
ad6e17590d | ||
|
|
2327905e6c | ||
|
|
6a1affd141 | ||
|
|
0b1399df94 | ||
|
|
7e3c6d13d9 | ||
|
|
51958983b0 | ||
|
|
cf3aa057cd | ||
|
|
2359e5c066 | ||
|
|
ca3b02653a | ||
|
|
ec53a162db | ||
|
|
c3deb83ec5 | ||
|
|
39d54845c0 | ||
|
|
4885a1724d | ||
|
|
72e3055b3b | ||
|
|
115070fbb9 | ||
|
|
d276e5df1d | ||
|
|
e3423744d2 | ||
|
|
af03e3840d | ||
|
|
057dba07da | ||
|
|
949562d90a | ||
|
|
657686d623 | ||
|
|
873b46a85b | ||
|
|
c462f658ab | ||
|
|
554274630b | ||
|
|
e770e72fa6 | ||
|
|
e662477fd2 | ||
|
|
1f4a7afc95 | ||
|
|
cbbc3347cf | ||
|
|
fface3030c | ||
|
|
89a2746ee5 | ||
|
|
25ea1eb064 | ||
|
|
e9dbf10433 | ||
|
|
9c600da847 | ||
|
|
9e00c7ae9b | ||
|
|
23f0cd1c9f | ||
|
|
bb345f2828 | ||
|
|
dd18f64d3f | ||
|
|
8519680df0 |
Generated
+14
@@ -1185,6 +1185,7 @@ dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-browse",
|
||||
"craft-color-ui",
|
||||
"craft-control",
|
||||
"craft-dialogs",
|
||||
"craft-draw",
|
||||
"craft-drawingml",
|
||||
@@ -2487,6 +2488,7 @@ dependencies = [
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
"memory-stats",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2672,6 +2674,7 @@ dependencies = [
|
||||
"egui",
|
||||
"egui_kittest",
|
||||
"log",
|
||||
"memory-stats",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
@@ -2695,6 +2698,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
@@ -4951,6 +4955,16 @@ 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"
|
||||
|
||||
@@ -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 |
|
||||
| App, universal (Apple silicon + Intel) | `deckcraft-<ver>-macos-universal.dmg` | Signed and notarized; `DeckCraft.app/Contents/MacOS/deckcraft-cli` is the command-line tool |
|
||||
| Command-line tool, universal | `deckcraft-cli-<ver>-macos-universal.zip` | Signed and notarized |
|
||||
|
||||
### Linux
|
||||
|
||||
@@ -19,5 +19,10 @@ 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 }
|
||||
|
||||
@@ -141,17 +141,24 @@ Start the app with --control-token-file PATH to have it create or read that file
|
||||
},
|
||||
Subcommand {
|
||||
name: "mcp",
|
||||
usage: "mcp [--connect PORT [--control-token TOKEN | --control-token-file PATH]] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...",
|
||||
usage: "mcp [--headless] [--when-closed launch|headless|error] [--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. 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.
|
||||
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.
|
||||
|
||||
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
|
||||
--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
|
||||
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
|
||||
|
||||
@@ -2,7 +2,16 @@
|
||||
#![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;
|
||||
|
||||
@@ -730,6 +739,25 @@ 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};
|
||||
@@ -737,6 +765,8 @@ 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);
|
||||
@@ -753,6 +783,9 @@ 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(());
|
||||
@@ -766,12 +799,46 @@ 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}"))?)
|
||||
}
|
||||
|
||||
@@ -157,3 +157,23 @@ 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}");
|
||||
}
|
||||
|
||||
@@ -29,3 +29,6 @@ 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"
|
||||
|
||||
@@ -215,3 +215,28 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! 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,7 +11,6 @@
|
||||
//! 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;
|
||||
|
||||
@@ -46,16 +45,7 @@ pub fn config_dir() -> Option<PathBuf> {
|
||||
current().dir.clone()
|
||||
}
|
||||
|
||||
/// 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"))
|
||||
}
|
||||
}
|
||||
pub use crate::platform_dir::platform_dir;
|
||||
|
||||
/// 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).
|
||||
@@ -89,6 +79,7 @@ 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()
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#![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)]
|
||||
@@ -25,6 +26,7 @@ mod build_flavor;
|
||||
mod display;
|
||||
mod launch_profile;
|
||||
mod nightly_session;
|
||||
mod platform_dir;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
|
||||
@@ -93,13 +95,48 @@ fn desktop_platform(install: InstallSpec, settings: Location, wake: Wake, at_exi
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
})
|
||||
.icon_png(ICON_128)
|
||||
.files(Arc::new(service))
|
||||
// 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())
|
||||
.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() })
|
||||
@@ -411,6 +448,7 @@ 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.
|
||||
@@ -434,6 +472,10 @@ 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()));
|
||||
}
|
||||
if !nightly {
|
||||
// Nightly is managed by ArtCraft Launcher: no self-update prompt or stable feed.
|
||||
app.enable_update_checks();
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
//! 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"))
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,12 @@ 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,
|
||||
@@ -280,8 +286,13 @@ impl EffectSpec {
|
||||
}
|
||||
}
|
||||
"desaturate" => {
|
||||
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));
|
||||
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));
|
||||
}
|
||||
}
|
||||
"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)),
|
||||
@@ -318,6 +329,12 @@ 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 {
|
||||
|
||||
+18
-2
@@ -36,6 +36,7 @@ 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};
|
||||
@@ -48,7 +49,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.
|
||||
/// colour override or a reduction in the saturation of text colours.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnimState {
|
||||
pub visible: bool,
|
||||
@@ -60,11 +61,24 @@ 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 }
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,12 +109,14 @@ 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);
|
||||
|
||||
+178
-12
@@ -1,6 +1,7 @@
|
||||
//! 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};
|
||||
@@ -12,14 +13,45 @@ 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, 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
|
||||
/// `!!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
|
||||
/// 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: matching costs the sum of the two shape lists, not their product.
|
||||
/// 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.
|
||||
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()];
|
||||
@@ -34,17 +66,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,
|
||||
};
|
||||
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();
|
||||
// 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);
|
||||
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.entry(k).or_default().push_back(j);
|
||||
index.insert(k, j, sb);
|
||||
}
|
||||
}
|
||||
if index.is_empty() {
|
||||
@@ -55,7 +87,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.get_mut(&k).and_then(VecDeque::pop_front) else { continue };
|
||||
let Some(j) = index.take(k, sa, b, &used_b) else { continue };
|
||||
let Some(sb) = b.shapes.get(j) else { continue };
|
||||
if let Some(u) = used_a.get_mut(i) {
|
||||
*u = true;
|
||||
@@ -77,6 +109,84 @@ 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() {
|
||||
@@ -186,7 +296,56 @@ 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 {
|
||||
Shape { id: ShapeId(0), name: String::new(), xfrm: None, fill: None, ..s.clone() }
|
||||
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));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two shapes differ in their geometry only, and it is drawn as an outline (shapes,
|
||||
@@ -217,6 +376,13 @@ 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
|
||||
|
||||
+254
-11
@@ -4,7 +4,8 @@ use std::sync::Arc;
|
||||
|
||||
use deckcraft_model::anim::{ANIMATIONS, TRANSITIONS, TextBuild};
|
||||
use deckcraft_model::{
|
||||
AnimClass, AnimStart, Animation, ColorRef, CustomShow, Presentation, Rgba, Shape, ShapeId, Slide, SlideId, TextBody, Transition, Xfrm,
|
||||
AnimClass, AnimStart, Animation, ColorRef, CustomShow, Fill, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, Slide, SlideId, TextBody,
|
||||
Transition, Xfrm,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
@@ -171,6 +172,45 @@ 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 {
|
||||
@@ -575,11 +615,161 @@ 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, and a named text box keeps its partner.
|
||||
// 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).
|
||||
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(1), ShapeId(2)), (ShapeId(3), ShapeId(4))]);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -608,6 +798,7 @@ 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());
|
||||
@@ -668,12 +859,14 @@ fn morph_frame_moves_blends_and_fades() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn morph_frame_cross_fades_changed_content() {
|
||||
fn forced_name_cross_fades_changed_content() {
|
||||
// #2467: `!!` forces a pair even when the text changed; the two cross-fade on the moving box.
|
||||
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") }];
|
||||
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))]);
|
||||
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);
|
||||
@@ -689,8 +882,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);
|
||||
@@ -713,6 +906,7 @@ 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);
|
||||
@@ -1116,6 +1310,7 @@ 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);
|
||||
@@ -1243,16 +1438,64 @@ 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.
|
||||
// One named pair at opposite ends with the same content.
|
||||
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 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);
|
||||
// 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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -279,7 +279,8 @@ 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 spec = Arc::new(build_spec(a, xf, sw, sh, &resolve));
|
||||
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 dur = secs(a.duration_ms);
|
||||
let delay = secs(a.delay_ms);
|
||||
let until_next_click = a.repeat == u32::MAX;
|
||||
@@ -612,7 +613,23 @@ fn shape_index(shapes: &[Shape]) -> HashMap<ShapeId, &Shape> {
|
||||
out
|
||||
}
|
||||
|
||||
fn build_spec(a: &Animation, xf: Xfrm, sw: f64, sh: f64, resolve: &dyn Fn(&deckcraft_model::ColorRef) -> Rgba) -> EffectSpec {
|
||||
/// 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 {
|
||||
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 {
|
||||
@@ -626,6 +643,8 @@ fn build_spec(a: &Animation, xf: Xfrm, sw: f64, sh: f64, resolve: &dyn Fn(&deckc
|
||||
amount: a.amount,
|
||||
color: a.color.as_ref().map(resolve),
|
||||
path,
|
||||
has_text,
|
||||
grays_own_fill,
|
||||
xf,
|
||||
slide_w: sw,
|
||||
slide_h: sh,
|
||||
|
||||
@@ -39,12 +39,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn hsl_roundtrip() {
|
||||
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);
|
||||
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);
|
||||
assert!(
|
||||
(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:?}"
|
||||
(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:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ chrono = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
deckcraft-anim = { workspace = true }
|
||||
memory-stats = "1.2.0"
|
||||
zip = { workspace = true }
|
||||
craft-metafile = { workspace = true, features = ["write"] }
|
||||
|
||||
|
||||
@@ -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, ids?} → {count, path?}",
|
||||
"{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?}",
|
||||
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}",
|
||||
"{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)}",
|
||||
has_slide,
|
||||
timing
|
||||
),
|
||||
@@ -314,9 +314,20 @@ 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 = build(p, slide_extent(s)?)?;
|
||||
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 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"))?);
|
||||
@@ -393,6 +404,9 @@ 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;
|
||||
@@ -412,6 +426,15 @@ 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;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -552,6 +575,29 @@ 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();
|
||||
|
||||
@@ -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|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|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!(
|
||||
query "file.info",
|
||||
"Info",
|
||||
@@ -390,11 +390,12 @@ fn report_damage(s: &mut Session, damaged: &Damage) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode the presentation in `format` (`deckcraft`, `pptx`, `potx`, `ppsx`, `outline`, `pdf`, `gif`).
|
||||
/// Encode the presentation in `format` (`deckcraft`, `pptx`, `potx`, `ppsx`, `outline`, `txt`, `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" | "txt" => Ok(deckcraft_format::slides_to_outline(doc).into_bytes()),
|
||||
"outline" => Ok(deckcraft_format::slides_to_outline(doc).into_bytes()),
|
||||
"txt" => Ok(outline_txt_bytes(&deckcraft_format::slides_to_outline(doc))),
|
||||
"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),
|
||||
@@ -404,6 +405,16 @@ 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};
|
||||
|
||||
@@ -515,6 +526,12 @@ 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)
|
||||
@@ -536,7 +553,9 @@ pub fn format_for_path(path: &str) -> &'static str {
|
||||
"pdf"
|
||||
} else if l.ends_with(".gif") {
|
||||
"gif"
|
||||
} else if l.ends_with(".txt") || l.ends_with(".md") {
|
||||
} else if l.ends_with(".txt") {
|
||||
"txt"
|
||||
} else if l.ends_with(".md") {
|
||||
"outline"
|
||||
} else if l.ends_with(".rtf") {
|
||||
"rtf"
|
||||
@@ -571,6 +590,7 @@ 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()))?;
|
||||
@@ -661,6 +681,7 @@ 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);
|
||||
|
||||
@@ -287,8 +287,16 @@ fn current_run(s: &Session) -> RunProps {
|
||||
}
|
||||
None => {
|
||||
let Some(sh) = st.selected_shapes().first().map(|x| (*x).clone()) else { return RunProps::default() };
|
||||
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();
|
||||
// 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());
|
||||
(sh, para, rp)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -344,6 +344,13 @@ 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()
|
||||
|
||||
+366
-15
@@ -247,25 +247,133 @@ 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`), or the name of the file the
|
||||
/// picture came from, which may have spaces (`Screenshot 2024 at 10.00.png`).
|
||||
/// 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",
|
||||
];
|
||||
|
||||
fn is_file_name(alt: &str, file: Option<&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();
|
||||
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))
|
||||
is_file_name_with(alt, file, &PICTURE_EXTENSIONS, &[&PICTURE_EXTENSIONS])
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
/// 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 {
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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![];
|
||||
@@ -283,9 +391,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 && 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).
|
||||
} 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).
|
||||
out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Alternative text is a file name"}));
|
||||
}
|
||||
});
|
||||
@@ -1102,8 +1210,251 @@ 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));
|
||||
// The picture's own file name counts, spaces and all.
|
||||
// A file name with spaces counts by its shape, with or without the picture's own name.
|
||||
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));
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,8 @@ 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(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -262,6 +262,13 @@ 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 {
|
||||
@@ -689,13 +696,24 @@ 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));
|
||||
sel.slide = sel.slide.min(doc.slides.len().saturating_sub(1));
|
||||
// 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;
|
||||
}
|
||||
} 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) {
|
||||
@@ -987,6 +1005,44 @@ 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);
|
||||
|
||||
@@ -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?, 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}",
|
||||
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?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick} → {id, ids: the regenerated shapes}",
|
||||
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?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad} → {id, ids: the regenerated shapes}",
|
||||
has_diagram,
|
||||
change_colors
|
||||
),
|
||||
|
||||
@@ -339,33 +339,47 @@ 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.
|
||||
@@ -374,5 +388,6 @@ pub(super) fn change_layout(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
d.kind = kind;
|
||||
Ok(Value::Null)
|
||||
})
|
||||
})?;
|
||||
Ok(regenerated(s, gid))
|
||||
}
|
||||
|
||||
@@ -267,12 +267,31 @@ fn cell_param(p: &Value, key: &str, cmd: &str) -> Result<Option<(usize, usize)>>
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)> {
|
||||
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)> {
|
||||
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)));
|
||||
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)))
|
||||
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))?))
|
||||
}
|
||||
|
||||
fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> Result<()>) -> Result<Value> {
|
||||
@@ -328,6 +347,7 @@ 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")) {
|
||||
@@ -465,7 +485,10 @@ 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 => at(s, p, "table.split")?,
|
||||
None => {
|
||||
let (r, c) = at(s, p, "table.split")?;
|
||||
(r.value(), c.value())
|
||||
}
|
||||
};
|
||||
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")) })
|
||||
}
|
||||
@@ -727,8 +750,17 @@ 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, 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 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 column_width(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -736,7 +768,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| {
|
||||
index_in_table("table.columnWidth", "col", c, t.n_cols(), "columns")?;
|
||||
let c = index_in_table("table.columnWidth", "col", &c, t.n_cols(), "column")?;
|
||||
// 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());
|
||||
@@ -765,7 +797,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| {
|
||||
index_in_table("table.rowHeight", "row", r, t.n_rows(), "rows")?;
|
||||
let r = index_in_table("table.rowHeight", "row", &r, t.n_rows(), "row")?;
|
||||
if let Some(x) = t.rows.get_mut(r) {
|
||||
x.height = h;
|
||||
}
|
||||
|
||||
@@ -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: the punctuation was typed before the space.
|
||||
// "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).
|
||||
let mut word: String = line.get(start..word_end).map(|w| w.iter().collect()).unwrap_or_default();
|
||||
if replacement(&s.prefs, &word).is_none() {
|
||||
if !typing && 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,6 +195,7 @@ 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) {
|
||||
@@ -315,6 +316,7 @@ 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) {
|
||||
|
||||
@@ -338,7 +338,10 @@ 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`)")) };
|
||||
let keep = body.paragraphs.first().and_then(|p| p.runs.first()).map(|r| r.props.clone()).unwrap_or_default();
|
||||
// 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 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() {
|
||||
@@ -353,6 +356,11 @@ 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(())
|
||||
|
||||
@@ -25,6 +25,10 @@ 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 {
|
||||
@@ -65,6 +69,9 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -72,6 +79,11 @@ 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) => {
|
||||
|
||||
@@ -73,6 +73,12 @@ 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())
|
||||
|
||||
@@ -255,6 +255,54 @@ 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;
|
||||
|
||||
@@ -168,6 +168,8 @@ 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);
|
||||
|
||||
@@ -237,6 +237,9 @@ 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>>,
|
||||
@@ -269,6 +272,7 @@ impl DocState {
|
||||
compare: None,
|
||||
last_duplicate: None,
|
||||
auto_list: None,
|
||||
autocorrected: None,
|
||||
notes_run: None,
|
||||
notes_before: None,
|
||||
}
|
||||
@@ -729,6 +733,9 @@ impl Session {
|
||||
}
|
||||
if outer {
|
||||
self.tool.vertex_kind = vertex_kind;
|
||||
if let Some(st) = self.active_mut() {
|
||||
st.autocorrected = None;
|
||||
}
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
@@ -736,6 +743,7 @@ 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)
|
||||
@@ -753,8 +761,12 @@ 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 });
|
||||
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind: vertex_kind.clone() });
|
||||
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 {
|
||||
|
||||
@@ -140,7 +140,13 @@ pub fn discard(dir: &Path, uid: u64) {
|
||||
/// Write entries for the unsaved presentations (and drop those of saved ones). Returns how many
|
||||
/// were written.
|
||||
pub fn save(s: &Session, dir: &Path) -> Result<usize> {
|
||||
std::fs::create_dir_all(dir).map_err(|e| EngineError::Other(format!("{}: {e}", dir.display())))?;
|
||||
// On Unix every folder made here is owner-only (`0o700`), like the entries in it: with the
|
||||
// default mode other accounts could list them. A folder that already exists keeps its mode.
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||
builder.create(dir).map_err(|e| EngineError::Other(format!("{}: {e}", dir.display())))?;
|
||||
claim_dir(dir);
|
||||
let mut n = 0;
|
||||
for d in s.documents() {
|
||||
@@ -364,6 +370,29 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// On Unix the recovery folder is owner-only like its entries, and a folder that already
|
||||
/// exists keeps its mode.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_recovery_folder_is_owner_only() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
|
||||
let base = temp("recovery-modes");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let new = base.join("recovery");
|
||||
save(&s, &new).unwrap();
|
||||
assert_eq!(mode(&new) & 0o077, 0, "the new recovery folder has group or other bits");
|
||||
let picked = base.join("picked");
|
||||
std::fs::create_dir_all(&picked).unwrap();
|
||||
std::fs::set_permissions(&picked, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let before = mode(&picked);
|
||||
save(&s, &picked).unwrap();
|
||||
assert_eq!(mode(&picked), before, "an existing folder keeps its mode");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A FIFO where an entry or its metadata belongs is skipped rather than read (that blocked
|
||||
/// start-up forever), and a folder full of entries reopens only [`MAX_REOPEN`] per start.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -64,6 +64,42 @@ 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())
|
||||
}
|
||||
@@ -91,7 +127,12 @@ 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}"));
|
||||
@@ -140,7 +181,13 @@ 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}");
|
||||
eprintln!("soak seed {seed}: {edits} of {steps} steps edited");
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
fn steps(default: usize) -> usize {
|
||||
@@ -149,6 +196,9 @@ 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));
|
||||
}
|
||||
@@ -157,6 +207,9 @@ 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));
|
||||
}
|
||||
|
||||
+278
-2
@@ -1399,13 +1399,107 @@ 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("outline"));
|
||||
assert_eq!(f("a.txt"), Some("txt"));
|
||||
assert_eq!(f("a.md"), 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();
|
||||
@@ -5359,6 +5453,51 @@ 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();
|
||||
@@ -5859,15 +5998,30 @@ 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.
|
||||
for i in 0..tools::MAX_GESTURE_POINTS + 10 {
|
||||
// The first press counts toward the cap, so 11 of these presses add no point.
|
||||
for i in 0..point_cap + 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);
|
||||
}
|
||||
|
||||
@@ -6128,6 +6282,8 @@ 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, ¶ms).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");
|
||||
@@ -6137,6 +6293,40 @@ 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, ¶ms).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();
|
||||
@@ -7424,6 +7614,67 @@ 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();
|
||||
@@ -8220,3 +8471,28 @@ 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, ¶ms).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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,6 +274,9 @@ 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.
|
||||
@@ -310,6 +313,15 @@ 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).
|
||||
|
||||
@@ -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() < super::MAX_GESTURE_POINTS;
|
||||
self.tool.press_added_vertex = points.len() < self.tool.press_point_cap();
|
||||
if self.tool.press_added_vertex {
|
||||
points.push(p);
|
||||
}
|
||||
|
||||
@@ -60,3 +60,20 @@ fn standalone_emf_and_wmf_files_insert_as_pictures_and_save_as_metafile_parts()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,9 +113,9 @@ struct Outline {
|
||||
/// non-ASCII `Token::Symbol`.
|
||||
skip_cont: usize,
|
||||
line: String,
|
||||
/// The document's code page (`\ansicpg`), which `\'hh` bytes are in: Windows-1252 until it
|
||||
/// names another single-byte one (#2394).
|
||||
/// The document's code page for `\'hh` bytes (Windows-1252 unless `\ansicpg` names a supported page).
|
||||
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,6 +203,7 @@ 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);
|
||||
@@ -214,6 +215,10 @@ 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(),
|
||||
@@ -235,6 +240,7 @@ impl Outline {
|
||||
craft_rtf::Token::Bin(_) => self.skip_cont = 0,
|
||||
}
|
||||
}
|
||||
self.hex_decoder.finish(&mut self.line);
|
||||
}
|
||||
|
||||
fn open_group(&mut self) {
|
||||
@@ -277,9 +283,10 @@ 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" => {
|
||||
if let Some(cp) = arg.and_then(|a| u16::try_from(a).ok()).filter(|cp| craft_rtf::codepage::is_byte_code_page(*cp)) {
|
||||
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()) {
|
||||
self.code_page = cp;
|
||||
}
|
||||
}
|
||||
@@ -311,7 +318,7 @@ impl Outline {
|
||||
return;
|
||||
}
|
||||
if !self.st.skip && h != 0 {
|
||||
self.line.push(craft_rtf::codepage::code_page_byte(self.code_page, h));
|
||||
self.hex_decoder.byte(h, self.code_page, &mut self.line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,7 +338,7 @@ impl Outline {
|
||||
return;
|
||||
}
|
||||
match n {
|
||||
b'\\' | b'{' | b'}' => self.line.push(n as char),
|
||||
b'\\' | b'{' | b'}' => self.hex_decoder.byte(n, self.code_page, &mut self.line),
|
||||
b'~' => self.line.push('\u{a0}'),
|
||||
b'_' => self.line.push('\u{2011}'),
|
||||
b'\n' | b'\r' => self.flush(true),
|
||||
@@ -358,6 +365,15 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -631,9 +647,7 @@ mod tests {
|
||||
assert_eq!(crate::slides_to_outline(&reopened), expected);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// `\ansicpg` names the code page of the escapes, including pages with multibyte letters.
|
||||
#[test]
|
||||
fn hex_escapes_decode_in_the_code_page_ansicpg_names() {
|
||||
let outline = |cpg: &str, title: &str, body: &str| {
|
||||
@@ -651,6 +665,40 @@ 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]
|
||||
|
||||
@@ -15,3 +15,8 @@ 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"] }
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
//! 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;
|
||||
@@ -0,0 +1,195 @@
|
||||
//! 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}");
|
||||
}
|
||||
@@ -57,6 +57,12 @@ 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;
|
||||
|
||||
@@ -20,9 +20,36 @@ impl Default for Headless {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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`";
|
||||
/// 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
|
||||
}
|
||||
|
||||
fn s<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
|
||||
p.get(k).and_then(Value::as_str)
|
||||
@@ -81,7 +108,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_APP}") } else { e.to_string() }
|
||||
if ui_only && deckcraft_engine::find_command(id).is_none() { format!("`{id}` is a UI command; {NEEDS_WINDOW}") } else { e.to_string() }
|
||||
});
|
||||
self.session.ui_requests.clear();
|
||||
r
|
||||
@@ -173,7 +200,8 @@ 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()})),
|
||||
m if m.starts_with("ui.") || m.starts_with("app.") => Err(format!("`{m}`: {NEEDS_APP}")),
|
||||
FOLDERS_METHOD => Ok(headless_folders(self.roots.as_deref())),
|
||||
m if m.starts_with("ui.") || m.starts_with("app.") => Err(format!("`{m}`: {NEEDS_WINDOW}")),
|
||||
other => Err(format!("unknown method `{other}`")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,13 @@
|
||||
//! 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. 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 (`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`).
|
||||
//! - [`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.
|
||||
@@ -15,6 +19,8 @@
|
||||
#![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;
|
||||
@@ -23,7 +29,7 @@ mod tools;
|
||||
pub use backend::Backend;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use backend::Remote;
|
||||
pub use headless::Headless;
|
||||
pub use headless::{FOLDERS_METHOD, Headless, NEEDS_WINDOW};
|
||||
pub use server::{PROTOCOL_VERSION, Server};
|
||||
pub use tools::{ToolResult, call_tool, tool_definitions};
|
||||
|
||||
|
||||
@@ -271,6 +271,36 @@ 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()));
|
||||
|
||||
+13
-5
@@ -4,7 +4,7 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::backend::Backend;
|
||||
use crate::headless::NEEDS_APP;
|
||||
use crate::headless::NEEDS_WINDOW;
|
||||
|
||||
/// The result of `tools/call`: MCP content blocks plus the `isError` flag.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -60,7 +60,13 @@ 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}})
|
||||
}
|
||||
|
||||
const APP_ONLY: &str = " Desktop app only (`deckcraft-cli mcp --connect PORT`).";
|
||||
/// 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).";
|
||||
|
||||
pub fn tool_definitions() -> Vec<Value> {
|
||||
vec![
|
||||
@@ -115,11 +121,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, 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 (outline, or txt with CRLF), 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", "rtf", "pdf", "gif"], "description": "Output format (default: from the path's extension)"},
|
||||
"format": {"type": "string", "enum": ["png", "jpeg", "pptx", "deckcraft", "outline", "txt", "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)"),
|
||||
@@ -287,6 +293,7 @@ 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),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -481,7 +488,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_APP}. Use render_slide to see a slide headlessly."));
|
||||
return ToolResult::error(format!("screenshot: {NEEDS_WINDOW}. 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) {
|
||||
@@ -495,6 +502,7 @@ 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}`")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,10 +81,10 @@ pub fn decode(bytes: &Bytes) -> Result<Pcm> {
|
||||
Some(r) => r,
|
||||
None => contained(|| decode_symphonia(bytes, "mkv")),
|
||||
},
|
||||
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 => {
|
||||
crate::mp4guard::check(c, bytes)?;
|
||||
contained(|| decode_symphonia(bytes, c.name()))
|
||||
}
|
||||
c => contained(|| decode_symphonia(bytes, c.name())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,7 +297,8 @@ 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.
|
||||
/// 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.
|
||||
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());
|
||||
|
||||
@@ -35,6 +35,17 @@ 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> {
|
||||
|
||||
@@ -52,7 +52,11 @@ 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.
|
||||
if let Some(d) = crate::audio::demux_duration_ms(bytes, Container::sniff(bytes).name()) {
|
||||
// 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()) {
|
||||
info.duration_ms = d;
|
||||
}
|
||||
}
|
||||
@@ -72,10 +76,8 @@ 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); 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()));
|
||||
}
|
||||
// Symphonia opens an MP4 wherever its probe finds an `ftyp` (after leading ID3v2 tags too).
|
||||
crate::mp4guard::check(c, bytes)?;
|
||||
let (codec, rate, channels, frames) = std::panic::catch_unwind(|| crate::audio::probe_symphonia(bytes, c.name()))
|
||||
.ok()
|
||||
.flatten()
|
||||
|
||||
@@ -434,3 +434,29 @@ 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");
|
||||
}
|
||||
|
||||
@@ -1175,3 +1175,72 @@ 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<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,22 +14,35 @@ 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. `fg` is the text colour (palette index 0xFFFF) and `alpha` fades it all.
|
||||
/// points per font unit.
|
||||
/// False when the glyph has no colour version, so the caller draws the plain outline.
|
||||
pub fn paint(ctx: &mut RenderContext, face: &FontFace, gid: u32, at: Affine, scale: f64, fg: Rgba, alpha: f64) -> bool {
|
||||
pub(super) fn paint(ctx: &mut RenderContext, face: &FontFace, gid: u32, at: Affine, scale: f64, colors: Colors) -> 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 palette: Vec<Rgba> = font
|
||||
let mut 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, opened: Vec::new(), work: 0 };
|
||||
p.ctx.push_layer(None, None, Some(alpha.clamp(0.0, 1.0) as f32), None, None);
|
||||
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 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() {
|
||||
|
||||
@@ -13,13 +13,41 @@ 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, paras: vec![] }
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,11 +58,23 @@ 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 }
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@ 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::{draw_layout_with, draw_text, line_bounds, preview_empty_bullets, prompt_body, text_transform, text_warp};
|
||||
use super::text_draw::{
|
||||
desaturate_layout, draw_animated_layout, draw_text, line_bounds, preview_empty_bullets, prompt_body, text_transform, text_warp,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
pub struct Renderer {
|
||||
@@ -1092,6 +1094,7 @@ 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).
|
||||
@@ -1100,7 +1103,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_layout_with(ctx, &l, tr, m, &st.paras),
|
||||
None => draw_animated_layout(ctx, &l, tr, m, &st.paras, st.text_desaturation),
|
||||
}
|
||||
} else if f.opts.edit && s.ph.is_some() {
|
||||
let kind = s.ph_type().unwrap_or(PhType::Body);
|
||||
|
||||
@@ -686,6 +686,48 @@ 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();
|
||||
@@ -1180,6 +1222,14 @@ 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]
|
||||
|
||||
@@ -339,6 +339,38 @@ 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.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::geometry::{blur, color, pre_translate, scale_of};
|
||||
use super::opts::ParaState;
|
||||
use super::opts::{ParaState, ShapeState};
|
||||
use super::{
|
||||
Affine, Arc, BezPath, Ctx, FontDb, HashMap, Opts, PhType, Rect, RenderContext, Rgba, Shape, TextBody, Vec2, colr, paint, peniko, resolve,
|
||||
};
|
||||
@@ -109,8 +109,55 @@ 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);
|
||||
@@ -144,13 +191,14 @@ pub fn draw_layout_with(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout,
|
||||
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(ctx, run, *gid, at, ps.opacity);
|
||||
draw_glyph_with(ctx, run, *gid, at, ps.opacity, None, desaturation);
|
||||
continue;
|
||||
};
|
||||
let li = lines_of.line_at(run.para, *y);
|
||||
@@ -161,7 +209,7 @@ pub fn draw_layout_with(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout,
|
||||
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);
|
||||
draw_glyph_with(ctx, run, *gid, at, ps.opacity, fill, desaturation);
|
||||
}
|
||||
}
|
||||
for d in l.decos.iter().filter(|d| !d.behind) {
|
||||
@@ -347,7 +395,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);
|
||||
draw_glyph_with(ctx, run, gid, at, opacity, None, 0.0);
|
||||
}
|
||||
|
||||
/// [`draw_glyph`], filled with `fill` (a gradient laid out in the text's space, and the map from
|
||||
@@ -359,6 +407,7 @@ 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() {
|
||||
@@ -367,7 +416,11 @@ 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, run.color, alpha) {
|
||||
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 })
|
||||
{
|
||||
return;
|
||||
}
|
||||
let path = glyph(&run.face, gid);
|
||||
|
||||
+112
-38
@@ -181,11 +181,12 @@ pub(crate) fn break_lines(p: &ParaShaped, params: &BreakParams) -> Vec<RawLine>
|
||||
next = i + 1;
|
||||
break;
|
||||
}
|
||||
let adv = if c == '\t' {
|
||||
let (adv, seg) = if c == '\t' {
|
||||
let seg = tab_segment(&p.cells, i);
|
||||
// The implicit stop is for the first line only: later lines start at the margin.
|
||||
tab_advance(x0 + x, tab_stops, default_tab, tab_segment(&p.cells, i), if lines.is_empty() { hang_stop } else { None }, x0 + avail)
|
||||
(tab_advance(x0 + x, tab_stops, default_tab, seg, if lines.is_empty() { hang_stop } else { None }, x0 + avail), seg)
|
||||
} else {
|
||||
p.cells.get(i).map(|c| c.adv).unwrap_or(0.0)
|
||||
(p.cells.get(i).map(|c| c.adv).unwrap_or(0.0), (0.0, 0.0, 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) {
|
||||
@@ -198,8 +199,22 @@ pub(crate) fn break_lines(p: &ParaShaped, params: &BreakParams) -> Vec<RawLine>
|
||||
next = i + 1;
|
||||
break;
|
||||
}
|
||||
// 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 {
|
||||
// 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 {
|
||||
end = i;
|
||||
next = i;
|
||||
while end > start && p.cells.get(end - 1).is_some_and(|c| c.ch == ' ') {
|
||||
@@ -289,11 +304,12 @@ 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, and the width of
|
||||
/// that text before its first ".".
|
||||
pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64) {
|
||||
/// 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) {
|
||||
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;
|
||||
@@ -302,47 +318,78 @@ pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64) {
|
||||
dec = Some(w);
|
||||
}
|
||||
w += c.adv;
|
||||
if !c.ch.is_whitespace() {
|
||||
last_non_ws = w;
|
||||
}
|
||||
}
|
||||
(w, dec.unwrap_or(w))
|
||||
(w, dec.unwrap_or(w), last_non_ws)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
///
|
||||
/// `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.
|
||||
/// `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);
|
||||
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 {
|
||||
// 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
|
||||
}
|
||||
Some(s) => effective_pos(s) <= h + 0.5,
|
||||
None => h >= default_next - 0.5,
|
||||
};
|
||||
if !explicit_wins {
|
||||
return (h - x).max(1.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);
|
||||
if let Some(s) = explicit {
|
||||
let to = (effective_pos(s) - x).max(0.0);
|
||||
return match s.align {
|
||||
TabAlign::Left => to,
|
||||
TabAlign::Right => (to - seg.0).max(0.0),
|
||||
@@ -362,8 +409,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), None, 600.0).is_finite());
|
||||
assert_eq!(tab_advance(10.0, &stops, 72.0, (0.0, 0.0), None, 600.0), 90.0);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -371,16 +418,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), Some(80.0), 60.0), 40.0);
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (20.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), None, 600.0), 500.0);
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.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), None, 800.0), 600.0);
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0, 100.0), None, 800.0), 600.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -388,8 +435,35 @@ 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), None, 600.0), 350.0);
|
||||
assert_eq!(tab_advance(100.0, &inside, 72.0, (100.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), None, 600.0), 400.0);
|
||||
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, ¢er, 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1477,6 +1477,106 @@ 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);
|
||||
|
||||
@@ -30,7 +30,9 @@ log = { workspace = true }
|
||||
web-time = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft = { workspace = true, features = ["update"] }
|
||||
# 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-update = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -40,6 +42,7 @@ 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 }
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! 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;
|
||||
@@ -0,0 +1,168 @@
|
||||
//! 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);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ 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;
|
||||
@@ -140,6 +141,10 @@ 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,
|
||||
@@ -321,6 +326,12 @@ 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;
|
||||
@@ -372,6 +383,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;
|
||||
}
|
||||
@@ -383,7 +399,8 @@ impl SlideApp {
|
||||
updates_ui::tick(self, ctx);
|
||||
self.take_file_answers();
|
||||
}
|
||||
self.autosave_if_due(ctx);
|
||||
// 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.tick_media_clock(ctx);
|
||||
// Exit work must finish before the platform quits inside this callback.
|
||||
embed::logic(ctx, || {
|
||||
@@ -397,6 +414,12 @@ 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;
|
||||
|
||||
@@ -35,12 +35,7 @@ impl SlideApp {
|
||||
match self.session.active() {
|
||||
Some(d) => {
|
||||
let uid = d.uid;
|
||||
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()));
|
||||
let (name, _, _) = super::files::save_target(d.path.as_deref(), &d.title());
|
||||
match self.save_document(uid) {
|
||||
SaveOutcome::Saved | SaveOutcome::Downloaded => Ok(json!({"path": name})),
|
||||
SaveOutcome::Pending => Ok(json!({"path": name, "pending": true})),
|
||||
@@ -399,6 +394,16 @@ 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,21 +1,41 @@
|
||||
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 = control::handle(self, ctx, &request);
|
||||
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 });
|
||||
}
|
||||
channel.settle(request, reply, control::document_id(self), settle_ms(ctx.global_style().animation_time));
|
||||
}
|
||||
let document = control::document_id(self);
|
||||
@@ -25,6 +45,40 @@ 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) {
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::host::{PickId, PickRequest, Picked, WriteIntent};
|
||||
use deckcraft_engine::cmd::file::{format_for_path, mark_saved_snapshot, save_bytes};
|
||||
use deckcraft_engine::cmd::file::{WRITABLE_EXTENSIONS, format_for_path, mark_saved_snapshot, save_bytes, writable_format_for_path};
|
||||
use deckcraft_model::Presentation;
|
||||
|
||||
use super::{FilePlace, FilePurpose, FileTarget, LocatedPlace, RECENT_MAX, SlideApp, Target, UiRequest, Value, ViewMode, json, media};
|
||||
@@ -310,6 +310,9 @@ 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,
|
||||
@@ -478,9 +481,10 @@ 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; 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 (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
|
||||
/// 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]) {
|
||||
@@ -825,13 +829,17 @@ impl SlideApp {
|
||||
return outcome;
|
||||
};
|
||||
let snapshot = d.doc.clone();
|
||||
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)) {
|
||||
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) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
let outcome = self.file_failure(e.to_string());
|
||||
@@ -1012,14 +1020,22 @@ impl SlideApp {
|
||||
path.to_path_buf()
|
||||
};
|
||||
let encoded;
|
||||
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
|
||||
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,
|
||||
};
|
||||
self.host.files().write(&out, bytes, intent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
@@ -1027,6 +1043,27 @@ 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(¤t) {
|
||||
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) }
|
||||
}
|
||||
|
||||
@@ -249,6 +249,56 @@ 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(©).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());
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//! (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};
|
||||
|
||||
@@ -13,21 +12,8 @@ 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 {
|
||||
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(),
|
||||
paras: tl.paragraph_targets(id).into_iter().map(|p| (p, ParaState::from(tl.state(id, Some(p), step, t)))).collect(),
|
||||
..ShapeState::from(a)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -291,6 +291,10 @@ 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)),
|
||||
@@ -388,6 +392,13 @@ 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) = ¶ms.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"));
|
||||
};
|
||||
|
||||
@@ -95,6 +95,9 @@ 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.
|
||||
|
||||
@@ -202,6 +202,64 @@ impl AutoCorrectForm {
|
||||
}
|
||||
}
|
||||
|
||||
/// Preferences › AI Integrations: the agent settings, saved apart from the preferences where
|
||||
/// `deckcraft-cli mcp` reads them (`app.agents`), and the link's state the page shows.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct AgentsPart {
|
||||
/// The settings as the page edits them, under [`crate::agents::PAGE`].
|
||||
draft: craft::ui::patterns::preferences::SettingsDraft,
|
||||
/// The settings last applied.
|
||||
saved: craft::automation::agents::AgentSettings,
|
||||
/// The settings when Preferences opened, which Cancel puts back.
|
||||
opening: craft::automation::agents::AgentSettings,
|
||||
/// Applied and not yet saved by [`pump`].
|
||||
applied: Option<craft::automation::agents::AgentSettings>,
|
||||
status: craft::automation::agents::AgentLinkStatus,
|
||||
mcp_flag: bool,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl AgentsPart {
|
||||
fn new(settings: craft::automation::agents::AgentSettings, status: craft::automation::agents::AgentLinkStatus, mcp_flag: bool) -> Self {
|
||||
let mut part = Self { draft: Default::default(), saved: settings.clone(), opening: settings, applied: None, status, mcp_flag };
|
||||
part.reset();
|
||||
part
|
||||
}
|
||||
|
||||
/// The draft back to the settings last applied.
|
||||
fn reset(&mut self) {
|
||||
self.draft.set(crate::agents::PAGE, &self.saved);
|
||||
}
|
||||
|
||||
/// The settings the draft holds.
|
||||
fn edited(&self) -> craft::automation::agents::AgentSettings {
|
||||
self.draft.get(crate::agents::PAGE).unwrap_or_else(|| self.saved.clone())
|
||||
}
|
||||
|
||||
/// The page: with the suite's `AI-MCP` flag, the framework's Agents page over the draft (the
|
||||
/// ArtCraft Launcher's switch decides; the page has none of its own); without it, a line that
|
||||
/// says so, as DeckCraft had no agent settings before the switch. Returns whether the draft changed.
|
||||
fn show(&mut self, ui: &mut Ui) -> bool {
|
||||
if !self.mcp_flag {
|
||||
craft::ui::display::Text::new(tl!(
|
||||
"Agents use DeckCraft without a window. The ArtCraft Launcher's Settings › AI agents switch lets them into the open window once the suite's AI-MCP flag is on."
|
||||
))
|
||||
.shade(craft::ui::display::Shade::Muted)
|
||||
.show(ui);
|
||||
return false;
|
||||
}
|
||||
craft::automation::ui::agents::AgentsPage::new(crate::agents::PAGE, &mut self.draft, &self.status).mcp_flag(true).show(ui).changed
|
||||
}
|
||||
}
|
||||
|
||||
/// What OK hands to [`pump`]: the preferences and, as the dialog leaves the host before `pump`
|
||||
/// sees it again, the agent settings the AI Integrations page holds at that moment.
|
||||
struct PreferencesOk {
|
||||
draft: PrefDraft,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: Option<craft::automation::agents::AgentSettings>,
|
||||
}
|
||||
|
||||
struct PreferencesDialog {
|
||||
state: PreferencesState,
|
||||
draft: PrefDraft,
|
||||
@@ -210,6 +268,9 @@ struct PreferencesDialog {
|
||||
scale_shown: f64,
|
||||
autocorrect: Option<AutoCorrectForm>,
|
||||
actions: Vec<Value>,
|
||||
/// The AI Integrations page, where agents may use the window.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: Option<AgentsPart>,
|
||||
}
|
||||
|
||||
impl PreferencesModel for PreferencesDialog {
|
||||
@@ -254,7 +315,14 @@ impl PreferencesModel for PreferencesDialog {
|
||||
);
|
||||
let mut page = PageSpec::new("preferences", tl!("Preferences"), Vec::new()).resettable(false);
|
||||
page.groups = vec![general, editing];
|
||||
vec![page]
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
|
||||
let mut pages = vec![page];
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.agents.is_some() {
|
||||
let keywords = "agents AI MCP ArtCraft Launcher control port folders";
|
||||
pages.push(PageSpec::custom(crate::agents::PAGE, crate::agents::PAGE_TITLE).keywords(keywords).resettable(false));
|
||||
}
|
||||
pages
|
||||
}
|
||||
|
||||
fn set(&mut self, key: &str, value: PrefValue) {
|
||||
@@ -299,7 +367,14 @@ impl PreferencesModel for PreferencesDialog {
|
||||
}
|
||||
}
|
||||
|
||||
fn custom_page(&mut self, _ui: &mut Ui, _page: &str) -> bool {
|
||||
fn custom_page(&mut self, ui: &mut Ui, page: &str) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if page == crate::agents::PAGE
|
||||
&& let Some(agents) = self.agents.as_mut()
|
||||
{
|
||||
return agents.show(ui);
|
||||
}
|
||||
let _ = (ui, page);
|
||||
false
|
||||
}
|
||||
|
||||
@@ -322,23 +397,49 @@ impl PreferencesModel for PreferencesDialog {
|
||||
|
||||
impl PreferencesDraft for PreferencesDialog {
|
||||
fn differs(&self) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.agents.as_ref().is_some_and(|agents| agents.edited() != agents.saved) {
|
||||
return true;
|
||||
}
|
||||
self.draft != self.saved
|
||||
}
|
||||
|
||||
fn apply(&mut self) -> Result<(), String> {
|
||||
self.applied = Some(self.draft.clone());
|
||||
self.saved = self.draft.clone();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(agents) = self.agents.as_mut() {
|
||||
let edited = agents.edited();
|
||||
if edited != agents.saved {
|
||||
agents.saved = edited.clone();
|
||||
agents.applied = Some(edited);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cancel(&mut self) {
|
||||
self.draft = self.saved.clone();
|
||||
self.scale_shown = self.draft.ui_scale;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(agents) = self.agents.as_mut() {
|
||||
agents.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PreferencesDialog {
|
||||
fn ok_result(&self) -> PreferencesOk {
|
||||
PreferencesOk {
|
||||
draft: self.draft.clone(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: self.agents.as_ref().map(AgentsPart::edited),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for PreferencesDialog {
|
||||
type Result = Option<PrefDraft>;
|
||||
type Result = PreferencesOk;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
dialog_id("preferences")
|
||||
@@ -357,14 +458,14 @@ impl StackDialog for PreferencesDialog {
|
||||
.show(ui, self);
|
||||
self.state = state;
|
||||
match output.closed {
|
||||
Some(Closed::Ok) => Some(DialogResult::Ok(Some(self.draft.clone()))),
|
||||
Some(Closed::Ok) => Some(DialogResult::Ok(self.ok_result())),
|
||||
Some(Closed::Cancel) => Some(DialogResult::Cancel),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _ctx: &Context) -> Option<Self::Result> {
|
||||
(!self.nested_open()).then(|| Some(self.draft.clone()))
|
||||
(!self.nested_open()).then(|| self.ok_result())
|
||||
}
|
||||
|
||||
fn take_actions(&mut self) -> Vec<Value> {
|
||||
@@ -430,6 +531,8 @@ pub(crate) fn open(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost, _pa
|
||||
draft,
|
||||
autocorrect: None,
|
||||
actions: Vec::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: crate::agents::page_state(app).map(|(settings, status, mcp_flag)| AgentsPart::new(settings, status, mcp_flag)),
|
||||
});
|
||||
}
|
||||
Ok(Some(dialog_id("preferences")))
|
||||
@@ -463,20 +566,122 @@ pub(crate) fn pump(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost) {
|
||||
if let Some(draft) = applied {
|
||||
write(app, &draft);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pump_agents(app, host);
|
||||
if let Some(result) = host.take_by_id::<PreferencesDialog>(dialog_id("preferences")) {
|
||||
match result {
|
||||
DialogResult::Ok(draft) => {
|
||||
if let Some(draft) = draft {
|
||||
write(app, &draft);
|
||||
}
|
||||
DialogResult::Ok(ok) => {
|
||||
write(app, &ok.draft);
|
||||
app.dialogs.preferences_opening = None;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
// An edit applied in the closing pass never reached `pump_agents`.
|
||||
if let Some(agents) = &ok.agents {
|
||||
save_agents(app, agents);
|
||||
}
|
||||
app.dialogs.agents_opening = None;
|
||||
}
|
||||
}
|
||||
DialogResult::Cancel => {
|
||||
if let Some(opening) = app.dialogs.preferences_opening.take() {
|
||||
write(app, &opening);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(opening) = app.dialogs.agents_opening.take() {
|
||||
save_agents(app, &opening);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves the agent settings the AI Integrations page applied, and shows the link's state as it is
|
||||
/// now. A refused save (an agent's input clicked it) puts the page back to the saved settings.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn pump_agents(app: &mut SlideApp, host: &mut DialogHost) {
|
||||
let Some(agents) = host.get_mut::<PreferencesDialog>().and_then(|dialog| dialog.agents.as_mut()) else { return };
|
||||
if app.dialogs.agents_opening.is_none() {
|
||||
app.dialogs.agents_opening = Some(agents.opening.clone());
|
||||
}
|
||||
if let Some(applied) = agents.applied.take() {
|
||||
save_agents(app, &applied);
|
||||
}
|
||||
if let Some((settings, status, mcp_flag)) = crate::agents::page_state(app) {
|
||||
if settings != agents.saved {
|
||||
agents.saved = settings;
|
||||
agents.reset();
|
||||
}
|
||||
agents.status = status;
|
||||
agents.mcp_flag = mcp_flag;
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves `settings` as the agent settings (`app.agents`), unless they are saved already; a refusal
|
||||
/// shows in the status bar.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn save_agents(app: &mut SlideApp, settings: &craft::automation::agents::AgentSettings) {
|
||||
if crate::agents::page_state(app).is_none_or(|(saved, ..)| saved == *settings) {
|
||||
return;
|
||||
}
|
||||
// Allow Agent Control belongs to the time before the launcher's switch; the page never sets it.
|
||||
let mut given = serde_json::to_value(settings).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default();
|
||||
given.remove("allowAgentControl");
|
||||
if let Err(error) = crate::agents::command(app, &Value::Object(given)) {
|
||||
app.set_status(error);
|
||||
}
|
||||
}
|
||||
|
||||
// OK takes the dialog off the host before `pump` sees it again, so an agent edit that was not
|
||||
// applied in an earlier pass reaches the agent settings only through the OK result.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod agents_ok_tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use craft::automation::agents::{AgentSettings, AgentSwitch, WhenAppClosed};
|
||||
use craft::ui::runtime::env::WindowKey;
|
||||
use craft::ui::shell::WindowDialogs;
|
||||
use serde_json::json;
|
||||
|
||||
use super::PreferencesDialog;
|
||||
use crate::test_harness::harness;
|
||||
|
||||
#[test]
|
||||
fn ok_saves_the_agent_settings_the_page_holds() {
|
||||
let base = std::env::temp_dir().join(format!("dc-ui-prefs-agents-ok-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("settings")).unwrap();
|
||||
let mut h = harness(deckcraft_engine::Session::with_new(), crate::Services::default());
|
||||
let saved = Arc::new(Mutex::new(Vec::<AgentSettings>::new()));
|
||||
let into = saved.clone();
|
||||
let save: crate::agents::SaveFn = Box::new(move |settings| {
|
||||
into.lock().unwrap().push(settings.clone());
|
||||
Ok(())
|
||||
});
|
||||
let agents = crate::agents::Agents::new(
|
||||
Some(base.join("settings")),
|
||||
"DeckCraft test".into(),
|
||||
AgentSwitch::fixed(true, false),
|
||||
AgentSettings::default(),
|
||||
save,
|
||||
)
|
||||
.with_default_folder(None);
|
||||
h.state_mut().with_agents(agents);
|
||||
h.run_steps(2);
|
||||
h.state_mut().open_dialog("preferences", json!({}));
|
||||
h.run_steps(3);
|
||||
|
||||
let ctx = h.ctx.clone();
|
||||
let edited = WindowDialogs::of(&ctx, &WindowKey::main()).with(|host| {
|
||||
let part = host.get_mut::<PreferencesDialog>().and_then(|dialog| dialog.agents.as_mut()).expect("the AI Integrations page is there");
|
||||
let mut edited = part.edited();
|
||||
edited.when_app_closed = if edited.when_app_closed == WhenAppClosed::Headless { WhenAppClosed::Launch } else { WhenAppClosed::Headless };
|
||||
part.draft.set(crate::agents::PAGE, &edited);
|
||||
assert!(host.confirm::<PreferencesDialog>(&ctx), "OK closes the dialog");
|
||||
edited
|
||||
});
|
||||
h.run_steps(1);
|
||||
assert_eq!(saved.lock().unwrap().last().map(|s| s.when_app_closed), Some(edited.when_app_closed), "the edit is saved");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,8 +20,12 @@ pub const UPDATE_APP: craft::update::app::App = craft::update::app::App {
|
||||
..craft::update::suite::DECKCRAFT
|
||||
};
|
||||
|
||||
/// Agents in the open window through the ArtCraft Launcher's switch (desktop).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod agents;
|
||||
pub mod backstage;
|
||||
pub mod canvas;
|
||||
pub mod confined_files;
|
||||
pub mod control;
|
||||
pub mod dialogs;
|
||||
pub mod doc_window;
|
||||
@@ -139,6 +143,15 @@ pub struct SlideApp {
|
||||
/// Shared services also installed on the window context.
|
||||
pub(crate) host: craft::host::Host,
|
||||
control: Option<craft::automation::control::ControlChannel>,
|
||||
/// The folders the control channel's requests may read and write: the agent folders while the
|
||||
/// channel is the agents link's ([`agents`]), `None` (anywhere) for `--control`.
|
||||
control_roots: Option<std::sync::Arc<deckcraft_engine::file_access::AutomationRoots>>,
|
||||
/// The agent folders kept in force while input an agent queued is still to be handled: the
|
||||
/// commands its keys and clicks fire run in later passes ([`SlideApp::agent_scope`]).
|
||||
agent_input: Option<app::AgentInput>,
|
||||
/// The agents link while the ArtCraft Launcher's switch may let agents in ([`SlideApp::with_agents`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: Option<Box<agents::Agents>>,
|
||||
autosave: Option<craft::platform::autosave::Autosave>,
|
||||
notices: craft::ui::notices::NoticeCenter,
|
||||
palette_open: bool,
|
||||
|
||||
@@ -32,10 +32,23 @@ impl Opening {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path as compared for "the same file": resolved on disk where it exists (so `a/../deck.pptx`
|
||||
/// and a different case on Windows match), else as given.
|
||||
fn same_file_key(path: &str) -> std::path::PathBuf {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Ok(p) = std::fs::canonicalize(path) {
|
||||
return p;
|
||||
}
|
||||
std::path::PathBuf::from(path)
|
||||
}
|
||||
|
||||
impl SlideApp {
|
||||
/// Open `path` through the host's queue while showing progress.
|
||||
/// The browser opens through its host bytes immediately.
|
||||
pub fn open_path_in_background(&mut self, path: &str) {
|
||||
if self.show_if_open(path) {
|
||||
return;
|
||||
}
|
||||
if let Some(o) = &self.opening {
|
||||
let name = o.name();
|
||||
self.set_status(format!("Still opening {name}"));
|
||||
@@ -56,6 +69,21 @@ impl SlideApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// When the presentation at `path` is already open, bring it forward instead of reading the
|
||||
/// file again, as PowerPoint does: a second copy from disk would show none of the unsaved
|
||||
/// edits, which look lost (#2191). Returns whether it was open.
|
||||
pub(crate) fn show_if_open(&mut self, path: &str) -> bool {
|
||||
let wanted = same_file_key(path);
|
||||
let Some(i) = self.session.documents().iter().position(|d| d.path.as_deref().is_some_and(|p| same_file_key(p) == wanted)) else {
|
||||
return false;
|
||||
};
|
||||
self.session.set_active(i);
|
||||
let title = self.session.active().map(|d| d.title()).unwrap_or_default();
|
||||
self.note_recent(path);
|
||||
self.set_status(format!("{title} is already open"));
|
||||
true
|
||||
}
|
||||
|
||||
/// Stop waiting for the file being opened; the presentation stays as it is.
|
||||
pub fn cancel_opening(&mut self) {
|
||||
if let Some(o) = self.opening.take() {
|
||||
@@ -205,6 +233,33 @@ mod tests {
|
||||
assert_eq!(h.state().session.journal.iter().filter(|(id, _)| id == "file.adopt").count(), before_adopts + 1);
|
||||
}
|
||||
|
||||
/// #2191: opening the file that is already open shows it, unsaved edits and all, instead of
|
||||
/// a fresh copy from disk.
|
||||
#[test]
|
||||
fn opening_an_open_file_shows_it_with_its_edits() {
|
||||
let (path, bytes) = saved_as("reopen.deckcraft", 2);
|
||||
let files = Arc::new(ScriptedFiles::new().with_file(&path, bytes));
|
||||
let mut h = scripted(Session::new(), files);
|
||||
inline_jobs(&mut h);
|
||||
h.state_mut().open_path_in_background(&path);
|
||||
finish(&mut h);
|
||||
h.state_mut().run("slide.new", serde_json::json!({})).unwrap();
|
||||
h.state_mut().run("file.new", serde_json::json!({})).unwrap();
|
||||
assert_eq!(h.state().session.active_index(), Some(1));
|
||||
h.state_mut().open_path_in_background(&path);
|
||||
assert!(h.state().opening.is_none(), "nothing is read from disk");
|
||||
assert_eq!(h.state().session.documents().len(), 2, "no second copy");
|
||||
assert_eq!(h.state().session.active_index(), Some(0), "the open copy comes forward");
|
||||
let st = h.state().session.active().unwrap();
|
||||
assert!(st.is_dirty());
|
||||
assert_eq!(st.doc.slides.len(), 3, "with its unsaved slide");
|
||||
assert!(h.state().fresh_status().is_some_and(|m| m.ends_with("is already open")));
|
||||
// The synchronous path does the same.
|
||||
h.state_mut().session.set_active(1);
|
||||
h.state_mut().open_path(&path).unwrap();
|
||||
assert_eq!((h.state().session.documents().len(), h.state().session.active_index()), (2, Some(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_drops_the_result() {
|
||||
let (path, bytes) = saved_as("cancel.deckcraft", 2);
|
||||
@@ -294,7 +349,9 @@ mod tests {
|
||||
assert!(h.state_mut().open_from_system(std::slice::from_ref(&pptx)).is_empty());
|
||||
assert!(h.state().show.is_none());
|
||||
assert!(h.state_mut().open_from_system(&[ppsx.clone(), pptx.clone()]).is_empty());
|
||||
assert_eq!(h.state().session.documents().len(), 3);
|
||||
// The .pptx is already open, so it comes forward instead of opening twice (#2191).
|
||||
assert_eq!(h.state().session.documents().len(), 2);
|
||||
assert!(h.state().session.active().is_some_and(|d| d.path.as_deref() == Some(pptx.as_str())));
|
||||
assert!(h.state().show.is_none(), "the last file is a .pptx");
|
||||
}
|
||||
|
||||
|
||||
@@ -218,8 +218,6 @@ pub(crate) fn slide_menu(ui: &mut Ui, app: &mut SlideApp, key: u64, opener: &Res
|
||||
app.pane_menu = None;
|
||||
return;
|
||||
};
|
||||
let slide = &state.doc.slides[at];
|
||||
let hidden = slide.hidden;
|
||||
let layouts: Vec<_> =
|
||||
state.doc.masters.first().map(|master| master.layouts.iter().map(|layout| (layout.name.clone(), layout.id.0)).collect()).unwrap_or_default();
|
||||
let words = Env::of(ui).view().words::<ThumbWords>();
|
||||
@@ -231,7 +229,7 @@ pub(crate) fn slide_menu(ui: &mut Ui, app: &mut SlideApp, key: u64, opener: &Res
|
||||
menu = menu.anchor(anchor);
|
||||
}
|
||||
}
|
||||
let out = menu.show(ui, |ui, _| {
|
||||
let out = menu.show(ui, |ui, cx| {
|
||||
if !craft::ui::runtime::measure::active(ui.ctx())
|
||||
&& app
|
||||
.session
|
||||
@@ -258,8 +256,23 @@ pub(crate) fn slide_menu(ui: &mut Ui, app: &mut SlideApp, key: u64, opener: &Res
|
||||
let _ = MenuItem::command(CommandRef::new("slide.reset")).label(tl!("Reset Slide")).show(ui);
|
||||
let pane = CommandRef::with_params("view.pane", json!({"pane": "background"}));
|
||||
let _ = MenuItem::command(pane).label(tl!("Format Background…")).show(ui);
|
||||
let label = if hidden { words.show_slide.clone() } else { words.hide_slide.clone() };
|
||||
let _ = MenuItem::command(CommandRef::with_params("slide.hide", json!({"index": at}))).label(label).show(ui);
|
||||
// The row toggles every selected slide, as the ribbon's toggle does, so it reads "Show Slide" only when every
|
||||
// slide it targets is already hidden; a mixed selection hides. The targets are the engine's `slide.hide` ones.
|
||||
// It stays a plain item: that command's checked state follows the current slide alone, so borrowing it would
|
||||
// stamp a selection-wide row with one slide's on/off mark, against the label here.
|
||||
let all_hidden = app.session.active().is_some_and(|state| {
|
||||
let sel = &state.selection;
|
||||
let mut targets: Vec<usize> = sel.slides.iter().filter_map(|id| state.doc.slide_index(*id)).collect();
|
||||
if targets.is_empty() {
|
||||
targets.push(sel.slide);
|
||||
}
|
||||
targets.iter().all(|at| state.doc.slides.get(*at).is_some_and(|slide| slide.hidden))
|
||||
});
|
||||
let label = if all_hidden { words.show_slide.clone() } else { words.hide_slide.clone() };
|
||||
if MenuItem::new(label).show(ui).ran {
|
||||
let _ = app.run("slide.hide", json!({}));
|
||||
cx.request_close();
|
||||
}
|
||||
});
|
||||
if out.closed.is_some() && requested {
|
||||
app.pane_menu = None;
|
||||
@@ -526,6 +539,59 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The slide menu's Hide/Show row acts on every selected slide, as the ribbon's toggle does: a mixed selection
|
||||
/// hides, and one click covers the whole selection in a single undo step (deckcraft#2553).
|
||||
#[test]
|
||||
fn the_slide_menu_hides_and_shows_every_selected_slide() -> Result<(), String> {
|
||||
let words = ThumbWords::english();
|
||||
let mut h = editor(slides(4)?, 900.0);
|
||||
h.state_mut().run("slide.hide", json!({"index": 0, "hidden": true}))?;
|
||||
h.state_mut().run("slide.selectRange", json!({"from": 0, "to": 2}))?;
|
||||
h.run_steps(3);
|
||||
// A half-hidden selection offers to hide, as the engine's all-hidden toggle does.
|
||||
h.state_mut().pane_menu = Some(("thumbs".into(), 0));
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label(words.show_slide.as_str()).is_none(), "a mixed selection reads Hide Slide");
|
||||
let undo = deck(&h)?.history.undo.len();
|
||||
h.get_by_label(words.hide_slide.as_str()).click();
|
||||
h.run_steps(3);
|
||||
let flags: Vec<bool> = deck(&h)?.doc.slides.iter().map(|slide| slide.hidden).collect();
|
||||
assert_eq!(flags, [true, true, true, false], "the click hides every selected slide, not only the one it opened on");
|
||||
assert_eq!(deck(&h)?.history.undo.len(), undo + 1, "hiding a whole selection is one undo step");
|
||||
h.state_mut().pane_menu = Some(("thumbs".into(), 0));
|
||||
h.run_steps(4);
|
||||
h.get_by_label(words.show_slide.as_str()).click();
|
||||
h.run_steps(3);
|
||||
let flags: Vec<bool> = deck(&h)?.doc.slides.iter().map(|slide| slide.hidden).collect();
|
||||
assert_eq!(flags, [false, false, false, false], "a second click shows the whole selection again");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The slide menu's Hide/Show row names a selection-wide action, so it carries no on/off mark: the bare command's
|
||||
/// checked state follows only the current slide, and that would contradict the row whenever a mixed selection is
|
||||
/// led by a hidden slide.
|
||||
#[test]
|
||||
fn the_slide_menu_hide_row_carries_no_single_slide_toggle() -> Result<(), String> {
|
||||
let words = ThumbWords::english();
|
||||
let mut h = editor(slides(4)?, 900.0);
|
||||
h.state_mut().run("slide.hide", json!({"index": 0, "hidden": true}))?;
|
||||
// A backward range makes the hidden slide 0 the current one, leading a selection that is only half hidden.
|
||||
h.state_mut().run("slide.selectRange", json!({"from": 2, "to": 0}))?;
|
||||
assert_eq!(deck(&h)?.selection.slide, 0, "the range's end is the current slide");
|
||||
h.run_steps(3);
|
||||
h.state_mut().pane_menu = Some(("thumbs".into(), 0));
|
||||
h.run_steps(4);
|
||||
let row = h.get_by_label(words.hide_slide.as_str());
|
||||
assert_eq!(row.accesskit_node().toggled(), None, "a selection-wide row shows no current slide's mark");
|
||||
let undo = deck(&h)?.history.undo.len();
|
||||
row.click();
|
||||
h.run_steps(3);
|
||||
let flags: Vec<bool> = deck(&h)?.doc.slides.iter().map(|slide| slide.hidden).collect();
|
||||
assert_eq!(flags, [true, true, true, false], "the label it showed is what the click did");
|
||||
assert_eq!(deck(&h)?.history.undo.len(), undo + 1, "the whole selection flips in one undo step");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A header counts in the grid's destination, but never in the engine's slide order.
|
||||
#[test]
|
||||
fn slides_move_dest_counts_without_the_moved_slides() -> Result<(), String> {
|
||||
|
||||
+21
-16
@@ -55,6 +55,9 @@ pub struct Show {
|
||||
slide_start: f64,
|
||||
step_end: f64,
|
||||
trans: Option<Transition>,
|
||||
/// When an input cut the slide's transition short (#2084): timed advancement waits until a
|
||||
/// later pass, so the revealed slide is drawn before an elapsed After timing moves on.
|
||||
trans_cut: Option<f64>,
|
||||
remote_preview: Option<crate::presenter::Preview>,
|
||||
/// All slides thumbnails sent to the web presenter window while its grid is open (#1866).
|
||||
remote_grid: Vec<crate::presenter::Preview>,
|
||||
@@ -218,6 +221,7 @@ impl Show {
|
||||
slide_start: 0.0,
|
||||
step_end: 0.0,
|
||||
trans: None,
|
||||
trans_cut: None,
|
||||
remote_preview: None,
|
||||
remote_grid: vec![],
|
||||
remote_sent: f64::NEG_INFINITY,
|
||||
@@ -358,7 +362,8 @@ impl Show {
|
||||
let cur_step = self.state.step;
|
||||
let n_steps = self.timeline(doc).steps();
|
||||
let step_due = self.autoplay && cur_step < n_steps && idle > AUTOPLAY_DELAY;
|
||||
let holding = self.clock_navigation_held();
|
||||
// The pass whose input cut the transition short draws the revealed slide first.
|
||||
let holding = self.clock_navigation_held() || self.trans_cut.is_some_and(|cut| now <= cut);
|
||||
if !holding && (step_due || (!self.rehearse && self.state.auto_advance_due(doc, idle) && !self.ended)) {
|
||||
actions.push(self.state.next(doc));
|
||||
} else if self.preview_only && cur_step >= n_steps && idle > PREVIEW_DELAY {
|
||||
@@ -368,6 +373,19 @@ impl Show {
|
||||
true
|
||||
}
|
||||
|
||||
/// A click, a forward key, the wheel or a Next button while the slide's transition is still
|
||||
/// playing finishes the transition instead of going on, as PowerPoint does (#2084): the slide
|
||||
/// shows in full and the next animation waits for another input. Returns whether a transition
|
||||
/// was cut short.
|
||||
pub(crate) fn finish_transition(&mut self, now: f64) -> bool {
|
||||
let playing = self.trans.as_ref().is_some_and(|t| now - t.start < t.dur.max(0.01));
|
||||
if playing {
|
||||
self.trans = None;
|
||||
self.trans_cut = Some(now);
|
||||
}
|
||||
playing
|
||||
}
|
||||
|
||||
/// The clock origins used by the show, for deterministic hidden/resume regressions.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn clock_snapshot(&self) -> ClockSnapshot {
|
||||
@@ -543,21 +561,8 @@ impl Show {
|
||||
fn state_for(tl: &Timeline, id: ShapeId, step: usize, t: f64, plays: &[TriggerPlay], stamps: &[StepStamp]) -> ShapeState {
|
||||
let a = tl.state_ordered(id, None, step, t, plays, stamps);
|
||||
ShapeState {
|
||||
visible: a.visible,
|
||||
opacity: a.opacity,
|
||||
offset: deckcraft_geom::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: deckcraft_geom::Vec2::new(a.offset_x, a.offset_y) })
|
||||
})
|
||||
.collect(),
|
||||
paras: tl.paragraph_targets(id).into_iter().map(|p| (p, ParaState::from(tl.state_ordered(id, Some(p), step, t, plays, stamps)))).collect(),
|
||||
..ShapeState::from(a)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -151,6 +151,9 @@ pub(crate) fn run_command(
|
||||
if show.ended {
|
||||
keep = false;
|
||||
None
|
||||
} else if show.finish_transition(now) {
|
||||
// While the slide's transition plays, Next only finishes it (#2084).
|
||||
None
|
||||
} else {
|
||||
Some(show.state.next(doc))
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::test_harness::{harness, harness_with};
|
||||
use crate::{Services, SlideApp};
|
||||
use craft::behavior::kurbo::{Point, Size};
|
||||
use craft::behavior::{Cursor, CursorIcon, PaintedCursor};
|
||||
use deckcraft_anim::{ShowAction, ShowState};
|
||||
use deckcraft_anim::{ShowAction, ShowState, StepStamp, Timeline, TriggerPlay};
|
||||
use deckcraft_model::{Presentation, ShapeId};
|
||||
use egui::{Pos2, Rect, pos2, vec2};
|
||||
use serde_json::json;
|
||||
@@ -625,6 +625,36 @@ fn animations_start_after_the_slides_transition() {
|
||||
assert_eq!(show.clock_snapshot().step_start, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_animations_follow_the_order_their_triggers_were_clicked() {
|
||||
use deckcraft_model::{AnimClass, Animation, Shape, Slide, TextBody};
|
||||
|
||||
let text = ShapeId(1);
|
||||
let reveal = ShapeId(2);
|
||||
let hide = ShapeId(3);
|
||||
let effect = |class, trigger| Animation { shape: text, paragraph: Some(0), class, trigger: Some(trigger), ..Default::default() };
|
||||
let slide = Slide {
|
||||
shapes: vec![
|
||||
Shape { id: text, text: Some(TextBody::from_text("A paragraph")), ..Default::default() },
|
||||
Shape { id: reveal, ..Default::default() },
|
||||
Shape { id: hide, ..Default::default() },
|
||||
],
|
||||
animations: vec![effect(AnimClass::Entrance, reveal), effect(AnimClass::Exit, hide)],
|
||||
..Default::default()
|
||||
};
|
||||
let tl = Timeline::new(&slide, 960.0, 540.0);
|
||||
let visible = |plays: &[TriggerPlay], stamps: &[StepStamp]| {
|
||||
state_for(&tl, text, 0, 0.0, plays, stamps).paras.iter().find(|(paragraph, _)| *paragraph == 0).unwrap().1.visible
|
||||
};
|
||||
let plays = [reveal, hide].map(|trigger| TriggerPlay { trigger, step: 1, t: 0.0 });
|
||||
let clicked = |first, second| [StepStamp { trigger: first, step: 0, at: 1 }, StepStamp { trigger: second, step: 0, at: 2 }];
|
||||
|
||||
assert!(!visible(&[], &[]), "the paragraph waits for its entrance trigger");
|
||||
assert!(visible(&plays[..1], &[]), "the entrance trigger reveals the paragraph");
|
||||
assert!(!visible(&plays, &clicked(reveal, hide)), "the later exit hides the paragraph");
|
||||
assert!(visible(&plays, &clicked(hide, reveal)), "the later entrance reveals the paragraph again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_first_frame_does_not_use_up_the_transition() {
|
||||
// #1385: the clock started at the key press, so rendering the new slide for longer than the
|
||||
@@ -1620,3 +1650,89 @@ fn transition_preview_for_first_slide_transitions_from_black() {
|
||||
assert_eq!(tr.from, None, "slide 0 transitions from black (None)");
|
||||
assert_eq!(tr.dur, 0.5);
|
||||
}
|
||||
|
||||
/// A two-slide show whose second slide comes in with a 3 s fade, played at 0.25 s a frame.
|
||||
fn show_with_slow_fade(after_ms: Option<u32>) -> egui_kittest::Harness<'static, SlideApp> {
|
||||
let mut session = deckcraft_engine::Session::with_new();
|
||||
session.execute("slide.new", &json!({})).unwrap();
|
||||
session.execute("transition.set", &json!({"kind": "fade", "index": 1, "duration": 3000})).unwrap();
|
||||
session.execute("transition.timing", &json!({"index": 1, "after": after_ms})).unwrap();
|
||||
let id = session.active().unwrap().doc.slides[1].shapes[0].id;
|
||||
session.execute("animation.add", &json!({"effect": "fade", "class": "entrance", "ids": [id.0], "start": "onClick", "duration": 500})).unwrap();
|
||||
let mut harness =
|
||||
harness_with(session, Services::default(), egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).with_step_dt(0.25), |_| {});
|
||||
harness.state_mut().ui.presenter_view = false;
|
||||
harness.run_steps(3);
|
||||
harness.state_mut().start_show(0, false);
|
||||
harness.run_steps(2);
|
||||
harness
|
||||
}
|
||||
|
||||
/// (slide, step, playing, transition still playing) of the running show.
|
||||
fn fade_state(harness: &egui_kittest::Harness<'static, SlideApp>) -> (usize, usize, bool, bool) {
|
||||
let show = harness.state().show.as_ref().unwrap();
|
||||
(show.state.slide, show.state.step, show.state.playing, show.trans.is_some())
|
||||
}
|
||||
|
||||
/// #2084: a click, →/Space or the wheel while the slide's transition plays finishes the
|
||||
/// transition and does not start the slide's first On Click animation; the next one does.
|
||||
#[test]
|
||||
fn a_click_during_a_transition_only_finishes_it() {
|
||||
let mut harness = show_with_slow_fade(None);
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, true), "slide 2 comes in with its 3 s fade");
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, false), "→ finishes the fade, the animation waits");
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, true, false), "the next → plays the animation");
|
||||
|
||||
// A mouse click does the same.
|
||||
let mut harness = show_with_slow_fade(None);
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, true));
|
||||
let center = pos2(500.0, 350.0);
|
||||
harness.hover_at(center);
|
||||
harness.run_steps(1);
|
||||
click_at(&mut harness, center);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, false), "a click finishes the fade, the animation waits");
|
||||
click_at(&mut harness, center);
|
||||
assert_eq!(fade_state(&harness), (1, 0, true, false), "the next click plays the animation");
|
||||
|
||||
// So does a wheel notch forward.
|
||||
let mut harness = show_with_slow_fade(None);
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
harness.hover_at(center);
|
||||
harness.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: vec2(0.0, -1.0),
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
});
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, false), "the wheel finishes the fade, the animation waits");
|
||||
}
|
||||
|
||||
/// #2084: with Use Timings and an After timing shorter than the time the fade has run, the
|
||||
/// input that cuts the fade short draws the revealed slide before the timing moves on.
|
||||
#[test]
|
||||
fn finishing_a_transition_holds_an_elapsed_after_timing_for_that_pass() {
|
||||
let mut harness = show_with_slow_fade(Some(500));
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(4);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, true), "a second into the 3 s fade");
|
||||
let doc = harness.state().session.active().unwrap().doc.clone();
|
||||
let show = harness.state_mut().show.as_mut().unwrap();
|
||||
let now = show.trans.as_ref().unwrap().start + 1.0;
|
||||
assert!(show.finish_transition(now));
|
||||
let mut actions = Vec::new();
|
||||
assert!(show.queue_clock_actions(&doc, now, &mut actions));
|
||||
assert!(actions.is_empty(), "the pass that finished the fade queues no timed step: {actions:?}");
|
||||
assert!(show.queue_clock_actions(&doc, now + 0.25, &mut actions));
|
||||
assert!(!actions.is_empty(), "a later pass takes the elapsed After timing");
|
||||
}
|
||||
|
||||
@@ -71,9 +71,11 @@ impl ShowTool<'_> {
|
||||
self.under = if self.on_slide() { shapes_under_pointer(self.show, self.doc, at, now) } else { None };
|
||||
}
|
||||
|
||||
fn next(&mut self) {
|
||||
fn next(&mut self, now: f64) {
|
||||
if self.show.ended {
|
||||
self.out.keep = false;
|
||||
} else if self.show.finish_transition(now) {
|
||||
// The wheel only finishes the slide's transition while it plays (#2084).
|
||||
} else {
|
||||
self.out.actions.push(self.show.state.next(self.doc));
|
||||
}
|
||||
@@ -121,7 +123,8 @@ impl CanvasTool for ShowTool<'_> {
|
||||
let notch = f64::from(NavigationOptions::default().wheel_line);
|
||||
if let Some(next) = wheel_turn(&wheel, Some(forward), notch, TurnAxis::Stronger) {
|
||||
if next {
|
||||
self.next();
|
||||
let now = self.time(cx);
|
||||
self.next(now);
|
||||
} else {
|
||||
self.previous();
|
||||
}
|
||||
@@ -236,6 +239,8 @@ impl CanvasTool for ShowTool<'_> {
|
||||
self.out.keep = false;
|
||||
} else if self.show.blank.is_some() {
|
||||
self.show.blank = None;
|
||||
} else if self.show.finish_transition(now) {
|
||||
// The click only finishes the slide's transition (#2084).
|
||||
} else {
|
||||
let none = Under::default();
|
||||
match self.show.click_slide(self.doc, self.under.as_ref().unwrap_or(&none), now) {
|
||||
|
||||
@@ -147,7 +147,7 @@ fn canvas_pass(app: &mut SlideApp, ui: &mut Ui, bcx: &mut BodyCx<'_>, show: &mut
|
||||
// gestures keep the canvas's own page turn.
|
||||
show.wheel_taken = false;
|
||||
if !show.pen && !show.zoomed {
|
||||
wheel_lines(&ctx, show, p.doc, out);
|
||||
wheel_lines(&ctx, show, p.doc, p.now, out);
|
||||
}
|
||||
let mut media_wake = None;
|
||||
with_env(
|
||||
@@ -232,7 +232,7 @@ fn canvas_pass(app: &mut SlideApp, ui: &mut Ui, bcx: &mut BodyCx<'_>, show: &mut
|
||||
/// and free-spin wheels send fractions of a line, accumulated in `show.wheel_carry`; a change of
|
||||
/// direction drops the leftover. The line events are taken out of the frame so the canvas's own
|
||||
/// wheel navigation does not turn the page a second time.
|
||||
fn wheel_lines(ctx: &egui::Context, show: &mut Show, doc: &Presentation, out: &mut Out) {
|
||||
fn wheel_lines(ctx: &egui::Context, show: &mut Show, doc: &Presentation, now: f64, out: &mut Out) {
|
||||
// A multi-pass layout replays the frame's events; only the pass that is kept may move slides,
|
||||
// but every pass must take the lines out so the canvas does not also turn the page.
|
||||
let act = !ctx.will_discard();
|
||||
@@ -293,6 +293,10 @@ fn wheel_lines(ctx: &egui::Context, show: &mut Show, doc: &Presentation, out: &m
|
||||
continue;
|
||||
}
|
||||
let forward = by > 0;
|
||||
// A forward notch only finishes the slide's transition while it plays (#2084).
|
||||
if forward && show.finish_transition(show.clock(now)) {
|
||||
continue;
|
||||
}
|
||||
match show.state.visible_step_clamped(doc, show.state.slide, forward, count) {
|
||||
Some(target) if target != show.state.slide => out.actions.push(show.state.goto(doc, target)),
|
||||
Some(_) | None if forward => {
|
||||
|
||||
@@ -23,6 +23,16 @@ const MAX_JOURNAL: usize = 10_000;
|
||||
/// Mean wall time per frame, generous for slow CI machines (the test profile is optimized).
|
||||
const MAX_MEAN_FRAME: Duration = Duration::from_millis(250);
|
||||
|
||||
/// RSS growth allowed between the warmed-up start and the end of a soak; generous because
|
||||
/// `cargo test` threads share the process.
|
||||
const MAX_RSS_GROWTH: u64 = 256 << 20;
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
@@ -161,6 +171,7 @@ fn soak(seed: u64, steps: usize) {
|
||||
let mut log = VecDeque::new();
|
||||
let t0 = Instant::now();
|
||||
let mut frames = 0usize;
|
||||
let mut rss_start = None;
|
||||
for step in 0..steps {
|
||||
log.push_back(act(&mut h, &mut r));
|
||||
if log.len() > 20 {
|
||||
@@ -168,6 +179,11 @@ fn soak(seed: u64, steps: usize) {
|
||||
}
|
||||
h.run_steps(2);
|
||||
frames += 8;
|
||||
// Sample after a quarter of the run and its frames, so texture caches and allocator arenas
|
||||
// are warm. Short runs sample only after their first completed action.
|
||||
if step + 1 == (steps / 4).max(1) {
|
||||
rss_start = rss_bytes();
|
||||
}
|
||||
if step % 10 == 9 {
|
||||
check(&h, seed, step, &log);
|
||||
}
|
||||
@@ -184,6 +200,11 @@ fn soak(seed: u64, steps: usize) {
|
||||
let mean = t0.elapsed() / frames.max(1) as u32;
|
||||
eprintln!("ui soak seed {seed}: {steps} actions, {edits} commands, ~{frames} frames, mean frame {mean:?}");
|
||||
assert!(mean <= MAX_MEAN_FRAME, "mean frame {mean:?} over {MAX_MEAN_FRAME:?}; seed {seed}");
|
||||
if let (Some(start), Some(end)) = (rss_start, rss_bytes()) {
|
||||
let grew = end.saturating_sub(start);
|
||||
eprintln!("ui soak seed {seed}: memory {} -> {} MiB", start >> 20, end >> 20);
|
||||
assert!(grew <= MAX_RSS_GROWTH, "memory grew {} MiB over {} MiB; seed {seed}", grew >> 20, MAX_RSS_GROWTH >> 20);
|
||||
}
|
||||
}
|
||||
|
||||
fn env(name: &str, default: u64) -> u64 {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! #1926: Ctrl+= (Subscript) and Ctrl+Shift+= (Superscript) zoomed or twitched the screen instead.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use deckcraft_engine::Session;
|
||||
use deckcraft_ui_egui::{Platform, Services, SlideApp};
|
||||
use egui::{Key, Modifiers};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
struct Window(SlideApp);
|
||||
|
||||
impl eframe::App for Window {
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.0.logic(ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.0.ui(ui);
|
||||
}
|
||||
}
|
||||
|
||||
fn window(cc: &mut eframe::CreationContext<'_>, session: Session) -> Window {
|
||||
let host = craft::host::Host::builder(craft::host::AppInfo { id: "deckcraft", name: "DeckCraft", version: "0" })
|
||||
.files(Arc::new(craft::host::ScriptedFiles::new()))
|
||||
.build();
|
||||
let clipboard = craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::MemoryClipboard::default());
|
||||
let platform = Platform {
|
||||
install: craft::ui::runtime::InstallSpec::new(Default::default(), Arc::new(craft::window::system::SystemWindows))
|
||||
.app_id("deckcraft")
|
||||
.clipboard(clipboard),
|
||||
host,
|
||||
settings: craft::settings::Location::Memory,
|
||||
intake: None,
|
||||
audio_out: None,
|
||||
control: None,
|
||||
frame: craft::window::policy::Frame::Native,
|
||||
at_exit: None,
|
||||
};
|
||||
let mut app = SlideApp::new(&cc.egui_ctx, platform).unwrap_or_else(|error| panic!("window installation failed: {error}"));
|
||||
app.session = session;
|
||||
app.services = Services::default();
|
||||
Window(app)
|
||||
}
|
||||
|
||||
fn harness_of(session: Session) -> Harness<'static, Window> {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(move |cc| window(cc, session));
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn harness() -> Harness<'static, Window> {
|
||||
let mut s = Session::with_new();
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [80.0, 80.0, 320.0, 80.0], "text": "Hello"})).unwrap();
|
||||
// A selected shape, not a caret: the shortcuts then format the text that is already there.
|
||||
let _ = s.execute("text.exit", &json!({}));
|
||||
harness_of(s)
|
||||
}
|
||||
|
||||
fn baseline_of(h: &Harness<'_, Window>) -> Option<f64> {
|
||||
let st = h.state().0.session.active().unwrap();
|
||||
st.selected_shapes()
|
||||
.first()
|
||||
.and_then(|sh| sh.text.as_ref())
|
||||
.and_then(|t| t.paragraphs.first())
|
||||
.and_then(|p| p.runs.first())
|
||||
.and_then(|r| r.props.baseline)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_equals_subscripts_without_zooming() {
|
||||
let mut h = harness();
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Equals);
|
||||
h.run_steps(1);
|
||||
assert_eq!(baseline_of(&h), Some(-0.25), "status {:?}", h.state().0.status);
|
||||
assert!(!h.ctx.options(|o| o.zoom_with_keyboard), "egui's own keyboard zoom must not act on Ctrl+=");
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.0);
|
||||
assert!(h.state().0.ui.zoom.is_none(), "Ctrl+= must not zoom the slide while there is text to format");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_shift_equals_superscripts_without_zooming() {
|
||||
let mut h = harness();
|
||||
// Ctrl+Shift+= is the shifted character, so egui reports it as `Plus`.
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Plus);
|
||||
h.run_steps(1);
|
||||
assert_eq!(baseline_of(&h), Some(0.3), "status {:?}", h.state().0.status);
|
||||
assert!(!h.ctx.options(|o| o.zoom_with_keyboard), "egui's own keyboard zoom must not act on Ctrl+Shift+=");
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.0);
|
||||
assert!(h.state().0.ui.zoom.is_none(), "Ctrl+Shift+= must not zoom the slide while there is text to format");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_equals_zooms_with_nothing_to_format() {
|
||||
let mut h = harness_of(Session::with_new());
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Equals);
|
||||
h.run_steps(1);
|
||||
assert!(h.state().0.ui.zoom.is_some(), "Ctrl+= zooms in when no text or shape is selected");
|
||||
}
|
||||
@@ -60,6 +60,26 @@ comes from `anim::timeline` each frame. Animations ▸ Preview plays that same s
|
||||
canvas for the current slide, then draws the slide at rest. PDF export renders each slide at print resolution and
|
||||
overlays an invisible real-text layer with embedded font subsets.
|
||||
|
||||
### Text tab alignment and wrapping
|
||||
|
||||
Tab positions, the current cursor and the right edge share the text column's start-edge
|
||||
coordinate system. Breaking and placement use the same absolute right edge (`x0 + avail`),
|
||||
including paragraph indents and right margins. Explicit stops are sorted once and selected
|
||||
by their configured positions before any clamping.
|
||||
|
||||
Beyond the right edge, right-aligned segments end at the margin. Center and decimal stops
|
||||
also account for the segment width after their alignment point, keeping the whole segment
|
||||
inside the margin when it fits without moving backward. Stops at or inside the edge keep
|
||||
their alignment points, even when their suffix extends past the margin. Left stops beyond
|
||||
the edge also clamp to it; default stops retain their regular grid.
|
||||
|
||||
Wrapping measures the following segment up to the next tab or line break. If its visible
|
||||
text does not fit here but fits together with its tab on a fresh line, the tab moves with
|
||||
it; trailing whitespace alone cannot trigger that move. Oversized segments still use
|
||||
ordinary wrapping. The hanging-indent implicit stop applies only to LTR first lines, and
|
||||
competes with explicit stops at their effective clamped positions. Fresh-line fit checks
|
||||
never reuse that first-line-only stop.
|
||||
|
||||
## File I/O
|
||||
|
||||
- **PPTX** (`crates/pptx`): lenient reader (unknown parts skipped, malformed parts logged and
|
||||
@@ -87,6 +107,7 @@ macOS, Windows, Linux, FreeBSD and web artifacts.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-30 | minor | PR #1671 merge: center/decimal tab clamping and visible-segment wrapping retain absolute-edge coordinates, binary-search stop selection and first-line hanging-indent behavior |
|
||||
| 2026-11-12 | trivial | The `metafile` crate is gone: `render` reads EMF/WMF with craft-metafile from craft-libs |
|
||||
| 2026-11-12 | trivial | The `bitstream`, `h264`, `hevc`, `vp9` and `av1` crates are gone: `media` decodes video with craft-video from craft-libs |
|
||||
| 2026-11-11 | trivial | The `opus`, `ogg`, `isobmff` and `matroska` crates are gone: `media` uses craft-audio and craft-media from craft-libs |
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
Start the app with `--control <port>`. The server listens on `127.0.0.1` only and speaks JSON
|
||||
lines: one request object per line, one reply per line.
|
||||
|
||||
While the ArtCraft Launcher's *Settings › AI agents* switch names DeckCraft, the open window also
|
||||
serves these methods to agents, on a port it publishes in `agent-connection.json` in its settings
|
||||
folder ([MCP server](mcp.md#agents-in-the-open-window)). That server takes only the challenge
|
||||
handshake's proof or the token from the file it names, keeps the framework's own limits (1 MiB
|
||||
requests, 8 MiB replies), and runs every request with the agent folders in force: a path outside
|
||||
them is refused. A window started with `--control` serves only that channel.
|
||||
|
||||
Authenticate before sending app methods, using the server's token or its challenge-response
|
||||
handshake. Before authentication, a request line is limited to 1 MiB. Authenticated request
|
||||
lines and replies are limited to 256 MiB. Malformed JSON gets an error reply and the connection
|
||||
|
||||
+9
-4
@@ -49,7 +49,7 @@ revision history.
|
||||
- **Estimate:** 4–8 h (backend probing outside the process or a safe-mode fallback, a software
|
||||
renderer path). Needs a tester with the hardware. **Beta blocker.**
|
||||
|
||||
### Soak testing has no memory or timing budgets
|
||||
### Soak memory budgets run in CI on Linux only
|
||||
- **Evidence:** `crates/engine/src/soak_tests.rs` runs seeded random command sequences over a
|
||||
~100-slide deck (validity, selection, undo/redo exactness, bounded undo, save/reopen in both
|
||||
formats every 100 steps); `DECKCRAFT_SOAK_STEPS` runs it long. It found a chart `clamp` panic
|
||||
@@ -57,9 +57,13 @@ revision history.
|
||||
seeded random clicks, drags, keys (plain, Ctrl, Shift), typing and scrolling over the sample
|
||||
deck, checking document validity, bounded undo/journal/thumbnail/texture caches, zero caught
|
||||
command and render panics (`Session::panics_caught`, `deckcraft_render::panics_caught`) and a
|
||||
mean frame under 250 ms; 4 × 3000-action runs are clean.
|
||||
- **Impact:** long-session crash rate is sampled in CI; RSS is not measured directly.
|
||||
- **Estimate:** 1–2 h (RSS sampling per platform).
|
||||
mean frame under 250 ms; 4 × 3000-action runs are clean. Both soaks also sample resident memory
|
||||
(`memory-stats`: `/proc` on Linux, `GetProcessMemoryInfo` on Windows, Mach task info on macOS)
|
||||
after a quarter of the run and fail if it then grows by more than 256 MiB.
|
||||
- **Impact:** long-session crash rate is sampled in CI; the RSS budget is only exercised on Linux
|
||||
(`ci.yml`), and the Windows and macOS code paths have never run in CI. The engine soak has no
|
||||
wall-time budget.
|
||||
- **Estimate:** 1 h (a Windows and macOS test job; a timing budget).
|
||||
|
||||
## File formats
|
||||
|
||||
@@ -370,6 +374,7 @@ Detail in [localization-parity.md](localization-parity.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-26 | trivial | The engine and UI soaks fail if resident memory grows by more than 256 MiB after warm-up (through `memory-stats`: Linux, Windows and macOS; only Linux runs in CI) |
|
||||
| 2026-11-02 | trivial | Run alternate-language metadata now survives native and PPTX saves; UI and proofing gaps remain; scores unchanged |
|
||||
| 2026-11-02 | trivial | PPTX reflection geometry is retained through native and PPTX resaves; no rendering parity claim |
|
||||
| 2026-11-02 | trivial | Reused slide geometry and content scale to the destination; picker thumbnails remain the reuse gap |
|
||||
|
||||
+56
-21
@@ -1,14 +1,56 @@
|
||||
# MCP server
|
||||
|
||||
`deckcraft-cli mcp` runs a Model Context Protocol server on stdio. By default it drives its own
|
||||
headless engine (no window); with `--connect PORT --control-token-file PATH` it drives a running
|
||||
DeckCraft started with `--control PORT --control-token-file PATH`, so an agent and a person can
|
||||
work on the same deck. The client authenticates with the app's per-launch token. Alternatively,
|
||||
use `--control-token TOKEN`; `DECKCRAFT_CONTROL_TOKEN` and `DECKCRAFT_CONTROL_TOKEN_FILE` supply
|
||||
`deckcraft-cli mcp` runs a Model Context Protocol server on stdio. Every tool call goes to the open
|
||||
DeckCraft window while AI agents may use it, and otherwise to the server's own headless engine (no
|
||||
window). `--headless` always uses the headless engine; `--sample` opens the sample deck in it. Stdio
|
||||
request frames are limited to 16 MiB including the newline; oversized frames receive a JSON-RPC
|
||||
error and are drained so the next request can still be handled. Invalid UTF-8 frames receive a
|
||||
parse error.
|
||||
|
||||
## Agents in the open window
|
||||
|
||||
One switch serves every Craft app: *ArtCraft Launcher › Settings › AI agents*. With the suite's
|
||||
`AI-MCP` flag on, DeckCraft lets agents into its open window while that switch names it; the
|
||||
launcher also adds one `ArtCraft` entry to the MCP clients it supports, so DeckCraft writes no client
|
||||
configuration of its own.
|
||||
|
||||
- **The window** (`crates/ui-egui/src/agents.rs`, over the framework's `AgentLink`): while the
|
||||
switch allows it, DeckCraft serves its [control protocol](control-protocol.md) on `127.0.0.1`,
|
||||
with a token in its settings folder, and publishes the port in `agent-connection.json` there. It
|
||||
stops and removes the file when the switch turns off; a file a crashed run left is removed at the
|
||||
next start. Port 0 (any free port) is the default; a taken port is tried again every few seconds.
|
||||
- **The client**: plain `deckcraft-cli mcp` reads that file on every tool call (the framework's
|
||||
`Live`), checks that the process it names is still running, and makes the window prove it holds
|
||||
the token before it proves it holds it too (`auth.challenge`), so the token never crosses the
|
||||
wire. A window opened after the session started is found too, unless a call already ran without
|
||||
a window: a session that went headless stays headless, so its documents don't move under the
|
||||
agent.
|
||||
- **While DeckCraft is closed**, the choice in *Preferences › AI Integrations* applies: open
|
||||
DeckCraft and wait for it, work without a window, or answer with an error. `--when-closed
|
||||
launch|headless|error` overrides it for one session.
|
||||
- **Folders**: an agent's requests in the window open and save files only in the agent folders set
|
||||
in *Preferences › AI Integrations* (`Documents/ArtCraft/Agents/DeckCraft` when none is set). That
|
||||
covers the engine's commands, the window's own reads and writes (`app.open`, `ui.render` and
|
||||
screenshots with a `path`, Save to a presentation's own path) and the commands the keys and
|
||||
clicks an agent queues fire later. The `agent_folders` tool names the folders; a headless session
|
||||
without automation roots answers `unrestricted: true`. Agents can't change the agent settings
|
||||
(`app.agents` refuses them from a confined request).
|
||||
- With the switch off, or without the `AI-MCP` flag, nothing listens and plain `mcp` runs headless.
|
||||
A window started with `--control` serves that channel for the whole run instead, and Preferences
|
||||
says the launch options manage it. A nightly and a run with `DECKCRAFT_NO_PREFS` let no agents in.
|
||||
|
||||
The settings live in `agents.json` in the settings folder (`%APPDATA%\DeckCraft`,
|
||||
`~/Library/Application Support/DeckCraft`, `~/.config/deckcraft`), written by the app and read by
|
||||
the CLI.
|
||||
|
||||
## `--connect` (deprecated)
|
||||
|
||||
`deckcraft-cli mcp --connect PORT --control-token-file PATH` still drives a DeckCraft started with
|
||||
`--control PORT --control-token-file PATH` for one more release, and says on stderr that it is
|
||||
deprecated. The client authenticates with the app's per-launch token. Alternatively, use
|
||||
`--control-token TOKEN`; `DECKCRAFT_CONTROL_TOKEN` and `DECKCRAFT_CONTROL_TOKEN_FILE` supply
|
||||
fallbacks when their corresponding flags are absent. Headless mode does not resolve these
|
||||
credentials. `--sample` opens the sample deck. Stdio request frames are limited to 16 MiB including
|
||||
the newline; oversized frames receive a JSON-RPC error and are drained so the next request can
|
||||
still be handled. Invalid UTF-8 frames receive a parse error.
|
||||
credentials. Agent folders don't apply to it: nothing confines a `--control` window.
|
||||
|
||||
Connected mode uses the framework's `ControlClient` for reply reading and framing, with a
|
||||
256 MiB reply cap including the newline. CRLF is accepted. Unparseable or unterminated replies,
|
||||
@@ -25,14 +67,6 @@ craft-libs' `crates/automation/src/client_tests.rs`: `replies_are_matched_by_id`
|
||||
`crates/mcp/src/backend.rs` keeps `lost_reply_is_not_resent` and
|
||||
`connection_closed_before_the_call_is_retried` to guard its replay and reconnect policy.
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"deckcraft": { "command": "deckcraft-cli", "args": ["mcp", "--connect", "7990", "--control-token-file", "PATH"] }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Confining file access
|
||||
|
||||
```sh
|
||||
@@ -71,9 +105,9 @@ folders:
|
||||
to allow access to another folder; both `--flag <dir>` and `--flag=<dir>` forms work.
|
||||
|
||||
The flags confine the in-process server, so `--connect` together with them is an error: the server
|
||||
would otherwise talk to an app that isn't confined. DeckCraft's desktop app has no equivalent flags
|
||||
yet, so a running app (`deckcraft --control`) is not confined. `--sample` is the operator's own
|
||||
choice and is opened before the roots apply.
|
||||
would otherwise talk to an app that isn't confined. With them, plain `mcp` always runs headless; the
|
||||
open window keeps to its own agent folders (above). A running app started with `deckcraft --control`
|
||||
is not confined. `--sample` is the operator's own choice and is opened before the roots apply.
|
||||
|
||||
What the roots do not cover: commands that take no path still read and change the open deck, and
|
||||
`inspect_document` and `inspect_slide` return it. The system font scan and the app's own recovery
|
||||
@@ -99,8 +133,9 @@ files it was given rather than guarding against other software on the computer.
|
||||
| `add_shape`, `add_text_box`, `set_text` | Shapes and text |
|
||||
| `insert_picture`, `insert_table`, `insert_chart` | Content |
|
||||
| `select`, `pointer`, `select_tool`, `key`, `type_text` | The same selection, mouse and keyboard paths as the UI |
|
||||
| `screenshot` | The whole window, UI included (connected mode) |
|
||||
| `call_app` | Any [control protocol](control-protocol.md) method (connected mode) |
|
||||
| `screenshot` | The whole window, UI included (open window) |
|
||||
| `call_app` | Any [control protocol](control-protocol.md) method (open window) |
|
||||
| `agent_folders` | Where the app opens and saves files for agents (`read_folder`, `write_folder`) |
|
||||
|
||||
A tool refuses an argument that is not in its schema (`insert_chart: unknown argument "data" (expected: categories, h, series, title, type, w, x, y)`). Keys inside `run_command`'s `params` are that command's parameters.
|
||||
|
||||
|
||||
@@ -117,6 +117,9 @@ echo "==> assembling $APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile).
|
||||
cp "$WORK/bin/deckcraft" "$APP/Contents/MacOS/DeckCraft"
|
||||
# The CLI too, beside the app: the ArtCraft Launcher finds `deckcraft-cli` next to the app's
|
||||
# executable and registers `deckcraft-cli mcp` for agents.
|
||||
cp "$WORK/bin/deckcraft-cli" "$APP/Contents/MacOS/deckcraft-cli"
|
||||
cp "$ROOT/assets/app-icon/deckcraft.icns" "$APP/Contents/Resources/DeckCraft.icns"
|
||||
# The licences and README, as in the CLI zip, plus the licences of the embedded craft-fonts
|
||||
# fonts when built with CRAFT_FONTS_DIR. Before signing, so the seal covers them.
|
||||
@@ -128,7 +131,8 @@ plutil -lint "$APP/Contents/Info.plist"
|
||||
printf 'APPL????' >"$APP/Contents/PkgInfo"
|
||||
|
||||
# Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature).
|
||||
# Today the only nested code is the main executable; frameworks/helpers would be signed here too.
|
||||
# The bundled CLI is nested executable code; sign it before sealing the app bundle.
|
||||
sign --options runtime --identifier ai.storyteller.deckcraft-cli "$APP/Contents/MacOS/deckcraft-cli"
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/DeckCraft"
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
|
||||
codesign --verify --strict --deep --verbose=2 "$APP"
|
||||
|
||||
Reference in New Issue
Block a user