mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 02:28:24 +00:00
Merge main into feat/live-paint-bucket-multi-click
This commit is contained in:
@@ -713,6 +713,71 @@ fn corner_commands_refuse_bad_params() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_commands_refuse_an_unknown_item_key() {
|
||||
let mut s = session();
|
||||
let id = square(&mut s);
|
||||
let i = id.0;
|
||||
let set = json!({"items": [{"id": i, "anchor": [0]}], "radius": 5});
|
||||
let e = s.execute("addon.pathtools.cornerSet", &set).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown parameter `items[0].anchor`; did you mean `items[0].anchors`?"), "{e}");
|
||||
let set_late = json!({"items": [{"id": i, "anchors": [0]}, {"id": i, "radius": 3}], "radius": 5});
|
||||
let e = s.execute("addon.pathtools.cornerSet", &set_late).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown parameter `items[1].radius`; the command takes: items[1].id, items[1].anchors"), "{e}");
|
||||
refuses(&mut s, "addon.pathtools.cornerSet", &[set, set_late]);
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"radius": 10})).unwrap();
|
||||
let remove = json!({"items": [{"id": i, "anchor": [0]}]});
|
||||
let e = s.execute("addon.pathtools.cornerRemove", &remove).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown parameter `items[0].anchor`; did you mean `items[0].anchors`?"), "{e}");
|
||||
refuses(&mut s, "addon.pathtools.cornerRemove", &[remove]);
|
||||
assert_eq!(drawn(&s, id, 0), 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_items_take_their_documented_keys() {
|
||||
let mut s = session();
|
||||
let id = square(&mut s);
|
||||
let i = id.0;
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": i, "anchors": [0]}], "radius": 5})).unwrap();
|
||||
assert_eq!((r["corners"].clone(), drawn(&s, id, 0), drawn(&s, id, 1)), (json!(1), 5.0, 0.0));
|
||||
// A member without `anchors` takes the request's.
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": i}], "anchors": [2], "radius": 6})).unwrap();
|
||||
assert_eq!(drawn(&s, id, 2), 6.0);
|
||||
let r = s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": i, "anchors": [0]}]})).unwrap();
|
||||
assert_eq!((r["corners"].clone(), drawn(&s, id, 0), drawn(&s, id, 2)), (json!(1), 0.0, 6.0));
|
||||
// A null `ids` beside `items` counts as not given.
|
||||
s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": i}], "ids": null})).unwrap();
|
||||
assert_eq!(drawn(&s, id, 2), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_commands_refuse_items_with_ids() {
|
||||
let mut s = session();
|
||||
let id = square(&mut s);
|
||||
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
|
||||
let both = json!({"items": [{"id": id.0, "anchors": [0]}], "ids": [other.0], "radius": 5});
|
||||
let e = s.execute("addon.pathtools.cornerSet", &both).unwrap_err().to_string();
|
||||
assert!(e.contains("give `items` or `ids`, not both"), "{e}");
|
||||
refuses(&mut s, "addon.pathtools.cornerSet", &[both]);
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "radius": 5})).unwrap();
|
||||
let both = json!({"items": [{"id": id.0}], "ids": [id.0]});
|
||||
let e = s.execute("addon.pathtools.cornerRemove", &both).unwrap_err().to_string();
|
||||
assert!(e.contains("give `items` or `ids`, not both"), "{e}");
|
||||
refuses(&mut s, "addon.pathtools.cornerRemove", &[both]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_corner_steps_with_older_item_keys_still_play() {
|
||||
let mut s = session();
|
||||
let id = square(&mut s);
|
||||
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
|
||||
let saved = json!({"items": [{"id": id.0, "anchors": [0], "old": 1}], "ids": [other.0], "radius": 5});
|
||||
s.replay("addon.pathtools.cornerSet", &saved).unwrap();
|
||||
assert_eq!((drawn(&s, id, 0), drawn(&s, id, 1)), (5.0, 0.0));
|
||||
s.replay("addon.pathtools.cornerRemove", &json!({"items": [{"id": id.0, "old": 1}]})).unwrap();
|
||||
assert_eq!(drawn(&s, id, 0), 0.0);
|
||||
}
|
||||
|
||||
/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd
|
||||
/// numbers counting from 1), its inner corners at the odd ones.
|
||||
fn star_path(s: &mut Session) -> NodeId {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! save or Export for Screens: those are checked against the options of the formats the command
|
||||
//! can write, in `marks`, `bleed` and the other objects too ([`check_export_options`]); and in the
|
||||
//! objects of an array whose keys `MEMBER_KEYS` lists, such as the `items` of
|
||||
//! `object.setLiveShape`.
|
||||
//! `object.setLiveShape` and `addon.pathtools.cornerSet`.
|
||||
//!
|
||||
//! [`Session::execute`] answers a key the description doesn't name with a parameter error
|
||||
//! ([`check_params`]), for every caller (the app, the control channel, MCP, the CLI) and for the
|
||||
@@ -256,6 +256,22 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
|
||||
/// neither null, is a parameter error ([`check_exclusive_keys`]).
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
|
||||
|
||||
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
|
||||
/// error naming the pair.
|
||||
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
|
||||
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
|
||||
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
|
||||
if given(key).is_some() && given(other).is_some() {
|
||||
return Err(bad(id, format!("give `{key}` or `{other}`, not both")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The parameter error of command `id` for `key`, which isn't one of `keys`: with the nearest of
|
||||
/// them, or all of them.
|
||||
pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError {
|
||||
@@ -273,7 +289,11 @@ pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError
|
||||
|
||||
/// Commands whose params hold an array of objects with keys of their own: the command, the key of
|
||||
/// the array and the keys each of its objects takes.
|
||||
const MEMBER_KEYS: &[(&str, &str, &[&str])] = &[("object.setLiveShape", "items", &["id", "corners"])];
|
||||
const MEMBER_KEYS: &[(&str, &str, &[&str])] = &[
|
||||
("object.setLiveShape", "items", &["id", "corners"]),
|
||||
("addon.pathtools.cornerSet", "items", &["id", "anchors"]),
|
||||
("addon.pathtools.cornerRemove", "items", &["id", "anchors"]),
|
||||
];
|
||||
|
||||
/// Each object in the arrays [`MEMBER_KEYS`] names for command `id` has only the keys it lists, or
|
||||
/// the parameter error naming the first other one with its place (`items[0].corner`), and the
|
||||
@@ -848,9 +868,9 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> {
|
||||
check_option_keys(id, "", given, &keys, why_not, &trees)
|
||||
}
|
||||
|
||||
/// [`check_keys`] for an engine command, the steps of a `command.batch` or an `action.batch` included,
|
||||
/// [`check_effect_params`] for the effect `effect.apply` adds and [`check_export_options`] for an
|
||||
/// export. A command the engine doesn't have passes: running it reports that.
|
||||
/// [`check_keys`], [`check_exclusive_keys`] and [`check_member_keys`] for an engine command, the steps of a `command.batch` or an
|
||||
/// `action.batch` included, [`check_effect_params`] for the effect `effect.apply` adds and
|
||||
/// [`check_export_options`] for an export. A command the engine doesn't have passes: running it reports that.
|
||||
pub fn check_params(id: &str, params: &Value) -> Result<()> {
|
||||
check_params_in(id, params, false)
|
||||
}
|
||||
@@ -869,6 +889,7 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
check_keys(id, spec.params, params)?;
|
||||
check_exclusive_keys(id, params)?;
|
||||
check_member_keys(id, params)?;
|
||||
if in_batch {
|
||||
crate::schemas::check(spec, params, false)?;
|
||||
|
||||
@@ -34,8 +34,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The Offset a wrap object takes, in points.
|
||||
pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive<f64> = -1000.0..=1000.0;
|
||||
|
||||
fn wrap_param(p: &Value, base: TextWrap) -> TextWrap {
|
||||
TextWrap { offset: f64_or(p, "offset", base.offset).clamp(-1000.0, 1000.0), invert: bool_or(p, "invert", base.invert) }
|
||||
let (lo, hi) = (*TEXT_WRAP_OFFSET_RANGE.start(), *TEXT_WRAP_OFFSET_RANGE.end());
|
||||
TextWrap { offset: f64_or(p, "offset", base.offset).clamp(lo, hi), invert: bool_or(p, "invert", base.invert) }
|
||||
}
|
||||
|
||||
fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -867,7 +867,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Data Sets…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 with a byte-order mark, UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
has_doc,
|
||||
dataset_import
|
||||
),
|
||||
|
||||
@@ -32,20 +32,17 @@ fn datasets_csv_bytes(p: &Value, cmd: &str) -> Result<(Vec<u8>, bool)> {
|
||||
}
|
||||
|
||||
/// The text of a datasets CSV given as a file or as `dataBase64`: UTF-16 after a UTF-16
|
||||
/// byte-order mark, else UTF-8, with or without a byte-order mark, else Windows-1252. A file
|
||||
/// that starts with a byte-order mark must be valid in its encoding, and a file without one must
|
||||
/// not hold NUL bytes (UTF-16 without a byte-order mark).
|
||||
/// byte-order mark, else UTF-16 without one when the file holds NUL bytes (see
|
||||
/// [`utf16_without_mark`]), else UTF-8, with or without a byte-order mark, else Windows-1252. A
|
||||
/// file that starts with a byte-order mark must be valid in its encoding, and a file with NUL
|
||||
/// bytes and no byte-order mark must read as UTF-16 by [`utf16_without_mark`]'s rule.
|
||||
fn datasets_csv_text(bytes: &[u8], cmd: &str) -> Result<String> {
|
||||
let utf16 = |rest: &[u8], le: bool| {
|
||||
let (units, odd) = rest.as_chunks::<2>();
|
||||
let units = units.iter().map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) });
|
||||
let text = char::decode_utf16(units).collect::<std::result::Result<String, _>>();
|
||||
text.ok().filter(|_| odd.is_empty()).ok_or_else(|| bad(cmd, "CSV is not UTF-16"))
|
||||
};
|
||||
match bytes {
|
||||
[0xFF, 0xFE, rest @ ..] => return utf16(rest, true),
|
||||
[0xFE, 0xFF, rest @ ..] => return utf16(rest, false),
|
||||
_ if bytes.contains(&0) => return Err(bad(cmd, "CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark")),
|
||||
[0xFF, 0xFE, rest @ ..] => return utf16(rest, true).ok_or_else(|| bad(cmd, "CSV is not UTF-16")),
|
||||
[0xFE, 0xFF, rest @ ..] => return utf16(rest, false).ok_or_else(|| bad(cmd, "CSV is not UTF-16")),
|
||||
_ if bytes.contains(&0) => {
|
||||
return utf16_without_mark(bytes).ok_or_else(|| bad(cmd, "CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match std::str::from_utf8(bytes) {
|
||||
@@ -55,6 +52,34 @@ fn datasets_csv_text(bytes: &[u8], cmd: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `bytes` as UTF-16, little-endian when `le` is set, or `None` when they aren't valid UTF-16.
|
||||
fn utf16(bytes: &[u8], le: bool) -> Option<String> {
|
||||
let (units, odd) = bytes.as_chunks::<2>();
|
||||
let units = units.iter().map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) });
|
||||
char::decode_utf16(units).collect::<std::result::Result<String, _>>().ok().filter(|_| odd.is_empty())
|
||||
}
|
||||
|
||||
/// `bytes`, which hold NUL bytes and no byte-order mark, as UTF-16, or `None`. At least half of
|
||||
/// the two-byte units must hold a NUL byte, as characters from U+0001 to U+00FF do; a file with
|
||||
/// fewer, such as UTF-8 or Windows-1252 text with stray NUL bytes, is refused. The byte order is
|
||||
/// the one that reads a line break (`\n` or `\r`). The other order reads one only from U+0A00 or
|
||||
/// U+0D00, so a file that reads one in both orders is refused. A file that reads none in either
|
||||
/// order has no data rows, and is read little-endian so that the import reports that. The text
|
||||
/// must be valid UTF-16 in that order and hold no NUL character.
|
||||
fn utf16_without_mark(bytes: &[u8]) -> Option<String> {
|
||||
let (units, odd) = bytes.as_chunks::<2>();
|
||||
if !odd.is_empty() || units.iter().filter(|c| c.contains(&0)).count() * 2 < units.len() {
|
||||
return None;
|
||||
}
|
||||
let is_line_break = |u: u16| matches!(u, 0x0A | 0x0D);
|
||||
let lines_le = units.iter().any(|&c| is_line_break(u16::from_le_bytes(c)));
|
||||
let lines_be = units.iter().any(|&c| is_line_break(u16::from_be_bytes(c)));
|
||||
if lines_le && lines_be {
|
||||
return None;
|
||||
}
|
||||
utf16(bytes, !lines_be).filter(|text| !text.contains('\0'))
|
||||
}
|
||||
|
||||
/// A row of a datasets CSV: the file line it starts on, its cells, and for each cell whether it was quoted.
|
||||
type CsvRow = (usize, Vec<String>, Vec<bool>);
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::auto_simplify_level;
|
||||
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
|
||||
pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step};
|
||||
pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE;
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use cmd::{EyedropperOptions, PathfinderOptions};
|
||||
pub use journal::Journal;
|
||||
|
||||
@@ -1748,6 +1748,203 @@ fn shape_builder_arrow_keys_pass_swatches_of_the_same_color() {
|
||||
assert_eq!(s.paint.fill, after, "the swatch after Twin B");
|
||||
}
|
||||
|
||||
/// The colors of the cursor swatch preview's chips, left to right, and which one is ringed.
|
||||
fn swatch_chips(s: &mut Session, v: ViewInfo) -> Vec<([u8; 4], bool)> {
|
||||
let mut chips: Vec<(f64, [u8; 4], bool)> = s
|
||||
.overlays(v)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
vectorcraft_tools::Overlay::Swatch { p, color, selected } => Some((p.x, color, selected)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
chips.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
chips.into_iter().map(|(_, c, sel)| (c, sel)).collect()
|
||||
}
|
||||
|
||||
/// A solid paint's color as the chips draw it.
|
||||
fn chip_color(p: &Paint) -> [u8; 4] {
|
||||
match p {
|
||||
Paint::Solid { color, .. } => color.to_rgba8(1.0),
|
||||
_ => panic!("not a solid color: {p:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Live Paint Bucket: Left and Right step the active paint through the document's color swatches
|
||||
/// (the selected art keeps its paint), the Cursor Swatch Preview (on at first) shows the active
|
||||
/// paint ringed between the swatches before and after it, and with it off the arrows still step.
|
||||
#[test]
|
||||
fn live_paint_bucket_arrow_keys_step_the_active_paint_through_the_swatches() {
|
||||
let mut s = session();
|
||||
let (a, _) = two(&mut s);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
assert_eq!(s.tool_options_of("livePaintBucket")["cursorSwatchPreview"], json!(true));
|
||||
assert!(s.tool_claims_key(ToolKey::Right, v) && s.tool_claims_key(ToolKey::Left, v));
|
||||
assert!(!s.tool_claims_key(ToolKey::Up, v), "Up and Down keep their own use");
|
||||
let list: Vec<(String, Paint)> =
|
||||
vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc).iter().map(|sw| (sw.name.clone(), sw.paint.clone())).collect();
|
||||
assert!(list.len() >= 4);
|
||||
let n = list.len();
|
||||
let stroke = s.paint.stroke.clone();
|
||||
s.execute("paint.setFill", &json!({"swatch": list[0].0, "ids": []})).unwrap();
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, list[2].1);
|
||||
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, list[1].1);
|
||||
assert_eq!(s.paint.stroke, stroke, "the stroke stays");
|
||||
assert_eq!(node(&s, a).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "A keeps its fill");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap();
|
||||
assert_eq!(swatch_chips(&mut s, v), vec![(chip_color(&list[0].1), false), (chip_color(&list[1].1), true), (chip_color(&list[2].1), false)]);
|
||||
let alt = Mods { alt: true, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0).with_mods(alt), v).unwrap();
|
||||
assert!(swatch_chips(&mut s, v).is_empty(), "Alt samples with the eyedropper and shows no chips");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap();
|
||||
// Past the first swatch, Left wraps around to the last.
|
||||
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
|
||||
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, list[n - 1].1);
|
||||
assert_eq!(swatch_chips(&mut s, v).iter().map(|c| c.0).collect::<Vec<_>>(), [&list[n - 2].1, &list[n - 1].1, &list[0].1].map(chip_color));
|
||||
// With the Stroke proxy in front, the arrows step the stroke and the chips show it.
|
||||
s.execute("paint.toggleActive", &json!({"fill": false})).unwrap();
|
||||
let fill = s.paint.fill.clone();
|
||||
s.execute("paint.setStroke", &json!({"swatch": list[1].0, "ids": []})).unwrap();
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!((&s.paint.fill, &s.paint.stroke), (&fill, &list[2].1));
|
||||
assert!(!s.fill_active, "the Stroke proxy stays in front");
|
||||
assert_eq!(swatch_chips(&mut s, v)[1], (chip_color(&list[2].1), true));
|
||||
assert_eq!(node(&s, a).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "A keeps its paint");
|
||||
// Cursor Swatch Preview off hides the chips; the arrows still step.
|
||||
s.set_tool_option_cmd(&json!({"tool": "livePaintBucket", "values": {"cursorSwatchPreview": false}})).unwrap();
|
||||
assert!(swatch_chips(&mut s, v).is_empty());
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.stroke, list[3].1);
|
||||
}
|
||||
|
||||
/// The Live Paint Bucket and the Shape Builder take Left and Right for swatches only without
|
||||
/// modifiers: Shift, Alt and Cmd/Ctrl arrows are left to their shortcuts and change no paint.
|
||||
#[test]
|
||||
fn swatch_arrow_keys_leave_modified_arrows_to_the_shortcuts() {
|
||||
let mut s = session();
|
||||
two(&mut s);
|
||||
let v = ViewInfo::default();
|
||||
let first = vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc)[0].name.clone();
|
||||
s.execute("paint.setFill", &json!({"swatch": first, "ids": []})).unwrap();
|
||||
for tool in ["livePaintBucket", "shapeBuilder"] {
|
||||
s.select_tool(tool, v).unwrap();
|
||||
if tool == "shapeBuilder" {
|
||||
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"pickColorFrom": "swatches"}})).unwrap();
|
||||
}
|
||||
let fill = s.paint.fill.clone();
|
||||
assert!(s.tool_claims_key_with(ToolKey::Right, Mods::default(), v), "{tool}");
|
||||
for m in [Mods { shift: true, ..Default::default() }, Mods { alt: true, ..Default::default() }, Mods { cmd: true, ..Default::default() }] {
|
||||
for key in [ToolKey::Left, ToolKey::Right] {
|
||||
assert!(!s.tool_claims_key_with(key, m, v), "{tool} {key:?} {m:?}");
|
||||
s.tool_key(key, m, v).unwrap();
|
||||
assert_eq!(s.paint.fill, fill, "{tool} {key:?} {m:?}");
|
||||
}
|
||||
}
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_ne!(s.paint.fill, fill, "{tool}: a plain Right steps");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two swatches of the same color: the Bucket's arrows step through both, and the fill and the
|
||||
/// stroke each step on from the swatch picked for them.
|
||||
#[test]
|
||||
fn live_paint_bucket_arrow_keys_pass_swatches_of_the_same_color_for_fill_and_stroke() {
|
||||
let mut s = session();
|
||||
two(&mut s);
|
||||
for name in ["Twin A", "Twin B"] {
|
||||
s.execute("swatch.new", &json!({"name": name, "color": "#123456"})).unwrap();
|
||||
}
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
let names: Vec<String> = vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc).iter().map(|sw| sw.name.clone()).collect();
|
||||
let a = names.iter().position(|n| n == "Twin A").unwrap();
|
||||
assert_eq!(names[a + 1], "Twin B");
|
||||
let after = vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc)[(a + 2) % names.len()].paint.clone();
|
||||
// The fill goes to Twin B.
|
||||
s.execute("paint.setFill", &json!({"swatch": "Twin A", "ids": []})).unwrap();
|
||||
let twin = s.paint.fill.clone();
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, twin, "Twin B");
|
||||
// The stroke starts at Twin A: Right goes to Twin B, then past it.
|
||||
s.execute("paint.setStroke", &json!({"swatch": "Twin A", "ids": []})).unwrap();
|
||||
assert!(!s.fill_active);
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.stroke, twin, "Twin B for the stroke");
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.stroke, after, "the swatch after Twin B");
|
||||
// Back on the fill, which is still Twin B: Right goes past it.
|
||||
s.execute("paint.toggleActive", &json!({"fill": true})).unwrap();
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, after, "the fill steps on from Twin B");
|
||||
}
|
||||
|
||||
/// A color that is no swatch shows alone and Right picks the first swatch, Left the last; a paint
|
||||
/// that is not a solid color shows no chip; one swatch steps to itself; with no color swatch the
|
||||
/// tool leaves the arrows alone; during a fill drag the arrows change nothing.
|
||||
#[test]
|
||||
fn live_paint_bucket_arrow_keys_handle_unmatched_paint_few_swatches_and_drags() {
|
||||
let mut s = session();
|
||||
live(&mut s);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap();
|
||||
let list: Vec<Paint> = vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc).iter().map(|sw| sw.paint.clone()).collect();
|
||||
let odd = Paint::solid(Color::rgb8(0x12, 0x34, 0x57));
|
||||
assert!(!list.contains(&odd));
|
||||
s.paint.fill = odd.clone();
|
||||
assert_eq!(swatch_chips(&mut s, v), vec![(chip_color(&odd), true)]);
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, list[0]);
|
||||
s.paint.fill = odd.clone();
|
||||
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, list[list.len() - 1]);
|
||||
s.paint.fill = Paint::None;
|
||||
assert!(swatch_chips(&mut s, v).is_empty());
|
||||
|
||||
// During a fill drag the arrows are not taken and change nothing.
|
||||
s.paint.fill = list[0].clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
|
||||
assert!(s.tool_busy());
|
||||
assert!(!s.tool_claims_key(ToolKey::Right, v));
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, list[0]);
|
||||
assert!(swatch_chips(&mut s, v).is_empty(), "no chips during a drag");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 25.0, 50.0), v).unwrap();
|
||||
|
||||
// One color swatch: both arrows pick it, and it stands on both sides of itself.
|
||||
let one = list[0].clone();
|
||||
s.edit("t", |d, _| {
|
||||
d.swatch_groups.clear();
|
||||
d.swatches.retain(|sw| sw.paint == one);
|
||||
d.swatches.truncate(1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc).len(), 1);
|
||||
s.paint.fill = odd;
|
||||
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, one);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 301.0, 300.0), v).unwrap();
|
||||
assert_eq!(swatch_chips(&mut s, v), vec![(chip_color(&one), false), (chip_color(&one), true), (chip_color(&one), false)]);
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, one);
|
||||
|
||||
// No color swatch: the arrows are left to the canvas and the paint stays.
|
||||
s.edit("t", |d, _| {
|
||||
d.swatches.clear();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!s.tool_claims_key(ToolKey::Right, v) && !s.tool_claims_key(ToolKey::Left, v));
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!(s.paint.fill, one);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_tool_alt_deletes_line_pieces() {
|
||||
let mut s = session();
|
||||
@@ -3676,9 +3873,10 @@ fn live_paint_tool_options_refuse_invalid_values_and_change_nothing() {
|
||||
let colors = [json!(3), json!("nope"), json!("#12345"), json!("#00ff0080"), json!("00ff0080"), json!("#0f08"), json!(null)];
|
||||
let widths = [json!("wide"), json!(null), json!(true)];
|
||||
let switches = [json!("true"), json!(null), json!(1)];
|
||||
for (tool, keys) in
|
||||
[("livePaintBucket", &["paintFills", "paintStrokes", "highlight"][..]), ("livePaintSelection", &["selectFills", "selectStrokes"][..])]
|
||||
{
|
||||
for (tool, keys) in [
|
||||
("livePaintBucket", &["paintFills", "paintStrokes", "cursorSwatchPreview", "highlight"][..]),
|
||||
("livePaintSelection", &["selectFills", "selectStrokes"][..]),
|
||||
] {
|
||||
let mut bad: Vec<(&str, Value)> = keys.iter().flat_map(|k| switches.iter().map(move |v| (*k, v.clone()))).collect();
|
||||
bad.extend(colors.iter().map(|v| ("color", v.clone())));
|
||||
bad.extend(widths.iter().map(|v| ("width", v.clone())));
|
||||
|
||||
@@ -2137,8 +2137,9 @@ fn datasets_csv_reads_windows_1252_files() {
|
||||
}
|
||||
|
||||
/// A CSV that starts with a UTF-16 byte-order mark is read as UTF-16, and
|
||||
/// one that isn't valid UTF-16 is refused. A file with NUL bytes and no byte-order mark is refused.
|
||||
/// A text value holding NUL imports back from the `csv` that `dataset.export` returns.
|
||||
/// one that isn't valid UTF-16 is refused. A file with NUL bytes and no byte-order mark that isn't
|
||||
/// UTF-16 is refused. A text value holding NUL imports back from the `csv` that `dataset.export`
|
||||
/// returns.
|
||||
#[test]
|
||||
fn datasets_csv_reads_utf16_files() {
|
||||
let mut s = session();
|
||||
@@ -2160,7 +2161,7 @@ fn datasets_csv_reads_utf16_files() {
|
||||
assert!(e.contains("CSV is not UTF-16"), "{e}");
|
||||
let e = import(&mut s, &[b"\xff\xfe".as_slice(), "City\nAB,".as_bytes(), b"\x00\xd8"].concat()).unwrap_err().to_string();
|
||||
assert!(e.contains("CSV is not UTF-16"), "{e}");
|
||||
let e = import(&mut s, &utf16(b"", "City\nx\n", true)).unwrap_err().to_string();
|
||||
let e = import(&mut s, b"City\nx\0\n").unwrap_err().to_string();
|
||||
assert!(e.contains("CSV holds NUL bytes"), "{e}");
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("José"), "a refused file changes nothing");
|
||||
s.execute("dataset.set", &json!({"name": "Data Set 1", "values": {"City": "a\u{0}b"}})).unwrap();
|
||||
@@ -2170,6 +2171,63 @@ fn datasets_csv_reads_utf16_files() {
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("a\u{0}b"));
|
||||
}
|
||||
|
||||
/// A CSV in UTF-16 without a byte-order mark, with a NUL byte in at least half of its units, is
|
||||
/// read in the byte order that reads a line break: in either order, with characters whose bytes
|
||||
/// read as a line break, a quote or NUL, and when its bytes are also valid UTF-8. Files with fewer
|
||||
/// NUL bytes, that read a line break in both orders, that aren't valid UTF-16 in it, that hold a
|
||||
/// NUL character or that have an odd length are refused.
|
||||
#[test]
|
||||
fn datasets_csv_reads_utf16_files_without_a_byte_order_mark() {
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "City", "kind": "text"})).unwrap();
|
||||
let import = |s: &mut Session, bytes: &[u8]| s.execute("dataset.import", &json!({"dataBase64": vectorcraft_format::base64_encode(bytes)}));
|
||||
let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("City")).cloned();
|
||||
let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into()));
|
||||
let utf16 = |text: &str, le: bool| -> Vec<u8> { text.encode_utf16().flat_map(|u| if le { u.to_le_bytes() } else { u.to_be_bytes() }).collect() };
|
||||
import(&mut s, &utf16("City\r\nParis\r\n", true)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("Paris"));
|
||||
import(&mut s, &utf16("City\nZoë 😀\n", false)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("Zoë 😀"));
|
||||
// U+4E00's low byte is NUL, U+010A holds a `\n` byte and U+2200 a `"` byte; all three files
|
||||
// are valid UTF-8 too.
|
||||
import(&mut s, &utf16("City\n一\n", true)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("一"));
|
||||
import(&mut s, &utf16("City\nĊ\n", true)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("Ċ"));
|
||||
import(&mut s, &utf16("City\n∀∀∀\n", true)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("∀∀∀"));
|
||||
// A file with no line break has no data rows in either byte order.
|
||||
for bytes in [utf16("City", true), utf16("City", false), b"\0aa\0".to_vec()] {
|
||||
let e = import(&mut s, &bytes).unwrap_err().to_string();
|
||||
assert!(e.contains("CSV has a header but no data rows"), "{e}");
|
||||
}
|
||||
import(&mut s, &utf16("City\tName\n一二三丁目\tKai\n", true)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("一二三丁目"));
|
||||
// Most units hold their NUL byte where a big-endian file would (U+4E00); the line breaks
|
||||
// give the byte order.
|
||||
import(&mut s, &utf16("City\n一一一一一一一一一一二\n", true)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("一一一一一一一一一一二"));
|
||||
// Windows-1252 and UTF-8 text with stray NUL bytes (the first with `\n\0` units), UTF-16 with
|
||||
// fewer than half of its units holding a NUL byte, and, last, two files that read a line break
|
||||
// in both byte orders (U+0D00 reads as `\r` and U+0A00 as `\n` big-endian).
|
||||
let refused: [&[u8]; 9] = [
|
||||
b"Caf\xe9\n\0Lyon\n\0",
|
||||
b"Cit\0\n",
|
||||
b"City\nx\0\n",
|
||||
&utf16("City\n丁丁丁丁丁丁丁丁丁丁\n", true),
|
||||
&utf16("City\na\u{0}\n", true),
|
||||
&[utf16("City\n", true), vec![0x00, 0xD8], utf16("\n", true)].concat(),
|
||||
&[utf16("City\n", false), vec![0xDC, 0x00], utf16("\n", false)].concat(),
|
||||
&utf16("City\n\u{0D00}\u{0D00}\u{0D00}\n", true),
|
||||
&utf16("City\u{0A00}\nParis\n", true),
|
||||
];
|
||||
for bytes in refused {
|
||||
let e = import(&mut s, bytes).unwrap_err().to_string();
|
||||
assert!(e.contains("CSV holds NUL bytes"), "{bytes:?}: {e}");
|
||||
}
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("一一一一一一一一一一二"), "a refused file changes nothing");
|
||||
}
|
||||
|
||||
/// A data set of [`library`]: its name, and each variable's name with its paragraphs.
|
||||
type LibrarySet<'a> = (&'a str, &'a [(&'a str, &'a [&'a str])]);
|
||||
|
||||
|
||||
@@ -1164,6 +1164,12 @@ impl Session {
|
||||
self.plane_key(key).is_some() || self.with_tool_cx(view, |t, cx| t.claims_key(cx, key))
|
||||
}
|
||||
|
||||
/// Does the active tool take `key`, pressed with `mods` held, ahead of the shortcuts bound to it
|
||||
/// (see `Tool::claims_key_with`)?
|
||||
pub fn tool_claims_key_with(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> bool {
|
||||
self.plane_key(key).is_some() || self.with_tool_cx(view, |t, cx| t.claims_key_with(cx, key, mods))
|
||||
}
|
||||
|
||||
/// Has the active tool started something that Escape ends while no button is pressed (see
|
||||
/// `Tool::ends_on_escape`)?
|
||||
pub fn tool_ends_on_escape(&mut self, view: ViewInfo) -> bool {
|
||||
|
||||
Reference in New Issue
Block a user