mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-01 02:04:59 -06:00
Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56c53986e9 | ||
|
|
399bf75642 | ||
|
|
6af018c195 | ||
|
|
c88ffe5177 | ||
|
|
38a3bbc72d | ||
|
|
aa00bd468a | ||
|
|
a0a4fac337 | ||
|
|
333590f9ae | ||
|
|
3001fb5dc1 | ||
|
|
523df35f5e | ||
|
|
356a77a7a9 | ||
|
|
98d1f7ad94 | ||
|
|
bc02000907 | ||
|
|
ab34c77599 | ||
|
|
90e44a619f | ||
|
|
25dc8b9dcf | ||
|
|
82d8ccff8c | ||
|
|
f65e481c95 | ||
|
|
2fb8a04999 | ||
|
|
0bce106403 | ||
|
|
329a17a997 | ||
|
|
41063f36f9 | ||
|
|
1740f3e136 | ||
|
|
6b2625f40f | ||
|
|
7f34fb3971 | ||
|
|
abfc33bbb3 | ||
|
|
c86eee0355 | ||
|
|
f0c202dca8 | ||
|
|
555e12c1a0 | ||
|
|
8b6fdce1ba | ||
|
|
54a9f741d6 | ||
|
|
d3161f6bb8 | ||
|
|
522f097f50 | ||
|
|
6d04a70cd8 | ||
|
|
63d1d2e588 | ||
|
|
76c05c1225 | ||
|
|
456cecdc58 | ||
|
|
d379334ea5 | ||
|
|
c3aab3ac1e | ||
|
|
ba45da9143 | ||
|
|
2427c60511 | ||
|
|
98bc3c32a8 | ||
|
|
d542b35bd4 | ||
|
|
0d190bc0af | ||
|
|
864820eda9 | ||
|
|
a121716629 | ||
|
|
0540fe22cf | ||
|
|
4ab850e248 | ||
|
|
5529c695bf | ||
|
|
d403e047cf | ||
|
|
5e73b015a3 | ||
|
|
93caf4d222 | ||
|
|
695edabe55 | ||
|
|
1da4e33490 | ||
|
|
11362ac715 | ||
|
|
37ac38cac7 | ||
|
|
36bf5591c1 | ||
|
|
4b14a96cc8 | ||
|
|
aa0afa1462 | ||
|
|
78b64ed2fc |
@@ -297,6 +297,16 @@ pub fn parse_params(doc: &str) -> std::result::Result<Vec<Param<'_>>, String> {
|
||||
/// growing would duplicate ids (#407).
|
||||
pub(crate) const NO_ID_SPACE: &str = "the presentation has used every object id and can hold no more";
|
||||
|
||||
/// A style command whose keys are all optional is refused when it is given none of them, rather
|
||||
/// than answering `changed` for a call that sets nothing.
|
||||
pub(crate) fn require_any(p: &Value, cmd: &str, keys: &[&str]) -> Result<()> {
|
||||
if keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
return Ok(());
|
||||
}
|
||||
let (last, rest) = keys.split_last().map_or(("", &[][..]), |(l, r)| (*l, r));
|
||||
Err(bad(cmd, format!("`{cmd}` was given nothing to set: pass {} or {last}", rest.join(", "))))
|
||||
}
|
||||
|
||||
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
|
||||
}
|
||||
@@ -377,12 +387,17 @@ pub(crate) fn ok() -> Result<Value> {
|
||||
|
||||
/// Parse a colour param: `"#RRGGBB"`, `"accent1"`…, or `{"scheme":"accent2","lumMod":75000}`.
|
||||
/// A preset or system colour keeps its base: `{"preset":"red"}`,
|
||||
/// `{"system":"windowText","last":"#000000"}`.
|
||||
/// `{"system":"windowText","last":"#000000"}`. `"mods"` lists transforms in order:
|
||||
/// `{"preset":"red","mods":[{"op":"inv"},{"op":"inv"}]}`. A list longer than [`MAX_COLOR_MODS`]
|
||||
/// makes the color invalid.
|
||||
pub(crate) fn color_param(p: &Value, key: &str) -> Option<deckcraft_model::ColorRef> {
|
||||
let v = p.get(key)?;
|
||||
color_value(v)
|
||||
}
|
||||
|
||||
/// Most transforms a color param's `"mods"` list may hold.
|
||||
pub(crate) const MAX_COLOR_MODS: usize = 256;
|
||||
|
||||
pub(crate) fn color_value(v: &Value) -> Option<deckcraft_model::ColorRef> {
|
||||
use deckcraft_model::ColorRef;
|
||||
match v {
|
||||
@@ -413,8 +428,22 @@ pub(crate) fn color_value(v: &Value) -> Option<deckcraft_model::ColorRef> {
|
||||
ColorRef::rgb(deckcraft_color::Rgba::from_hex(o.get("rgb").and_then(Value::as_str)?)?)
|
||||
};
|
||||
for (k, val) in o {
|
||||
if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, val.as_i64().and_then(|x| i32::try_from(x).ok())) {
|
||||
c.mods.push(t);
|
||||
let n = val.as_i64().and_then(|x| i32::try_from(x).ok());
|
||||
if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, n) {
|
||||
// A value-bearing transform without a usable integer is skipped, not zeroed.
|
||||
if n.is_some() || t.value().is_none() {
|
||||
c.mods.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
// `mods` lists transforms in order, repeats included: `[{"op":"inv"},{"op":"lumMod","val":50000}]`.
|
||||
if let Some(list) = o.get("mods") {
|
||||
let list = list.as_array()?;
|
||||
if list.len() > MAX_COLOR_MODS {
|
||||
return None;
|
||||
}
|
||||
for m in list {
|
||||
c.mods.push(<deckcraft_color::ColorTransform as serde::Deserialize>::deserialize(m).ok()?);
|
||||
}
|
||||
}
|
||||
Some(c)
|
||||
@@ -547,6 +576,10 @@ pub(crate) fn current_names(doc: &deckcraft_model::Presentation, sel: &crate::Se
|
||||
/// A name ending in `?` is optional. Text after `→` is the result, not an input.
|
||||
pub fn needs_arguments(params: &str) -> bool {
|
||||
let input = params.split('→').next().unwrap_or(params);
|
||||
// Every key optional, but the command refuses a call that gives none of them.
|
||||
if input.contains("(at least one key)") {
|
||||
return true;
|
||||
}
|
||||
let Some(start) = input.find('{') else { return false };
|
||||
let inside = input.get(start + 1..).unwrap_or("");
|
||||
let inside = inside.split('}').next().unwrap_or(inside);
|
||||
@@ -743,6 +776,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_integer_colour_transform_is_skipped_not_zeroed() {
|
||||
for bad in [serde_json::json!("75000"), serde_json::json!(75000.0), serde_json::json!(0.75), serde_json::json!(3_000_000_000i64)] {
|
||||
let c = color_value(&serde_json::json!({"scheme": "accent1", "lumMod": bad})).unwrap();
|
||||
assert!(c.mods.is_empty(), "{bad}: {:?}", c.mods);
|
||||
}
|
||||
let c = color_value(&serde_json::json!({"scheme": "accent1", "lumMod": 75000})).unwrap();
|
||||
assert_eq!(c.mods, vec![deckcraft_color::ColorTransform::LumMod(75000)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_palette_skips_a_command_that_needs_a_value() {
|
||||
assert!(needs_arguments("{path}"));
|
||||
@@ -752,6 +795,7 @@ mod tests {
|
||||
assert!(needs_arguments("{axis: horizontal|vertical, ids?}"));
|
||||
assert!(needs_arguments("{percent}"));
|
||||
assert!(!needs_arguments("{}"));
|
||||
assert!(needs_arguments("{left?: pt, top?: pt} (at least one key)"));
|
||||
assert!(!needs_arguments("{on?: bool}"));
|
||||
assert!(!needs_arguments("{theme?: name, size?: [w,h] pt, blank?: bool}"));
|
||||
assert!(!needs_arguments("{uid?: one entry, else all}"));
|
||||
@@ -783,5 +827,40 @@ mod tests {
|
||||
assert!(color_value(&json!({"preset": name})).is_some(), "{name}");
|
||||
}
|
||||
assert!(color_value(&json!({"system": "3dDkShadow", "last": "#000000"})).is_some());
|
||||
let listed = color_value(&json!({"preset": "red", "mods": [{"op": "inv"}, {"op": "lumOff", "val": 20_000}, {"op": "inv"}]}));
|
||||
let mods = vec![ColorTransform::Inv, ColorTransform::LumOff(20_000), ColorTransform::Inv];
|
||||
assert_eq!(listed, Some(ColorRef { base: ColorBase::Preset { name: "red".into() }, mods }));
|
||||
assert_eq!(color_value(&json!({"preset": "red", "mods": [{"op": "notATransform"}]})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_mods_lists_follow_keyed_transforms() {
|
||||
use deckcraft_color::{ColorTransform, SchemeSlot};
|
||||
use deckcraft_model::{ColorBase, ColorRef};
|
||||
use serde_json::json;
|
||||
let red = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] };
|
||||
assert_eq!(color_value(&json!({"preset": "red", "mods": []})), Some(red.clone()), "an empty list adds no transforms");
|
||||
let two = color_value(&json!({"preset": "red", "mods": [{"op": "lumMod", "val": 75_000}, {"op": "lumOff", "val": 10_000}]}));
|
||||
assert_eq!(two, Some(red.with(ColorTransform::LumMod(75_000)).with(ColorTransform::LumOff(10_000))));
|
||||
// The keyed `lumMod` comes first, then the list in order.
|
||||
let both =
|
||||
color_value(&json!({"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}, {"op": "lumMod", "val": 50_000}]}));
|
||||
let want = ColorRef::scheme(SchemeSlot::Accent2)
|
||||
.with(ColorTransform::LumMod(75_000))
|
||||
.with(ColorTransform::LumOff(10_000))
|
||||
.with(ColorTransform::LumMod(50_000));
|
||||
assert_eq!(both, Some(want));
|
||||
// An unknown op anywhere in the list, or a `mods` value that is not a list, makes the color invalid.
|
||||
assert_eq!(color_value(&json!({"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}, {"op": "sparkle"}]})), None);
|
||||
assert_eq!(color_value(&json!({"preset": "red", "mods": {"op": "inv"}})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_mods_lists_longer_than_the_cap_are_invalid() {
|
||||
use deckcraft_color::ColorTransform;
|
||||
use serde_json::json;
|
||||
let at_cap = color_value(&json!({"preset": "red", "mods": vec![json!({"op": "inv"}); MAX_COLOR_MODS]}));
|
||||
assert_eq!(at_cap.map(|c| c.mods), Some(vec![ColorTransform::Inv; MAX_COLOR_MODS]));
|
||||
assert_eq!(color_value(&json!({"preset": "red", "mods": vec![json!({"op": "inv"}); MAX_COLOR_MODS + 1]})), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,8 +335,9 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
return paste_plain(s, t);
|
||||
}
|
||||
let editing = s.doc()?.selection.text.is_some();
|
||||
if editing {
|
||||
let (editing, notes) = s.doc()?.selection.text.as_ref().map_or((false, false), |t| (true, t.notes));
|
||||
// Copied shapes are pasted as shapes even while a text box is being edited (the caret leaves it), but never into the notes.
|
||||
if editing && (notes || s.clipboard.text.is_some() || s.clipboard.shapes.is_empty()) {
|
||||
if let Some(body) = s.clipboard.text.clone() {
|
||||
return super::text::paste_body(s, &body);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::sync::Arc;
|
||||
use super::text::{format_body, format_para, format_run, format_run_levels};
|
||||
use super::{
|
||||
CommandSpec, always, bad, base64_decode, bool_or, bool_param, cmd, color_param, edit_shapes, f64_or, f64_param, has_doc, has_text,
|
||||
has_text_or_shapes, ids_param, ok, str_param,
|
||||
has_text_or_shapes, ids_param, ok, require_any, str_param,
|
||||
};
|
||||
use crate::{Result, Session};
|
||||
use deckcraft_model::ShapeId;
|
||||
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paragraph…",
|
||||
["Format"],
|
||||
None,
|
||||
"{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines}",
|
||||
"{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines, lineSpacingPt?: pt} (at least one key)",
|
||||
has_text_or_shapes,
|
||||
paragraph
|
||||
),
|
||||
@@ -259,7 +259,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Text Box Margins",
|
||||
["Format Shape", "Text Box"],
|
||||
None,
|
||||
"{left?: pt, top?: pt, right?: pt, bottom?: pt}",
|
||||
"{left?: pt, top?: pt, right?: pt, bottom?: pt} (at least one key)",
|
||||
has_text_or_shapes,
|
||||
margins
|
||||
),
|
||||
@@ -426,6 +426,87 @@ mod tests {
|
||||
assert!(r.size.is_none() && r.fill.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_dialog_ok_keeps_the_text_color() {
|
||||
use deckcraft_color::Rgba;
|
||||
let preset = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }.with(ColorTransform::LumMod(50_000));
|
||||
let system = ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgb(0x12, 0x34, 0x56) }, mods: vec![] }
|
||||
.with(ColorTransform::Alpha(60_000));
|
||||
// A transform without a value, and a color that is not opaque.
|
||||
let inverted = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }.with(ColorTransform::Inv);
|
||||
let translucent = ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgba(0x12, 0x34, 0x56, 0x80) }, mods: vec![] };
|
||||
let rgb = ColorRef::rgb(Rgba::rgba(0x12, 0x34, 0x56, 0x80));
|
||||
// A repeated transform, and two transforms in an order that is not alphabetical.
|
||||
let twice = inverted.clone().with(ColorTransform::Inv);
|
||||
let ordered = ColorRef::scheme(SchemeSlot::Accent2).with(ColorTransform::LumOff(20_000)).with(ColorTransform::LumMod(50_000));
|
||||
for color in [preset, system, inverted, translucent, rgb, twice, ordered] {
|
||||
let mut s = shape();
|
||||
let fill = Fill::Solid { color: color.clone() };
|
||||
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
|
||||
s.ui_requests.clear();
|
||||
s.execute("format.fontDialog", &json!({})).unwrap();
|
||||
let Some(UiRequest::Dialog { params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
|
||||
s.execute("format.fontDialog", &json!({"color": params["color"]})).unwrap();
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color }), "{}", params["color"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_dialog_ok_without_color_keeps_colors_a_command_cannot_give() {
|
||||
use deckcraft_color::Rgba;
|
||||
let last = Rgba::rgb(0x12, 0x34, 0x56);
|
||||
let preset = ColorRef { base: ColorBase::Preset { name: "notAColor".into() }, mods: vec![] }.with(ColorTransform::LumMod(50_000));
|
||||
let system = ColorRef { base: ColorBase::System { name: "notAColor".into(), last }, mods: vec![] };
|
||||
// More transforms than a command's `mods` list may carry, as an opened file can hold.
|
||||
let many = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![ColorTransform::Inv; crate::cmd::MAX_COLOR_MODS + 1] };
|
||||
for color in [preset, system, many] {
|
||||
let mut s = shape();
|
||||
let fill = Fill::Solid { color: color.clone() };
|
||||
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
|
||||
s.ui_requests.clear();
|
||||
s.execute("format.fontDialog", &json!({})).unwrap();
|
||||
let Some(UiRequest::Dialog { mut params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
|
||||
// OK with the Color field untouched and another field edited, as the dialog sends it.
|
||||
params.as_object_mut().unwrap().remove("color");
|
||||
params["size"] = json!(20.0);
|
||||
params["bold"] = json!(true);
|
||||
s.execute("format.fontDialog", ¶ms).unwrap();
|
||||
let r = props(&s);
|
||||
assert_eq!((r.size, r.bold), (Some(20.0), Some(true)));
|
||||
assert_eq!(r.fill, Some(Fill::Solid { color }));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_dialog_color_mods_round_trip_and_unknown_ops_are_errors() {
|
||||
let two = ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] }
|
||||
.with(ColorTransform::LumMod(75_000))
|
||||
.with(ColorTransform::LumOff(10_000));
|
||||
let mut s = shape();
|
||||
let fill = Fill::Solid { color: two.clone() };
|
||||
format_run(&mut s, &|r| r.fill = Some(fill.clone())).unwrap();
|
||||
s.ui_requests.clear();
|
||||
s.execute("format.fontDialog", &json!({})).unwrap();
|
||||
let Some(UiRequest::Dialog { params, .. }) = s.ui_requests.last().cloned() else { panic!("dialog request") };
|
||||
assert_eq!(params["color"], json!({"preset": "red", "mods": [{"op": "lumMod", "val": 75_000}, {"op": "lumOff", "val": 10_000}]}));
|
||||
s.execute("format.fontDialog", &json!({"color": params["color"]})).unwrap();
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color: two.clone() }));
|
||||
// An unknown op is an error, and the run keeps its color.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
let err = s.execute("format.fontDialog", &json!({"color": {"preset": "red", "mods": [{"op": "sparkle"}]}})).unwrap_err();
|
||||
assert!(err.to_string().contains("color"), "{err}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color: two }));
|
||||
// An empty list gives the color with no transforms.
|
||||
s.execute("format.fontDialog", &json!({"color": {"preset": "red", "mods": []}})).unwrap();
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color: ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![] } }));
|
||||
// A scheme color with a keyed `lumMod` and a list keeps both, the keyed one first.
|
||||
s.execute("format.fontDialog", &json!({"color": {"scheme": "accent2", "lumMod": 75_000, "mods": [{"op": "lumOff", "val": 10_000}]}}))
|
||||
.unwrap();
|
||||
let scheme = ColorRef::scheme(SchemeSlot::Accent2).with(ColorTransform::LumMod(75_000)).with(ColorTransform::LumOff(10_000));
|
||||
assert_eq!(props(&s).fill, Some(Fill::Solid { color: scheme }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_dialog_with_no_fields_asks_the_ui_to_open() {
|
||||
let mut s = shape();
|
||||
|
||||
@@ -443,23 +443,39 @@ fn font_edits(p: &Value) -> Result<FontEdits> {
|
||||
fn color_command_value(c: &deckcraft_model::ColorRef) -> Value {
|
||||
use deckcraft_model::ColorBase;
|
||||
let mut o = serde_json::Map::new();
|
||||
for m in &c.mods {
|
||||
if let Some(v) = m.value() {
|
||||
o.insert(m.xml_name().to_string(), json!(v));
|
||||
}
|
||||
// An ordered list, so the order of the transforms and repeated ones such as `[inv, inv]` are kept.
|
||||
if !c.mods.is_empty() {
|
||||
o.insert("mods".into(), json!(c.mods));
|
||||
}
|
||||
match &c.base {
|
||||
ColorBase::Rgb { rgb } if o.is_empty() => json!(format!("#{}", rgb.hex())),
|
||||
// `#RRGGBB`, or `#RRGGBBAA` for a color that is not opaque.
|
||||
let hex = |c: &deckcraft_color::Rgba| if c.a == 255 { format!("#{}", c.hex()) } else { format!("#{}{:02X}", c.hex(), c.a) };
|
||||
// A preset or system name that `color_value` does not know (kept from an opened file) is given as
|
||||
// the color it is drawn with, so a caller that sends this `color` back gets a valid color. The
|
||||
// Font dialog sends no `color` when its Color field is untouched, so the run keeps the stored name.
|
||||
let base = match &c.base {
|
||||
ColorBase::Preset { name } if !deckcraft_color::is_preset_name(name) => ColorBase::Rgb { rgb: deckcraft_color::Rgba::BLACK },
|
||||
ColorBase::System { name, last } if !deckcraft_color::is_system_name(name) => ColorBase::Rgb { rgb: *last },
|
||||
b => b.clone(),
|
||||
};
|
||||
match &base {
|
||||
ColorBase::Rgb { rgb } if o.is_empty() => json!(hex(rgb)),
|
||||
ColorBase::Rgb { rgb } => {
|
||||
o.insert("rgb".into(), json!(format!("#{}", rgb.hex())));
|
||||
o.insert("rgb".into(), json!(hex(rgb)));
|
||||
Value::Object(o)
|
||||
}
|
||||
ColorBase::Scheme { slot } => {
|
||||
o.insert("scheme".into(), json!(slot.xml_name()));
|
||||
Value::Object(o)
|
||||
}
|
||||
ColorBase::Preset { name } => json!(name),
|
||||
ColorBase::System { last, .. } => json!(format!("#{}", last.hex())),
|
||||
ColorBase::Preset { name } => {
|
||||
o.insert("preset".into(), json!(name));
|
||||
Value::Object(o)
|
||||
}
|
||||
ColorBase::System { name, last } => {
|
||||
o.insert("system".into(), json!(name));
|
||||
o.insert("last".into(), json!(hex(last)));
|
||||
Value::Object(o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Align, Anchor, AutoFit, Bullet, Result, Session, Spacing, TextDir, Value, bad, bool_or, color_param, current_para, f64_or, f64_param,
|
||||
format_body, format_para, json, ok, on_param, resolve, str_param,
|
||||
format_body, format_para, json, ok, on_param, require_any, resolve, str_param,
|
||||
};
|
||||
|
||||
pub(super) fn align_to(s: &mut Session, a: Align) -> Result<Value> {
|
||||
@@ -119,6 +119,26 @@ pub(super) fn line_spacing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn paragraph(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The Paragraph dialog's other fields are format.paragraphDialog's; say so instead of
|
||||
// calling the call empty.
|
||||
if let Some(k) =
|
||||
["special", "specialBy", "indentRight", "spaceBeforeKind", "spaceAfterKind"].into_iter().find(|k| p.get(*k).is_some_and(|v| !v.is_null()))
|
||||
{
|
||||
// The dialog applies a kind or `specialBy` only with the value it qualifies.
|
||||
let with = match k {
|
||||
"spaceBeforeKind" => " together with `spaceBefore`",
|
||||
"spaceAfterKind" => " together with `spaceAfter`",
|
||||
"specialBy" => " together with `special`",
|
||||
_ => "",
|
||||
};
|
||||
return Err(bad(
|
||||
"format.paragraph",
|
||||
format!(
|
||||
"`{k}` is a field of format.paragraphDialog (the whole Paragraph dialog); pass it there{with}. format.paragraph does not read it"
|
||||
),
|
||||
));
|
||||
}
|
||||
require_any(p, "format.paragraph", &["align", "indentLeft", "indentFirst", "spaceBefore", "spaceAfter", "lineSpacing", "lineSpacingPt"])?;
|
||||
let a = str_param(p, "align").map(|a| parse_align("format.paragraph", a)).transpose()?;
|
||||
let ml = f64_param(p, "indentLeft");
|
||||
let ind = f64_param(p, "indentFirst");
|
||||
@@ -414,6 +434,7 @@ pub(super) fn wrap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn margins(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
require_any(p, "format.margins", &["left", "top", "right", "bottom"])?;
|
||||
let (l, t, r, b) = (f64_param(p, "left"), f64_param(p, "top"), f64_param(p, "right"), f64_param(p, "bottom"));
|
||||
format_body(s, &move |bp| {
|
||||
if l.is_some() {
|
||||
|
||||
@@ -10,7 +10,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
CommandSpec, NO_ID_SPACE, bad, bool_or, bool_param, cmd, color_param, color_value, edit_geometry, edit_shapes, f64_param, has_selection,
|
||||
has_slide, id_param, ok, opt_usize_param, str_param, targets, usize_param, with_param, xfrm_of,
|
||||
has_slide, id_param, ok, opt_usize_param, require_any, str_param, targets, usize_param, with_param, xfrm_of,
|
||||
};
|
||||
use crate::{Result, Session};
|
||||
|
||||
@@ -112,7 +112,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Outline",
|
||||
["Shape Format", "Shape Styles"],
|
||||
None,
|
||||
"{color?, none?, width?: pt, dash?: solid|dot|dash|lgDash|dashDot|sysDot|sysDash, cap?: flat|round|square, join?: round|bevel|miter, compound?: single|double|thickThin|thinThick|triple, head?: none|triangle|stealth|diamond|oval|arrow, tail?, headSize?: sm|med|lg, tailSize?, reset?, ids?}; a group also formats its members",
|
||||
"{color?, none?, width?: pt, dash?: solid|dot|dash|lgDash|dashDot|sysDot|sysDash, cap?: flat|round|square, join?: round|bevel|miter, compound?: single|double|thickThin|thinThick|triple, head?: none|triangle|stealth|diamond|oval|arrow, tail?, headSize?: sm|med|lg, tailSize?, reset?, ids?} (at least one key); a group also formats its members",
|
||||
has_selection,
|
||||
line
|
||||
),
|
||||
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Effects",
|
||||
["Shape Format", "Shape Styles"],
|
||||
None,
|
||||
"{shadow?: none|outer|inner|perspective|{color, blur, dist, dir}, glow?: none|{color, radius}, softEdges?: pt, reflection?: none|tight|half|full, bevel?: none|circle|…, threeD?: {camera?: preset, rotX?, rotY?, rotZ?: deg, z?: pt, bevelTop?, bevelBottom?: none|circle|…, bevelTopW?, bevelTopH?, bevelBottomW?, bevelBottomH?, depth?, contour?: pt, material?, lighting?, reset?: true}, shadowProps?: {color?, transparency?: 0..1, size?: 0.01..2 (1 = 100%), blur?: pt, dist?: pt, dir?: deg}, glowProps?: {color?, transparency?, radius?: pt}, reflectionProps?: {transparency?, size?: 0..1, dist?: pt, blur?: pt}, reset?, ids?} (the *Props keys adjust the current effect, adding a default one when there is none)",
|
||||
"{shadow?: none|outer|inner|perspective|{color, blur, dist, dir}, glow?: none|{color, radius}, softEdges?: pt, reflection?: none|tight|half|full, bevel?: none|circle|…, threeD?: {camera?: preset, rotX?, rotY?, rotZ?: deg, z?: pt, bevelTop?, bevelBottom?: none|circle|…, bevelTopW?, bevelTopH?, bevelBottomW?, bevelBottomH?, depth?, contour?: pt, material?, lighting?, reset?: true}, shadowProps?: {color?, transparency?: 0..1, size?: 0.01..2 (1 = 100%), blur?: pt, dist?: pt, dir?: deg}, glowProps?: {color?, transparency?, radius?: pt}, reflectionProps?: {transparency?, size?: 0..1, dist?: pt, blur?: pt}, reset?, ids?} (at least one key) (the *Props keys adjust the current effect, adding a default one when there is none)",
|
||||
has_selection,
|
||||
effects
|
||||
),
|
||||
@@ -169,7 +169,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Corrections",
|
||||
["Picture Format", "Adjust"],
|
||||
None,
|
||||
"{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?}",
|
||||
"{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?} (at least one key)",
|
||||
has_selection,
|
||||
picture_adjust
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
ColorRef, ColorTransform, Dash, Effects, Fill, Geom, Glow, Gradient, GradientShape, GradientStop, Line, LineEnd, PictureFill, PictureMode,
|
||||
Reflection, Result, Rgba, SchemeSlot, Session, Shadow, ShapeStyle, Value, apply_fill, bad, bool_or, color_param, color_value, edit_geometry,
|
||||
edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, str_param, targets,
|
||||
edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, require_any, str_param, targets,
|
||||
};
|
||||
|
||||
pub(super) fn adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -237,6 +237,7 @@ fn line_end(v: &str) -> Option<LineEnd> {
|
||||
}
|
||||
|
||||
pub(super) fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
require_any(p, "shape.line", &["color", "none", "width", "dash", "cap", "join", "compound", "head", "tail", "headSize", "tailSize", "reset"])?;
|
||||
let reset = bool_or(p, "reset", false);
|
||||
let none = bool_or(p, "none", false);
|
||||
let color = color_param(p, "color");
|
||||
@@ -356,6 +357,15 @@ fn shadow_preset(v: &Value) -> Option<Option<Shadow>> {
|
||||
}
|
||||
|
||||
pub(super) fn effects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `glow: null` and `softEdges: null` clear those effects (No Glow, No Soft Edges), so a null
|
||||
// counts as something to set for them.
|
||||
if !["glow", "softEdges"].iter().any(|k| p.get(*k).is_some()) {
|
||||
require_any(
|
||||
p,
|
||||
"shape.effects",
|
||||
&["shadow", "glow", "softEdges", "reflection", "bevel", "threeD", "shadowProps", "glowProps", "reflectionProps", "reset"],
|
||||
)?;
|
||||
}
|
||||
let reset = bool_or(p, "reset", false);
|
||||
let shadow = p.get("shadow").and_then(shadow_preset);
|
||||
let glow: Option<Option<Glow>> = p.get("glow").map(|g| match g {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json};
|
||||
use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json, require_any};
|
||||
|
||||
pub(super) fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = [f64_param(p, "left"), f64_param(p, "top"), f64_param(p, "right"), f64_param(p, "bottom")];
|
||||
@@ -15,6 +15,7 @@ pub(super) fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn picture_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
require_any(p, "picture.adjust", &["brightness", "contrast", "saturation", "grayscale", "transparency", "reset"])?;
|
||||
edit_shapes(s, p, "picture.adjust", |sh| {
|
||||
if let deckcraft_model::ShapeKind::Picture { fill } = &mut sh.kind {
|
||||
let a = &mut fill.adjust;
|
||||
|
||||
+114
-15
@@ -1,7 +1,7 @@
|
||||
//! Table Design and Table Layout tabs.
|
||||
|
||||
use deckcraft_geom::{Affine, Point, Rect};
|
||||
use deckcraft_model::{Shape, ShapeKind, Table};
|
||||
use deckcraft_model::{Cell, Shape, ShapeKind, Table};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
@@ -24,18 +24,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"rowBelow",
|
||||
"table.insertRowBelow"
|
||||
)),
|
||||
cmd!("table.insertColumnLeft", "Insert Left", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols(
|
||||
s,
|
||||
p,
|
||||
"colLeft",
|
||||
"table.insertColumnLeft"
|
||||
)),
|
||||
cmd!("table.insertColumnRight", "Insert Right", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols(
|
||||
s,
|
||||
p,
|
||||
"colRight",
|
||||
"table.insertColumnRight"
|
||||
)),
|
||||
cmd!(
|
||||
"table.insertColumnLeft",
|
||||
"Insert Left",
|
||||
["Table Layout", "Rows & Columns"],
|
||||
None,
|
||||
"{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside",
|
||||
has_selection,
|
||||
|s, p| rows_cols(s, p, "colLeft", "table.insertColumnLeft")
|
||||
),
|
||||
cmd!(
|
||||
"table.insertColumnRight",
|
||||
"Insert Right",
|
||||
["Table Layout", "Rows & Columns"],
|
||||
None,
|
||||
"{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside",
|
||||
has_selection,
|
||||
|s, p| rows_cols(s, p, "colRight", "table.insertColumnRight")
|
||||
),
|
||||
cmd!("table.deleteRow", "Delete Rows", ["Table Layout", "Rows & Columns"], None, "{row?, id?}", has_selection, |s, p| rows_cols(
|
||||
s,
|
||||
p,
|
||||
@@ -322,6 +328,15 @@ fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> R
|
||||
|
||||
fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result<Value> {
|
||||
let (r, c) = at(s, p, name)?;
|
||||
// Absent: the table grows, as in PowerPoint; present, it must be a bool, so a mistyped value is refused
|
||||
// rather than silently taken as the default.
|
||||
let keep_width = match (op, p.get("keepWidth")) {
|
||||
(_, None) | (_, Some(Value::Null)) => false,
|
||||
(_, Some(Value::Bool(b))) => *b,
|
||||
("colLeft", Some(_)) => return Err(bad("table.insertColumnLeft", "`keepWidth` must be true or false")),
|
||||
("colRight", Some(_)) => return Err(bad("table.insertColumnRight", "`keepWidth` must be true or false")),
|
||||
_ => false,
|
||||
};
|
||||
let op = op.to_string();
|
||||
with_table(s, p, name, move |t| {
|
||||
match op.as_str() {
|
||||
@@ -329,8 +344,8 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result
|
||||
let ok = match op.as_str() {
|
||||
"rowAbove" => t.insert_row(r),
|
||||
"rowBelow" => t.insert_row(r.saturating_add(1)),
|
||||
"colLeft" => t.insert_col(c),
|
||||
_ => t.insert_col(c.saturating_add(1)),
|
||||
"colLeft" => insert_col_like(t, c, c, keep_width),
|
||||
_ => insert_col_like(t, c.saturating_add(1), c, keep_width),
|
||||
};
|
||||
if !ok {
|
||||
return Err(bad(name, format!("the table is at its {}-cell limit", deckcraft_model::table::MAX_CELLS)));
|
||||
@@ -351,6 +366,90 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result
|
||||
})
|
||||
}
|
||||
|
||||
/// Insert a column before `at` that looks like column `neighbour` (the one it is inserted beside):
|
||||
/// its width, and in every row the neighbour cell's explicit formatting with no text. With
|
||||
/// `keep_width` the columns then shrink in proportion so the table keeps its total width;
|
||||
/// otherwise (PowerPoint's behaviour) the table grows by the new column and the widths stay.
|
||||
/// Returns false, leaving the table as it was, when the column would take it past the cell limit.
|
||||
fn insert_col_like(t: &mut Table, at: usize, neighbour: usize, keep_width: bool) -> bool {
|
||||
let total = t.width();
|
||||
let neighbour = neighbour.min(t.cols.len().saturating_sub(1));
|
||||
let w = t.cols.get(neighbour).copied();
|
||||
// A neighbour covered by a merge (horizontally or vertically) is formatted as its anchor, which is what shows.
|
||||
let covered = |r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.h_merge || x.v_merge);
|
||||
let templates: Vec<Option<Cell>> = (0..t.rows.len())
|
||||
.map(|r0| {
|
||||
let (mut r, mut n) = (r0, neighbour);
|
||||
while covered(r, n) {
|
||||
let cell = &t.rows[r].cells[n];
|
||||
if cell.h_merge && n > 0 {
|
||||
n -= 1;
|
||||
} else if cell.v_merge && r > 0 {
|
||||
r -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Only the formatting is kept: the anchor's text is not copied once per covered row.
|
||||
t.rows[r].cells.get(n).map(|src| {
|
||||
let mut tpl = Cell::new("");
|
||||
copy_cell_format(&mut tpl, src);
|
||||
tpl
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !t.insert_col(at) {
|
||||
return false;
|
||||
}
|
||||
let at = at.min(t.cols.len().saturating_sub(1));
|
||||
if let (Some(w), Some(slot)) = (w, t.cols.get_mut(at)) {
|
||||
*slot = w;
|
||||
}
|
||||
for (row, tpl) in t.rows.iter_mut().zip(templates) {
|
||||
if let (Some(cell), Some(tpl)) = (row.cells.get_mut(at), tpl) {
|
||||
copy_cell_format(cell, &tpl);
|
||||
}
|
||||
}
|
||||
let grown = t.width();
|
||||
if keep_width && total > 1e-9 && grown > 1e-9 {
|
||||
let k = total / grown;
|
||||
for cw in &mut t.cols {
|
||||
*cw *= k;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `dst` takes `src`'s formatting (fill, borders, margins, anchor, text direction and the text
|
||||
/// properties of its first paragraph, kept on the end mark of an empty paragraph) and keeps its
|
||||
/// own spans and merge cover. Hyperlinks are not copied.
|
||||
fn copy_cell_format(dst: &mut Cell, src: &Cell) {
|
||||
dst.fill.clone_from(&src.fill);
|
||||
dst.borders.clone_from(&src.borders);
|
||||
dst.diag_down.clone_from(&src.diag_down);
|
||||
dst.diag_up.clone_from(&src.diag_up);
|
||||
dst.margins = src.margins;
|
||||
dst.anchor = src.anchor;
|
||||
dst.vertical = src.vertical;
|
||||
dst.anchor_ctr = src.anchor_ctr;
|
||||
dst.horz_overflow = src.horz_overflow;
|
||||
let para = src.text.paragraphs.first().map(|p0| {
|
||||
let mut end_props = p0.runs.first().map_or_else(|| p0.end_props.clone(), |r| r.props.clone());
|
||||
end_props.link = None;
|
||||
end_props.hover = None;
|
||||
let mut def_props = p0.def_props.clone();
|
||||
def_props.link = None;
|
||||
def_props.hover = None;
|
||||
deckcraft_model::text::Paragraph { level: p0.level, props: p0.props.clone(), runs: vec![], def_props, end_props }
|
||||
});
|
||||
let mut list_style = src.text.list_style.clone();
|
||||
for l in list_style.levels.iter_mut().flatten() {
|
||||
l.run.link = None;
|
||||
l.run.hover = None;
|
||||
}
|
||||
dst.text = deckcraft_model::text::TextBody { body: src.text.body.clone(), list_style, paragraphs: vec![para.unwrap_or_default()] };
|
||||
}
|
||||
|
||||
fn merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = s.doc()?.selection.cells;
|
||||
let from = cell_param(p, "from", "table.merge")?.or(sel.map(|c| c.1)).ok_or_else(|| bad("table.merge", "missing `from`"))?;
|
||||
|
||||
@@ -668,6 +668,32 @@ fn sample_placeholders_paste_with_their_look() {
|
||||
assert!(checked >= 3, "the sample has text placeholders ({checked})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_shapes_paste_as_shapes_while_a_text_box_is_being_edited() {
|
||||
let mut s = session();
|
||||
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [10, 10, 50, 50]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let r = s.execute("insert.textBox", &json!({"text": "Hello"})).unwrap();
|
||||
let id = r["id"].as_u64().unwrap();
|
||||
s.execute("text.edit", &json!({"id": id})).unwrap();
|
||||
let before = s.doc().unwrap().current_slide().unwrap().shapes.len();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes.len(), before + 1);
|
||||
assert!(s.doc().unwrap().selection.text.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_shapes_are_not_pasted_while_the_notes_are_being_edited() {
|
||||
let mut s = session();
|
||||
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [10, 10, 50, 50]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("text.edit", &json!({"notes": true})).unwrap();
|
||||
let before = s.doc().unwrap().current_slide().unwrap().shapes.len();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes.len(), before);
|
||||
assert!(s.doc().unwrap().selection.text.as_ref().is_some_and(|t| t.notes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_shapes_get_the_next_automatic_name() {
|
||||
let mut s = session();
|
||||
@@ -7233,6 +7259,81 @@ fn connector_default_sites_follow_the_dominant_direction() {
|
||||
assert_eq!((r["fromSite"].as_u64(), r["toSite"].as_u64()), (Some(2), Some(3)), "both given: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_commands_given_nothing_to_set_are_refused() {
|
||||
let mut s = session();
|
||||
s.execute("insert.textBox", &json!({"text": "Hi", "rect": [50.0, 50.0, 200.0, 100.0]})).unwrap();
|
||||
for cmd in ["shape.line", "shape.effects", "picture.adjust", "format.paragraph", "format.margins"] {
|
||||
let rev = s.doc().unwrap().revision;
|
||||
let e = s.execute(cmd, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("given nothing to set") && e.contains(cmd), "{cmd}: {e}");
|
||||
assert_eq!(s.doc().unwrap().revision, rev, "{cmd} changed the deck");
|
||||
}
|
||||
let e = s.execute("shape.line", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("pass color, none, width, dash"), "{e}");
|
||||
// A key, even one that changes nothing visible, is something to set.
|
||||
s.execute("shape.line", &json!({"width": 2})).unwrap();
|
||||
s.execute("format.margins", &json!({"left": 5})).unwrap();
|
||||
// A null glow or soft edge clears it (No Glow, No Soft Edges): that is something to set.
|
||||
let fx = |s: &Session| s.doc().unwrap().selected_shapes()[0].effects.clone().unwrap_or_default();
|
||||
s.execute("shape.effects", &json!({"glow": 8, "softEdges": 5})).unwrap();
|
||||
assert!(fx(&s).glow.is_some() && fx(&s).soft_edge.is_some());
|
||||
s.execute("shape.effects", &json!({"glow": null})).unwrap();
|
||||
assert!(fx(&s).glow.is_none() && fx(&s).soft_edge.is_some());
|
||||
s.execute("shape.effects", &json!({"softEdges": null})).unwrap();
|
||||
assert!(fx(&s).soft_edge.is_none());
|
||||
// The Paragraph dialog's own fields are format.paragraphDialog's, and the refusal says so.
|
||||
for (k, v) in [("special", json!("hanging")), ("spaceBeforeKind", json!("pct")), ("indentRight", json!(10))] {
|
||||
let e = s.execute("format.paragraph", &json!({ k: v })).unwrap_err().to_string();
|
||||
assert!(e.contains("format.paragraphDialog") && e.contains(k), "{k}: {e}");
|
||||
}
|
||||
let e = s.execute("format.paragraph", &json!({"spaceBeforeKind": "pct"})).unwrap_err().to_string();
|
||||
assert!(e.contains("together with `spaceBefore`"), "{e}");
|
||||
// The palette lists only commands that run without arguments; these need one key.
|
||||
for cmd in ["shape.line", "shape.effects", "picture.adjust", "format.paragraph", "format.margins"] {
|
||||
let spec = crate::command_specs().iter().find(|c| c.id == cmd).unwrap();
|
||||
assert!(crate::cmd::needs_arguments(spec.params), "{cmd}: {}", spec.params);
|
||||
}
|
||||
s.execute("format.paragraphDialog", &json!({"special": "hanging", "specialBy": 18})).unwrap();
|
||||
}
|
||||
|
||||
/// A call whose keys are all null sets nothing and is refused like an empty one, changing
|
||||
/// nothing; one valid key is enough, nulls beside it ignored.
|
||||
#[test]
|
||||
fn style_commands_refuse_only_nulls_and_take_one_key() {
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 2, image::Rgba([200, 30, 30, 255])))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let mut s = session();
|
||||
let pic =
|
||||
s.execute("insert.picture", &json!({"data": cmd::base64_encode(&png), "name": "a.png", "rect": [100, 100, 40, 20]})).unwrap()["id"].clone();
|
||||
let text = s.execute("insert.textBox", &json!({"text": "Hi", "rect": [50, 300, 200, 100]})).unwrap()["id"].clone();
|
||||
let nulls = |keys: &[&str]| serde_json::Value::Object(keys.iter().map(|k| ((*k).to_string(), serde_json::Value::Null)).collect());
|
||||
for (cmd, id, keys, one) in [
|
||||
(
|
||||
"picture.adjust",
|
||||
&pic,
|
||||
&["brightness", "contrast", "saturation", "grayscale", "transparency", "reset"][..],
|
||||
json!({"brightness": 0.3, "contrast": null}),
|
||||
),
|
||||
(
|
||||
"format.paragraph",
|
||||
&text,
|
||||
&["align", "indentLeft", "indentFirst", "spaceBefore", "spaceAfter", "lineSpacing", "lineSpacingPt"][..],
|
||||
json!({"align": "center", "spaceBefore": null}),
|
||||
),
|
||||
] {
|
||||
s.execute("edit.select", &json!({"ids": [id]})).unwrap();
|
||||
let rev = s.doc().unwrap().revision;
|
||||
let e = s.execute(cmd, &nulls(keys)).unwrap_err().to_string();
|
||||
assert!(e.contains("given nothing to set") && e.contains(cmd), "{cmd}: {e}");
|
||||
assert_eq!(s.doc().unwrap().revision, rev, "{cmd}: only nulls changed the deck");
|
||||
s.execute(cmd, &one).unwrap_or_else(|e| panic!("{cmd} {one}: {e}"));
|
||||
assert_ne!(s.doc().unwrap().revision, rev, "{cmd}: one key set something");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_with_an_invalid_colour_is_rejected_and_keeps_the_highlight() {
|
||||
let mut s = session();
|
||||
@@ -7328,6 +7429,160 @@ fn master_body_placeholder_format_keeps_per_level_formatting() {
|
||||
assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]);
|
||||
}
|
||||
|
||||
/// A `keepWidth` that is not a bool is refused, naming it, and the table is left alone, not read
|
||||
/// as the default (the table growing by the new column).
|
||||
#[test]
|
||||
fn table_insert_column_refuses_a_keep_width_that_is_not_a_bool() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]]));
|
||||
for (cmd, bad) in [("table.insertColumnRight", json!("false")), ("table.insertColumnLeft", json!(0))] {
|
||||
let err = s.execute(cmd, &json!({"id": id.0, "col": 1, "keepWidth": bad})).unwrap_err().to_string();
|
||||
assert!(err.contains("keepWidth") && err.contains(cmd), "{err}");
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 3, "{cmd} changed the table: {:?}", t.cols);
|
||||
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_insert_column_with_keep_width_keeps_the_table_width_and_copies_the_neighbour_format() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
|
||||
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 2], [1, 2]]})).unwrap();
|
||||
s.execute("table.cellMargins", &json!({"id": id.0, "left": 20, "right": 20, "top": 5, "bottom": 5, "cells": [[0, 2]]})).unwrap();
|
||||
s.execute("table.cellAlign", &json!({"id": id.0, "anchor": "bottom", "cells": [[0, 2]]})).unwrap();
|
||||
s.execute("edit.select", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("table.selectCells", &json!({"from": [0, 2], "to": [1, 2]})).unwrap();
|
||||
s.execute("format.bold", &json!({"on": true})).unwrap();
|
||||
// Right of the last column: four columns in the same 840 pt, the new one as wide as its
|
||||
// neighbour, the others shrunk to make room.
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 4);
|
||||
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
|
||||
assert!(t.cols.iter().all(|w| (w - 210.0).abs() < 1e-6), "{:?}", t.cols);
|
||||
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w);
|
||||
// The new cells take the neighbour's explicit formatting.
|
||||
let new = t.cell(0, 3).unwrap();
|
||||
assert_eq!(new.fill, Some(deckcraft_model::Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0)))));
|
||||
assert_eq!(new.margins, Some([20.0, 20.0, 5.0, 5.0]));
|
||||
assert_eq!(new.anchor, Some(deckcraft_model::text::Anchor::Bottom));
|
||||
assert_eq!(new.text.text(), "", "the new cell is empty");
|
||||
let bold = new.text.paragraphs.first().map(|p| p.end_props.bold.or(p.def_props.bold));
|
||||
assert_eq!(bold, Some(Some(true)), "the neighbour's bold carries over: {:?}", new.text);
|
||||
assert_eq!(t.cell(1, 3).unwrap().fill, t.cell(1, 2).unwrap().fill);
|
||||
// Left of the first column: the neighbour is the old first column.
|
||||
s.execute("table.insertColumnLeft", &json!({"id": id.0, "col": 0, "keepWidth": true})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 5);
|
||||
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
|
||||
assert_eq!(t.cell(0, 1).unwrap().text.text(), "a");
|
||||
assert_eq!(t.cell(0, 0).unwrap().fill, None);
|
||||
// keepWidth: false grows the table by the neighbour's width, as before.
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 4, "keepWidth": false})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 6);
|
||||
assert!((t.width() - 840.0 - 168.0).abs() < 1e-6, "width {}", t.width());
|
||||
// The insertion is journaled as called, and each one is a single undo step back to the table
|
||||
// as it was: the columns, their widths and the frame.
|
||||
let (jid, jp) = s.journal.last().cloned().unwrap();
|
||||
assert_eq!(jid, "table.insertColumnRight");
|
||||
assert_eq!(jp["keepWidth"], json!(false), "{jp}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 5);
|
||||
assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.n_cols(), 3);
|
||||
assert!(t.cols.iter().all(|w| (w - 280.0).abs() < 1e-6), "{:?}", t.cols);
|
||||
assert_eq!(t.cell(0, 2).unwrap().text.text(), "c");
|
||||
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_insert_column_beside_a_merge_copies_the_anchor_format() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
|
||||
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap();
|
||||
s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [0, 1]})).unwrap();
|
||||
// Right of the merge: the neighbour column holds the covered cell, but the anchor shows.
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert!(t.cell(0, 1).unwrap().h_merge, "the merge stays put");
|
||||
assert_eq!(t.cell(0, 2).unwrap().fill, t.cell(0, 0).unwrap().fill);
|
||||
assert!(t.cell(0, 2).unwrap().fill.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_insert_column_beside_a_two_row_merge_copies_the_anchor_format() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]]));
|
||||
s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap();
|
||||
s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [1, 1]})).unwrap();
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert!(t.cell(1, 1).unwrap().h_merge && t.cell(1, 1).unwrap().v_merge, "the merge stays put");
|
||||
assert!(t.cell(0, 2).unwrap().fill.is_some());
|
||||
assert_eq!(t.cell(1, 2).unwrap().fill, t.cell(0, 0).unwrap().fill);
|
||||
}
|
||||
|
||||
/// A table near the slide's right edge, with no room for another column: by default an inserted
|
||||
/// column widens it past the edge, as PowerPoint's Insert Right does (the frame keeps its left and
|
||||
/// grows), and `keepWidth: true` keeps it on the slide.
|
||||
#[test]
|
||||
fn table_insert_column_near_the_slide_edge_grows_past_it_unless_it_keeps_its_width() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]]));
|
||||
let slide_w = s.doc().unwrap().doc.slide_size.width;
|
||||
let frame = |s: &Session| s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
let before = frame(&s);
|
||||
assert!(before.x + before.w <= slide_w && before.x + before.w + 280.0 > slide_w, "another column won't fit: {before:?}");
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2})).unwrap();
|
||||
assert_eq!(table_of(&s, id).n_cols(), 4);
|
||||
let grown = frame(&s);
|
||||
assert!((grown.x - before.x).abs() < 1e-6 && (grown.w - 1120.0).abs() < 1e-6, "{grown:?}");
|
||||
assert!(grown.x + grown.w > slide_w, "past the edge");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap();
|
||||
let kept = frame(&s);
|
||||
assert_eq!(table_of(&s, id).n_cols(), 4);
|
||||
assert!((kept.x - before.x).abs() < 1e-6 && (kept.w - before.w).abs() < 1e-6, "{kept:?}");
|
||||
assert!(kept.x + kept.w <= slide_w, "still on the slide");
|
||||
}
|
||||
|
||||
/// PowerPoint inserts a column as wide as its neighbour and widens the table by that amount; the
|
||||
/// other widths stay. Deleting a column narrows the table by its width, the others untouched.
|
||||
#[test]
|
||||
fn table_insert_and_delete_column_leave_other_widths_alone() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[160.0, 234.0, 235.0, 235.0], json!([["a", "b", "c", "d"]]));
|
||||
for (cmd, col, at, wide) in [("table.insertColumnRight", 0, 1, 160.0), ("table.insertColumnLeft", 3, 3, 235.0)] {
|
||||
let before = table_of(&s, id).cols.clone();
|
||||
let w0 = table_of(&s, id).width();
|
||||
s.execute(cmd, &json!({"id": id.0, "col": col})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
let mut want = before.clone();
|
||||
want.insert(at, wide);
|
||||
assert_eq!(t.cols, want, "{cmd}");
|
||||
assert!((t.width() - w0 - wide).abs() < 1e-6, "{cmd} width {}", t.width());
|
||||
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
assert!((x.w - t.width()).abs() < 1e-6, "{cmd} frame {}", x.w);
|
||||
}
|
||||
let before = table_of(&s, id).cols.clone();
|
||||
s.execute("table.deleteColumn", &json!({"id": id.0, "col": 1})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
let mut want = before.clone();
|
||||
let gone = want.remove(1);
|
||||
assert_eq!(t.cols, want);
|
||||
assert!((t.width() - (before.iter().sum::<f64>() - gone)).abs() < 1e-6);
|
||||
let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap();
|
||||
assert!((x.w - t.width()).abs() < 1e-6, "frame {}", x.w);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_edits_past_the_cell_cap_are_refused_not_trimmed() {
|
||||
use deckcraft_model::table::{MAX_CELLS, Row};
|
||||
|
||||
+106
-11
@@ -7,9 +7,9 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use symphonia::core::audio::SampleBuffer;
|
||||
use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
|
||||
use symphonia::core::codecs::{CODEC_TYPE_NULL, Decoder, DecoderOptions};
|
||||
use symphonia::core::errors::Error as SymError;
|
||||
use symphonia::core::formats::FormatOptions;
|
||||
use symphonia::core::formats::{FormatOptions, Track};
|
||||
use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions};
|
||||
use symphonia::core::meta::MetadataOptions;
|
||||
use symphonia::core::probe::Hint;
|
||||
@@ -172,6 +172,21 @@ fn contained<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
const MAX_DEMUX_ERRORS: u32 = 64;
|
||||
|
||||
fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result<Pcm> {
|
||||
decode_symphonia_capped(bytes, ext, MAX_PCM_SAMPLES)
|
||||
}
|
||||
|
||||
/// The track playback decodes, with its decoder: the first one a decoder can be made for (a
|
||||
/// video's audio track follows its video track). The duration probe measures the same track.
|
||||
fn playable_track(tracks: &[Track]) -> Option<(u32, Box<dyn Decoder>)> {
|
||||
let codecs = symphonia::default::get_codecs();
|
||||
tracks
|
||||
.iter()
|
||||
.filter(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
||||
.find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d)))
|
||||
}
|
||||
|
||||
/// [`decode_symphonia`] stopping once `max_samples` samples have been decoded.
|
||||
fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Result<Pcm> {
|
||||
let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default());
|
||||
let mut hint = Hint::new();
|
||||
match ext {
|
||||
@@ -189,14 +204,7 @@ fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result<Pcm> {
|
||||
other => sym_err(other),
|
||||
})?;
|
||||
let mut format = probed.format;
|
||||
let codecs = symphonia::default::get_codecs();
|
||||
// The first track we can decode (a video's audio track follows its video track).
|
||||
let (track_id, mut decoder) = format
|
||||
.tracks()
|
||||
.iter()
|
||||
.filter(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
||||
.find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d)))
|
||||
.ok_or(MediaError::Missing("audio track we can decode"))?;
|
||||
let (track_id, mut decoder) = playable_track(format.tracks()).ok_or(MediaError::Missing("audio track we can decode"))?;
|
||||
let mut out: Vec<f32> = Vec::new();
|
||||
let mut rate = 0;
|
||||
let mut channels = 0u16;
|
||||
@@ -245,7 +253,15 @@ fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result<Pcm> {
|
||||
}
|
||||
if let Some(b) = buf.as_mut() {
|
||||
b.copy_interleaved_ref(decoded);
|
||||
out.extend_from_slice(b.samples());
|
||||
// stop at the cap with whole frames, keeping what fits, like the Opus paths
|
||||
let room = max_samples.saturating_sub(out.len());
|
||||
let s = b.samples();
|
||||
if s.len() > room {
|
||||
let fit = room - room % (ch.max(1) as usize);
|
||||
out.extend_from_slice(s.get(..fit).unwrap_or_default());
|
||||
break;
|
||||
}
|
||||
out.extend_from_slice(s);
|
||||
}
|
||||
}
|
||||
Err(SymError::DecodeError(e)) => log::debug!("audio decode: {e}"),
|
||||
@@ -280,6 +296,48 @@ pub(crate) fn probe_symphonia(bytes: &Bytes, ext: &str) -> Option<(String, u32,
|
||||
Some((name, p.sample_rate.unwrap_or(0), p.channels.map(|c| c.count() as u16).unwrap_or(0), p.n_frames))
|
||||
}
|
||||
|
||||
/// Length in milliseconds of the track playback decodes, summed from its packet durations: the
|
||||
/// file is demuxed but not decoded. `None` when the demuxer reports no durations.
|
||||
pub(crate) fn demux_duration_ms(bytes: &Bytes, ext: &str) -> Option<u64> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default());
|
||||
let mut hint = Hint::new();
|
||||
if ext != "unknown" {
|
||||
hint.with_extension(ext);
|
||||
}
|
||||
let opts = FormatOptions { enable_gapless: true, ..Default::default() };
|
||||
let mut format = symphonia::default::get_probe().format(&hint, mss, &opts, &MetadataOptions::default()).ok()?.format;
|
||||
let (id, _) = playable_track(format.tracks())?;
|
||||
let tb = format.tracks().iter().find(|t| t.id == id)?.codec_params.time_base?;
|
||||
let mut ticks = 0u64;
|
||||
let mut errors = 0u32;
|
||||
loop {
|
||||
match format.next_packet() {
|
||||
Ok(p) => {
|
||||
errors = 0;
|
||||
if p.track_id() == id {
|
||||
ticks = ticks.saturating_add(p.dur);
|
||||
}
|
||||
}
|
||||
Err(SymError::DecodeError(_)) => {
|
||||
errors += 1;
|
||||
if errors > MAX_DEMUX_ERRORS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
if ticks == 0 {
|
||||
return None;
|
||||
}
|
||||
let t = tb.calc_time(ticks);
|
||||
Some(t.seconds.saturating_mul(1000).saturating_add((t.frac * 1000.0).round() as u64))
|
||||
}))
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Interleaved PCM resampled (linear) to `rate`.
|
||||
pub fn resample(pcm: &Pcm, rate: u32) -> Pcm {
|
||||
if pcm.rate == rate || pcm.rate == 0 || rate == 0 {
|
||||
@@ -316,6 +374,43 @@ mod tests {
|
||||
assert!((r.at(101, 0) - 0.505).abs() < 1e-3);
|
||||
}
|
||||
|
||||
/// A long decode stops at the sample cap and keeps what it has, like the Opus paths, so audio
|
||||
/// past the cap still plays (up to the cap) instead of failing.
|
||||
#[test]
|
||||
fn decode_stops_at_the_sample_cap() {
|
||||
let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default());
|
||||
let full = decode_symphonia_capped(&b, "aac", usize::MAX).unwrap();
|
||||
let capped = decode_symphonia_capped(&b, "aac", 1001).unwrap();
|
||||
assert!(full.samples.len() > 1001, "the fixture is longer than the cap");
|
||||
assert!(!capped.samples.is_empty() && capped.samples.len() <= 1001, "{}", capped.samples.len());
|
||||
assert_eq!(capped.samples.len() % capped.channels as usize, 0, "whole frames only");
|
||||
assert_eq!(capped.samples[..], full.samples[..capped.samples.len()], "the start is kept as decoded");
|
||||
}
|
||||
|
||||
/// The duration is measured on the track playback decodes: the first one a decoder can be made
|
||||
/// for, not the first one with any codec.
|
||||
#[test]
|
||||
fn duration_and_playback_pick_the_same_track() {
|
||||
use symphonia::core::audio::Channels;
|
||||
use symphonia::core::codecs::{CODEC_TYPE_AAC, CODEC_TYPE_OPUS, CodecParameters};
|
||||
let stereo = Channels::FRONT_LEFT | Channels::FRONT_RIGHT;
|
||||
let mut opus = CodecParameters::new();
|
||||
opus.for_codec(CODEC_TYPE_OPUS).with_sample_rate(48_000).with_channels(stereo);
|
||||
let mut aac = CodecParameters::new();
|
||||
aac.for_codec(CODEC_TYPE_AAC).with_sample_rate(44_100).with_channels(stereo);
|
||||
let tracks = [Track::new(1, opus), Track::new(2, aac)];
|
||||
// the first track has a codec but no decoder in this build (Symphonia has no Opus decoder)
|
||||
assert_ne!(tracks[0].codec_params.codec, CODEC_TYPE_NULL);
|
||||
assert_eq!(playable_track(&tracks).map(|(id, _)| id), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn demux_duration_matches_decoded_length() {
|
||||
let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default());
|
||||
let ms = demux_duration_ms(&b, "aac").unwrap_or(0) as i64;
|
||||
assert!((ms - 500).abs() <= 60, "{ms} ms");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wma_is_reported_unsupported() {
|
||||
let mut b = crate::ASF_HEADER.to_vec();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Media probing: container, duration, audio and video stream parameters — without decoding
|
||||
//! (except for audio files whose container doesn't state a length).
|
||||
//! (audio files whose container doesn't state a length are demuxed, not decoded).
|
||||
|
||||
use crate::video::{codec_name, mkv_codec_name};
|
||||
use crate::{ASF_HEADER, Bytes, Container, MediaError, Result};
|
||||
@@ -50,9 +50,10 @@ fn ms(secs: f64) -> u64 {
|
||||
pub fn probe(bytes: &Bytes) -> Result<MediaInfo> {
|
||||
let mut info = probe_headers(bytes)?;
|
||||
if info.duration_ms == 0 && info.audio.as_ref().is_some_and(|a| a.decodable) && info.video.is_none() {
|
||||
// No length in the header (raw MP3 / ADTS without an index): decode to measure.
|
||||
if let Ok(pcm) = crate::audio::decode(bytes) {
|
||||
info.duration_ms = ms(pcm.duration());
|
||||
// No length in the header (raw MP3 / ADTS without an index): add up the packet
|
||||
// lengths. This only demuxes, so a long file neither allocates its PCM nor stalls the caller.
|
||||
if let Some(d) = crate::audio::demux_duration_ms(bytes, Container::sniff(bytes).name()) {
|
||||
info.duration_ms = d;
|
||||
}
|
||||
}
|
||||
Ok(info)
|
||||
|
||||
@@ -14,11 +14,13 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::SlideApp;
|
||||
|
||||
/// The colour box's text for the engine's colour value: a scheme name or an RGB string.
|
||||
/// The colour box's text for the engine's colour value: a scheme, preset or system name, or an RGB string.
|
||||
fn color_label(value: &Value) -> String {
|
||||
match value {
|
||||
Value::String(text) => text.clone(),
|
||||
Value::Object(object) => object.get("scheme").or_else(|| object.get("rgb")).and_then(Value::as_str).unwrap_or("").to_owned(),
|
||||
Value::Object(object) => {
|
||||
["scheme", "rgb", "preset", "last"].iter().find_map(|key| object.get(*key)).and_then(Value::as_str).unwrap_or("").to_owned()
|
||||
}
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
@@ -158,11 +160,8 @@ pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut Dialo
|
||||
Some(FieldValue::Json(value)) => value,
|
||||
_ => &Value::Null,
|
||||
};
|
||||
if color == color_label(original) {
|
||||
if !original.is_null() {
|
||||
params["color"] = original.clone();
|
||||
}
|
||||
} else if !color.trim().is_empty() {
|
||||
// An untouched Color field sends no `color`, so the text keeps its color reference as stored.
|
||||
if color != color_label(original) && !color.trim().is_empty() {
|
||||
params["color"] = json!(color.trim());
|
||||
}
|
||||
app.run("format.fontDialog", params).map(|_| ())
|
||||
|
||||
@@ -82,3 +82,79 @@ fn ok_keeps_a_scheme_colour_that_the_colour_box_still_shows_unchanged() {
|
||||
assert_ne!(after.italic, before.italic);
|
||||
assert_eq!(after.italic, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_and_system_colors_show_in_the_dialog_and_ok_keeps_them() {
|
||||
for (color, shown) in [
|
||||
(json!({"preset": "red", "lumMod": 50000}), "red"),
|
||||
(json!({"system": "windowText", "last": "#123456", "alpha": 60000}), "#123456"),
|
||||
(json!({"preset": "red", "mods": [{"op": "inv"}, {"op": "inv"}]}), "red"),
|
||||
(json!({"scheme": "accent2", "mods": [{"op": "lumOff", "val": 20000}, {"op": "lumMod", "val": 50000}]}), "accent2"),
|
||||
] {
|
||||
let mut h = harness();
|
||||
h.state_mut().session.execute("format.fontDialog", &json!({ "color": color })).unwrap();
|
||||
let before = fill_of(&h);
|
||||
assert!(before.is_some());
|
||||
h.get_by_label("Font…").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(font_fields(&h)["color"], json!(shown));
|
||||
let ctx = h.ctx.clone();
|
||||
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.confirm", &json!({"dialog": "top"})).unwrap().unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(!crate::dialogs::open_keys(&h.ctx).iter().any(|key| key == "font"), "status {:?}", h.state().status);
|
||||
assert_eq!(fill_of(&h), before, "{shown}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ok_with_color_untouched_keeps_a_color_the_dialog_cannot_send_back() {
|
||||
use deckcraft_color::{ColorTransform, Rgba};
|
||||
use deckcraft_model::{ColorBase, ColorRef, Fill};
|
||||
// Names that `color_value` does not know, as an opened file can hold, and more transforms than a
|
||||
// command's `mods` list may carry.
|
||||
let unknown_preset = ColorRef { base: ColorBase::Preset { name: "notAColor".into() }, mods: vec![ColorTransform::Inv; 257] };
|
||||
let unknown_system = ColorRef { base: ColorBase::System { name: "notAColor".into(), last: Rgba::rgb(0x12, 0x34, 0x56) }, mods: vec![] };
|
||||
for color in [unknown_preset, unknown_system] {
|
||||
let mut h = harness();
|
||||
set_fill(&mut h, Fill::Solid { color });
|
||||
let before = fill_of(&h);
|
||||
h.get_by_label("Font…").click();
|
||||
h.run_steps(2);
|
||||
assert!(crate::dialogs::open_keys(&h.ctx).iter().any(|key| key == "font"));
|
||||
let ctx = h.ctx.clone();
|
||||
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.set", &json!({"dialog": "top", "field": "bold", "value": true})).unwrap().unwrap();
|
||||
h.run_steps(1);
|
||||
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.confirm", &json!({"dialog": "top"})).unwrap().unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(!crate::dialogs::open_keys(&h.ctx).iter().any(|key| key == "font"), "status {:?}", h.state().status);
|
||||
assert_eq!(props(&h).bold, Some(true), "status {:?}", h.state().status);
|
||||
assert_eq!(fill_of(&h), before);
|
||||
}
|
||||
}
|
||||
|
||||
/// The open font dialog's fields, as the control protocol reports them.
|
||||
fn font_fields(h: &Harness<'_, SlideApp>) -> serde_json::Value {
|
||||
crate::control::inspect(h.state(), &h.ctx)["dialogs"].as_array().unwrap().iter().find(|d| d["key"] == "font").unwrap()["fields"].clone()
|
||||
}
|
||||
|
||||
/// Sets the first run's fill directly, so the test can hold a color that a command would reject.
|
||||
fn set_fill(h: &mut Harness<'_, SlideApp>, fill: deckcraft_model::Fill) {
|
||||
let st = h.state_mut().session.active_mut().unwrap();
|
||||
let id = st.selection.shapes[0];
|
||||
let slide = st.selection.slide;
|
||||
let doc = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let slide = std::sync::Arc::make_mut(&mut doc.slides[slide]);
|
||||
let shape = slide.shapes.iter_mut().find(|sh| sh.id == id).unwrap();
|
||||
let run = shape.text.as_mut().and_then(|t| t.paragraphs.first_mut()).and_then(|p| p.runs.first_mut()).unwrap();
|
||||
run.props.fill = Some(fill);
|
||||
}
|
||||
|
||||
fn fill_of(h: &Harness<'_, SlideApp>) -> Option<deckcraft_model::Fill> {
|
||||
let st = h.state().session.active().unwrap();
|
||||
st.selected_shapes()
|
||||
.first()
|
||||
.and_then(|sh| sh.text.as_ref())
|
||||
.and_then(|t| t.paragraphs.first())
|
||||
.and_then(|p| p.runs.first())
|
||||
.and_then(|r| r.props.fill.clone())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# Where things moved in #1433
|
||||
|
||||
[#1433](https://github.com/storytold/deckcraft/pull/1433) (merge `ee875abf`) split the largest
|
||||
source files into modules. Nothing changed in behaviour, but a branch that edits an old file now
|
||||
conflicts with it. This note says which new modules received each old file's code, so you can place
|
||||
your hunks by hand after `git merge origin/main`. Paths are relative to `crates/` unless noted; each
|
||||
old file stays as the parent module and keeps its re-exports, so import paths are unchanged.
|
||||
|
||||
To find the exact new home of one function: `git grep -n 'fn name' origin/main -- crates` (or
|
||||
`git log -S'fn name' --oneline origin/main -- crates`).
|
||||
|
||||
## Plain renames (content unchanged)
|
||||
|
||||
| Old | New |
|
||||
|---|---|
|
||||
| `engine/src/cmd/mod.rs` | `engine/src/cmd.rs` |
|
||||
| `opus/src/celt/mod.rs`, `opus/src/silk/mod.rs` | `opus/src/celt.rs`, `opus/src/silk.rs` |
|
||||
| `pptx/src/read/mod.rs`, `pptx/src/write/mod.rs` | `pptx/src/read.rs`, `pptx/src/write.rs` |
|
||||
| `ui-egui/src/selpane.rs` | `ui-egui/src/panels/selpane.rs` |
|
||||
| `ui-egui/src/backstage_tests.rs` | `ui-egui/src/backstage/tests.rs` |
|
||||
| `ui-egui/src/selpane_tests.rs`, `ui-egui/src/sorter_tests.rs` | `ui-egui/src/panels/selpane/ui_tests.rs`, `ui-egui/src/sorter/ui_tests.rs` |
|
||||
|
||||
`ui-egui/src` files moved into a folder: `guides_tests`, `preview`, `ruler_tests`, `squiggles` →
|
||||
`canvas/`; `columns_dialog_tests`, `credits`, `font_dialog_tests`, `paragraph_dialog_tests`,
|
||||
`photo_album_tests`, `preferences_tests`, `size_position_tests`, `spelling_tests`,
|
||||
`theme_colors_tests`, `theme_fonts_tests`, `updates_ui` → `dialogs/`; `animtimeline`,
|
||||
`background_tests`, `fillui`, `notes`, `pattern_fill_tests`, `smartart_tests`, `thesaurus_tests`,
|
||||
`thumbs` → `panels/`; `align_tests`, `drawtable_tests`, `effects_tests`, `icons_popup_tests`,
|
||||
`inktoshape_tests`, `master_layout_tests`, `qat` → `ribbon/`.
|
||||
|
||||
## Split files (old file → new modules, all under the old file's folder)
|
||||
|
||||
Each old file keeps its module declarations and any code that was not moved; several rows move
|
||||
only the tests.
|
||||
|
||||
| Old file | New modules |
|
||||
|---|---|
|
||||
| `apps/deckcraft/src/control_server.rs` | `control_server/tests.rs` (its tests) |
|
||||
| `engine/src/cmd/design.rs` | `design/{colors, master_view, slide_background, slide_setup, browse_theme_tests, tests}.rs` |
|
||||
| `engine/src/cmd/format.rs` | `format/{font, paragraph, painter, ruler, text_effects}.rs` |
|
||||
| `engine/src/cmd/insert.rs` | `insert/{album, chart, links, picture, text_fields, icon_and_picture_tests}.rs` |
|
||||
| `engine/src/cmd/shape.rs` | `shape/{appearance, freeform, picture, size}.rs` |
|
||||
| `engine/src/cmd/smartart.rs` | `smartart/{diagrams, edit, layout, nodes, paint}.rs` |
|
||||
| `engine/src/cmd/text.rs` | `text/{autocorrect, caret, editing, formatting, ime, layout}.rs` |
|
||||
| `engine/src/tools.rs` | `tools/{click, drag, geometry, hit, pointer}.rs` |
|
||||
| `fonts/src/lib.rs`, `format/src/lib.rs` | `src/tests.rs` (their tests) |
|
||||
| `geom/src/preset.rs` | `preset/{build, builder, catalog, shapes, tests}.rs` |
|
||||
| `media/src/player.rs` | `player/tests.rs` |
|
||||
| `render/src/lib.rs` | `src/{geometry, opts, raster, renderer, slide, stroke, text_draw}.rs` |
|
||||
| `text/src/lib.rs` | `src/{autonum, breaking, layout, run, shape, style, symbol}.rs` |
|
||||
| `ui-egui/src/lib.rs` | `src/{app, state, services, clock, ime_hooks, tests}.rs`; the `SlideApp` impl is in `app.rs` and `app/{clipboard, commands, control, files, frame, ime, input, keys, playback}.rs` |
|
||||
| `ui-egui/src/panes.rs` (deleted) | `panels.rs` and `panels/{animation, background, comments, designer, format_shape, smartart, thesaurus}.rs` (format-shape pane → `format_shape.rs`, slide background → `background.rs`, animation pane → `animation.rs`, comments and revisions → `comments.rs`) |
|
||||
| `ui-egui/src/backstage.rs` | `backstage/{files, info, print}.rs` |
|
||||
| `ui-egui/src/canvas.rs` | `canvas/{context_menu, guides, ime, input, media, overlays, rulers, scroll, tests}.rs` |
|
||||
| `ui-egui/src/capture.rs` | `capture/tests.rs` |
|
||||
| `ui-egui/src/dialogs.rs` | `dialogs/{about, alt_text, body, columns, date_time, equation, export, find, font, grid_options, hyperlink, language, paragraph, photo_album, preferences, size_position, slide_size, tabs, theme_colors, theme_fonts, trim, zoom, tests}.rs`; dialogs not listed (for example most bodies) are in `body.rs` |
|
||||
| `ui-egui/src/icons.rs` | `icons/{draw, geometry}.rs` |
|
||||
| `ui-egui/src/ribbon.rs` | `ribbon/{animations, arrange, chart, design, draw, galleries, home, insert, masters, picture_format, playback, review, shape_format, slide_show, smartart, table, title_bar, transitions, view}.rs`; one file per ribbon tab, plus `galleries.rs` for the shared gallery popups |
|
||||
| `ui-egui/src/show.rs` | `show/{keys, media, presenter, render, ui, zoom, tests}.rs` |
|
||||
|
||||
Also touched: `engine/src/file_access.rs` (16 lines), `docs/file-format-parity.md`, `docs/gaps.md`
|
||||
and `packaging/common.sh` (one line each, path references).
|
||||
|
||||
## Carrying a branch forward
|
||||
|
||||
1. `git merge origin/main` (never rebase) and let git list the conflicting old files.
|
||||
2. For each conflicting hunk whose code moved to a listed module, apply the hunk there by hand.
|
||||
Resolve hunks for code that remains in the old file there, and preserve that code.
|
||||
`ui-egui/src/panes.rs` is deleted: do not restore it, move its hunks into `panels.rs` or the
|
||||
listed `panels/` modules (the crate exposes `panels` and aliases it as `panes`).
|
||||
3. Run `cargo xtask ci`.
|
||||
Reference in New Issue
Block a user