mirror of
https://github.com/storytold/deckcraft.git
synced 2026-11-21 21:40:38 -06:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dea0af6ceb | ||
|
|
3b6f9e7cb8 | ||
|
|
5f58c3c208 | ||
|
|
596ec54b59 | ||
|
|
9e975b0049 | ||
|
|
4c844f9332 | ||
|
|
5cf7f5f20a | ||
|
|
fb7755717b | ||
|
|
d04db56f3b | ||
|
|
ea1b4c5539 | ||
|
|
e6574eb39e | ||
|
|
48de308315 | ||
|
|
455a3fdc35 | ||
|
|
3746f259a0 | ||
|
|
175fa54642 | ||
|
|
64c89064ea | ||
|
|
96c6b5da4c | ||
|
|
40052f4b09 | ||
|
|
8ecb818f81 | ||
|
|
953ae8d060 | ||
|
|
1b2b48c0d7 | ||
|
|
9e7fab1038 |
Generated
+52
-3
@@ -853,6 +853,11 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
@@ -868,13 +873,24 @@ name = "craft-deckcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32#254e9a409b410dc93c0e06ff66cd1e767893ac32"
|
||||
dependencies = [
|
||||
"craft-zip",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32)",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b#44d83fa8f635333dcb3c231f87381387a1f5631b"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
@@ -932,6 +948,17 @@ dependencies = [
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -1027,6 +1054,16 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b#44d83fa8f635333dcb3c231f87381387a1f5631b"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -1046,6 +1083,16 @@ dependencies = [
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
@@ -1162,7 +1209,7 @@ dependencies = [
|
||||
name = "deckcraft-color"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"craft-drawingml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1280,7 +1327,9 @@ dependencies = [
|
||||
name = "deckcraft-pptx"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-cfb",
|
||||
"craft-opc",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
|
||||
"deckcraft-color",
|
||||
"deckcraft-engine",
|
||||
"deckcraft-geom",
|
||||
|
||||
@@ -11,8 +11,14 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/deckcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# OPC part-name primitives; relationship admission stays app-local.
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" }
|
||||
# Compound File Binary directory reads (password-protected deck detection).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" }
|
||||
# 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.
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "44d83fa8f635333dcb3c231f87381387a1f5631b", version = "0.1.0" }
|
||||
# internal
|
||||
deckcraft-geom = { path = "crates/geom" }
|
||||
deckcraft-color = { path = "crates/color" }
|
||||
|
||||
+3
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~20 points and ~120–210 h away
|
||||
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-11 · **Change:** trivial (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-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-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,6 +154,7 @@ app's JSON control channel (`deckcraft --control PORT`).
|
||||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 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 | 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-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered |
|
||||
@@ -342,6 +343,7 @@ app's JSON control channel (`deckcraft --control PORT`).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-14 | trivial | Progress log: a slide the show advances to again plays its animations again (#2090); parity scores unchanged |
|
||||
| 2026-11-11 | trivial | Opus and container code moved to craft-libs crates; 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 |
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
//! - a shape with a link and a triggered animation follows the link at once. The animation's clock
|
||||
//! runs only while its slide is shown, so it goes on where it stopped when the show returns;
|
||||
//! - with "advance on click" off a click never leaves the slide, but it still plays animation steps;
|
||||
//! - a slide the show returns to (link or arrow keys) looks as it was left.
|
||||
//! - a slide the show returns to by a link or by going back looks as it was left; going forward
|
||||
//! to a slide starts it over (#2090).
|
||||
|
||||
use deckcraft_model::text::Action;
|
||||
use deckcraft_model::{Presentation, ShapeId};
|
||||
|
||||
+12
-3
@@ -47,7 +47,8 @@ pub enum LinkJump {
|
||||
|
||||
/// Where a slide show is. Besides the current position it remembers what was played on every slide
|
||||
/// the show has visited (main steps, triggered sequences), so a slide reached again by a link or
|
||||
/// the arrow keys looks the way it was left, as in PowerPoint.
|
||||
/// by going back looks the way it was left, as in PowerPoint. Going forward to a slide starts it
|
||||
/// over, so its animations play again (#2090).
|
||||
#[derive(Clone, Debug, PartialEq, Default)]
|
||||
pub struct ShowState {
|
||||
/// Index into `presentation.slides`.
|
||||
@@ -226,6 +227,14 @@ impl ShowState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Advance to slide `i`: it starts over, as if the show had not been there, so its
|
||||
/// animations play again (#2090). Links and Back keep a slide as it was left.
|
||||
fn enter_forward(&mut self, pres: &Presentation, i: usize) {
|
||||
self.leave(pres);
|
||||
self.runs.remove(&i);
|
||||
self.enter(pres, i);
|
||||
}
|
||||
|
||||
fn next_index(&self, pres: &Presentation) -> Option<usize> {
|
||||
let order = self.visit(pres);
|
||||
match order.iter().position(|&i| i == self.slide) {
|
||||
@@ -271,12 +280,12 @@ impl ShowState {
|
||||
}
|
||||
match self.next_index(pres) {
|
||||
Some(i) => {
|
||||
self.enter(pres, i);
|
||||
self.enter_forward(pres, i);
|
||||
ShowAction::Slide(i)
|
||||
}
|
||||
None if looping(pres) => match self.visit(pres).first() {
|
||||
Some(&i) => {
|
||||
self.enter(pres, i);
|
||||
self.enter_forward(pres, i);
|
||||
ShowAction::Slide(i)
|
||||
}
|
||||
None => {
|
||||
|
||||
@@ -876,6 +876,8 @@ fn show_back_leaves_a_slide_whose_first_step_is_automatic() {
|
||||
// While the automatic step plays.
|
||||
assert_eq!(s.prev(&p), ShowAction::Slide(0), "{start:?}");
|
||||
assert_eq!(s.next(&p), ShowAction::Slide(1));
|
||||
// Going forward again plays the automatic step again (#2090).
|
||||
assert_eq!(s.step_done(&p), ShowAction::FinishStep(0), "{start:?}");
|
||||
// Once it has played, the click step is undone first, then Back leaves the slide.
|
||||
assert_eq!(s.next(&p), ShowAction::PlayStep(1));
|
||||
assert_eq!(s.step_done(&p), ShowAction::FinishStep(1));
|
||||
@@ -885,6 +887,56 @@ fn show_back_leaves_a_slide_whose_first_step_is_automatic() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slide_entered_going_forward_again_plays_its_animations_again() {
|
||||
// #2090: the show remembered slide 2 as fully built, so its entrance effects did not play the
|
||||
// second time the show advanced to it.
|
||||
for start in [AnimStart::WithPrevious, AnimStart::AfterPrevious] {
|
||||
let mut p = pres(3);
|
||||
Arc::make_mut(&mut p.slides[1]).shapes = vec![shape(1, "A")];
|
||||
Arc::make_mut(&mut p.slides[1]).animations = vec![anim(1, AnimClass::Entrance, "fade", start)];
|
||||
let mut s = ShowState::new(&p);
|
||||
assert_eq!(s.next(&p), ShowAction::Slide(1));
|
||||
assert_eq!(s.step_done(&p), ShowAction::FinishStep(0));
|
||||
assert_eq!(s.prev(&p), ShowAction::Slide(0), "{start:?}");
|
||||
assert_eq!(s.next(&p), ShowAction::Slide(1));
|
||||
assert_eq!((s.step, s.playing), (0, true), "{start:?}: the slide starts again");
|
||||
let a = ShowState::timeline(&p, 1).state(ShapeId(1), None, s.step, 0.0);
|
||||
assert!(!a.visible || a.opacity < 0.01, "{start:?}: the shape has not come in yet");
|
||||
// Back from the next slide still shows it as it was left.
|
||||
assert_eq!(s.step_done(&p), ShowAction::FinishStep(0));
|
||||
assert_eq!(s.next(&p), ShowAction::Slide(2));
|
||||
assert_eq!(s.prev(&p), ShowAction::Slide(1));
|
||||
assert_eq!((s.step, s.playing), (1, false), "{start:?}");
|
||||
}
|
||||
// An On Click build left by a jump starts again when the show advances to the slide.
|
||||
let mut p = pres(2);
|
||||
Arc::make_mut(&mut p.slides[1]).shapes = vec![shape(1, "A")];
|
||||
Arc::make_mut(&mut p.slides[1]).animations = vec![anim(1, AnimClass::Entrance, "fade", AnimStart::OnClick)];
|
||||
let mut s = ShowState::new(&p);
|
||||
assert_eq!(s.next(&p), ShowAction::Slide(1));
|
||||
assert_eq!(s.next(&p), ShowAction::PlayStep(0));
|
||||
assert_eq!(s.step_done(&p), ShowAction::FinishStep(0));
|
||||
assert_eq!(s.goto(&p, 0), ShowAction::Slide(0));
|
||||
assert_eq!(s.next(&p), ShowAction::Slide(1));
|
||||
assert_eq!((s.step, s.playing), (0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_looping_show_plays_the_first_slide_again() {
|
||||
// #2090: a kiosk or loop-until-Esc show comes round to the first slide going forward.
|
||||
let mut p = pres(2);
|
||||
p.show.loop_until_esc = true;
|
||||
Arc::make_mut(&mut p.slides[0]).shapes = vec![shape(1, "A")];
|
||||
Arc::make_mut(&mut p.slides[0]).animations = vec![anim(1, AnimClass::Entrance, "fade", AnimStart::WithPrevious)];
|
||||
let mut s = ShowState::new(&p);
|
||||
assert!(s.playing);
|
||||
assert_eq!(s.step_done(&p), ShowAction::FinishStep(0));
|
||||
assert_eq!(s.next(&p), ShowAction::Slide(1));
|
||||
assert_eq!(s.next(&p), ShowAction::Slide(0));
|
||||
assert_eq!((s.step, s.playing), (0, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_auto_advance() {
|
||||
let mut p = pres(2);
|
||||
|
||||
@@ -325,6 +325,23 @@ fn a_slide_comes_back_the_way_it_was_left() {
|
||||
assert_eq!(s.step, ShowState::steps(&pres, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slide_entered_going_forward_again_starts_over() {
|
||||
// #2090: the show advances to slide 2 a second time; its triggered animation is undone too.
|
||||
let s1 = slide(1000, vec![], vec![], true);
|
||||
let s2 = slide(1001, vec![shape(4)], vec![exit_on_click(4, 4, 0)], true);
|
||||
let pres = Presentation { slides: vec![s1, s2], ..Default::default() };
|
||||
let mut r = Run::new(pres, vec![vec![], vec![hit(4, None)]]);
|
||||
assert_eq!(r.show.next(&r.pres), ShowAction::Slide(1));
|
||||
assert_eq!(r.click(), Click::Animated);
|
||||
assert!(!r.visible(ShapeId(4)));
|
||||
assert_eq!(r.show.prev(&r.pres), ShowAction::Slide(0));
|
||||
assert_eq!(r.show.prev(&r.pres), ShowAction::None);
|
||||
assert_eq!(r.show.next(&r.pres), ShowAction::Slide(1));
|
||||
assert!(r.visible(ShapeId(4)), "the shape is back");
|
||||
assert!(r.show.trigger_plays().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_playing_main_step_is_finished_when_the_show_leaves() {
|
||||
let a = Animation { shape: ShapeId(1), class: AnimClass::Entrance, effect: "fade".into(), duration_ms: 500, ..Default::default() };
|
||||
|
||||
@@ -9,4 +9,4 @@ description = "DeckCraft colour: RGB/HSL, theme colour slots, DrawingML-style co
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
craft-drawingml = { workspace = true }
|
||||
|
||||
+5
-753
@@ -1,758 +1,10 @@
|
||||
//! DeckCraft colour: sRGB colours, theme colour slots and DrawingML-style colour transforms
|
||||
//! (tint, shade, luminance modulation/offset, alpha…), so theme-relative colours resolve the way
|
||||
//! presentation files expect.
|
||||
//! DrawingML colours for DeckCraft: `Rgba`, scheme slots, colour schemes and colour transforms.
|
||||
//! They live in craft-libs (`craft_drawingml::color`, craft-libs#778 and #792), shared with the
|
||||
//! PPTX reader and writer; this crate re-exports them under the name the app uses.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// An sRGB colour with straight alpha, components 0–255.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct Rgba {
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
pub a: u8,
|
||||
}
|
||||
|
||||
impl Default for Rgba {
|
||||
fn default() -> Self {
|
||||
Rgba::BLACK
|
||||
}
|
||||
}
|
||||
|
||||
impl Rgba {
|
||||
pub const BLACK: Rgba = Rgba::rgb(0, 0, 0);
|
||||
pub const WHITE: Rgba = Rgba::rgb(255, 255, 255);
|
||||
pub const TRANSPARENT: Rgba = Rgba { r: 0, g: 0, b: 0, a: 0 };
|
||||
|
||||
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
||||
Rgba { r, g, b, a: 255 }
|
||||
}
|
||||
pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
|
||||
Rgba { r, g, b, a }
|
||||
}
|
||||
/// `RRGGBB` or `#RRGGBB` (also `RRGGBBAA`).
|
||||
pub fn from_hex(s: &str) -> Option<Self> {
|
||||
let s = s.trim();
|
||||
let s = s.strip_prefix('#').unwrap_or(s);
|
||||
if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let byte = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok());
|
||||
match s.len() {
|
||||
6 => Some(Rgba::rgb(byte(0)?, byte(2)?, byte(4)?)),
|
||||
8 => Some(Rgba::rgba(byte(0)?, byte(2)?, byte(4)?, byte(6)?)),
|
||||
3 => {
|
||||
let n = |i: usize| s.get(i..i + 1).and_then(|h| u8::from_str_radix(h, 16).ok()).map(|v| v * 17);
|
||||
Some(Rgba::rgb(n(0)?, n(1)?, n(2)?))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `RRGGBB` uppercase (no alpha).
|
||||
pub fn hex(&self) -> String {
|
||||
format!("{:02X}{:02X}{:02X}", self.r, self.g, self.b)
|
||||
}
|
||||
pub fn with_alpha(self, a: u8) -> Self {
|
||||
Rgba { a, ..self }
|
||||
}
|
||||
pub fn to_f32(self) -> [f32; 4] {
|
||||
[self.r as f32 / 255.0, self.g as f32 / 255.0, self.b as f32 / 255.0, self.a as f32 / 255.0]
|
||||
}
|
||||
pub fn from_f64(r: f64, g: f64, b: f64, a: f64) -> Self {
|
||||
let c = |v: f64| if v.is_finite() { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } else { 0 };
|
||||
Rgba { r: c(r), g: c(g), b: c(b), a: c(a) }
|
||||
}
|
||||
/// Relative luminance (WCAG), 0–1.
|
||||
pub fn luminance(self) -> f64 {
|
||||
let lin = |c: u8| {
|
||||
let v = c as f64 / 255.0;
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
};
|
||||
0.2126 * lin(self.r) + 0.7152 * lin(self.g) + 0.0722 * lin(self.b)
|
||||
}
|
||||
/// WCAG contrast ratio between two colours (1–21).
|
||||
pub fn contrast(self, other: Rgba) -> f64 {
|
||||
let (a, b) = (self.luminance(), other.luminance());
|
||||
let (hi, lo) = if a > b { (a, b) } else { (b, a) };
|
||||
(hi + 0.05) / (lo + 0.05)
|
||||
}
|
||||
pub fn to_hsl(self) -> (f64, f64, f64) {
|
||||
let r = self.r as f64 / 255.0;
|
||||
let g = self.g as f64 / 255.0;
|
||||
let b = self.b as f64 / 255.0;
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let l = (max + min) / 2.0;
|
||||
if (max - min).abs() < 1e-12 {
|
||||
return (0.0, 0.0, l);
|
||||
}
|
||||
let d = max - min;
|
||||
let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
|
||||
let h = if (max - r).abs() < 1e-12 {
|
||||
(g - b) / d + if g < b { 6.0 } else { 0.0 }
|
||||
} else if (max - g).abs() < 1e-12 {
|
||||
(b - r) / d + 2.0
|
||||
} else {
|
||||
(r - g) / d + 4.0
|
||||
};
|
||||
(h * 60.0, s, l)
|
||||
}
|
||||
pub fn from_hsl(h: f64, s: f64, l: f64, a: u8) -> Self {
|
||||
let h = ((h % 360.0) + 360.0) % 360.0 / 360.0;
|
||||
let s = s.clamp(0.0, 1.0);
|
||||
let l = l.clamp(0.0, 1.0);
|
||||
if s == 0.0 {
|
||||
return Rgba::from_f64(l, l, l, a as f64 / 255.0);
|
||||
}
|
||||
let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
|
||||
let p = 2.0 * l - q;
|
||||
let f = |t: f64| {
|
||||
let t = if t < 0.0 {
|
||||
t + 1.0
|
||||
} else if t > 1.0 {
|
||||
t - 1.0
|
||||
} else {
|
||||
t
|
||||
};
|
||||
if t < 1.0 / 6.0 {
|
||||
p + (q - p) * 6.0 * t
|
||||
} else if t < 0.5 {
|
||||
q
|
||||
} else if t < 2.0 / 3.0 {
|
||||
p + (q - p) * (2.0 / 3.0 - t) * 6.0
|
||||
} else {
|
||||
p
|
||||
}
|
||||
};
|
||||
Rgba::from_f64(f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0), a as f64 / 255.0)
|
||||
}
|
||||
/// Linear interpolation (straight alpha).
|
||||
pub fn lerp(self, o: Rgba, t: f64) -> Rgba {
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let m = |a: u8, b: u8| (a as f64 + (b as f64 - a as f64) * t).round().clamp(0.0, 255.0) as u8;
|
||||
Rgba { r: m(self.r, o.r), g: m(self.g, o.g), b: m(self.b, o.b), a: m(self.a, o.a) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The twelve theme colour slots, plus the mapped aliases (`bg1`, `tx1`…) and `phClr` (the
|
||||
/// placeholder colour a style matrix entry is applied with).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SchemeSlot {
|
||||
Dk1,
|
||||
Lt1,
|
||||
Dk2,
|
||||
Lt2,
|
||||
Accent1,
|
||||
Accent2,
|
||||
Accent3,
|
||||
Accent4,
|
||||
Accent5,
|
||||
Accent6,
|
||||
Hlink,
|
||||
FolHlink,
|
||||
Bg1,
|
||||
Tx1,
|
||||
Bg2,
|
||||
Tx2,
|
||||
PhClr,
|
||||
}
|
||||
|
||||
impl SchemeSlot {
|
||||
pub const THEME: [SchemeSlot; 12] = [
|
||||
SchemeSlot::Dk1,
|
||||
SchemeSlot::Lt1,
|
||||
SchemeSlot::Dk2,
|
||||
SchemeSlot::Lt2,
|
||||
SchemeSlot::Accent1,
|
||||
SchemeSlot::Accent2,
|
||||
SchemeSlot::Accent3,
|
||||
SchemeSlot::Accent4,
|
||||
SchemeSlot::Accent5,
|
||||
SchemeSlot::Accent6,
|
||||
SchemeSlot::Hlink,
|
||||
SchemeSlot::FolHlink,
|
||||
];
|
||||
pub fn xml_name(self) -> &'static str {
|
||||
match self {
|
||||
SchemeSlot::Dk1 => "dk1",
|
||||
SchemeSlot::Lt1 => "lt1",
|
||||
SchemeSlot::Dk2 => "dk2",
|
||||
SchemeSlot::Lt2 => "lt2",
|
||||
SchemeSlot::Accent1 => "accent1",
|
||||
SchemeSlot::Accent2 => "accent2",
|
||||
SchemeSlot::Accent3 => "accent3",
|
||||
SchemeSlot::Accent4 => "accent4",
|
||||
SchemeSlot::Accent5 => "accent5",
|
||||
SchemeSlot::Accent6 => "accent6",
|
||||
SchemeSlot::Hlink => "hlink",
|
||||
SchemeSlot::FolHlink => "folHlink",
|
||||
SchemeSlot::Bg1 => "bg1",
|
||||
SchemeSlot::Tx1 => "tx1",
|
||||
SchemeSlot::Bg2 => "bg2",
|
||||
SchemeSlot::Tx2 => "tx2",
|
||||
SchemeSlot::PhClr => "phClr",
|
||||
}
|
||||
}
|
||||
pub fn from_xml(s: &str) -> Option<Self> {
|
||||
Some(match s {
|
||||
"dk1" => SchemeSlot::Dk1,
|
||||
"lt1" => SchemeSlot::Lt1,
|
||||
"dk2" => SchemeSlot::Dk2,
|
||||
"lt2" => SchemeSlot::Lt2,
|
||||
"accent1" => SchemeSlot::Accent1,
|
||||
"accent2" => SchemeSlot::Accent2,
|
||||
"accent3" => SchemeSlot::Accent3,
|
||||
"accent4" => SchemeSlot::Accent4,
|
||||
"accent5" => SchemeSlot::Accent5,
|
||||
"accent6" => SchemeSlot::Accent6,
|
||||
"hlink" => SchemeSlot::Hlink,
|
||||
"folHlink" => SchemeSlot::FolHlink,
|
||||
"bg1" => SchemeSlot::Bg1,
|
||||
"tx1" => SchemeSlot::Tx1,
|
||||
"bg2" => SchemeSlot::Bg2,
|
||||
"tx2" => SchemeSlot::Tx2,
|
||||
"phClr" => SchemeSlot::PhClr,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
SchemeSlot::Dk1 | SchemeSlot::Tx1 => "Text/Background - Dark 1",
|
||||
SchemeSlot::Lt1 | SchemeSlot::Bg1 => "Text/Background - Light 1",
|
||||
SchemeSlot::Dk2 | SchemeSlot::Tx2 => "Text/Background - Dark 2",
|
||||
SchemeSlot::Lt2 | SchemeSlot::Bg2 => "Text/Background - Light 2",
|
||||
SchemeSlot::Accent1 => "Accent 1",
|
||||
SchemeSlot::Accent2 => "Accent 2",
|
||||
SchemeSlot::Accent3 => "Accent 3",
|
||||
SchemeSlot::Accent4 => "Accent 4",
|
||||
SchemeSlot::Accent5 => "Accent 5",
|
||||
SchemeSlot::Accent6 => "Accent 6",
|
||||
SchemeSlot::Hlink => "Hyperlink",
|
||||
SchemeSlot::FolHlink => "Followed Hyperlink",
|
||||
SchemeSlot::PhClr => "Placeholder colour",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A colour scheme: the twelve theme colours.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ColorScheme {
|
||||
pub name: String,
|
||||
pub colors: [Rgba; 12],
|
||||
}
|
||||
|
||||
impl ColorScheme {
|
||||
pub fn get(&self, slot: SchemeSlot) -> Rgba {
|
||||
let i = match slot {
|
||||
SchemeSlot::Dk1 | SchemeSlot::Tx1 => 0,
|
||||
SchemeSlot::Lt1 | SchemeSlot::Bg1 => 1,
|
||||
SchemeSlot::Dk2 | SchemeSlot::Tx2 => 2,
|
||||
SchemeSlot::Lt2 | SchemeSlot::Bg2 => 3,
|
||||
SchemeSlot::Accent1 => 4,
|
||||
SchemeSlot::Accent2 => 5,
|
||||
SchemeSlot::Accent3 => 6,
|
||||
SchemeSlot::Accent4 => 7,
|
||||
SchemeSlot::Accent5 => 8,
|
||||
SchemeSlot::Accent6 => 9,
|
||||
SchemeSlot::Hlink => 10,
|
||||
SchemeSlot::FolHlink => 11,
|
||||
SchemeSlot::PhClr => 4,
|
||||
};
|
||||
self.colors.get(i).copied().unwrap_or(Rgba::BLACK)
|
||||
}
|
||||
pub fn set(&mut self, slot: SchemeSlot, c: Rgba) {
|
||||
if let Some(i) = SchemeSlot::THEME.iter().position(|s| *s == slot)
|
||||
&& let Some(v) = self.colors.get_mut(i)
|
||||
{
|
||||
*v = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One colour transform, in file units (percentages ×1000, angles ×60000), applied in order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", tag = "op", content = "val")]
|
||||
pub enum ColorTransform {
|
||||
Tint(i32),
|
||||
Shade(i32),
|
||||
LumMod(i32),
|
||||
LumOff(i32),
|
||||
SatMod(i32),
|
||||
SatOff(i32),
|
||||
HueMod(i32),
|
||||
HueOff(i32),
|
||||
Alpha(i32),
|
||||
AlphaMod(i32),
|
||||
AlphaOff(i32),
|
||||
Comp,
|
||||
Inv,
|
||||
Gray,
|
||||
RedMod(i32),
|
||||
GreenMod(i32),
|
||||
BlueMod(i32),
|
||||
}
|
||||
|
||||
impl ColorTransform {
|
||||
pub fn xml_name(&self) -> &'static str {
|
||||
match self {
|
||||
ColorTransform::Tint(_) => "tint",
|
||||
ColorTransform::Shade(_) => "shade",
|
||||
ColorTransform::LumMod(_) => "lumMod",
|
||||
ColorTransform::LumOff(_) => "lumOff",
|
||||
ColorTransform::SatMod(_) => "satMod",
|
||||
ColorTransform::SatOff(_) => "satOff",
|
||||
ColorTransform::HueMod(_) => "hueMod",
|
||||
ColorTransform::HueOff(_) => "hueOff",
|
||||
ColorTransform::Alpha(_) => "alpha",
|
||||
ColorTransform::AlphaMod(_) => "alphaMod",
|
||||
ColorTransform::AlphaOff(_) => "alphaOff",
|
||||
ColorTransform::Comp => "comp",
|
||||
ColorTransform::Inv => "inv",
|
||||
ColorTransform::Gray => "gray",
|
||||
ColorTransform::RedMod(_) => "redMod",
|
||||
ColorTransform::GreenMod(_) => "greenMod",
|
||||
ColorTransform::BlueMod(_) => "blueMod",
|
||||
}
|
||||
}
|
||||
pub fn value(&self) -> Option<i32> {
|
||||
match *self {
|
||||
ColorTransform::Tint(v)
|
||||
| ColorTransform::Shade(v)
|
||||
| ColorTransform::LumMod(v)
|
||||
| ColorTransform::LumOff(v)
|
||||
| ColorTransform::SatMod(v)
|
||||
| ColorTransform::SatOff(v)
|
||||
| ColorTransform::HueMod(v)
|
||||
| ColorTransform::HueOff(v)
|
||||
| ColorTransform::Alpha(v)
|
||||
| ColorTransform::AlphaMod(v)
|
||||
| ColorTransform::AlphaOff(v)
|
||||
| ColorTransform::RedMod(v)
|
||||
| ColorTransform::GreenMod(v)
|
||||
| ColorTransform::BlueMod(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn from_xml(name: &str, val: Option<i32>) -> Option<Self> {
|
||||
let v = val.unwrap_or(0);
|
||||
Some(match name {
|
||||
"tint" => ColorTransform::Tint(v),
|
||||
"shade" => ColorTransform::Shade(v),
|
||||
"lumMod" => ColorTransform::LumMod(v),
|
||||
"lumOff" => ColorTransform::LumOff(v),
|
||||
"satMod" => ColorTransform::SatMod(v),
|
||||
"satOff" => ColorTransform::SatOff(v),
|
||||
"hueMod" => ColorTransform::HueMod(v),
|
||||
"hueOff" => ColorTransform::HueOff(v),
|
||||
"alpha" => ColorTransform::Alpha(v),
|
||||
"alphaMod" => ColorTransform::AlphaMod(v),
|
||||
"alphaOff" => ColorTransform::AlphaOff(v),
|
||||
"comp" => ColorTransform::Comp,
|
||||
"inv" => ColorTransform::Inv,
|
||||
"gray" => ColorTransform::Gray,
|
||||
"redMod" => ColorTransform::RedMod(v),
|
||||
"greenMod" => ColorTransform::GreenMod(v),
|
||||
"blueMod" => ColorTransform::BlueMod(v),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply transforms to a base colour.
|
||||
pub fn apply(base: Rgba, transforms: &[ColorTransform]) -> Rgba {
|
||||
let mut c = base;
|
||||
for t in transforms {
|
||||
c = apply_one(c, *t);
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
fn pct(v: i32) -> f64 {
|
||||
v as f64 / 100_000.0
|
||||
}
|
||||
|
||||
fn apply_one(c: Rgba, t: ColorTransform) -> Rgba {
|
||||
match t {
|
||||
// tint: towards white by (1 - value); shade: towards black by (1 - value). Office applies
|
||||
// these in linear light, which keeps mid-tones from washing out.
|
||||
ColorTransform::Tint(v) => {
|
||||
let k = pct(v).clamp(0.0, 1.0);
|
||||
map_linear(c, |x| x * k + (1.0 - k))
|
||||
}
|
||||
ColorTransform::Shade(v) => {
|
||||
let k = pct(v).clamp(0.0, 1.0);
|
||||
map_linear(c, |x| x * k)
|
||||
}
|
||||
ColorTransform::LumMod(v) => {
|
||||
let (h, s, l) = c.to_hsl();
|
||||
Rgba::from_hsl(h, s, l * pct(v), c.a)
|
||||
}
|
||||
ColorTransform::LumOff(v) => {
|
||||
let (h, s, l) = c.to_hsl();
|
||||
Rgba::from_hsl(h, s, l + pct(v), c.a)
|
||||
}
|
||||
ColorTransform::SatMod(v) => {
|
||||
let (h, s, l) = c.to_hsl();
|
||||
Rgba::from_hsl(h, s * pct(v), l, c.a)
|
||||
}
|
||||
ColorTransform::SatOff(v) => {
|
||||
let (h, s, l) = c.to_hsl();
|
||||
Rgba::from_hsl(h, s + pct(v), l, c.a)
|
||||
}
|
||||
ColorTransform::HueMod(v) => {
|
||||
let (h, s, l) = c.to_hsl();
|
||||
Rgba::from_hsl(h * pct(v), s, l, c.a)
|
||||
}
|
||||
ColorTransform::HueOff(v) => {
|
||||
let (h, s, l) = c.to_hsl();
|
||||
Rgba::from_hsl(h + v as f64 / 60_000.0, s, l, c.a)
|
||||
}
|
||||
ColorTransform::Alpha(v) => c.with_alpha((pct(v).clamp(0.0, 1.0) * 255.0).round() as u8),
|
||||
ColorTransform::AlphaMod(v) => c.with_alpha((c.a as f64 * pct(v)).round().clamp(0.0, 255.0) as u8),
|
||||
ColorTransform::AlphaOff(v) => c.with_alpha((c.a as f64 + pct(v) * 255.0).round().clamp(0.0, 255.0) as u8),
|
||||
ColorTransform::Comp => {
|
||||
let (h, s, l) = c.to_hsl();
|
||||
Rgba::from_hsl(h + 180.0, s, l, c.a)
|
||||
}
|
||||
ColorTransform::Inv => Rgba { r: 255 - c.r, g: 255 - c.g, b: 255 - c.b, a: c.a },
|
||||
ColorTransform::Gray => {
|
||||
let y = (0.299 * c.r as f64 + 0.587 * c.g as f64 + 0.114 * c.b as f64).round().clamp(0.0, 255.0) as u8;
|
||||
Rgba { r: y, g: y, b: y, a: c.a }
|
||||
}
|
||||
ColorTransform::RedMod(v) => Rgba { r: (c.r as f64 * pct(v)).round().clamp(0.0, 255.0) as u8, ..c },
|
||||
ColorTransform::GreenMod(v) => Rgba { g: (c.g as f64 * pct(v)).round().clamp(0.0, 255.0) as u8, ..c },
|
||||
ColorTransform::BlueMod(v) => Rgba { b: (c.b as f64 * pct(v)).round().clamp(0.0, 255.0) as u8, ..c },
|
||||
}
|
||||
}
|
||||
|
||||
fn to_lin(v: u8) -> f64 {
|
||||
let v = v as f64 / 255.0;
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
fn from_lin(v: f64) -> f64 {
|
||||
let v = v.clamp(0.0, 1.0);
|
||||
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
fn map_linear(c: Rgba, f: impl Fn(f64) -> f64) -> Rgba {
|
||||
Rgba::from_f64(from_lin(f(to_lin(c.r))), from_lin(f(to_lin(c.g))), from_lin(f(to_lin(c.b))), c.a as f64 / 255.0)
|
||||
}
|
||||
|
||||
/// The colour-picker grid shown under each theme colour: lighter 80/60/40%, darker 25/50%
|
||||
/// (for dark colours: lighter 90/75/50/25/10%).
|
||||
pub fn theme_variants(c: Rgba) -> [(Vec<ColorTransform>, &'static str); 5] {
|
||||
let (_, _, l) = c.to_hsl();
|
||||
if l < 0.2 {
|
||||
[
|
||||
(vec![ColorTransform::LumMod(10000), ColorTransform::LumOff(90000)], "Lighter 90%"),
|
||||
(vec![ColorTransform::LumMod(25000), ColorTransform::LumOff(75000)], "Lighter 75%"),
|
||||
(vec![ColorTransform::LumMod(50000), ColorTransform::LumOff(50000)], "Lighter 50%"),
|
||||
(vec![ColorTransform::LumMod(75000), ColorTransform::LumOff(25000)], "Lighter 25%"),
|
||||
(vec![ColorTransform::LumMod(90000), ColorTransform::LumOff(10000)], "Lighter 10%"),
|
||||
]
|
||||
} else if l > 0.8 {
|
||||
[
|
||||
(vec![ColorTransform::LumMod(95000)], "Darker 5%"),
|
||||
(vec![ColorTransform::LumMod(85000)], "Darker 15%"),
|
||||
(vec![ColorTransform::LumMod(75000)], "Darker 25%"),
|
||||
(vec![ColorTransform::LumMod(65000)], "Darker 35%"),
|
||||
(vec![ColorTransform::LumMod(50000)], "Darker 50%"),
|
||||
]
|
||||
} else {
|
||||
[
|
||||
(vec![ColorTransform::LumMod(20000), ColorTransform::LumOff(80000)], "Lighter 80%"),
|
||||
(vec![ColorTransform::LumMod(40000), ColorTransform::LumOff(60000)], "Lighter 60%"),
|
||||
(vec![ColorTransform::LumMod(60000), ColorTransform::LumOff(40000)], "Lighter 40%"),
|
||||
(vec![ColorTransform::LumMod(75000)], "Darker 25%"),
|
||||
(vec![ColorTransform::LumMod(50000)], "Darker 50%"),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Standard colours row of the colour picker.
|
||||
pub const STANDARD_COLORS: [(Rgba, &str); 10] = [
|
||||
(Rgba::rgb(0xC0, 0x00, 0x00), "Dark Red"),
|
||||
(Rgba::rgb(0xFF, 0x00, 0x00), "Red"),
|
||||
(Rgba::rgb(0xFF, 0xC0, 0x00), "Orange"),
|
||||
(Rgba::rgb(0xFF, 0xFF, 0x00), "Yellow"),
|
||||
(Rgba::rgb(0x92, 0xD0, 0x50), "Light Green"),
|
||||
(Rgba::rgb(0x00, 0xB0, 0x50), "Green"),
|
||||
(Rgba::rgb(0x00, 0xB0, 0xF0), "Light Blue"),
|
||||
(Rgba::rgb(0x00, 0x70, 0xC0), "Blue"),
|
||||
(Rgba::rgb(0x00, 0x20, 0x60), "Dark Blue"),
|
||||
(Rgba::rgb(0x70, 0x30, 0xA0), "Purple"),
|
||||
];
|
||||
|
||||
/// A few CSS-like preset colour names (`prstClr`).
|
||||
pub fn preset(name: &str) -> Option<Rgba> {
|
||||
let c = match name {
|
||||
"black" => (0, 0, 0),
|
||||
"white" => (255, 255, 255),
|
||||
"red" => (255, 0, 0),
|
||||
"green" => (0, 128, 0),
|
||||
"lime" => (0, 255, 0),
|
||||
"blue" => (0, 0, 255),
|
||||
"yellow" => (255, 255, 0),
|
||||
"cyan" | "aqua" => (0, 255, 255),
|
||||
"magenta" | "fuchsia" => (255, 0, 255),
|
||||
"gray" | "grey" => (128, 128, 128),
|
||||
"silver" => (192, 192, 192),
|
||||
"maroon" => (128, 0, 0),
|
||||
"navy" => (0, 0, 128),
|
||||
"olive" => (128, 128, 0),
|
||||
"purple" => (128, 0, 128),
|
||||
"teal" => (0, 128, 128),
|
||||
"orange" => (255, 165, 0),
|
||||
"pink" => (255, 192, 203),
|
||||
"brown" => (165, 42, 42),
|
||||
"gold" => (255, 215, 0),
|
||||
"ltGray" | "lightGray" => (211, 211, 211),
|
||||
"dkGray" | "darkGray" => (169, 169, 169),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Rgba::rgb(c.0, c.1, c.2))
|
||||
}
|
||||
|
||||
/// Every preset colour name a file may write (`ST_PresetColorVal`, with the later editions' aliases).
|
||||
pub const PRESET_NAMES: [&str; 190] = [
|
||||
"aliceBlue",
|
||||
"antiqueWhite",
|
||||
"aqua",
|
||||
"aquamarine",
|
||||
"azure",
|
||||
"beige",
|
||||
"bisque",
|
||||
"black",
|
||||
"blanchedAlmond",
|
||||
"blue",
|
||||
"blueViolet",
|
||||
"brown",
|
||||
"burlyWood",
|
||||
"cadetBlue",
|
||||
"chartreuse",
|
||||
"chocolate",
|
||||
"coral",
|
||||
"cornflowerBlue",
|
||||
"cornsilk",
|
||||
"crimson",
|
||||
"cyan",
|
||||
"darkBlue",
|
||||
"darkCyan",
|
||||
"darkGoldenrod",
|
||||
"darkGray",
|
||||
"darkGrey",
|
||||
"darkGreen",
|
||||
"darkKhaki",
|
||||
"darkMagenta",
|
||||
"darkOliveGreen",
|
||||
"darkOrange",
|
||||
"darkOrchid",
|
||||
"darkRed",
|
||||
"darkSalmon",
|
||||
"darkSeaGreen",
|
||||
"darkSlateBlue",
|
||||
"darkSlateGray",
|
||||
"darkSlateGrey",
|
||||
"darkTurquoise",
|
||||
"darkViolet",
|
||||
"dkBlue",
|
||||
"dkCyan",
|
||||
"dkGoldenrod",
|
||||
"dkGray",
|
||||
"dkGrey",
|
||||
"dkGreen",
|
||||
"dkKhaki",
|
||||
"dkMagenta",
|
||||
"dkOliveGreen",
|
||||
"dkOrange",
|
||||
"dkOrchid",
|
||||
"dkRed",
|
||||
"dkSalmon",
|
||||
"dkSeaGreen",
|
||||
"dkSlateBlue",
|
||||
"dkSlateGray",
|
||||
"dkSlateGrey",
|
||||
"dkTurquoise",
|
||||
"dkViolet",
|
||||
"deepPink",
|
||||
"deepSkyBlue",
|
||||
"dimGray",
|
||||
"dimGrey",
|
||||
"dodgerBlue",
|
||||
"firebrick",
|
||||
"floralWhite",
|
||||
"forestGreen",
|
||||
"fuchsia",
|
||||
"gainsboro",
|
||||
"ghostWhite",
|
||||
"gold",
|
||||
"goldenrod",
|
||||
"gray",
|
||||
"grey",
|
||||
"green",
|
||||
"greenYellow",
|
||||
"honeydew",
|
||||
"hotPink",
|
||||
"indianRed",
|
||||
"indigo",
|
||||
"ivory",
|
||||
"khaki",
|
||||
"lavender",
|
||||
"lavenderBlush",
|
||||
"lawnGreen",
|
||||
"lemonChiffon",
|
||||
"lightBlue",
|
||||
"lightCoral",
|
||||
"lightCyan",
|
||||
"lightGoldenrodYellow",
|
||||
"lightGray",
|
||||
"lightGrey",
|
||||
"lightGreen",
|
||||
"lightPink",
|
||||
"lightSalmon",
|
||||
"lightSeaGreen",
|
||||
"lightSkyBlue",
|
||||
"lightSlateGray",
|
||||
"lightSlateGrey",
|
||||
"lightSteelBlue",
|
||||
"lightYellow",
|
||||
"ltBlue",
|
||||
"ltCoral",
|
||||
"ltCyan",
|
||||
"ltGoldenrodYellow",
|
||||
"ltGray",
|
||||
"ltGrey",
|
||||
"ltGreen",
|
||||
"ltPink",
|
||||
"ltSalmon",
|
||||
"ltSeaGreen",
|
||||
"ltSkyBlue",
|
||||
"ltSlateGray",
|
||||
"ltSlateGrey",
|
||||
"ltSteelBlue",
|
||||
"ltYellow",
|
||||
"lime",
|
||||
"limeGreen",
|
||||
"linen",
|
||||
"magenta",
|
||||
"maroon",
|
||||
"medAquamarine",
|
||||
"medBlue",
|
||||
"medOrchid",
|
||||
"medPurple",
|
||||
"medSeaGreen",
|
||||
"medSlateBlue",
|
||||
"medSpringGreen",
|
||||
"medTurquoise",
|
||||
"medVioletRed",
|
||||
"mediumAquamarine",
|
||||
"mediumBlue",
|
||||
"mediumOrchid",
|
||||
"mediumPurple",
|
||||
"mediumSeaGreen",
|
||||
"mediumSlateBlue",
|
||||
"mediumSpringGreen",
|
||||
"mediumTurquoise",
|
||||
"mediumVioletRed",
|
||||
"midnightBlue",
|
||||
"mintCream",
|
||||
"mistyRose",
|
||||
"moccasin",
|
||||
"navajoWhite",
|
||||
"navy",
|
||||
"oldLace",
|
||||
"olive",
|
||||
"oliveDrab",
|
||||
"orange",
|
||||
"orangeRed",
|
||||
"orchid",
|
||||
"paleGoldenrod",
|
||||
"paleGreen",
|
||||
"paleTurquoise",
|
||||
"paleVioletRed",
|
||||
"papayaWhip",
|
||||
"peachPuff",
|
||||
"peru",
|
||||
"pink",
|
||||
"plum",
|
||||
"powderBlue",
|
||||
"purple",
|
||||
"red",
|
||||
"rosyBrown",
|
||||
"royalBlue",
|
||||
"saddleBrown",
|
||||
"salmon",
|
||||
"sandyBrown",
|
||||
"seaGreen",
|
||||
"seaShell",
|
||||
"sienna",
|
||||
"silver",
|
||||
"skyBlue",
|
||||
"slateBlue",
|
||||
"slateGray",
|
||||
"slateGrey",
|
||||
"snow",
|
||||
"springGreen",
|
||||
"steelBlue",
|
||||
"tan",
|
||||
"teal",
|
||||
"thistle",
|
||||
"tomato",
|
||||
"turquoise",
|
||||
"violet",
|
||||
"wheat",
|
||||
"white",
|
||||
"whiteSmoke",
|
||||
"yellow",
|
||||
"yellowGreen",
|
||||
];
|
||||
|
||||
/// Every system colour name a file may write (`ST_SystemColorVal`).
|
||||
pub const SYSTEM_NAMES: [&str; 30] = [
|
||||
"scrollBar",
|
||||
"background",
|
||||
"activeCaption",
|
||||
"inactiveCaption",
|
||||
"menu",
|
||||
"window",
|
||||
"windowFrame",
|
||||
"menuText",
|
||||
"windowText",
|
||||
"captionText",
|
||||
"activeBorder",
|
||||
"inactiveBorder",
|
||||
"appWorkspace",
|
||||
"highlight",
|
||||
"highlightText",
|
||||
"btnFace",
|
||||
"btnShadow",
|
||||
"grayText",
|
||||
"btnText",
|
||||
"inactiveCaptionText",
|
||||
"btnHighlight",
|
||||
"3dDkShadow",
|
||||
"3dLight",
|
||||
"infoText",
|
||||
"infoBk",
|
||||
"hotLight",
|
||||
"gradientActiveCaption",
|
||||
"gradientInactiveCaption",
|
||||
"menuHighlight",
|
||||
"menuBar",
|
||||
];
|
||||
|
||||
/// Whether `name` is a preset colour name a file may write.
|
||||
pub fn is_preset_name(name: &str) -> bool {
|
||||
PRESET_NAMES.contains(&name)
|
||||
}
|
||||
|
||||
/// Whether `name` is a system colour name a file may write.
|
||||
pub fn is_system_name(name: &str) -> bool {
|
||||
SYSTEM_NAMES.contains(&name)
|
||||
}
|
||||
pub use craft_drawingml::color::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -820,7 +72,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn scheme_slots() {
|
||||
let mut s = ColorScheme { name: "t".into(), colors: [Rgba::BLACK; 12] };
|
||||
let mut s = ColorScheme::new("t", [Rgba::BLACK; 12]);
|
||||
s.set(SchemeSlot::Accent3, Rgba::WHITE);
|
||||
assert_eq!(s.get(SchemeSlot::Accent3), Rgba::WHITE);
|
||||
assert_eq!(s.get(SchemeSlot::Tx1), Rgba::BLACK);
|
||||
|
||||
@@ -417,17 +417,28 @@ fn regroup(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `to` of arrange.align and arrange.distribute: `Some(true)` for the slide, `Some(false)` for the
|
||||
/// selection, `None` when it is left out. Any other value, a non-string included, is refused.
|
||||
fn align_to(cmd: &str, p: &Value) -> Result<Option<bool>> {
|
||||
match p.get("to").map(Value::as_str) {
|
||||
None => Ok(None),
|
||||
Some(Some("slide")) => Ok(Some(true)),
|
||||
Some(Some("selection")) => Ok(Some(false)),
|
||||
Some(_) => Err(bad(cmd, "`to` must be slide or selection")),
|
||||
}
|
||||
}
|
||||
|
||||
fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let edge = str_param(p, "edge").unwrap_or("left").to_string();
|
||||
let edge = match str_param(p, "edge") {
|
||||
Some(e @ ("left" | "center" | "right" | "top" | "middle" | "bottom")) => e.to_string(),
|
||||
_ => return Err(bad("arrange.align", "`edge` must be left, center, right, top, middle or bottom")),
|
||||
};
|
||||
let to = align_to("arrange.align", p)?;
|
||||
let ids = targets(s, p)?;
|
||||
let st = s.doc()?;
|
||||
let size = st.doc.slide_size;
|
||||
let boxes: Vec<(ShapeId, Xfrm)> = ids.iter().filter_map(|id| st.shape(*id).map(|x| (*id, xfrm_of(&st.doc, &st.selection, x)))).collect();
|
||||
let to_slide = match str_param(p, "to") {
|
||||
Some("slide") => true,
|
||||
Some(_) => false,
|
||||
None => boxes.len() < 2,
|
||||
};
|
||||
let to_slide = to.unwrap_or(boxes.len() < 2);
|
||||
let reference = if to_slide {
|
||||
Rect::new(0.0, 0.0, size.width, size.height)
|
||||
} else {
|
||||
@@ -453,13 +464,18 @@ fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let horiz = !str_param(p, "dir").unwrap_or("horizontal").starts_with('v');
|
||||
let horiz = match p.get("dir").map(Value::as_str) {
|
||||
None | Some(Some("horizontal")) => true,
|
||||
Some(Some("vertical")) => false,
|
||||
Some(_) => return Err(bad("arrange.distribute", "`dir` must be horizontal or vertical")),
|
||||
};
|
||||
let to = align_to("arrange.distribute", p)?;
|
||||
let ids = targets(s, p)?;
|
||||
let st = s.doc()?;
|
||||
let size = st.doc.slide_size;
|
||||
let mut boxes: Vec<(ShapeId, Rect)> =
|
||||
ids.iter().filter_map(|id| st.shape(*id).map(|x| (*id, xfrm_of(&st.doc, &st.selection, x).bounds()))).collect();
|
||||
let to_slide = str_param(p, "to") == Some("slide") || boxes.len() < 3;
|
||||
let to_slide = to == Some(true) || boxes.len() < 3;
|
||||
if boxes.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
|
||||
@@ -1184,6 +1184,82 @@ fn distribute_wide_middle_stays_in_selection_bounds() {
|
||||
assert!(xs.iter().all(|x| (*x - [0.0, 10.0, 110.0][xs.iter().position(|y| y == x).unwrap()]).abs() < 1e-6), "{xs:?}");
|
||||
}
|
||||
|
||||
/// An `edge`, `dir` or `to` that the commands do not name, or no `edge` at all, is refused with
|
||||
/// the accepted values. Before, such a call reported its shapes as edited and moved nothing,
|
||||
/// aligned to the selection, or fell back to the left edge or to horizontal.
|
||||
#[test]
|
||||
fn align_and_distribute_refuse_values_they_do_not_name() {
|
||||
let mut s = session();
|
||||
let mut ids = vec![];
|
||||
for (x, y) in [(10.0, 10.0), (200.0, 50.0), (500.0, 200.0)] {
|
||||
ids.push(s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 40, 40]})).unwrap()["id"].as_u64().unwrap());
|
||||
}
|
||||
s.execute("edit.select", &json!({"ids": ids})).unwrap();
|
||||
let before = s.doc().unwrap().revision;
|
||||
let edges = "`edge` must be left, center, right, top, middle or bottom";
|
||||
let dirs = "`dir` must be horizontal or vertical";
|
||||
let tos = "`to` must be slide or selection";
|
||||
for (cmd, params, want) in [
|
||||
("arrange.align", json!({"edge": "centre"}), edges),
|
||||
("arrange.align", json!({"edge": "Left"}), edges),
|
||||
("arrange.align", json!({"edge": "hcenter"}), edges),
|
||||
("arrange.align", json!({}), edges),
|
||||
("arrange.align", json!({"ids": [ids[0]], "edge": "left", "to": "Slide"}), tos),
|
||||
("arrange.distribute", json!({"dir": "Vertical"}), dirs),
|
||||
("arrange.distribute", json!({"dir": "columns"}), dirs),
|
||||
("arrange.distribute", json!({"dir": "v"}), dirs),
|
||||
("arrange.distribute", json!({"dir": "vertical", "to": "page"}), tos),
|
||||
] {
|
||||
let err = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(err.contains(want), "{cmd} {params}: {err}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().revision, before, "a refused call leaves the slide as it was");
|
||||
let pos = |s: &mut Session, id: u64, k: &str| s.execute("shape.inspect", &json!({"id": id})).unwrap()["box"][k].as_f64().unwrap();
|
||||
s.execute("arrange.align", &json!({"ids": [ids[1]], "edge": "left", "to": "slide"})).unwrap();
|
||||
assert!(pos(&mut s, ids[1], "x").abs() < 1e-6);
|
||||
// Within the selection's span, 10..240: 120 pt of shapes leaves two 55 pt gaps.
|
||||
s.execute("arrange.distribute", &json!({"ids": ids, "dir": "vertical", "to": "selection"})).unwrap();
|
||||
assert!((pos(&mut s, ids[1], "y") - 105.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// A `dir` or `to` that is present but is not a string (null, a number, a bool, an object or an
|
||||
/// array) is refused with the accepted values, and the shapes and the revision stay as they were.
|
||||
/// Before, such a value counted as left out: `dir` meant horizontal and `to` each command's
|
||||
/// default, so the call moved the selected shapes.
|
||||
#[test]
|
||||
fn align_and_distribute_refuse_dir_and_to_that_are_not_strings() {
|
||||
let dirs = "`dir` must be horizontal or vertical";
|
||||
let tos = "`to` must be slide or selection";
|
||||
let mut failures = vec![];
|
||||
for v in [json!(null), json!(123), json!(false), json!({}), json!([])] {
|
||||
for (cmd, params, want) in [
|
||||
("arrange.distribute", json!({"dir": v.clone()}), dirs),
|
||||
("arrange.distribute", json!({"dir": "horizontal", "to": v.clone()}), tos),
|
||||
("arrange.align", json!({"edge": "left", "to": v.clone()}), tos),
|
||||
] {
|
||||
let mut s = session();
|
||||
let mut ids = vec![];
|
||||
for (x, y) in [(10.0, 10.0), (200.0, 50.0), (500.0, 200.0)] {
|
||||
ids.push(s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 40, 40]})).unwrap()["id"].as_u64().unwrap());
|
||||
}
|
||||
s.execute("edit.select", &json!({"ids": ids})).unwrap();
|
||||
let boxes = |s: &mut Session| -> Vec<Value> {
|
||||
ids.iter().map(|id| s.execute("shape.inspect", &json!({"id": id})).unwrap()["box"].clone()).collect()
|
||||
};
|
||||
let (rev, before) = (s.doc().unwrap().revision, boxes(&mut s));
|
||||
match s.execute(cmd, ¶ms) {
|
||||
Ok(_) => failures.push(format!("{cmd} {params}: accepted")),
|
||||
Err(e) if !e.to_string().contains(want) => failures.push(format!("{cmd} {params}: {e}")),
|
||||
Err(_) => {}
|
||||
}
|
||||
if s.doc().unwrap().revision != rev || boxes(&mut s) != before {
|
||||
failures.push(format!("{cmd} {params}: moved the shapes"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{failures:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_draw_move_resize() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -69,7 +69,7 @@ impl Default for Theme {
|
||||
fn default() -> Self {
|
||||
builtin_themes().into_iter().next().unwrap_or_else(|| Theme {
|
||||
name: "DeckCraft".into(),
|
||||
colors: ColorScheme { name: "DeckCraft".into(), colors: [Rgba::BLACK; 12] },
|
||||
colors: ColorScheme::new("DeckCraft", [Rgba::BLACK; 12]),
|
||||
fonts: FontScheme::default(),
|
||||
format: FormatScheme::default(),
|
||||
raw_extra: None,
|
||||
@@ -97,7 +97,7 @@ fn hex(s: &str) -> Rgba {
|
||||
}
|
||||
|
||||
fn scheme(name: &str, c: [&str; 12]) -> ColorScheme {
|
||||
ColorScheme { name: name.into(), colors: c.map(hex) }
|
||||
ColorScheme::new(name, c.map(hex))
|
||||
}
|
||||
|
||||
fn ph() -> ColorRef {
|
||||
|
||||
@@ -9,7 +9,9 @@ description = "DeckCraft PPTX: Office Open XML (PresentationML/DrawingML) import
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-opc.workspace = true
|
||||
craft-xml.workspace = true
|
||||
craft-cfb.workspace = true
|
||||
deckcraft-model = { workspace = true }
|
||||
deckcraft-geom = { workspace = true }
|
||||
deckcraft-color = { workspace = true }
|
||||
|
||||
+16
-94
@@ -1,103 +1,24 @@
|
||||
//! Just enough of the Compound File Binary (CFB/OLE2) container to tell a password-protected
|
||||
//! presentation apart: PowerPoint wraps an encrypted `.pptx` in a CFB holding `EncryptionInfo`
|
||||
//! and `EncryptedPackage` streams (ECMA-376 / [MS-OFFCRYPTO]) instead of a zip. Every read is
|
||||
//! bounds-checked and every loop bounded. Copied from GridCraft's `crates/xlsx/src/cfb.rs`.
|
||||
|
||||
/// The CFB signature at the start of the file.
|
||||
const SIGNATURE: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
|
||||
|
||||
const END_OF_CHAIN: u32 = 0xFFFF_FFFE;
|
||||
/// Sector ids at or above this are markers (free, end of chain, FAT/DIFAT sector), not sectors.
|
||||
const MAX_REG_SECT: u32 = 0xFFFF_FFFA;
|
||||
/// Directory sectors followed at most (4096 entries with 512-byte sectors).
|
||||
const MAX_DIR_SECTORS: usize = 1024;
|
||||
/// DIFAT sectors followed at most.
|
||||
const MAX_DIFAT_SECTORS: usize = 1024;
|
||||
//! Password-protected presentations. PowerPoint wraps an encrypted `.pptx` in a Compound File
|
||||
//! Binary (CFB/OLE2) container holding `EncryptionInfo` and `EncryptedPackage` streams
|
||||
//! (ECMA-376 / [MS-OFFCRYPTO]) instead of a zip. The container's directory is read by the shared
|
||||
//! `craft-cfb` crate, which bounds every chain and falls back to a UTF-16 name search when a
|
||||
//! damaged file's directory cannot be followed.
|
||||
|
||||
/// Stream names that mark an encrypted (password-protected) OOXML package.
|
||||
const ENCRYPTED_STREAMS: [&str; 2] = ["EncryptedPackage", "EncryptionInfo"];
|
||||
|
||||
fn u16_at(b: &[u8], at: usize) -> Option<u16> {
|
||||
let s = b.get(at..at.checked_add(2)?)?;
|
||||
Some(u16::from_le_bytes([*s.first()?, *s.get(1)?]))
|
||||
/// Directory entries read at most: 1024 directory sectors of 512 bytes, as before the move to
|
||||
/// `craft-cfb`, so a hostile directory chain stays cheap.
|
||||
const MAX_DIR_ENTRIES: usize = 4096;
|
||||
|
||||
fn limits() -> craft_cfb::Limits {
|
||||
craft_cfb::Limits { max_dir_entries: MAX_DIR_ENTRIES, ..craft_cfb::Limits::default() }
|
||||
}
|
||||
|
||||
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
|
||||
let s = b.get(at..at.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?]))
|
||||
}
|
||||
|
||||
/// Whether `bytes` is a compound file holding an encryption stream. Walks the directory through
|
||||
/// the FAT; when the structure can't be followed (truncated or malformed), falls back to scanning
|
||||
/// the bytes for the UTF-16LE stream names.
|
||||
/// Whether `bytes` is a compound file holding an encryption stream.
|
||||
pub(crate) fn is_encrypted(bytes: &[u8]) -> bool {
|
||||
if !bytes.starts_with(&SIGNATURE) {
|
||||
return false;
|
||||
}
|
||||
match directory_names(bytes) {
|
||||
Some(names) => names.iter().any(|n| ENCRYPTED_STREAMS.iter().any(|e| n.eq_ignore_ascii_case(e))),
|
||||
None => ENCRYPTED_STREAMS.iter().any(|e| contains_utf16(bytes, e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn contains_utf16(hay: &[u8], needle: &str) -> bool {
|
||||
let n: Vec<u8> = needle.encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
!n.is_empty() && hay.windows(n.len()).any(|w| w == n.as_slice())
|
||||
}
|
||||
|
||||
/// Names of every directory entry, or `None` when the directory can't be read.
|
||||
fn directory_names(b: &[u8]) -> Option<Vec<String>> {
|
||||
if !b.starts_with(&SIGNATURE) {
|
||||
return None;
|
||||
}
|
||||
let shift = u16_at(b, 30)?;
|
||||
if shift != 9 && shift != 12 {
|
||||
return None;
|
||||
}
|
||||
let size = 1usize << shift;
|
||||
let per = size / 4;
|
||||
let sector = |id: u32| -> Option<&[u8]> {
|
||||
let start = (id as usize).checked_add(1)?.checked_mul(size)?;
|
||||
b.get(start..start.checked_add(size)?)
|
||||
};
|
||||
// The DIFAT: the FAT's sector ids, 109 in the header then chained DIFAT sectors.
|
||||
let mut difat: Vec<u32> = (0..109).filter_map(|i| u32_at(b, 76 + i * 4)).filter(|&s| s < MAX_REG_SECT).collect();
|
||||
let mut next = u32_at(b, 68)?;
|
||||
for _ in 0..MAX_DIFAT_SECTORS {
|
||||
if next >= MAX_REG_SECT {
|
||||
break;
|
||||
}
|
||||
let s = sector(next)?;
|
||||
difat.extend((0..per - 1).filter_map(|i| u32_at(s, i * 4)).filter(|&x| x < MAX_REG_SECT));
|
||||
next = u32_at(s, (per - 1) * 4)?;
|
||||
}
|
||||
let fat_next = |id: u32| -> Option<u32> {
|
||||
let idx = id as usize;
|
||||
let fat_sector = *difat.get(idx / per)?;
|
||||
u32_at(sector(fat_sector)?, (idx % per) * 4)
|
||||
};
|
||||
let mut names = Vec::new();
|
||||
let mut id = u32_at(b, 48)?;
|
||||
for _ in 0..MAX_DIR_SECTORS {
|
||||
if id == END_OF_CHAIN {
|
||||
return Some(names);
|
||||
}
|
||||
if id >= MAX_REG_SECT {
|
||||
return None;
|
||||
}
|
||||
let s = sector(id)?;
|
||||
for e in s.as_chunks::<128>().0 {
|
||||
let len = usize::from(u16_at(e, 64)?);
|
||||
if !(2..=64).contains(&len) {
|
||||
continue;
|
||||
}
|
||||
let units: Vec<u16> = (0..(len - 2) / 2).filter_map(|i| u16_at(e, i * 2)).collect();
|
||||
names.push(String::from_utf16_lossy(&units));
|
||||
}
|
||||
id = fat_next(id)?;
|
||||
}
|
||||
// A directory longer than the bound (or a cyclic chain): report what was read.
|
||||
Some(names)
|
||||
let limits = limits();
|
||||
ENCRYPTED_STREAMS.iter().any(|name| craft_cfb::has_entry_named(bytes, name, &limits))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -105,6 +26,7 @@ mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use craft_cfb::{ENDOFCHAIN as END_OF_CHAIN, SIGNATURE};
|
||||
|
||||
/// A minimal valid compound file (512-byte sectors: FAT at sector 0, directory at sector 1)
|
||||
/// whose directory holds a root entry plus the given stream names.
|
||||
@@ -146,7 +68,7 @@ mod tests {
|
||||
#[test]
|
||||
fn reads_directory_names() {
|
||||
let b = build(&["EncryptionInfo", "EncryptedPackage"]);
|
||||
assert_eq!(directory_names(&b), Some(vec!["Root Entry".into(), "EncryptionInfo".into(), "EncryptedPackage".into()]));
|
||||
assert_eq!(craft_cfb::directory_names(&b, &limits()), Some(vec!["Root Entry".into(), "EncryptionInfo".into(), "EncryptedPackage".into()]));
|
||||
assert!(is_encrypted(&b));
|
||||
// A PowerPoint 97-2003 .ppt is a compound file too, without the encryption streams.
|
||||
assert!(!is_encrypted(&build(&["PowerPoint Document", "Current User"])));
|
||||
|
||||
+24
-38
@@ -255,46 +255,11 @@ pub fn sidecar_part(name: &str) -> bool {
|
||||
}
|
||||
|
||||
pub fn dir_of(part: &str) -> String {
|
||||
let p = part.trim_start_matches('/');
|
||||
match p.rfind('/') {
|
||||
Some(i) => p.get(..i).unwrap_or("").to_string(),
|
||||
None => String::new(),
|
||||
}
|
||||
craft_opc::dir_of(part).to_owned()
|
||||
}
|
||||
|
||||
pub fn file_of(part: &str) -> &str {
|
||||
part.rsplit('/').next().unwrap_or(part)
|
||||
}
|
||||
|
||||
pub fn rels_path(part: &str) -> String {
|
||||
let p = part.trim_start_matches('/');
|
||||
let dir = dir_of(p);
|
||||
let file = file_of(p);
|
||||
if dir.is_empty() { format!("_rels/{file}.rels") } else { format!("{dir}/_rels/{file}.rels") }
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
let c = b.get(i).copied().unwrap_or(0);
|
||||
if c == b'%'
|
||||
&& let Some(h) = b
|
||||
.get(i + 1..i + 3)
|
||||
.filter(|h| h.iter().all(u8::is_ascii_hexdigit))
|
||||
.and_then(|h| std::str::from_utf8(h).ok())
|
||||
.and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(h);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
use craft_opc::percent_decode;
|
||||
pub use craft_opc::{file_of, rels_path};
|
||||
|
||||
/// Resolve a relative target against a base directory into a part name.
|
||||
pub fn resolve(base: &str, target: &str) -> String {
|
||||
@@ -469,6 +434,27 @@ impl PackageOut {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_names_preserve_relationship_wire_policy() {
|
||||
for (part, dir, file, rels) in [
|
||||
("", "", "", "_rels/.rels"),
|
||||
("/", "", "", "_rels/.rels"),
|
||||
("///ppt/slides/slide1.xml", "ppt/slides", "slide1.xml", "ppt/slides/_rels/slide1.xml.rels"),
|
||||
("ppt/", "ppt", "", "ppt/_rels/.rels"),
|
||||
("é/😀.xml", "é", "😀.xml", "é/_rels/😀.xml.rels"),
|
||||
] {
|
||||
assert_eq!(dir_of(part), dir);
|
||||
assert_eq!(file_of(part), file);
|
||||
assert_eq!(rels_path(part), rels);
|
||||
}
|
||||
assert_eq!(percent_decode("a+b%20c%2Fd%23e"), "a+b c/d#e");
|
||||
assert_eq!(percent_decode("% %1 %zz %+1 %ff"), "% %1 %zz %+1 �");
|
||||
// Keep Deck's policy: strip the raw fragment first, then decode percent escapes once.
|
||||
assert_eq!(resolve("ppt/slides", "../media/a%23b.png#ignored"), "ppt/media/a#b.png");
|
||||
assert_eq!(resolve("ppt/slides", "%252e%252e/a"), "ppt/slides/%2e%2e/a");
|
||||
assert_eq!(resolve("ppt/slides", "%2e%2e/%2e%2e/%2e%2e/a"), "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_keeps_encoded_hash_and_strips_fragment() {
|
||||
assert_eq!(resolve("ppt/slides", "../media/a%23b.png"), "ppt/media/a#b.png");
|
||||
|
||||
+22
-48
@@ -1,59 +1,33 @@
|
||||
//! A minimal PNG encoder for the placeholder image written when a picture's media is missing.
|
||||
//! The placeholder image written when a picture's media is missing: a 1×1 fully transparent RGBA
|
||||
//! PNG, kept as its fixed bytes (signature, IHDR, one stored-deflate IDAT scanline, IEND) so the
|
||||
//! app carries no PNG encoder of its own.
|
||||
|
||||
fn crc32(data: &[u8]) -> u32 {
|
||||
let mut c = 0xFFFF_FFFFu32;
|
||||
for b in data {
|
||||
c ^= *b as u32;
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
}
|
||||
|
||||
fn adler32(data: &[u8]) -> u32 {
|
||||
let (mut a, mut b) = (1u32, 0u32);
|
||||
for x in data {
|
||||
a = (a + *x as u32) % 65521;
|
||||
b = (b + a) % 65521;
|
||||
}
|
||||
(b << 16) | a
|
||||
}
|
||||
|
||||
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
let mut c = Vec::with_capacity(data.len() + 4);
|
||||
c.extend_from_slice(kind);
|
||||
c.extend_from_slice(data);
|
||||
out.extend_from_slice(&c);
|
||||
out.extend_from_slice(&crc32(&c).to_be_bytes());
|
||||
}
|
||||
/// The PNG file, byte for byte what the former local encoder produced.
|
||||
const TRANSPARENT_1X1: [u8; 73] = [
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
|
||||
0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x01, 0x05, 0x00, 0xFA, 0xFF,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x64, 0x78, 0x95, 0x38, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60,
|
||||
0x82,
|
||||
];
|
||||
|
||||
/// A 1×1 fully transparent RGBA PNG.
|
||||
pub fn transparent_1x1() -> Vec<u8> {
|
||||
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
let mut ihdr = vec![];
|
||||
ihdr.extend_from_slice(&1u32.to_be_bytes());
|
||||
ihdr.extend_from_slice(&1u32.to_be_bytes());
|
||||
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
|
||||
chunk(&mut out, b"IHDR", &ihdr);
|
||||
// One scanline: filter byte + RGBA, stored (uncompressed) deflate block.
|
||||
let raw = [0u8, 0, 0, 0, 0];
|
||||
let mut z = vec![0x78, 0x01, 0x01];
|
||||
z.extend_from_slice(&(raw.len() as u16).to_le_bytes());
|
||||
z.extend_from_slice(&(!(raw.len() as u16)).to_le_bytes());
|
||||
z.extend_from_slice(&raw);
|
||||
z.extend_from_slice(&adler32(&raw).to_be_bytes());
|
||||
chunk(&mut out, b"IDAT", &z);
|
||||
chunk(&mut out, b"IEND", &[]);
|
||||
out
|
||||
TRANSPARENT_1X1.to_vec()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
#[test]
|
||||
fn crc_known() {
|
||||
assert_eq!(super::crc32(b"IEND"), 0xAE42_6082);
|
||||
assert!(super::transparent_1x1().starts_with(b"\x89PNG"));
|
||||
fn placeholder_is_a_transparent_1x1_png() {
|
||||
let png = super::transparent_1x1();
|
||||
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
|
||||
// IHDR: 1×1, 8-bit RGBA, no interlace.
|
||||
assert_eq!(&png[12..16], b"IHDR");
|
||||
assert_eq!(&png[16..29], &[0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]);
|
||||
assert!(png.ends_with(b"IEND\xAE\x42\x60\x82"));
|
||||
// The stored scanline: filter byte 0, then one pixel with zero alpha.
|
||||
assert_eq!(&png[49..54], &[0, 0, 0, 0, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,11 +25,24 @@ use crate::PptxError;
|
||||
use crate::opc::{self, Package, Rels};
|
||||
use crate::xml::{Doc, El, Node};
|
||||
|
||||
/// A snapshot of the import state a discarded read rolls back to.
|
||||
pub struct Mark {
|
||||
diagram_xml_bytes: usize,
|
||||
media: usize,
|
||||
media_keys: usize,
|
||||
tag_bytes: usize,
|
||||
tags_capped: bool,
|
||||
kept_sidecar_bytes: usize,
|
||||
kept_chart_keys: usize,
|
||||
}
|
||||
|
||||
/// Import state shared by all parts.
|
||||
pub struct Imp<'a> {
|
||||
pub pkg: &'a Package,
|
||||
pub media: Vec<MediaItem>,
|
||||
pub media_by_part: HashMap<String, MediaId>,
|
||||
/// Keys added to `media_by_part`, in order, so a rollback removes only its own.
|
||||
pub media_keys: Vec<String>,
|
||||
pub next: u32,
|
||||
pub slide_by_part: HashMap<String, SlideId>,
|
||||
pub custom_show_names: HashMap<String, String>,
|
||||
@@ -45,6 +58,8 @@ pub struct Imp<'a> {
|
||||
pub chart_points_cap: usize,
|
||||
/// Cached kept sidecars by normalized chart part name.
|
||||
pub kept_charts: HashMap<String, deckcraft_model::chart::ChartKept>,
|
||||
/// Keys added to `kept_charts`, in order, for rollback.
|
||||
pub kept_chart_keys: Vec<String>,
|
||||
/// Chart parts whose sidecar capture was refused, with the retained-byte total it started from:
|
||||
/// the same start gives the same refusal, so the copy is not repeated.
|
||||
pub rejected_kept: HashMap<String, usize>,
|
||||
@@ -56,6 +71,12 @@ pub struct Imp<'a> {
|
||||
pub tag_bytes: usize,
|
||||
/// The tag budget ran out and the warning was given.
|
||||
pub tags_capped: bool,
|
||||
/// 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`).
|
||||
pub smartart_shapes: usize,
|
||||
/// Bytes of SmartArt layout, style and colour definitions copied into diagrams so far.
|
||||
pub diagram_xml_bytes: usize,
|
||||
/// Whether a part has relationships of its own, by normalized part name: looked up once
|
||||
/// however many embedded objects point at the part.
|
||||
pub has_rels: HashMap<String, bool>,
|
||||
@@ -77,9 +98,41 @@ impl Imp<'_> {
|
||||
let content_type = self.pkg.content_type(part).filter(|c| !c.is_empty()).unwrap_or_else(|| crate::mime_for(&name).to_string());
|
||||
let id = MediaId(self.alloc());
|
||||
self.media.push(MediaItem { id, name, content_type, data: Arc::new(data), link: None });
|
||||
self.media_keys.push(key.clone());
|
||||
self.media_by_part.insert(key, id);
|
||||
Some(id)
|
||||
}
|
||||
/// What a discarded read must give back: the budgets it charged and the media and kept-chart
|
||||
/// entries it added (see [`Imp::rollback`]).
|
||||
pub fn mark(&self) -> Mark {
|
||||
Mark {
|
||||
diagram_xml_bytes: self.diagram_xml_bytes,
|
||||
media: self.media.len(),
|
||||
media_keys: self.media_keys.len(),
|
||||
tag_bytes: self.tag_bytes,
|
||||
tags_capped: self.tags_capped,
|
||||
kept_sidecar_bytes: self.kept_sidecar_bytes,
|
||||
kept_chart_keys: self.kept_chart_keys.len(),
|
||||
}
|
||||
}
|
||||
/// Undo everything since `m`: only the entries added since are removed, so the cost follows
|
||||
/// what the discarded read added, not the size of the caches.
|
||||
pub fn rollback(&mut self, m: &Mark) {
|
||||
self.diagram_xml_bytes = m.diagram_xml_bytes;
|
||||
self.tag_bytes = m.tag_bytes;
|
||||
self.tags_capped = m.tags_capped;
|
||||
self.kept_sidecar_bytes = m.kept_sidecar_bytes;
|
||||
self.media.truncate(m.media);
|
||||
for k in self.media_keys.drain(m.media_keys..) {
|
||||
self.media_by_part.remove(&k);
|
||||
}
|
||||
for k in self.kept_chart_keys.drain(m.kept_chart_keys..) {
|
||||
self.kept_charts.remove(&k);
|
||||
}
|
||||
// Chart decode work (`chart_decode_bytes`, `chart_points`) stays charged: it was done, and
|
||||
// giving it back would let a discarded read repeat it. `rejected_kept` is keyed by the
|
||||
// retained total a refusal started from, so it stays valid after the rollback.
|
||||
}
|
||||
/// Media item for an external link.
|
||||
pub fn media_link(&mut self, url: &str) -> MediaId {
|
||||
if let Some(m) = self.media.iter().find(|m| m.link.as_deref() == Some(url)) {
|
||||
@@ -529,6 +582,7 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec<
|
||||
pkg: &pkg,
|
||||
media: vec![],
|
||||
media_by_part: HashMap::new(),
|
||||
media_keys: vec![],
|
||||
next: 0,
|
||||
slide_by_part: HashMap::new(),
|
||||
custom_show_names: HashMap::new(),
|
||||
@@ -538,11 +592,15 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec<
|
||||
chart_points: 0,
|
||||
chart_points_cap: chart::MAX_PRESENTATION_CHART_POINTS,
|
||||
kept_charts: HashMap::new(),
|
||||
kept_chart_keys: vec![],
|
||||
rejected_kept: HashMap::new(),
|
||||
chart_decode_bytes: 0,
|
||||
tags_by_part: HashMap::new(),
|
||||
tag_bytes: 0,
|
||||
tags_capped: false,
|
||||
theme_extra_bytes: 0,
|
||||
smartart_shapes: 0,
|
||||
diagram_xml_bytes: 0,
|
||||
has_rels: HashMap::new(),
|
||||
};
|
||||
let part = Part::new(&pkg, &theme_path, &doc);
|
||||
@@ -589,6 +647,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) ->
|
||||
pkg: &pkg,
|
||||
media: vec![],
|
||||
media_by_part: HashMap::new(),
|
||||
media_keys: vec![],
|
||||
next: max_id.max(1),
|
||||
slide_by_part: HashMap::new(),
|
||||
custom_show_names: HashMap::new(),
|
||||
@@ -598,11 +657,15 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) ->
|
||||
chart_points: 0,
|
||||
chart_points_cap,
|
||||
kept_charts: HashMap::new(),
|
||||
kept_chart_keys: vec![],
|
||||
rejected_kept: HashMap::new(),
|
||||
chart_decode_bytes: 0,
|
||||
tags_by_part: HashMap::new(),
|
||||
tag_bytes: 0,
|
||||
tags_capped: false,
|
||||
theme_extra_bytes: 0,
|
||||
smartart_shapes: 0,
|
||||
diagram_xml_bytes: 0,
|
||||
has_rels: HashMap::new(),
|
||||
};
|
||||
// Slide ids first so hyperlinks anywhere can point at slides.
|
||||
@@ -1545,6 +1608,54 @@ fn header_footer(p: &Presentation) -> HeaderFooter {
|
||||
hf
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod rollback_tests {
|
||||
use super::*;
|
||||
|
||||
/// A rolled-back read gives back its budgets and removes only the media and kept-chart entries it added.
|
||||
#[test]
|
||||
fn rollback_restores_budgets_and_removes_only_what_was_added() {
|
||||
let bytes = crate::export(&deckcraft_model::Presentation::default()).expect("export");
|
||||
let pkg = Package::open(&bytes).expect("package");
|
||||
let mut imp = Imp {
|
||||
pkg: &pkg,
|
||||
media: vec![],
|
||||
media_by_part: HashMap::new(),
|
||||
media_keys: vec![],
|
||||
next: 0,
|
||||
slide_by_part: HashMap::new(),
|
||||
custom_show_names: HashMap::new(),
|
||||
table_style_ids: Vec::new(),
|
||||
vml_previews: HashMap::new(),
|
||||
kept_sidecar_bytes: 0,
|
||||
chart_points: 0,
|
||||
chart_points_cap: chart::MAX_PRESENTATION_CHART_POINTS,
|
||||
kept_charts: HashMap::new(),
|
||||
kept_chart_keys: vec![],
|
||||
rejected_kept: HashMap::new(),
|
||||
chart_decode_bytes: 0,
|
||||
tags_by_part: HashMap::new(),
|
||||
tag_bytes: 0,
|
||||
tags_capped: false,
|
||||
theme_extra_bytes: 0,
|
||||
smartart_shapes: 0,
|
||||
diagram_xml_bytes: 0,
|
||||
has_rels: HashMap::new(),
|
||||
};
|
||||
let kept_before = imp.media_for("ppt/presentation.xml").expect("media");
|
||||
let (m, items) = (imp.mark(), imp.media.len());
|
||||
assert!(imp.media_for("ppt/presProps.xml").is_some());
|
||||
imp.kept_chart_keys.push("ppt/charts/chart1.xml".into());
|
||||
imp.kept_charts.insert("ppt/charts/chart1.xml".into(), Default::default());
|
||||
(imp.diagram_xml_bytes, imp.tag_bytes, imp.tags_capped, imp.kept_sidecar_bytes) = (7, 5, true, 9);
|
||||
imp.rollback(&m);
|
||||
assert_eq!(imp.media.len(), items);
|
||||
assert_eq!(imp.media_by_part.get("ppt/presentation.xml"), Some(&kept_before));
|
||||
assert!(!imp.media_by_part.contains_key("ppt/presprops.xml") && imp.kept_charts.is_empty() && imp.kept_chart_keys.is_empty());
|
||||
assert_eq!((imp.diagram_xml_bytes, imp.tag_bytes, imp.tags_capped, imp.kept_sidecar_bytes), (0, 0, false, 0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -600,6 +600,7 @@ pub(crate) fn capture_kept(imp: &mut super::Imp, chart_part: &str) -> deckcraft_
|
||||
return ChartKept::default();
|
||||
}
|
||||
imp.kept_sidecar_bytes += rel_total;
|
||||
imp.kept_chart_keys.push(key.clone());
|
||||
imp.kept_charts.insert(key, kept.clone());
|
||||
kept
|
||||
}
|
||||
|
||||
@@ -474,20 +474,54 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S
|
||||
};
|
||||
// Keep the parts it points to so a save writes it back whole (#203). A part with relationships
|
||||
// of its own, or an external link, can't be carried: the save then falls back to the preview.
|
||||
let parts = super::rel_refs(e)
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
let rel = part.rels.get(&id).filter(|r| !r.external)?;
|
||||
let pkg = imp.pkg;
|
||||
if *imp.has_rels.entry(crate::opc::norm(&rel.target)).or_insert_with(|| !pkg.rels(&rel.target).items.is_empty()) {
|
||||
return None;
|
||||
// Validate every relationship (and charge the budget) before copying anything, so a fallback
|
||||
// that cannot be kept whole copies no part at all.
|
||||
let mark = imp.mark();
|
||||
let mut planned = Vec::new();
|
||||
let mut spent = imp.diagram_xml_bytes;
|
||||
let mut ok = true;
|
||||
for id in super::rel_refs(e) {
|
||||
let Some(rel) = part.rels.get(&id).filter(|r| !r.external) else {
|
||||
ok = false;
|
||||
break;
|
||||
};
|
||||
let pkg = imp.pkg;
|
||||
if *imp.has_rels.entry(crate::opc::norm(&rel.target)).or_insert_with(|| !pkg.rels(&rel.target).items.is_empty()) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
// A diagram's definition parts copied here count against the same presentation-wide budget.
|
||||
if rel.kind.starts_with("diagram") && !imp.media_by_part.contains_key(&crate::opc::norm(&rel.target)) {
|
||||
let len = pkg.get(&rel.target).map_or(0, |b| b.len());
|
||||
if len > MAX_DIAGRAM_PART_BYTES || spent.saturating_add(len) > MAX_DIAGRAM_XML_BYTES {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
let (kind, target) = (rel.ty.clone(), rel.target.clone());
|
||||
let media = if rel.kind == "diagramData" { diagram_data(imp, &target) } else { imp.media_for(&target) };
|
||||
Some((id, kind, media?))
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.unwrap_or_default();
|
||||
spent += len;
|
||||
}
|
||||
if pkg.get(&rel.target).is_none() {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
planned.push((id, rel.ty.clone(), rel.target.clone(), rel.kind == "diagramData"));
|
||||
}
|
||||
let parts = if ok {
|
||||
imp.diagram_xml_bytes = spent;
|
||||
let copied: Option<Vec<_>> = planned
|
||||
.into_iter()
|
||||
.map(|(id, kind, target, data)| {
|
||||
let media = if data { diagram_data(imp, &target) } else { imp.media_for(&target) };
|
||||
Some((id, kind, media?))
|
||||
})
|
||||
.collect();
|
||||
if copied.is_none() {
|
||||
imp.rollback(&mark);
|
||||
}
|
||||
copied
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let parts = parts.unwrap_or_default();
|
||||
s.kind = ShapeKind::Opaque { xml: part.keep(e), preview, label, parts };
|
||||
s
|
||||
}
|
||||
@@ -558,13 +592,28 @@ fn diagram_data(imp: &mut Imp, target: &str) -> Option<deckcraft_model::MediaId>
|
||||
data: std::sync::Arc::new(xml.into_bytes()),
|
||||
link: None,
|
||||
});
|
||||
imp.media_keys.push(norm_target.clone());
|
||||
imp.media_by_part.insert(norm_target, id);
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// Shapes all SmartArt drawings of one presentation may add; a frame read after that is left as a
|
||||
/// placeholder. Each frame that references a drawing reads it again.
|
||||
const MAX_SMARTART_SHAPES: usize = 250_000;
|
||||
|
||||
/// SmartArt definition XML (layout, style, colours) all diagrams of one presentation may copy.
|
||||
const MAX_DIAGRAM_XML_BYTES: usize = 32 << 20;
|
||||
|
||||
/// The largest single diagram definition part copied.
|
||||
const MAX_DIAGRAM_PART_BYTES: usize = 4 << 20;
|
||||
|
||||
fn count_shapes(shapes: &[Shape]) -> usize {
|
||||
shapes.iter().map(|s| 1 + count_shapes(s.children())).sum()
|
||||
}
|
||||
|
||||
/// SmartArt: read the pre-drawn shapes of its drawing part as a group.
|
||||
fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> Option<Shape> {
|
||||
if depth > 8 {
|
||||
if depth > 8 || imp.smartart_shapes >= MAX_SMARTART_SHAPES {
|
||||
return None;
|
||||
}
|
||||
let rel_ids = gd.child("relIds")?;
|
||||
@@ -576,10 +625,21 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) ->
|
||||
let dpart = Part::new(imp.pkg, &drawing_rel, &d);
|
||||
let tree = d.root.child("spTree")?;
|
||||
let mut sub = IdCtx { fresh: true, ..Default::default() };
|
||||
let before = imp.smartart_shapes;
|
||||
let mark = imp.mark();
|
||||
let children = sp_tree(imp, &dpart, &mut sub, tree, depth + 1);
|
||||
if children.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Counted once here, nested SmartArt included: a drawing that frames reuse counts every time it is read.
|
||||
let total = before.saturating_add(count_shapes(&children));
|
||||
if total > MAX_SMARTART_SHAPES {
|
||||
// Over the presentation's remaining budget: a placeholder, and nothing charged, nested SmartArt included.
|
||||
imp.smartart_shapes = before;
|
||||
imp.rollback(&mark);
|
||||
return None;
|
||||
}
|
||||
imp.smartart_shapes = total;
|
||||
let children = smartart_text_rects(imp, &mut sub, tree, children, depth + 1);
|
||||
let mut g = frame.clone();
|
||||
let x = frame.xfrm.unwrap_or_default();
|
||||
@@ -668,10 +728,11 @@ fn text_on_rect(imp: &mut Imp, ctx: &mut IdCtx, s: &mut Shape, t: Xfrm) -> Optio
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if ctx.count >= MAX_SHAPES {
|
||||
if ctx.count >= MAX_SHAPES || imp.smartart_shapes >= MAX_SMARTART_SHAPES {
|
||||
return None;
|
||||
}
|
||||
ctx.count += 1;
|
||||
imp.smartart_shapes += 1;
|
||||
let text = s.text.take();
|
||||
// No fill, outline or effects; the style keeps only the text colour and font.
|
||||
let style = s.style.clone().map(|mut st| {
|
||||
@@ -707,15 +768,22 @@ fn text_area(geom: &Geom, w: f64, h: f64) -> deckcraft_geom::Rect {
|
||||
|
||||
/// The outline of a SmartArt graphic (for the Text Pane), with its layout, quick style and colour
|
||||
/// parts kept to be written back.
|
||||
fn diagram_outline(imp: &Imp, part: &Part, rel_ids: &El, data: &El) -> Option<deckcraft_model::Diagram> {
|
||||
fn diagram_outline(imp: &mut Imp, part: &Part, rel_ids: &El, data: &El) -> Option<deckcraft_model::Diagram> {
|
||||
let nodes = crate::dgm::outline(data);
|
||||
if nodes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (pkg, spent) = (imp.pkg, std::cell::Cell::new(imp.diagram_xml_bytes));
|
||||
let raw = |attr: &str| -> Option<String> {
|
||||
let rel = part.rels.get(rel_ids.attr(attr)?)?;
|
||||
let bytes = imp.pkg.get(&rel.target)?;
|
||||
(bytes.len() <= 4 << 20).then(|| String::from_utf8(bytes.to_vec()).ok()).flatten()
|
||||
let bytes = pkg.get(&rel.target)?;
|
||||
// Every diagram copies its definitions, so the copies share one presentation-wide budget.
|
||||
if bytes.len() > MAX_DIAGRAM_PART_BYTES || spent.get().saturating_add(bytes.len()) > MAX_DIAGRAM_XML_BYTES {
|
||||
return None;
|
||||
}
|
||||
let xml = String::from_utf8(bytes.to_vec()).ok()?;
|
||||
spent.set(spent.get() + xml.len());
|
||||
Some(xml)
|
||||
};
|
||||
let layout_xml = raw("r:lo");
|
||||
let (layout_id, cat) = layout_xml
|
||||
@@ -736,16 +804,19 @@ fn diagram_outline(imp: &Imp, part: &Part, rel_ids: &El, data: &El) -> Option<de
|
||||
let pr = data.path(&["ptLst"]).and_then(|l| l.children_named("pt").find(|p| p.attr("type") == Some("doc"))).and_then(|p| p.child("prSet"));
|
||||
let style = crate::dgm::style_for(pr.and_then(|p| p.attr("qsTypeId")).unwrap_or("")).to_string();
|
||||
let colors = crate::dgm::colors_for(pr.and_then(|p| p.attr("csTypeId")).unwrap_or(""));
|
||||
let (style_xml, colors_xml) = (raw("r:qs"), raw("r:cs"));
|
||||
imp.diagram_xml_bytes = spent.get();
|
||||
Some(deckcraft_model::Diagram {
|
||||
kind: crate::dgm::kind_for(&id, &cat).to_string(),
|
||||
nodes,
|
||||
style,
|
||||
colors,
|
||||
imported: true,
|
||||
layout_id: id,
|
||||
// Without the layout part the writer generates one for `kind`; empty keeps data's loTypeId in step with it.
|
||||
layout_id: if layout_xml.is_some() { id } else { String::new() },
|
||||
layout_xml,
|
||||
style_xml: raw("r:qs"),
|
||||
colors_xml: raw("r:cs"),
|
||||
style_xml,
|
||||
colors_xml,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -20,11 +20,15 @@ fn font_set(e: Option<&El>) -> FontSet {
|
||||
FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), scripts }
|
||||
}
|
||||
|
||||
/// Bytes of preserved theme XML (object defaults and extra colour schemes) all masters of one
|
||||
/// presentation may keep.
|
||||
const MAX_THEME_EXTRA_BYTES: usize = 16 << 20;
|
||||
|
||||
pub fn read_theme(imp: &mut Imp, part: &Part, root: &El) -> Theme {
|
||||
let mut t = Theme { name: root.attr("name").unwrap_or("Theme").to_string(), ..Default::default() };
|
||||
let Some(te) = root.child("themeElements") else { return t };
|
||||
if let Some(cs) = te.child("clrScheme") {
|
||||
let mut scheme = ColorScheme { name: cs.attr("name").unwrap_or("").to_string(), colors: t.colors.colors };
|
||||
let mut scheme = ColorScheme::new(cs.attr("name").unwrap_or("").to_string(), t.colors.colors);
|
||||
for slot in SchemeSlot::THEME {
|
||||
if let Some(c) = cs.child(slot.xml_name()).and_then(dml::color) {
|
||||
let rgb = match c.base {
|
||||
@@ -89,8 +93,13 @@ pub fn read_theme(imp: &mut Imp, part: &Part, root: &El) -> Theme {
|
||||
.filter(|e| !super::has_rel_refs(e))
|
||||
.map(|e| part.keep(e))
|
||||
.collect();
|
||||
if !extra.is_empty() {
|
||||
// Every master that references this theme keeps its own copy of the preserved XML, so the
|
||||
// copies share one budget for the presentation.
|
||||
if !extra.is_empty() && imp.theme_extra_bytes.saturating_add(extra.len()) <= MAX_THEME_EXTRA_BYTES {
|
||||
imp.theme_extra_bytes += extra.len();
|
||||
t.raw_extra = Some(extra);
|
||||
} else if !extra.is_empty() {
|
||||
log::warn!("pptx: theme object defaults not kept; the preserved-XML budget is spent");
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ pub fn draw_layout_with(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout,
|
||||
};
|
||||
let li = lines_of.line_at(run.para, *y);
|
||||
if !grads.iter().any(|(i, _)| *i == li) {
|
||||
let scheme = deckcraft_color::ColorScheme { name: String::new(), colors: [Rgba::BLACK; 12] };
|
||||
let scheme = deckcraft_color::ColorScheme::new(String::new(), [Rgba::BLACK; 12]);
|
||||
let stops = g.stops.iter().map(|s| (s.pos, s.color.resolve(&scheme, None))).collect();
|
||||
let bounds = l.lines.get(li).and_then(line_bounds).unwrap_or(tr);
|
||||
grads.push((li, paint::gradient(&g.shape, stops, bounds, run.alpha * ps.opacity)));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Slide show and presenter view: parity with PowerPoint
|
||||
|
||||
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-02 · **Change:** minor (deleting slides removes them from custom shows; previous: minor, Presenter View only with a second display on Linux and the BSDs, #1156; previous: minor, Set Up Slide Show ▸ Keep mouse cursor visible, #1445; previous: minor, Ctrl+wheel zooms the show around the pointer, #1286; previous: major, community PR wave 2026-10-14: interactive decks, laser pointer, See All Slides and zoom, go-to-slide number, custom show playback, presenter timer, clock, notes size and keyboard, Show Media Controls, swipe; breadth 68%; duplicated rows and headers folded; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-14 · **Change:** minor (a slide the show advances to again plays its animations again, #2090; previous: minor, deleting slides removes them from custom shows; previous: minor, Presenter View only with a second display on Linux and the BSDs, #1156; previous: minor, Set Up Slide Show ▸ Keep mouse cursor visible, #1445; previous: minor, Ctrl+wheel zooms the show around the pointer, #1286; previous: major, community PR wave 2026-10-14: interactive decks, laser pointer, See All Slides and zoom, go-to-slide number, custom show playback, presenter timer, clock, notes size and keyboard, Show Media Controls, swipe; breadth 68%; duplicated rows and headers folded; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
|
||||
Presenting is the job PowerPoint is hired for. This doc covers the show window, presenter view,
|
||||
rehearsal and recording. Transition and animation playback are in
|
||||
@@ -23,7 +23,8 @@ ready** (estimated), **10–16 h** to parity.
|
||||
| Hidden slides skipped | yes | yes | |
|
||||
| Hyperlinks and action settings followed (slides, web, mail, End Show, Last Viewed) | yes | yes | Only `http(s)` and `mailto` open outside the show, by design (`safe_url`) |
|
||||
| A shape with a triggered animation plays it when clicked; shapes an animation has hidden cannot be clicked; a shape without an action on top of one with an action blocks it; the pointer is a hand over what can be clicked | yes | yes | Click boxes are bounding boxes; "play sound" actions (`ppaction://media`) do nothing yet |
|
||||
| A slide the show returns to (link, arrow keys) looks as it was left; a triggered animation goes on where it stopped | yes | yes | A main-sequence step still playing when the show leaves is finished |
|
||||
| A slide the show returns to by a link or Back looks as it was left; a triggered animation goes on where it stopped | yes | yes | A main-sequence step still playing when the show leaves is finished |
|
||||
| A slide the show advances to again (click, →, Space, automatic advance, loop) starts over and plays its animations again | yes | yes | Its triggered animations start over too (#2090) |
|
||||
| "Advance on click" off: a click never leaves the slide (animation steps still play, keys still move on) | yes | yes | |
|
||||
| Hyperlinks and action settings followed (slides, web, mail, End Show, Last Viewed, Custom Show) | yes | yes | Only `http(s)` and `mailto` open outside the show, by design (`safe_url`). A Custom Show action plays that show |
|
||||
| Media playback with controls, play across slides, full-screen video, Play/Pause/Stop in the click sequence | yes | yes | WMA/WMV not decodable. Click sequence since #116. Slide Show ▸ Show Media Controls (on by default) hides the playback bar. Seeks and loops preserve new-generation video frames and end-of-stream; queue regression and repeated seeks across H.264/HEVC/VP9/AV1 in `crates/media` |
|
||||
@@ -96,4 +97,5 @@ Reading View in a window with navigation: present (checklist row done).
|
||||
| 2026-10-14 | minor | See All Slides (G) and click-to-zoom (Z) during the show. Presenter view opens that grid and sets black, white and zoom. Checklist breadth stays 66% |
|
||||
| 2026-10-24 | minor | Ctrl+wheel (Cmd+wheel on a Mac) zooms the show in and out around the pointer, up to 4×; the plain wheel still turns the page (#1286) |
|
||||
| 2026-10-23 | trivial | Presenter view draws the notes with their formatting (bullets, numbers, indents, bold/italic) instead of plain text (#1128) |
|
||||
| 2026-11-14 | minor | A slide the show advances to again starts over, so its entrance effects play again; Back and links still show it as it was left (#2090) |
|
||||
| 2026-10-10 | major | Created: show, presenter view, rehearse and record, compared with PowerPoint 16.113's Slide Show tab and menu |
|
||||
|
||||
Reference in New Issue
Block a user