Compare commits

...
Author SHA1 Message Date
autocraft-bot[bot] 56c53986e9 Merge pull request #2490 from storytold/integration-deckcraft-20261201-7
Integration batch integration-deckcraft-20261201-7
2026-12-01 07:33:35 +00:00
autocraft-bot[bot] 399bf75642 Merge pull request #1586 2026-12-01 07:13:53 +00:00
autocraft-bot[bot] 6af018c195 Merge pull request #1570 2026-12-01 07:13:44 +00:00
autocraft-bot[bot] c88ffe5177 Merge pull request #2488 from storytold/integration-deckcraft-20261201-5
Integration batch integration-deckcraft-20261201-5
2026-12-01 07:07:57 +00:00
autocraft-bot[bot] 38a3bbc72d Merge pull request #1491 2026-12-01 06:48:00 +00:00
autocraft-bot[bot] aa00bd468a Merge pull request #1476 2026-12-01 06:47:57 +00:00
autocraft-bot[bot] a0a4fac337 Merge pull request #1468 2026-12-01 06:47:53 +00:00
autocraft-bot[bot] 333590f9ae Merge pull request #2486 from storytold/integration-deckcraft-20261201-3
Integration batch integration-deckcraft-20261201-3
2026-12-01 06:15:33 +00:00
autocraft-bot[bot] 3001fb5dc1 Merge pull request #1345 2026-12-01 05:56:23 +00:00
autocraft-bot[bot] 523df35f5e Merge pull request #2485 from storytold/integration-deckcraft-20261201-2
Integration batch integration-deckcraft-20261201-2
2026-12-01 05:22:07 +00:00
autocraft-bot[bot] 356a77a7a9 Merge pull request #1018 2026-12-01 05:01:57 +00:00
autocraft-bot[bot] 98d1f7ad94 Merge pull request #1014 2026-12-01 05:01:49 +00:00
autocraft-bot[bot] bc02000907 Merge pull request #735 2026-12-01 05:01:44 +00:00
dotCooCoo ab34c77599 Merge main into fix/font-dialog-keeps-preset-system-colors 2026-11-30 10:12:14 -08:00
autocraft-bot[bot] 90e44a619f Apply review fixes
- crates/engine/src/cmd/format/paragraph.rs
2026-11-27 12:46:37 +00:00
tydude001 500a90c77a Merge main into rpm-soname-requires
main's co-installable Nightly packages (#2350) rename the .desktop, metainfo and doc directory and
drop the mime file. The one-by-one /usr/share list now takes those names from package.sh
(${NFPM_DESK_ID}, ${NFPM_NAME}), which also drops the mime entry when none is staged, as it does
the /usr/lib tree. Packaged from v0.18.1's binaries, stable and Nightly hold the same files as
main's, .rpm and .deb; both install with rpm -U and zypper on Tumbleweed, dnf on Fedora 44 and apt on
Debian 13, without owning /usr/share/mime.
2026-11-25 08:05:27 -06:00
dotCooCoo 25dc8b9dcf Format: OK with the Font dialog's Color untouched keeps the stored color
The Font dialog's OK sent the `color` it was opened with back to
`format.fontDialog`. For a preset or system name that `color_value` does
not know, that color is the RGB it is drawn with, so OK replaced the name
even when only another field changed. A color with more than 256
transforms made OK fail with "invalid `color`", so the other edits were
not applied either.

OK now sends no `color` when the Color field is untouched, and the text
keeps its color reference as stored. An edited Color field is sent as
before.

