mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-01 02:04:59 -06:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f324f6b82 |
@@ -297,16 +297,6 @@ 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() }
|
||||
}
|
||||
@@ -428,12 +418,8 @@ 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 {
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
// `mods` lists transforms in order, repeats included: `[{"op":"inv"},{"op":"lumMod","val":50000}]`.
|
||||
@@ -576,10 +562,6 @@ 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);
|
||||
@@ -776,16 +758,6 @@ 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}"));
|
||||
@@ -795,7 +767,6 @@ 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}"));
|
||||
|
||||
@@ -335,9 +335,8 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
return paste_plain(s, t);
|
||||
}
|
||||
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()) {
|
||||
let editing = s.doc()?.selection.text.is_some();
|
||||
if editing {
|
||||
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, require_any, str_param,
|
||||
has_text_or_shapes, ids_param, ok, 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, lineSpacingPt?: pt} (at least one key)",
|
||||
"{align?, indentLeft?: pt, indentFirst?: pt (negative = hanging), spaceBefore?: pt, spaceAfter?: pt, lineSpacing?: lines}",
|
||||
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} (at least one key)",
|
||||
"{left?: pt, top?: pt, right?: pt, bottom?: pt}",
|
||||
has_text_or_shapes,
|
||||
margins
|
||||
),
|
||||
|
||||
@@ -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, require_any, resolve, str_param,
|
||||
format_body, format_para, json, ok, on_param, resolve, str_param,
|
||||
};
|
||||
|
||||
pub(super) fn align_to(s: &mut Session, a: Align) -> Result<Value> {
|
||||
@@ -119,26 +119,6 @@ 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");
|
||||
@@ -434,7 +414,6 @@ 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, require_any, str_param, targets, usize_param, with_param, xfrm_of,
|
||||
has_slide, id_param, ok, opt_usize_param, 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?} (at least one key); 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?}; 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?} (at least one key) (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?} (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?} (at least one key)",
|
||||
"{brightness?: -1..1, contrast?: -1..1, saturation?: 0..4, grayscale?: bool, transparency?: 0..1, reset?: bool, ids?}",
|
||||
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, require_any, str_param, targets,
|
||||
edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, str_param, targets,
|
||||
};
|
||||
|
||||
pub(super) fn adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -237,7 +237,6 @@ 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");
|
||||
@@ -357,15 +356,6 @@ 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, require_any};
|
||||
use super::{NO_ID_SPACE, Result, Session, Value, bad, bool_or, bool_param, edit_geometry, edit_shapes, f64_param, json};
|
||||
|
||||
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,7 +15,6 @@ 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;
|
||||
|
||||
@@ -668,32 +668,6 @@ 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();
|
||||
@@ -7259,81 +7233,6 @@ 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();
|
||||
|
||||
+11
-106
@@ -7,9 +7,9 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use symphonia::core::audio::SampleBuffer;
|
||||
use symphonia::core::codecs::{CODEC_TYPE_NULL, Decoder, DecoderOptions};
|
||||
use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
|
||||
use symphonia::core::errors::Error as SymError;
|
||||
use symphonia::core::formats::{FormatOptions, Track};
|
||||
use symphonia::core::formats::FormatOptions;
|
||||
use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions};
|
||||
use symphonia::core::meta::MetadataOptions;
|
||||
use symphonia::core::probe::Hint;
|
||||
@@ -172,21 +172,6 @@ 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 {
|
||||
@@ -204,7 +189,14 @@ fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Resu
|
||||
other => sym_err(other),
|
||||
})?;
|
||||
let mut format = probed.format;
|
||||
let (track_id, mut decoder) = playable_track(format.tracks()).ok_or(MediaError::Missing("audio track we can decode"))?;
|
||||
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 mut out: Vec<f32> = Vec::new();
|
||||
let mut rate = 0;
|
||||
let mut channels = 0u16;
|
||||
@@ -253,15 +245,7 @@ fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Resu
|
||||
}
|
||||
if let Some(b) = buf.as_mut() {
|
||||
b.copy_interleaved_ref(decoded);
|
||||
// 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);
|
||||
out.extend_from_slice(b.samples());
|
||||
}
|
||||
}
|
||||
Err(SymError::DecodeError(e)) => log::debug!("audio decode: {e}"),
|
||||
@@ -296,48 +280,6 @@ 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 {
|
||||
@@ -374,43 +316,6 @@ 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
|
||||
//! (audio files whose container doesn't state a length are demuxed, not decoded).
|
||||
//! (except for audio files whose container doesn't state a length).
|
||||
|
||||
use crate::video::{codec_name, mkv_codec_name};
|
||||
use crate::{ASF_HEADER, Bytes, Container, MediaError, Result};
|
||||
@@ -50,10 +50,9 @@ 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): 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;
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
Ok(info)
|
||||
|
||||
Reference in New Issue
Block a user