mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-02 02:36:14 -06:00
Merge pull request #1476
This commit is contained in:
@@ -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() }
|
||||
}
|
||||
@@ -562,6 +572,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);
|
||||
@@ -767,6 +781,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}"));
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -7233,6 +7233,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();
|
||||
|
||||
Reference in New Issue
Block a user