Compare commits

...
Author SHA1 Message Date
Dylan M. Taylor f8d80dea14 media: use contains() instead of iter().any() in mp4guard 2026-11-18 19:29:01 -05:00
autocraft-bot[bot] e9b36f2f0a Apply review fixes
- crates/media/src/mp4guard.rs
2026-11-18 22:05:19 +00:00
Dylan M. Taylor eccff7a177 media: cut over mp4guard box-tree bounds validation to craft-media 2026-11-18 16:46:34 -05:00
FredApps 5e36a3552e Merge pull request #1938 from scks1/fix/placed-group-text
render: text in scaled groups is placed where it is drawn
2026-11-18 17:37:57 +07:00
FredApps d83ac52f0f Merge main into this branch
Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-18 17:16:31 +07:00
FredApps f15db38adb Merge pull request #2026 from Naseq/fix-2025-empty-notes-slide
PPTX: preserve empty notes slides on save and reopen (#2025)
2026-11-18 17:11:49 +07:00
FredApps aa406ac091 Merge main into this branch
Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-18 16:39:37 +07:00
FredApps 19fa1dd94b Merge pull request #2071 from Hamza0101/fix/line-chart-value-labels
Charts: line series draw their value labels (#2066)
2026-11-18 16:31:22 +07:00
FredApps d1b327e98e Merge pull request #2020 from jgriggs-sluh/feat/export-all-slides-pictures
Export: every slide as PNG or JPEG from File › Export › Change File Type and Save As
2026-11-18 16:31:07 +07:00
FredApps d159b890d7 Merge pull request #1989 from yonatan-langer83/prefs-slider-label
Preferences: the Interface size slider is labelled again
2026-11-18 16:30:53 +07:00
FredApps dfe012713a Merge pull request #1970 from Naseq/fix-1922-canvas-clip-notes
Canvas: clip the canvas Ui to its own rect so nothing it paints or hit-tests reaches the notes pane (#1922)
2026-11-18 16:30:39 +07:00
FredApps e2ca2c41b9 Merge pull request #1942 from neilcawse/fix/pptx-media-timing-nodes
pptx: round-trip p:video and p:audio media timing nodes and autoplay conditions
2026-11-18 16:30:01 +07:00
VladimirCericandaiongg e419262c4c Review › Language: Serbian in Cyrillic and Latin, each with its own dictionary (#1619)
The Language list offers Serbian (Cyrillic) sr-Cyrl-RS and Serbian (Latin) sr-Latn-RS. A dictionary is used only for text in its own script (LibreOffice's sr and sr-Latn, Hunspell's sr_RS and sr_Latn_RS, Fedora's sr_RS@latin), Serbian dictionaries are tried before the Serbo-Croatian sh alias, and only Latin and Cyrillic subtags or modifiers are read as a dictionary's script.

Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com>
2026-11-18 16:29:25 +07:00
FredApps 9a8e8227ff Merge pull request #791 from Hamza0101/fix/font-script-typefaces
format.font: set the East Asian and complex-script typefaces too
2026-11-18 16:28:54 +07:00
autocraft-bot[bot] 4aec38a2bc Merge pull request #942 from Hamza0101/fix/hf-date-format-on-read
Header & Footer: an automatic date's format comes back on import
2026-11-18 03:37:26 +00:00
autocraft-bot[bot] 49447f46a7 Merge pull request #2083 from ljkx/render-text-effects-from-defrpr
render: text effects from a paragraph's defRPr or the default text style need filters
2026-11-18 03:28:09 +00:00
Neil Cawse c8dd6695a7 Merge remote-tracking branch 'upstream/main' into fix/pptx-media-timing-nodes 2026-11-18 03:22:30 +00:00
autocraft-bot[bot] 2ba369f5d8 Apply review fixes
- crates/ui-egui/src/dialogs/tests.rs
2026-11-18 03:20:42 +00:00
Dylan M. Taylor e0f7fc8c38 Merge pull request #2201 from storytold/refactor/shared-table-style-writer
Use shared DrawingML table style XML writer
2026-11-17 12:11:29 -05:00
Dylan M. Taylor 2c135484c1 Drop unused test-oracle GUID reexports 2026-11-17 11:50:07 -05:00
Dylan M. Taylor 352b1ee170 Pin table-style writer to merged shared implementation 2026-11-17 11:31:14 -05:00
Dylan M. Taylor 82fddc8ffd Use shared DrawingML table style XML writer
Preserve the former writer as a test-only byte oracle, including the original Brandon Thomas and Nikita Rakitin implementation history. Keep app XML admission and all existing table tests unchanged.
2026-11-17 08:37:55 -05:00
Dylan M. Taylor 1629e4d953 Tables: cap the grid and merge area before edits allocate or walk them (#1742) 2026-11-17 08:13:56 -05:00
Neil Cawse 40ce901c2c Merge remote-tracking branch 'upstream/main' into fix/pptx-media-timing-nodes 2026-11-17 12:49:14 +00:00
Luis 497582406d Gradient stops: double-clicking a stop opens its colour menu (#2175) (#2196)
Double-clicking a stop marker in the Format pane's gradient editor did nothing. It now selects the stop and opens the colour menu of the selected stop, as in PowerPoint. The menu button is also named for screen readers.
2026-11-17 08:36:53 +00:00
Luis e1ca71495c Slide show: a slide's animations wait for its transition (#2089) (#2197)
A first step that starts With or After Previous began with the slide, so its effects played under the transition. Its clock now starts when the transition has finished, as in PowerPoint. Slides without a transition, and Show without animation, start the step at once as before.
2026-11-17 08:35:55 +00:00
Dylan M. Taylor 5c698493bc ci: lock workflow actions through an actions.lock lockfile (#2078) 2026-11-16 21:58:00 -05:00
Dylan M. Taylor f964d06cc5 docs: prefer shared Craft libraries for reusable features (#2178) 2026-11-16 21:57:57 -05:00
Dylan M. Taylor ac73229ef4 pptx: reuse shared custom-geometry path tokenization (#2192) 2026-11-16 21:57:53 -05:00
Neil Cawse 71fa4b6ccd Merge remote-tracking branch 'upstream/main' into fix/pptx-media-timing-nodes 2026-11-17 02:30:00 +00:00
Neil Cawse fc6a3c4dbd pptx: validate enclosing mainSeq id on onBegin timing exemption 2026-11-17 02:30:00 +00:00
Dylan M. Taylor 1ec01a091a refactor(pptx): reuse shared table style identifiers (#792) (#2189) 2026-11-16 19:31:55 +00:00
jgriggs-sluh ff812840c0 Merge remote-tracking branch 'origin/main' into feat/export-all-slides-pictures
# Conflicts:
#	ROADMAP.md
2026-11-16 08:30:50 -06:00
Naseq f5f106d694 ROADMAP: fold the #2025 status into the current line; rows in date order (review) 2026-11-16 14:34:13 +04:30
Naseq 6a99c025e9 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	ROADMAP.md
2026-11-16 14:00:30 +04:30
Neil Cawse e4e6f4da3b Merge remote-tracking branch 'upstream/main' into fix/pptx-media-timing-nodes 2026-11-14 18:04:25 +00:00
Naseq 8102964f6b Merge remote-tracking branch 'origin/main' into merge-fix-2025-empty-notes-slide
# Conflicts:
#	ROADMAP.md
#	docs/file-format-parity.md
2026-11-14 13:46:33 +04:30
Neil Cawse 987a979121 Merge remote-tracking branch 'upstream/main' into fix/pptx-media-timing-nodes 2026-11-14 02:00:01 +00:00
Neil Cawse ea85b0412a pptx: preserve deferred ancestor conditions in command-based autoplay inference 2026-11-13 18:55:05 +00:00
Neil Cawse a4d458febe Merge remote-tracking branch 'upstream/main' into fix/pptx-media-timing-nodes 2026-11-13 18:51:40 +00:00
autocraft-bot[bot] 52ceb3974b Apply review fixes
- crates/model/src/chart.rs
2026-11-13 17:48:22 +00:00
ljkx 324a15bc50 render: test a glow from the presentation default text style
A glow that text inherits only from `p:defaultTextStyle` must also put
the slide on the filter canvas. The new test checks `needs_filters` and
renders with worker threads requested, expecting the green halo instead
of a blank slide. It fails when the `default_text_style` branch of
`text_has_effects` is dropped. Both glow tests now share one assertion
helper.
2026-11-13 17:40:16 +01:00
ljkx e6daa65687 Merge remote-tracking branch 'upstream/main' into render-text-effects-from-defrpr 2026-11-13 17:36:38 +01:00
jgriggs-sluh 103dc9b05c Save As: the type list shows all nine types without scrolling (#2019)
With the two all-slides types the list outgrew the combo box's default
height, and JPEG Pictures, all slides sat behind a scroll.
2026-11-13 08:26:45 -06:00
jgriggs-sluh 24fadbfc0e Merge remote-tracking branch 'origin/main' into feat/export-all-slides-pictures
# Conflicts:
#	ROADMAP.md
2026-11-13 08:19:45 -06:00
Simon Koch-Sultan 2f894ba110 Merge main into fix/placed-group-text
ROADMAP.md: main's 2026-11-11 status line, progress-log rows and
revision row come first, then this branch's 2026-11-07 lines.
2026-11-13 07:17:11 -05:00
Hamza b5dfac1366 Charts: value labels only on line series, with stacked and position tests
Review of #2071: scatter and bubble series, drawn by the same function, are
left as they were. The label keeps the point's own value before stacking, and
new tests check a stacked label shows that value and sits just above its point.
2026-11-13 14:41:28 +05:00
ljkxandClaude Opus 5.5 53044b2ceb render: text effects from a paragraph's defRPr or the default text style need filters
`text_has_effects` missed a shadow or glow that text inherits from its
paragraph's `a:pPr/a:defRPr` or the presentation's default text style.
Such a slide was drawn on the multi-threaded vello_cpu dispatcher, which
panics on filter layers; the render guard caught it and the slide came
out blank. Found by the Text Shadow UI test in #1691.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:57:53 +01:00
jgriggs-sluh 379391329b Merge remote-tracking branch 'origin/main' into feat/export-all-slides-pictures
# Conflicts:
#	ROADMAP.md
2026-11-12 09:49:12 -06:00
Hamza 8d51427d1e Charts: line series draw their value labels
A line chart whose series ask for value labels (c:dLbls/c:showVal,
chart-wide or on the series) drew none: draw_lines placed the points
and the line but never a label, though bar and pie charts draw theirs
(#868). Each point now shows its own value (not the stacked total)
just above it, in the chart's text colour and number format, as the
bars place theirs. Area series still draw none.

Fixes #2066
2026-11-12 11:30:53 +05:00
Neil Cawse 688fbc5896 Merge remote-tracking branch 'upstream/main' into fix/pptx-media-timing-nodes 2026-11-11 18:35:52 +00:00
Naseq e4b1a609f2 PPTX: preserve empty notes slides on save and reopen (#2025)
When a slide has an associated notes slide with no text, PPTX export
previously omitted both the notes slide part and its relationship,
treating notes slides without text runs as removable.

Track whether a slide has an associated notes slide (`has_notes_slide`).
Import marks it when reading a notes slide relationship, and export keeps
the notes slide part, its slide relationship, and notes master linkage
even when its text body is empty. Native serialization preserves the
presence flag, and setting notes via `slide.notes` also enables it.

Regression test in `crates/pptx/tests/it/notes.rs` verifies that a slide
with an empty notes slide retains its notes part and relationship across
multiple import and export roundtrips.
2026-11-11 11:46:30 +04:30
Neil Cawse 0aabe94d68 Merge remote-tracking branch 'origin/main' into fix/pptx-media-timing-nodes 2026-11-11 02:18:40 +00:00
jgriggs-sluh 2ca092c263 Document the Export… dialog's body function (#2019) 2026-11-10 16:12:52 -06:00
jgriggs-sluh deb6e1707b Test that Transparent background reaches every slide's PNG in Change File Type (#2019) 2026-11-10 15:59:47 -06:00
jgriggs-sluh 037747739f Docs: UI parity Save As row and status lines for all-slides picture export (#2019) 2026-11-10 14:48:19 -06:00
autocraft-bot[bot] 55aec60818 Apply review fixes
- docs/ui-parity.md
2026-11-10 20:45:43 +00:00
jgriggs-sluh 53f09a0298 Export: every slide as PNG or JPEG from File › Export › Change File Type and Save As (#2019)
Change File Type and Save As offered PNG and JPEG for the current slide only;
all slides as pictures was reachable only through the Export… dialog, and only
as PNG. Both File-tab pages now list "PNG Pictures, all slides" and "JPEG
Pictures, all slides" (with Transparent background for PNG), and the Export…
dialog adds "JPEG images (all slides)". `file.export` already wrote one file
per slide with `all: true`; this is UI only.

Closes #2019
2026-11-10 14:30:25 -06:00
Neil Cawse 0fabcf1da7 fix(pptx): restrict fullScrn to p:video and extract defers_start helper 2026-11-09 14:27:06 +00:00
Yonatan Langer a55b73c71f Preferences: the Interface size slider is labelled again
The egui 0.37 migration (#1350) dropped the slider's own text
("Interface size") and kept only its accessible name, so the dialog
showed a bare "1.00" with nothing saying what it changes. The slider
now sits in a row with an "Interface size:" label, laid out like the
Measurement units row below it. Its accessible name is unchanged.

Test: the_interface_size_slider_is_labelled_on_screen (the label is
shown, before the slider, on the same row).
2026-11-09 14:42:49 +02:00
Neil Cawse 9fb1c5f974 fix(pptx): round-trip media rewind/play_across_slides and detect main-sequence autoplay 2026-11-08 13:50:22 +00:00
Neil Cawse 096b70421e test(pptx): cover media-only timing export round-trip and autoplay condition edge cases 2026-11-08 13:41:07 +00:00
Neil Cawse c6e21c4fb5 refactor(pptx): delegate empty-timing check to timing::timing 2026-11-08 13:41:07 +00:00
Neil Cawse 8c85789cb1 pptx: round-trip p:video and p:audio media timing nodes and autoplay conditions 2026-11-08 13:41:07 +00:00
Naseq 0a07e9eae1 Canvas: clip the canvas Ui to its own rect so the media bar and other canvas paint stay out of the notes pane (#1922) 2026-11-08 15:18:27 +04:30
Simon Koch-Sultan ba63277c80 render: text in scaled groups is placed where it is drawn
The renderer sets the text of a shape inside a group whose child
coordinates scale it at the shape's size on the slide, so font sizes and
insets stay in points (Renderer::text_space). place() set the same text in
the group's child units and then scaled it with the group, so placed text
broke its lines differently and lay elsewhere than the drawn text. The PDF
text layer and the text hyperlink areas read placed text.

text_space's rule moves into placed.rs as one function that the renderer
and place() both call. Table cell text is unchanged: tables draw their
text under the group's scale, and place() already did the same.

Test: text_in_a_scaled_group_is_placed_as_drawn puts one line in groups
whose child space is 1, 1600, 4 and 1/4 times smaller than the group and
checks each glyph's id, position on the slide and drawn size against the
same line on its own.

ROADMAP.md gets a status line, a progress-log row and a revision-history
row.
2026-11-07 09:34:47 -05:00
aiongg 2dbcbc0c8a Apply review fixes
- crates/engine/src/cmd/format.rs
- crates/engine/src/cmd/format/font.rs
2026-11-04 20:16:10 +00:00
Hamza e39e693dab format.font: a CJK run takes its East Asian typeface, and each script is set on its own 2026-11-03 17:07:28 +05:00
Hamza 370b38e69a A date with no field to keep takes the deck's remembered format
My previous commit withheld the format from `set_date` whenever the caller had
not named one, so a field the slide already had would not be rewritten. That is
right where there is a field. A placeholder showing a fixed date holds plain
text and no date field at all, so there was no format to preserve and the
withheld format left `date_kind("")` to build a `datetime1`: a slide taken from
`datetime11` to fixed text and back came away on the short date (noted in
review).

The deck's format now always reaches `set_date`, and `format_given` is what
decides whether it may rewrite an existing field. With no field, there is
nothing to preserve and the remembered format is what a new one takes.

`a_fixed_date_turned_automatic_again_comes_back_on_the_remembered_format` walks
that transition with no `dateFormat` in the call, which is what the dialog
sends, and goes on to assert the guard still holds where a field does exist. It
is a test of its own rather than more of `the_automatic_date_takes_the_format_it_is_given`,
because setting a format for one slide also moves the deck's global one, which
that test's later assertions depend on.
2026-11-02 15:57:14 +05:00
Hamza 1a16bf975c format.font: a script typeface that is not a string is refused
`str_param` answers `None` both for an absent key and for a key holding something
that is not a string, so `typeface_param` read the two as the same thing. With
`{"family": "Lato", "eastAsia": 42}` the command set the Latin typeface, left the
East Asian one as it was and reported success -- the one thing the caller asked
for was the one thing that did not happen (noted in review).

Read through `p.get(key)` instead, the way `opt_usize_param` and `id_param`
already read theirs: an absent key, and an explicit `null`, still mean the script
keeps its typeface; anything else present has to be a string.

`family` is judged the same way, so `{"family": 42}` now says the key is not a
typeface name rather than that it is missing.
2026-11-02 15:43:23 +05:00
Hamza 372c0e6c44 Apply only a date format the caller asked for
The dialog always sends `dateText`, so an Apply with no format selection
reached `set_date` carrying the deck's global format, and rewrote a slide's own
date field to it. Measured on two slides, the first on the time format and the
second on the short date:

    before   [datetime11, datetime5]
    apply {"date": true, "dateText": "", "all": true}
    after    [datetime5,  datetime5]

The first slide's format was never mentioned by the caller, and it was gone.
`set_date` already keeps an existing field when the format is empty, so it now
gets an empty format unless `dateFormat` was supplied; a format that is
supplied still reaches every slide, which the test checks so the guard cannot
quietly become a block.
2026-10-29 16:48:32 +05:00
Hamza 3a1a74d2aa format.font: set the East Asian and complex-script typefaces (#786)
A run carries a typeface per script (ECMA-376 §21.1.2.3): `a:latin`, `a:ea`
and `a:cs`. `format.font` set only the Latin one, so a CJK run kept drawing --
and saving -- in whatever `a:ea` named before, and there was no way to change
it.

`eastAsia` and `complexScript` set the other two. Left out they keep their
value, which is what the command has always done. A name that is empty or
longer than the Font dialog allows is refused rather than stored.

Rebased onto main, 637 commits on: engine's format.rs is split, so `font` and
`typeface_param` are in cmd/format/font.rs, the command's registry entry
stays in cmd/format.rs, and the tests went to cmd/text.rs.
2026-10-28 20:41:25 +05:00
Hamza 64d3127fe8 Header & Footer: an automatic date's format comes back on import
`header_footer()` recorded a Date placeholder's text only when it held no field,
and never looked at the field itself, so an automatic date's format was dropped
on import: `date_format` stayed empty whatever the deck used.

With the dialog of the previous commit that is not only cosmetic. Opening a deck
whose dates are `datetime5` showed `datetime1` selected, and pressing Apply then
sent that back and reformatted the deck's dates — a silent change to a file the
user only opened to look at.

The reader now remembers which of the thirteen formats the field is, so the
dialog opens on the deck's own choice. An unknown spelling (`datetime`,
`datetimeFigureOut`, which both render as the short date) is left as no choice
rather than guessed at, since the command only accepts the thirteen and would
refuse it. A fixed date still comes back as its text, as before.

`crates/pptx` gains a dependency on `crates/text` for `datetime::DATE_KINDS`,
which layer 3 may take on layer 2; `cargo xtask layers` passes.
2026-10-28 20:29:33 +05:00
65 changed files with 2512 additions and 469 deletions
+31
View File
@@ -0,0 +1,31 @@
# This file is machine-generated by `gh actions-lock`.
# Do not edit by hand; run `gh actions-lock` to update.
# Docs: https://gh.io/actions-lockfile
version: 'v0.0.3'
workflows:
'.github/workflows/ci.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/freebsd.yml': []
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nix.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
dependencies:
'actions/checkout@v7.0.1':
ref: 'v7.0.1'
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/harden-runner@v2.22.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
owner_id: 88700172
repo_id: 422287306
+2 -2
View File
@@ -27,11 +27,11 @@ jobs:
CRAFT_FONTS_REF: 37827adc41fd165f9a9234ac40f94dbad353aa69
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- name: Check out craft-fonts
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@v7.0.1
with:
repository: storytold/craft-fonts
ref: ${{ env.CRAFT_FONTS_REF }}
+34
View File
@@ -0,0 +1,34 @@
name: Lockfile
# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin
# no longer verifies upstream, so a moved tag cannot slip a different commit into a run.
# Docs: https://gh.io/actions-lockfile
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
env:
GH_TOKEN: ${{ github.token }}
jobs:
lockfile:
name: Lockfile is in sync
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install gh-actions-lock
run: gh extension install github/gh-actions-lock --pin v0.4.1
- name: Verify the lockfile
run: gh actions-lock --verify
+2 -2
View File
@@ -28,10 +28,10 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install the pinned packaging toolchain
+4
View File
@@ -239,3 +239,7 @@ the `ROADMAP.md` progress log, and update each touched doc's status line and rev
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
## Shared libraries
Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers.
Generated
+353 -7
View File
@@ -129,6 +129,24 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "aligned"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685"
dependencies = [
"as-slice",
]
[[package]]
name = "aligned-vec"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
dependencies = [
"equator",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -227,6 +245,17 @@ dependencies = [
"x11rb",
]
[[package]]
name = "arg_enum_proc_macro"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "arrayref"
version = "0.3.9"
@@ -245,6 +274,15 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
[[package]]
name = "as-slice"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"
dependencies = [
"stable_deref_trait",
]
[[package]]
name = "ash"
version = "0.38.0+1.3.281"
@@ -434,6 +472,40 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "av-scenechange"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"
dependencies = [
"aligned",
"anyhow",
"arg_enum_proc_macro",
"arrayvec",
"log",
"num-rational",
"num-traits",
"pastey",
"rayon",
"thiserror 2.0.21",
"v_frame",
"y4m",
]
[[package]]
name = "av1-grain"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8"
dependencies = [
"anyhow",
"arrayvec",
"log",
"nom",
"num-rational",
"v_frame",
]
[[package]]
name = "base64"
version = "0.22.1"
@@ -473,6 +545,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bitstream-io"
version = "4.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f"
dependencies = [
"no_std_io2",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -513,6 +594,12 @@ dependencies = [
"piper",
]
[[package]]
name = "built"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -847,7 +934,7 @@ dependencies = [
[[package]]
name = "craft-audio"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-media",
"thiserror 2.0.21",
@@ -891,6 +978,17 @@ dependencies = [
"serde",
]
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b#cff5af869dbf6926801c9ac63a927d155202ba3b"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b)",
"kurbo",
"log",
"serde",
]
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -922,7 +1020,7 @@ dependencies = [
[[package]]
name = "craft-media"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"thiserror 2.0.21",
]
@@ -1027,9 +1125,10 @@ dependencies = [
[[package]]
name = "craft-video"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-media",
"rav1e",
"rayon",
"thiserror 2.0.21",
]
@@ -1064,6 +1163,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b#cff5af869dbf6926801c9ac63a927d155202ba3b"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
@@ -1209,7 +1318,7 @@ dependencies = [
name = "deckcraft-color"
version = "0.19.0"
dependencies = [
"craft-drawingml",
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
]
[[package]]
@@ -1266,7 +1375,7 @@ dependencies = [
name = "deckcraft-geom"
version = "0.19.0"
dependencies = [
"craft-drawingml",
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
"kurbo",
"serde",
]
@@ -1329,12 +1438,15 @@ name = "deckcraft-pptx"
version = "0.19.0"
dependencies = [
"craft-cfb",
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b)",
"craft-opc",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
"deckcraft-color",
"deckcraft-engine",
"deckcraft-geom",
"deckcraft-model",
"deckcraft-text",
"image",
"log",
"quick-xml 0.41.0",
@@ -1580,7 +1692,7 @@ dependencies = [
"bitflags 2.13.2",
"emath",
"epaint",
"itertools",
"itertools 0.15.0",
"log",
"nohash-hasher",
"profiling",
@@ -1642,7 +1754,7 @@ dependencies = [
"ahash",
"egui",
"enum-map",
"itertools",
"itertools 0.15.0",
"log",
"profiling",
]
@@ -1786,6 +1898,26 @@ name = "epaint_default_fonts"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[package]]
name = "equator"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
dependencies = [
"equator-macro",
]
[[package]]
name = "equator-macro"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -2696,6 +2828,17 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "interpolate_name"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "is-docker"
version = "0.2.0"
@@ -2715,6 +2858,15 @@ dependencies = [
"once_cell",
]
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.15.0"
@@ -2905,6 +3057,16 @@ version = "0.2.190"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
[[package]]
name = "libfuzzer-sys"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"
dependencies = [
"arbitrary",
"cc",
]
[[package]]
name = "libloading"
version = "0.8.9"
@@ -2990,6 +3152,16 @@ dependencies = [
"libc",
]
[[package]]
name = "maybe-rayon"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"
dependencies = [
"cfg-if",
"rayon",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -3128,6 +3300,12 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.31.3"
@@ -3140,6 +3318,15 @@ dependencies = [
"libc",
]
[[package]]
name = "no_std_io2"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003"
dependencies = [
"memchr",
]
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -3155,6 +3342,12 @@ dependencies = [
"memchr",
]
[[package]]
name = "noop_proc_macro"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -3164,6 +3357,16 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -3181,6 +3384,26 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -3666,6 +3889,18 @@ dependencies = [
"windows-link",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pastey"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
[[package]]
name = "pdf-writer"
version = "0.15.0"
@@ -3903,6 +4138,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "presser"
version = "0.3.1"
@@ -3932,6 +4176,19 @@ name = "profiling"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
dependencies = [
"profiling-procmacros",
]
[[package]]
name = "profiling-procmacros"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"
dependencies = [
"quote",
"syn 2.0.119",
]
[[package]]
name = "pxfm"
@@ -3984,12 +4241,75 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "range-alloc"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
[[package]]
name = "rav1e"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b"
dependencies = [
"aligned-vec",
"arbitrary",
"arg_enum_proc_macro",
"arrayvec",
"av-scenechange",
"av1-grain",
"bitstream-io",
"built",
"cfg-if",
"interpolate_name",
"itertools 0.14.0",
"libc",
"libfuzzer-sys",
"log",
"maybe-rayon",
"new_debug_unreachable",
"noop_proc_macro",
"num-derive",
"num-traits",
"paste",
"profiling",
"rand",
"rand_chacha",
"simd_helpers",
"thiserror 2.0.21",
"v_frame",
]
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -4477,6 +4797,15 @@ dependencies = [
"simdutf8",
]
[[package]]
name = "simd_helpers"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6"
dependencies = [
"quote",
]
[[package]]
name = "simdutf8"
version = "0.1.5"
@@ -5327,6 +5656,17 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "v_frame"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2"
dependencies = [
"aligned-vec",
"num-traits",
"wasm-bindgen",
]
[[package]]
name = "vello_common"
version = "0.2.0"
@@ -6394,6 +6734,12 @@ dependencies = [
"serde_json",
]
[[package]]
name = "y4m"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
[[package]]
name = "yoke"
version = "0.8.3"
+5 -3
View File
@@ -18,6 +18,8 @@ craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9
# XML writer primitives; parser admission and OOXML policy stay app-local.
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" }
# DrawingML colours, themes and text (craft-libs#778, #792): the model DeckCraft reads and writes.
# Isolated table XML writer; existing DrawingML model/readers keep their revision.
craft-drawingml-table = { package = "craft-drawingml", git = "https://github.com/storytold/craft-libs", rev = "cff5af869dbf6926801c9ac63a927d155202ba3b" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "44d83fa8f635333dcb3c231f87381387a1f5631b", version = "0.1.0" }
# internal
deckcraft-geom = { path = "crates/geom" }
@@ -62,10 +64,10 @@ craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "254e9a409
# The .deckcraft package layer (identity, manifest, member names, bounded reads); crates/format maps the presentation onto it.
craft-deckcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "254e9a409b410dc93c0e06ff66cd1e767893ac32", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" }
craft-media = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false }
craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["opus-decode"] }
craft-media = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "=0.1.0", default-features = false }
craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "=0.1.0", default-features = false, features = ["opus-decode"] }
# H.264, HEVC, VP9 and AV1 decoders.
craft-video = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["h264-decode", "hevc-decode", "vp9-decode", "av1-decode", "threads"] }
craft-video = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "=0.1.0", default-features = false, features = ["h264-decode", "hevc-decode", "vp9-decode", "av1-decode", "threads"] }
# WMF, EMF and EMF+ reader.
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] }
+9 -1
View File
@@ -2,7 +2,9 @@
**Stage: alpha** · next: beta, ~20 points and ~120–210 h away
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-14 · **Change:** trivial (a slide the show advances to again plays its animations again, #2090; slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: every slide as PNG or JPEG from File › Export › Change File Type and Save As, #2019; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-14 · **Change:** minor (a slide the show advances to again plays its animations again, #2090; slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; empty notes slides are kept through PPTX and native saves, #2025; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-07 · **Change:** trivial (progress log: text in a group whose child coordinates scale its shapes is placed for export where the slide draws it; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (progress log: web `?host=parent` bridge opens and saves through a same-origin framing page; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
@@ -154,9 +156,12 @@ app's JSON control channel (`deckcraft --control PORT`).
| Date | What landed |
|---|---|
| 2026-11-16 | Export: every slide as its own PNG or JPEG picture from File › Export › Change File Type and File › Save As; the Export… dialog adds JPEG images (all slides) (#2019) |
| 2026-11-14 | Slide show: a slide the show advances to again (click, →, Space, automatic advance or a loop) starts over, so its animations play again, as in PowerPoint. Back and links still show it as it was left (#2090) |
| 2026-11-11 | PPTX: a slide whose notes slide has empty text retains its notesSlide part and relationship on save and reopen (#2025); empty notes slides survive native round trips |
| 2026-11-11 | Media: the Opus decoder and the Ogg, MP4/MOV and Matroska demuxers are craft-audio and craft-media from craft-libs; DeckCraft's own copies and re-export crates are removed |
| 2026-11-07 | PPTX slide-list entries with missing relationships are reported in lostSlides instead of silently omitted. The engine opens the partial deck as a repaired copy with no original save path. Slide lists over 10,000 entries are explicitly refused before a partial load; exactly 10,000 remain supported. Synthetic 13-slide regression; does not establish the cause of #1910's field report. |
| 2026-11-07 | Text inside a group whose child coordinates scale its shapes is laid out for export as the slide draws it, at the shape's size in points, so the PDF text layer and the boxes of its text hyperlinks lie on the drawn text. SmartArt groups, whose child space equals their frame, are unchanged |
| 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered |
| 2026-11-03 | Web: the `?host=parent` bridge (as in GridCraft, WordCraft and PdfCraft) lets a same-origin page that frames DeckCraft send a presentation and store its saves; Save writes an opened .pptx back as .pptx under its own name, as on the desktop |
| 2026-11-02 | Slide show on Linux and the BSDs: Presenter View stays off when winit lists exactly one display, as in PowerPoint; if it lists none, the setting is kept. On one display the presenter window covered the show, and the hidden window stalled every frame: slide changes took up to ~1.7 s under Hyprland (#1156) |
@@ -343,8 +348,11 @@ app's JSON control channel (`deckcraft --control PORT`).
| Date | Change | Summary |
|---|---|---|
| 2026-11-16 | trivial | Progress log: export all slides as PNG or JPEG from the File tab (#2019); scores unchanged |
| 2026-11-14 | trivial | Progress log: a slide the show advances to again plays its animations again (#2090); parity scores unchanged |
| 2026-11-11 | minor | Progress log: empty notes slides preserved on PPTX/native save (#2025); parity scores unchanged |
| 2026-11-11 | trivial | Opus and container code moved to craft-libs crates; parity scores unchanged |
| 2026-11-07 | trivial | Progress log: text in scaled groups is placed for export where it is drawn; parity scores unchanged |
| 2026-11-04 | trivial | Ogg Opus recovery duration includes its recovered tail; parity scores unchanged |
| 2026-11-02 | trivial | Progress log: run alternate-language metadata round-trips through native and PPTX formats; product parity scores unchanged |
| 2026-11-03 | trivial | Reuse Slides brings referenced custom table styles along; scores unchanged |
+3
View File
@@ -148,6 +148,9 @@ fn warn_if_damaged(path: &str, opened: &serde_json::Value) {
if slides > 0 {
eprintln!("deckcraft-cli: warning: {path}: {slides} slide{} couldn't be read and left out", if slides == 1 { "" } else { "s" });
}
for w in opened.get("importWarnings").and_then(|v| v.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) {
eprintln!("deckcraft-cli: warning: {path}: {w}");
}
if media > 0 {
eprintln!("deckcraft-cli: warning: {path}: {media} picture or media file{} couldn't be read", if media == 1 { "" } else { "s" });
}
+9
View File
@@ -433,6 +433,15 @@ pub(crate) fn shape_of(s: &Session, id: ShapeId) -> Result<deckcraft_model::Shap
pub fn xfrm_of(doc: &deckcraft_model::Presentation, sel: &crate::Selection, shape: &deckcraft_model::Shape) -> Xfrm {
let mut x = shape.xfrm.unwrap_or_else(|| ctx_xfrm(doc, sel, shape));
if let deckcraft_model::ShapeKind::Table(t) = &shape.kind {
// A loaded table may not be normalized yet: measure the bounded grid an edit will
// leave, not every cell the file stored.
let normalized;
let t = if t.is_normalized() {
t
} else {
normalized = t.normalized();
&normalized
};
let drawn: f64 = table_drawn_heights(doc, sel, t).iter().sum();
if drawn.is_finite() && drawn > x.h {
x.h = drawn;
+67 -3
View File
@@ -176,7 +176,10 @@ pub(super) fn header_footer(s: &mut Session, p: &Value) -> Result<Value> {
}
(Some(pos), true) if k == PhType::Date && (date_given || format_given) => {
if let Some(sh) = sl.shapes.get_mut(pos) {
set_date(sh, &hf.date_text, &hf.date_format);
// The deck's format always travels; whether the caller asked for it
// is what decides if it may rewrite a field the slide already has
// (see `set_date`).
set_date(sh, &hf.date_text, &hf.date_format, format_given);
}
}
_ => {}
@@ -200,8 +203,19 @@ fn date_now(format: &str) -> String {
}
/// Point a slide's date placeholder at a fixed date (its own plain text) or, for an empty
/// `fixed`, at an automatic date field (one it already has keeps its format).
fn set_date(sh: &mut Shape, fixed: &str, format: &str) {
/// `fixed`, at an automatic date field.
///
/// `format_given` is whether the caller named a format. The dialog always sends `dateText`, so an
/// Apply with no format selection reached here carrying the deck's global format and rewrote a
/// slide's own `datetime11` field to it -- a format the caller never mentioned. A field the slide
/// already has therefore keeps its own format unless one was asked for.
///
/// That holds only where there *is* a field to keep. A placeholder showing a fixed date has no
/// date field and no format of its own, so clearing `dateText` without naming a format used to
/// build a `datetime1`: a slide that went from `datetime11` to fixed text and back came away on
/// the short date. With nothing to preserve, the deck's remembered format is the right one to
/// take (noted in review).
fn set_date(sh: &mut Shape, fixed: &str, format: &str, format_given: bool) {
let runs = || sh.text.iter().flat_map(|t| &t.paragraphs).flat_map(|p| &p.runs);
let field_now = runs().find_map(|r| match &r.kind {
RunKind::Field { field } if deckcraft_text::datetime::is_date_field(field) => Some(field.clone()),
@@ -209,6 +223,7 @@ fn set_date(sh: &mut Shape, fixed: &str, format: &str) {
});
let has_field = field_now.is_some();
let props = runs().next().map(|r| r.props.clone()).unwrap_or_default();
let format = if format_given || !has_field { format } else { "" };
let want = date_kind(format);
let (text, kind) = match fixed {
// Automatic: keep the field, but follow a format that has changed.
@@ -298,6 +313,55 @@ mod header_footer_date_tests {
got[0].0.clone()
}
/// The dialog always sends `dateText`, so an Apply with no format selection reached
/// `set_date` with the deck's global format and rewrote a slide's own date field to it. The
/// format the caller did not mention is not a format the caller asked for (noted in review).
#[test]
fn an_apply_with_no_format_leaves_each_slides_own_format_alone() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({})).unwrap();
s.execute("design.headerFooter", &json!({"date": true, "dateFormat": "datetime11", "all": true})).unwrap();
let kinds = |s: &Session| dates(s).into_iter().map(|(_, k)| k).collect::<Vec<_>>();
assert_eq!(kinds(&s), vec![Some("datetime11".to_string()); 2], "both slides start on the time format");
// One slide alone takes a different format, which also becomes the deck's global one.
s.execute("design.headerFooter", &json!({"date": true, "dateFormat": "datetime5", "all": false})).unwrap();
assert_eq!(kinds(&s), vec![Some("datetime11".to_string()), Some("datetime5".to_string())]);
assert_eq!(s.doc().unwrap().doc.header_footer.date_format, "datetime5");
// Apply with no `dateFormat`: the first slide keeps datetime11 rather than being rewritten
// to the global datetime5.
s.execute("design.headerFooter", &json!({"date": true, "dateText": "", "all": true})).unwrap();
assert_eq!(kinds(&s), vec![Some("datetime11".to_string()), Some("datetime5".to_string())], "neither slide was rewritten");
// And a format that *is* given still reaches every slide, so the guard is not a block.
s.execute("design.headerFooter", &json!({"date": true, "dateFormat": "datetime2", "all": true})).unwrap();
assert_eq!(kinds(&s), vec![Some("datetime2".to_string()); 2], "a format the caller asked for still applies");
}
/// A fixed date is plain text, so the placeholder has no date field and no format of its
/// own. Clearing `dateText` without naming a format therefore has nothing to preserve, and
/// built a `datetime1`: a slide that went from `datetime11` to fixed text and back came away
/// on the short date (noted in review).
#[test]
fn a_fixed_date_turned_automatic_again_comes_back_on_the_remembered_format() {
let mut s = Session::with_new();
run_automatic(&mut s, json!({"date": true, "dateFormat": "datetime11", "all": true}), "datetime11");
s.execute("design.headerFooter", &json!({"date": true, "dateText": "4 July 1776", "all": true})).unwrap();
assert_eq!(dates(&s), vec![("4 July 1776".to_string(), None)], "fixed: plain text, no field");
// No `dateFormat` in this call, which is what the dialog sends on an Apply.
run_automatic(&mut s, json!({"date": true, "dateText": "", "all": true}), "datetime11");
// And the guard this must not undo: where there *is* a field, an Apply naming no format
// still leaves the slide's own format alone, although the deck's format now reaches
// `set_date` either way.
s.execute("design.headerFooter", &json!({"date": true, "dateFormat": "datetime5", "all": false})).unwrap();
s.execute("design.headerFooter", &json!({"date": true, "dateText": "", "all": true})).unwrap();
assert_eq!(dates(&s)[0].1.as_deref(), Some("datetime5"), "the slide's own format survives");
}
/// Header & Footer's automatic date takes the format it is given. `HeaderFooter::date_format`
/// existed for this and was never read: the placeholder was always `datetime1`, and a
/// `dateFormat` parameter was accepted and silently dropped.
+17 -9
View File
@@ -139,11 +139,13 @@ pub struct Damage {
pub media: Vec<String>,
/// Slides a `.pptx` lists but that couldn't be read, so they are not in the presentation.
pub slides: Vec<String>,
/// Content a `.pptx` had that was cut to fit a limit; the file still opened.
pub warnings: Vec<String>,
}
impl Damage {
pub fn is_empty(&self) -> bool {
self.media.is_empty() && self.slides.is_empty()
self.media.is_empty() && self.slides.is_empty() && self.warnings.is_empty()
}
}
@@ -151,17 +153,17 @@ impl Damage {
pub fn open_checked(name: &str, bytes: &[u8]) -> Result<(Presentation, Damage)> {
if deckcraft_format::sniff(bytes) {
let (p, media) = deckcraft_format::load_checked(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
return Ok((p, Damage { media, slides: vec![] }));
return Ok((p, Damage { media, ..Default::default() }));
}
open_other(name, bytes).map(|(p, slides)| (p, Damage { media: vec![], slides }))
open_other(name, bytes).map(|(p, slides, warnings)| (p, Damage { slides, warnings, ..Default::default() }))
}
fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec<String>)> {
fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec<String>, Vec<String>)> {
if deckcraft_pptx::sniff(bytes) {
let (mut p, lost_slides) = deckcraft_pptx::import_checked(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let (mut p, lost_slides, warnings) = deckcraft_pptx::import_report(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
deckcraft_format::repair(&mut p);
probe_clips(&mut p);
return Ok((p, lost_slides));
return Ok((p, lost_slides, warnings));
}
if deckcraft_pptx::is_encrypted(bytes) {
return Err(EngineError::Other(format!("{name} is password-protected. DeckCraft can't open password-protected presentations yet.")));
@@ -180,7 +182,7 @@ fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec<String>)> {
if p.slides.is_empty() {
p = defaults::new_presentation(None);
}
return Ok((p, vec![]));
return Ok((p, vec![], vec![]));
}
Err(EngineError::Other(format!("{name}: not a presentation DeckCraft can read")))
}
@@ -276,7 +278,7 @@ fn adopt_loaded(s: &mut Session, f: LoadedFile) -> Result<Value> {
let st = s.doc()?;
Ok(json!({
"document": i, "slides": st.doc.slides.len(), "missingFonts": st.missing_fonts,
"damagedMedia": damaged.media, "lostSlides": damaged.slides,
"damagedMedia": damaged.media, "lostSlides": damaged.slides, "importWarnings": damaged.warnings,
}))
}
@@ -311,7 +313,9 @@ fn open_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let (doc, damaged) = open_checked(name, &data)?;
let i = add_opened(s, name, None, doc);
report_damage(s, &damaged)?;
Ok(json!({"document": i, "missingFonts": s.doc()?.missing_fonts, "damagedMedia": damaged.media, "lostSlides": damaged.slides}))
Ok(
json!({"document": i, "missingFonts": s.doc()?.missing_fonts, "damagedMedia": damaged.media, "lostSlides": damaged.slides, "importWarnings": damaged.warnings}),
)
}
/// Tell the user which pictures, media and slides a damaged file lost, and mark the copy repaired.
@@ -339,6 +343,10 @@ fn report_damage(s: &mut Session, damaged: &Damage) -> Result<()> {
if n == 1 { "was" } else { "were" },
));
}
for w in &damaged.warnings {
text.push_str(w);
text.push_str(". ");
}
text.push_str("It was opened as a repaired copy; save it under a new name to keep the original file.");
s.ui_requests.push(crate::UiRequest::Message { text });
Ok(())
+9 -1
View File
@@ -62,7 +62,15 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!("format.superscript", "Superscript", ["Home", "Font"], Some("Cmd+Shift+="), "{on?: bool}", has_text_or_shapes, superscript),
cmd!("format.subscript", "Subscript", ["Home", "Font"], Some("Cmd+="), "{on?: bool}", has_text_or_shapes, subscript),
cmd!("format.font", "Font", ["Home", "Font"], None, "{family}", has_text_or_shapes, font),
cmd!(
"format.font",
"Font",
["Home", "Font"],
None,
"{family, eastAsia?: family, complexScript?: family} — `family` is the Latin typeface (`a:latin`); the other two set the East Asian (`a:ea`) and complex-script (`a:cs`) typefaces, which are left alone when not given",
has_text_or_shapes,
font
),
cmd!("format.size", "Font Size", ["Home", "Font"], None, "{size: pt}", has_text_or_shapes, size),
cmd!("format.grow", "Increase Font Size", ["Home", "Font"], Some("Cmd+Shift+."), "{}", has_text_or_shapes, grow),
cmd!("format.shrink", "Decrease Font Size", ["Home", "Font"], Some("Cmd+Shift+,"), "{}", has_text_or_shapes, shrink),
+34 -2
View File
@@ -45,9 +45,41 @@ pub(super) fn subscript(s: &mut Session, p: &Value) -> Result<Value> {
format_run(s, &move |r| r.baseline = Some(if v { -0.25 } else { 0.0 }))
}
/// A typeface name from `key`: trimmed, and the length `format.fontDialog` allows.
///
/// Absent, as `opt_usize_param` and `id_param` read an absent key, so a call that leaves a script
/// out keeps that typeface. Present but not a string is refused: `str_param` answers `None` to
/// both, so `{"family": "Lato", "eastAsia": 42}` used to set the Latin typeface, leave the East
/// Asian one alone and report success -- the one thing the caller asked for silently not done.
fn typeface_param(p: &Value, key: &str) -> Result<Option<String>> {
let v = match p.get(key) {
None | Some(Value::Null) => return Ok(None),
Some(v) => v.as_str().ok_or_else(|| bad("format.font", format!("`{key}` is not a typeface name: {v}")))?,
};
let t = v.trim();
if t.is_empty() || t.chars().count() > 200 {
return Err(bad("format.font", format!("`{key}` must be 1-200 characters")));
}
Ok(Some(t.to_string()))
}
pub(super) fn font(s: &mut Session, p: &Value) -> Result<Value> {
let f = str_param(p, "family").ok_or_else(|| bad("format.font", "missing `family`"))?.to_string();
format_run(s, &move |r| r.font = Some(f.clone()))
let f = typeface_param(p, "family")?.ok_or_else(|| bad("format.font", "missing `family`"))?;
// A run carries a typeface per script (ECMA-376 §21.1.2.3): `a:latin`, `a:ea` and `a:cs`.
// Setting only the Latin one leaves a CJK run drawing -- and saving -- in whatever `a:ea`
// named before, so the two are settable (#786). Left out, they keep their value, which is
// what `format.font` has always done.
let ea = typeface_param(p, "eastAsia")?;
let cs = typeface_param(p, "complexScript")?;
format_run(s, &move |r| {
r.font = Some(f.clone());
if let Some(v) = &ea {
r.font_ea = Some(v.clone());
}
if let Some(v) = &cs {
r.font_cs = Some(v.clone());
}
})
}
pub(super) fn size(s: &mut Session, p: &Value) -> Result<Value> {
+5 -1
View File
@@ -602,11 +602,15 @@ fn notes(s: &mut Session, p: &Value) -> Result<Value> {
let text = str_param(p, "text").unwrap_or("").to_string();
s.edit(|doc, _| {
if let Some(sl) = doc.slides.get_mut(i) {
let notes = &mut Arc::make_mut(sl).notes;
let sl = Arc::make_mut(sl);
let notes = &mut sl.notes;
match body {
Some(b) => *notes = b,
None => deckcraft_model::edit::replace_text(notes, &text),
}
if !notes.is_empty() {
sl.has_notes_slide = true;
}
}
Ok(())
})?;
+17 -4
View File
@@ -286,6 +286,12 @@ fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> R
};
let r = edit_shapes(s, &json!({"id": id}), cmd, |sh| match &mut sh.kind {
ShapeKind::Table(t) => {
// Edits walk the grid: bound it first (a loaded table need not be normalized yet).
// An over-cap table is refused, not trimmed: a trim would delete rows while reporting success.
if t.over_cap() {
return Err(bad(cmd, format!("the table is larger than {} cells; edit refused", deckcraft_model::table::MAX_CELLS)));
}
t.normalize();
f(t)?;
t.normalize();
let (w, h) = (t.width(), t.height());
@@ -319,10 +325,17 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result
let op = op.to_string();
with_table(s, p, name, move |t| {
match op.as_str() {
"rowAbove" => t.insert_row(r),
"rowBelow" => t.insert_row(r.saturating_add(1)),
"colLeft" => t.insert_col(c),
"colRight" => t.insert_col(c.saturating_add(1)),
"rowAbove" | "rowBelow" | "colLeft" | "colRight" => {
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)),
};
if !ok {
return Err(bad(name, format!("the table is at its {}-cell limit", deckcraft_model::table::MAX_CELLS)));
}
}
"delRow" => {
if !t.delete_row(r) {
return Err(bad(name, "can't delete the last row"));
+133
View File
@@ -186,3 +186,136 @@ pub(crate) fn edit_text<T>(s: &mut Session, f: impl FnOnce(&mut TextBody, &mut T
}
Ok(r)
}
#[cfg(test)]
mod font_script_tests {
use super::*;
/// Every run's (latin, east asian, complex script) typefaces in the deck.
fn typefaces(s: &mut Session) -> Vec<(Option<String>, Option<String>, Option<String>)> {
s.doc()
.unwrap()
.doc
.slides
.iter()
.flat_map(|sl| sl.shapes.iter())
.filter_map(|sh| sh.text.as_ref())
.flat_map(|t| t.paragraphs.iter())
.flat_map(|para| para.runs.iter())
.map(|r| (r.props.font.clone(), r.props.font_ea.clone(), r.props.font_cs.clone()))
.collect()
}
#[test]
fn format_font_sets_the_east_asian_and_complex_script_typefaces() {
// A run carries a typeface per script; setting only the Latin one leaves a CJK run
// drawing, and saving, in whatever `a:ea` named before (#786).
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "Hello"})).unwrap();
s.execute("text.exit", &json!({})).unwrap();
// All three at once.
s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC", "complexScript": "Noto Sans Arabic"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
// The Latin-only call keeps its old meaning: the other two are left alone, which is
// what makes the new parameters additive.
s.execute("format.font", &json!({"family": "Comic Neue"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
// And they reach the file: the issue is that a saved deck kept asking for the old
// East Asian font.
let bytes = crate::cmd::file::save_bytes(&s.doc().unwrap().doc, "pptx").unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
// The text box is on whichever slide was current, so look across all of them.
let mut xml = String::new();
for i in 0..zip.len() {
let mut f = zip.by_index(i).unwrap();
if f.name().starts_with("ppt/slides/slide") && f.name().ends_with(".xml") {
std::io::Read::read_to_string(&mut f, &mut xml).unwrap();
}
}
assert!(xml.contains(r#"<a:ea typeface="Noto Sans CJK SC"/>"#), "no a:ea in the saved slides");
assert!(xml.contains(r#"<a:cs typeface="Noto Sans Arabic"/>"#), "no a:cs in the saved slides");
assert!(xml.contains(r#"<a:latin typeface="Comic Neue"/>"#), "no a:latin in the saved slides");
// Read back, they are still there.
s.execute("file.openBytes", &json!({"name": "f.pptx", "data": crate::cmd::base64_encode(&bytes)})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
}
#[test]
fn format_font_rejects_an_unusable_typeface_name() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "Hello"})).unwrap();
s.execute("text.exit", &json!({})).unwrap();
for p in [json!({"family": " "}), json!({"family": "Lato", "eastAsia": ""}), json!({"family": "Lato", "complexScript": "x".repeat(201)})] {
assert!(s.execute("format.font", &p).is_err(), "{p} should be rejected");
}
// A script key that is present but not a string is refused, not read as absent. It used
// to set `family` and report success with the script typeface untouched, so the one thing
// the call asked for was the one thing that did not happen (noted in review).
for p in [
json!({"family": "Lato", "eastAsia": 42}),
json!({"family": "Lato", "complexScript": true}),
json!({"family": "Lato", "eastAsia": ["Noto Sans CJK SC"]}),
json!({"family": "Lato", "complexScript": {"name": "Noto Sans Arabic"}}),
json!({"family": 42}),
] {
let e = s.execute("format.font", &p).expect_err(&format!("{p} should be rejected"));
assert!(format!("{e}").contains("is not a typeface name"), "{p}: {e}");
}
// Nothing above changed a run: the first call in this test left `family` unset, and a
// refused call must not have set it on the way to the error.
assert_eq!(typefaces(&mut s), vec![(None, None, None)]);
// An explicit `null` reads as absent, as it does for an index or a shape id, so the
// script keeps whatever typeface it had.
s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC"})).unwrap();
s.execute("format.font", &json!({"family": "Lato", "eastAsia": null})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]);
// A name with spaces around it is kept, trimmed.
s.execute("format.font", &json!({"family": " Lato ", "eastAsia": " Noto Sans CJK SC "})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]);
}
/// Each script's typeface is set on its own, and a run whose text is entirely CJK takes its
/// East Asian one: that is the run #786 is about, where `a:latin` alone changes nothing that
/// is drawn (noted in review).
#[test]
fn a_cjk_run_takes_the_east_asian_typeface_and_each_script_is_set_on_its_own() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "你好世界"})).unwrap();
s.execute("text.exit", &json!({})).unwrap();
// `eastAsia` alone (with the required `family`): the complex-script typeface is untouched.
s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]);
// `complexScript` alone: the East Asian typeface just set is kept, not cleared.
s.execute("format.font", &json!({"family": "Lato", "complexScript": "Noto Sans Arabic"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
// A Latin-only call on the CJK run changes `a:latin` and nothing a CJK glyph is drawn in.
s.execute("format.font", &json!({"family": "Comic Neue"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
// The saved run carries its text and the East Asian typeface together.
let bytes = crate::cmd::file::save_bytes(&s.doc().unwrap().doc, "pptx").unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
for i in 0..zip.len() {
let mut f = zip.by_index(i).unwrap();
if f.name().starts_with("ppt/slides/slide") && f.name().ends_with(".xml") {
std::io::Read::read_to_string(&mut f, &mut xml).unwrap();
}
}
let run = xml.find("你好世界").and_then(|at| xml[..at].rfind("<a:r>").map(|start| &xml[start..at])).unwrap_or_default();
assert!(run.contains(r#"<a:ea typeface="Noto Sans CJK SC"/>"#), "the CJK run has no a:ea: {run}");
}
}
+14 -1
View File
@@ -115,7 +115,7 @@ fn split_rows(t: &mut Table, y: f64, x0: f64, x1: f64) -> bool {
let b = match ys.iter().position(|e| (e - y).abs() <= SNAP) {
Some(b) => b,
None => {
if t.rows.len() >= MAX_GRID {
if t.rows.len() >= MAX_GRID || t.cols.len().saturating_mul(t.rows.len().saturating_add(1)) > deckcraft_model::table::MAX_CELLS {
return false;
}
let Some(k) = ys.windows(2).position(|w| w[0] < y && y < w[1]) else { return false };
@@ -273,4 +273,17 @@ mod tests {
}
assert!(t.rows.len() <= MAX_GRID && n > 100, "{} rows", t.rows.len());
}
#[test]
fn pencil_refuses_a_row_past_the_cell_cap() {
let cols = 1000;
let rows = deckcraft_model::table::MAX_CELLS / cols;
let mut t = Table {
cols: vec![10.0; cols],
rows: vec![deckcraft_model::table::Row { height: 50.0, cells: vec![Cell::new(""); cols] }; rows],
..Default::default()
};
assert!(!draw_line(&mut t, (0.0, 25.0), (10_000.0, 25.0)));
assert_eq!((t.n_rows(), t.n_cols()), (rows, cols));
}
}
+138 -15
View File
@@ -538,7 +538,57 @@ fn valid_lang(lang: &str) -> bool {
(1..=16).contains(&lang.len()) && lang.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// The `.aff`/`.dic` pair for `lang` in `dirs`: the exact locale first, then any of its language.
/// The script a language tag or a dictionary's name states, lowercased: a script subtag
/// (`sr-Latn`, `sr_Latn_RS`) or a `@latin`/`@cyrillic` modifier (Fedora's `sr_RS@latin`). Only
/// the scripts a dictionary is chosen by are read (Latin and Cyrillic), so another part of a name
/// (a variant such as `de-1996`, a suffix such as `en_US-wiki`) is never taken for one.
fn named_script(name: &str) -> Option<String> {
name.split(['-', '_', '@']).skip(1).find_map(|p| match p.to_ascii_lowercase().as_str() {
"latn" | "latin" => Some("latn".to_string()),
"cyrl" | "cyrillic" => Some("cyrl".to_string()),
_ => None,
})
}
/// The script of a language written in more than one, when a tag or a dictionary's name doesn't
/// state it: Serbian is Cyrillic (`sr-RS`, and LibreOffice's and Hunspell's `sr` dictionary), its
/// Latin dictionary says so (`sr-Latn`, `sr_Latn_RS`, `sr_RS@latin`).
fn default_script(base: &str) -> Option<&'static str> {
match base {
"sr" => Some("cyrl"),
_ => None,
}
}
/// Another language code a language's dictionaries are filed under, and their script: Serbian
/// Latin dictionaries are often Serbo-Croatian ones (Hunspell's `sh_RS`, `sh_YU`).
fn alias(base: &str) -> Option<(&'static str, &'static str)> {
match base {
"sr" => Some(("sh", "latn")),
_ => None,
}
}
/// The language code a dictionary is named for (`sr_Latn_RS`, `sr-Latn` → `sr`), lowercased.
fn stem_language(stem: &str) -> String {
stem.split(['-', '_', '@']).next().unwrap_or("").to_ascii_lowercase()
}
/// Is the dictionary named `stem` for text in the script of `lang` (language `base`)? A Cyrillic
/// dictionary would flag every word of Latin text, and the other way round. The run's language tag
/// decides, not the letters of the text. When either side's script is unknown, any dictionary of
/// the language fits, as before.
fn same_script(lang: &str, stem: &str, base: &str) -> bool {
let default = || default_script(base).map(str::to_string);
let aliased = alias(base).filter(|(code, _)| stem_language(stem) == *code).map(|(_, script)| script.to_string());
match (named_script(lang).or_else(default), named_script(stem).or(aliased).or_else(default)) {
(Some(want), Some(have)) => want == have,
_ => true,
}
}
/// The `.aff`/`.dic` pair for `lang` in `dirs`: the exact locale first, then any of its language
/// (or the language its dictionaries are also filed under, [`alias`]) in the same script.
pub fn find_in(dirs: &[PathBuf], lang: &str) -> Option<(PathBuf, PathBuf)> {
// A language tag names a file in the dictionary folders and nothing else: no `..`, no separators.
if !valid_lang(lang) {
@@ -550,23 +600,33 @@ pub fn find_in(dirs: &[PathBuf], lang: &str) -> Option<(PathBuf, PathBuf)> {
(a.is_file() && b.is_file()).then_some((a, b))
};
for d in dirs {
if let Some(p) = pair(d, &full) {
if let Some(p) = pair(d, &full).or_else(|| pair(d, lang)) {
return Some(p);
}
}
for d in dirs {
if let Some(p) = pair(d, &base) {
return Some(p);
}
let Ok(rd) = std::fs::read_dir(d) else { continue };
let mut stems: Vec<String> = rd
.filter_map(|e| e.ok()?.file_name().into_string().ok())
.filter_map(|n| n.strip_suffix(".aff").map(str::to_string))
.filter(|n| n.to_lowercase().starts_with(&format!("{base}_")))
.collect();
stems.sort();
if let Some(p) = stems.iter().find_map(|s| pair(d, s)) {
return Some(p);
// The language's own dictionaries first, in every folder; then those filed under its alias
// (a Serbian Latin dictionary before a Serbo-Croatian one).
let codes = std::iter::once(base.as_str()).chain(alias(&base).map(|(code, _)| code));
for code in codes {
for d in dirs {
if same_script(lang, code, &base)
&& let Some(p) = pair(d, code)
{
return Some(p);
}
let Ok(rd) = std::fs::read_dir(d) else { continue };
// `sr_Latn_RS`, LibreOffice's `sr-Latn` and Fedora's `sr_RS@latin` all name a Serbian
// dictionary.
let mut stems: Vec<String> = rd
.filter_map(|e| e.ok()?.file_name().into_string().ok())
.filter_map(|n| n.strip_suffix(".aff").map(str::to_string))
.filter(|n| stem_language(n) == code && !n.eq_ignore_ascii_case(code))
.filter(|n| same_script(lang, n, &base))
.collect();
stems.sort();
if let Some(p) = stems.iter().find_map(|s| pair(d, s)) {
return Some(p);
}
}
}
None
@@ -1078,4 +1138,67 @@ SFX D Y 1\nSFX D 0 ed/S .\n";
assert_eq!(stem("fr-FR"), None);
let _ = std::fs::remove_dir_all(&dir);
}
/// Serbian is written in two scripts, and each finds its own dictionary: LibreOffice names
/// the Cyrillic one `sr` and the Latin one `sr-Latn`, Hunspell packages `sr_RS` and
/// `sr_Latn_RS`, Fedora `sr_RS` and `sr_RS@latin`, and Latin ones may be Serbo-Croatian
/// (`sh_RS`, `sh_YU`). A dictionary of the other script is never used: it would flag every word.
#[test]
fn serbian_finds_the_dictionary_of_its_script() {
let dir = std::env::temp_dir().join(format!("deckcraft-dict-sr-{}", std::process::id()));
let stem = |names: &[&str], l: &str| {
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::create_dir_all(&dir);
for n in names {
let _ = std::fs::write(dir.join(format!("{n}.aff")), "");
let _ = std::fs::write(dir.join(format!("{n}.dic")), "");
}
find_in(std::slice::from_ref(&dir), l).and_then(|(a, _)| a.file_stem().map(|s| s.to_string_lossy().into_owned()))
};
let libreoffice = ["sr", "sr-Latn"];
assert_eq!(stem(&libreoffice, "sr-Cyrl-RS").as_deref(), Some("sr"));
assert_eq!(stem(&libreoffice, "sr-RS").as_deref(), Some("sr"));
assert_eq!(stem(&libreoffice, "sr-Latn-RS").as_deref(), Some("sr-Latn"));
let hunspell = ["sr_Latn_RS", "sr_RS"];
assert_eq!(stem(&hunspell, "sr-Cyrl-RS").as_deref(), Some("sr_RS"));
assert_eq!(stem(&hunspell, "sr-Latn-RS").as_deref(), Some("sr_Latn_RS"));
let fedora = ["sr_RS", "sr_RS@latin"];
assert_eq!(stem(&fedora, "sr-Cyrl-RS").as_deref(), Some("sr_RS"));
assert_eq!(stem(&fedora, "sr-Latn-RS").as_deref(), Some("sr_RS@latin"));
assert_eq!(stem(&["sr_RS@latin"], "sr-Cyrl-RS"), None);
// Serbo-Croatian dictionaries are Latin: they serve Serbian Latin, never Cyrillic.
assert_eq!(stem(&["sh_RS"], "sr-Latn-RS").as_deref(), Some("sh_RS"));
assert_eq!(stem(&["sh_YU"], "sr-Latn-RS").as_deref(), Some("sh_YU"));
assert_eq!(stem(&["sh"], "sr-Latn-RS").as_deref(), Some("sh"));
assert_eq!(stem(&["sh_RS"], "sr-Cyrl-RS"), None);
assert_eq!(stem(&["sh_RS", "sr"], "sr-RS").as_deref(), Some("sr"));
// A Serbian Latin dictionary comes before a Serbo-Croatian one.
assert_eq!(stem(&["sh_RS", "sr-Latn"], "sr-Latn-RS").as_deref(), Some("sr-Latn"));
assert_eq!(stem(&["sh", "sr_RS@latin"], "sr-Latn-RS").as_deref(), Some("sr_RS@latin"));
// Only the other script installed: no dictionary, so no marks, rather than every word.
assert_eq!(stem(&["sr"], "sr-Latn-RS"), None);
assert_eq!(stem(&["sr-Latn"], "sr-Cyrl-RS"), None);
// Languages in one script are unchanged.
assert_eq!(stem(&["de_DE"], "de-AT").as_deref(), Some("de_DE"));
let _ = std::fs::remove_dir_all(&dir);
}
/// The script is read from a script subtag or a `@latin`/`@cyrillic` modifier, in tags and
/// dictionary names alike; a variant, a region or another suffix is not a script.
#[test]
fn a_script_is_read_only_from_a_script_subtag() {
let script = |n| named_script(n);
assert_eq!(script("sr-Cyrl").as_deref(), Some("cyrl"));
assert_eq!(script("sr-Cyrl-RS").as_deref(), Some("cyrl"));
assert_eq!(script("sr-Latn").as_deref(), Some("latn"));
assert_eq!(script("sr_Latn_RS").as_deref(), Some("latn"));
assert_eq!(script("sr_RS@latin").as_deref(), Some("latn"));
assert_eq!(script("sr_RS@cyrillic").as_deref(), Some("cyrl"));
for none in ["sr", "sr-RS", "sr_RS", "de-1996", "de_DE", "en_US-wiki", "en-GB-oxendict", "zh-Hans"] {
assert_eq!(script(none), None, "{none}");
}
// Plain Serbian, with no script, is Cyrillic.
assert!(same_script("sr", "sr", "sr") && same_script("sr-RS", "sr_Cyrl_RS", "sr"));
assert!(!same_script("sr", "sr-Latn", "sr"));
}
}
+39
View File
@@ -7297,6 +7297,45 @@ fn master_body_placeholder_format_keeps_per_level_formatting() {
assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]);
}
#[test]
fn table_edits_past_the_cell_cap_are_refused_not_trimmed() {
use deckcraft_model::table::{MAX_CELLS, Row};
let mut s = session();
let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
let cols = 200;
let rows = MAX_CELLS / cols;
let big = deckcraft_model::Table {
cols: vec![1.0; cols],
rows: vec![Row { height: 1.0, cells: vec![Default::default(); cols] }; rows],
..Default::default()
};
for sl in std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).slides.iter_mut() {
for sh in std::sync::Arc::make_mut(sl).shapes.iter_mut() {
if sh.id == id {
sh.kind = deckcraft_model::ShapeKind::Table(big.clone());
}
}
}
for cmd in ["table.insertRowAbove", "table.insertRowBelow"] {
let e = s.execute(cmd, &json!({"id": id.0, "row": 0})).unwrap_err().to_string();
assert!(e.contains("cell limit"), "{cmd}: {e}");
}
let e = s.execute("table.insertColumnLeft", &json!({"id": id.0, "col": 0})).unwrap_err().to_string();
assert!(e.contains("cell limit"), "{e}");
assert_eq!(table_of(&s, id), big, "a refused insert leaves every row in place");
// A table already over the cap is refused too, not trimmed behind a success.
let huge = deckcraft_model::Table { rows: vec![Row { height: 1.0, cells: vec![Default::default(); cols] }; rows + 1], ..big.clone() };
for sl in std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).slides.iter_mut() {
for sh in std::sync::Arc::make_mut(sl).shapes.iter_mut() {
if sh.id == id {
sh.kind = deckcraft_model::ShapeKind::Table(huge.clone());
}
}
}
assert!(s.execute("table.deleteRow", &json!({"id": id.0, "row": 0})).is_err());
assert_eq!(table_of(&s, id).n_rows(), rows + 1);
}
/// #2059: Decrease Font Size (Ctrl+[, Cmd+Shift+,) steps down one size at a time from any size:
/// PowerPoint's list up to 96, then 8 points at a time above it, as Increase Font Size steps up.
/// A size above 66 used to shrink straight to 66.
+23 -22
View File
@@ -35,6 +35,8 @@ pub(crate) fn probe_fits(b: &[u8]) -> bool {
}
}
use craft_media::isobmff::boxes::BoxIter;
fn be32(b: &[u8], at: usize) -> Option<u64> {
b.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as u64)
}
@@ -43,37 +45,28 @@ fn boxes_fit(b: &[u8], file_len: u64, depth: u32) -> bool {
if depth > 16 {
return false;
}
let mut at = 0usize;
while b.len() - at >= 8 {
let Some(size32) = be32(b, at) else { return false };
let kind = &b[at + 4..at + 8];
let (header, size) = match size32 {
0 => (8, (b.len() - at) as u64),
1 => match b.get(at + 8..at + 16) {
Some(s) => (16, u64::from_be_bytes(s.try_into().unwrap_or_default())),
None => return false,
},
n => (8, n),
};
if size < header as u64 || size > (b.len() - at) as u64 {
let mut iter = if depth == 0 { BoxIter::new(b).allow_truncated() } else { BoxIter::new(b) };
while let Some(item) = iter.next() {
// Fewer than 8 trailing bytes are not a box header; symphonia stops there.
let Ok(bx) = item else { return b.len().saturating_sub(iter.offset()) < 8 };
let kind = &bx.kind.0;
if bx.truncated {
// A box that runs past the end of the file is fine at the top level (the file was cut
// short; symphonia stops there), but never inside a parent.
return depth == 0 && !matches!(kind, b"moov" | b"moof");
// short; symphonia stops there), but never inside a parent (the iterator rejects it there) or for `moov` / `moof`.
return !matches!(kind, b"moov" | b"moof");
}
let body = &b[at + header..at + size as usize];
let ok = if CONTAINERS.iter().any(|c| c.as_slice() == kind) {
boxes_fit(body, file_len, depth + 1)
let ok = if CONTAINERS.contains(&kind) {
boxes_fit(bx.payload, file_len, depth + 1)
} else if kind == b"meta" {
// ISO `meta` is a full box (4 bytes of version and flags first); QuickTime's is not.
let skip = if be32(body, 0) == Some(0) { 4 } else { 0 };
boxes_fit(&body[skip.min(body.len())..], file_len, depth + 1)
let skip = if be32(bx.payload, 0) == Some(0) { 4 } else { 0 };
boxes_fit(&bx.payload[skip.min(bx.payload.len())..], file_len, depth + 1)
} else {
table_fits(kind, body, file_len)
table_fits(kind, bx.payload, file_len)
};
if !ok {
return false;
}
at += size as usize;
}
true
}
@@ -122,4 +115,12 @@ mod tests {
let far = [&vec![0u8; PROBE_SEARCH_LIMIT + 16][..], &mp4].concat();
assert!(probe_fits(&far), "past the probe window symphonia never reads it as an MP4");
}
#[test]
fn short_tails_and_cut_top_level_boxes() {
let ftyp = [&16u32.to_be_bytes()[..], b"ftyp", b"isom", &[0; 4]].concat();
assert!(tables_fit(&[&ftyp[..], &[0, 0, 1]].concat()));
assert!(tables_fit(&[&ftyp[..], &100u32.to_be_bytes(), b"mdat"].concat()));
assert!(!tables_fit(&[&ftyp[..], &100u32.to_be_bytes(), b"moov"].concat()));
}
}
+1
View File
@@ -1362,6 +1362,7 @@ impl Chart {
.collect(),
kind: Some(ChartType::Line),
secondary_axis: true,
data_labels: Some(false),
..Default::default()
});
v.y2_min = Some(0.0);
+4
View File
@@ -626,6 +626,9 @@ pub struct Slide {
pub animations: Vec<Animation>,
/// Speaker notes.
pub notes: TextBody,
/// Whether the slide has an associated notes slide even if its text is empty.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub has_notes_slide: bool,
pub comments: Vec<Comment>,
/// `clrMapOvr`: a colour map replacing the layout's or master's (`bg1`→`dk1`…); None follows
/// the layout.
@@ -652,6 +655,7 @@ impl Default for Slide {
transition: None,
animations: vec![],
notes: TextBody::default(),
has_notes_slide: false,
comments: vec![],
color_map: None,
tags: vec![],
+186 -16
View File
@@ -83,6 +83,12 @@ impl Default for Table {
}
}
/// Cells a table may hold after [`Table::normalize`] (PowerPoint's own limit is 75 x 75).
pub const MAX_CELLS: usize = 100_000;
/// Cell visits [`Table::merge`] may spend growing its rectangle over existing merges: a few
/// passes over the largest grid, where a real table needs one or two.
const MAX_MERGE_WORK: usize = 16 * MAX_CELLS;
impl Table {
pub fn new(rows: usize, cols: usize, width: f64, row_height: f64) -> Self {
let rows = rows.clamp(1, 1000);
@@ -113,15 +119,24 @@ impl Table {
self.rows.iter().map(|r| r.height).sum()
}
/// Insert an empty row before `at`. A merge the new row falls inside grows to cover it.
pub fn insert_row(&mut self, at: usize) {
/// Returns false, leaving the table as it was, when the row would take it past [`MAX_CELLS`].
pub fn insert_row(&mut self, at: usize) -> bool {
if self.cols.len().saturating_mul(self.rows.len().saturating_add(1)) > MAX_CELLS {
return false;
}
let at = at.min(self.rows.len());
let merges = self.merges();
let h = self.rows.get(at.saturating_sub(1)).map(|r| r.height).unwrap_or(30.0);
self.rows.insert(at, Row { height: h, cells: (0..self.cols.len()).map(|_| Cell::new("")).collect() });
self.set_merges(merges.into_iter().map(|m| m.insert_row(at)));
true
}
/// Insert an empty column before `at`. A merge the new column falls inside grows to cover it.
pub fn insert_col(&mut self, at: usize) {
/// Returns false, leaving the table as it was, when the column would take it past [`MAX_CELLS`].
pub fn insert_col(&mut self, at: usize) -> bool {
if self.cols.len().saturating_add(1).saturating_mul(self.rows.len()) > MAX_CELLS {
return false;
}
let at = at.min(self.cols.len());
let merges = self.merges();
let w = self.cols.get(at.saturating_sub(1)).copied().unwrap_or(80.0);
@@ -131,6 +146,7 @@ impl Table {
r.cells.insert(i, Cell::new(""));
}
self.set_merges(merges.into_iter().map(|m| m.insert_col(at)));
true
}
/// Delete row `at`. Merges through it shrink; a merge anchored on it moves its anchor (and
/// text) to the next row it covers.
@@ -170,8 +186,12 @@ impl Table {
true
}
/// The merged areas: every uncovered cell spanning more than one cell, clipped to the grid.
/// Merges of a well-formed table do not overlap, so together they cover at most the grid; a
/// file's overlapping spans past that are dropped, so rebuilding them cannot revisit cells
/// without bound.
fn merges(&self) -> Vec<Merge> {
let (nr, nc) = (self.rows.len(), self.cols.len());
let mut area = nr.saturating_mul(nc);
let mut out = vec![];
for (r, row) in self.rows.iter().enumerate() {
for (c, cell) in row.cells.iter().enumerate().take(nc) {
@@ -180,7 +200,10 @@ impl Table {
}
let rs = (cell.row_span.max(1) as usize).min(nr - r);
let gs = (cell.grid_span.max(1) as usize).min(nc - c);
if rs > 1 || gs > 1 {
if (rs > 1 || gs > 1)
&& let Some(left) = area.checked_sub(rs.saturating_mul(gs))
{
area = left;
out.push(Merge { r, c, rs, gs });
}
}
@@ -233,9 +256,17 @@ impl Table {
if r1 >= self.rows.len() || c1 >= self.cols.len() || (r0 == r1 && c0 == c1) {
return false;
}
// Grow the rectangle until no existing merge sticks out of it.
// Grow the rectangle until no existing merge sticks out of it. Each pass reads the whole
// grid and may grow it by one row, so the passes are charged against
// [`MAX_MERGE_WORK`]: past it the merge is refused, before anything changed.
let (mut r0, mut c0, mut r1, mut c1) = (r0, c0, r1, c1);
let pass = self.rows.len().saturating_mul(self.cols.len()).max(1);
let mut work = 0usize;
loop {
work = work.saturating_add(pass);
if work > MAX_MERGE_WORK {
return false;
}
let before = (r0, c0, r1, c1);
for (r, row) in self.rows.iter().enumerate() {
for (c, cell) in row.cells.iter().enumerate().take(self.cols.len()) {
@@ -289,21 +320,50 @@ impl Table {
return false;
}
// Spans come from the file and may reach past the table; only walk the cells that exist.
for rr in r..r.saturating_add(rs).min(self.rows.len()) {
for cc in c..c.saturating_add(gs).min(self.cols.len()) {
if let Some(x) = self.cell_mut(rr, cc) {
x.h_merge = false;
x.v_merge = false;
x.grid_span = 1;
x.row_span = 1;
}
let end = r.saturating_add(rs).min(self.rows.len());
let gs = gs.min(self.cols.len().saturating_sub(c));
for row in self.rows.get_mut(r..end).unwrap_or_default() {
for x in row.cells.iter_mut().skip(c).take(gs) {
x.h_merge = false;
x.v_merge = false;
x.grid_span = 1;
x.row_span = 1;
}
}
true
}
/// Make every row have exactly `cols.len()` cells (repair after loading).
pub fn normalize(&mut self) {
/// Whether the grid is as [`Table::normalize`] leaves it: within [`MAX_CELLS`], every row
/// exactly `cols.len()` cells wide.
pub fn is_normalized(&self) -> bool {
let n = self.cols.len();
n <= MAX_CELLS && self.rows.len() <= (MAX_CELLS / n.max(1)).max(1) && self.rows.iter().all(|r| r.cells.len() == n)
}
/// Whether [`Table::normalize`] would drop rows or columns to fit [`MAX_CELLS`].
pub fn over_cap(&self) -> bool {
let n = self.cols.len();
n > MAX_CELLS || self.rows.len() > (MAX_CELLS / n.max(1)).max(1)
}
/// What [`Table::normalize`] would leave of this table, cloning only the rows and cells that
/// survive (an oversized table is not copied whole first).
pub fn normalized(&self) -> Table {
let n = self.cols.len().min(MAX_CELLS);
let keep = (MAX_CELLS / n.max(1)).max(1);
let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect();
let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self };
t.normalize();
if self.over_cap() {
t.clip_spans();
}
t
}
/// Make every row have exactly `cols.len()` cells (repair after loading). A grid over
/// [`MAX_CELLS`] loses its last rows (and columns) first, so a file naming many rows and many
/// columns but few cells cannot make this allocate their product.
pub fn normalize(&mut self) {
let truncated = self.over_cap();
self.cols.truncate(MAX_CELLS);
let n = self.cols.len();
self.rows.truncate((MAX_CELLS / n.max(1)).max(1));
for r in &mut self.rows {
r.cells.resize_with(n, || Cell::new(""));
for c in &mut r.cells {
@@ -311,6 +371,20 @@ impl Table {
c.row_span = c.row_span.max(1);
}
}
if truncated {
self.clip_spans();
}
}
/// Cut every merge span to the rows and columns that remain, so no merge reaches past a
/// table that lost rows or columns to the cell cap.
fn clip_spans(&mut self) {
let (nr, nc) = (self.rows.len(), self.cols.len());
for (ri, r) in self.rows.iter_mut().enumerate() {
for (ci, c) in r.cells.iter_mut().enumerate() {
c.row_span = c.row_span.min((nr - ri) as u32).max(1);
c.grid_span = c.grid_span.min((nc - ci) as u32).max(1);
}
}
}
}
@@ -519,6 +593,102 @@ mod tests {
}
}
/// Each cell spans two rows, uncovered: merging the last two rows would grow the rectangle a
/// row per pass over the whole grid, 10,000 passes. The merge is refused at its work bound
/// instead, leaving the table as it was; a small merge still works.
#[test]
fn merge_expansion_stops_at_its_work_bound() {
let mut t = Table::new(1_000, 10, 400.0, 30.0);
for row in &mut t.rows {
for c in &mut row.cells {
c.row_span = 2;
}
}
let before = t.clone();
assert!(!t.merge(998, 0, 999, 9));
assert_eq!(t, before);
let mut small = Table::new(4, 4, 400.0, 30.0);
assert!(small.merge(0, 0, 1, 1));
assert!(small.is_normalized() && !Table { cols: vec![1.0; 3], rows: vec![Row::default(); 2], ..Default::default() }.is_normalized());
}
#[test]
fn normalize_caps_a_sparse_grid_at_max_cells() {
// 1,000 columns and 1,000 empty rows would be a million cells.
let mut t = Table { cols: vec![10.0; 1000], rows: vec![Row::default(); 1000], ..Default::default() };
t.normalize();
assert_eq!(t.cols.len(), 1000);
assert_eq!(t.rows.len(), MAX_CELLS / 1000);
assert!(t.rows.iter().all(|r| r.cells.len() == 1000));
// Columns alone past the cap keep one row of MAX_CELLS cells.
let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() };
t.normalize();
assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1));
// `normalized` leaves what `normalize` does.
let wide = Table { cols: vec![10.0; 1000], rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1500] }; 150], ..Default::default() };
let mut n = wide.clone();
n.normalize();
assert_eq!(wide.normalized(), n);
// A normal table is untouched.
let mut t = Table::new(4, 4, 400.0, 30.0);
t.normalize();
assert_eq!((t.n_rows(), t.n_cols()), (4, 4));
}
#[test]
fn overlapping_file_spans_rebuild_in_bounded_work() {
// Every cell an uncovered anchor spanning to the far corner: their areas add up to about
// n^4 / 4, but only what fits the grid is kept, so an edit's rebuild stays near n^2.
let n = 200;
let mut t = Table::new(n, n, 400.0, 30.0);
for row in &mut t.rows {
for c in &mut row.cells {
c.grid_span = u32::MAX;
c.row_span = u32::MAX;
}
}
assert_eq!(t.merges().len(), 1, "the first anchor already covers the whole grid");
assert!(t.insert_row(n));
assert_eq!(t.n_rows(), n + 1);
assert!(t.split(0, 0));
}
/// A table at the cell cap refuses another row or column instead of losing rows to
/// normalization, and the cap sits above PowerPoint's own 75 x 75.
#[test]
fn insert_past_the_cap_is_refused() {
const { assert!(MAX_CELLS >= 75 * 75) };
let mut t =
Table { cols: vec![1.0; 200], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); 200] }; MAX_CELLS / 200], ..Default::default() };
assert!(!t.over_cap());
let before = t.clone();
assert!(!t.insert_row(0));
assert!(!t.insert_col(0));
assert_eq!(t, before);
assert!(Table::new(75, 75, 100.0, 10.0).insert_row(0));
}
/// A merge that crosses the truncation boundary is clipped to the rows and columns that remain.
#[test]
fn merges_are_clipped_when_the_cap_drops_rows() {
let cols = 1000;
let rows = MAX_CELLS / cols + 1;
let mut t = Table { cols: vec![1.0; cols], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); cols] }; rows], ..Default::default() };
t.rows[0].cells[0].row_span = rows as u32;
t.rows[0].cells[cols - 1].grid_span = 5;
let n = t.normalized();
assert_eq!(n.rows.len(), rows - 1);
assert_eq!(n.rows[0].cells[0].row_span as usize, rows - 1);
assert_eq!(n.rows[0].cells[cols - 1].grid_span, 1);
t.normalize();
assert_eq!(t.rows[0].cells[0].row_span as usize, rows - 1);
// Within the cap, spans are left as the file wrote them.
let mut small = Table::new(3, 3, 30.0, 10.0);
small.rows[2].cells[2].grid_span = 4;
small.normalize();
assert_eq!(small.rows[2].cells[2].grid_span, 4);
}
fn merged() -> Table {
// 4x4 with a 2x2 merge at (1,1) holding "M".
let mut t = Table::new(4, 4, 400.0, 30.0);
@@ -552,10 +722,10 @@ mod tests {
fn row_and_column_edits_keep_merges_consistent() {
for at in 0..=4 {
let mut t = merged();
t.insert_row(at);
assert!(t.insert_row(at));
assert_topology(&t);
let mut t = merged();
t.insert_col(at);
assert!(t.insert_col(at));
assert_topology(&t);
}
for at in 0..4 {
+3
View File
@@ -12,7 +12,10 @@ workspace = true
craft-opc.workspace = true
craft-xml.workspace = true
craft-cfb.workspace = true
craft-drawingml.workspace = true
craft-drawingml-table.workspace = true
deckcraft-model = { workspace = true }
deckcraft-text = { workspace = true }
deckcraft-geom = { workspace = true }
deckcraft-color = { workspace = true }
quick-xml = { workspace = true }
+16 -67
View File
@@ -348,73 +348,7 @@ fn arc_to(d: &mut String, cur: (f64, f64), wr: f64, hr: f64, st: f64, sw: f64) -
}
/// Parse our path syntax into commands.
pub fn parse_path(d: &str) -> Vec<(char, Vec<f64>)> {
let mut out = vec![];
let mut cmd: Option<char> = None;
let mut nums: Vec<f64> = vec![];
let flush = |cmd: Option<char>, nums: &mut Vec<f64>, out: &mut Vec<(char, Vec<f64>)>| {
if let Some(c) = cmd {
let n = match c {
'M' | 'L' => 2,
'C' => 6,
'Q' => 4,
_ => 0,
};
if n == 0 {
out.push((c, vec![]));
} else {
for (i, chunk) in nums.chunks(n).enumerate() {
if chunk.len() == n && out.len() < 1_000_000 {
// Repeated coordinates after M continue as L.
let c2 = if c == 'M' && i > 0 { 'L' } else { c };
out.push((c2, chunk.to_vec()));
}
}
}
}
nums.clear();
};
let mut token = String::new();
let push_tok = |token: &mut String, nums: &mut Vec<f64>| {
if !token.is_empty() {
if let Ok(v) = token.parse::<f64>()
&& v.is_finite()
{
nums.push(v);
}
token.clear();
}
};
let cs: Vec<char> = d.chars().collect();
for (i, &ch) in cs.iter().enumerate() {
match ch {
// An 'E' inside a number followed by a digit (or a sign and a digit) is an exponent,
// not the end command.
'E' if !token.is_empty() && {
let n1 = cs.get(i + 1).copied().unwrap_or(' ');
let n2 = cs.get(i + 2).copied().unwrap_or(' ');
n1.is_ascii_digit() || ((n1 == '-' || n1 == '+') && n2.is_ascii_digit())
} =>
{
token.push(ch)
}
'M' | 'L' | 'C' | 'Q' | 'Z' | 'm' | 'l' | 'c' | 'q' | 'z' | 'E' => {
push_tok(&mut token, &mut nums);
flush(cmd, &mut nums, &mut out);
cmd = Some(ch.to_ascii_uppercase());
}
' ' | ',' | '\t' | '\n' => push_tok(&mut token, &mut nums),
'-' if !token.is_empty() && !token.ends_with(['e', 'E']) => {
push_tok(&mut token, &mut nums);
token.push(ch);
}
c => token.push(c),
}
}
push_tok(&mut token, &mut nums);
flush(cmd, &mut nums, &mut out);
out
}
pub use craft_drawingml::custgeom::parse_path;
/// Write custom paths as `a:custGeom`. Coordinates are integers in the file, so small path spaces
/// are scaled up.
@@ -596,3 +530,18 @@ mod tests {
assert!(parse_path("garbage ### C 1").is_empty() || parse_path("garbage").is_empty());
}
}
#[cfg(test)]
mod shared_path_tests {
use super::parse_path;
#[test]
fn shared_path_tokens_preserve_exponents_repeats_and_dropped_tails() {
assert_eq!(
parse_path("M1E2 -3E-1 4 5 L6-7 Q8 9 10 11 Z"),
vec![('M', vec![100.0, -0.3]), ('L', vec![4.0, 5.0]), ('L', vec![6.0, -7.0]), ('Q', vec![8.0, 9.0, 10.0, 11.0]), ('Z', vec![]),]
);
assert_eq!(parse_path("M0 0 L1"), vec![('M', vec![0.0, 0.0])]);
assert_eq!(parse_path("MNaN 0 1 2"), vec![('M', vec![0.0, 1.0])]);
}
}
+6
View File
@@ -71,6 +71,12 @@ pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>), PptxE
read::import_checked(bytes)
}
/// [`import_checked`], plus warnings for content cut to fit a limit (a table past the cell cap
/// keeps its leading rows); the file still opens.
pub fn import_report(bytes: &[u8]) -> Result<(Presentation, Vec<String>, Vec<String>), PptxError> {
read::import_report(bytes)
}
/// [`import`] with a lower presentation-wide chart point budget, so tests reach the over-budget
/// path without a multi-million-point chart.
#[doc(hidden)]
+51 -7
View File
@@ -71,6 +71,8 @@ pub struct Imp<'a> {
pub tag_bytes: usize,
/// The tag budget ran out and the warning was given.
pub tags_capped: bool,
/// What the file lost that the reader kept going past (see [`MAX_IMPORT_WARNINGS`]).
pub warnings: Vec<String>,
/// Bytes of preserved theme XML kept by the masters read so far.
pub theme_extra_bytes: usize,
/// Shapes read from SmartArt drawings so far (see `shapes::MAX_SMARTART_SHAPES`).
@@ -82,7 +84,17 @@ pub struct Imp<'a> {
pub has_rels: HashMap<String, bool>,
}
/// Import warnings kept; a hostile file with many oversized tables adds no more than this.
const MAX_IMPORT_WARNINGS: usize = 32;
impl Imp<'_> {
/// Record something the file lost, and log it.
pub fn warn(&mut self, msg: String) {
log::warn!("pptx: {msg}");
if self.warnings.len() < MAX_IMPORT_WARNINGS {
self.warnings.push(msg);
}
}
pub fn alloc(&mut self) -> u32 {
self.next = self.next.saturating_add(1);
self.next
@@ -598,6 +610,7 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec<
tags_by_part: HashMap::new(),
tag_bytes: 0,
tags_capped: false,
warnings: vec![],
theme_extra_bytes: 0,
smartart_shapes: 0,
diagram_xml_bytes: 0,
@@ -616,13 +629,24 @@ pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
/// or truncated slide part, or an entry whose relationship is missing): those slides are left
/// out, so a caller can say so (#203).
pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>), PptxError> {
import_with_chart_points(bytes, chart::MAX_PRESENTATION_CHART_POINTS)
import_report(bytes).map(|(p, lost, _)| (p, lost))
}
/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a
/// table past the cell cap keeps its leading rows).
pub fn import_report(bytes: &[u8]) -> Result<(Presentation, Vec<String>, Vec<String>), PptxError> {
import_report_with_chart_points(bytes, chart::MAX_PRESENTATION_CHART_POINTS)
}
const MAX_SLIDE_ENTRIES: usize = 10_000;
/// [`import_checked`] with the presentation's chart point budget set (tests lower it).
pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> Result<(Presentation, Vec<String>), PptxError> {
import_report_with_chart_points(bytes, chart_points_cap).map(|(p, lost, _)| (p, lost))
}
/// [`import_report`] with the presentation's chart point budget set.
fn import_report_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> Result<(Presentation, Vec<String>, Vec<String>), PptxError> {
let mut lost_slides: Vec<String> = vec![];
let pkg = Package::open(bytes)?;
let root_rels = pkg.rels("");
@@ -663,6 +687,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) ->
tags_by_part: HashMap::new(),
tag_bytes: 0,
tags_capped: false,
warnings: vec![],
theme_extra_bytes: 0,
smartart_shapes: 0,
diagram_xml_bytes: 0,
@@ -697,7 +722,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) ->
p.media = std::mem::take(&mut imp.media);
p.next_id = imp.next;
p.fix_next_id();
Ok((p, lost_slides))
Ok((p, lost_slides, std::mem::take(&mut imp.warnings)))
}
/// Masters, layouts and slides to read, in file order and without duplicates: (master paths,
@@ -862,6 +887,7 @@ fn read_slides(
let mut slide = read_slide(imp, &part, doc, *id, layout);
if let Some(notes) = slide_notes(imp, &part, &mut owned_parts) {
slide.notes = notes;
slide.has_notes_slide = true;
}
read_slide_comments(pkg, pres_part, &part, &mut slide, &mut owned_parts);
file_slide_ids.insert(*file_id, *id);
@@ -1586,11 +1612,28 @@ fn header_footer(p: &Presentation) -> HeaderFooter {
Some(PhType::SlideNum) => hf.slide_number = true,
Some(PhType::Date) => {
hf.date = true;
if let Some(t) = &sh.text
&& !t.paragraphs.iter().flat_map(|p| &p.runs).any(|r| matches!(r.kind, deckcraft_model::text::RunKind::Field { .. }))
&& hf.date_text.is_empty()
{
hf.date_text = t.text();
let field = sh.text.iter().flat_map(|t| t.paragraphs.iter()).flat_map(|p| p.runs.iter()).find_map(|r| match &r.kind {
deckcraft_model::text::RunKind::Field { field } if deckcraft_text::datetime::is_date_field(field) => Some(field.as_str()),
_ => None,
});
match field {
// An automatic date: remember which of the thirteen formats it is, so the
// Header and Footer dialog opens on the deck's own choice instead of the
// default. An unknown spelling (`datetime`, `datetimeFigureOut`) is left
// as no choice rather than guessed at.
Some(kind) => {
if hf.date_format.is_empty() && deckcraft_text::datetime::DATE_KINDS.contains(&kind) {
hf.date_format = kind.to_string();
}
}
// A fixed date: its text, as before.
None => {
if hf.date_text.is_empty()
&& let Some(t) = &sh.text
{
hf.date_text = t.text();
}
}
}
}
Some(PhType::Footer) => {
@@ -1637,6 +1680,7 @@ mod rollback_tests {
tags_by_part: HashMap::new(),
tag_bytes: 0,
tags_capped: false,
warnings: vec![],
theme_extra_bytes: 0,
smartart_shapes: 0,
diagram_xml_bytes: 0,
+3
View File
@@ -856,6 +856,9 @@ fn table(imp: &mut Imp, part: &Part, tbl: &El) -> Table {
let n = t.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0);
t.cols = vec![72.0; n];
}
if t.over_cap() {
imp.warn(format!("a table in {} is over {} cells; its last rows were left out", part.name, deckcraft_model::table::MAX_CELLS));
}
t.normalize();
t
}
+120 -15
View File
@@ -57,14 +57,44 @@ struct Found<'a> {
group: usize,
/// Sum of the start delays of the time nodes between the click group and the effect, in ms.
offset: u32,
/// Whether any ancestor time node defers start until an event (`onClick`, `onEnd`, targeted `onBegin`) or nonzero delay.
deferred: bool,
}
/// Where `collect` is in the time tree: the click group and the delay accumulated inside it.
#[derive(Clone, Copy)]
struct At {
trigger: Option<u32>,
main_seq_id: Option<u32>,
group: usize,
offset: u32,
deferred: bool,
}
/// Returns whether `st` (`p:stCondLst`) is PowerPoint's automatic main-sequence step wrapper:
/// `<p:cond delay="indefinite"/>` paired only with `<p:cond evt="onBegin" delay="0"><p:tn val="{main_seq_id}"/></p:cond>`
/// referencing the immediate enclosing `mainSeq` `<p:cTn>`.
fn is_main_seq_auto(st: &El, main_seq_id: Option<u32>) -> bool {
let Some(ms_id) = main_seq_id else {
return false;
};
let is_indefinite = |d: &El| {
d.attr("evt").is_none()
&& d.attr("delay").map(str::trim) == Some("indefinite")
&& d.child("tgtEl").is_none()
&& d.child("tn").is_none()
&& d.child("rtn").is_none()
};
let is_main_seq_on_begin = |d: &El| {
d.attr("evt") == Some("onBegin")
&& d.attr("delay").map(str::trim) == Some("0")
&& d.child("tgtEl").is_none()
&& d.child("rtn").is_none()
&& d.child("tn").and_then(|tn| tn.u32("val")) == Some(ms_id)
};
st.children_named("cond").any(is_indefinite)
&& st.children_named("cond").any(is_main_seq_on_begin)
&& st.children_named("cond").all(|d| is_indefinite(d) || is_main_seq_on_begin(d))
}
fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec<Found<'a>>, depth: usize) {
@@ -73,7 +103,8 @@ fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec<Found<'a>>,
}
for c in e.elements() {
if c.is("cTn") && c.has_attr("presetClass") {
out.push(Found { ctn: c, trigger: at.trigger, group: at.group, offset: at.offset });
let deferred = at.deferred || c.child("stCondLst").is_some_and(defers_start);
out.push(Found { ctn: c, trigger: at.trigger, group: at.group, offset: at.offset, deferred });
continue;
}
let mut at = at;
@@ -82,17 +113,25 @@ fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec<Found<'a>>,
&& ctn.attr("nodeType") == Some("interactiveSeq")
{
at.trigger = ctn.path(&["stCondLst", "cond", "tgtEl", "spTgt"]).and_then(|s| s.u32("spid"));
at.main_seq_id = None;
}
if c.is("cTn")
&& let Some(cond) = c.path(&["stCondLst", "cond"])
{
if cond.attr("delay").map(str::trim) == Some("indefinite") {
*groups += 1;
at.group = *groups;
at.offset = 0;
} else {
at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0));
if c.is("cTn") {
let is_main_seq = c.attr("nodeType") == Some("mainSeq");
if let Some(st) = c.child("stCondLst") {
if !(!is_main_seq && !at.deferred && is_main_seq_auto(st, at.main_seq_id)) && defers_start(st) {
at.deferred = true;
}
if let Some(cond) = st.child("cond") {
if cond.attr("delay").map(str::trim) == Some("indefinite") {
*groups += 1;
at.group = *groups;
at.offset = 0;
} else {
at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0));
}
}
}
at.main_seq_id = if is_main_seq && !at.deferred { c.u32("id") } else { None };
}
collect(c, at, groups, out, depth + 1);
}
@@ -207,12 +246,44 @@ fn behaviour_auto_reverses(c: &El) -> bool {
/// Volume, mute, Loop until Stopped, Hide While Not Playing and Play Full Screen live in the timing tree
/// (`p:video`/`p:audio` > `p:cMediaNode`), not on the picture: copy them onto the target's `MediaClip`.
/// Returns whether `st` (`p:stCondLst`) defers playback instead of starting immediately on slide entry.
fn defers_start(st: &El) -> bool {
let is_auto_begin = |c: &El| {
c.attr("evt") == Some("onBegin")
&& c.attr("delay").map(str::trim) == Some("0")
&& c.child("tgtEl").is_none()
&& c.child("tn").is_none()
&& c.child("rtn").is_none()
};
let has_on_begin = st.children_named("cond").any(is_auto_begin);
st.children_named("cond")
.any(|c| (c.attr("evt").is_some() && !is_auto_begin(c)) || (!has_on_begin && c.attr("delay").map(str::trim) != Some("0")))
}
/// Applies `p:video`/`p:audio` timing node settings and main-sequence autoplay triggers to media shapes.
pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) {
let mut nodes = vec![];
for tag in ["video", "audio"] {
timing.find_all(tag, &mut nodes);
fn collect_media<'a>(e: &'a El, deferred: bool, out: &mut Vec<(&'a El, bool)>, depth: usize) {
if depth > 64 || out.len() >= 10_000 {
return;
}
let mut deferred = deferred;
if e.is("cTn")
&& let Some(st) = e.child("stCondLst")
&& defers_start(st)
{
deferred = true;
}
if e.is("video") || e.is("audio") {
out.push((e, deferred));
return;
}
for c in e.elements() {
collect_media(c, deferred, out, depth + 1);
}
}
for node in nodes.into_iter().take(10_000) {
let mut nodes = vec![];
collect_media(timing, false, &mut nodes, 0);
for (node, deferred) in nodes {
let Some(cm) = node.child("cMediaNode") else { continue };
let Some(id) = cm.path(&["tgtEl", "spTgt"]).and_then(|t| t.u32("spid")).and_then(|f| ctx.lookup(f)) else { continue };
let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind) else { continue };
@@ -228,10 +299,44 @@ pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) {
if cm.child("cTn").and_then(|c| c.attr("repeatCount")) == Some("indefinite") {
clip.loop_play = true;
}
if cm.child("cTn").and_then(|c| c.attr("fill")) == Some("remove") {
clip.rewind = true;
}
if cm.u32("numSld").is_some_and(|n| n > 1) {
clip.play_across_slides = true;
}
if !deferred && cm.path(&["cTn", "stCondLst", "cond"]).is_some_and(|c| c.attr("evt").is_none() && c.attr("delay").map(str::trim) == Some("0"))
{
clip.autoplay = true;
}
if node.bool("fullScrn") == Some(true) {
clip.full_screen = true;
}
}
let root_deferred = timing.path(&["tnLst", "par", "cTn", "stCondLst"]).is_some_and(defers_start);
if !root_deferred && let Some(tn) = timing.child("tnLst") {
let mut found = vec![];
collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0);
for f in found.into_iter().filter(|f| f.trigger.is_none()) {
let c = f.ctn;
if c.attr("nodeType") == Some("clickEffect") || f.deferred {
break;
}
let class = AnimClass::from_xml(c.attr("presetClass").unwrap_or("entr"));
let preset = c.u32("presetID").unwrap_or(0);
let effect = maps::effect_for_preset(class, preset).unwrap_or_else(|| maps::fallback_effect(class));
let delay = c.path(&["stCondLst", "cond"]).and_then(|d| ms_attr(d, "delay")).unwrap_or(0);
if class == AnimClass::Media
&& effect == "play"
&& f.offset == 0
&& delay == 0
&& let Some(id) = c.find("spTgt").and_then(|t| t.u32("spid")).and_then(|s| ctx.lookup(s))
&& let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind)
{
clip.autoplay = true;
}
}
}
}
/// Flatten the timing tree into the Animation Pane list.
@@ -239,7 +344,7 @@ pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes:
let _ = (imp, part);
let Some(tn) = timing.child("tnLst") else { return vec![] };
let mut found = vec![];
collect(tn, At { trigger: None, group: 0, offset: 0 }, &mut 0, &mut found, 0);
collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0);
// Paragraph builds (`bldP`) by (spid, grpId) -> whether `build="p"`.
let bld_p: std::collections::HashMap<(u32, String), bool> = timing
.child("bldLst")
+57 -244
View File
@@ -1,259 +1,72 @@
//! Table styles: our style ids ↔ table style GUIDs, and `tableStyles.xml` definitions for the
//! styles we write (generated from theme accents, matching how DeckCraft draws them).
//! Table style XML uses the shared writer; app XML admission remains unchanged.
pub use craft_drawingml::table::styles::{guid, guid_for_style, is_own_guid, style_from_guid};
use crate::opc::NS_A;
use crate::xml::{A, W};
/// Well-known built-in table style GUIDs (format identifiers) and our equivalent ids.
const KNOWN: &[(&str, &str)] = &[
("{2D5ABB26-0587-4C30-8999-92F81FD0307C}", "none"),
("{5940675A-B579-460E-94D1-54222C63F5DA}", "grid"),
("{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}", "medium2-accent1"),
("{073A0DAA-6AF3-43AB-8588-CEC1D06C72B9}", "medium2-tx1"),
("{21E4AEA4-8DFA-4A89-87EB-49C32662AFE8}", "medium2-accent2"),
("{F5AB1C69-6EDB-4FF4-983F-18BD219EF322}", "medium2-accent3"),
("{00A15C55-8517-42AA-B614-E9B94910E393}", "medium2-accent4"),
("{7DF18680-E054-41AD-8BC1-D1AEF772440D}", "medium2-accent5"),
("{93296810-A885-4BE3-A3E7-6D5BEEA58F35}", "medium2-accent6"),
];
/// GUIDs we write as built-in references (no definition needed).
const BUILTIN_WRITE: [&str; 3] = ["none", "grid", "medium2-accent1"];
fn fnv(s: &str, seed: u64) -> u64 {
let mut h = 0xcbf2_9ce4_8422_2325u64 ^ seed;
for b in s.bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec<u8> {
craft_drawingml_table::table::styles::table_styles_xml_with(used, defs.iter().map(|d| (d.id.as_str(), d.raw.as_str())), "DeckCraft", |raw| {
crate::xml::parse(raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle"))
})
}
/// A stable GUID derived from text (version-4 layout).
pub fn guid(text: &str) -> String {
let a = fnv(text, 0x5163_7261_6674);
let b = fnv(text, 0x7461_626c_6573);
format!(
"{{{:08X}-{:04X}-4{:03X}-8{:03X}-{:012X}}}",
(a >> 32) as u32,
(a >> 16) as u16,
(a & 0x0fff) as u16,
(b >> 48) as u16 & 0x0fff,
b & 0xffff_ffff_ffff
)
}
#[cfg(test)]
#[path = "tables_legacy.rs"]
mod legacy;
#[cfg(test)]
fn own_guid(style: &str) -> String {
guid(&format!("deckcraft-table-style:{style}"))
}
/// Is `g` the GUID DeckCraft writes for one of its own styles?
pub fn is_own_guid(g: &str) -> bool {
let up = g.to_ascii_uppercase();
deckcraft_model::table::table_styles().iter().any(|(id, _)| own_guid(id) == up)
}
/// Table style GUID → our style id (or the GUID itself when unknown).
pub fn style_from_guid(g: &str) -> String {
let up = g.to_ascii_uppercase();
if let Some((_, s)) = KNOWN.iter().find(|(k, _)| *k == up) {
return s.to_string();
}
for (id, _) in deckcraft_model::table::table_styles() {
if own_guid(&id) == up {
return id;
}
}
if g.is_empty() { "none".into() } else { g.to_string() }
}
/// GUID to write for our style id, and whether a definition must be written.
pub fn guid_for_style(style: &str) -> (String, bool) {
if style.starts_with('{') {
return (style.to_string(), false);
}
if BUILTIN_WRITE.contains(&style)
&& let Some((g, _)) = KNOWN.iter().find(|(_, s)| *s == style)
{
return (g.to_string(), false);
}
let known = deckcraft_model::table::table_styles().iter().any(|(id, _)| id == style);
if known { (own_guid(style), true) } else { ("{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}".into(), false) }
}
fn clr(w: &mut W, slot: &str, mods: &[(&str, i32)]) {
if mods.is_empty() {
w.val("a:schemeClr", slot);
return;
}
w.open("a:schemeClr", A::new().a("val", slot));
for (n, v) in mods {
w.val(n, v);
}
w.close("a:schemeClr");
}
fn solid(w: &mut W, slot: &str, mods: &[(&str, i32)]) {
w.open0("a:fill");
w.open0("a:solidFill");
clr(w, slot, mods);
w.close("a:solidFill");
w.close("a:fill");
}
fn borders(w: &mut W, b: Option<(&str, &[(&str, i32)], i32)>) {
w.open0("a:tcBdr");
if let Some((slot, mods, width)) = b {
for side in ["a:left", "a:right", "a:top", "a:bottom", "a:insideH", "a:insideV"] {
w.open0(side);
w.open("a:ln", A::new().a("w", width).a("cmpd", "sng"));
w.open0("a:solidFill");
clr(w, slot, mods);
w.close("a:solidFill");
w.close("a:ln");
w.close(side);
}
}
w.close("a:tcBdr");
}
fn txt(w: &mut W, bold: bool, color: Option<&str>) {
w.open("a:tcTxStyle", A::new().o("b", bold.then_some("on")));
w.open("a:fontRef", A::new().a("idx", "minor"));
w.val("a:prstClr", "black");
w.close("a:fontRef");
match color {
Some(c) => w.val("a:schemeClr", c),
None => w.val("a:schemeClr", "dk1"),
}
w.close("a:tcTxStyle");
}
/// Write one `a:tblStyle` for our style id.
fn style_def(w: &mut W, id: &str, name: &str) {
let kind = id.split('-').next().unwrap_or("medium2");
let acc = match id.rsplit('-').next().unwrap_or("accent1") {
"tx1" => "dk1",
a if a.starts_with("accent") => a,
_ => "accent1",
};
let acc: &str = acc;
w.open("a:tblStyle", A::new().a("styleId", own_guid(id)).a("styleName", name));
let part =
|w: &mut W, tag: &str, bold: bool, text: Option<&str>, fill: Option<(&str, &[(&str, i32)])>, bdr: Option<(&str, &[(&str, i32)], i32)>| {
w.open0(tag);
if bold || text.is_some() {
txt(w, bold, text);
}
w.open0("a:tcStyle");
borders(w, bdr);
if let Some((s, m)) = fill {
solid(w, s, m);
}
w.close("a:tcStyle");
w.close(tag);
};
match kind {
"grid" => {
part(w, "a:wholeTbl", false, Some("dk1"), None, Some(("dk1", &[], 9525)));
}
"light1" => {
part(w, "a:wholeTbl", false, Some("dk1"), None, None);
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 20000)])), None);
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 20000)])), None);
part(w, "a:lastCol", true, None, None, None);
part(w, "a:firstCol", true, None, None, None);
part(w, "a:lastRow", true, None, None, None);
part(w, "a:firstRow", true, None, None, Some((acc, &[], 12700)));
}
"light2" => {
part(w, "a:wholeTbl", false, Some("dk1"), None, Some((acc, &[], 12700)));
// Schema order: … lastCol, firstCol, lastRow, …, firstRow.
part(w, "a:firstCol", true, None, None, None);
part(w, "a:lastRow", true, None, None, None);
part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), Some((acc, &[], 12700)));
}
"dark1" => {
part(w, "a:wholeTbl", false, Some("lt1"), Some((acc, &[("a:shade", 75000)])), Some(("lt1", &[], 12700)));
part(w, "a:band1H", false, None, Some((acc, &[("a:shade", 60000)])), None);
part(w, "a:band1V", false, None, Some((acc, &[("a:shade", 60000)])), None);
part(w, "a:firstCol", true, None, None, None);
part(w, "a:lastRow", true, None, None, None);
part(w, "a:firstRow", true, Some("lt1"), Some(("dk1", &[])), None);
}
"medium4" => {
part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some((acc, &[], 9525)));
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None);
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None);
part(w, "a:lastCol", true, None, None, None);
part(w, "a:firstCol", true, None, None, None);
part(w, "a:lastRow", true, None, None, None);
part(w, "a:firstRow", true, None, Some((acc, &[("a:tint", 40000)])), None);
}
_ => {
// medium2
part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some(("lt1", &[], 12700)));
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None);
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None);
part(w, "a:lastCol", true, Some("lt1"), Some((acc, &[])), None);
part(w, "a:firstCol", true, Some("lt1"), Some((acc, &[])), None);
part(w, "a:lastRow", true, Some("lt1"), Some((acc, &[])), None);
part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), None);
}
}
w.close("a:tblStyle");
}
/// `ppt/tableStyles.xml` with definitions for the styles in `used`: ours, generated, and those the
/// opened file defined (`defs`), written back as they were read.
pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec<u8> {
let mut w = W::new();
w.open("a:tblStyleLst", A::new().a("xmlns:a", NS_A).a("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"));
let names = deckcraft_model::table::table_styles();
// Indexes instead of scans: written ids (as given and ASCII lower-case), and the file's
// definitions by lower-case id (the first wins).
let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new();
let mut done_lower: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut def_of: std::collections::HashMap<String, &deckcraft_model::table::TableStyleDef> = std::collections::HashMap::new();
for d in defs {
def_of.entry(d.id.to_ascii_lowercase()).or_insert(d);
}
for s in used {
if !done.insert(s.as_str()) {
continue;
}
done_lower.insert(s.to_ascii_lowercase());
if let Some(d) = def_of.get(&s.to_ascii_lowercase())
&& crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle"))
{
w.raw(&d.raw);
continue;
}
let (_, define) = guid_for_style(s);
if !define {
continue;
}
let name = names.iter().find(|(id, _)| id == s).map(|(_, n)| format!("DeckCraft {n}")).unwrap_or_else(|| s.clone());
style_def(&mut w, s, &name);
}
// Styles the file defined but no table uses still belong to the deck.
for d in defs {
if done_lower.contains(&d.id.to_ascii_lowercase()) {
continue;
}
if crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) {
done_lower.insert(d.id.to_ascii_lowercase());
w.raw(&d.raw);
}
}
w.close("a:tblStyleLst");
w.finish()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shared_writer_matches_legacy_bytes_and_admission() {
use deckcraft_model::table::TableStyleDef;
let mut used: Vec<String> = deckcraft_model::table::table_styles().into_iter().map(|(id, _)| id).collect();
used.extend(["unknown<&\"".into(), "Custom".into(), "Custom".into(), "CUSTOM".into()]);
for raw in [
"<a:tblStyle xmlns:a=\"urn:test\"/>",
"<tblStyle>", // Existing lenient partial-root policy.
"<tblStyle></other><trailing/>",
"<!--prefix--><tblStyle name=\"&amp;\"/>",
"<notAStyle/>",
"",
"<tblStyle><child/></tblStyle>",
] {
let defs = vec![
TableStyleDef { id: "custom".into(), raw: raw.into(), ..Default::default() },
TableStyleDef { id: "CUSTOM".into(), raw: "<tblStyle second=\"1\"/>".into(), ..Default::default() },
TableStyleDef { id: "unused".into(), raw: "<tblStyle unused=\"1\"/>".into(), ..Default::default() },
];
for selection in [&used[..], &[][..]] {
assert_eq!(table_styles_xml(selection, &defs), legacy::table_styles_xml(selection, &defs), "{raw:?}");
}
}
for depth in [255, 256, 257] {
let raw = format!("{}{}", "<tblStyle>".repeat(depth), "</tblStyle>".repeat(depth));
let defs = [TableStyleDef { id: "custom".into(), raw, ..Default::default() }];
assert_eq!(table_styles_xml(&used, &defs), legacy::table_styles_xml(&used, &defs));
}
}
#[test]
fn shared_style_catalog_matches_deckcraft() {
assert_eq!(deckcraft_model::table::table_styles(), craft_drawingml::table::table_styles());
assert_eq!(style_from_guid(""), "none");
let custom = "{abcdef00-0000-0000-0000-000000000000}";
assert_eq!(style_from_guid(custom), custom);
assert_eq!(guid_for_style(custom), (custom.to_string(), false));
assert_eq!(guid_for_style("unknown"), guid_for_style("medium2-accent1"));
for (id, _) in deckcraft_model::table::table_styles() {
let generated = own_guid(&id);
assert!(is_own_guid(&generated.to_ascii_lowercase()));
if guid_for_style(&id).1 {
assert_eq!(guid_for_style(&id).0, generated);
}
}
}
#[test]
fn style_parts_follow_schema_order() {
const ORDER: [&str; 14] = [
+182
View File
@@ -0,0 +1,182 @@
//! Table styles: our style ids ↔ table style GUIDs, and `tableStyles.xml` definitions for the
//! styles we write (generated from theme accents, matching how DeckCraft draws them).
use crate::opc::NS_A;
use crate::xml::{A, W};
// Keep file-format identifiers in the shared DrawingML implementation. The local
// writer below still owns DeckCraft's table style definitions and XML policy.
pub use craft_drawingml::table::styles::{guid, guid_for_style};
fn own_guid(style: &str) -> String {
guid(&format!("deckcraft-table-style:{style}"))
}
fn clr(w: &mut W, slot: &str, mods: &[(&str, i32)]) {
if mods.is_empty() {
w.val("a:schemeClr", slot);
return;
}
w.open("a:schemeClr", A::new().a("val", slot));
for (n, v) in mods {
w.val(n, v);
}
w.close("a:schemeClr");
}
fn solid(w: &mut W, slot: &str, mods: &[(&str, i32)]) {
w.open0("a:fill");
w.open0("a:solidFill");
clr(w, slot, mods);
w.close("a:solidFill");
w.close("a:fill");
}
fn borders(w: &mut W, b: Option<(&str, &[(&str, i32)], i32)>) {
w.open0("a:tcBdr");
if let Some((slot, mods, width)) = b {
for side in ["a:left", "a:right", "a:top", "a:bottom", "a:insideH", "a:insideV"] {
w.open0(side);
w.open("a:ln", A::new().a("w", width).a("cmpd", "sng"));
w.open0("a:solidFill");
clr(w, slot, mods);
w.close("a:solidFill");
w.close("a:ln");
w.close(side);
}
}
w.close("a:tcBdr");
}
fn txt(w: &mut W, bold: bool, color: Option<&str>) {
w.open("a:tcTxStyle", A::new().o("b", bold.then_some("on")));
w.open("a:fontRef", A::new().a("idx", "minor"));
w.val("a:prstClr", "black");
w.close("a:fontRef");
match color {
Some(c) => w.val("a:schemeClr", c),
None => w.val("a:schemeClr", "dk1"),
}
w.close("a:tcTxStyle");
}
/// Write one `a:tblStyle` for our style id.
fn style_def(w: &mut W, id: &str, name: &str) {
let kind = id.split('-').next().unwrap_or("medium2");
let acc = match id.rsplit('-').next().unwrap_or("accent1") {
"tx1" => "dk1",
a if a.starts_with("accent") => a,
_ => "accent1",
};
let acc: &str = acc;
w.open("a:tblStyle", A::new().a("styleId", own_guid(id)).a("styleName", name));
let part =
|w: &mut W, tag: &str, bold: bool, text: Option<&str>, fill: Option<(&str, &[(&str, i32)])>, bdr: Option<(&str, &[(&str, i32)], i32)>| {
w.open0(tag);
if bold || text.is_some() {
txt(w, bold, text);
}
w.open0("a:tcStyle");
borders(w, bdr);
if let Some((s, m)) = fill {
solid(w, s, m);
}
w.close("a:tcStyle");
w.close(tag);
};
match kind {
"grid" => {
part(w, "a:wholeTbl", false, Some("dk1"), None, Some(("dk1", &[], 9525)));
}
"light1" => {
part(w, "a:wholeTbl", false, Some("dk1"), None, None);
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 20000)])), None);
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 20000)])), None);
part(w, "a:lastCol", true, None, None, None);
part(w, "a:firstCol", true, None, None, None);
part(w, "a:lastRow", true, None, None, None);
part(w, "a:firstRow", true, None, None, Some((acc, &[], 12700)));
}
"light2" => {
part(w, "a:wholeTbl", false, Some("dk1"), None, Some((acc, &[], 12700)));
// Schema order: … lastCol, firstCol, lastRow, …, firstRow.
part(w, "a:firstCol", true, None, None, None);
part(w, "a:lastRow", true, None, None, None);
part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), Some((acc, &[], 12700)));
}
"dark1" => {
part(w, "a:wholeTbl", false, Some("lt1"), Some((acc, &[("a:shade", 75000)])), Some(("lt1", &[], 12700)));
part(w, "a:band1H", false, None, Some((acc, &[("a:shade", 60000)])), None);
part(w, "a:band1V", false, None, Some((acc, &[("a:shade", 60000)])), None);
part(w, "a:firstCol", true, None, None, None);
part(w, "a:lastRow", true, None, None, None);
part(w, "a:firstRow", true, Some("lt1"), Some(("dk1", &[])), None);
}
"medium4" => {
part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some((acc, &[], 9525)));
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None);
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None);
part(w, "a:lastCol", true, None, None, None);
part(w, "a:firstCol", true, None, None, None);
part(w, "a:lastRow", true, None, None, None);
part(w, "a:firstRow", true, None, Some((acc, &[("a:tint", 40000)])), None);
}
_ => {
// medium2
part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some(("lt1", &[], 12700)));
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None);
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None);
part(w, "a:lastCol", true, Some("lt1"), Some((acc, &[])), None);
part(w, "a:firstCol", true, Some("lt1"), Some((acc, &[])), None);
part(w, "a:lastRow", true, Some("lt1"), Some((acc, &[])), None);
part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), None);
}
}
w.close("a:tblStyle");
}
/// `ppt/tableStyles.xml` with definitions for the styles in `used`: ours, generated, and those the
/// opened file defined (`defs`), written back as they were read.
pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec<u8> {
let mut w = W::new();
w.open("a:tblStyleLst", A::new().a("xmlns:a", NS_A).a("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"));
let names = deckcraft_model::table::table_styles();
// Indexes instead of scans: written ids (as given and ASCII lower-case), and the file's
// definitions by lower-case id (the first wins).
let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new();
let mut done_lower: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut def_of: std::collections::HashMap<String, &deckcraft_model::table::TableStyleDef> = std::collections::HashMap::new();
for d in defs {
def_of.entry(d.id.to_ascii_lowercase()).or_insert(d);
}
for s in used {
if !done.insert(s.as_str()) {
continue;
}
done_lower.insert(s.to_ascii_lowercase());
if let Some(d) = def_of.get(&s.to_ascii_lowercase())
&& crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle"))
{
w.raw(&d.raw);
continue;
}
let (_, define) = guid_for_style(s);
if !define {
continue;
}
let name = names.iter().find(|(id, _)| id == s).map(|(_, n)| format!("DeckCraft {n}")).unwrap_or_else(|| s.clone());
style_def(&mut w, s, &name);
}
// Styles the file defined but no table uses still belong to the deck.
for d in defs {
if done_lower.contains(&d.id.to_ascii_lowercase()) {
continue;
}
if crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) {
done_lower.insert(d.id.to_ascii_lowercase());
w.raw(&d.raw);
}
}
w.close("a:tblStyleLst");
w.finish()
}
+13 -6
View File
@@ -65,6 +65,8 @@ pub struct Exp<'a> {
n_kept: u32,
pub slide_parts: HashMap<SlideId, String>,
pub table_styles: Vec<String>,
/// A table past the cell cap was met; export fails rather than write a trimmed one.
pub table_over_cap: bool,
/// The ids in `table_styles`, for checking membership without a scan.
pub table_style_set: std::collections::HashSet<String>,
placeholder: Option<String>,
@@ -427,7 +429,7 @@ struct NotesMasterWrite {
fn notes_master_write(p: &Presentation) -> Option<NotesMasterWrite> {
let nm = p.notes_master.as_deref();
let kept = nm.filter(|m| !m.shapes.is_empty());
let has_notes = p.slides.iter().any(|s| !s.notes.is_empty());
let has_notes = p.slides.iter().any(|s| !s.notes.is_empty() || s.has_notes_slide);
if !has_notes && nm.is_none() {
return None;
}
@@ -558,6 +560,7 @@ pub fn export(p: &Presentation, main_ct: &str) -> Result<Vec<u8>, PptxError> {
n_kept: 0,
slide_parts: HashMap::new(),
table_styles: vec![],
table_over_cap: false,
table_style_set: Default::default(),
placeholder: None,
};
@@ -666,7 +669,7 @@ pub fn export(p: &Presentation, main_ct: &str) -> Result<Vec<u8>, PptxError> {
if let Some(lp) = layout_parts.get(&s.layout) {
so.rels.add("slideLayout", &opc::relative(&sname, lp), false);
}
if !s.notes.is_empty() {
if !s.notes.is_empty() || s.has_notes_slide {
let nname = format!("ppt/notesSlides/notesSlide{}.xml", i + 1);
so.rels.add("notesSlide", &opc::relative(&sname, &nname), false);
let mut no = Out::new(&nname);
@@ -766,6 +769,12 @@ pub fn export(p: &Presentation, main_ct: &str) -> Result<Vec<u8>, PptxError> {
root.add_new(&k.rel_type, &k.name, false);
}
x.pkg.rels("", &root);
if x.table_over_cap {
return Err(PptxError::Unsupported(format!(
"a table has more than {} cells; export refused rather than drop rows",
deckcraft_model::table::MAX_CELLS
)));
}
x.pkg.finish()
}
@@ -813,9 +822,7 @@ fn slide_xml(x: &mut Exp, o: &mut Out, s: &Slide, comment_rel: Option<&str>) ->
if let Some(t) = &s.transition {
timing::transition(&mut w, x, o, t);
}
if !s.animations.is_empty() {
timing::timing(&mut w, x, &s.animations, &s.shapes, &ids);
}
timing::timing(&mut w, x, &s.animations, &s.shapes, &ids);
slide_ext_list(&mut w, s.raw_ext.as_deref(), comment_rel);
w.close("p:sld");
w.finish()
@@ -1301,7 +1308,7 @@ fn app_xml(p: &Presentation) -> Vec<u8> {
);
w.elt("Application", "DeckCraft");
w.elt("Slides", &p.slides.len().to_string());
w.elt("Notes", &p.slides.iter().filter(|s| !s.notes.is_empty()).count().to_string());
w.elt("Notes", &p.slides.iter().filter(|s| !s.notes.is_empty() || s.has_notes_slide).count().to_string());
w.elt("HiddenSlides", &p.slides.iter().filter(|s| s.hidden).count().to_string());
if !p.props.company.is_empty() {
w.elt("Company", &p.props.company);
+2 -2
View File
@@ -724,8 +724,8 @@ fn frame_close(w: &mut W) {
}
fn table(w: &mut W, x: &mut Exp, o: &mut Out, t: &Table) {
let mut t = t.clone();
t.normalize();
x.table_over_cap |= t.over_cap();
let t = t.normalized();
w.open0("a:tbl");
let (guid, _) = crate::tables::guid_for_style(&t.style);
if x.table_style_set.insert(t.style.clone()) {
+60 -2
View File
@@ -592,7 +592,7 @@ fn shape_index<'a>(shapes: &'a [Shape], depth: usize, out: &mut std::collections
}
}
/// Write `p:timing` for a slide's animations.
/// Write `p:timing` for a slide's animations and media settings.
pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idmap: &IdMap) {
let mut grp_count: std::collections::HashMap<u32, u32> = Default::default();
let mut main: Vec<Eff> = vec![];
@@ -686,7 +686,8 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm
None => main.extend(effs),
}
}
if main.is_empty() && triggered.is_empty() {
let media = collect_media(shapes, idmap);
if main.is_empty() && triggered.is_empty() && media.is_empty() {
return;
}
let mut ids = Ids(0);
@@ -757,6 +758,9 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm
w.close("p:nextCondLst");
w.close("p:seq");
}
for (spid, clip) in &media {
write_media_node(w, &mut ids, *spid, clip);
}
w.close("p:childTnLst");
w.close("p:cTn");
w.close("p:par");
@@ -770,3 +774,57 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm
}
w.close("p:timing");
}
/// Collects media shapes on the slide that have non-default playback settings requiring a `p:video`/`p:audio` timing node.
fn collect_media<'a>(shapes: &'a [Shape], idmap: &IdMap) -> Vec<(u32, &'a deckcraft_model::MediaClip)> {
let mut media = Vec::new();
deckcraft_model::walk(shapes, &mut |shape, _| {
if let ShapeKind::Media(clip) = &shape.kind
&& (clip.autoplay
|| (clip.volume - 1.0).abs() > 1e-6
|| clip.hide_while_not_playing
|| clip.loop_play
|| clip.rewind
|| clip.play_across_slides
|| (clip.video && clip.full_screen))
&& let Some(spid) = idmap.get(shape.id)
{
media.push((spid, clip));
}
});
media
}
/// Writes a `p:video` or `p:audio` media timing node (`p:cMediaNode`) for a media shape.
fn write_media_node(w: &mut W, ids: &mut Ids, spid: u32, clip: &deckcraft_model::MediaClip) {
let tag = if clip.video { "p:video" } else { "p:audio" };
w.open(tag, A::new().t("fullScrn", clip.video && clip.full_screen));
let mut cm = A::new().a("vol", (clip.volume.clamp(0.0, 1.0) * 100_000.0).round() as u32);
if clip.volume <= 1e-6 {
cm = cm.t("mute", true);
}
if clip.hide_while_not_playing {
cm = cm.a("showWhenStopped", 0);
}
if clip.play_across_slides {
cm = cm.a("numSld", 999);
}
w.open("p:cMediaNode", cm);
w.open(
"p:cTn",
A::new()
.a("id", ids.next())
.a("fill", if clip.rewind { "remove" } else { "hold" })
.a("display", 0)
.o("repeatCount", clip.loop_play.then_some("indefinite")),
);
w.open0("p:stCondLst");
w.empty("p:cond", A::new().a("delay", if clip.autoplay { "0" } else { "indefinite" }));
w.close("p:stCondLst");
w.close("p:cTn");
w.open0("p:tgtEl");
w.empty("p:spTgt", A::new().a("spid", spid));
w.close("p:tgtEl");
w.close("p:cMediaNode");
w.close(tag);
}
+45
View File
@@ -0,0 +1,45 @@
//! The Header & Footer date through PPTX: an automatic date's format comes back on import, so the
//! dialog opens on the deck's own choice; a fixed date still comes back as its text.
use deckcraft_model::{Presentation, defaults};
use serde_json::json;
/// A deck whose Date placeholders are set up by the engine, exported and imported again.
fn round_trip(args: serde_json::Value) -> Presentation {
let mut s = deckcraft_engine::Session::with_new();
s.execute("design.headerFooter", &args).expect("headerFooter");
let p = s.doc().expect("doc").doc.clone();
let bytes = deckcraft_pptx::export(&p).expect("export");
deckcraft_pptx::import(&bytes).expect("import")
}
#[test]
fn an_automatic_dates_format_survives_a_round_trip() {
// A chosen format comes back as the remembered choice.
let q = round_trip(json!({"date": true, "dateFormat": "datetime5", "all": true}));
assert!(q.header_footer.date, "the date placeholder is there");
assert_eq!(q.header_footer.date_format, "datetime5", "the format is remembered");
assert_eq!(q.header_footer.date_text, "", "an automatic date has no fixed text");
// A different one, so the test cannot pass by always reading datetime5.
let q = round_trip(json!({"date": true, "dateFormat": "datetime11", "all": true}));
assert_eq!(q.header_footer.date_format, "datetime11");
// The default: no format asked for, so nothing to remember beyond the field itself.
let q = round_trip(json!({"date": true, "all": true}));
assert_eq!(q.header_footer.date_format, "datetime1", "the placeholder's own field is datetime1");
// A fixed date is text, not a field: its text comes back and no format is claimed.
let q = round_trip(json!({"date": true, "dateText": "4 July 1776", "all": true}));
assert_eq!(q.header_footer.date_text, "4 July 1776");
assert_eq!(q.header_footer.date_format, "", "a fixed date has no format");
}
#[test]
fn a_deck_without_a_date_placeholder_claims_no_format() {
let p = defaults::new_presentation(None);
let bytes = deckcraft_pptx::export(&p).expect("export");
let q = deckcraft_pptx::import(&bytes).expect("import");
assert!(!q.header_footer.date);
assert_eq!(q.header_footer.date_format, "");
}
+38
View File
@@ -288,6 +288,44 @@ fn unreadable_slide_is_reported() {
assert_eq!(deckcraft_pptx::import(&broken).expect("import").slides.len(), 1);
}
fn table_deck(rows: usize, cols: usize) -> deckcraft_model::Presentation {
use deckcraft_model::table::Row;
use deckcraft_model::{Shape, ShapeId, ShapeKind, Table, Xfrm};
let mut p = defaults::new_presentation(None);
let id = ShapeId(p.alloc_id().expect("ids"));
let t = Table { cols: vec![1.0; cols], rows: vec![Row { height: 1.0, cells: vec![Default::default(); cols] }; rows], ..Default::default() };
let slide = std::sync::Arc::make_mut(&mut p.slides[0]);
slide.shapes.push(Shape { id, name: "T".into(), xfrm: Some(Xfrm::new(0.0, 0.0, 10.0, 10.0)), kind: ShapeKind::Table(t), ..Default::default() });
p
}
/// A table past the cell cap opens with its leading rows and an import warning; saving one that
/// is over the cap is an error, never a silent trim.
#[test]
fn oversized_table_warns_on_import_and_refuses_export() {
let max = deckcraft_model::table::MAX_CELLS;
let cols = 1000;
let rows = max / cols;
// A table exactly at the cap round-trips with no warning.
let bytes = deckcraft_pptx::export(&table_deck(rows, cols)).expect("export at the cap");
let (_, _, warnings) = deckcraft_pptx::import_report(&bytes).expect("import");
assert!(warnings.is_empty(), "{warnings:?}");
// One more row in the file: kept truncated, and reported.
let mut es = entries(&bytes);
let slide = es.iter_mut().find(|(n, _)| n == "ppt/slides/slide1.xml").expect("slide1");
let xml = String::from_utf8(std::mem::take(&mut slide.1)).expect("utf8");
let start = xml.rfind("<a:tr ").expect("row");
let end = xml.rfind("</a:tr>").expect("row end") + "</a:tr>".len();
slide.1 = format!("{}{}{}", &xml[..end], &xml[start..end], &xml[end..]).into_bytes();
let (q, _, warnings) = deckcraft_pptx::import_report(&rezip(&es)).expect("import");
assert_eq!(warnings.len(), 1, "{warnings:?}");
let t = q.slides[0].shapes.iter().find_map(|s| if let deckcraft_model::ShapeKind::Table(t) = &s.kind { Some(t) } else { None }).expect("table");
assert_eq!((t.rows.len(), t.cols.len()), (rows, cols));
// A model table past the cap is refused on export.
let err = deckcraft_pptx::export(&table_deck(rows + 1, cols)).expect_err("over the cap");
assert!(err.to_string().contains("table"), "{err}");
}
/// Missing slide relationships must not turn a damaged deck into a clean partial load (#1910).
#[test]
fn missing_slide_relationships_are_reported() {
+126
View File
@@ -74,3 +74,129 @@ fn muted_audio_has_no_volume_and_other_clips_keep_theirs() {
assert_eq!(c[0].volume, 1.0);
assert_eq!((c[1].volume, c[1].loop_play, c[1].full_screen), (0.0, false, false));
}
#[test]
fn media_autoplay_respects_ancestor_conditions_and_delays() {
let immediate = clips(|v, a| {
format!(
r#"<p:par><p:cTn id="2" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:video><p:cMediaNode><p:cTn id="3" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cMediaNode></p:video></p:childTnLst></p:cTn></p:par><p:par><p:cTn id="4" fill="hold"><p:stCondLst><p:cond evt="onBegin" delay="0"/></p:stCondLst><p:childTnLst><p:audio><p:cMediaNode><p:cTn id="5" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{a}"/></p:tgtEl></p:cMediaNode></p:audio></p:childTnLst></p:cTn></p:par>"#
)
});
assert!(immediate[0].autoplay, "delay=0 ancestor allows autoplay");
assert!(immediate[1].autoplay, "untargeted onBegin delay=0 ancestor allows autoplay");
let delayed_and_onclick = clips(|v, a| {
format!(
r#"<p:par><p:cTn id="2" fill="hold"><p:stCondLst><p:cond delay="2000"/></p:stCondLst><p:childTnLst><p:video><p:cMediaNode><p:cTn id="3" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cMediaNode></p:video></p:childTnLst></p:cTn></p:par><p:par><p:cTn id="4" fill="hold"><p:stCondLst><p:cond evt="onClick" delay="0"/></p:stCondLst><p:childTnLst><p:audio><p:cMediaNode><p:cTn id="5" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{a}"/></p:tgtEl></p:cMediaNode></p:audio></p:childTnLst></p:cTn></p:par>"#
)
});
assert!(!delayed_and_onclick[0].autoplay, "delayed ancestor blocks autoplay");
assert!(!delayed_and_onclick[1].autoplay, "onClick ancestor blocks autoplay");
let targeted_tn_and_own_cond = clips(|v, a| {
format!(
r#"<p:par><p:cTn id="2" fill="hold"><p:stCondLst><p:cond evt="onBegin" delay="0"><p:tn val="2"/></p:cond></p:stCondLst><p:childTnLst><p:video><p:cMediaNode><p:cTn id="3" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cMediaNode></p:video></p:childTnLst></p:cTn></p:par><p:par><p:cTn id="4" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:audio><p:cMediaNode><p:cTn id="5" fill="hold"><p:stCondLst><p:cond evt="onBegin" delay="0"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{a}"/></p:tgtEl></p:cMediaNode></p:audio></p:childTnLst></p:cTn></p:par>"#
)
});
assert!(!targeted_tn_and_own_cond[0].autoplay, "targeted onBegin ancestor blocks autoplay");
assert!(!targeted_tn_and_own_cond[1].autoplay, "media cond with explicit evt is not autoplay");
let delayed_media_cond = clips(|v, _| {
format!(
r#"<p:par><p:cTn id="2" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:video><p:cMediaNode><p:cTn id="3" fill="hold"><p:stCondLst><p:cond delay="500"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cMediaNode></p:video></p:childTnLst></p:cTn></p:par>"#
)
});
assert!(!delayed_media_cond[0].autoplay, "non-zero media cond delay is not autoplay");
}
#[test]
fn media_only_slide_exports_and_round_trips_video_and_audio_timing_nodes() {
let mut p = defaults::new_presentation(None);
let video = p.add_media("clip.mp4", "video/mp4", b"video".to_vec()).expect("media");
let audio = p.add_media("clip.m4a", "audio/mp4", b"audio".to_vec()).expect("media");
let vid_id = ShapeId(p.alloc_id().expect("id"));
let aud_id = ShapeId(p.alloc_id().expect("id"));
let s0 = Arc::make_mut(&mut p.slides[0]);
s0.shapes.push(deckcraft_model::Shape {
id: vid_id,
name: "AutoplayVideo".into(),
xfrm: Some(Xfrm::new(40.0, 40.0, 200.0, 100.0)),
kind: ShapeKind::Media(MediaClip {
media: video,
video: true,
autoplay: true,
volume: 0.75,
hide_while_not_playing: true,
loop_play: true,
rewind: true,
play_across_slides: true,
full_screen: true,
..Default::default()
}),
..Default::default()
});
s0.shapes.push(deckcraft_model::Shape {
id: aud_id,
name: "ManualMutedAudio".into(),
xfrm: Some(Xfrm::new(40.0, 160.0, 200.0, 100.0)),
kind: ShapeKind::Media(MediaClip { media: audio, video: false, autoplay: false, volume: 0.0, loop_play: true, ..Default::default() }),
..Default::default()
});
let bytes = deckcraft_pptx::export(&p).expect("export");
let back = deckcraft_pptx::import(&bytes).expect("import");
let clips: Vec<&MediaClip> = back.slides[0]
.shapes
.iter()
.filter_map(|s| match &s.kind {
ShapeKind::Media(m) => Some(m),
_ => None,
})
.collect();
assert_eq!(clips.len(), 2);
assert!(
clips[0].video
&& clips[0].autoplay
&& clips[0].hide_while_not_playing
&& clips[0].loop_play
&& clips[0].rewind
&& clips[0].play_across_slides
&& clips[0].full_screen
);
assert!((clips[0].volume - 0.75).abs() < 1e-4);
assert!(
!clips[1].video
&& !clips[1].autoplay
&& clips[1].loop_play
&& !clips[1].rewind
&& !clips[1].play_across_slides
&& !clips[1].hide_while_not_playing
&& !clips[1].full_screen
);
assert_eq!(clips[1].volume, 0.0);
// Main-sequence automatic Play (mediacall) effect with indefinite media node also sets autoplay.
let main_seq_play = self::clips(|v, _| {
format!(
r#"<p:seq concurrent="1" nextAc="seek"><p:cTn id="2" dur="indefinite" nodeType="mainSeq"><p:childTnLst><p:par><p:cTn id="3" fill="hold"><p:stCondLst><p:cond delay="indefinite"/><p:cond evt="onBegin" delay="0"><p:tn val="2"/></p:cond></p:stCondLst><p:childTnLst><p:par><p:cTn id="4" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:par><p:cTn id="5" presetID="1" presetClass="mediacall" presetSubtype="0" fill="hold" nodeType="withEffect"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:cmd type="call" cmd="playFrom(0.0)"><p:cBhvr><p:cTn id="6" dur="1" fill="hold"/><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cBhvr></p:cmd></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:seq><p:video><p:cMediaNode><p:cTn id="7" fill="hold"><p:stCondLst><p:cond delay="indefinite"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cMediaNode></p:video>"#
)
});
assert!(main_seq_play[0].autoplay, "main-sequence automatic Play effect sets autoplay");
// An `indefinite` + `onBegin delay="0"` condition whose `<p:tn>` references a different
// click-dependent time node rather than the enclosing `mainSeq` must stay deferred.
let non_main_seq_tn_play = self::clips(|v, _| {
format!(
r#"<p:seq concurrent="1" nextAc="seek"><p:cTn id="2" dur="indefinite" nodeType="mainSeq"><p:childTnLst><p:par><p:cTn id="99" fill="hold"><p:stCondLst><p:cond delay="indefinite"/></p:stCondLst><p:childTnLst><p:par><p:cTn id="100" fill="hold"><p:stCondLst><p:cond evt="onClick" delay="0"/></p:stCondLst></p:cTn></p:par></p:childTnLst></p:cTn></p:par><p:par><p:cTn id="3" fill="hold"><p:stCondLst><p:cond delay="indefinite"/><p:cond evt="onBegin" delay="0"><p:tn val="99"/></p:cond></p:stCondLst><p:childTnLst><p:par><p:cTn id="4" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:par><p:cTn id="5" presetID="1" presetClass="mediacall" presetSubtype="0" fill="hold" nodeType="withEffect"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:cmd type="call" cmd="playFrom(0.0)"><p:cBhvr><p:cTn id="6" dur="1" fill="hold"/><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cBhvr></p:cmd></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:seq><p:video><p:cMediaNode><p:cTn id="7" fill="hold"><p:stCondLst><p:cond delay="indefinite"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cMediaNode></p:video>"#
)
});
assert!(!non_main_seq_tn_play[0].autoplay, "onBegin referencing non-mainSeq click-dependent node is not autoplay");
// Command-based Play beneath an onClick or onEnd ancestor must not set autoplay.
let deferred_cmd_play = self::clips(|v, a| {
format!(
r#"<p:par><p:cTn id="2" fill="hold"><p:stCondLst><p:cond evt="onClick" delay="0"/></p:stCondLst><p:childTnLst><p:par><p:cTn id="3" presetID="1" presetClass="mediacall" presetSubtype="0" fill="hold" nodeType="withEffect"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:cmd type="call" cmd="playFrom(0.0)"><p:cBhvr><p:cTn id="4" dur="1" fill="hold"/><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cBhvr></p:cmd></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:par><p:par><p:cTn id="5" fill="hold"><p:stCondLst><p:cond evt="onEnd" delay="0"><p:tn val="2"/></p:cond></p:stCondLst><p:childTnLst><p:par><p:cTn id="6" presetID="1" presetClass="mediacall" presetSubtype="0" fill="hold" nodeType="withEffect"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:cmd type="call" cmd="playFrom(0.0)"><p:cBhvr><p:cTn id="7" dur="1" fill="hold"/><p:tgtEl><p:spTgt spid="{a}"/></p:tgtEl></p:cBhvr></p:cmd></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:par><p:video><p:cMediaNode><p:cTn id="8" fill="hold" display="0"><p:stCondLst><p:cond delay="indefinite"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{v}"/></p:tgtEl></p:cMediaNode></p:video><p:audio><p:cMediaNode><p:cTn id="9" fill="hold" display="0"><p:stCondLst><p:cond delay="indefinite"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{a}"/></p:tgtEl></p:cMediaNode></p:audio>"#
)
});
assert!(!deferred_cmd_play[0].autoplay, "command-based Play under onClick ancestor is not autoplay");
assert!(!deferred_cmd_play[1].autoplay, "command-based Play under onEnd ancestor is not autoplay");
}
+48
View File
@@ -14,6 +14,31 @@ const NOTES: &str = "ppt/notesSlides/notesSlide1.xml";
/// label and plain text), a level-2 paragraph with buNone, and a closing plain line.
const NOTES_XML: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<p:notes xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang="sk-SK" b="1" dirty="0"/><a:t>Metodický prehľad</a:t></a:r></a:p><a:p><a:r><a:rPr lang="sk-SK" dirty="0"/><a:t>Žiaci pracujú vo dvojiciach.</a:t></a:r></a:p><a:p><a:pPr marL="285750" lvl="1" indent="-285750"><a:buFont typeface="Wingdings" panose="05000000000000000000" pitchFamily="2" charset="2"/><a:buChar char="&#167;"/></a:pPr><a:r><a:rPr lang="sk-SK" b="1" dirty="0"/><a:t>Cieľ: </a:t></a:r><a:r><a:rPr lang="sk-SK" dirty="0"/><a:t>vysvetliť cyklus</a:t></a:r></a:p><a:p><a:pPr marL="285750" lvl="1" indent="-285750"><a:buFont typeface="Wingdings" panose="05000000000000000000" pitchFamily="2" charset="2"/><a:buChar char="&#167;"/></a:pPr><a:r><a:rPr lang="sk-SK" i="1" dirty="0"/><a:t>Reflexia</a:t></a:r></a:p><a:p><a:pPr marL="285750" lvl="1" indent="-285750"><a:buNone/></a:pPr><a:r><a:rPr lang="sk-SK" dirty="0"/><a:t>Bez odrážky</a:t></a:r></a:p><a:p><a:r><a:rPr lang="sk-SK" dirty="0"/><a:t>Pomôcky: počítač</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:notes>"#;
const EMPTY_NOTES_XML: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<p:notes xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp></p:spTree></p:cSld></p:notes>"#;
fn empty_notes_deck() -> Vec<u8> {
let mut p = defaults::new_presentation(None);
Arc::make_mut(&mut p.slides[0]).notes = TextBody::from_text("placeholder");
let bytes = deckcraft_pptx::export(&p).expect("export");
let mut src = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip");
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
let mut found = false;
for i in 0..src.len() {
let mut f = src.by_index(i).expect("entry");
let name = f.name().to_string();
let mut data = vec![];
f.read_to_end(&mut data).expect("read");
if name == NOTES {
data = EMPTY_NOTES_XML.as_bytes().to_vec();
found = true;
}
out.start_file(name, zip::write::SimpleFileOptions::default()).expect("start");
out.write_all(&data).expect("write");
}
assert!(found, "the export has no {NOTES}");
out.finish().expect("finish").into_inner()
}
/// A deck with one notes slide, its notes replaced by [`NOTES_XML`].
fn deck() -> Vec<u8> {
@@ -80,3 +105,26 @@ fn notes_formatting_survives_a_round_trip() {
assert!(xml.contains(r#"lvl="1""#) && xml.contains(r#"marL="285750""#) && xml.contains(r#"indent="-285750""#), "{xml}");
assert!(xml.contains(r#"<a:buFont typeface="Wingdings""#) && xml.contains("<a:buChar") && xml.contains("<a:buNone/>"), "{xml}");
}
#[test]
fn empty_notes_slide_is_preserved_on_save_and_reopen() {
let raw = empty_notes_deck();
let p = deckcraft_pptx::import(&raw).expect("import");
assert!(p.slides[0].notes.is_empty(), "imported notes text is empty");
assert!(p.slides[0].has_notes_slide, "slide notes presence is captured");
let saved = deckcraft_pptx::export(&p).expect("export");
let mut z = zip::ZipArchive::new(Cursor::new(&saved)).expect("zip");
assert!(z.by_name(NOTES).is_ok(), "empty notes slide part is kept in saved package");
let mut rels_xml = String::new();
z.by_name("ppt/slides/_rels/slide1.xml.rels").expect("slide rels").read_to_string(&mut rels_xml).expect("read slide rels");
assert!(rels_xml.contains("notesSlide"), "slide points to notes slide: {rels_xml}");
let again = deckcraft_pptx::import(&saved).expect("reimport");
assert!(again.slides[0].notes.is_empty());
assert!(again.slides[0].has_notes_slide, "notes slide presence survives roundtrip");
let saved_again = deckcraft_pptx::export(&again).expect("export again");
let mut z2 = zip::ZipArchive::new(Cursor::new(saved_again)).expect("zip");
assert!(z2.by_name(NOTES).is_ok(), "empty notes slide part is kept on subsequent export");
}
+22
View File
@@ -494,6 +494,7 @@ fn draw_inner(ctx: &mut RenderContext, rctx: &Ctx, c: &Chart, frame: ChartFrame<
to_axis: &to_axis,
zero,
base,
text_color: text_col,
error_marks: &mut err_marks,
},
);
@@ -886,6 +887,7 @@ struct LineDrawing<'a, 'ctx> {
to_axis: &'a dyn Fn(bool, f64) -> f64,
zero: f64,
base: f64,
text_color: Rgba,
error_marks: &'a mut Vec<(f64, f64, f64, f64, bool)>,
}
@@ -914,10 +916,13 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
let col = if area_kind { series_fill(rctx, c, si, Some(s)) } else { series_line(rctx, c, si, s) };
let series_stats = s.error_bars.as_ref().map(|_| deckcraft_model::chart::SeriesStats::of(&s.values));
let mut pts = vec![];
// Each point's own value (not the stacked total), for its data label.
let mut values = vec![];
// Whether the series has any x value, found once rather than per point.
let any_x = s.x_values.iter().flatten().next().is_some();
for i in 0..ncat {
let Some(v) = s.values.get(i).copied().flatten() else { continue };
let own = v;
let v = if stacked {
let base_v = acc.get(i).copied().unwrap_or(0.0);
if let Some(a) = acc.get_mut(i) {
@@ -942,6 +947,7 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
err_marks.push((x, to_axis(sec, lo), to_axis(sec, hi), base * 0.4, s.error_bars.as_ref().is_some_and(|e| e.end_cap)));
}
pts.push(Point::new(x, to_axis(sec, v)));
values.push(own);
}
if pts.is_empty() {
continue;
@@ -969,6 +975,22 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) {
ctx.fill_path(&kurbo::Circle::new(*q, 3.5).to_path(0.1));
}
}
// A line series that asks for value labels (`c:dLbls/c:showVal`) shows each point's value
// just above it, as bars do theirs (#2066). Area series keep none (theirs sit inside the
// area), and scatter and bubble series, which also come here, are left as they were.
if matches!(kind, ChartType::Line | ChartType::LineMarkers | ChartType::StackedLine) && c.series_data_labels(s) {
let gap = base * 0.3 + 3.5;
for (q, v) in pts.iter().zip(&values) {
label(
ctx,
rctx,
m,
&c.data_label(s, *v),
Rect::new(q.x - 40.0, q.y - gap - base * 1.4, q.x + 40.0, q.y - gap),
LabelStyle { size: base * 0.9, align: Align::Center, anchor: Anchor::Bottom, col: draw.text_color, bold: false },
);
}
}
}
}
+3
View File
@@ -97,6 +97,9 @@ mod tests_wild;
#[cfg(test)]
mod tests_effect_holes;
#[cfg(test)]
mod tests_placed_group;
#[cfg(test)]
mod mt_tests {
use super::*;
+28 -4
View File
@@ -12,7 +12,10 @@ use crate::{SlideFields, shape_geometry, table};
/// One shape's text as drawn on the slide.
pub struct PlacedText {
pub layout: TextLayout,
/// Shape-local → slide points (text rotation included, flips not: see [`crate::text_transform`]).
/// Text-local → slide points (text rotation included, flips not: see [`crate::text_transform`]).
/// Text-local space is the shape's own space, except inside a group whose child coordinates
/// scale the shape: there the text is set at the shape's size on the slide, as the renderer
/// draws it, so font sizes and insets stay in points.
pub transform: Affine,
pub body: TextBody,
}
@@ -149,13 +152,15 @@ fn place(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, s: &Shape, parent:
ShapeKind::Chart(_) | ShapeKind::Ink { .. } => {}
_ => {
let Some(body) = s.text.as_ref().filter(|b| !b.is_empty()) else { return };
let tr = shape_geometry(s, x.w, x.h).text_rect;
place_text(out, rctx, fields, s.id, s, body, tr, m);
// Placed space is slide points, so `m` is also the shape's transform relative to them.
let (tw, th, tm) = text_space(m, m, depth, x.w, x.h);
let tr = shape_geometry(s, tw, th).text_rect;
place_text(out, rctx, fields, s.id, s, body, tr, tm);
}
}
}
/// Lay out `body` in text rect `tr` of shape `s` (shape-local → slide `m`) and record it and its hyperlinks.
/// Lay out `body` in text rect `tr` of shape `s` (text-local → slide `m`) and record it and its hyperlinks.
#[allow(clippy::too_many_arguments)]
fn place_text(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, owner: ShapeId, s: &Shape, body: &TextBody, tr: Rect, m: Affine) {
let layout = deckcraft_text::layout(rctx, s, body, &Opts { rect: tr, fields, prompt_color: None, no_shrink: false });
@@ -188,6 +193,25 @@ fn place_text(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, owner: ShapeId
out.texts.push(PlacedText { layout, transform: m, body: placed });
}
/// The size and transform a shape's text is set in. `rel` is the shape's transform relative to
/// slide points and `m` the one its text is drawn under; `depth` is its group nesting. Inside a
/// group whose child coordinates scale the shape, the text is set at the shape's size in slide
/// points under `m` with that scale taken out, so insets and font sizes stay in points; otherwise
/// in `w` × `h` under `m` itself.
pub(crate) fn text_space(rel: Affine, m: Affine, depth: usize, w: f64, h: f64) -> (f64, f64, Affine) {
let c = rel.as_coeffs();
let (sx, sy) = (c[0].hypot(c[1]), c[2].hypot(c[3]));
let ok = |k: f64| k.is_finite() && k > 1e-9;
if depth == 0 || !ok(sx) || !ok(sy) || ((sx - 1.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9) {
return (w, h, m);
}
let (tw, th) = (w * sx, h * sy);
if !tw.is_finite() || !th.is_finite() {
return (w, h, m);
}
(tw, th, m * Affine::scale_non_uniform(1.0 / sx, 1.0 / sy))
}
/// The hyperlink of the model run containing character `at` of paragraph `para`.
fn run_link(body: &TextBody, para: usize, at: usize) -> Option<Hyperlink> {
let p = body.paragraphs.get(para)?;
+1 -11
View File
@@ -368,17 +368,7 @@ impl Renderer {
/// insets and font sizes stay in points; otherwise `w`, `h` and `m` themselves.
fn text_space(&self, m: Affine, depth: usize, w: f64, h: f64) -> (f64, f64, Affine) {
let (_, rel) = self.line_space(m, depth);
let c = rel.as_coeffs();
let (sx, sy) = (c[0].hypot(c[1]), c[2].hypot(c[3]));
let ok = |k: f64| k.is_finite() && k > 1e-9;
if depth == 0 || !ok(sx) || !ok(sy) || ((sx - 1.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9) {
return (w, h, m);
}
let (tw, th) = (w * sx, h * sy);
if !tw.is_finite() || !th.is_finite() {
return (w, h, m);
}
(tw, th, m * Affine::scale_non_uniform(1.0 / sx, 1.0 / sy))
crate::placed::text_space(rel, m, depth, w, h)
}
/// A shape's geometry in its own `w` × `h` space, built at its size on the slide: inside a
+5 -3
View File
@@ -37,18 +37,20 @@ pub fn needs_filters(pres: &Presentation, slide: &Slide) -> bool {
any
}
/// Does the shape's text have a shadow or glow (on a run, in its list style, or in the master's
/// text styles it inherits)? Such text is blurred, which needs filters.
/// Does the shape's text have a shadow or glow (on a run, in its paragraph's `defRPr`, in its list
/// style, or in the master's or presentation's text styles it inherits)? Such text is blurred,
/// which needs filters.
fn text_has_effects(rctx: &Ctx, s: &Shape) -> bool {
use deckcraft_model::text::{ListStyle, RunProps};
let fx = |r: &RunProps| r.shadow.as_ref().is_some_and(|s| !s.inner) || r.glow.as_ref().is_some_and(|g| g.radius > 0.0);
let styled = |l: &ListStyle| l.levels.iter().flatten().any(|lv| fx(&lv.run));
let Some(t) = &s.text else { return false };
t.paragraphs.iter().any(|p| p.runs.iter().any(|r| fx(&r.props)) || fx(&p.end_props))
t.paragraphs.iter().any(|p| p.runs.iter().any(|r| fx(&r.props)) || fx(&p.end_props) || fx(&p.def_props))
|| styled(&t.list_style)
|| styled(&rctx.master.title_style)
|| styled(&rctx.master.body_style)
|| styled(&rctx.master.other_style)
|| styled(&rctx.pres.default_text_style)
}
/// Render slide `index` at `opts.scale` pixels per point. A panic inside the renderer becomes a
+144
View File
@@ -1239,6 +1239,39 @@ fn effect_text(set: impl Fn(&mut deckcraft_model::text::RunProps)) -> Presentati
deck_with(vec![sh])
}
/// Text whose glow comes only from its paragraph's `defRPr` needs the filters too: drawn on the
/// worker threads it panicked (vello_cpu has no filters there) and the slide came out blank.
#[test]
fn a_paragraph_default_text_glow_needs_filters() {
let mut sh = Shape { id: ShapeId(741), xfrm: Some(Xfrm::new(100.0, 100.0, 600.0, 300.0)), text_box: true, ..Default::default() };
let mut t = TextBody::from_text("IIII");
let p = &mut t.paragraphs[0];
p.runs[0].props.size = Some(100.0);
p.runs[0].props.fill = Some(deckcraft_model::style::Fill::solid(ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 0, 0))));
p.def_props.glow = Some(deckcraft_model::style::Glow { color: ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 255, 0)), radius: 8.0 });
sh.text = Some(t);
assert_green_glow_drawn_with_threads(&deck_with(vec![sh]));
}
/// Text whose glow comes only from the presentation's default text style (`p:defaultTextStyle`)
/// needs the filters too, or the threaded render panics and the slide comes out blank.
#[test]
fn a_presentation_default_text_style_glow_needs_filters() {
let mut deck = effect_text(|_| {});
let level = deck.default_text_style.levels[0].as_mut().expect("the default text style sets level 1");
level.run.glow = Some(deckcraft_model::style::Glow { color: ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 255, 0)), radius: 8.0 });
assert_green_glow_drawn_with_threads(&deck);
}
/// Asserts that `deck`'s first slide needs filters and that, rendered with worker threads
/// requested, its text shows a green glow halo rather than a blank slide.
fn assert_green_glow_drawn_with_threads(deck: &Presentation) {
assert!(needs_filters(deck, &deck.slides[0]));
let img = render_slide(deck, 0, &RenderOpts { scale: 1.0, threads: 4, ..Default::default() });
let halo = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[1] > 150 && p[0] < 120 && p[2] < 120).count();
assert!(halo > 300, "green halo pixels {halo}");
}
#[test]
fn text_glow_and_shadow_are_drawn() {
let count = |img: &Image, f: &dyn Fn(&[u8; 4]) -> bool| img.pixels.as_chunks::<4>().0.iter().filter(|px| f(px)).count();
@@ -3205,6 +3238,117 @@ fn pie_data_labels_take_the_chart_text_colour_when_it_has_one() {
assert!(count(&plain, &white) > count(&coloured, &white), "the labels were white before");
}
/// #2066: a line series that asks for value labels (`c:dLbls/c:showVal`, chart-wide or its own)
/// shows each point's value above it; with the chart's text red, the labels add red ink there.
/// Area series still draw none (their labels belong inside the area, not on a point).
#[test]
fn line_chart_value_labels_are_drawn_above_their_points() {
let draw = |kind: ChartType, labels: bool, own: bool| {
let mut c = Chart::sample(kind);
c.title = None;
c.legend = None;
c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0)));
if own {
c.series[0].data_labels = Some(labels);
} else {
c.data_labels = labels;
}
let sh = Shape { id: ShapeId(633), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() })
};
let red = |img: &Image| {
(0..400u32)
.flat_map(|x| (0..300u32).map(move |y| (x, y)))
.filter(|(x, y)| {
let p = img.pixel(*x, *y);
p[0] > 200 && p[1] < 60 && p[2] < 60
})
.count()
};
for kind in [ChartType::Line, ChartType::LineMarkers] {
let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false)));
assert!(on > off + 100, "{kind:?}: labels add red ink ({off} → {on})");
let own = red(&draw(kind, true, true));
assert!(own > off + 30, "{kind:?}: a series' own showVal shows its labels ({off} → {own})");
}
// Area series keep none, and scatter and bubble series (drawn by the same code) are unchanged.
for kind in [ChartType::Area, ChartType::Scatter, ChartType::Bubble] {
let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false)));
assert_eq!(on, off, "{kind:?}: no point labels");
}
}
/// The magenta pixels the labels add to a line chart of two series, only the second labelled,
/// with the chart's text magenta (no series, gridline or axis line is): its axis labels are
/// magenta too, so they are what the unlabelled chart has.
fn line_label_ink(kind: ChartType, first: f64, second: f64) -> (Image, Vec<(u32, u32)>) {
let off: std::collections::HashSet<_> = magenta_pixels(&line_label_render(kind, first, second, false)).into_iter().collect();
let img = line_label_render(kind, first, second, true);
let added = magenta_pixels(&img).into_iter().filter(|p| !off.contains(p)).collect();
(img, added)
}
fn line_label_render(kind: ChartType, first: f64, second: f64, labels: bool) -> Image {
let mut c = Chart::sample(ChartType::Line);
c.kind = kind;
c.title = None;
c.legend = None;
c.series.truncate(2);
c.series[0].values = vec![Some(first); 4];
c.series[1].values = vec![Some(second); 4];
c.series[1].data_labels = Some(labels);
c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 255)));
let sh = Shape { id: ShapeId(634), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() })
}
/// Magenta ink on white, its anti-aliased edges included.
fn is_magenta(p: [u8; 4]) -> bool {
p[0] > 200 && p[2] > 200 && p[1] < 200
}
fn magenta_pixels(img: &Image) -> Vec<(u32, u32)> {
(0..img.width).flat_map(|x| (0..img.height).map(move |y| (x, y))).filter(|(x, y)| is_magenta(img.pixel(*x, *y))).collect()
}
/// #2066: in a stacked line chart a point's label is its own value, not the running total it is
/// drawn at. The second series' 5s, stacked on 100s, are labels as wide as an unstacked series of
/// 5s, and far narrower than one of 105s (the width: the pixel columns the label ink covers).
#[test]
fn a_stacked_line_labels_each_point_with_its_own_value() {
let width = |kind, second| line_label_ink(kind, 100.0, second).1.iter().map(|(x, _)| *x).collect::<std::collections::HashSet<_>>().len();
let (stacked, fives, totals) = (width(ChartType::StackedLine, 5.0), width(ChartType::Line, 5.0), width(ChartType::Line, 105.0));
assert!(stacked > 0 && fives > 0, "labels are drawn ({stacked}, {fives})");
assert!(stacked.abs_diff(fives) <= 4, "stacked 5s are labelled \"5\" ({stacked} columns vs {fives} for 5s)");
assert!(stacked * 2 < totals, "not with the total \"105\" ({stacked} columns vs {totals} for 105s)");
}
/// #2066: a line label sits just above its point: all its ink is above the series' line, and
/// its lowest row is close to it.
#[test]
fn a_line_label_sits_just_above_its_point() {
let (img, ink) = line_label_ink(ChartType::Line, 20.0, 50.0);
assert!(!ink.is_empty(), "labels are drawn");
let cols: std::collections::HashSet<u32> = ink.iter().map(|(x, _)| *x).collect();
let (first, last) = (cols.iter().min().copied().unwrap(), cols.iter().max().copied().unwrap());
// The labelled series' flat line at 50: the topmost coloured pixel in the plot's columns
// between the labels (the other line is lower, at 20; the axis labels lie outside them).
let line_top = (first..last)
.filter(|x| !cols.iter().any(|c| c.abs_diff(*x) < 4))
.filter_map(|x| {
(0..img.height).find(|y| {
let p = img.pixel(x, *y);
let (hi, lo) = (p[0].max(p[1]).max(p[2]), p[0].min(p[1]).min(p[2]));
hi - lo > 80 && !is_magenta(p)
})
})
.min()
.unwrap();
let lowest = ink.iter().map(|(_, y)| *y).max().unwrap();
assert!(lowest < line_top, "the labels are above the line (lowest ink row {lowest}, line at {line_top})");
assert!(line_top - lowest < 20, "and just above it (lowest ink row {lowest}, line at {line_top})");
}
/// #1165: an ellipse sized at the EMU limit, crossing the slide, made vello's flattener allocate a
/// buffer from its on-screen length and abort. It is skipped; the rest of the slide still draws.
#[test]
+62
View File
@@ -0,0 +1,62 @@
//! `place_slide` sets the text of a shape inside a group whose child coordinates scale it the way
//! the slide draws it: at the shape's size on the slide, with font sizes and insets in points.
use super::{Fill, Point, place_slide};
use deckcraft_model::style::ColorRef;
use deckcraft_model::text::TextBody;
use deckcraft_model::{Presentation, Shape, ShapeId, ShapeKind, Xfrm};
/// A deck whose slide shows a shape at (100, 100), 400 × 200 points, with 24 pt black text: on its
/// own, or inside a group whose child space is `scale` times smaller than the group.
fn deck(scale: Option<f64>) -> Presentation {
let mut body = TextBody::from_text("Placed where it is drawn");
body.paragraphs[0].runs[0].props.size = Some(24.0);
body.paragraphs[0].runs[0].props.fill = Some(Fill::solid(ColorRef::rgb(deckcraft_color::Rgba::BLACK)));
let shape = match scale {
None => Shape { id: ShapeId(701), xfrm: Some(Xfrm::new(100.0, 100.0, 400.0, 200.0)), text: Some(body), ..Default::default() },
Some(k) => {
let child = Shape { id: ShapeId(701), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0 / k, 200.0 / k)), text: Some(body), ..Default::default() };
Shape {
id: ShapeId(700),
xfrm: Some(Xfrm::new(100.0, 100.0, 400.0, 200.0)),
kind: ShapeKind::Group { children: vec![child], child: Xfrm::new(0.0, 0.0, 400.0 / k, 200.0 / k) },
..Default::default()
}
}
};
let mut p = Presentation::default();
std::sync::Arc::make_mut(&mut p.slides[0]).shapes = vec![shape];
p
}
/// Each placed glyph: its id, its origin on the slide and its run's drawn size (the font size
/// times the scale of the text's transform).
fn glyphs_on_slide(p: &Presentation) -> Vec<(u32, Point, f64)> {
let placed = place_slide(p, 0);
let mut out = vec![];
for t in &placed.texts {
let k = t.transform.determinant().abs().sqrt();
for g in &t.layout.runs {
for &(gid, x, y) in &g.glyphs {
out.push((gid, t.transform * Point::new(x, y), g.size * k));
}
}
}
out
}
#[test]
fn text_in_a_scaled_group_is_placed_as_drawn() {
let plain = glyphs_on_slide(&deck(None));
assert!(!plain.is_empty());
assert!(plain.iter().all(|g| (g.2 - 24.0).abs() < 1e-6), "{plain:?}");
for scale in [1.0, 1600.0, 4.0, 0.25] {
let grouped = glyphs_on_slide(&deck(Some(scale)));
assert_eq!(grouped.len(), plain.len(), "scale {scale}");
for (a, b) in grouped.iter().zip(&plain) {
assert_eq!(a.0, b.0, "scale {scale}");
assert!((a.1 - b.1).hypot() < 0.01, "scale {scale}: glyph at {:?}, on its own at {:?}", a.1, b.1);
assert!((a.2 - b.2).abs() < 0.01, "scale {scale}: drawn at {} pt, on its own at {} pt", a.2, b.2);
}
}
}
+31
View File
@@ -1992,3 +1992,34 @@ fn signed_insets_are_preserved_when_they_fit() {
assert_eq!(l.lines.len(), 1);
assert_eq!(l.inner.x0, -10.0);
}
/// Each run is shaped in its own language (Review › Language), so a font's forms for that language
/// (OpenType `locl`) are drawn: the Serbian б, not the Russian one, in a Serbian run beside a
/// Russian run of the same word.
#[test]
fn serbian_runs_draw_the_fonts_serbian_forms() {
let b = |f: &FontFace, lang: &str| {
let params = deckcraft_fonts::ShapeParams { language: Some(lang), ..Default::default() };
deckcraft_fonts::shape_range(f, "б", 0.."б".len(), &params, |c| c).first().map(|g| g.gid)
};
let serbian_form = |f: &FontFace| b(f, "sr-Cyrl-RS") != b(f, "ru-RU");
let Some(family) = first_family(&["DejaVu Sans", "DejaVu Serif", "Source Sans 3", "Source Serif 4", "Noto Sans", "Noto Serif"], serbian_form)
else {
eprintln!("skipped: no font with a Serbian б");
return;
};
let run = |text: &str, lang: &str| {
let mut r = Run::new(text);
r.props.lang = Some(lang.into());
r.props.font = Some(family.clone());
r
};
let (p, sh) = bidi_setup(vec![run("грб ", "sr-Cyrl-RS"), run("грб", "ru-RU")], 2000.0, false, Align::Left);
let l = lay(&p, &sh, 2000.0, 300.0);
// Glyph of each paragraph character.
let at = |i: usize| l.runs.iter().find_map(|r| r.cells.iter().position(|&(k, _)| k == i).and_then(|g| r.glyphs.get(g)).map(|g| g.0));
// г р б, space, г р б: each б is the one its language gives.
let face = FontDb::global().face(&family, "Regular");
assert_eq!(at(2), b(&face, "sr-Cyrl-RS"), "{family}: the Serbian б");
assert_eq!(at(6), b(&face, "ru-RU"), "{family}: the Russian б");
}
+2 -1
View File
@@ -182,7 +182,7 @@ impl SlideApp {
format!("{name}.{ext}")
}
/// Exports the active presentation as `fmt` (`pdf`, `png`, `pngAll`, `jpeg`, `pptx`,
/// Exports the active presentation as `fmt` (`pdf`, `png`, `pngAll`, `jpeg`, `jpegAll`, `pptx`,
/// `deckcraft`, `outline`) through `file.export`: the save picker on the desktop, a download
/// on the web. `extra` adds `file.export` params (the PDF's layout, slides…). The
/// presentation keeps its own file. Returns whether a file was written or handed over.
@@ -193,6 +193,7 @@ impl SlideApp {
"png" => ("png", "png", false),
"pngAll" => ("png", "png", true),
"jpeg" | "jpg" => ("jpg", "jpeg", false),
"jpegAll" => ("jpg", "jpeg", true),
"pptx" => ("pptx", "pptx", false),
"outline" | "txt" => ("txt", "outline", false),
"rtf" => ("rtf", "rtf", false),
+5 -1
View File
@@ -2,7 +2,7 @@ use super::files::task;
use super::{Backstage, Icon, Outcome, Page, RichText, Sense, SlideApp, Tokens, Ui, Value, dim, heading, json, theme, vec2};
/// Save As and Change File Type: (id for [`SlideApp::export_as`], label, detail).
pub const SAVE_TYPES: [(&str, &str, &str); 7] = [
pub const SAVE_TYPES: [(&str, &str, &str); 9] = [
("pptx", "PowerPoint Presentation (*.pptx)", "Opens in PowerPoint and other presentation apps"),
("deckcraft", "DeckCraft Presentation (*.deckcraft)", "DeckCraft's own format: everything is kept"),
("pdf", "PDF (*.pdf)", "A fixed copy that keeps its layout on any device"),
@@ -10,6 +10,8 @@ pub const SAVE_TYPES: [(&str, &str, &str); 7] = [
("rtf", "Outline/RTF (*.rtf)", "The slide titles and bullet text for word processors"),
("png", "PNG Picture (*.png)", "The current slide as a picture"),
("jpeg", "JPEG Picture (*.jpg)", "The current slide as a compressed picture"),
("pngAll", "PNG Pictures, all slides (*.png)", "Every slide as its own picture"),
("jpegAll", "JPEG Pictures, all slides (*.jpg)", "Every slide as its own compressed picture"),
];
/// Info page properties: (`file.properties` key, label, hint).
@@ -156,6 +158,8 @@ pub(super) fn save_as(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, out:
ui.horizontal(|ui| {
craft_ui::ComboBox::from_id_salt("backstage_save_type")
.width(340.0)
// Every type in view: at the default height the last ones were behind a scroll.
.height(f32::INFINITY)
.selected_text(current)
.show_ui(ui, |ui| {
for (id, label, _) in SAVE_TYPES {
+1 -1
View File
@@ -357,7 +357,7 @@ pub(super) fn export(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
}
}
ui.add_space(12.0);
let png = bs.file_type == "png";
let png = matches!(bs.file_type, "png" | "pngAll");
if png {
ui.checkbox(&mut bs.png_transparent, "Transparent background")
.on_hover_text("Leave the slide background out: only what is on the slide is drawn");
+58
View File
@@ -349,6 +349,64 @@ fn change_file_type_png_can_leave_the_background_transparent() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Export › Change File Type exports every slide as its own picture, PNG or JPEG (#2019).
#[test]
fn change_file_type_exports_all_slides_as_pictures() {
let dir = temp_dir("all-slides");
let (services, asked) = saving_into(&dir);
let mut h = harness(SlideApp::new(Session::with_new(), services));
h.state_mut().run("slide.new", json!({})).unwrap();
h.state_mut().run("slide.new", json!({})).unwrap();
let title = h.state().session.active().unwrap().title();
h.state_mut().run("app.backstage", json!({"page": "export"})).unwrap();
h.run_steps(3);
click_on_page(&h, "Change File Type");
h.run_steps(3);
click_on_page(&h, "JPEG Pictures, all slides (*.jpg)");
h.run_steps(2);
assert!(h.query_by_label("Transparent background").is_none(), "JPEG has no transparency");
click_on_page(&h, "Save As");
h.run_steps(3);
for k in 1..=3 {
let jpg = std::fs::read(dir.join(format!("{title}{k}.jpg"))).unwrap();
assert!(jpg.starts_with(&[0xFF, 0xD8]), "slide {k} is a JPEG");
}
assert!(!dir.join(format!("{title}4.jpg")).exists(), "one picture per slide");
h.state_mut().run("app.backstage", json!({"page": "export"})).unwrap();
h.run_steps(3);
click_on_page(&h, "Change File Type");
h.run_steps(3);
click_on_page(&h, "PNG Pictures, all slides (*.png)");
h.run_steps(2);
h.get_by_label("Transparent background").click();
h.run_steps(2);
click_on_page(&h, "Save As");
h.run_steps(3);
for k in 1..=3 {
let png = std::fs::read(dir.join(format!("{title}{k}.png"))).unwrap();
let img = deckcraft_render::decode_image(&png).unwrap();
assert_eq!(img.get_pixel(2, 2).0[3], 0, "slide {k} leaves the background out");
}
assert_eq!(*asked.borrow(), vec![format!("{title}.jpg"), format!("{title}.png")]);
let _ = std::fs::remove_dir_all(&dir);
}
/// Save As shows every type in its open list: the last one is picked by a click, not hidden
/// below the list's default height (#2019).
#[test]
fn save_as_type_list_shows_every_type() {
let mut h = harness(new_app());
h.state_mut().run("app.backstage", json!({"page": "saveAs"})).unwrap();
h.run_steps(3);
h.get_by_label("Save as type").click();
h.run_steps(3);
let (last, label, _) = crate::backstage::SAVE_TYPES[crate::backstage::SAVE_TYPES.len() - 1];
h.get_by_label(label).click();
h.run_steps(3);
assert_eq!(h.state().backstage.as_ref().map(|b| b.file_type), Some(last));
}
/// Close closes a saved presentation at once and asks about unsaved changes first.
#[test]
fn close_closes_and_asks_about_unsaved_changes() {
+5
View File
@@ -152,6 +152,11 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let avail = ui.available_rect_before_wrap();
app.canvas_rect = Some(avail);
// The notes pane and the panes beside the canvas are editor chrome over it: nothing the
// canvas paints or hit-tests (the media bar hangs 6 pt below its clip, handles stick out of a
// shape, scroll bars) may reach into them. The parent's clip still covers the whole central
// area, so clip this `Ui` to the rect the canvas was given (#1922).
ui.set_clip_rect(avail.intersect(ui.clip_rect()));
let Some(st) = app.session.active() else { return };
// The leftover fraction of a wheel line belongs to one presentation. Drop it whenever another
// one is drawn here, hovered or not, so switching away and back starts from zero.
+2
View File
@@ -230,6 +230,8 @@ pub const LANGS: &[(&str, &str)] = &[
("Українська", "uk-UA"),
("Русский", "ru-RU"),
("Беларуская", "be-BY"),
("Српски (ћирилица)", "sr-Cyrl-RS"),
("Srpski (latinica)", "sr-Latn-RS"),
("Türkçe", "tr-TR"),
("Ελληνικά", "el-GR"),
("日本語", "ja-JP"),
+12 -2
View File
@@ -707,6 +707,9 @@ fn dlg_rename_section(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
ok || cancel
}
/// Export…: the format (PDF, PNG or JPEG of the current slide or of every slide, PowerPoint,
/// outline, animated GIF, RTF) and its options; Export hands them to [`SlideApp::export_as`].
/// Returns true when the dialog should close.
fn dlg_export(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
ui.label("Export the presentation as:");
let fmt = d.get("fmt", "pdf");
@@ -715,6 +718,7 @@ fn dlg_export(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
("PNG images (current slide)", "png"),
("PNG images (all slides)", "pngAll"),
("JPEG image (current slide)", "jpeg"),
("JPEG images (all slides)", "jpegAll"),
("PowerPoint Presentation (.pptx)", "pptx"),
("Outline (.txt)", "outline"),
("Animated GIF (.gif)", "gif"),
@@ -1351,8 +1355,14 @@ fn dlg_preferences(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
// on release, and at once from the keyboard.
let pending = d.fields.get("uiScale").and_then(|v| v.parse::<f32>().ok());
let mut scale = pending.unwrap_or(app.ui.ui_scale);
let r = ui.add(egui::Slider::new(&mut scale, 0.75..=1.75));
// No visible label here (the row is laid out to fit); the accessible name only.
// Labelled like the Measurement units row below it. The egui 0.37 migration (#1350) dropped
// the slider's own text and kept only its accessible name, which left a bare "1.00".
let r = ui
.horizontal(|ui| {
ui.label("Interface size:");
ui.add(egui::Slider::new(&mut scale, 0.75..=1.75))
})
.inner;
let enabled = r.enabled();
r.widget_info(|| egui::WidgetInfo::slider(enabled, f64::from(scale), "Interface size"));
if r.is_pointer_button_down_on() {
@@ -39,6 +39,18 @@ fn dark(app: &SlideApp) -> bool {
app.ui.brightness == Brightness::Dark
}
/// The interface size slider has a visible label, not just a bare "1.00" beside it.
#[test]
fn the_interface_size_slider_is_labelled_on_screen() {
let mut h = harness();
open_options(&mut h);
let label = h.query_by_label("Interface size:").expect("the slider's label is shown");
let slider = interface_size(&h);
let (label, slider) = (label.rect(), slider.rect());
assert!(label.max.x <= slider.min.x, "the label sits before the slider: {label:?}, {slider:?}");
assert!(label.center().y > slider.min.y && label.center().y < slider.max.y, "on the same row: {label:?}, {slider:?}");
}
/// A checkbox applies as it is toggled and Cancel puts the old value back.
#[test]
fn options_cancel_undoes_the_changes() {
+1 -1
View File
@@ -28,7 +28,7 @@ fn header_footer_apply_keeps_an_existing_date_format() {
use crate::SlideApp;
let mut session = deckcraft_engine::Session::with_new();
session.execute("design.headerFooter", &json!({"date": true, "dateText": "", "dateFormat": "datetime4", "all": true})).unwrap();
// A file whose document-level format is unset, as an imported deck's is.
// A file whose document-level format is unset, as an imported deck's is when its date field is not one of the thirteen kinds.
Arc::make_mut(&mut session.doc_mut().unwrap().doc).header_footer.date_format = String::new();
let date_fields = |app: &SlideApp| -> Vec<String> {
app.session
+56
View File
@@ -70,3 +70,59 @@ fn play_on_the_editor_media_bar_plays_the_selected_clip() {
click(&mut h, bar + vec2(w - 30.0, 13.0));
assert_eq!(h.state().session.active().unwrap().selection.shapes, vec![id]);
}
/// #1922: the bar hangs 6 pt under the clip, so a clip at the bottom edge of the slide put it
/// inside the speaker-notes pane, painted over the notes text. The canvas is clipped to its own
/// rect: nothing it paints reaches the notes pane, and a click there goes to the notes field.
#[test]
fn the_media_bar_never_paints_or_clicks_into_the_notes_pane() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
let r = s.execute("insert.audio", &json!({"name": "tone.wav", "data": deckcraft_engine::cmd::base64_encode(&wav(2.0))})).unwrap();
let id = ShapeId(r["id"].as_u64().unwrap() as u32);
// Dragged across the bottom edge of the slide, onto the pasteboard.
let h_slide = s.doc().unwrap().doc.slide_size.height;
s.execute("shape.setBounds", &json!({"ids": [id.0], "x": 300.0, "y": h_slide - 10.0, "w": 120.0, "h": 60.0})).unwrap();
let mut app = SlideApp::new(s, Services::default());
app.ui.notes = true;
app.ui.notes_height = 140.0;
let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
let notes = h.query_all_by_role(Role::MultilineTextInput).next().map(|n| n.rect()).expect("the notes field");
let canvas = h.state().canvas_rect.unwrap();
assert!(canvas.max.y <= notes.min.y + 1.0, "the notes pane sits under the canvas: {canvas:?} / {notes:?}");
let d = h.state().session.active().unwrap();
let x = d.doc.slides[d.selection.slide].shape(id).unwrap().xfrm.unwrap();
let (slide, k) = (h.state().slide_rect.unwrap(), h.state().canvas_scale);
let bottom = slide.min.y + (x.y + x.h) as f32 * k;
let bar_y = bottom + 6.0 + 13.0;
assert!(bar_y > notes.min.y, "the bar's row ({bar_y}) would fall inside the notes pane (top {})", notes.min.y);
// The bar's own background (the only dark rounded rect the canvas paints there) has no
// visible area below the canvas edge: whatever the canvas paints is clipped to the canvas.
let bar_fill = egui::Color32::from_rgba_unmultiplied(28, 28, 32, 230);
let bars: Vec<egui::Rect> = h
.output()
.shapes
.iter()
.filter_map(|cs| match &cs.shape {
egui::Shape::Rect(r) if r.fill == bar_fill => Some(r.rect.intersect(cs.clip_rect)),
_ => None,
})
.collect();
assert!(!bars.is_empty(), "the bar is still laid out for the selected clip");
assert!(bars.iter().all(|v| !v.is_positive() || v.max.y <= canvas.max.y + 0.5), "the bar is painted into the notes pane: {bars:?}");
// A click where the bar would be lands in the notes field, not on the bar.
click(&mut h, pos2(slide.min.x + (x.x + x.w / 2.0) as f32 * k, bar_y));
assert!(h.state().media.status(id).is_none(), "Play was not hit through the notes pane");
assert!(h.ctx.memory(|m| m.focused()).is_some(), "the notes field took the click");
}
+63 -1
View File
@@ -232,6 +232,8 @@ pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient, sc: &ColorScheme) ->
let (marks, _) = ui.allocate_exact_size(vec2(bar.width(), 14.0), Sense::hover());
let drag_id = ui.scope_id().with((id, "drag"));
let mut dragging: Option<(usize, f64)> = ui.data_mut(|d| d.get_temp(drag_id));
// A double-clicked stop opens its colour menu, as in PowerPoint (#2175).
let mut open_color = false;
for (i, s) in g.stops.iter().enumerate() {
let pos = dragging.filter(|d| d.0 == i).map_or(s.pos, |d| d.1);
let x = bar.min.x + pos as f32 * bar.width();
@@ -245,6 +247,10 @@ pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient, sc: &ColorScheme) ->
if resp.clicked() || resp.drag_started() {
sel = i;
}
if resp.double_clicked() {
sel = i;
open_color = true;
}
if resp.dragged()
&& let Some(p) = resp.interact_pointer_pos()
{
@@ -287,7 +293,12 @@ pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient, sc: &ColorScheme) ->
let (sw, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());
ui.painter().rect(sw, CornerRadius::same(3), c32(&s.color, sc), Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
let r = widgets::drop_button(ui, "", vec2(24.0, 20.0), true);
widgets::color_popup(&r).show(|ui| {
r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Stop color"));
let mut popup = widgets::color_popup(&r);
if open_color {
popup = popup.open_memory(egui::SetOpenCommand::Bool(true));
}
popup.show(|ui| {
if let Some(Some(c)) = widgets::color_grid(ui, sc, None) {
let mut ng = g.clone();
ng.stops[sel].color = with_alpha(c, alpha_of(&s.color));
@@ -516,7 +527,58 @@ pub fn pattern_editor(ui: &mut Ui, pt: &PatternFill, sc: &ColorScheme) -> Option
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
/// #2175: double-clicking a gradient stop selects it and opens its colour menu; a colour
/// picked there colours that stop.
#[test]
fn double_clicking_a_stop_opens_its_color_menu() {
let sc = deckcraft_model::Theme::default().colors;
let start = Gradient {
stops: vec![
GradientStop { pos: 0.0, color: ColorRef::scheme(SchemeSlot::Accent1) },
GradientStop { pos: 1.0, color: ColorRef::scheme(SchemeSlot::Accent2) },
],
..default_gradient(ColorRef::scheme(SchemeSlot::Accent1), 90.0)
};
// The gradient, and whether the interface fonts are in (they apply from the next frame).
let mut h = Harness::builder().with_size(vec2(400.0, 700.0)).with_step_dt(1.0 / 60.0).build_ui_state(
move |ui, (g, fonts): &mut (Gradient, bool)| {
if !*fonts {
theme::install_fonts(ui.ctx());
*fonts = true;
return;
}
if let Some(ng) = gradient_editor(ui, "test-grad", &g.clone(), &sc) {
*g = ng;
}
},
(start, false),
);
h.run_steps(3);
assert!(h.query_by_label("Theme Colors").is_none(), "the menu starts closed");
let stop = h.get_by_label("Gradient stop 2").rect().center();
h.hover_at(stop);
h.run_steps(1);
for _ in 0..2 {
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: stop, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
}
}
h.run_steps(2);
assert!(h.query_by_label("Theme Colors").is_some(), "the colour menu opened");
h.get_by_label(SchemeSlot::Accent6.label()).click();
h.run_steps(2);
let g = &h.state().0;
assert_eq!(g.stops.len(), 2, "no stop was added");
assert_eq!(g.stops[1].color, ColorRef::scheme(SchemeSlot::Accent6), "the double-clicked stop took the colour");
assert_eq!(g.stops[0].color, ColorRef::scheme(SchemeSlot::Accent1));
}
#[test]
fn gradient_json_retains_flip_mode() {
+5 -2
View File
@@ -552,7 +552,8 @@ impl Show {
true
}
/// On entering a slide: auto-play its first step when it begins With/After Previous.
/// On entering a slide: auto-play its first step when it begins With/After Previous, once the
/// slide's transition is over.
/// `ShowState` already starts such a step when it enters the slide (#631: asking it for the
/// next step again finished the step at once, so the slide appeared fully built), so only
/// its clock starts here. Autoplay previews start an On Click first step themselves.
@@ -568,7 +569,9 @@ impl Show {
None
};
if let Some(k) = started {
self.step_start = now;
// The slide's transition plays first; its animations start when it has finished, as
// in PowerPoint (#2089).
self.step_start = self.trans.as_ref().map_or(now, |t| now.max(t.start + t.dur));
self.media_clock = Some((k, f64::NEG_INFINITY));
}
}
+35
View File
@@ -516,6 +516,41 @@ fn a_transition_keeps_the_old_slide_in_its_own_texture() {
assert!(show.tex.is_none(), "the new slide gets a texture of its own instead of overwriting the old one");
}
/// #2089: a slide's With Previous entrance waits for the slide's transition to finish, as in
/// PowerPoint, instead of playing under it.
#[test]
fn animations_start_after_the_slides_transition() {
let mut s = deckcraft_engine::Session::with_new();
s.execute("slide.new", &json!({})).unwrap();
s.execute("transition.set", &json!({"kind": "fade", "index": 1, "duration": 400})).unwrap();
let id = s.active().unwrap().doc.slides[1].shapes[0].id;
s.execute("animation.add", &json!({"effect": "fade", "class": "entrance", "ids": [id.0], "start": "withPrevious", "duration": 500})).unwrap();
let doc = s.active().unwrap().doc.clone();
let mut show = Show::new(&doc, 0, false, false);
let a = show.state.next(&doc);
assert_eq!(a, ShowAction::Slide(1));
assert!(show.apply(a, &doc, 10.0));
assert!(show.trans.is_some(), "the fade plays");
assert!(show.state.playing, "the With Previous step is under way");
assert!((show.clock_snapshot().step_start - 10.4).abs() < 1e-9, "its clock starts when the 0.4 s fade ends");
let tl = ShowState::timeline(&doc, 1);
let at = |now: f64| state_for(&tl, id, show.state.step, now - show.clock_snapshot().step_start, &[], &[]);
assert!(!at(10.3).visible, "hidden while the transition plays");
assert!(at(10.6).visible && at(10.6).opacity < 1.0, "fading in after it");
// The step is not cut short by the time the transition took.
let mut actions = Vec::new();
assert!(show.queue_clock_actions(&doc, 10.8, &mut actions));
assert!(actions.is_empty(), "0.4 s into a 0.5 s step: still playing");
// Without a transition the step starts at once, as before.
s.execute("transition.set", &json!({"kind": "none", "index": 1})).unwrap();
let doc = s.active().unwrap().doc.clone();
let mut show = Show::new(&doc, 0, false, false);
let a = show.state.next(&doc);
assert!(show.apply(a, &doc, 10.0));
assert_eq!(show.clock_snapshot().step_start, 10.0);
}
#[test]
fn going_back_plays_the_left_slides_transition_reversed() {
// #1531: Back from B to A played A's own entrance transition. PowerPoint plays the one B came
+21
View File
@@ -88,6 +88,27 @@ fn web_png_export_can_leave_the_background_transparent() {
assert_eq!(corner_alpha(&got[2].1), 255, "JPEG has no transparency");
}
/// Every type File › Save As and Export › Change File Type list is one `export_as` writes:
/// a listed type it doesn't know would only say "can't export" (#2019).
#[test]
fn every_listed_save_type_exports() {
use std::cell::RefCell;
use std::rc::Rc;
let got: Rc<RefCell<Vec<String>>> = Rc::default();
let log = got.clone();
let services = Services { download: Some(Box::new(move |name: &str, _: &[u8]| log.borrow_mut().push(name.to_string()))), ..Default::default() };
let mut app = SlideApp::new(Session::with_new(), services);
app.session.execute("slide.new", &json!({})).unwrap();
for (id, _, _) in crate::backstage::SAVE_TYPES {
assert!(app.export_as(id, json!({})), "{id} exports");
}
let title = app.session.active().unwrap().title();
let got = got.borrow();
for name in [format!("{title}1.jpg"), format!("{title}2.jpg"), format!("{title}1.png"), format!("{title}2.png")] {
assert!(got.contains(&name), "{name} downloaded, got {got:?}");
}
}
fn title_text(app: &SlideApp) -> String {
let d = app.session.active().unwrap();
let sh = &d.doc.slides[0].shapes[0];
+4 -3
View File
@@ -1,6 +1,6 @@
# File-format parity with PowerPoint
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-07 · **Change:** trivial (a slide whose relationship is missing is reported in `lostSlides`; previous: minor (cell anchorCtr, vertOverflow/horzOverflow, compatLnSpc, normalizeH, thaiDist, table rtl, run altLang and reflection transforms round-trip; Reuse Slides brings referenced custom table styles; previous: minor (native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233))) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-11 · **Change:** minor (empty notes slides are preserved on save and reopen, #2025; previous: trivial, a slide whose relationship is missing is reported in `lostSlides`; previous: minor (cell anchorCtr, vertOverflow/horzOverflow, compatLnSpc, normalizeH, thaiDist, table rtl, run altLang and reflection transforms round-trip; Reuse Slides brings referenced custom table styles; previous: minor (native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233))) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
Every format PowerPoint reads or writes, DeckCraft's support, fidelity and how it is tested.
Gaps are itemized in [gaps.md](gaps.md#file-formats). Dimension score: **~58% ready**
@@ -77,7 +77,7 @@ the round trip even though DeckCraft doesn't model it.
| Presentation, slide size, sections (p14), custom shows | yes | yes | |
| Slide masters, layouts, placeholders and inheritance | yes | yes | |
| Themes: colour, font (Latin/EA/CS), effect schemes, background styles | yes | yes | Unknown theme parts kept |
| Notes slides and notes master | yes | yes | Header, footer, date and slide-number text on the notes master is kept. Edited in View ▸ Notes Master. Notes keep their run and paragraph formatting (bold, italic, underline, size, levels, indents, bullets), shown and kept when edited in the notes pane and Notes Page (`crates/pptx/tests/it/notes.rs`). PDF notes pages print them as plain text; levels and bullets inherited from a custom notes master aren't shown |
| Notes slides and notes master | yes | yes | Header, footer, date and slide-number text on the notes master is kept. Edited in View ▸ Notes Master. Notes keep their run and paragraph formatting (bold, italic, underline, size, levels, indents, bullets), shown and kept when edited in the notes pane and Notes Page (`crates/pptx/tests/it/notes.rs`). Empty notes slides are preserved on save and reopen (#2025). PDF notes pages print them as plain text; levels and bullets inherited from a custom notes master aren't shown |
| Handout master | yes | yes | Header, footer, date and slide-number text is kept. Edited in View ▸ Handout Master |
| Shapes: preset geometry (~180 presets), custom geometry, groups, connectors | yes | yes | Presets re-derived in `crates/geom/src/preset.rs` (and `preset/extra.rs`). Outlines, dashes, arrowheads and ink inside a group, and text, keep their size in points whatever the group's child-coordinate scale (#233). |
| Fills: solid, gradient, picture (stretch/tile/crop), pattern, group | yes | yes | |
@@ -92,7 +92,7 @@ the round trip even though DeckCraft doesn't model it.
| Charts (`cx:` chartex: waterfall, funnel, treemap, sunburst, histogram, Pareto, box) | yes | yes | Unchanged parts kept, with their embedded workbook (#335); edited and new ones written from the model with a plain-chart fallback. Treemap and sunburst hierarchy levels kept; region maps kept, drawn as tiles (no map geometry) |
| SmartArt (`dgm`) | the drawing part as a group (text laid out on its `dsp:txXfrm` rectangle), and the outline from the data model (Text Pane) | as a diagram: data model from the outline; layout, quick style and colour parts (the file's own kept until the layout is switched); the group as the cached drawing | DeckCraft's layout definitions are simple; a diagram without a cached drawing isn't drawn. SmartArt kept only as XML, without its relationship parts, still loses the drawing and data parts (#203) |
| Equations (OMML, `a14:m`) | no | no | PR #55 open |
| Audio / video (`p14:media`, trim, fades, bookmarks) | yes | partly | Playback options lost on save (#74) |
| Audio / video (`p14:media`, trim, fades, bookmarks, playback options) | yes | yes | Volume, mute, autoplay, loop, rewind, play across slides, hide while not playing and full screen round-trip (`media_timing.rs`) |
| Ink (`contentPart`) | yes | as a group of freeform lines | PowerPoint sees shapes, not ink |
| Transitions incl. p14/p15 (Vortex, Morph…) | all 48 | all 48 | `every_transition_kind_round_trips` |
| Animations: timing tree, build paragraphs, triggers, motion paths | yes (flattened to the Animation Pane list) | yes (rebuilt) | `every_animation_effect_survives`; repeat, triggers, bounce end and rewind kept |
@@ -122,6 +122,7 @@ the round trip even though DeckCraft doesn't model it.
| 2026-11-07 | trivial | A slide-list entry whose relationship is missing is reported in `lostSlides` like an unreadable slide part, so the deck opens as a repaired copy; slide lists over 10,000 entries are refused with an import-limit error rather than silently truncated (#1910) |
| 2026-11-02 | minor | Optional table RTL direction is read and written as `a:tblPr/@rtl`; native and two PPTX saves preserve true, false and absent values with distinguishable column text |
| 2026-11-02 | minor | Text runs preserve alternate-language metadata in native and PPTX round trips |
| 2026-11-11 | minor | Empty notes slides retain their notesSlide part and relationship on save and reopen (#2025) |
| 2026-11-03 | trivial | Reuse Slides transfers referenced custom table styles from native and PPTX sources; grouped tables, undo, native save/reopen and style-id conflicts are covered |
| 2026-10-18 | minor | Native chart payloads use referenced ZIP members and share media byte/item limits; old inline sidecars remain readable. Synthetic tests cover multi-megabyte layout, all shape owners, shared budgets, missing/corrupt members and invalid references. Scores and milestone scope unchanged |
| 2026-11-02 | trivial | Reflection start position, affine scale/skew, direction and fade, alignment and rotation attributes survive native and PPTX saves; rendering remains partial |
+12 -4
View File
@@ -1,6 +1,6 @@
# Localization parity with PowerPoint
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-24 · **Change:** minor (opt-in native LXGW WenKai Lite fallback and interface CJK tests; local implementation only, managed validation pending; previous: minor, IME composition underlined in table cells; previous: minor, IME composition and CJK interface text, #101; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-31 · **Change:** minor (Review › Language offers Serbian in Cyrillic and Latin, each with its own dictionary; previous: minor, opt-in native LXGW WenKai Lite fallback and interface CJK tests; local implementation only, managed validation pending; previous: minor, IME composition underlined in table cells; previous: minor, IME composition and CJK interface text, #101; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
DeckCraft's interface is English only today: strings are literals in the UI and engine code, with
no catalog and no language switch. Requests: #15 (follow the system language), #30 and PR #34
@@ -51,15 +51,23 @@ the next re-measure.
## Proofing languages
PowerPoint checks spelling in dozens of languages and lets each run carry a proofing language.
DeckCraft keeps `a:rPr/@lang` on round trip but its spelling check is a small English list of
common misspellings (`crates/engine/src/cmd/review.rs`); see [gaps.md](gaps.md#proofing-spelling-thesaurus-autocorrect).
DeckCraft keeps `a:rPr/@lang` on round trip and checks each run in its own language against the
Hunspell dictionaries installed on the system (`crates/engine/src/spell.rs`), falling back to a
built-in list of common English misspellings when there is none (`review.spelling`); see
[gaps.md](gaps.md#proofing-spelling-thesaurus-autocorrect).
Review › Language sets the proofing language of the selected text or, with *Whole presentation*,
of every text in the file and the default for new text (`format.languageAll`).
of every text in the file and the default for new text (`format.languageAll`). Each run is shaped
in its language, so fonts draw their forms for it (OpenType `locl`: the Serbian б, г, д, п, т).
Serbian is offered in both scripts (`sr-Cyrl-RS`, `sr-Latn-RS`). The run's language tag picks the
dictionary, and only one in the script the tag names: LibreOffice's `sr` and `sr-Latn`, Hunspell's
`sr_RS` and `sr_Latn_RS`, Fedora's `sr_RS@latin`, and the Serbo-Croatian `sh_RS`/`sh_YU` for Latin.
A dictionary of the other script would flag every word, so it is never used.
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-31 | minor | Review › Language offers Serbian (Cyrillic and Latin); each run's language tag picks a dictionary in the script it names |
| 2026-10-24 | minor | Local 0.37 candidate adds an opt-in native LXGW WenKai Lite glyph fallback and CJK interface-test coverage. This records local implementation only: managed tests, formatting, clippy, wasm-size and native GUI qualification remain pending. Browser font budget and uniform Chinese typography are unchanged. |
| 2026-10-21 | minor | Review › Language can set the proofing language of the whole presentation |
| 2026-10-14 | minor | IME composition in a table cell is underlined in place; the candidate window sits on that cell's caret |
+4 -3
View File
@@ -1,6 +1,6 @@
# UI parity with PowerPoint
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** trivial (File › About replaces Account; product links, credits and appearance retained; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-10 · **Change:** trivial (File › Export › Change File Type and Save As export every slide as PNG or JPEG, #2019; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** trivial (locked No Fill and no-outline click-through regression coverage added; No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-26 · **Change:** trivial (dragging several selected slides moves them all; previous: trivial, Edit Points: Shift, Ctrl/Cmd or Alt/Option on a handle drag sets the point type; previous: trivial, scroll bars on the zoomed slide pane, #1157; previous: major, community PR wave 2026-10-14: 14 new dialogs (41 in all), Eyedropper, Export button, New Window, Grid Options, WordArt gallery and handles, Slide Sorter sections, Quick Access Toolbar, Format Background and Format Shape depth, rich-text clipboard; duplicated rows and headers folded; previous: minor, File tab / Backstage, #76) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-22 · **Change:** trivial (group fill and outline edits reach members, #1079; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
@@ -57,10 +57,10 @@ menu colours taken from the theme tokens (menu `chrome`, page `card`).
| Open | Recent, Shared with Me, OneDrive, This PC, Add a Place, Browse; Presentations / Folders; Recover Unsaved Presentations | Recent and Browse (`app.openDialog`), recent presentations with a search box (`file.open`), Recover Unsaved Presentations (`file.recovery.open`). No cloud places or Folders tab |
| Info | Name and path, Upload / Share / Copy path / Open file location; Protect, Inspect, Version History, Manage Presentation; Properties, Related Dates, Related People | Name and path, Copy path, Open file location; Inspect Presentation (Accessibility Checker), Manage Presentation (Revert); Size, Slides, Hidden slides and editable Title, Subject, Tags, Categories, Company, Comments, Author (`file.info`, `file.properties`). No Protect, Version History or dates |
| Save | Saves; a presentation never saved goes to Save As | Same (`file.save`) |
| Save As | Places, folder, file name, type, Save, More options | Type (PowerPoint, DeckCraft, PDF, Outline, PNG, JPEG) and Save, which opens the system Save dialog (web: Download). .pptx/.deckcraft take the new file; the others are copies (`file.saveAs`, `file.export`) |
| Save As | Places, folder, file name, type, Save, More options | Type (PowerPoint, DeckCraft, PDF, Outline, PNG, JPEG, and PNG or JPEG of every slide, #2019) and Save, which opens the system Save dialog (web: Download). .pptx/.deckcraft take the new file; the others are copies (`file.saveAs`, `file.export`) |
| Print | Print and Copies, Printer, Print All / Selection / Current / Custom Range, Slides box, layout (Full Page Slides, Notes Pages, Outline, Handouts 1–9), sides, collation, colour, Edit Header & Footer; page preview with pager and zoom | Print, Print All Slides / Current Slide / Custom Range, Slides box (`1-3, 5`), Full Page Slides / Notes Pages / Handouts 1–9, Print Hidden Slides, Frame Slides, Edit Header & Footer; preview with pager. DeckCraft prints through a PDF (`file.export`) opened in the system viewer, which has the printers (web: downloaded). No printer list, copies, sides or colour |
| Share | Cloud sharing | Not offered |
| Export | Create PDF/XPS Document, Create a Video, Create an Animated GIF, Package Presentation for CD, Create Handouts, Change File Type | Create PDF Document, Create Handouts (a PDF), Change File Type (PNG with an optional transparent background, #784). No video, GIF or CD package |
| Export | Create PDF/XPS Document, Create a Video, Create an Animated GIF, Package Presentation for CD, Create Handouts, Change File Type | Create PDF Document, Create Handouts (a PDF), Change File Type (PNG or JPEG of the current slide or of every slide, #2019; PNG with an optional transparent background, #784). No video, GIF or CD package |
| Close | Closes; asks Save / Don't Save / Cancel about unsaved changes | Same (`file.close` after the prompt); Ctrl+W asks too |
| Account | User information, sign-in, Office Background and Office Theme, product information, About | About: product information, project links, contributor/model credits and appearance (light/dark, `view.dark`). No Account entry |
| Options | Opens the PowerPoint Options dialog | Opens Preferences |
@@ -173,6 +173,7 @@ consistency is open (#73, #56).
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | trivial | Change File Type and Save As export every slide as PNG or JPEG (#2019); scores unchanged |
| 2026-11-02 | trivial | File › About replaces Account; product links, credits and appearance retained |
| 2026-10-31 | trivial | No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged |
| 2026-10-29 | trivial | Picture Format: the Picture Styles row shows as many styles as fit beside the groups after it (at least two) and a More arrow with all 24, as the Transitions and Animations galleries do; Crop and Size are in view in the default window (#1232) |
+9
View File
@@ -1,2 +1,11 @@
sonar.projectKey=storytold_deckcraft
sonar.organization=storytold
# githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by
# .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned
# and the lockfile covers the actions those actions use too. Sonar does not read lockfiles yet, so
# the rule flags the tag refs anyway:
# https://community.sonarsource.com/t/githubactions-s7637-false-positives-for-actions-pinned-through-native-actions-lock/190814
sonar.issue.ignore.multicriteria=gha-lockfile
sonar.issue.ignore.multicriteria.gha-lockfile.ruleKey=githubactions:S7637
sonar.issue.ignore.multicriteria.gha-lockfile.resourceKey=.github/workflows/**