Tests: a UI test opens the dialog on an unknown preset with 257
transforms and on an unknown system color, ticks Bold and presses OK; an
engine test sends the dialog's fields without `color` and checks that
the stored color, size and bold are kept.
2026-11-21 22:30:26 -08:00
dotCooCoo 82d8ccff8c Merge main into fix/font-dialog-keeps-preset-system-colors 2026-11-20 23:26:19 -08:00
tydude001 f41ae04700 packaging: RPM recommends libX11-xcb and libxkbcommon-x11, so the GUI starts on X11
The GUI opens libX11-xcb.so.1 and libxkbcommon-x11.so.0 at runtime on X11, and its binary also
names libwayland-egl.so.1, but nothing in the RPM asked for them. Fresh Fedora 44, Leap 15.6 and
Tumbleweed installs, with recommendations on, left libxkbcommon-x11 out. Started on X11 (Xvfb) in
Fedora 44 and Leap 15.6, GridCraft then panicked ("Library libxkbcommon-x11.so could not be
loaded"). With only libX11-xcb missing, winit fails to create its event loop
("libX11-xcb.so.1: cannot open shared object file"). All three are now recommended by soname.
libXrandr is dropped: no binary names it.
2026-11-18 07:34:53 -06:00
Zach BerryandClaude Fable 5.2 f65e481c95 Column insert: the per-row template keeps the formatting only
The template cloned the whole anchor cell, text included, once per covered
row. It is now an empty cell given the anchor's formatting. A test comment
described a default the command never had.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 20:57:38 -06:00
Zach BerryandClaude Fable 5.2 2fb8a04999 Merge main into table-insert-keeps-width
The column insert helper now reports main's cell limit: it returns false and
leaves the table alone when the new column would pass it, and the command
refuses as main's row and column inserts do. Tests from both sides are kept.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 18:12:30 -06:00
NetterSilverandClaude Haiku 5.5 0bce106403 Skip non-integer colour transform values instead of zeroing them
Found while testing crates/engine/src/cmd.rs:~425 (color_value)

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 17:24:05 +00:00
dotCooCoo 329a17a997 Merge main into fix/font-dialog-keeps-preset-system-colors 2026-11-13 11:53:41 -08:00
tydude001 8a9159a401 packaging: RPM recommends the windowing libraries by soname, so they resolve on openSUSE
The recommendations named Fedora's packages (libwayland-client, libX11, libXcursor, libXi, libXrandr),
which openSUSE calls libwayland-client0, libX11-6 and so on, so zypper skipped all five. As sonames,
like the requirements above them, they resolve on both: with recommendations on, as on a desktop
install, Tumbleweed and Leap 15.6 now select all five for the package itself, and Fedora 44 installs
the same five as before.
2026-11-12 14:52:19 -06:00
autocraft-bot[bot] 41063f36f9 Apply review fixes
- crates/engine/src/cmd/table.rs
2026-11-11 09:37:56 +00:00
autocraft-bot[bot] 1740f3e136 Merge main into table-insert-keeps-width 2026-11-11 09:16:34 +00:00
aiongg 6b2625f40f Merge main into refuse-empty-style-calls 2026-11-07 20:15:30 +00:00
aiongg 7f34fb3971 Merge main into refuse-empty-style-calls 2026-11-07 08:39:44 +00:00
tydude001 e779415cce packaging: name /usr/share's files one by one, so the RPM doesn't own /usr/share/mime
A tree of /usr/share made the RPM own /usr/share/mime and /usr/share/mime/packages at 0755, which
openSUSE's filesystem package owns at 0555: rpm -U refuses the package, and zypper installs it but
leaves the directory at 0755. This is the layout WordCraft took in storytold/wordcraft#5369.
2026-11-06 12:43:50 -06:00
tydude001 99b600081f Merge main into rpm-soname-requires 2026-11-06 11:47:59 -06:00
Harrison Booth abfc33bbb3 Merge origin/main into dc-path-map 2026-11-06 08:12:42 -06:00
Zach BerryandClaude Opus 5.5 996d67c1a6 Move the empty-shape formatting fix to its own change
It is unrelated to the connector default sites; it is now its own change on its own branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 21:55:15 -06:00
Zach BerryandClaude Opus 5.5 f0c4bd6e6f shape.connect: with one site given, the other end is the site closest to it
The facing rule is for when neither site is given; with exactly one given the other end
is the other shape's site closest to it, as it was before the default changed. Test extended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 21:53:02 -06:00
Zach BerryandClaude Opus 5.5 39d8c5d7dd shape.connect: a tie between sites goes to the lower site index
The default sites follow the direction between the shapes' centres, but an exact diagonal ties a
box's bottom with its right side (and its top with its left), and shapes with one centre tie
every site; the pick then fell to whichever site came last. A tie now goes to the lower index:
an exact diagonal connects bottom to top, and shapes with one centre both take site 0. The
spec says so. Tests for both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 21:24:32 -06:00
Zach BerryandClaude Opus 5.5 0666ef9980 Imports after upstream replaced wildcard imports (#1444)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 21:24:10 -06:00
Zach BerryandClaude Fable 5.1 6cf5280038 shape.connect takes the direction between the shapes' box centres, not the means of their sites
The mean of a shape's connection sites is off its centre when the sites
are not symmetric (a triangle's lie mostly along its base), which pulled
the dominant direction sideways and glued an arrow to a box's side when
the box was mostly below. The centres come from xfrm_of, so placeholders
and tables are measured as drawn.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-05 21:24:10 -06:00
Zach BerryandClaude Fable 5.1 ffcb3fe68a Connector default sites face the other shape; formatting set before the text survives text.set
shape.connect with no sites given picked the closest pair of sites, which for a diagonal neighbour
chose a side site and drew the arrow across the boxes. Each shape now uses the site that faces the
other along the direction between their centres (a box mostly below is left from the bottom),
which is where a person glues an arrow; the params doc says so.

format.size, format.bold, format.color on a shape that has no text yet kept nothing, so the size
vanished when set_text then landed the text. An empty body now keeps that formatting on the
paragraph's end mark and text.set keeps the first run's properties, or those, so the two work in
either order. A test for each.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-05 21:24:10 -06:00
Zach BerryandClaude Opus 5.5 c86eee0355 Insert column: resolve a covered neighbour to its anchor vertically too
A neighbour cell inside a multi-row merge sits below the anchor and carries the
vertical cover flag, so the new column's cell copied an unformatted cell. Walk
up and left to the visible anchor; the test merges two rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:33:17 -06:00
Zach BerryandClaude Opus 5.5 f0c202dca8 Insert column: copy the merge anchor's format when the neighbour is covered
A neighbour cell covered by a horizontal merge has no formatting of its own, so the inserted cell looked different from what is shown. Resolve it to the leftmost anchor before copying.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:04:32 -06:00
aiongg 555e12c1a0 Apply review fixes
- crates/engine/src/cmd/table.rs
2026-11-05 03:45:16 +00:00
Zach BerryandClaude Opus 5.5 8b6fdce1ba Move growing a merge at its edge on column insertion to its own change
The review asked for it separately: this PR keeps the neighbour's width and
cell formatting for an inserted column, and an optional keepWidth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:50:27 -06:00
Zach BerryandClaude Opus 5.5 54a9f741d6 Test: a column inserted into a table near the slide's edge
By default the table grows past the edge, as PowerPoint's Insert Right does (the frame keeps its
left); keepWidth: true keeps it on the slide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:38:50 -06:00
Zach BerryandClaude Fable 5.1 d3161f6bb8 [CCC1] table.insertColumn leaves the other column widths alone
PowerPoint inserts the new column as wide as the column it is inserted
beside and widens the table by that amount; the existing widths stay.
DeckCraft rescaled every column to keep the table width by default.
keepWidth now defaults to false (true stays as an opt-in). Deleting a
column already narrows the table by its width and leaves the rest alone;
a test pins both.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-04 19:38:50 -06:00
Zach BerryandClaude Sonnet 5.5 522f097f50 [EE1] table.insertColumn* extends a merge that spans the neighbour column
A horizontal merge covering the column the new one is inserted beside now
grows over it, also at its edge (a merged title row keeps spanning the table).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 19:38:50 -06:00
Zach BerryandClaude Fable 5.1 6d04a70cd8 The column-insertion test also checks the journal entry and that each insertion is one undo step
The test went through Session::execute but only read the table afterwards;
it now checks the last journal entry is the call as made and that three
undos bring back the three 280 pt columns, their text and the frame width.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-04 19:38:50 -06:00
Zach BerryandClaude Fable 5.1 63d1d2e588 table.insertColumn* refuses a keepWidth that is not a bool, so a mistyped value is not taken as the default
A `"keepWidth": "false"` was read as absent and the columns shrunk as if
`true` had been asked; now the command answers an error naming the field
and leaves the table alone, as the other bool params that are validated do.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-04 19:38:50 -06:00
Zach BerryandClaude Fable 5.1 76c05c1225 table.insertColumn* keeps the table's width and copies the neighbour column's cell formatting
Inserting a column grew the table by one column width, so a full-width table
ran off the slide, and the new cells came with none of the fill, bold or anchor
the neighbouring cells had. The new column now takes the width of the column it
is inserted beside and the other columns shrink in proportion, so the table keeps
its total width (`keepWidth: false` restores the growth); each new cell takes the
neighbour cell's fill, borders, margins, anchor, text direction and text
properties (kept on the empty paragraph's end mark). Rows are left alone: a table
growing by a row is normal.

Found by an AI agent building a deck through the MCP server.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-04 19:38:50 -06:00
aiongg 456cecdc58 Apply review fixes
- crates/engine/src/cmd/format/paragraph.rs
2026-11-04 20:55:50 +00:00
dotCooCoo d379334ea5 Format: the Font dialog gives an unknown preset or system name as the color it draws
A preset or system color name kept from an opened file that the color
parser does not know is given to the dialog as its drawn RGB (black for a
preset, the stored last color for a system color), so OK no longer
rejects the color when another field changes.
2026-11-04 08:04:50 -08:00
dotCooCoo c3aab3ac1e Format: a color's mods list holds at most 256 transforms
color_value reads a mods list element by element instead of cloning it,
and a list longer than MAX_COLOR_MODS (256) makes the color invalid.
2026-11-04 07:51:35 -08:00
MarekSpodBiedry ba45da9143 Merge remote-tracking branch 'origin/main' into review-1570 2026-11-04 07:51:05 +01:00
dotCooCoo 2427c60511 Format: test color mods lists with two mods, unknown ops, empty lists and keyed transforms
Adds tests for the `mods` list of a color parameter: a preset with two
transforms round-trips through the Font dialog, an unknown op makes the
color invalid and the dialog returns an error without editing, an empty
list gives the color with no transforms, and a scheme color with a keyed
lumMod and a list keeps both, the keyed one first.
2026-11-03 20:30:46 -08:00
Harrison Booth 98bc3c32a8 Merge current main into path map branch 2026-11-03 10:01:55 -06:00
Zach BerryandClaude Opus 5.5 d542b35bd4 Test: picture.adjust and format.paragraph refuse only-null calls and take one key
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:03:05 -06:00
MarekSpodBiedry 0d190bc0af Keep pasting into the notes while they are being edited (#1550) 2026-11-01 07:38:17 +01:00
MarekSpodBiedry 864820eda9 Merge remote-tracking branch 'origin/main' into review-1570 2026-11-01 07:37:33 +01:00
Zach BerryandClaude Sonnet 5.5 a121716629 [CC2] Style commands given none of their optional keys are refused
shape.line, shape.effects, picture.adjust, format.paragraph and
format.margins answered changed for a call that set nothing. They now
say what to pass. shape.fill already refused; the toggles (bold, bullets)
and geometry commands keep their meaningful defaults.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 16:19:39 -05:00
marshiyar 0540fe22cf Media: stop the Symphonia decode at the sample cap and measure the track playback decodes
A decode past MAX_PCM_SAMPLES returned an error, so an MP3 or AAC longer than about 12 minutes that played before would not play at all. It now stops at the cap with whole frames and keeps what it has, like the Opus paths. demux_duration_ms measured the first track with any codec; it now measures the track playback decodes, picked by the same playable_track.

Tests: decode_stops_at_the_sample_cap and duration_and_playback_pick_the_same_track fail without the change.
2026-10-30 22:13:52 -07:00
marshiyar 4ab850e248 Media: cap symphonia audio decode and measure unindexed audio without decoding 2026-10-30 20:26:20 -07:00
Harrison Booth 5529c695bf docs: complete module split path mappings 2026-10-30 14:32:09 -05:00
Harrison Booth d403e047cf docs: preserve optional local session context 2026-10-30 14:22:02 -05:00
Harrison Booth 5e73b015a3 Merge origin/main into dc-path-map 2026-10-30 14:15:18 -05:00
MarekSpodBiedry 93caf4d222 Paste copied shapes while a text box is being edited (#1550) 2026-10-30 16:38:51 +01:00
dotCooCoo 695edabe55 Merge main into fix/font-dialog-keeps-preset-system-colors 2026-10-28 02:59:10 -07:00
Harrison Booth 1da4e33490 docs: qualify what the old files keep, list style.rs, say where panes.rs hunks go 2026-10-27 20:53:24 -05:00
Harrison Booth 11362ac715 docs: path map for the #1433 module split; drop CLAUDE.md references to the gitignored plan/ directory 2026-10-27 19:13:21 -05:00
dotCooCoo 37ac38cac7 Format: the Font dialog keeps the order of a color's transforms
The dialog's color parameter lists transforms in order under `mods`, in
the form the model stores them, so OK keeps repeats such as [inv, inv]
and transforms that are not in alphabetical order. Color parameters
accept `mods` alongside the keyed form.
2026-10-25 13:26:55 -07:00
dotCooCoo 36bf5591c1 Format: spell color the American way in the new comments 2026-10-25 08:57:11 -07:00
dotCooCoo 4b14a96cc8 Merge commit 'refs/check/rl-deckcraft-main' into fix/font-dialog-keeps-preset-system-colors
# Conflicts:
#	crates/engine/src/cmd/mod.rs
2026-10-25 08:56:47 -07:00
dotCooCoo aa0afa1462 Format: the Font dialog's color keeps inv, comp and gray, and a color's alpha
A transform without a value (inv, comp, gray) is written as `true`, and an RGB or a system color's last value that is not opaque is written as `#RRGGBBAA`, so OK in the Font dialog keeps both.
2026-10-24 21:14:43 -07:00
dotCooCoo 78b64ed2fc Format: OK in the Font dialog keeps a preset or system text color
The Font dialog got a preset text color as its bare name, which dropped
its transforms, and a system color as its last RGB value, which dropped
the system color. Pressing OK then replaced the run's color: a preset
"red" at 50% luminance came back as plain red.

`color_command_value` now writes `{"preset": name}` and
`{"system": name, "last": "#RRGGBB"}` with the transforms, and
`color_value` reads both forms. The dialog's Color field shows the
preset's name or the system color's last value.
2026-10-24 20:22:00 -07:00
tydude001andClaude Opus 5.5 767221ca06 packaging: RPM requires library sonames, so openSUSE can install it
DeckCraft's RPM requires Fedora package names: `libxkbcommon`, `(vulkan-loader or libglvnd-egl)`,
`alsa-lib`. openSUSE has no `libxkbcommon`, `vulkan-loader` or `libglvnd-egl` package, so zypper
refuses it with `nothing provides 'libxkbcommon'` (exit 4, which the ArtCraft Launcher shows as
"error 4"; storytold/craft-launcher#341).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 12:16:18 -05:00
18 changed files with 995 additions and 86 deletions
+82 -3
View File
@@ -297,6 +297,16 @@ pub fn parse_params(doc: &str) -> std::result::Result<Vec<Param<'_>>, String> {
/// growing would duplicate ids (#407).
pub(crate) const NO_ID_SPACE: &str = "the presentation has used every object id and can hold no more";
/// A style command whose keys are all optional is refused when it is given none of them, rather
/// than answering `changed` for a call that sets nothing.
pub(crate) fn require_any(p: &Value, cmd: &str, keys: &[&str]) -> Result<()> {
if keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Ok(());
}
let (last, rest) = keys.split_last().map_or(("", &[][..]), |(l, r)| (*l, r));
Err(bad(cmd, format!("`{cmd}` was given nothing to set: pass {} or {last}", rest.join(", "))))
}
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
@@ -377,12 +387,17 @@ pub(crate) fn ok() -> Result<Value> {
/// Parse a colour param: `"#RRGGBB"`, `"accent1"`…, or `{"scheme":"accent2","lumMod":75000}`.
/// A preset or system colour keeps its base: `{"preset":"red"}`,
/// `{"system":"windowText","last":"#000000"}`.
/// `{"system":"windowText","last":"#000000"}`. `"mods"` lists transforms in order:
/// `{"preset":"red","mods":[{"op":"inv"},{"op":"inv"}]}`. A list longer than [`MAX_COLOR_MODS`]
/// makes the color invalid.
pub(crate) fn color_param(p: &Value, key: &str) -> Option<deckcraft_model::ColorRef> {
let v = p.get(key)?;
color_value(v)
}
/// Most transforms a color param's `"mods"` list may hold.
pub(crate) const MAX_COLOR_MODS: usize = 256;
pub(crate) fn color_value(v: &Value) -> Option<deckcraft_model::ColorRef> {
use deckcraft_model::ColorRef;
match v {
@@ -413,8 +428,22 @@ pub(crate) fn color_value(v: &Value) -> Option<deckcraft_model::ColorRef> {
ColorRef::rgb(deckcraft_color::Rgba::from_hex(o.get("rgb").and_then(Value::as_str)?)?)
};
for (k, val) in o {
if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, val.as_i64().and_then(|x| i32::try_from(x).ok())) {
c.mods.push(t);
let n = val.as_i64().and_then(|x| i32::try_from(x).ok());
if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, n) {
// A value-bearing transform without a usable integer is skipped, not zeroed.
if n.is_some() || t.value().is_none() {
c.mods.push(t);
}
}
}
// `mods` lists transforms in order, repeats included: `[{"op":"inv"},{"op":"lumMod","val":50000}]`.
if let Some(list) = o.get("mods") {
let list = list.as_array()?;
if list.len() > MAX_COLOR_MODS {
return None;
}
for m in list {
c.mods.push(<deckcraft_color::ColorTransform as serde::Deserialize>::deserialize(m).ok()?);
}
}
Some(c)
@@ -547,6 +576,10 @@ pub(crate) fn current_names(doc: &deckcraft_model::Presentation, sel: &crate::Se
/// A name ending in `?` is optional. Text after `→` is the result, not an input.
pub fn needs_arguments(params: &str) -> bool {
let input = params.split('→').next().unwrap_or(params);
// Every key optional, but the command refuses a call that gives none of them.
if input.contains("(at least one key)") {
return true;
}
let Some(start) = input.find('{') else { return false };
let inside = input.get(start + 1..).unwrap_or("");
let inside = inside.split('}').next().unwrap_or(inside);
@@ -743,6 +776,16 @@ mod tests {
}
}
#[test]
fn a_non_integer_colour_transform_is_skipped_not_zeroed() {
for bad in [serde_json::json!("75000"), serde_json::json!(75000.0), serde_json::json!(0.75), serde_json::json!(3_000_000_000i64)] {
let c = color_value(&serde_json::json!({"scheme": "accent1", "lumMod": bad})).unwrap();
assert!(c.mods.is_empty(), "{bad}: {:?}", c.mods);
}
let c = color_value(&serde_json::json!({"scheme": "accent1", "lumMod": 75000})).unwrap();
assert_eq!(c.mods, vec![deckcraft_color::ColorTransform::LumMod(75000)]);
}
#[test]
fn the_palette_skips_a_command_that_needs_a_value() {
assert!(needs_arguments("{path}"));
@@ -752,6 +795,7 @@ mod tests {
assert!(needs_arguments("{axis: horizontal|vertical, ids?}"));
assert!(needs_arguments("{percent}"));
assert!(!needs_arguments("{}"));
assert!(needs_arguments("{left?: pt, top?: pt} (at least one key)"));
assert!(!needs_arguments("{on?: bool}"));
assert!(!needs_arguments("{theme?: name, size?: [w,h] pt, blank?: bool}"));
assert!(!needs_arguments("{uid?: one entry, else all}"));
@@ -783,5 +827,40 @@ mod tests {
assert!(color_value(&json!({"preset": name})).is_some(), "{name}");
}
assert!(color_value(&json!({"system": "3dDkShadow", "last": "#000000"})).is_some());
let listed = color_value(&json!({"preset": "red", "mods": [{"op": "inv"}, {"op": "lumOff", "val": 20_000}, {"op": "inv"}]}));
let mods = vec![ColorTransform::Inv, ColorTransform::LumOff(20_000), ColorTransform::Inv];
assert_eq!(listed, Some(ColorRef { base: ColorBase::Preset { name: "red".into() }, mods }));
assert_eq!(color_value(&json!({"preset": "red", "mods": [{"op": "notATransform"}]})), None);
}
#[test]
fn color_mods_lists_follow_keyed_transforms() {
use deckcraft_color::{ColorTransform, SchemeSlot};
use deckcraft_model::{ColorBase, ColorRef};
use serde_json::json;
let red = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] };
assert_eq!(color_value(&json!({"preset": "red", "mods": []})), Some(red.clone()), "an empty list adds no transforms");
let two = color_value(&json!({"preset": "red", "mods": [{"op": "lumMod", "val": 75_000}, {"op": "lumOff", "val": 10_000}]}));
assert_eq!(two, Some(red.with(ColorTransform::LumMod(75_000)).with(ColorTransform::LumOff(10_000))));
// The keyed `lumMod` comes first, then the list in order.
let both =
color_value(&json!({"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}, {"op": "lumMod", "val": 50_000}]}));
let want = ColorRef::scheme(SchemeSlot::Accent2)
.with(ColorTransform::LumMod(75_000))
.with(ColorTransform::LumOff(10_000))
.with(ColorTransform::LumMod(50_000));
assert_eq!(both, Some(want));
// An unknown op anywhere in the list, or a `mods` value that is not a list, makes the color invalid.
assert_eq!(color_value(&json!({"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}, {"op": "sparkle"}]})), None);
assert_eq!(color_value(&json!({"preset": "red", "mods": {"op": "inv"}})), None);
}
#[test]
fn color_mods_lists_longer_than_the_cap_are_invalid() {
use deckcraft_color::ColorTransform;
use serde_json::json;
let at_cap = color_value(&json!({"preset": "red", "mods": vec![json!({"op": "inv"}); MAX_COLOR_MODS]}));
assert_eq!(at_cap.map(|c| c.mods), Some(vec![ColorTransform::Inv; MAX_COLOR_MODS]));
assert_eq!(color_value(&json!({"preset": "red", "mods": vec![json!({"op": "inv"}); MAX_COLOR_MODS + 1]})), None);
}
}
+3 -2
View File
@@ -335,8 +335,9 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
}
return paste_plain(s, t);
}
let editing = s.doc()?.selection.text.is_some();
if editing {
let (editing, notes) = s.doc()?.selection.text.as_ref().map_or((false, false), |t| (true, t.notes));
// Copied shapes are pasted as shapes even while a text box is being edited (the caret leaves it), but never into the notes.
if editing && (notes || s.clipboard.text.is_some() || s.clipboard.shapes.is_empty()) {
if let Some(body) = s.clipboard.text.clone() {
return super::text::paste_body(s, &body);
}
+84 -3
View File
@@ -11,7 +11,7 @@ use std::sync::Arc;
use super::text::{format_body, format_para, format_run, format_run_levels};
use super::{
CommandSpec, always, bad, base64_decode, bool_or, bool_param, cmd, color_param, edit_shapes, f64_or, f64_param, has_doc, has_text,
has_text_or_shapes, ids_param, ok, str_param,
has_text_or_shapes, ids_param, ok, require_any, str_param,
};
use crate::{Result, Session};
use deckcraft_model::ShapeId;
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paragraph…",
["Format"],
None,
"{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines}",
"{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines, lineSpacingPt?: pt} (at least one key)",
has_text_or_shapes,
paragraph
),
@@ -259,7 +259,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Box Margins",
["Format Shape", "Text Box"],
None,
"{left?: pt, top?: pt, right?: pt, bottom?: pt}",
"{left?: pt, top?: pt, right?: pt, bottom?: pt} (at least one key)",
has_text_or_shapes,
margins
),
@@ -426,6 +426,87 @@ mod tests {
assert!(r.size.is_none() && r.fill.is_none());
}
#[test]
fn font_dialog_ok_keeps_the_text_color() {
use deckcraft_color::Rgba;
let preset = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }.with(ColorTransform::LumMod(50_000));
let system = ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgb(0x12, 0x34, 0x56) }, mods: vec![] }
.with(ColorTransform::Alpha(60_000));
// A transform without a value, and a color that is not opaque.
let inverted = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }.with(ColorTransform::Inv);
let translucent = ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgba(0x12, 0x34, 0x56, 0x80) }, mods: vec![] };
let rgb = ColorRef::rgb(Rgba::rgba(0x12, 0x34, 0x56, 0x80));
// A repeated transform, and two transforms in an order that is not alphabetical.
let twice = inverted.clone().with(ColorTransform::Inv);
let ordered = ColorRef::scheme(SchemeSlot::Accent2).with(ColorTransform::LumOff(20_000)).with(ColorTransform::LumMod(50_000));
for color in [preset, system, inverted, translucent, rgb, twice, ordered] {
let mut s = shape();
let fill = Fill::Solid { color: color.clone() };
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
s.ui_requests.clear();
s.execute("format.fontDialog", &json!({})).unwrap();
let Some(UiRequest::Dialog { params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
s.execute("format.fontDialog", &json!({"color": params["color"]})).unwrap();
assert_eq!(props(&s).fill, Some(Fill::Solid { color }), "{}", params["color"]);
}
}
#[test]
fn font_dialog_ok_without_color_keeps_colors_a_command_cannot_give() {
use deckcraft_color::Rgba;
let last = Rgba::rgb(0x12, 0x34, 0x56);
let preset = ColorRef { base: ColorBase::Preset { name: "notAColor".into() }, mods: vec![] }.with(ColorTransform::LumMod(50_000));
let system = ColorRef { base: ColorBase::System { name: "notAColor".into(), last }, mods: vec![] };
// More transforms than a command's `mods` list may carry, as an opened file can hold.
let many = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![ColorTransform::Inv; crate::cmd::MAX_COLOR_MODS + 1] };
for color in [preset, system, many] {
let mut s = shape();
let fill = Fill::Solid { color: color.clone() };
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
s.ui_requests.clear();
s.execute("format.fontDialog", &json!({})).unwrap();
let Some(UiRequest::Dialog { mut params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
// OK with the Color field untouched and another field edited, as the dialog sends it.
params.as_object_mut().unwrap().remove("color");
params["size"] = json!(20.0);
params["bold"] = json!(true);
s.execute("format.fontDialog", &params).unwrap();
let r = props(&s);
assert_eq!((r.size, r.bold), (Some(20.0), Some(true)));
assert_eq!(r.fill, Some(Fill::Solid { color }));
}
}
#[test]
fn font_dialog_color_mods_round_trip_and_unknown_ops_are_errors() {
let two = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }
.with(ColorTransform::LumMod(75_000))
.with(ColorTransform::LumOff(10_000));
let mut s = shape();
let fill = Fill::Solid { color: two.clone() };
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
s.ui_requests.clear();
s.execute("format.fontDialog", &json!({})).unwrap();
let Some(UiRequest::Dialog { params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
assert_eq!(params["color"], json!({"preset": "red", "mods": [{"op": "lumMod", "val": 75_000}, {"op": "lumOff", "val": 10_000}]}));
s.execute("format.fontDialog", &json!({"color": params["color"]})).unwrap();
assert_eq!(props(&s).fill, Some(Fill::Solid { color: two.clone() }));
// An unknown op is an error, and the run keeps its color.
let n = s.doc().unwrap().history.undo.len();
let err = s.execute("format.fontDialog", &json!({"color": {"preset": "red", "mods": [{"op": "sparkle"}]}})).unwrap_err();
assert!(err.to_string().contains("color"), "{err}");
assert_eq!(s.doc().unwrap().history.undo.len(), n);
assert_eq!(props(&s).fill, Some(Fill::Solid { color: two }));
// An empty list gives the color with no transforms.
s.execute("format.fontDialog", &json!({"color": {"preset": "red", "mods": []}})).unwrap();
assert_eq!(props(&s).fill, Some(Fill::Solid { color: ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] } }));
// A scheme color with a keyed `lumMod` and a list keeps both, the keyed one first.
s.execute("format.fontDialog", &json!({"color": {"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}]}}))
.unwrap();
let scheme = ColorRef::scheme(SchemeSlot::Accent2).with(ColorTransform::LumMod(75_000)).with(ColorTransform::LumOff(10_000));
assert_eq!(props(&s).fill, Some(Fill::Solid { color: scheme }));
}
#[test]
fn font_dialog_with_no_fields_asks_the_ui_to_open() {
let mut s = shape();
+25 -9
View File
@@ -443,23 +443,39 @@ fn font_edits(p: &Value) -> Result<FontEdits> {
fn color_command_value(c: &deckcraft_model::ColorRef) -> Value {
use deckcraft_model::ColorBase;
let mut o = serde_json::Map::new();
for m in &c.mods {
if let Some(v) = m.value() {
o.insert(m.xml_name().to_string(), json!(v));
}
// An ordered list, so the order of the transforms and repeated ones such as `[inv, inv]` are kept.
if !c.mods.is_empty() {
o.insert("mods".into(), json!(c.mods));
}
match &c.base {
ColorBase::Rgb { rgb } if o.is_empty() => json!(format!("#{}", rgb.hex())),
// `#RRGGBB`, or `#RRGGBBAA` for a color that is not opaque.
let hex = |c: &deckcraft_color::Rgba| if c.a == 255 { format!("#{}", c.hex()) } else { format!("#{}{:02X}", c.hex(), c.a) };
// A preset or system name that `color_value` does not know (kept from an opened file) is given as
// the color it is drawn with, so a caller that sends this `color` back gets a valid color. The
// Font dialog sends no `color` when its Color field is untouched, so the run keeps the stored name.
let base = match &c.base {
ColorBase::Preset { name } if !deckcraft_color::is_preset_name(name) => ColorBase::Rgb { rgb: deckcraft_color::Rgba::BLACK },
ColorBase::System { name, last } if !deckcraft_color::is_system_name(name) => ColorBase::Rgb { rgb: *last },
b => b.clone(),
};
match &base {
ColorBase::Rgb { rgb } if o.is_empty() => json!(hex(rgb)),
ColorBase::Rgb { rgb } => {
o.insert("rgb".into(), json!(format!("#{}", rgb.hex())));
o.insert("rgb".into(), json!(hex(rgb)));
Value::Object(o)
}
ColorBase::Scheme { slot } => {
o.insert("scheme".into(), json!(slot.xml_name()));
Value::Object(o)
}
ColorBase::Preset { name } => json!(name),
ColorBase::System { last, .. } => json!(format!("#{}", last.hex())),
ColorBase::Preset { name } => {
o.insert("preset".into(), json!(name));
Value::Object(o)
}
ColorBase::System { name, last } => {
o.insert("system".into(), json!(name));
o.insert("last".into(), json!(hex(last)));
Value::Object(o)
}
}
}
+22 -1
View File
@@ -1,6 +1,6 @@
use super::{
Align, Anchor, AutoFit, Bullet, Result, Session, Spacing, TextDir, Value, bad, bool_or, color_param, current_para, f64_or, f64_param,
format_body, format_para, json, ok, on_param, resolve, str_param,
format_body, format_para, json, ok, on_param, require_any, resolve, str_param,
};
pub(super) fn align_to(s: &mut Session, a: Align) -> Result<Value> {
@@ -119,6 +119,26 @@ pub(super) fn line_spacing(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(super) fn paragraph(s: &mut Session, p: &Value) -> Result<Value> {
// The Paragraph dialog's other fields are format.paragraphDialog's; say so instead of
// calling the call empty.
if let Some(k) =
["special", "specialBy", "indentRight", "spaceBeforeKind", "spaceAfterKind"].into_iter().find(|k| p.get(*k).is_some_and(|v| !v.is_null()))
{
// The dialog applies a kind or `specialBy` only with the value it qualifies.
let with = match k {
"spaceBeforeKind" => " together with `spaceBefore`",
"spaceAfterKind" => " together with `spaceAfter`",
"specialBy" => " together with `special`",
_ => "",
};
return Err(bad(
"format.paragraph",
format!(
"`{k}` is a field of format.paragraphDialog (the whole Paragraph dialog); pass it there{with}. format.paragraph does not read it"
),
));
}
require_any(p, "format.paragraph", &["align", "indentLeft", "indentFirst", "spaceBefore", "spaceAfter", "lineSpacing", "lineSpacingPt"])?;
let a = str_param(p, "align").map(|a| parse_align("format.paragraph", a)).transpose()?;
let ml = f64_param(p, "indentLeft");
let ind = f64_param(p, "indentFirst");
@@ -414,6 +434,7 @@ pub(super) fn wrap(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(super) fn margins(s: &mut Session, p: &Value) -> Result<Value> {
require_any(p, "format.margins", &["left", "top", "right", "bottom"])?;
let (l, t, r, b) = (f64_param(p, "left"), f64_param(p, "top"), f64_param(p, "right"), f64_param(p, "bottom"));
format_body(s, &move |bp| {
if l.is_some() {
+5 -5
View File
@@ -10,7 +10,7 @@ use serde_json::{Value, json};
use super::{
CommandSpec, NO_ID_SPACE, bad, bool_or, bool_param, cmd, color_param, color_value, edit_geometry, edit_shapes, f64_param, has_selection,
has_slide, id_param, ok, opt_usize_param, str_param, targets, usize_param, with_param, xfrm_of,
has_slide, id_param, ok, opt_usize_param, require_any, str_param, targets, usize_param, with_param, xfrm_of,
};
use crate::{Result, Session};
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Connect Shapes",
[],
None,
"{from: shape id, to: shape id, fromSite?, toSite?: site index (default: the closest pair), id?: existing line to glue (else a new connector), preset?: straightConnector1|bentConnector3|curvedConnector3} → {id}",
"{from: shape id, to: shape id, fromSite?, toSite?: site index (default: with neither given, the sites facing each other along the dominant direction between the shapes, a tie to the lower index; with one given, the closest site of the other shape; a box has 0 top, 1 left, 2 bottom, 3 right; shape.sites lists them), id?: existing line to glue (else a new connector), preset?: straightConnector1|bentConnector3|curvedConnector3} → {id}",
has_slide,
connect
),
@@ -112,7 +112,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Shape Outline",
["Shape Format", "Shape Styles"],
None,
"{color?, none?, width?: pt, dash?: solid|dot|dash|lgDash|dashDot|sysDot|sysDash, cap?: flat|round|square, join?: round|bevel|miter, compound?: single|double|thickThin|thinThick|triple, head?: none|triangle|stealth|diamond|oval|arrow, tail?, headSize?: sm|med|lg, tailSize?, reset?, ids?}; a group also formats its members",
"{color?, none?, width?: pt, dash?: solid|dot|dash|lgDash|dashDot|sysDot|sysDash, cap?: flat|round|square, join?: round|bevel|miter, compound?: single|double|thickThin|thinThick|triple, head?: none|triangle|stealth|diamond|oval|arrow, tail?, headSize?: sm|med|lg, tailSize?, reset?, ids?} (at least one key); a group also formats its members",
has_selection,
line
),
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Shape Effects",
["Shape Format", "Shape Styles"],
None,
"{shadow?: none|outer|inner|perspective|{color, blur, dist, dir}, glow?: none|{color, radius}, softEdges?: pt, reflection?: none|tight|half|full, bevel?: none|circle|…, threeD?: {camera?: preset, rotX?, rotY?, rotZ?: deg, z?: pt, bevelTop?, bevelBottom?: none|circle|…, bevelTopW?, bevelTopH?, bevelBottomW?, bevelBottomH?, depth?, contour?: pt, material?, lighting?, reset?: true}, shadowProps?: {color?, transparency?: 0..1, size?: 0.01..2 (1 = 100%), blur?: pt, dist?: pt, dir?: deg}, glowProps?: {color?, transparency?, radius?: pt}, reflectionProps?: {transparency?, size?: 0..1, dist?: pt, blur?: pt}, reset?, ids?} (the *Props keys adjust the current effect, adding a default one when there is none)",
"{shadow?: none|outer|inner|perspective|{color, blur, dist, dir}, glow?: none|{color, radius}, softEdges?: pt, reflection?: none|tight|half|full, bevel?: none|circle|…, threeD?: {camera?: preset, rotX?, rotY?, rotZ?: deg, z?: pt, bevelTop?, bevelBottom?: none|circle|…, bevelTopW?, bevelTopH?, bevelBottomW?, bevelBottomH?, depth?, contour?: pt, material?, lighting?, reset?: true}, shadowProps?: {color?, transparency?: 0..1, size?: 0.01..2 (1 = 100%), blur?: pt, dist?: pt, dir?: deg}, glowProps?: {color?, transparency?, radius?: pt}, reflectionProps?: {transparency?, size?: 0..1, dist?: pt, blur?: pt}, reset?, ids?} (at least one key) (the *Props keys adjust the current effect, adding a default one when there is none)",
has_selection,
effects
),
@@ -169,7 +169,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Corrections",
["Picture Format", "Adjust"],
None,
"{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?}",
"{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?} (at least one key)",
has_selection,
picture_adjust
),
+11 -1
View File
@@ -1,7 +1,7 @@
use super::{
ColorRef, ColorTransform, Dash, Effects, Fill, Geom, Glow, Gradient, GradientShape, GradientStop, Line, LineEnd, PictureFill, PictureMode,
Reflection, Result, Rgba, SchemeSlot, Session, Shadow, ShapeStyle, Value, apply_fill, bad, bool_or, color_param, color_value, edit_geometry,
edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, str_param, targets,
edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, require_any, str_param, targets,
};
pub(super) fn adjust(s: &mut Session, p: &Value) -> Result<Value> {
@@ -237,6 +237,7 @@ fn line_end(v: &str) -> Option<LineEnd> {
}
pub(super) fn line(s: &mut Session, p: &Value) -> Result<Value> {
require_any(p, "shape.line", &["color", "none", "width", "dash", "cap", "join", "compound", "head", "tail", "headSize", "tailSize", "reset"])?;
let reset = bool_or(p, "reset", false);
let none = bool_or(p, "none", false);
let color = color_param(p, "color");
@@ -356,6 +357,15 @@ fn shadow_preset(v: &Value) -> Option<Option<Shadow>> {
}
pub(super) fn effects(s: &mut Session, p: &Value) -> Result<Value> {
// `glow: null` and `softEdges: null` clear those effects (No Glow, No Soft Edges), so a null
// counts as something to set for them.
if !["glow", "softEdges"].iter().any(|k| p.get(*k).is_some()) {
require_any(
p,
"shape.effects",
&["shadow", "glow", "softEdges", "reflection", "bevel", "threeD", "shadowProps", "glowProps", "reflectionProps", "reset"],
)?;
}
let reset = bool_or(p, "reset", false);
let shadow = p.get("shadow").and_then(shadow_preset);
let glow: Option<Option<Glow>> = p.get("glow").map(|g| match g {
+43 -13
View File
@@ -1,4 +1,4 @@
use super::{ColorRef, Fill, Geom, Line, NO_ID_SPACE, Result, Session, Value, bad, bool_or, id_param, json, str_param, usize_param};
use super::{ColorRef, Fill, Geom, Line, NO_ID_SPACE, Result, Session, Value, bad, bool_or, id_param, json, str_param, usize_param, xfrm_of};
pub(super) fn sites(s: &mut Session, p: &Value) -> Result<Value> {
let id = id_param(p, "id", "shape.sites")?.ok_or_else(|| bad("shape.sites", "missing `id`"))?;
@@ -24,20 +24,50 @@ pub(super) fn connect(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("shape.connect", "both shapes need connection sites (lines and groups have none)"));
}
let pick = |v: &[deckcraft_geom::Point], key: &str| usize_param(p, key).filter(|i| *i < v.len());
// A site left unsaid is the one facing the other shape along the dominant direction between
// the two (a box mostly below is left from the bottom), which is where a person glues an
// arrow; "the closest pair" chose a side site for a diagonal neighbour and crossed boxes.
// The direction runs between the shapes' box centres: the mean of the sites is off-centre
// for a shape whose sites are not symmetric (a triangle's lie mostly along its base).
// In slide space, as the sites are: a shape inside a group is placed where the group draws it.
let centre = |id| {
crate::connect::locate(&st.doc, &st.selection, st.shapes(), id)
.map(|(sh, to_abs)| to_abs * xfrm_of(&st.doc, &st.selection, sh).center())
.unwrap_or_default()
};
let (ca, cb) = (centre(from), centre(to));
// A tie goes to the lowest site index: an exact diagonal leaves a box from its bottom (site 2,
// before the right side, 3) and enters the other at its top (0, before the left side, 1), and
// shapes with one centre, where every direction is as good, both take site 0.
let facing = |v: &[deckcraft_geom::Point], c: deckcraft_geom::Point, dx: f64, dy: f64| {
let len = dx.hypot(dy).max(1e-9);
let cos: Vec<f64> = v
.iter()
.map(|q| {
let (sx, sy) = (q.x - c.x, q.y - c.y);
(sx * dx + sy * dy) / (sx.hypot(sy).max(1e-9) * len)
})
.collect();
let best = cos.iter().copied().fold(f64::NEG_INFINITY, f64::max);
cos.iter().position(|x| *x >= best - 1e-9).unwrap_or(0)
};
// With one site given, the other end is the site of the other shape closest to it, as before;
// the facing rule is for the case where neither is given.
let closest = |v: &[deckcraft_geom::Point], to: deckcraft_geom::Point| {
let mut best = (f64::MAX, 0);
for (i, q) in v.iter().enumerate() {
let d = (*q - to).hypot();
if d < best.0 {
best = (d, i);
}
}
best.1
};
let (ia, ib) = match (pick(&a, "fromSite"), pick(&b, "toSite")) {
(Some(i), Some(j)) => (i, j),
(fi, fj) => {
let mut best = (f64::MAX, 0, 0);
for (i, pa) in a.iter().enumerate().filter(|(i, _)| fi.is_none_or(|f| f == *i)) {
for (j, pb) in b.iter().enumerate().filter(|(j, _)| fj.is_none_or(|f| f == *j)) {
let d = (*pa - *pb).hypot();
if d < best.0 {
best = (d, i, j);
}
}
}
(best.1, best.2)
}
(Some(i), None) => (i, closest(&b, a[i])),
(None, Some(j)) => (closest(&a, b[j]), j),
(None, None) => (facing(&a, ca, cb.x - ca.x, cb.y - ca.y), facing(&b, cb, ca.x - cb.x, ca.y - cb.y)),
};
let (p0, p1) = (a[ia], b[ib]);
let id = match id_param(p, "id", "shape.connect")? {
+2 -1
View File
@@ -1,4 +1,4 @@
use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json};
use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json, require_any};
pub(super) fn crop(s: &mut Session, p: &Value) -> Result<Value> {
let c = [f64_param(p, "left"), f64_param(p, "top"), f64_param(p, "right"), f64_param(p, "bottom")];
@@ -15,6 +15,7 @@ pub(super) fn crop(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(super) fn picture_adjust(s: &mut Session, p: &Value) -> Result<Value> {
require_any(p, "picture.adjust", &["brightness", "contrast", "saturation", "grayscale", "transparency", "reset"])?;
edit_shapes(s, p, "picture.adjust", |sh| {
if let deckcraft_model::ShapeKind::Picture { fill } = &mut sh.kind {
let a = &mut fill.adjust;
+114 -15
View File
@@ -1,7 +1,7 @@
//! Table Design and Table Layout tabs.
use deckcraft_geom::{Affine, Point, Rect};
use deckcraft_model::{Shape, ShapeKind, Table};
use deckcraft_model::{Cell, Shape, ShapeKind, Table};
use serde_json::{Value, json};
use super::{
@@ -24,18 +24,24 @@ pub fn specs() -> Vec<CommandSpec> {
"rowBelow",
"table.insertRowBelow"
)),
cmd!("table.insertColumnLeft", "Insert Left", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols(
s,
p,
"colLeft",
"table.insertColumnLeft"
)),
cmd!("table.insertColumnRight", "Insert Right", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols(
s,
p,
"colRight",
"table.insertColumnRight"
)),
cmd!(
"table.insertColumnLeft",
"Insert Left",
["Table Layout", "Rows & Columns"],
None,
"{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside",
has_selection,
|s, p| rows_cols(s, p, "colLeft", "table.insertColumnLeft")
),
cmd!(
"table.insertColumnRight",
"Insert Right",
["Table Layout", "Rows & Columns"],
None,
"{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside",
has_selection,
|s, p| rows_cols(s, p, "colRight", "table.insertColumnRight")
),
cmd!("table.deleteRow", "Delete Rows", ["Table Layout", "Rows & Columns"], None, "{row?, id?}", has_selection, |s, p| rows_cols(
s,
p,
@@ -322,6 +328,15 @@ 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)?;
// 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")) {
(_, None) | (_, Some(Value::Null)) => false,
(_, Some(Value::Bool(b))) => *b,
("colLeft", Some(_)) => return Err(bad("table.insertColumnLeft", "`keepWidth` must be true or false")),
("colRight", Some(_)) => return Err(bad("table.insertColumnRight", "`keepWidth` must be true or false")),
_ => false,
};
let op = op.to_string();
with_table(s, p, name, move |t| {
match op.as_str() {
@@ -329,8 +344,8 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result
let ok = match op.as_str() {
"rowAbove" => t.insert_row(r),
"rowBelow" => t.insert_row(r.saturating_add(1)),
"colLeft" => t.insert_col(c),
_ => t.insert_col(c.saturating_add(1)),
"colLeft" => insert_col_like(t, c, c, keep_width),
_ => insert_col_like(t, c.saturating_add(1), c, keep_width),
};
if !ok {
return Err(bad(name, format!("the table is at its {}-cell limit", deckcraft_model::table::MAX_CELLS)));
@@ -351,6 +366,90 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result
})
}
/// Insert a column before `at` that looks like column `neighbour` (the one it is inserted beside):
/// its width, and in every row the neighbour cell's explicit formatting with no text. With
/// `keep_width` the columns then shrink in proportion so the table keeps its total width;
/// otherwise (PowerPoint's behaviour) the table grows by the new column and the widths stay.
/// Returns false, leaving the table as it was, when the column would take it past the cell limit.
fn insert_col_like(t: &mut Table, at: usize, neighbour: usize, keep_width: bool) -> bool {
let total = t.width();
let neighbour = neighbour.min(t.cols.len().saturating_sub(1));
let w = t.cols.get(neighbour).copied();
// A neighbour covered by a merge (horizontally or vertically) is formatted as its anchor, which is what shows.
let covered = |r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.h_merge || x.v_merge);
let templates: Vec<Option<Cell>> = (0..t.rows.len())
.map(|r0| {
let (mut r, mut n) = (r0, neighbour);
while covered(r, n) {
let cell = &t.rows[r].cells[n];
if cell.h_merge && n > 0 {
n -= 1;
} else if cell.v_merge && r > 0 {
r -= 1;
} else {
break;
}
}
// Only the formatting is kept: the anchor's text is not copied once per covered row.
t.rows[r].cells.get(n).map(|src| {
let mut tpl = Cell::new("");
copy_cell_format(&mut tpl, src);
tpl
})
})
.collect();
if !t.insert_col(at) {
return false;
}
let at = at.min(t.cols.len().saturating_sub(1));
if let (Some(w), Some(slot)) = (w, t.cols.get_mut(at)) {
*slot = w;
}
for (row, tpl) in t.rows.iter_mut().zip(templates) {
if let (Some(cell), Some(tpl)) = (row.cells.get_mut(at), tpl) {
copy_cell_format(cell, &tpl);
}
}
let grown = t.width();
if keep_width && total > 1e-9 && grown > 1e-9 {
let k = total / grown;
for cw in &mut t.cols {
*cw *= k;
}
}
true
}
/// `dst` takes `src`'s formatting (fill, borders, margins, anchor, text direction and the text
/// properties of its first paragraph, kept on the end mark of an empty paragraph) and keeps its
/// own spans and merge cover. Hyperlinks are not copied.
fn copy_cell_format(dst: &mut Cell, src: &Cell) {
dst.fill.clone_from(&src.fill);
dst.borders.clone_from(&src.borders);
dst.diag_down.clone_from(&src.diag_down);
dst.diag_up.clone_from(&src.diag_up);
dst.margins = src.margins;
dst.anchor = src.anchor;
dst.vertical = src.vertical;
dst.anchor_ctr = src.anchor_ctr;
dst.horz_overflow = src.horz_overflow;
let para = src.text.paragraphs.first().map(|p0| {
let mut end_props = p0.runs.first().map_or_else(|| p0.end_props.clone(), |r| r.props.clone());
end_props.link = None;
end_props.hover = None;
let mut def_props = p0.def_props.clone();
def_props.link = None;
def_props.hover = None;
deckcraft_model::text::Paragraph { level: p0.level, props: p0.props.clone(), runs: vec![], def_props, end_props }
});
let mut list_style = src.text.list_style.clone();
for l in list_style.levels.iter_mut().flatten() {
l.run.link = None;
l.run.hover = None;
}
dst.text = deckcraft_model::text::TextBody { body: src.text.body.clone(), list_style, paragraphs: vec![para.unwrap_or_default()] };
}
fn merge(s: &mut Session, p: &Value) -> Result<Value> {
let sel = s.doc()?.selection.cells;
let from = cell_param(p, "from", "table.merge")?.or(sel.map(|c| c.1)).ok_or_else(|| bad("table.merge", "missing `from`"))?;
+299
View File
@@ -668,6 +668,32 @@ fn sample_placeholders_paste_with_their_look() {
assert!(checked >= 3, "the sample has text placeholders ({checked})");
}
#[test]
fn copied_shapes_paste_as_shapes_while_a_text_box_is_being_edited() {
let mut s = session();
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [10, 10, 50, 50]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
let r = s.execute("insert.textBox", &json!({"text": "Hello"})).unwrap();
let id = r["id"].as_u64().unwrap();
s.execute("text.edit", &json!({"id": id})).unwrap();
let before = s.doc().unwrap().current_slide().unwrap().shapes.len();
s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes.len(), before + 1);
assert!(s.doc().unwrap().selection.text.is_none());
}
#[test]
fn copied_shapes_are_not_pasted_while_the_notes_are_being_edited() {
let mut s = session();
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [10, 10, 50, 50]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("text.edit", &json!({"notes": true})).unwrap();
let before = s.doc().unwrap().current_slide().unwrap().shapes.len();
s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes.len(), before);
assert!(s.doc().unwrap().selection.text.as_ref().is_some_and(|t| t.notes));
}
#[test]
fn pasted_shapes_get_the_next_automatic_name() {
let mut s = session();
@@ -7189,6 +7215,125 @@ fn invalid_slide_index_never_falls_back_to_the_selection_in_export_commands() {
let _ = std::fs::remove_dir_all(&dir);
}
/// G6: with no sites given, shape.connect joins the sites that face each other along the
/// dominant direction between the two shapes (a box mostly below leaves from the bottom), not
/// "the closest pair", which for a diagonal neighbour picked a side site and crossed boxes.
#[test]
fn connector_default_sites_follow_the_dominant_direction() {
let mut s = session();
let a = s.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 0, 100, 50]})).unwrap()["id"].as_u64().unwrap();
let diag = s.execute("shape.insert", &json!({"preset": "rect", "rect": [150, 200, 100, 50]})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("shape.connect", &json!({"from": a, "to": diag})).unwrap();
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(0)), "mostly below: bottom → top, not right → left: {r}");
let r = s.execute("shape.connect", &json!({"from": diag, "to": a})).unwrap();
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(0), Some(2)), "and back: top → bottom: {r}");
// The direction runs between the shapes' centres, not between the means of their sites: a
// triangle's sites lie mostly along its base, which pulled the direction sideways and chose
// the box's left site for a box that is mostly below.
let tri = s.execute("shape.insert", &json!({"preset": "triangle", "rect": [400, 0, 100, 100]})).unwrap()["id"].as_u64().unwrap();
let below = s.execute("shape.insert", &json!({"preset": "rect", "rect": [520, 155, 100, 50]})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("shape.connect", &json!({"from": tri, "to": below})).unwrap();
assert_eq!(r["toSite"].as_u64(), Some(0), "centre to centre is mostly down: the box's top, not its left: {r}");
// An exact diagonal ties the bottom with the right side (and the top with the left): the lower
// site index wins, so bottom → top, and top → bottom back.
let p = s.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 300, 100, 50]})).unwrap()["id"].as_u64().unwrap();
let q = s.execute("shape.insert", &json!({"preset": "rect", "rect": [200, 500, 100, 50]})).unwrap()["id"].as_u64().unwrap();
let sites = |s: &mut Session, from: u64, to: u64| {
let r = s.execute("shape.connect", &json!({"from": from, "to": to})).unwrap();
(r["fromSite"].as_u64(), r["toSite"].as_u64())
};
assert_eq!(sites(&mut s, p, q), (Some(2), Some(0)));
assert_eq!(sites(&mut s, q, p), (Some(0), Some(2)));
// Shapes with one centre tie every site: site 0 on both.
let big = s.execute("shape.insert", &json!({"preset": "rect", "rect": [600, 300, 200, 100]})).unwrap()["id"].as_u64().unwrap();
let small = s.execute("shape.insert", &json!({"preset": "rect", "rect": [650, 325, 100, 50]})).unwrap()["id"].as_u64().unwrap();
assert_eq!(sites(&mut s, big, small), (Some(0), Some(0)));
// One site given: the other end is the other shape's site closest to it, as before the facing
// rule (which is for when neither is given). From a's right side (100, 25) the diagonal box's
// top (200, 200) is nearest; to its left side (150, 225), a's bottom (50, 50).
let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "fromSite": 3})).unwrap();
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(3), Some(0)), "fromSite only: {r}");
let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "toSite": 1})).unwrap();
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(1)), "toSite only: {r}");
let r = s.execute("shape.connect", &json!({"from": a, "to": diag, "fromSite": 2, "toSite": 3})).unwrap();
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(3)), "both given: {r}");
}
#[test]
fn style_commands_given_nothing_to_set_are_refused() {
let mut s = session();
s.execute("insert.textBox", &json!({"text": "Hi", "rect": [50.0, 50.0, 200.0, 100.0]})).unwrap();
for cmd in ["shape.line", "shape.effects", "picture.adjust", "format.paragraph", "format.margins"] {
let rev = s.doc().unwrap().revision;
let e = s.execute(cmd, &json!({})).unwrap_err().to_string();
assert!(e.contains("given nothing to set") && e.contains(cmd), "{cmd}: {e}");
assert_eq!(s.doc().unwrap().revision, rev, "{cmd} changed the deck");
}
let e = s.execute("shape.line", &json!({})).unwrap_err().to_string();
assert!(e.contains("pass color, none, width, dash"), "{e}");
// A key, even one that changes nothing visible, is something to set.
s.execute("shape.line", &json!({"width": 2})).unwrap();
s.execute("format.margins", &json!({"left": 5})).unwrap();
// A null glow or soft edge clears it (No Glow, No Soft Edges): that is something to set.
let fx = |s: &Session| s.doc().unwrap().selected_shapes()[0].effects.clone().unwrap_or_default();
s.execute("shape.effects", &json!({"glow": 8, "softEdges": 5})).unwrap();
assert!(fx(&s).glow.is_some() && fx(&s).soft_edge.is_some());
s.execute("shape.effects", &json!({"glow": null})).unwrap();
assert!(fx(&s).glow.is_none() && fx(&s).soft_edge.is_some());
s.execute("shape.effects", &json!({"softEdges": null})).unwrap();
assert!(fx(&s).soft_edge.is_none());
// The Paragraph dialog's own fields are format.paragraphDialog's, and the refusal says so.
for (k, v) in [("special", json!("hanging")), ("spaceBeforeKind", json!("pct")), ("indentRight", json!(10))] {
let e = s.execute("format.paragraph", &json!({ k: v })).unwrap_err().to_string();
assert!(e.contains("format.paragraphDialog") && e.contains(k), "{k}: {e}");
}
let e = s.execute("format.paragraph", &json!({"spaceBeforeKind": "pct"})).unwrap_err().to_string();
assert!(e.contains("together with `spaceBefore`"), "{e}");
// The palette lists only commands that run without arguments; these need one key.
for cmd in ["shape.line", "shape.effects", "picture.adjust", "format.paragraph", "format.margins"] {
let spec = crate::command_specs().iter().find(|c| c.id == cmd).unwrap();
assert!(crate::cmd::needs_arguments(spec.params), "{cmd}: {}", spec.params);
}
s.execute("format.paragraphDialog", &json!({"special": "hanging", "specialBy": 18})).unwrap();
}
/// A call whose keys are all null sets nothing and is refused like an empty one, changing
/// nothing; one valid key is enough, nulls beside it ignored.
#[test]
fn style_commands_refuse_only_nulls_and_take_one_key() {
let mut png = vec![];
image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 2, image::Rgba([200, 30, 30, 255])))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let mut s = session();
let pic =
s.execute("insert.picture", &json!({"data": cmd::base64_encode(&png), "name": "a.png", "rect": [100, 100, 40, 20]})).unwrap()["id"].clone();
let text = s.execute("insert.textBox", &json!({"text": "Hi", "rect": [50, 300, 200, 100]})).unwrap()["id"].clone();
let nulls = |keys: &[&str]| serde_json::Value::Object(keys.iter().map(|k| ((*k).to_string(), serde_json::Value::Null)).collect());
for (cmd, id, keys, one) in [
(
"picture.adjust",
&pic,
&["brightness", "contrast", "saturation", "grayscale", "transparency", "reset"][..],
json!({"brightness": 0.3, "contrast": null}),
),
(
"format.paragraph",
&text,
&["align", "indentLeft", "indentFirst", "spaceBefore", "spaceAfter", "lineSpacing", "lineSpacingPt"][..],
json!({"align": "center", "spaceBefore": null}),
),
] {
s.execute("edit.select", &json!({"ids": [id]})).unwrap();
let rev = s.doc().unwrap().revision;
let e = s.execute(cmd, &nulls(keys)).unwrap_err().to_string();
assert!(e.contains("given nothing to set") && e.contains(cmd), "{cmd}: {e}");
assert_eq!(s.doc().unwrap().revision, rev, "{cmd}: only nulls changed the deck");
s.execute(cmd, &one).unwrap_or_else(|e| panic!("{cmd} {one}: {e}"));
assert_ne!(s.doc().unwrap().revision, rev, "{cmd}: one key set something");
}
}
#[test]
fn highlight_with_an_invalid_colour_is_rejected_and_keeps_the_highlight() {
let mut s = session();
@@ -7284,6 +7429,160 @@ fn master_body_placeholder_format_keeps_per_level_formatting() {
assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]);
}
/// A `keepWidth` that is not a bool is refused, naming it, and the table is left alone, not read
/// as the default (the table growing by the new column).
#[test]
fn table_insert_column_refuses_a_keep_width_that_is_not_a_bool() {
let mut s = session();
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]]));
for (cmd, bad) in [("table.insertColumnRight", json!("false")), ("table.insertColumnLeft", json!(0))] {
let err = s.execute(cmd, &json!({"id": id.0, "col": 1, "keepWidth": bad})).unwrap_err().to_string();
assert!(err.contains("keepWidth") && err.contains(cmd), "{err}");
let t = table_of(&s, id);
assert_eq!(t.n_cols(), 3, "{cmd} changed the table: {:?}", t.cols);
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
}
}
#[test]
fn table_insert_column_with_keep_width_keeps_the_table_width_and_copies_the_neighbour_format() {
let mut s = session();
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 2], [1, 2]]})).unwrap();
s.execute("table.cellMargins", &json!({"id": id.0, "left": 20, "right": 20, "top": 5, "bottom": 5, "cells": [[0, 2]]})).unwrap();
s.execute("table.cellAlign", &json!({"id": id.0, "anchor": "bottom", "cells": [[0, 2]]})).unwrap();
s.execute("edit.select", &json!({"ids": [id.0]})).unwrap();
s.execute("table.selectCells", &json!({"from": [0, 2], "to": [1, 2]})).unwrap();
s.execute("format.bold", &json!({"on": true})).unwrap();
// Right of the last column: four columns in the same 840 pt, the new one as wide as its
// neighbour, the others shrunk to make room.
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap();
let t = table_of(&s, id);
assert_eq!(t.n_cols(), 4);
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
assert!(t.cols.iter().all(|w| (w - 210.0).abs() < 1e-6), "{:?}", t.cols);
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w);
// The new cells take the neighbour's explicit formatting.
let new = t.cell(0, 3).unwrap();
assert_eq!(new.fill, Some(deckcraft_model::Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0)))));
assert_eq!(new.margins, Some([20.0, 20.0, 5.0, 5.0]));
assert_eq!(new.anchor, Some(deckcraft_model::text::Anchor::Bottom));
assert_eq!(new.text.text(), "", "the new cell is empty");
let bold = new.text.paragraphs.first().map(|p| p.end_props.bold.or(p.def_props.bold));
assert_eq!(bold, Some(Some(true)), "the neighbour's bold carries over: {:?}", new.text);
assert_eq!(t.cell(1, 3).unwrap().fill, t.cell(1, 2).unwrap().fill);
// Left of the first column: the neighbour is the old first column.
s.execute("table.insertColumnLeft", &json!({"id": id.0, "col": 0, "keepWidth": true})).unwrap();
let t = table_of(&s, id);
assert_eq!(t.n_cols(), 5);
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
assert_eq!(t.cell(0, 1).unwrap().text.text(), "a");
assert_eq!(t.cell(0, 0).unwrap().fill, None);
// keepWidth: false grows the table by the neighbour's width, as before.
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 4, "keepWidth": false})).unwrap();
let t = table_of(&s, id);
assert_eq!(t.n_cols(), 6);
assert!((t.width() - 840.0 - 168.0).abs() < 1e-6, "width {}", t.width());
// The insertion is journaled as called, and each one is a single undo step back to the table
// as it was: the columns, their widths and the frame.
let (jid, jp) = s.journal.last().cloned().unwrap();
assert_eq!(jid, "table.insertColumnRight");
assert_eq!(jp["keepWidth"], json!(false), "{jp}");
s.execute("edit.undo", &json!({})).unwrap();
let t = table_of(&s, id);
assert_eq!(t.n_cols(), 5);
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let t = table_of(&s, id);
assert_eq!(t.n_cols(), 3);
assert!(t.cols.iter().all(|w| (w - 280.0).abs() < 1e-6), "{:?}", t.cols);
assert_eq!(t.cell(0, 2).unwrap().text.text(), "c");
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w);
}
#[test]
fn table_insert_column_beside_a_merge_copies_the_anchor_format() {
let mut s = session();
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap();
s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [0, 1]})).unwrap();
// Right of the merge: the neighbour column holds the covered cell, but the anchor shows.
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap();
let t = table_of(&s, id);
assert!(t.cell(0, 1).unwrap().h_merge, "the merge stays put");
assert_eq!(t.cell(0, 2).unwrap().fill, t.cell(0, 0).unwrap().fill);
assert!(t.cell(0, 2).unwrap().fill.is_some());
}
#[test]
fn table_insert_column_beside_a_two_row_merge_copies_the_anchor_format() {
let mut s = session();
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap();
s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [1, 1]})).unwrap();
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap();
let t = table_of(&s, id);
assert!(t.cell(1, 1).unwrap().h_merge && t.cell(1, 1).unwrap().v_merge, "the merge stays put");
assert!(t.cell(0, 2).unwrap().fill.is_some());
assert_eq!(t.cell(1, 2).unwrap().fill, t.cell(0, 0).unwrap().fill);
}
/// A table near the slide's right edge, with no room for another column: by default an inserted
/// column widens it past the edge, as PowerPoint's Insert Right does (the frame keeps its left and
/// grows), and `keepWidth: true` keeps it on the slide.
#[test]
fn table_insert_column_near_the_slide_edge_grows_past_it_unless_it_keeps_its_width() {
let mut s = session();
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]]));
let slide_w = s.doc().unwrap().doc.slide_size.width;
let frame = |s: &Session| s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
let before = frame(&s);
assert!(before.x + before.w <= slide_w && before.x + before.w + 280.0 > slide_w, "another column won't fit: {before:?}");
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2})).unwrap();
assert_eq!(table_of(&s, id).n_cols(), 4);
let grown = frame(&s);
assert!((grown.x - before.x).abs() < 1e-6 && (grown.w - 1120.0).abs() < 1e-6, "{grown:?}");
assert!(grown.x + grown.w > slide_w, "past the edge");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap();
let kept = frame(&s);
assert_eq!(table_of(&s, id).n_cols(), 4);
assert!((kept.x - before.x).abs() < 1e-6 && (kept.w - before.w).abs() < 1e-6, "{kept:?}");
assert!(kept.x + kept.w <= slide_w, "still on the slide");
}
/// PowerPoint inserts a column as wide as its neighbour and widens the table by that amount; the
/// other widths stay. Deleting a column narrows the table by its width, the others untouched.
#[test]
fn table_insert_and_delete_column_leave_other_widths_alone() {
let mut s = session();
let id = table_at(&mut s, &[160.0, 234.0, 235.0, 235.0], json!([["a", "b", "c", "d"]]));
for (cmd, col, at, wide) in [("table.insertColumnRight", 0, 1, 160.0), ("table.insertColumnLeft", 3, 3, 235.0)] {
let before = table_of(&s, id).cols.clone();
let w0 = table_of(&s, id).width();
s.execute(cmd, &json!({"id": id.0, "col": col})).unwrap();
let t = table_of(&s, id);
let mut want = before.clone();
want.insert(at, wide);
assert_eq!(t.cols, want, "{cmd}");
assert!((t.width() - w0 - wide).abs() < 1e-6, "{cmd} width {}", t.width());
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
assert!((x.w - t.width()).abs() < 1e-6, "{cmd} frame {}", x.w);
}
let before = table_of(&s, id).cols.clone();
s.execute("table.deleteColumn", &json!({"id": id.0, "col": 1})).unwrap();
let t = table_of(&s, id);
let mut want = before.clone();
let gone = want.remove(1);
assert_eq!(t.cols, want);
assert!((t.width() - (before.iter().sum::<f64>() - gone)).abs() < 1e-6);
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
assert!((x.w - t.width()).abs() < 1e-6, "frame {}", x.w);
}
#[test]
fn table_edits_past_the_cell_cap_are_refused_not_trimmed() {
use deckcraft_model::table::{MAX_CELLS, Row};
+106 -11
View File
@@ -7,9 +7,9 @@
use std::io::Cursor;
use symphonia::core::audio::SampleBuffer;
use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
use symphonia::core::codecs::{CODEC_TYPE_NULL, Decoder, DecoderOptions};
use symphonia::core::errors::Error as SymError;
use symphonia::core::formats::FormatOptions;
use symphonia::core::formats::{FormatOptions, Track};
use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions};
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
@@ -172,6 +172,21 @@ fn contained<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
const MAX_DEMUX_ERRORS: u32 = 64;
fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result<Pcm> {
decode_symphonia_capped(bytes, ext, MAX_PCM_SAMPLES)
}
/// The track playback decodes, with its decoder: the first one a decoder can be made for (a
/// video's audio track follows its video track). The duration probe measures the same track.
fn playable_track(tracks: &[Track]) -> Option<(u32, Box<dyn Decoder>)> {
let codecs = symphonia::default::get_codecs();
tracks
.iter()
.filter(|t| t.codec_params.codec != CODEC_TYPE_NULL)
.find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d)))
}
/// [`decode_symphonia`] stopping once `max_samples` samples have been decoded.
fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Result<Pcm> {
let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default());
let mut hint = Hint::new();
match ext {
@@ -189,14 +204,7 @@ fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result<Pcm> {
other => sym_err(other),
})?;
let mut format = probed.format;
let codecs = symphonia::default::get_codecs();
// The first track we can decode (a video's audio track follows its video track).
let (track_id, mut decoder) = format
.tracks()
.iter()
.filter(|t| t.codec_params.codec != CODEC_TYPE_NULL)
.find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d)))
.ok_or(MediaError::Missing("audio track we can decode"))?;
let (track_id, mut decoder) = playable_track(format.tracks()).ok_or(MediaError::Missing("audio track we can decode"))?;
let mut out: Vec<f32> = Vec::new();
let mut rate = 0;
let mut channels = 0u16;
@@ -245,7 +253,15 @@ fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result<Pcm> {
}
if let Some(b) = buf.as_mut() {
b.copy_interleaved_ref(decoded);
out.extend_from_slice(b.samples());
// stop at the cap with whole frames, keeping what fits, like the Opus paths
let room = max_samples.saturating_sub(out.len());
let s = b.samples();
if s.len() > room {
let fit = room - room % (ch.max(1) as usize);
out.extend_from_slice(s.get(..fit).unwrap_or_default());
break;
}
out.extend_from_slice(s);
}
}
Err(SymError::DecodeError(e)) => log::debug!("audio decode: {e}"),
@@ -280,6 +296,48 @@ pub(crate) fn probe_symphonia(bytes: &Bytes, ext: &str) -> Option<(String, u32,
Some((name, p.sample_rate.unwrap_or(0), p.channels.map(|c| c.count() as u16).unwrap_or(0), p.n_frames))
}
/// 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.
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());
let mut hint = Hint::new();
if ext != "unknown" {
hint.with_extension(ext);
}
let opts = FormatOptions { enable_gapless: true, ..Default::default() };
let mut format = symphonia::default::get_probe().format(&hint, mss, &opts, &MetadataOptions::default()).ok()?.format;
let (id, _) = playable_track(format.tracks())?;
let tb = format.tracks().iter().find(|t| t.id == id)?.codec_params.time_base?;
let mut ticks = 0u64;
let mut errors = 0u32;
loop {
match format.next_packet() {
Ok(p) => {
errors = 0;
if p.track_id() == id {
ticks = ticks.saturating_add(p.dur);
}
}
Err(SymError::DecodeError(_)) => {
errors += 1;
if errors > MAX_DEMUX_ERRORS {
break;
}
}
Err(_) => break,
}
}
if ticks == 0 {
return None;
}
let t = tb.calc_time(ticks);
Some(t.seconds.saturating_mul(1000).saturating_add((t.frac * 1000.0).round() as u64))
}))
.ok()
.flatten()
}
/// Interleaved PCM resampled (linear) to `rate`.
pub fn resample(pcm: &Pcm, rate: u32) -> Pcm {
if pcm.rate == rate || pcm.rate == 0 || rate == 0 {
@@ -316,6 +374,43 @@ mod tests {
assert!((r.at(101, 0) - 0.505).abs() < 1e-3);
}
/// A long decode stops at the sample cap and keeps what it has, like the Opus paths, so audio
/// past the cap still plays (up to the cap) instead of failing.
#[test]
fn decode_stops_at_the_sample_cap() {
let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default());
let full = decode_symphonia_capped(&b, "aac", usize::MAX).unwrap();
let capped = decode_symphonia_capped(&b, "aac", 1001).unwrap();
assert!(full.samples.len() > 1001, "the fixture is longer than the cap");
assert!(!capped.samples.is_empty() && capped.samples.len() <= 1001, "{}", capped.samples.len());
assert_eq!(capped.samples.len() % capped.channels as usize, 0, "whole frames only");
assert_eq!(capped.samples[..], full.samples[..capped.samples.len()], "the start is kept as decoded");
}
/// The duration is measured on the track playback decodes: the first one a decoder can be made
/// for, not the first one with any codec.
#[test]
fn duration_and_playback_pick_the_same_track() {
use symphonia::core::audio::Channels;
use symphonia::core::codecs::{CODEC_TYPE_AAC, CODEC_TYPE_OPUS, CodecParameters};
let stereo = Channels::FRONT_LEFT | Channels::FRONT_RIGHT;
let mut opus = CodecParameters::new();
opus.for_codec(CODEC_TYPE_OPUS).with_sample_rate(48_000).with_channels(stereo);
let mut aac = CodecParameters::new();
aac.for_codec(CODEC_TYPE_AAC).with_sample_rate(44_100).with_channels(stereo);
let tracks = [Track::new(1, opus), Track::new(2, aac)];
// the first track has a codec but no decoder in this build (Symphonia has no Opus decoder)
assert_ne!(tracks[0].codec_params.codec, CODEC_TYPE_NULL);
assert_eq!(playable_track(&tracks).map(|(id, _)| id), Some(2));
}
#[test]
fn demux_duration_matches_decoded_length() {
let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default());
let ms = demux_duration_ms(&b, "aac").unwrap_or(0) as i64;
assert!((ms - 500).abs() <= 60, "{ms} ms");
}
#[test]
fn wma_is_reported_unsupported() {
let mut b = crate::ASF_HEADER.to_vec();
+5 -4
View File
@@ -1,5 +1,5 @@
//! Media probing: container, duration, audio and video stream parameters — without decoding
//! (except for audio files whose container doesn't state a length).
//! (audio files whose container doesn't state a length are demuxed, not decoded).
use crate::video::{codec_name, mkv_codec_name};
use crate::{ASF_HEADER, Bytes, Container, MediaError, Result};
@@ -50,9 +50,10 @@ fn ms(secs: f64) -> u64 {
pub fn probe(bytes: &Bytes) -> Result<MediaInfo> {
let mut info = probe_headers(bytes)?;
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): decode to measure.
if let Ok(pcm) = crate::audio::decode(bytes) {
info.duration_ms = ms(pcm.duration());
// 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()) {
info.duration_ms = d;
}
}
Ok(info)
+6 -7
View File
@@ -14,11 +14,13 @@ use serde_json::{Value, json};
use crate::SlideApp;
/// The colour box's text for the engine's colour value: a scheme name or an RGB string.
/// The colour box's text for the engine's colour value: a scheme, preset or system name, or an RGB string.
fn color_label(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Object(object) => object.get("scheme").or_else(|| object.get("rgb")).and_then(Value::as_str).unwrap_or("").to_owned(),
Value::Object(object) => {
["scheme", "rgb", "preset", "last"].iter().find_map(|key| object.get(*key)).and_then(Value::as_str).unwrap_or("").to_owned()
}
_ => String::new(),
}
}
@@ -158,11 +160,8 @@ pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut Dialo
Some(FieldValue::Json(value)) => value,
_ => &Value::Null,
};
if color == color_label(original) {
if !original.is_null() {
params["color"] = original.clone();
}
} else if !color.trim().is_empty() {
// An untouched Color field sends no `color`, so the text keeps its color reference as stored.
if color != color_label(original) && !color.trim().is_empty() {
params["color"] = json!(color.trim());
}
app.run("format.fontDialog", params).map(|_| ())
@@ -82,3 +82,79 @@ fn ok_keeps_a_scheme_colour_that_the_colour_box_still_shows_unchanged() {
assert_ne!(after.italic, before.italic);
assert_eq!(after.italic, Some(false));
}
#[test]
fn preset_and_system_colors_show_in_the_dialog_and_ok_keeps_them() {
for (color, shown) in [
(json!({"preset": "red", "lumMod": 50000}), "red"),
(json!({"system": "windowText", "last": "#123456", "alpha": 60000}), "#123456"),
(json!({"preset": "red", "mods": [{"op": "inv"}, {"op": "inv"}]}), "red"),
(json!({"scheme": "accent2", "mods": [{"op": "lumOff", "val": 20000}, {"op": "lumMod", "val": 50000}]}), "accent2"),
] {
let mut h = harness();
h.state_mut().session.execute("format.fontDialog", &json!({ "color": color })).unwrap();
let before = fill_of(&h);
assert!(before.is_some());
h.get_by_label("Font…").click();
h.run_steps(2);
assert_eq!(font_fields(&h)["color"], json!(shown));
let ctx = h.ctx.clone();
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.confirm", &json!({"dialog": "top"})).unwrap().unwrap();
h.run_steps(3);
assert!(!crate::dialogs::open_keys(&h.ctx).iter().any(|key| key == "font"), "status {:?}", h.state().status);
assert_eq!(fill_of(&h), before, "{shown}");
}
}
#[test]
fn ok_with_color_untouched_keeps_a_color_the_dialog_cannot_send_back() {
use deckcraft_color::{ColorTransform, Rgba};
use deckcraft_model::{ColorBase, ColorRef, Fill};
// Names that `color_value` does not know, as an opened file can hold, and more transforms than a
// command's `mods` list may carry.
let unknown_preset = ColorRef { base: ColorBase::Preset { name: "notAColor".into() }, mods: vec![ColorTransform::Inv; 257] };
let unknown_system = ColorRef { base: ColorBase::System { name: "notAColor".into(), last: Rgba::rgb(0x12, 0x34, 0x56) }, mods: vec![] };
for color in [unknown_preset, unknown_system] {
let mut h = harness();
set_fill(&mut h, Fill::Solid { color });
let before = fill_of(&h);
h.get_by_label("Font…").click();
h.run_steps(2);
assert!(crate::dialogs::open_keys(&h.ctx).iter().any(|key| key == "font"));
let ctx = h.ctx.clone();
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.set", &json!({"dialog": "top", "field": "bold", "value": true})).unwrap().unwrap();
h.run_steps(1);
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.confirm", &json!({"dialog": "top"})).unwrap().unwrap();
h.run_steps(3);
assert!(!crate::dialogs::open_keys(&h.ctx).iter().any(|key| key == "font"), "status {:?}", h.state().status);
assert_eq!(props(&h).bold, Some(true), "status {:?}", h.state().status);
assert_eq!(fill_of(&h), before);
}
}
/// The open font dialog's fields, as the control protocol reports them.
fn font_fields(h: &Harness<'_, SlideApp>) -> serde_json::Value {
crate::control::inspect(h.state(), &h.ctx)["dialogs"].as_array().unwrap().iter().find(|d| d["key"] == "font").unwrap()["fields"].clone()
}
/// Sets the first run's fill directly, so the test can hold a color that a command would reject.
fn set_fill(h: &mut Harness<'_, SlideApp>, fill: deckcraft_model::Fill) {
let st = h.state_mut().session.active_mut().unwrap();
let id = st.selection.shapes[0];
let slide = st.selection.slide;
let doc = std::sync::Arc::make_mut(&mut st.doc);
let slide = std::sync::Arc::make_mut(&mut doc.slides[slide]);
let shape = slide.shapes.iter_mut().find(|sh| sh.id == id).unwrap();
let run = shape.text.as_mut().and_then(|t| t.paragraphs.first_mut()).and_then(|p| p.runs.first_mut()).unwrap();
run.props.fill = Some(fill);
}
fn fill_of(h: &Harness<'_, SlideApp>) -> Option<deckcraft_model::Fill> {
let st = h.state().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.fill.clone())
}
+71
View File
@@ -0,0 +1,71 @@
# Where things moved in #1433
[#1433](https://github.com/storytold/deckcraft/pull/1433) (merge `ee875abf`) split the largest
source files into modules. Nothing changed in behaviour, but a branch that edits an old file now
conflicts with it. This note says which new modules received each old file's code, so you can place
your hunks by hand after `git merge origin/main`. Paths are relative to `crates/` unless noted; each
old file stays as the parent module and keeps its re-exports, so import paths are unchanged.
To find the exact new home of one function: `git grep -n 'fn name' origin/main -- crates` (or
`git log -S'fn name' --oneline origin/main -- crates`).
## Plain renames (content unchanged)
| Old | New |
|---|---|
| `engine/src/cmd/mod.rs` | `engine/src/cmd.rs` |
| `opus/src/celt/mod.rs`, `opus/src/silk/mod.rs` | `opus/src/celt.rs`, `opus/src/silk.rs` |
| `pptx/src/read/mod.rs`, `pptx/src/write/mod.rs` | `pptx/src/read.rs`, `pptx/src/write.rs` |
| `ui-egui/src/selpane.rs` | `ui-egui/src/panels/selpane.rs` |
| `ui-egui/src/backstage_tests.rs` | `ui-egui/src/backstage/tests.rs` |
| `ui-egui/src/selpane_tests.rs`, `ui-egui/src/sorter_tests.rs` | `ui-egui/src/panels/selpane/ui_tests.rs`, `ui-egui/src/sorter/ui_tests.rs` |
`ui-egui/src` files moved into a folder: `guides_tests`, `preview`, `ruler_tests`, `squiggles` →
`canvas/`; `columns_dialog_tests`, `credits`, `font_dialog_tests`, `paragraph_dialog_tests`,
`photo_album_tests`, `preferences_tests`, `size_position_tests`, `spelling_tests`,
`theme_colors_tests`, `theme_fonts_tests`, `updates_ui` → `dialogs/`; `animtimeline`,
`background_tests`, `fillui`, `notes`, `pattern_fill_tests`, `smartart_tests`, `thesaurus_tests`,
`thumbs` → `panels/`; `align_tests`, `drawtable_tests`, `effects_tests`, `icons_popup_tests`,
`inktoshape_tests`, `master_layout_tests`, `qat` → `ribbon/`.
## Split files (old file → new modules, all under the old file's folder)
Each old file keeps its module declarations and any code that was not moved; several rows move
only the tests.
| Old file | New modules |
|---|---|
| `apps/deckcraft/src/control_server.rs` | `control_server/tests.rs` (its tests) |
| `engine/src/cmd/design.rs` | `design/{colors, master_view, slide_background, slide_setup, browse_theme_tests, tests}.rs` |
| `engine/src/cmd/format.rs` | `format/{font, paragraph, painter, ruler, text_effects}.rs` |
| `engine/src/cmd/insert.rs` | `insert/{album, chart, links, picture, text_fields, icon_and_picture_tests}.rs` |
| `engine/src/cmd/shape.rs` | `shape/{appearance, freeform, picture, size}.rs` |
| `engine/src/cmd/smartart.rs` | `smartart/{diagrams, edit, layout, nodes, paint}.rs` |
| `engine/src/cmd/text.rs` | `text/{autocorrect, caret, editing, formatting, ime, layout}.rs` |
| `engine/src/tools.rs` | `tools/{click, drag, geometry, hit, pointer}.rs` |
| `fonts/src/lib.rs`, `format/src/lib.rs` | `src/tests.rs` (their tests) |
| `geom/src/preset.rs` | `preset/{build, builder, catalog, shapes, tests}.rs` |
| `media/src/player.rs` | `player/tests.rs` |
| `render/src/lib.rs` | `src/{geometry, opts, raster, renderer, slide, stroke, text_draw}.rs` |
| `text/src/lib.rs` | `src/{autonum, breaking, layout, run, shape, style, symbol}.rs` |
| `ui-egui/src/lib.rs` | `src/{app, state, services, clock, ime_hooks, tests}.rs`; the `SlideApp` impl is in `app.rs` and `app/{clipboard, commands, control, files, frame, ime, input, keys, playback}.rs` |
| `ui-egui/src/panes.rs` (deleted) | `panels.rs` and `panels/{animation, background, comments, designer, format_shape, smartart, thesaurus}.rs` (format-shape pane → `format_shape.rs`, slide background → `background.rs`, animation pane → `animation.rs`, comments and revisions → `comments.rs`) |
| `ui-egui/src/backstage.rs` | `backstage/{files, info, print}.rs` |
| `ui-egui/src/canvas.rs` | `canvas/{context_menu, guides, ime, input, media, overlays, rulers, scroll, tests}.rs` |
| `ui-egui/src/capture.rs` | `capture/tests.rs` |
| `ui-egui/src/dialogs.rs` | `dialogs/{about, alt_text, body, columns, date_time, equation, export, find, font, grid_options, hyperlink, language, paragraph, photo_album, preferences, size_position, slide_size, tabs, theme_colors, theme_fonts, trim, zoom, tests}.rs`; dialogs not listed (for example most bodies) are in `body.rs` |
| `ui-egui/src/icons.rs` | `icons/{draw, geometry}.rs` |
| `ui-egui/src/ribbon.rs` | `ribbon/{animations, arrange, chart, design, draw, galleries, home, insert, masters, picture_format, playback, review, shape_format, slide_show, smartart, table, title_bar, transitions, view}.rs`; one file per ribbon tab, plus `galleries.rs` for the shared gallery popups |
| `ui-egui/src/show.rs` | `show/{keys, media, presenter, render, ui, zoom, tests}.rs` |
Also touched: `engine/src/file_access.rs` (16 lines), `docs/file-format-parity.md`, `docs/gaps.md`
and `packaging/common.sh` (one line each, path references).
## Carrying a branch forward
1. `git merge origin/main` (never rebase) and let git list the conflicting old files.
2. For each conflicting hunk whose code moved to a listed module, apply the hunk there by hand.
Resolve hunks for code that remains in the old file there, and preserve that code.
`ui-egui/src/panes.rs` is deleted: do not restore it, move its hunks into `panels.rs` or the
listed `panels/` modules (the crate exposes `panels` and aliases it as `panes`).
3. Run `cargo xtask ci`.
+34 -10
View File
@@ -44,16 +44,27 @@ overrides:
- mesa-vulkan-drivers
- xdg-desktop-portal
rpm:
# Library sonames rather than package names, so the same requirements resolve on Fedora/RHEL
# and openSUSE (which has no libxkbcommon, vulkan-loader or libglvnd-egl package). The glibc
# floor names libm because the binaries' GLIBC_2.35 symbols (hypot, hypotf) are libm's: RHEL 9's
# glibc 2.34 provides libc.so.6(GLIBC_2.35) through backports, but not this, so it refuses.
depends:
- libxkbcommon
- alsa-lib
- (vulkan-loader or libglvnd-egl)
- libc.so.6()(64bit)
- libm.so.6(GLIBC_2.35)(64bit)
- libgcc_s.so.1()(64bit)
- libxkbcommon.so.0()(64bit)
- (libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))
- libasound.so.2()(64bit)
# The windowing libraries the GUI loads at runtime, by soname too, so the recommendations resolve on
# openSUSE as well. Without libX11-xcb and libxkbcommon-x11 the GUI cannot start on X11.
recommends:
- libwayland-client
- libX11
- libXcursor
- libXi
- libXrandr
- libwayland-client.so.0()(64bit)
- libX11.so.6()(64bit)
- libXcursor.so.1()(64bit)
- libXi.so.6()(64bit)
- libX11-xcb.so.1()(64bit)
- libxkbcommon-x11.so.0()(64bit)
- libwayland-egl.so.1()(64bit)
- mesa-vulkan-drivers
- xdg-desktop-portal
@@ -64,11 +75,24 @@ contents:
- src: ${STAGE}/usr/bin/${NFPM_CLI}
dst: /usr/bin/${NFPM_CLI}
file_info: { mode: 0755 }
# Named one by one rather than as a tree of /usr/share: a tree would also own shared directories
# such as /usr/share/mime, which openSUSE's filesystem package owns with other modes, and RPM
# refuses to install a package that conflicts with it. ${NFPM_DESK_ID} and ${NFPM_NAME} are filled
# in by package.sh (a Nightly renames them), which also drops the mime entry when none is staged.
- src: ${STAGE}/usr/share/applications/${NFPM_DESK_ID}.desktop
dst: /usr/share/applications/${NFPM_DESK_ID}.desktop
- src: ${STAGE}/usr/share/mime/packages/ai.storyteller.deckcraft.xml
dst: /usr/share/mime/packages/ai.storyteller.deckcraft.xml
- src: ${STAGE}/usr/share/metainfo/${NFPM_DESK_ID}.metainfo.xml
dst: /usr/share/metainfo/${NFPM_DESK_ID}.metainfo.xml
- src: ${STAGE}/usr/share/icons/hicolor/
dst: /usr/share/icons/hicolor/
type: tree
- src: ${STAGE}/usr/lib/
dst: /usr/lib/
type: tree
- src: ${STAGE}/usr/share/
dst: /usr/share/
- src: ${STAGE}/usr/share/doc/${NFPM_NAME}/
dst: /usr/share/doc/${NFPM_NAME}/
type: tree
scripts:
+7 -1
View File
@@ -151,6 +151,7 @@ if has deb || has rpm; then
export NFPM_NAME="deckcraft"
export NFPM_BIN="deckcraft"
export NFPM_CLI="deckcraft-cli"
NFPM_DESK_ID="$APP_ID"
if [[ "$IS_NIGHTLY" = 1 ]]; then
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
NIGHTLY_ICON="$ROOT/assets/app-icon/deckcraft-nightly.png"
@@ -158,6 +159,7 @@ if has deb || has rpm; then
export NFPM_NAME="deckcraft-nightly"
export NFPM_BIN="deckcraft-nightly"
export NFPM_CLI="deckcraft-nightly-cli"
NFPM_DESK_ID="$NIGHTLY_DESK_ID"
NFPM_STAGE="$WORK/nfpm-root"
rm -rf "$NFPM_STAGE"
cp -R "$STAGE" "$NFPM_STAGE"
@@ -192,8 +194,12 @@ if has deb || has rpm; then
DROP_LIB_TREE=
# shellcheck disable=SC2016
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
# nfpm refuses a named file that isn't staged, and a Nightly stages no mime file.
DROP_MIME=
# shellcheck disable=SC2016
sed "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
[[ -d "$NFPM_STAGE/usr/share/mime" ]] || DROP_MIME='\|^ - src: \${STAGE}/usr/share/mime/|,+1d;'
# shellcheck disable=SC2016
sed "${DROP_LIB_TREE}${DROP_MIME}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g;s|\${NFPM_DESK_ID}|$NFPM_DESK_ID|g;s|\${NFPM_NAME}|$NFPM_NAME|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
for fmt in deb rpm; do
if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi
done