mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into feat/font-sheet
This commit is contained in:
commit
87cdcb8ddd
27 files changed
+2246
-116
No files matched your search
@@ -9,6 +9,7 @@
|
||||
//! submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
|
||||
pub mod font_sheet;
|
||||
pub mod numbers;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -67,6 +68,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
release_path
|
||||
),
|
||||
cmd!(
|
||||
"addon.type.numbers",
|
||||
"Make Numbers Sequence…",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}",
|
||||
has_selection,
|
||||
numbers::make_numbers
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(font_sheet::specs())
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
//! Make Numbers Sequence (`addon.type.numbers`): numbers the selected type objects from a start
|
||||
//! value by a step, replacing each object's whole text, the numbers in it, or a `{%n}` placeholder.
|
||||
//! The objects are taken in stacking order, by rows or by columns. Leading and trailing zeros pad
|
||||
//! the numbers to one width. Based on Sergey Osokin's MIT-licensed MakeNumbersSequence script
|
||||
//! (<https://github.com/creold/illustrator-scripts/blob/master/md/Text.md#makenumberssequence>).
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::effects;
|
||||
use vectorcraft_text::edit;
|
||||
use vectorcraft_text::retype::is_combining_mark;
|
||||
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::textedit::text_mut;
|
||||
use super::super::super::threads;
|
||||
use super::super::super::typecmd::refresh_bounds;
|
||||
use super::super::super::typemenu::text_ids;
|
||||
use super::super::super::{bad, number_or, switch_or, targets};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The command id.
|
||||
pub const COMMAND: &str = "addon.type.numbers";
|
||||
/// The orders the objects are numbered in.
|
||||
pub const ORDERS: [&str; 3] = ["stacking", "rows", "columns"];
|
||||
/// What each object's number replaces.
|
||||
pub const REPLACES: [&str; 3] = ["all", "numbers", "placeholder"];
|
||||
/// The placeholder `replace: "placeholder"` replaces, in any case.
|
||||
pub const PLACEHOLDER: &str = "{%n}";
|
||||
/// The largest start, end or step.
|
||||
const MAX_VALUE: f64 = 1e12;
|
||||
/// The most decimal places a number keeps.
|
||||
const MAX_DECIMALS: usize = 6;
|
||||
/// The largest fixed number of digits.
|
||||
pub const MAX_DIGITS: u64 = 30;
|
||||
/// The most type objects one run numbers.
|
||||
const MAX_TEXTS: usize = 100_000;
|
||||
/// The most numbers or placeholders one run replaces.
|
||||
pub(crate) const MAX_MATCHES: usize = 10_000;
|
||||
|
||||
/// What one run does, read from its params.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct Options {
|
||||
pub start: f64,
|
||||
/// None: the numbers run to the last type object.
|
||||
pub end: Option<f64>,
|
||||
pub step: f64,
|
||||
pub order: &'static str,
|
||||
pub replace: &'static str,
|
||||
/// Some(seed): the numbers go to the objects in random order.
|
||||
pub shuffle: Option<u64>,
|
||||
pub leading_zeros: bool,
|
||||
/// The least number of whole digits with leading zeros; None: as many as the widest number.
|
||||
pub digits: Option<usize>,
|
||||
pub trailing_zeros: bool,
|
||||
pub remove_unused: bool,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
pub(crate) fn parse(p: &Value) -> Result<Self> {
|
||||
const C: &str = COMMAND;
|
||||
let value = |key: &str, default: f64| -> Result<f64> {
|
||||
let v = number_or(p, key, default, C)?;
|
||||
if !v.is_finite() || v.abs() > MAX_VALUE {
|
||||
return Err(bad(C, format!("`{key}` must be from -{MAX_VALUE} to {MAX_VALUE}")));
|
||||
}
|
||||
Ok(v)
|
||||
};
|
||||
let start = value("start", 1.0)?;
|
||||
let step = value("step", 1.0)?;
|
||||
let end = match p.get("end") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(value("end", 0.0)?),
|
||||
};
|
||||
let order = pick(choice(p, C, "order", &ORDERS)?.unwrap_or("stacking"), &ORDERS);
|
||||
let replace = pick(choice(p, C, "replace", &REPLACES)?.unwrap_or("all"), &REPLACES);
|
||||
let seed = whole_or(p, "seed", 0, C)?;
|
||||
let shuffle = if switch_or(p, "shuffle", false, C)? { Some(seed) } else { None };
|
||||
let digits = match p.get("digits") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => {
|
||||
let d = whole_or(p, "digits", 1, C)?;
|
||||
if !(1..=MAX_DIGITS).contains(&d) {
|
||||
return Err(bad(C, format!("`digits` must be from 1 to {MAX_DIGITS}")));
|
||||
}
|
||||
Some(usize::try_from(d).unwrap_or(1))
|
||||
}
|
||||
};
|
||||
let remove_unused = switch_or(p, "removeUnused", false, C)?;
|
||||
if remove_unused && end.is_none() {
|
||||
return Err(bad(C, "`removeUnused` needs an `end`"));
|
||||
}
|
||||
Ok(Self {
|
||||
start,
|
||||
end,
|
||||
step,
|
||||
order,
|
||||
replace,
|
||||
shuffle,
|
||||
leading_zeros: switch_or(p, "leadingZeros", true, C)?,
|
||||
digits,
|
||||
trailing_zeros: switch_or(p, "trailingZeros", false, C)?,
|
||||
remove_unused,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as the static entry of `list` it equals.
|
||||
fn pick(v: &str, list: &[&'static str]) -> &'static str {
|
||||
list.iter().copied().find(|x| *x == v).unwrap_or(list[0])
|
||||
}
|
||||
|
||||
/// The decimal places `v` is written with, at most [`MAX_DECIMALS`].
|
||||
fn decimals(v: f64) -> usize {
|
||||
let s = format!("{v}");
|
||||
s.split_once('.').map_or(0, |(_, f)| f.len()).min(MAX_DECIMALS)
|
||||
}
|
||||
|
||||
/// Round the shortest decimal representation of `v` to fixed point at `places`.
|
||||
fn scaled(v: f64, places: usize) -> i128 {
|
||||
let s = format!("{v}");
|
||||
let magnitude = s.trim_start_matches('-');
|
||||
let (whole, fraction) = magnitude.split_once('.').unwrap_or((magnitude, ""));
|
||||
let digits = whole.bytes().chain(fraction.bytes().chain(std::iter::repeat(b'0')).take(places));
|
||||
let mut value = digits.fold(0_i128, |n, digit| n * 10 + i128::from(digit - b'0'));
|
||||
if fraction.as_bytes().get(places).is_some_and(|digit| *digit >= b'5') {
|
||||
value += 1;
|
||||
}
|
||||
if v < 0.0 { -value } else { value }
|
||||
}
|
||||
|
||||
/// `v` scaled by `10^places`, without trailing zeros and with no minus sign on zero.
|
||||
fn write(v: i128, places: usize) -> String {
|
||||
let scale = 10_u128.pow(places as u32);
|
||||
let magnitude = v.unsigned_abs();
|
||||
let sign = if v < 0 { "-" } else { "" };
|
||||
let whole = magnitude / scale;
|
||||
if places == 0 {
|
||||
return format!("{sign}{whole}");
|
||||
}
|
||||
let fraction = magnitude % scale;
|
||||
let s = format!("{sign}{whole}.{fraction:0places$}");
|
||||
s.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
}
|
||||
|
||||
/// The numbers for `count` objects as text: from `start` by `step` (its sign set to run toward
|
||||
/// `end`), stopping past `end`, then padded with zeros as `o` says.
|
||||
pub(crate) fn sequence(o: &Options, count: usize) -> Vec<String> {
|
||||
let places = [Some(o.start), Some(o.step), o.end].into_iter().flatten().map(decimals).max().unwrap_or(0);
|
||||
let step = match o.end {
|
||||
Some(end) if (o.start <= end) == (o.step < 0.0) => -o.step,
|
||||
_ => o.step,
|
||||
};
|
||||
// Count steps at the supported decimal precision so an inclusive end survives rounding.
|
||||
let scaled = |v: f64| scaled(v, places);
|
||||
let start_i = scaled(o.start);
|
||||
let step_i = scaled(step);
|
||||
let fit = match o.end {
|
||||
Some(end) if step_i != 0 => usize::try_from((scaled(end) - start_i) / step_i + 1).unwrap_or(usize::MAX),
|
||||
_ => count,
|
||||
};
|
||||
let values: Vec<i128> = (0..count.min(fit)).map(|i| start_i + i as i128 * step_i).collect();
|
||||
let mut out: Vec<String> = values.iter().map(|v| write(*v, places)).collect();
|
||||
if o.trailing_zeros {
|
||||
let most = out.iter().map(|s| s.split_once('.').map_or(0, |(_, f)| f.len())).max().unwrap_or(0);
|
||||
if most > 0 {
|
||||
for s in &mut out {
|
||||
let have = s.split_once('.').map_or(0, |(_, f)| f.len());
|
||||
if have == 0 {
|
||||
s.push('.');
|
||||
}
|
||||
s.extend(std::iter::repeat_n('0', most - have));
|
||||
}
|
||||
}
|
||||
}
|
||||
if o.leading_zeros {
|
||||
let last = o.end.map(scaled).unwrap_or_else(|| values.last().copied().unwrap_or(start_i));
|
||||
// Whole digits as written, after rounding to `places`.
|
||||
let whole = |v: i128| {
|
||||
let s = write(v, places);
|
||||
let s = s.trim_start_matches('-');
|
||||
s.split_once('.').map_or(s.len(), |(w, _)| w.len())
|
||||
};
|
||||
let width = whole(start_i).max(whole(last)).max(o.digits.unwrap_or(1));
|
||||
for s in &mut out {
|
||||
if s.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
let have = s.split_once('.').map_or(s.len(), |(w, _)| w.len());
|
||||
if have < width {
|
||||
s.insert_str(0, &"0".repeat(width - have));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The byte ranges of `text` a number replaces: each run of ASCII digits, with any `.` or `,`
|
||||
/// followed by more digits inside it, and a `-` before it that does not follow a letter or digit.
|
||||
pub(crate) fn number_spans(text: &str) -> Vec<(usize, usize)> {
|
||||
let b = text.as_bytes();
|
||||
let mut out = vec![];
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if !b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let signed = i > 0 && b[i - 1] == b'-' && !text[..i - 1].chars().rev().find(|c| !is_combining_mark(*c)).is_some_and(char::is_alphanumeric);
|
||||
let start = if signed { i - 1 } else { i };
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
}
|
||||
while i + 1 < b.len() && matches!(b[i], b'.' | b',') && b[i + 1].is_ascii_digit() {
|
||||
i += 1;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out.push((start, i));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The byte ranges of `text` that hold the placeholder, in any case.
|
||||
pub(crate) fn placeholder_spans(text: &str) -> Vec<(usize, usize)> {
|
||||
let lower = text.to_ascii_lowercase();
|
||||
lower.match_indices(PLACEHOLDER).map(|(i, m)| (i, i + m.len())).collect()
|
||||
}
|
||||
|
||||
/// `ids` in rows (top to bottom, each row left to right) or columns (left to right, each top to
|
||||
/// bottom), by the centres of `bounds`. Objects whose centres are within half the median height
|
||||
/// (width for columns) of a row's first object share its row.
|
||||
fn by_position(ids: Vec<(NodeId, Rect)>, rows: bool) -> Vec<NodeId> {
|
||||
let along = |r: &Rect| if rows { r.center().y } else { r.center().x };
|
||||
let across = |r: &Rect| if rows { r.center().x } else { r.center().y };
|
||||
let mut sizes: Vec<f64> = ids.iter().map(|(_, r)| if rows { r.height() } else { r.width() }).collect();
|
||||
sizes.sort_by(f64::total_cmp);
|
||||
let n = sizes.len();
|
||||
let median = match n {
|
||||
0 | 1 => 0.0,
|
||||
_ if n.is_multiple_of(2) => (sizes[n / 2 - 1] + sizes[n / 2]) / 2.0,
|
||||
_ => sizes[n / 2],
|
||||
};
|
||||
let tolerance = median / 2.0;
|
||||
let mut ids = ids;
|
||||
ids.sort_by(|a, b| along(&a.1).total_cmp(&along(&b.1)));
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
let mut row: Vec<(NodeId, Rect)> = vec![];
|
||||
for item in ids {
|
||||
if row.first().is_some_and(|first| along(&item.1) - along(&first.1) > tolerance) {
|
||||
row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1)));
|
||||
out.extend(row.drain(..).map(|(id, _)| id));
|
||||
}
|
||||
row.push(item);
|
||||
}
|
||||
row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1)));
|
||||
out.extend(row.into_iter().map(|(id, _)| id));
|
||||
out
|
||||
}
|
||||
|
||||
/// One replacement in a text: its start and end bytes and the number that goes there.
|
||||
type Edit = (usize, usize, String);
|
||||
|
||||
/// Each span of `spans` in `text` replaced by `number`, as edits from the last to the first. A
|
||||
/// span that already reads `number` is left out, so its formatting stays.
|
||||
pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec<Edit> {
|
||||
spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let o = Options::parse(p)?;
|
||||
let named = targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(id) = named.iter().find(|id| d.node(**id).is_none()) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
// Type objects, groups' included, in stacking order from the back; locked or hidden ones stay.
|
||||
let mut texts = text_ids(d, &named);
|
||||
{
|
||||
let editable = d.editable();
|
||||
texts.retain(|id| editable(*id));
|
||||
}
|
||||
let paths = d.index_paths(texts.iter().copied());
|
||||
texts.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
|
||||
if texts.len() > MAX_TEXTS {
|
||||
return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}")));
|
||||
}
|
||||
let threads = threads::ThreadIndex::of(d);
|
||||
if texts.iter().any(|id| threads.threaded(*id)) {
|
||||
return Err(bad(C, "threaded type can't be numbered: its frames share one story"));
|
||||
}
|
||||
let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => t.plain_text(),
|
||||
_ => String::new(),
|
||||
};
|
||||
// Only objects that hold a number or the placeholder count, for the order too.
|
||||
let mut texts: Vec<(NodeId, String)> = texts
|
||||
.into_iter()
|
||||
.map(|id| (id, plain(id)))
|
||||
.filter(|(_, t)| match o.replace {
|
||||
"numbers" => t.bytes().any(|b| b.is_ascii_digit()),
|
||||
"placeholder" => !placeholder_spans(t).is_empty(),
|
||||
_ => true,
|
||||
})
|
||||
.collect();
|
||||
if o.order != "stacking" && o.shuffle.is_none() {
|
||||
let placed: Vec<(NodeId, Rect)> = texts
|
||||
.iter()
|
||||
.map(|(id, _)| (*id, effects::preview::bounds_of(d, &[*id], false).unwrap_or(Rect::new(f64::MAX, f64::MAX, f64::MAX, f64::MAX))))
|
||||
.collect();
|
||||
let mut by_id: std::collections::HashMap<NodeId, String> = texts.into_iter().collect();
|
||||
texts = by_position(placed, o.order == "rows").into_iter().filter_map(|id| by_id.remove(&id).map(|t| (id, t))).collect();
|
||||
}
|
||||
// The objects are shuffled, not the numbers, so an end limit can number any of them.
|
||||
if let Some(seed) = o.shuffle {
|
||||
let mut rng = Rng::new(seed);
|
||||
for i in (1..texts.len()).rev() {
|
||||
let j = usize::try_from(rng.next_u64() % (i as u64 + 1)).unwrap_or(0);
|
||||
texts.swap(i, j);
|
||||
}
|
||||
}
|
||||
let numbers = sequence(&o, texts.len());
|
||||
let mut plans: Vec<(NodeId, Vec<Edit>)> = vec![];
|
||||
let mut matches = 0;
|
||||
for ((id, text), number) in texts.iter().zip(&numbers) {
|
||||
let spans = match o.replace {
|
||||
"numbers" => number_spans(text),
|
||||
"placeholder" => placeholder_spans(text),
|
||||
_ => vec![],
|
||||
};
|
||||
// Checked before any replacement text is made.
|
||||
matches += spans.iter().filter(|(a, b)| text.get(*a..*b) != Some(number.as_str())).count();
|
||||
if matches > MAX_MATCHES {
|
||||
return Err(bad(C, format!("too many numbers or placeholders to replace: at most {MAX_MATCHES}")));
|
||||
}
|
||||
let changes = match o.replace {
|
||||
"numbers" | "placeholder" => edits(text, spans, number),
|
||||
_ => vec![(0, text.len(), number.clone())],
|
||||
};
|
||||
// The text it would have, to leave out objects that already read so.
|
||||
let mut after = text.clone();
|
||||
for (a, b, n) in &changes {
|
||||
after.replace_range(*a..*b, n);
|
||||
}
|
||||
if after != *text {
|
||||
plans.push((*id, changes));
|
||||
}
|
||||
}
|
||||
let numbered: Vec<u64> = texts.iter().take(numbers.len()).map(|(id, _)| id.0).collect();
|
||||
// A clipping group's or layer's mask is its first child; removing it would make the next child the mask.
|
||||
let mask = |id: NodeId| {
|
||||
d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| g.clips() && g.children().and_then(|c| c.first()).is_some_and(|c| c.id == id))
|
||||
};
|
||||
let removed: Vec<NodeId> =
|
||||
if o.remove_unused { texts.iter().skip(numbers.len()).map(|(id, _)| *id).filter(|id| !mask(*id)).collect() } else { vec![] };
|
||||
if plans.is_empty() && removed.is_empty() {
|
||||
return Ok(json!({ "count": 0, "ids": numbered, "removed": [] }));
|
||||
}
|
||||
let count = plans.len();
|
||||
s.edit("Make Numbers Sequence", |d, sel| {
|
||||
for (id, changes) in &plans {
|
||||
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
|
||||
for (a, b, n) in changes {
|
||||
t.splice_paras(*a, *b, n);
|
||||
edit::replace_range(&mut t.runs, *a, *b, n);
|
||||
t.ruby_after_replace(*a, *b, n.len());
|
||||
}
|
||||
refresh_bounds(t);
|
||||
}
|
||||
d.remove_many(&removed)?;
|
||||
if !removed.is_empty() {
|
||||
sel.remove_all(removed.iter().copied());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": count, "ids": numbered, "removed": removed.iter().map(|id| id.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
//! Make Numbers Sequence: the numbers a sequence gives, what each replace mode changes, the
|
||||
//! orders, removed objects, one undo step, and bad params refused without a change.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence};
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn text_at(s: &mut Session, x: f64, y: f64, words: &str) -> NodeId {
|
||||
NodeId(s.execute("text.create", &json!({"x": x, "y": y, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn seq(p: Value, count: usize) -> Vec<String> {
|
||||
sequence(&Options::parse(&p).unwrap(), count)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sequence_steps_toward_its_end_and_pads_with_zeros() {
|
||||
assert_eq!(seq(json!({"start": 1, "step": 5, "end": 20}), 10), ["01", "06", "11", "16"], "stops past the end");
|
||||
assert_eq!(seq(json!({"start": 10, "step": 3, "end": 1, "leadingZeros": false}), 10), ["10", "7", "4", "1"], "the step turns to run down");
|
||||
assert_eq!(seq(json!({"start": 8, "digits": 3}), 3), ["008", "009", "010"]);
|
||||
assert_eq!(seq(json!({"start": -1, "step": 1}), 3), ["-1", "0", "1"], "negative numbers get no zeros");
|
||||
assert_eq!(seq(json!({"start": 0.1, "step": 0.1, "leadingZeros": false}), 3), ["0.1", "0.2", "0.3"], "no rounding noise");
|
||||
assert_eq!(seq(json!({"start": 1, "step": 0.25, "trailingZeros": true}), 3), ["1.00", "1.25", "1.50"]);
|
||||
assert_eq!(seq(json!({"start": 4, "step": 0}), 3), ["4", "4", "4"]);
|
||||
assert_eq!(
|
||||
seq(json!({"start": 1e9 + 0.1, "step": 0.1, "end": 1e9 + 0.3}), 5),
|
||||
["1000000000.1", "1000000000.2", "1000000000.3"],
|
||||
"a value that rounds to the end counts"
|
||||
);
|
||||
assert_eq!(
|
||||
seq(json!({"start": 10000000000.1, "step": 0.1, "end": 10000000000.3}), 5),
|
||||
["10000000000.1", "10000000000.2", "10000000000.3"],
|
||||
"large values keep the inclusive decimal end"
|
||||
);
|
||||
assert_eq!(seq(json!({"start": 1e12, "step": 0.000001, "end": 1e12}), 3), ["1000000000000"], "an end equal to the start counts");
|
||||
assert_eq!(
|
||||
seq(json!({"start": 999999999999.9_f64, "step": 0.000001}), 3),
|
||||
["999999999999.9", "999999999999.900001", "999999999999.900002"],
|
||||
"large values keep their decimal digits when scaled for a small step"
|
||||
);
|
||||
assert_eq!(
|
||||
seq(json!({"start": 999999999999.9_f64, "step": 0.000001, "end": 999999999999.9_f64}), 3),
|
||||
["999999999999.9"],
|
||||
"the end uses the same decimal scaling as the start"
|
||||
);
|
||||
assert_eq!(seq(json!({"start": 0.1, "step": 3.3}), 4), ["00.1", "03.4", "06.7", "10"], "padded to the rounded last number");
|
||||
assert_eq!(seq(json!({"start": 1, "step": 1_000_000_000_000_u64}), 9009).last().map(String::as_str), Some("9008000000000001"));
|
||||
assert_eq!(seq(json!({"start": -0.25, "step": 0.125}), 5), ["-0.25", "-0.125", "0", "0.125", "0.25"]);
|
||||
assert_eq!(seq(json!({"start": -0.0000001, "step": 0}), 1), ["0"], "rounded zero has no minus sign");
|
||||
assert_eq!(seq(json!({"start": 9.9999999, "step": 0}), 1), ["10"], "width uses the rounded whole part");
|
||||
assert_eq!(seq(json!({"start": -0.0000005, "step": 0}), 1), ["-0.000001"], "decimal ties round away from zero");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unthreaded_type_checks_the_threads_once() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let scans = super::threads::thread_scans();
|
||||
super::make_numbers(&mut s, &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert_eq!(super::threads::thread_scans() - scans, 1, "selection size does not multiply thread scans");
|
||||
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "2", "3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threaded_type_is_refused() {
|
||||
let mut s = session();
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "1 2 3", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
let n = steps(&s);
|
||||
assert!(s.execute(C, &json!({"ids": [a, b]})).is_err());
|
||||
assert_eq!((plain(&s, NodeId(a)), steps(&s)), ("1 2 3".to_string(), n));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_spans_find_numbers_and_placeholders() {
|
||||
assert_eq!(number_spans("No. 12, page 3.5 of 1,000."), [(4, 6), (13, 16), (20, 25)]);
|
||||
assert!(number_spans("none").is_empty());
|
||||
assert_eq!(placeholder_spans("a{%N}b{%n}"), [(1, 5), (6, 10)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_whole_text_gets_numbered_in_stacking_order_as_one_step() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let n = steps(&s);
|
||||
let out = s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[1].0], "start": 7})).unwrap();
|
||||
assert_eq!(out["count"], json!(3));
|
||||
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["7", "8", "9"], "from the back");
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(ids.iter().all(|id| plain(&s, *id) == "x"), "undone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_and_placeholders_are_replaced_inside_the_text() {
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, "Seat 99, row 4");
|
||||
let b = text_at(&mut s, 40.0, 140.0, "no digits");
|
||||
let c = text_at(&mut s, 40.0, 180.0, "Seat 1");
|
||||
s.execute(C, &json!({"ids": [a.0, b.0, c.0], "replace": "numbers", "start": 5})).unwrap();
|
||||
assert_eq!([plain(&s, a), plain(&s, b), plain(&s, c)], ["Seat 5, row 5", "no digits", "Seat 6"], "text with no number is skipped");
|
||||
let d = text_at(&mut s, 40.0, 220.0, "Tag {%N} / {%n}");
|
||||
let e = text_at(&mut s, 40.0, 260.0, "Tag 3");
|
||||
s.execute(C, &json!({"ids": [d.0, e.0], "replace": "placeholder", "start": 2})).unwrap();
|
||||
assert_eq!([plain(&s, d), plain(&s, e)], ["Tag 2 / 2", "Tag 3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruby_follows_each_number_or_placeholder_replacement() {
|
||||
let mut s = session();
|
||||
let word = "漢字";
|
||||
for (replace, words) in [("numbers", "1 2 漢字"), ("placeholder", "{%n} {%N} 漢字")] {
|
||||
let id = text_at(&mut s, 40.0, 100.0, words);
|
||||
let start = words.find(word).unwrap();
|
||||
s.execute("type.ruby", &json!({"ids": [id.0], "start": start, "end": start + word.len(), "text": "かんじ"})).unwrap();
|
||||
s.execute(C, &json!({"ids": [id.0], "replace": replace, "start": 123456})).unwrap();
|
||||
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") };
|
||||
let text = t.plain_text();
|
||||
assert_eq!(text, "123456 123456 漢字");
|
||||
assert_eq!(t.ruby.len(), 1);
|
||||
let ruby = &t.ruby[0];
|
||||
assert_eq!(&text[ruby.start..ruby.end], word, "ruby follows both replacements in {replace} mode");
|
||||
assert_eq!(ruby.text, "かんじ");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_and_columns_order_by_position() {
|
||||
let mut s = session();
|
||||
// Created bottom-right first, so stacking order differs from both positions.
|
||||
let br = text_at(&mut s, 300.0, 200.0, "x");
|
||||
let tl = text_at(&mut s, 40.0, 100.0, "x");
|
||||
let bl = text_at(&mut s, 40.0, 200.0, "x");
|
||||
let tr = text_at(&mut s, 300.0, 102.0, "x");
|
||||
let ids = json!([br.0, tl.0, bl.0, tr.0]);
|
||||
s.execute(C, &json!({"ids": ids, "order": "rows"})).unwrap();
|
||||
assert_eq!([tl, tr, bl, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"], "a small offset stays in its row");
|
||||
s.execute(C, &json!({"ids": ids, "order": "columns"})).unwrap();
|
||||
assert_eq!([tl, bl, tr, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_leaves_the_rest_or_removes_it() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..4).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
s.execute(C, &json!({"ids": all, "end": 2})).unwrap();
|
||||
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "2", "x", "x"]);
|
||||
let out = s.execute(C, &json!({"ids": all, "start": 5, "end": 6, "removeUnused": true})).unwrap();
|
||||
assert_eq!(out["removed"], json!([ids[2].0, ids[3].0]));
|
||||
assert!(s.doc().unwrap().doc.node(ids[3]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_gives_every_number_once() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 3, "leadingZeros": false})).unwrap();
|
||||
let mut got: Vec<String> = ids.iter().map(|id| plain(&s, *id)).collect();
|
||||
assert_ne!(got, ["1", "2", "3", "4", "5", "6"], "seed 3 moves them");
|
||||
got.sort();
|
||||
assert_eq!(got, ["1", "2", "3", "4", "5", "6"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_with_an_end_can_number_any_object() {
|
||||
let mut numbered = [false; 6];
|
||||
for seed in 0..40 {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": seed, "end": 2, "removeUnused": true})).unwrap();
|
||||
assert_eq!(out["removed"].as_array().unwrap().len(), 4);
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
numbered[i] |= s.doc().unwrap().doc.node(*id).is_some();
|
||||
}
|
||||
}
|
||||
assert_eq!(numbered, [true; 6], "every object is numbered for some seed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_seed_numbers_and_removes_the_same_objects() {
|
||||
let run = || {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..8).map(|i| text_at(&mut s, 40.0, 40.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 11, "end": 4, "removeUnused": true})).unwrap();
|
||||
let texts: Vec<Option<String>> = ids.iter().map(|id| s.doc().unwrap().doc.node(*id).map(|_| plain(&s, *id))).collect();
|
||||
let removed: Vec<usize> =
|
||||
out["removed"].as_array().unwrap().iter().map(|r| ids.iter().position(|id| Some(id.0) == r.as_u64()).unwrap()).collect();
|
||||
(texts, removed)
|
||||
};
|
||||
let (texts, removed) = run();
|
||||
assert_eq!(removed.len(), 4);
|
||||
assert_eq!(run(), (texts, removed), "seed 11 gives each object the same number and removes the same ones");
|
||||
}
|
||||
|
||||
fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.doc().unwrap().doc.parent_of(ids[0]).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_number_in_the_text_is_replaced_with_its_sign() {
|
||||
assert_eq!(number_spans("Seat -4, A-4"), [(5, 7), (11, 12)], "a hyphen after a letter is not a sign");
|
||||
assert_eq!(number_spans("É-4"), [(3, 4)], "nor after a letter outside ASCII");
|
||||
assert_eq!(number_spans("E\u{301}-4"), [(4, 5)], "nor after a letter with a combining mark");
|
||||
assert_eq!(number_spans("क्-4"), [(7, 8)], "nor after a letter with a virama");
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, "Seat -4");
|
||||
let b = text_at(&mut s, 40.0, 140.0, "Seat 9");
|
||||
s.execute(C, &json!({"ids": [a.0, b.0], "replace": "numbers", "start": 2, "step": -3})).unwrap();
|
||||
assert_eq!([plain(&s, a), plain(&s, b)], ["Seat 2", "Seat -1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_that_already_reads_the_number_is_not_edited() {
|
||||
let text = "5 and 4";
|
||||
assert_eq!(super::edits(text, number_spans(text), "5"), [(6, 7, "5".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_matches_in_one_run_are_refused() {
|
||||
let mut unchanged = session();
|
||||
let text = vec!["1"; super::MAX_MATCHES + 1].join(" ");
|
||||
let id = text_at(&mut unchanged, 40.0, 100.0, &text);
|
||||
let before = steps(&unchanged);
|
||||
let out = unchanged.execute(C, &json!({"ids": [id.0], "start": 1, "replace": "numbers"})).unwrap();
|
||||
assert_eq!(out["count"], 0);
|
||||
assert_eq!(plain(&unchanged, id), text);
|
||||
assert_eq!(steps(&unchanged), before);
|
||||
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, &"{%n}".repeat(super::MAX_MATCHES + 1));
|
||||
let n = steps(&s);
|
||||
assert!(s.execute(C, &json!({"ids": [a.0], "replace": "placeholder"})).is_err());
|
||||
assert_eq!(steps(&s), n);
|
||||
// Whole texts are not matches: the object limit covers them.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
text_at(&mut s, 40.0, 140.0, "x");
|
||||
// Each duplicate of the whole selection doubles it: 2^14 objects in 14 steps.
|
||||
for _ in 0..14 {
|
||||
s.execute("edit.duplicate", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
}
|
||||
let count = s.doc().unwrap().selection.objects.len();
|
||||
assert!(count > super::MAX_MATCHES, "{count} objects");
|
||||
let out = s.execute(C, &json!({"step": 0}));
|
||||
assert!(out.is_ok());
|
||||
let out = out.unwrap();
|
||||
assert!(out["count"].as_u64().unwrap() > super::MAX_MATCHES as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_type_in_a_group_is_left_alone() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let group = group_of(&mut s, &ids);
|
||||
s.execute("object.setProps", &json!({"ids": [ids[1].0], "locked": true})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [ids[2].0], "visible": false})).unwrap();
|
||||
let out = s.execute(C, &json!({"ids": [group.0], "end": 1, "removeUnused": true})).unwrap();
|
||||
assert_eq!(out["removed"], json!([]));
|
||||
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "x", "x"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_unused_type_keeps_a_clipping_mask_and_the_selection() {
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, "x");
|
||||
let b = text_at(&mut s, 40.0, 140.0, "x");
|
||||
// The top object becomes the mask; it sits lowest on the page, so rows number it last.
|
||||
let mask = text_at(&mut s, 40.0, 300.0, "x");
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, mask.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().doc.parent_of(mask).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let out = s.execute(C, &json!({"order": "rows", "end": 1, "removeUnused": true})).unwrap();
|
||||
assert_eq!(out["removed"], json!([b.0]), "the mask stays");
|
||||
assert!(s.doc().unwrap().doc.node(mask).is_some());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [group], "the group stays selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_are_found_among_the_type_that_gets_numbers() {
|
||||
let mut s = session();
|
||||
let upper = text_at(&mut s, 300.0, 100.0, "1");
|
||||
let lower = text_at(&mut s, 40.0, 135.0, "1");
|
||||
let h1 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 400, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap());
|
||||
let h2 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 700, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute(C, &json!({"ids": [upper.0, lower.0, h1.0, h2.0], "replace": "numbers", "order": "rows", "start": 1, "leadingZeros": false})).unwrap();
|
||||
assert_eq!([plain(&s, upper), plain(&s, lower)], ["1", "2"], "headings without numbers do not merge the rows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() {
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, "1");
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0]})).unwrap()["count"], json!(0));
|
||||
assert_eq!(steps(&s), n);
|
||||
for p in [
|
||||
json!({"ids": [a.0], "start": "one"}),
|
||||
json!({"ids": [a.0], "step": 1e13}),
|
||||
json!({"ids": [a.0], "order": "diagonal"}),
|
||||
json!({"ids": [a.0], "digits": 0}),
|
||||
json!({"ids": [a.0], "removeUnused": true}),
|
||||
json!({"ids": [a.0], "shuffle": "yes"}),
|
||||
json!({"ids": [a.0], "seed": "x"}),
|
||||
] {
|
||||
assert!(s.execute(C, &p).is_err(), "{p} fails");
|
||||
}
|
||||
assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n));
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::write_atomic;
|
||||
use super::{EngineError, Result, Session, Value, bad, json};
|
||||
|
||||
// ---------- the file system (none on the web, where commands take and return bytes) ----------
|
||||
@@ -325,8 +323,30 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
// Work that stops early for a cancel can leave a truncated result: none of it is written.
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
// Never a half-written file: see [`write_atomic`].
|
||||
write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e))
|
||||
// Never a half-written file: see [`vectorcraft_format::write_atomic`].
|
||||
write_checked(path, |f| std::io::Write::write_all(f, bytes)).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// [`vectorcraft_format::write_atomic_with`] for `path`, which [`may_write`] allowed. While writes
|
||||
/// are checked ([`crate::file_access::writes_checked`]), the folder that receives the file is
|
||||
/// checked again as it is opened, and the file goes into that open folder
|
||||
/// ([`vectorcraft_format::write_atomic_checked`]): a folder on the path that is replaced after the
|
||||
/// check does not redirect the write.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>) -> std::io::Result<()> {
|
||||
let path = std::path::Path::new(path);
|
||||
if !crate::file_access::writes_checked() {
|
||||
return vectorcraft_format::write_atomic_with(path, fill);
|
||||
}
|
||||
vectorcraft_format::write_atomic_checked(path, fill, |opened| {
|
||||
// On Unix `opened` is the open folder's real path with the file's name: compared as it is,
|
||||
// without looking the folder up again. Elsewhere it is `path` itself.
|
||||
#[cfg(unix)]
|
||||
let checked = crate::file_access::check_write_real(opened);
|
||||
#[cfg(not(unix))]
|
||||
let checked = crate::file_access::check_write_unrecorded(&opened.to_string_lossy());
|
||||
checked.map_err(std::io::Error::other)
|
||||
})
|
||||
}
|
||||
|
||||
/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the
|
||||
@@ -344,7 +364,7 @@ fn write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e))
|
||||
write_checked(path, |f| fill(f)).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
|
||||
@@ -358,7 +378,7 @@ pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e))
|
||||
write_checked(path, |f| fill(f)).map_err(|e| save_write_error(path, e))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -751,4 +771,43 @@ mod tests {
|
||||
assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The second check of a checked write compares the open folder's real path as it is: a folder
|
||||
/// on that path replaced afterwards by a link into the write root does not make a place outside
|
||||
/// the root pass.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_compares_the_open_folder_without_looking_it_up_again() {
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-real-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (root, out) = (base.join("root"), base.join("out"));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::create_dir_all(out.join("x")).unwrap();
|
||||
let real = out.join("x/doc.svg");
|
||||
std::fs::remove_dir(out.join("x")).unwrap();
|
||||
std::os::unix::fs::symlink(&root, out.join("x")).unwrap();
|
||||
let roots = AutomationRoots::new(&[], &[root.as_path()]).unwrap();
|
||||
assert!(confine(roots.as_ref(), || crate::file_access::check_write_unrecorded(&real.to_string_lossy())).is_ok(), "looked up, it passes");
|
||||
let checked = confine(roots.as_ref(), || crate::file_access::check_write_real(&real));
|
||||
assert!(checked.is_err_and(|e| e.contains("outside the write root")));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A checked write through a link to a folder whose name is not valid UTF-8, inside the write
|
||||
/// root, is saved.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_checked_write_saves_into_a_folder_whose_name_is_not_text() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-bytes-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let bytes = base.join(std::ffi::OsStr::from_bytes(b"folder-\xff"));
|
||||
std::fs::create_dir_all(&bytes).unwrap();
|
||||
std::os::unix::fs::symlink(&bytes, base.join("text")).unwrap();
|
||||
let roots = AutomationRoots::new(&[], &[base.as_path()]).unwrap();
|
||||
let path = base.join("text/doc.svg").to_string_lossy().into_owned();
|
||||
confine(roots.as_ref(), || write_file(&path, b"new")).unwrap();
|
||||
assert_eq!(std::fs::read(bytes.join("doc.svg")).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
@@ -758,13 +758,14 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and
|
||||
/// report where it is on disk.
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and
|
||||
/// report where it is on disk, or edit text once per match with no limit on the matches in one call.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
"addon.pen.nextSegment",
|
||||
"addon.type.fontSheet",
|
||||
"addon.type.numbers",
|
||||
"color.contrast",
|
||||
"effect.refreshDeferred",
|
||||
"graphicStyle.setOptions",
|
||||
|
||||
@@ -100,16 +100,9 @@ impl AutomationRoots {
|
||||
/// May the file or folder at `path` be read (or written)? It must lie inside one of the roots
|
||||
/// of that kind. `Err` says why not.
|
||||
pub fn check(&self, path: &str, access: Access) -> Result<(), String> {
|
||||
let roots = match access {
|
||||
Access::Read => &self.read,
|
||||
Access::Write => &self.write,
|
||||
};
|
||||
// The messages are spelled out whole, as the translation catalogs match them.
|
||||
let roots = self.of(access);
|
||||
if roots.is_empty() {
|
||||
return match access {
|
||||
Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")),
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")),
|
||||
};
|
||||
return Err(refused(roots, path, access));
|
||||
}
|
||||
// Resolving a path on another computer connects to it: unless a root is on a network
|
||||
// share, such a path is refused by its name before anything is looked up.
|
||||
@@ -120,12 +113,22 @@ impl AutomationRoots {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
|
||||
match (shown.as_slice(), access) {
|
||||
([root], Access::Read) => Err(format!("automation path rejected: outside the read root {root}: {path}")),
|
||||
([root], Access::Write) => Err(format!("automation path rejected: outside the write root {root}: {path}")),
|
||||
(_, Access::Read) => Err(format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", "))),
|
||||
(_, Access::Write) => Err(format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", "))),
|
||||
Err(refused(roots, path, access))
|
||||
}
|
||||
|
||||
/// [`AutomationRoots::check`] for `real`, a path whose links have been followed already: it is
|
||||
/// compared with the roots as it is, and not looked up again.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
|
||||
let roots = self.of(access);
|
||||
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
|
||||
}
|
||||
|
||||
/// The roots of the kind `access`.
|
||||
fn of(&self, access: Access) -> &[Root] {
|
||||
match access {
|
||||
Access::Read => &self.read,
|
||||
Access::Write => &self.write,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +160,24 @@ impl AutomationRoots {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `path` is refused `access` under `roots`, the roots of that kind.
|
||||
fn refused(roots: &[Root], path: &str, access: Access) -> String {
|
||||
// The messages are spelled out whole, as the translation catalogs match them.
|
||||
if roots.is_empty() {
|
||||
return match access {
|
||||
Access::Read => format!("automation filesystem access is not granted: read authority is absent: {path}"),
|
||||
Access::Write => format!("automation filesystem access is not granted: write authority is absent: {path}"),
|
||||
};
|
||||
}
|
||||
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
|
||||
match (shown.as_slice(), access) {
|
||||
([root], Access::Read) => format!("automation path rejected: outside the read root {root}: {path}"),
|
||||
([root], Access::Write) => format!("automation path rejected: outside the write root {root}: {path}"),
|
||||
(_, Access::Read) => format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", ")),
|
||||
(_, Access::Write) => format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the roots are in force on a thread ([`confine`], [`unconfined`]).
|
||||
#[derive(Clone, Debug)]
|
||||
enum Scope {
|
||||
@@ -371,18 +392,34 @@ impl ScriptGate {
|
||||
also.check(path, access)?;
|
||||
}
|
||||
let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() };
|
||||
let allowed = real.is_some_and(|real| {
|
||||
let scoped = match access {
|
||||
Access::Read => self.read.allows(&real) || self.write.allows(&real),
|
||||
Access::Write => self.write.allows(&real),
|
||||
};
|
||||
// A read-only file is not written over, also where a rename could replace it.
|
||||
let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
|
||||
let held = matches!(access, Access::Write) && self.held.contains(&real);
|
||||
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
|
||||
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
|
||||
});
|
||||
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
if real.is_some_and(|real| self.allows_real(&real, access)) { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
}
|
||||
|
||||
/// [`ScriptGate::check`] for `real`, a path whose links have been followed already: it is
|
||||
/// compared as it is, and not looked up again.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
|
||||
if let Some(also) = &self.also {
|
||||
also.check_real(real, access)?;
|
||||
}
|
||||
if !ScriptScope::refused_by_name(real) && self.allows_real(real, access) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Script file access denied: {}", real.display()))
|
||||
}
|
||||
}
|
||||
|
||||
/// May the place at the real path `real` be read (or written) through this gate alone?
|
||||
fn allows_real(&self, real: &Path, access: Access) -> bool {
|
||||
let scoped = match access {
|
||||
Access::Read => self.read.allows(real) || self.write.allows(real),
|
||||
Access::Write => self.write.allows(real),
|
||||
};
|
||||
// A read-only file is not written over, also where a rename could replace it.
|
||||
let read_only = matches!(access, Access::Write) && std::fs::metadata(real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
|
||||
let held = matches!(access, Access::Write) && self.held.iter().any(|h| h == real);
|
||||
let linked = matches!(access, Access::Read) && self.linked.has(real) && !self.read.keeps_out(real);
|
||||
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,8 +499,7 @@ pub fn is_path_key(key: &str) -> bool {
|
||||
/// May `path` be written here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_write(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)?;
|
||||
check_write_unrecorded(path)?;
|
||||
WRITES.with(|w| {
|
||||
if let Some(paths) = w.borrow_mut().as_mut()
|
||||
&& !paths.iter().any(|(p, _)| p == path)
|
||||
@@ -474,6 +510,26 @@ pub fn check_write(path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_write`] without recording `path` as written.
|
||||
pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)
|
||||
}
|
||||
|
||||
/// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been
|
||||
/// followed already (the folder a checked write has opened): it is compared as it is, so the folder
|
||||
/// is not looked up again by its path.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_write_real(real: &Path) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?;
|
||||
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write))
|
||||
}
|
||||
|
||||
/// Whether a write here is checked: roots are in force, or a script's command runs.
|
||||
pub(crate) fn writes_checked() -> bool {
|
||||
current().is_some() || in_script_command()
|
||||
}
|
||||
|
||||
/// A file's modification time and length; `None` when there is no file at `path`.
|
||||
type Stamp = Option<(Option<std::time::SystemTime>, u64)>;
|
||||
|
||||
@@ -1200,6 +1256,7 @@ mod tests {
|
||||
fn a_script_gate_does_not_write_over_a_read_only_file() {
|
||||
let (base, _) = folders("gate-read-only");
|
||||
let out = base.join("out/kept.svg");
|
||||
let _cleanup = ReadOnlyFixture { file: out.clone(), folder: base.clone() };
|
||||
std::fs::write(&out, "<svg/>").unwrap();
|
||||
let gate = ScriptGate {
|
||||
read: ScriptScope::default(),
|
||||
@@ -1218,14 +1275,47 @@ mod tests {
|
||||
assert!(document_write(), "an open document's file is written");
|
||||
let mut perms = std::fs::metadata(&out).unwrap().permissions();
|
||||
perms.set_readonly(true);
|
||||
std::fs::set_permissions(&out, perms.clone()).unwrap();
|
||||
std::fs::set_permissions(&out, perms).unwrap();
|
||||
assert_eq!(check(&kept), (false, true), "a read-only file is read but not written");
|
||||
assert!(check(&fresh).0, "a new file next to it is written");
|
||||
assert!(!document_write(), "also when it is an open document's file");
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&out, perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Makes `file` writable again and removes `folder` when the test ends, a failed assertion
|
||||
/// included: Windows does not delete a read-only file.
|
||||
struct ReadOnlyFixture {
|
||||
file: PathBuf,
|
||||
folder: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for ReadOnlyFixture {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(meta) = std::fs::metadata(&self.file) {
|
||||
let mut perms = meta.permissions();
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
let _ = std::fs::set_permissions(&self.file, perms);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&self.folder);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_only_fixture_is_removed_when_its_test_fails() {
|
||||
let (base, _) = folders("read-only-fixture");
|
||||
let file = base.join("out/locked.svg");
|
||||
std::fs::write(&file, "<svg/>").unwrap();
|
||||
let failed = std::panic::catch_unwind(|| {
|
||||
let _cleanup = ReadOnlyFixture { file: file.clone(), folder: base.clone() };
|
||||
let mut perms = std::fs::metadata(&file).unwrap().permissions();
|
||||
perms.set_readonly(true);
|
||||
std::fs::set_permissions(&file, perms).unwrap();
|
||||
assert!(std::fs::metadata(&file).unwrap().permissions().readonly(), "the fixture is read-only");
|
||||
panic!("a failed assertion");
|
||||
});
|
||||
let payload = failed.err().unwrap_or_else(|| panic!("the closure did not panic"));
|
||||
assert_eq!(payload.downcast_ref::<&str>(), Some(&"a failed assertion"), "the test's own panic, not a setup failure");
|
||||
assert!(!base.exists(), "{} is left", base.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -975,9 +975,16 @@ pub(super) fn after_kept_command(h: &Host) {
|
||||
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
|
||||
/// paths stay valid through the change ([`paths::see_all_points`]).
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
edit_item_with(h, item, |h| command(h, id, params))
|
||||
}
|
||||
|
||||
/// Runs `f` on the item's document as [`edit_item`] runs its command. `f` runs after the document
|
||||
/// is made active, so bounds it reads take in type that the switch measured again (in the
|
||||
/// document's own composite fonts, [`Session::set_active`]).
|
||||
fn edit_item_with<T>(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
paths::see_all_points(h);
|
||||
let kept = h.dom.editing.replace(Some(item));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f));
|
||||
h.dom.editing.set(kept);
|
||||
r
|
||||
}
|
||||
@@ -2549,14 +2556,18 @@ fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
let c = h.dom.coords.get();
|
||||
let now = f.to_script(c, Point::new(r.x0, r.y0));
|
||||
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
|
||||
let (dx, dy) = (to.x - r.x0, to.y - r.y0);
|
||||
if dx.abs() > 1e-9 || dy.abs() > 1e-9 {
|
||||
edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?;
|
||||
}
|
||||
// Measured once the document is active.
|
||||
edit_item_with(h, item, |h| {
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(()) };
|
||||
let c = h.dom.coords.get();
|
||||
let now = f.to_script(c, Point::new(r.x0, r.y0));
|
||||
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
|
||||
let (dx, dy) = (to.x - r.x0, to.y - r.y0);
|
||||
if dx.abs() > 1e-9 || dy.abs() > 1e-9 {
|
||||
command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -2590,18 +2601,21 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
}
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
let now = if width { r.width() } else { r.height() };
|
||||
if now <= 0.0 {
|
||||
return Err(HostError::Error(format!("the object has no {what} to scale")));
|
||||
}
|
||||
if (now - size).abs() < 1e-9 {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let pct = size / now * 100.0;
|
||||
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
|
||||
let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"});
|
||||
edit_item(h, item, "object.scale", &p)?;
|
||||
// Measured once the document is active, so the ratio applies to the bounds the scale works on.
|
||||
edit_item_with(h, item, |h| {
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(()) };
|
||||
let now = if width { r.width() } else { r.height() };
|
||||
if now <= 0.0 {
|
||||
return Err(HostError::Error(format!("the object has no {what} to scale")));
|
||||
}
|
||||
if (now - size).abs() < 1e-9 {
|
||||
return Ok(());
|
||||
}
|
||||
let pct = size / now * 100.0;
|
||||
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
|
||||
command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
|
||||
@@ -155,6 +155,37 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() {
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was");
|
||||
}
|
||||
|
||||
/// Type in a document in the back that the switch to that document measures again (here: not
|
||||
/// measured yet) is sized and moved by the bounds measured after the switch.
|
||||
#[test]
|
||||
fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the_switch() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Wide type here", "size": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
let uid = s.active().unwrap().uid;
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let front = s.active().unwrap().uid;
|
||||
let unmeasure = |s: &mut Session| {
|
||||
let st = s.document_mut(uid).unwrap();
|
||||
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) {
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
}
|
||||
};
|
||||
let mut got = Vec::new();
|
||||
for (set, want) in
|
||||
[("t.width = 150; vc.log(t.width);", 150.0), ("t.height = 90; vc.log(t.height);", 90.0), ("t.top = 200; vc.log(t.top);", 200.0)]
|
||||
{
|
||||
unmeasure(&mut s);
|
||||
let out = log(&mut s, &format!("var t = app.documents[1].pageItems[0]; {set}"));
|
||||
got.push((set, out[0].as_f64().unwrap(), want));
|
||||
}
|
||||
for (set, got, want) in got {
|
||||
assert!((got - want).abs() < 1e-6, "{set} read {got}");
|
||||
}
|
||||
assert_eq!(s.active().unwrap().uid, front, "the front document stays in front");
|
||||
}
|
||||
|
||||
/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the
|
||||
/// visible bounds.
|
||||
#[test]
|
||||
|
||||
@@ -10,13 +10,77 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
/// A test's folder, removed when the test ends, a failed assertion included. A read-only file in
|
||||
/// it, which Windows does not delete, is made writable first when the first removal fails.
|
||||
struct Workspace(PathBuf);
|
||||
|
||||
impl std::ops::Deref for Workspace {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for Workspace {
|
||||
fn as_ref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Workspace {
|
||||
fn drop(&mut self) {
|
||||
if std::fs::remove_dir_all(&self.0).is_err() {
|
||||
make_writable(&self.0);
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the read-only flag of every file and folder in `path`, `path` included. Links are not
|
||||
/// followed.
|
||||
fn make_writable(path: &Path) {
|
||||
let Ok(meta) = std::fs::symlink_metadata(path) else { return };
|
||||
if meta.file_type().is_symlink() {
|
||||
return;
|
||||
}
|
||||
let mut perms = meta.permissions();
|
||||
if perms.readonly() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
let _ = std::fs::set_permissions(path, perms);
|
||||
}
|
||||
if meta.is_dir() {
|
||||
for entry in std::fs::read_dir(path).into_iter().flatten().flatten() {
|
||||
make_writable(&entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for test `name`, by its real path, with `main` for the script.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
fn folder(name: &str) -> Workspace {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::create_dir_all(base.join("outside")).unwrap();
|
||||
std::fs::canonicalize(&base).unwrap()
|
||||
Workspace(std::fs::canonicalize(&base).unwrap())
|
||||
}
|
||||
|
||||
/// A test that fails leaves no folder behind, also when it made a file in it read-only.
|
||||
#[test]
|
||||
fn a_failed_test_leaves_no_folder() {
|
||||
let base = folder("failed");
|
||||
let path = base.to_path_buf();
|
||||
let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
|
||||
let locked = base.join("main/locked.txt");
|
||||
std::fs::write(&locked, b"x").unwrap();
|
||||
let mut perms = std::fs::metadata(&locked).unwrap().permissions();
|
||||
perms.set_readonly(true);
|
||||
std::fs::set_permissions(&locked, perms).unwrap();
|
||||
panic!("a failed assertion");
|
||||
}));
|
||||
assert!(failed.is_err());
|
||||
assert!(!path.exists(), "{} is left", path.display());
|
||||
}
|
||||
|
||||
/// A session whose scripts keep their data folders in `base/settings/Script Data`.
|
||||
|
||||
+676
-24
@@ -82,6 +82,285 @@ fn create_new(path: &Path) -> io::Result<File> {
|
||||
OpenOptions::new().write(true).create_new(true).open(path)
|
||||
}
|
||||
|
||||
/// [`write_atomic_with`] for a `path` the caller has allowed by its name. On Unix the folder that
|
||||
/// holds the file is opened once, and `allowed` is asked again with the path that open folder has
|
||||
/// then, joined with the file's name. The temporary file, the replacement, a copy over the file
|
||||
/// where the folder refuses the replacement, and the folder flush all go through that open folder,
|
||||
/// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is
|
||||
/// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at
|
||||
/// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it;
|
||||
/// a link put there later is replaced, never followed. Elsewhere this is `allowed(path)` followed by
|
||||
/// [`write_atomic_with`].
|
||||
#[cfg(unix)]
|
||||
pub fn write_atomic_checked(
|
||||
path: &Path,
|
||||
fill: impl FnOnce(&mut File) -> io::Result<()>,
|
||||
allowed: impl FnOnce(&Path) -> io::Result<()>,
|
||||
) -> io::Result<()> {
|
||||
use rustix::fs::{AtFlags, Mode, OFlags};
|
||||
// A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name`
|
||||
// would drop the slash and save `draft.svg`.
|
||||
let spelled = std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str());
|
||||
if spelled.ends_with(b"/") || spelled.ends_with(b"/.") || spelled == b"." {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())));
|
||||
}
|
||||
let resolved = resolve_link(path)?;
|
||||
let name = resolved
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", resolved.display())))?
|
||||
.to_os_string();
|
||||
let parent = resolved.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
|
||||
let dir = open_folder(parent)?;
|
||||
let real = opened_folder_path(&dir, parent)?;
|
||||
let target = real.join(stored_name(&dir, &real, &name));
|
||||
allowed(&target)?;
|
||||
// Only whether a file is there: its permissions are read again once it is about to be replaced.
|
||||
let replacing = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).is_ok();
|
||||
let tmp_name = temp_path(&target)?.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_default();
|
||||
// Replacing a file: owner-only while it is written, as in `write_atomic_with`.
|
||||
let mode = if replacing { Mode::RUSR | Mode::WUSR } else { Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH };
|
||||
let new_file = OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC;
|
||||
let remove_tmp = || {
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = rustix::fs::unlinkat(&dir, &tmp_name, AtFlags::empty());
|
||||
};
|
||||
// The folder may have moved since it was opened: messages name it where it is now.
|
||||
let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file);
|
||||
let synced = || {
|
||||
// Opened for reading here: the folder handle above may allow name lookups only.
|
||||
let flushed =
|
||||
rustix::fs::openat(&dir, ".", OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).and_then(|d| rustix::fs::fsync(&d));
|
||||
flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() }))
|
||||
};
|
||||
let open_target = |write: bool| -> io::Result<File> {
|
||||
let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY };
|
||||
Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?))
|
||||
};
|
||||
match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) {
|
||||
Ok(mut f) => {
|
||||
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
|
||||
if let Err(e) = filled {
|
||||
drop(f);
|
||||
remove_tmp();
|
||||
return Err(e);
|
||||
}
|
||||
// The file's permissions as they are now, after `fill`, as in `write_atomic_with`: a
|
||||
// change made to them meanwhile is kept. Best effort; a file that can't be looked at
|
||||
// leaves the replacement owner-only.
|
||||
if let Ok(old) = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW) {
|
||||
let _ = keep_permissions_at(&dir, &name, &old, &f);
|
||||
}
|
||||
drop(f);
|
||||
#[cfg(test)]
|
||||
let refuse = RENAME_REFUSED.with(std::cell::Cell::get);
|
||||
#[cfg(not(test))]
|
||||
let refuse = false;
|
||||
let renamed = if refuse { Err(rustix::io::Errno::ACCESS) } else { rustix::fs::renameat(&dir, &tmp_name, &dir, &name) };
|
||||
let Err(refused) = renamed else { return synced() };
|
||||
// The file as it was is copied beside the temporary file, through the open folder, or
|
||||
// to the system's folder where the open folder takes no new file.
|
||||
let old_name = Path::new(&tmp_name).with_extension("old").into_os_string();
|
||||
let old_elsewhere = std::env::temp_dir().join(&old_name);
|
||||
let old_in_folder = std::cell::Cell::new(true);
|
||||
let over = Over {
|
||||
tmp: &|| now(&tmp_name),
|
||||
create_old: &|| match rustix::fs::openat(&dir, &old_name, new_file, Mode::RUSR | Mode::WUSR) {
|
||||
Ok(f) => {
|
||||
old_in_folder.set(true);
|
||||
Ok(File::from(f))
|
||||
}
|
||||
Err(e) if e == rustix::io::Errno::EXIST => Err(e.into()),
|
||||
Err(_) => {
|
||||
old_in_folder.set(false);
|
||||
create_private(&old_elsewhere)
|
||||
}
|
||||
},
|
||||
old: &|| if old_in_folder.get() { now(&old_name) } else { old_elsewhere.clone() },
|
||||
remove_old: &|| {
|
||||
// Best effort: an unfinished copy is of no use.
|
||||
if old_in_folder.get() {
|
||||
let _ = rustix::fs::unlinkat(&dir, &old_name, AtFlags::empty());
|
||||
} else {
|
||||
let _ = std::fs::remove_file(&old_elsewhere);
|
||||
}
|
||||
},
|
||||
open_tmp: &|| {
|
||||
Ok(File::from(rustix::fs::openat(&dir, &tmp_name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?))
|
||||
},
|
||||
remove_tmp: &remove_tmp,
|
||||
open_target: &open_target,
|
||||
synced: &synced,
|
||||
};
|
||||
write_over_in(&over, refused.into())
|
||||
}
|
||||
// A folder that isn't there, a full volume: nothing can be saved there.
|
||||
Err(e) if matches!(io::Error::from(e).kind(), io::ErrorKind::NotFound | io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded) => {
|
||||
Err(e.into())
|
||||
}
|
||||
Err(refused) => {
|
||||
// The folder takes no temporary file: it is written in the system's folder and copied in.
|
||||
let elsewhere = std::env::temp_dir().join(&tmp_name);
|
||||
let mut f = create_private(&elsewhere).map_err(|_| io::Error::from(refused))?;
|
||||
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
|
||||
drop(f);
|
||||
let remove = || {
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(&elsewhere);
|
||||
};
|
||||
if let Err(e) = filled {
|
||||
remove();
|
||||
return Err(e);
|
||||
}
|
||||
let old = elsewhere.with_extension("old");
|
||||
let over = Over {
|
||||
tmp: &|| elsewhere.clone(),
|
||||
create_old: &|| create_private(&old),
|
||||
old: &|| old.clone(),
|
||||
remove_old: &|| {
|
||||
let _ = std::fs::remove_file(&old);
|
||||
},
|
||||
open_tmp: &|| File::open(&elsewhere),
|
||||
remove_tmp: &remove,
|
||||
open_target: &open_target,
|
||||
synced: &synced,
|
||||
};
|
||||
write_over_in(&over, refused.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// See the Unix version.
|
||||
#[cfg(not(unix))]
|
||||
pub fn write_atomic_checked(
|
||||
path: &Path,
|
||||
fill: impl FnOnce(&mut File) -> io::Result<()>,
|
||||
allowed: impl FnOnce(&Path) -> io::Result<()>,
|
||||
) -> io::Result<()> {
|
||||
allowed(path)?;
|
||||
write_atomic_with(path, fill)
|
||||
}
|
||||
|
||||
/// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links
|
||||
/// followed, when that is still the folder `dir` holds (the same device and inode). A folder
|
||||
/// replaced in between is an error.
|
||||
#[cfg(unix)]
|
||||
fn opened_folder_path(dir: &std::os::fd::OwnedFd, parent: &Path) -> io::Result<PathBuf> {
|
||||
let real = std::fs::canonicalize(parent)?;
|
||||
let (open, now) = (rustix::fs::fstat(dir)?, rustix::fs::stat(&real)?);
|
||||
if (open.st_dev, open.st_ino) != (now.st_dev, now.st_ino) {
|
||||
// Not a permission the file system refused: [`read_only_location`] does not take it for one.
|
||||
return Err(io::Error::other(format!("{}: the folder changed while it was opened", parent.display())));
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// The name the entry `name` in the open folder `dir`, whose real path is `real`, is stored under.
|
||||
/// On a volume that ignores letter case, `report.svg` can be stored as `Report.svg`, the name a
|
||||
/// grant for that file was given. `name` itself when nothing is there, or when the entry the path
|
||||
/// leads to is not the one in `dir` (the same device and inode, links not followed).
|
||||
#[cfg(unix)]
|
||||
fn stored_name(dir: &std::os::fd::OwnedFd, real: &Path, name: &std::ffi::OsStr) -> std::ffi::OsString {
|
||||
use rustix::fs::AtFlags;
|
||||
let Ok(here) = rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) else { return name.to_os_string() };
|
||||
let Ok(stored) = std::fs::canonicalize(real.join(name)) else { return name.to_os_string() };
|
||||
let same = stored.parent() == Some(real) && rustix::fs::lstat(&stored).is_ok_and(|s| (s.st_dev, s.st_ino) == (here.st_dev, here.st_ino));
|
||||
match stored.file_name() {
|
||||
Some(stored) if same => stored.to_os_string(),
|
||||
_ => name.to_os_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder at `parent`, opened for looking names up in it. On Linux, Android and FreeBSD that
|
||||
/// is `O_PATH`, and on Apple platforms `O_SEARCH`: neither needs permission to list the folder, so
|
||||
/// a folder that can be written and searched but not listed still takes the file. Where the system
|
||||
/// refuses `O_SEARCH`, the folder is opened for reading.
|
||||
#[cfg(unix)]
|
||||
fn open_folder(parent: &Path) -> io::Result<std::os::fd::OwnedFd> {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
|
||||
let access = OFlags::PATH;
|
||||
#[cfg(target_vendor = "apple")]
|
||||
{
|
||||
// `O_EXEC`, which with `O_DIRECTORY` is `O_SEARCH` (<sys/fcntl.h>).
|
||||
let search = OFlags::from_bits_retain(0x4000_0000);
|
||||
match rustix::fs::open(parent, search | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()) {
|
||||
Err(e) if e == rustix::io::Errno::INVAL => {}
|
||||
opened => return Ok(opened?),
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd")))]
|
||||
let access = OFlags::RDONLY;
|
||||
Ok(rustix::fs::open(parent, access | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?)
|
||||
}
|
||||
|
||||
/// The path the open folder `dir` has now, which may differ from `opened`, its real path when it
|
||||
/// was opened, after it moved. `opened` where the system does not say.
|
||||
#[cfg(unix)]
|
||||
fn folder_now(dir: &std::os::fd::OwnedFd, opened: &Path) -> PathBuf {
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
if let Ok(now) = std::fs::read_link(format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(dir)))
|
||||
&& now.is_absolute()
|
||||
{
|
||||
return now;
|
||||
}
|
||||
#[cfg(target_vendor = "apple")]
|
||||
if let Ok(now) = rustix::fs::getpath(dir) {
|
||||
return PathBuf::from(<std::ffi::OsString as std::os::unix::ffi::OsStringExt>::from_vec(now.into_bytes()));
|
||||
}
|
||||
let _ = dir;
|
||||
opened.to_path_buf()
|
||||
}
|
||||
|
||||
/// [`keep_permissions`] for the temporary file `tmp`, about to replace `name` in folder `dir`, whose
|
||||
/// file has the status `old`. A name that does not hold a plain file has none to keep. The ACL is
|
||||
/// read only from that same file (the same device and inode); when it can't be, the replacement
|
||||
/// keeps no group or other permissions.
|
||||
#[cfg(unix)]
|
||||
fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> io::Result<()> {
|
||||
use rustix::fs::{FileType, Mode};
|
||||
if FileType::from_raw_mode(old.st_mode) != FileType::RegularFile {
|
||||
return Ok(());
|
||||
}
|
||||
let mut mode = Mode::from_raw_mode(old.st_mode);
|
||||
let gid = rustix::fs::Gid::from_raw(old.st_gid);
|
||||
let kept_group = rustix::fs::fstat(tmp).is_ok_and(|t| t.st_gid == old.st_gid) || rustix::fs::fchown(tmp, None, Some(gid)).is_ok();
|
||||
if !kept_group || !keep_acl_at(dir, name, old, tmp) {
|
||||
mode.remove(Mode::RWXG | Mode::RWXO);
|
||||
}
|
||||
rustix::fs::fchmod(tmp, mode).map_err(io::Error::from)
|
||||
}
|
||||
|
||||
/// [`keep_acl`] for `name` in folder `dir`, when it is still the file with the status `old`. The
|
||||
/// file is opened with `O_PATH` without following a link, which needs no permission to read it, and
|
||||
/// its ACL is read through `/proc/self/fd`, which names that open file.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> bool {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
use rustix::io::Errno;
|
||||
const ACL: &str = "system.posix_acl_access";
|
||||
let Ok(target) = rustix::fs::openat(dir, name, OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty()) else {
|
||||
return false;
|
||||
};
|
||||
if !rustix::fs::fstat(&target).is_ok_and(|t| (t.st_dev, t.st_ino) == (old.st_dev, old.st_ino)) {
|
||||
return false;
|
||||
}
|
||||
let opened = format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(&target));
|
||||
let mut buf = vec![0u8; 64 << 10];
|
||||
match rustix::fs::getxattr(opened.as_str(), ACL, &mut buf[..]) {
|
||||
Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::fsetxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()),
|
||||
Err(e) if e == Errno::NODATA => match rustix::fs::fremovexattr(tmp, ACL) {
|
||||
Ok(()) => true,
|
||||
Err(e) => e == Errno::NODATA || e == Errno::NOTSUP,
|
||||
},
|
||||
Err(e) => e == Errno::NOTSUP,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "linux")))]
|
||||
fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &rustix::fs::Stat, _: &File) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// [`write_atomic_with`], with `create` making the temporary file beside the target and `rename`
|
||||
/// moving it over the target.
|
||||
fn write_atomic_stepping(
|
||||
@@ -130,47 +409,114 @@ fn write_atomic_stepping(
|
||||
/// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the
|
||||
/// error says where they are.
|
||||
fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
|
||||
let opened = File::open(tmp).and_then(|from| Ok((from, OpenOptions::new().write(true).create(true).truncate(false).open(target)?)));
|
||||
let old = tmp.with_extension("old");
|
||||
let over = Over {
|
||||
tmp: &|| tmp.to_path_buf(),
|
||||
create_old: &|| create_private(&old),
|
||||
old: &|| old.clone(),
|
||||
remove_old: &|| {
|
||||
let _ = std::fs::remove_file(&old);
|
||||
},
|
||||
open_tmp: &|| File::open(tmp),
|
||||
remove_tmp: &|| {
|
||||
let _ = std::fs::remove_file(tmp);
|
||||
},
|
||||
open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) },
|
||||
synced: &|| sync_written_parent(target),
|
||||
};
|
||||
write_over_in(&over, refused)
|
||||
}
|
||||
|
||||
/// How [`write_over_in`] reaches its files: by their paths, or through a folder opened once
|
||||
/// ([`write_atomic_checked`]).
|
||||
struct Over<'a> {
|
||||
/// Where the temporary file is when an error message names it (its folder may have moved).
|
||||
tmp: &'a dyn Fn() -> PathBuf,
|
||||
/// A new file, for its owner only and never replacing one, that the file as it was is copied to.
|
||||
create_old: &'a dyn Fn() -> io::Result<File>,
|
||||
/// Where the file `create_old` made is when an error message names it.
|
||||
old: &'a dyn Fn() -> PathBuf,
|
||||
/// Best effort: removes the file `create_old` made.
|
||||
remove_old: &'a dyn Fn(),
|
||||
open_tmp: &'a dyn Fn() -> io::Result<File>,
|
||||
/// Best effort.
|
||||
remove_tmp: &'a dyn Fn(),
|
||||
/// The target for writing (created when missing, not truncated) when `true`, for reading when
|
||||
/// `false`.
|
||||
open_target: &'a dyn Fn(bool) -> io::Result<File>,
|
||||
/// The target's folder flushed, after the target is written.
|
||||
synced: &'a dyn Fn() -> io::Result<()>,
|
||||
}
|
||||
|
||||
/// [`write_over`] through `over`.
|
||||
fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> {
|
||||
let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?)));
|
||||
let Ok((mut from, mut to)) = opened else {
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(tmp);
|
||||
(over.remove_tmp)();
|
||||
return Err(refused);
|
||||
};
|
||||
// Nothing to keep of a file that is new or empty.
|
||||
let old = to.metadata().map_or(true, |m| m.len() > 0).then(|| tmp.with_extension("old"));
|
||||
if let Some(old) = &old
|
||||
&& let Err(e) = keep_old(target, old)
|
||||
// Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes
|
||||
// into: one put at its name meanwhile is not copied in its place.
|
||||
let kept = to.metadata().map_or(true, |m| m.len() > 0);
|
||||
if kept
|
||||
&& let Err(e) = (over.open_target)(false).and_then(|mut target| {
|
||||
if !same_file(&target, &to) {
|
||||
return Err(io::Error::other("the file was replaced while it was opened"));
|
||||
}
|
||||
keep_old(&mut target, over)
|
||||
})
|
||||
{
|
||||
// Best effort: a partial copy is of no use.
|
||||
let _ = std::fs::remove_file(old);
|
||||
let why =
|
||||
format!("{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", tmp.display());
|
||||
let why = format!(
|
||||
"{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}",
|
||||
(over.tmp)().display()
|
||||
);
|
||||
return Err(io::Error::new(refused.kind(), RecoveryError(why)));
|
||||
}
|
||||
let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to));
|
||||
drop((from, to));
|
||||
match (copied, old) {
|
||||
(Ok(()), old) => {
|
||||
match (copied, kept) {
|
||||
(Ok(()), kept) => {
|
||||
// Best effort: the file is saved, so the copies are no longer needed.
|
||||
let _ = std::fs::remove_file(tmp);
|
||||
if let Some(old) = old {
|
||||
let _ = std::fs::remove_file(old);
|
||||
(over.remove_tmp)();
|
||||
if kept {
|
||||
(over.remove_old)();
|
||||
}
|
||||
sync_written_parent(target)
|
||||
(over.synced)()
|
||||
}
|
||||
(Err(e), Some(old)) => Err(io::Error::new(
|
||||
(Err(e), true) => Err(io::Error::new(
|
||||
e.kind(),
|
||||
RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display())),
|
||||
RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", (over.tmp)().display(), (over.old)().display())),
|
||||
)),
|
||||
(Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", tmp.display())))),
|
||||
(Err(e), false) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", (over.tmp)().display())))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A flushed copy of `target` as it is, at `old` (for its owner only).
|
||||
fn keep_old(target: &Path, old: &Path) -> io::Result<()> {
|
||||
let mut to = create_private(old)?;
|
||||
io::copy(&mut File::open(target)?, &mut to)?;
|
||||
sync_file(&to)
|
||||
/// A flushed copy of what `target` holds, in the file `over.create_old` makes. A copy this call made
|
||||
/// and could not finish is removed; a file already at that name is left as it is.
|
||||
fn keep_old(target: &mut File, over: &Over<'_>) -> io::Result<()> {
|
||||
let mut to = (over.create_old)()?;
|
||||
let copied = io::copy(target, &mut to).and_then(|_| sync_file(&to));
|
||||
if copied.is_err() {
|
||||
drop(to);
|
||||
(over.remove_old)();
|
||||
}
|
||||
copied
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are open on the same file (the same device and inode). Always `true` off
|
||||
/// Unix.
|
||||
fn same_file(a: &File, b: &File) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
matches!((a.metadata(), b.metadata()), (Ok(a), Ok(b)) if (a.dev(), a.ino()) == (b.dev(), b.ino()))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = (a, b);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// A new file for its owner only (Unix): the system's temporary folder is shared.
|
||||
@@ -325,6 +671,9 @@ thread_local! {
|
||||
static FLUSHES_LEFT: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
|
||||
/// Tests: how many plain `fsync` fallbacks were made on this thread.
|
||||
static PLAIN_FSYNCS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: [`write_atomic_checked`]'s folder refuses the rename.
|
||||
#[cfg(unix)]
|
||||
static RENAME_REFUSED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// A symbolic link keeps pointing at its file: write the file it names.
|
||||
@@ -466,6 +815,282 @@ mod tests {
|
||||
true
|
||||
}
|
||||
|
||||
/// A folder `root/inside` and a folder `outside` beside `root`, by their real paths, and a check
|
||||
/// that allows paths under `root` only.
|
||||
#[cfg(unix)]
|
||||
fn checked_folders(name: &str) -> (PathBuf, PathBuf, PathBuf) {
|
||||
let d = std::fs::canonicalize(dir(name)).unwrap();
|
||||
let (root, outside) = (d.join("root"), d.join("outside"));
|
||||
std::fs::create_dir_all(root.join("inside")).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
(d, root, outside)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ {
|
||||
move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) }
|
||||
}
|
||||
|
||||
/// A folder on the path that is a link to a folder outside when the write starts fails the check
|
||||
/// made on the folder that is opened, and nothing is written outside.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_refuses_a_folder_replaced_before_it_is_opened() {
|
||||
let (d, root, outside) = checked_folders("checked-before");
|
||||
std::fs::remove_dir(root.join("inside")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, root.join("inside")).unwrap();
|
||||
let r = write_atomic_checked(&root.join("inside/doc.txt"), |f| f.write_all(b"new"), under(&root));
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("is outside")), "{r:?}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing is left outside");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A folder on the path replaced by a link to a folder outside after it is checked and opened
|
||||
/// does not redirect the write: the file goes into the folder that was opened.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_stays_in_the_folder_it_opened() {
|
||||
let (d, root, outside) = checked_folders("checked-after");
|
||||
let check = under(&root);
|
||||
let r = write_atomic_checked(
|
||||
&root.join("inside/doc.txt"),
|
||||
|f| f.write_all(b"new"),
|
||||
|p| {
|
||||
check(p)?;
|
||||
std::fs::rename(root.join("inside"), root.join("moved"))?;
|
||||
std::os::unix::fs::symlink(&outside, root.join("inside"))
|
||||
},
|
||||
);
|
||||
r.unwrap();
|
||||
assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder");
|
||||
assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A link put at the file's name after the check is replaced by the file, not followed.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_replaces_a_link_put_at_its_name() {
|
||||
let (d, root, outside) = checked_folders("checked-link");
|
||||
std::fs::write(outside.join("other.txt"), b"keep").unwrap();
|
||||
let path = root.join("inside/doc.txt");
|
||||
let check = under(&root);
|
||||
write_atomic_checked(
|
||||
&path,
|
||||
|f| f.write_all(b"new"),
|
||||
|p| {
|
||||
check(p)?;
|
||||
std::os::unix::fs::symlink(outside.join("other.txt"), &path)
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(outside.join("other.txt")).unwrap(), b"keep");
|
||||
assert!(std::fs::symlink_metadata(&path).unwrap().is_file());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// Permissions taken away from the file while the new content is written stay taken away.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_keeps_permissions_changed_while_it_fills() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (d, root, _) = checked_folders("checked-mode");
|
||||
let path = root.join("inside/doc.txt");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
let fill = |f: &mut File| {
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
||||
f.write_all(b"new")
|
||||
};
|
||||
write_atomic_checked(&path, fill, under(&root)).unwrap();
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A folder that changed between being opened and being looked up by its path is not reported
|
||||
/// as a read-only location.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_changed_folder_is_not_a_read_only_location() {
|
||||
let (d, root, outside) = checked_folders("checked-identity");
|
||||
let opened = open_folder(&root.join("inside")).unwrap();
|
||||
let e = opened_folder_path(&opened, &outside).unwrap_err();
|
||||
assert!(e.to_string().contains("the folder changed while it was opened"), "{e}");
|
||||
assert!(!read_only_location(&e), "{e:?}");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A checked write whose folder moved after it was opened, refused the rename, and failed to
|
||||
/// copy into the file: the temporary file and the copy of the old content stay in that folder,
|
||||
/// and the error names them where they are now. (FreeBSD does not say where an open folder is
|
||||
/// now: there the error names them where the folder was opened.)
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_names_the_kept_file_where_its_folder_moved() {
|
||||
let (d, root, _) = checked_folders("checked-moved");
|
||||
std::fs::write(root.join("inside/doc.txt"), b"original").unwrap();
|
||||
let check = under(&root);
|
||||
let r = write_atomic_checked(
|
||||
&root.join("inside/doc.txt"),
|
||||
|f| f.write_all(b"new"),
|
||||
|p| {
|
||||
check(p)?;
|
||||
std::fs::rename(root.join("inside"), root.join("moved"))?;
|
||||
RENAME_REFUSED.with(|c| c.set(true));
|
||||
// The temporary file's flush and the copy of the old content work, the next doesn't.
|
||||
FLUSHES_LEFT.with(|c| c.set(Some(2)));
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
RENAME_REFUSED.with(|c| c.set(false));
|
||||
FLUSHES_LEFT.with(|c| c.set(None));
|
||||
let message = r.unwrap_err().to_string();
|
||||
let kept = |ext: &str| -> PathBuf {
|
||||
let found: Vec<_> = std::fs::read_dir(root.join("moved"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().path())
|
||||
.filter(|p| p.extension().is_some_and(|x| x == ext))
|
||||
.collect();
|
||||
let [kept] = found.as_slice() else { panic!("one .{ext} file: {found:?}") };
|
||||
std::fs::canonicalize(kept).unwrap()
|
||||
};
|
||||
let (tmp, old) = (kept("tmp"), kept("old"));
|
||||
assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec()));
|
||||
let named_in =
|
||||
if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") };
|
||||
for file in [&tmp, &old] {
|
||||
let named = named_in.join(file.file_name().unwrap());
|
||||
assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A refused rename copies the old content through the file handle it then overwrites: when a
|
||||
/// different file is at the name by the time it is opened for reading, nothing is overwritten and
|
||||
/// the new content stays in the temporary file.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_refused_rename_copies_aside_the_file_it_overwrites() {
|
||||
let d = dir("no-rename-swapped");
|
||||
let (path, other, tmp) = (d.join("doc.txt"), d.join("other.txt"), d.join("doc.tmp"));
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
std::fs::write(&other, b"someone else's").unwrap();
|
||||
std::fs::write(&tmp, b"new").unwrap();
|
||||
let old = d.join("doc.old");
|
||||
let over = Over {
|
||||
tmp: &|| tmp.clone(),
|
||||
create_old: &|| create_private(&old),
|
||||
old: &|| old.clone(),
|
||||
remove_old: &|| {
|
||||
let _ = std::fs::remove_file(&old);
|
||||
},
|
||||
open_tmp: &|| File::open(&tmp),
|
||||
remove_tmp: &|| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
},
|
||||
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) },
|
||||
synced: &|| Ok(()),
|
||||
};
|
||||
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
|
||||
assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read(&tmp).unwrap(), b"new");
|
||||
assert!(!old.exists());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A path written as a folder is refused, and no file is made under the name before the slash.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_refuses_a_path_written_as_a_folder() {
|
||||
let (d, root, _) = checked_folders("checked-slash");
|
||||
for spelled in ["inside/draft.svg/", "inside/draft.svg/."] {
|
||||
let r = write_atomic_checked(&root.join(spelled), |f| f.write_all(b"new"), under(&root));
|
||||
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::InvalidInput), "{spelled}");
|
||||
}
|
||||
assert!(!root.join("inside/draft.svg").exists());
|
||||
write_atomic_checked(&root.join("inside/draft.svg"), |f| f.write_all(b"new"), under(&root)).unwrap();
|
||||
assert_eq!(std::fs::read(root.join("inside/draft.svg")).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// On a volume that ignores letter case, a write to `report.txt` where `Report.txt` is stored
|
||||
/// is checked as `Report.txt`, the name a grant for the file has. (Skipped where the volume keeps
|
||||
/// letter case apart.)
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_checks_the_stored_name_of_the_file() {
|
||||
let (d, root, _) = checked_folders("checked-case");
|
||||
let stored = root.join("inside/Report.txt");
|
||||
std::fs::write(&stored, b"old").unwrap();
|
||||
if !root.join("inside/report.txt").exists() {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
return;
|
||||
}
|
||||
let exact = |p: &Path| if p == stored { Ok(()) } else { Err(io::Error::other(format!("{} is not granted", p.display()))) };
|
||||
write_atomic_checked(&root.join("inside/report.txt"), |f| f.write_all(b"new"), exact).unwrap();
|
||||
assert_eq!(std::fs::read(&stored).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A replaced file that its owner may write but not read keeps the ACL that lets someone else
|
||||
/// read it. (Skipped on a file system without ACLs, and for root, which can read any file.)
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_checked_write_keeps_the_acl_of_a_file_its_owner_cannot_read() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
const ACL: &str = "system.posix_acl_access";
|
||||
let (d, root, _) = checked_folders("checked-acl-write-only");
|
||||
let path = root.join("inside/doc.txt");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
// u::-w-, u:nobody:r--, g::---, m::r--, o::---
|
||||
let mut acl = 2u32.to_le_bytes().to_vec();
|
||||
for (tag, perm, id) in [(0x01u16, 2u16, u32::MAX), (0x02, 4, 65534), (0x04, 0, u32::MAX), (0x10, 4, u32::MAX), (0x20, 0, u32::MAX)] {
|
||||
acl.extend(tag.to_le_bytes());
|
||||
acl.extend(perm.to_le_bytes());
|
||||
acl.extend(id.to_le_bytes());
|
||||
}
|
||||
match rustix::fs::setxattr(&path, ACL, &acl, rustix::fs::XattrFlags::empty()) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e == rustix::io::Errno::NOTSUP => {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
return;
|
||||
}
|
||||
Err(e) => panic!("setting the ACL: {e}"),
|
||||
}
|
||||
if File::open(&path).is_ok() {
|
||||
// Root reads any file.
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
return;
|
||||
}
|
||||
write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)).unwrap();
|
||||
let mut buf = vec![0u8; 4096];
|
||||
let n = rustix::fs::getxattr(&path, ACL, &mut buf[..]).unwrap();
|
||||
assert_eq!(buf.get(..n).unwrap(), acl.as_slice(), "the ACL is kept");
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A folder that can be written and searched but not listed takes the file. (The permission
|
||||
/// does not hold for root, which can list any folder.)
|
||||
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
|
||||
#[test]
|
||||
fn a_checked_write_saves_into_a_folder_that_cannot_be_listed() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (d, root, _) = checked_folders("checked-search-only");
|
||||
let folder = root.join("inside");
|
||||
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o300)).unwrap();
|
||||
let r = write_atomic_checked(&folder.join("doc.txt"), |f| f.write_all(b"new"), under(&root));
|
||||
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
// The folder flush needs it opened for reading: the file is written, and the error says so.
|
||||
assert!(r.as_ref().map_or_else(|e| e.get_ref().is_some_and(|e| e.is::<WrittenError>()), |()| true), "{r:?}");
|
||||
assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// The other files in `d` besides `keep`.
|
||||
fn leftovers(d: &Path, keep: &str) -> Vec<String> {
|
||||
std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect()
|
||||
@@ -722,6 +1347,33 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A refused rename where a file is already at the name the old content would be copied to:
|
||||
/// that file is left as it is, and the temporary file with the new content stays.
|
||||
#[test]
|
||||
fn a_refused_rename_leaves_a_file_already_at_the_backup_name() {
|
||||
let d = dir("no-rename-backup-taken");
|
||||
let path = d.join("doc.vectorcraft");
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
let r = write_atomic_stepping(
|
||||
&path,
|
||||
|f| f.write_all(b"new"),
|
||||
create_new,
|
||||
|tmp, _| {
|
||||
std::fs::write(tmp.with_extension("old"), b"an earlier copy")?;
|
||||
denied()
|
||||
},
|
||||
);
|
||||
let message = r.unwrap_err().to_string();
|
||||
let mut left = leftovers(&d, "doc.vectorcraft");
|
||||
left.sort();
|
||||
let [old, tmp] = left.as_slice() else { panic!("the earlier copy and the new content: {left:?}") };
|
||||
assert!(message.contains(tmp.as_str()), "{message}");
|
||||
assert_eq!(std::fs::read(d.join(old)).unwrap(), b"an earlier copy");
|
||||
assert_eq!(std::fs::read(d.join(tmp)).unwrap(), b"new");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A refused rename where the old content can't be copied aside (here: no flush works): the
|
||||
/// file is left as it was, the temporary file with the whole new content stays and the error
|
||||
/// names it.
|
||||
|
||||
@@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob};
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
pub use atomic::sync_parent;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_checked, write_atomic_with, write_new_with};
|
||||
use craft_gzip::Gz;
|
||||
pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode};
|
||||
use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json};
|
||||
|
||||
+120
-15
@@ -421,15 +421,127 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given.
|
||||
/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. Every
|
||||
/// class's name, parent and members are checked before any class is added, and a failure part way
|
||||
/// through removes the classes and globals this call added, so a failed call leaves the realm as it
|
||||
/// was.
|
||||
pub(crate) fn install(i: &mut Interp, classes: Vec<HostClass>, instances: Vec<(String, Data)>) -> JsResult<()> {
|
||||
let members = match checked_members(&i.host_classes, &classes) {
|
||||
Ok(m) => m,
|
||||
Err(message) => return Err(i.throw(ErrorType::Type, &message)),
|
||||
};
|
||||
let mark = i.temp_roots.len();
|
||||
let mut undo = Undo { classes: i.host_classes.len(), globals: Vec::new(), objects: Vec::new() };
|
||||
let r = install_checked(i, classes, members, instances, &mut undo);
|
||||
if r.is_err() {
|
||||
undo.roll_back(i);
|
||||
}
|
||||
i.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// What [`install`] puts back when it fails part way.
|
||||
struct Undo {
|
||||
/// How many classes the realm had before the call.
|
||||
classes: usize,
|
||||
/// Each global the call defined, with the property it replaced, in the order defined. The
|
||||
/// replaced values stay in the interpreter's temporary roots until [`install`] returns, so a
|
||||
/// collection during the call does not free them.
|
||||
globals: Vec<(Key, Option<Prop>)>,
|
||||
/// The class and prototype of the object made for each family and handle before the call. An
|
||||
/// instance of the call can give such an object one of the call's classes.
|
||||
objects: Vec<(MadeKey, u32, Option<ObjId>)>,
|
||||
}
|
||||
|
||||
impl Undo {
|
||||
fn define_global(&mut self, i: &mut Interp, name: &str, prop: Prop) -> JsResult<()> {
|
||||
let global = i.global;
|
||||
let k = key(name);
|
||||
let was = i.object(global)?.props.get(&k).cloned();
|
||||
match &was {
|
||||
Some(Prop::Data { value, .. }) => i.temp_roots.push(value.clone()),
|
||||
Some(Prop::Accessor { get, set, .. }) => i.temp_roots.extend(get.iter().chain(set).map(|&f| Value::Object(f))),
|
||||
None => {}
|
||||
}
|
||||
i.define(global, k.clone(), prop)?;
|
||||
self.globals.push((k, was));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn roll_back(self, i: &mut Interp) {
|
||||
let global = i.global;
|
||||
for (k, was) in self.globals.into_iter().rev() {
|
||||
let Ok(o) = i.object_mut(global) else { break };
|
||||
match was {
|
||||
Some(prop) => {
|
||||
o.props.insert(k, prop);
|
||||
}
|
||||
None => {
|
||||
o.props.remove(&k);
|
||||
i.heap.bytes = i.heap.bytes.saturating_sub(crate::interp::binding_bytes(k.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (made, class, proto) in self.objects {
|
||||
let Some(&id) = i.host_objects.get(&made) else { continue };
|
||||
if is_made(&i.heap, &i.host_classes, id, &made)
|
||||
&& let Ok(o) = i.object_mut(id)
|
||||
&& let Class::Host(h) = &mut o.class
|
||||
{
|
||||
h.class = class;
|
||||
o.proto = proto;
|
||||
}
|
||||
}
|
||||
i.host_classes.truncate(self.classes);
|
||||
forget_collected(&mut i.host_objects, &i.heap, &i.host_classes);
|
||||
}
|
||||
}
|
||||
|
||||
/// The members of each of `classes` as `reflect` lists them ([`reflected_members`]), once every
|
||||
/// class has a name that neither `existing` nor an earlier class of `classes` has, and a parent
|
||||
/// that one of them has. → the error's message for the first class that does not.
|
||||
fn checked_members(existing: &[Entry], classes: &[HostClass]) -> Result<Vec<Rc<[Reflected]>>, String> {
|
||||
let mut names: HashSet<&str> = existing.iter().map(|e| &*e.name).collect();
|
||||
let mut out = Vec::with_capacity(classes.len());
|
||||
for class in classes {
|
||||
install_class(i, class)?;
|
||||
if names.contains(class.name.as_str()) {
|
||||
return Err(format!("the host class {} is defined twice", class.name));
|
||||
}
|
||||
if let Some(p) = &class.parent
|
||||
&& !names.contains(p.as_str())
|
||||
{
|
||||
return Err(format!("the host class {p} is not defined"));
|
||||
}
|
||||
out.push(reflected_members(class)?);
|
||||
names.insert(&class.name);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [`install`] once [`checked_members`] has passed, recording in `undo` what it changes.
|
||||
fn install_checked(
|
||||
i: &mut Interp,
|
||||
classes: Vec<HostClass>,
|
||||
members: Vec<Rc<[Reflected]>>,
|
||||
instances: Vec<(String, Data)>,
|
||||
undo: &mut Undo,
|
||||
) -> JsResult<()> {
|
||||
for (class, members) in classes.into_iter().zip(members) {
|
||||
install_class(i, class, members, undo)?;
|
||||
}
|
||||
if !instances.is_empty() {
|
||||
for (made, &id) in &i.host_objects {
|
||||
if is_made(&i.heap, &i.host_classes, id, made)
|
||||
&& let Ok(o) = i.object(id)
|
||||
&& let Class::Host(h) = &o.class
|
||||
{
|
||||
undo.objects.push((made.clone(), h.class, o.proto));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, d) in instances {
|
||||
let v = i.write_hosted(d)?;
|
||||
let global = i.global;
|
||||
i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?;
|
||||
undo.define_global(i, &name, Prop::Data { value: v, flags: 0 })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -450,22 +562,16 @@ pub(crate) fn install_globals(i: &mut Interp, globals: Vec<(String, HostFunction
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
if i.host_classes.iter().any(|e| *e.name == *class.name) {
|
||||
return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name)));
|
||||
}
|
||||
/// Adds `class`, which [`checked_members`] passed with `members`.
|
||||
fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, undo: &mut Undo) -> JsResult<()> {
|
||||
let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX);
|
||||
let (parent, family, parent_class) = match &class.parent {
|
||||
None => (i.intrinsics.object_proto, own, None),
|
||||
Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) {
|
||||
Some((n, e)) => (e.proto, e.family, u32::try_from(n).ok()),
|
||||
None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))),
|
||||
None => return Err(Abrupt::Internal(format!("the host class {p} was checked but is not defined"))),
|
||||
},
|
||||
};
|
||||
let members = match reflected_members(&class) {
|
||||
Ok(m) => m,
|
||||
Err(message) => return Err(i.throw(ErrorType::Type, &message)),
|
||||
};
|
||||
let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent)));
|
||||
let mark = i.temp_roots.len();
|
||||
i.temp_roots.push(Value::Object(proto));
|
||||
@@ -486,8 +592,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
unavailable: Rc::new(names(unavailable)),
|
||||
members,
|
||||
});
|
||||
let global = i.global;
|
||||
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
undo.define_global(i, &class.name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
}
|
||||
|
||||
/// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the
|
||||
|
||||
@@ -1035,6 +1035,72 @@ fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it()
|
||||
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into()));
|
||||
}
|
||||
|
||||
/// A class named `name` with the parent `parent` and one read-only member `size`.
|
||||
fn sized_class(name: &str, parent: Option<&str>) -> HostClass {
|
||||
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
|
||||
HostClass {
|
||||
name: name.into(),
|
||||
parent: parent.map(Into::into),
|
||||
members: vec![("size".to_string(), HostMember::Get(value))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_class_leaves_the_earlier_classes_of_its_call_undefined() {
|
||||
let doubled = || {
|
||||
let mut c = sized_class("Bad", None);
|
||||
c.members.push(c.members[0].clone());
|
||||
c
|
||||
};
|
||||
for (bad, message) in [(sized_class("Bad", Some("Missing")), "Missing is not defined"), (doubled(), "names the member size twice")] {
|
||||
let mut r = realm(1_000_000);
|
||||
let e = r.define_host_classes(vec![sized_class("First", None), bad], vec![("first".into(), host_ref("First", &[1.0]))]).unwrap_err();
|
||||
assert!(e.message.contains(message), "{}", e.message);
|
||||
assert_eq!(r.run("[typeof First, typeof first, typeof Bad].join()").unwrap(), JsValue::String("undefined,undefined,undefined".into()));
|
||||
r.define_host_classes(vec![sized_class("First", None)], vec![("first".into(), host_ref("First", &[1.0]))]).unwrap();
|
||||
assert_eq!(r.run("first.size").unwrap(), JsValue::Number(1.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_class_may_follow_its_parent_in_the_same_call_but_not_precede_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
let e = r.define_host_classes(vec![sized_class("Leaf", Some("Base")), sized_class("Base", None)], Vec::new()).unwrap_err();
|
||||
assert!(e.message.contains("Base is not defined"), "{}", e.message);
|
||||
assert_eq!(r.run("typeof Leaf + typeof Base").unwrap(), JsValue::String("undefinedundefined".into()));
|
||||
r.define_host_classes(vec![sized_class("Base", None), sized_class("Leaf", Some("Base"))], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap();
|
||||
assert_eq!(r.run("it instanceof Base && it.size === 1").unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_instance_removes_the_classes_and_globals_of_its_call_and_restores_held_objects() {
|
||||
let mut r = realm(1_000_000);
|
||||
r.define_host_classes(vec![sized_class("Base", None)], vec![("held".into(), host_ref("Base", &[1.0]))]).unwrap();
|
||||
r.run("var keep = 'kept'").unwrap();
|
||||
let instances = vec![("keep".into(), host_ref("Leaf", &[1.0])), ("other".into(), host_ref("Missing", &[2.0]))];
|
||||
let e = r.define_host_classes(vec![sized_class("Leaf", Some("Base"))], instances).unwrap_err();
|
||||
assert!(e.message.contains("unknown class Missing"), "{}", e.message);
|
||||
let source = "[keep, typeof Leaf, typeof other, held.constructor === Base, held.hasOwnProperty('size'), held.size].join()";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("kept,undefined,undefined,true,true,1".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_call_restores_a_replaced_global_that_a_collection_in_the_call_would_free() {
|
||||
let mut r = realm(1_000_000);
|
||||
r.define_host_classes(vec![sized_class("Base", None)], Vec::new()).unwrap();
|
||||
r.run("var keep = { sentinel: 1 }").unwrap();
|
||||
let instances =
|
||||
vec![("keep".into(), host_ref("Base", &[1.0])), ("next".into(), host_ref("Base", &[2.0])), ("other".into(), host_ref("Missing", &[3.0]))];
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
|
||||
let e = r.define_host_classes(Vec::new(), instances);
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
|
||||
assert!(e.unwrap_err().message.contains("unknown class Missing"));
|
||||
assert_eq!(r.run("[keep.sentinel, typeof next].join()").unwrap(), JsValue::String("1,undefined".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
@@ -753,6 +753,7 @@ impl Realm {
|
||||
/// prototype holds its members, and the global objects `instances`, each made from the
|
||||
/// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be
|
||||
/// replaced. A heap too small for them ends with the error the realm's next run would give.
|
||||
/// A call that fails adds none of its classes or instances, and can be made again.
|
||||
pub fn define_host_classes(&mut self, classes: Vec<crate::HostClass>, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> {
|
||||
match crate::host_classes::install(&mut self.interp, classes, instances) {
|
||||
Ok(()) => Ok(()),
|
||||
|
||||
@@ -1543,7 +1543,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
|
||||
@@ -113,4 +113,9 @@ toml = "1"
|
||||
|
||||
# The files of other crates that this crate's tests read, for CI's test selection.
|
||||
[package.metadata.craft]
|
||||
reads = ["crates/engine/src/cmd/addons/cutting/banner.rs", "crates/plugins/tests/fixtures/desaturate.wasm"]
|
||||
reads = [
|
||||
"crates/engine/src/cmd/addons/cutting/banner.rs",
|
||||
"crates/plugins/tests/fixtures/desaturate.wasm",
|
||||
"packaging/macos/nightly-lib.sh",
|
||||
"packaging/macos/nightly_plist.py",
|
||||
]
|
||||
@@ -162,6 +162,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
|
||||
pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open,
|
||||
typetools::COMMAND => typetools::open,
|
||||
typetools::font_sheet::COMMAND => typetools::font_sheet::open,
|
||||
typetools::numbers::COMMAND => typetools::numbers::open,
|
||||
color::legend::COMMAND => color::legend::open,
|
||||
color::nearest::COMMAND => color::nearest::open,
|
||||
color::random_fill::COMMAND => color::random_fill::open,
|
||||
|
||||
@@ -14,6 +14,8 @@ use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::{self, Spec};
|
||||
use crate::menus::{c, cp};
|
||||
|
||||
pub mod numbers;
|
||||
|
||||
/// The command the dialog runs.
|
||||
pub const COMMAND: &str = "addon.type.textTweaker";
|
||||
/// An attribute: (param, label, unit, decimals, values taken, default start and end), as the
|
||||
@@ -46,6 +48,7 @@ pub fn menu() -> Vec<Node> {
|
||||
c("Text Tweaker…", COMMAND),
|
||||
cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})),
|
||||
c("Create Font Sheet…", font_sheet::COMMAND),
|
||||
c("Make Numbers Sequence…", numbers::COMMAND),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Make Numbers Sequence's dialog: the start, end and step, zeros, the order the type objects are
|
||||
//! numbered in and what each number replaces. It previews on the canvas and runs
|
||||
//! `addon.type.numbers` on OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::{self, Spec};
|
||||
|
||||
/// The command the dialog runs.
|
||||
pub const COMMAND: &str = "addon.type.numbers";
|
||||
const ORDERS: [(&str, &str); 3] = [("stacking", "By Stacking Order"), ("rows", "By Rows"), ("columns", "By Columns")];
|
||||
const REPLACES: [(&str, &str); 3] = [("all", "Whole Text"), ("numbers", "Numbers in Text"), ("placeholder", "Only {%n} Placeholder")];
|
||||
/// The seeds the dialog offers.
|
||||
const SEEDS: u64 = 1_000_000;
|
||||
/// The largest start, end or step, as the command takes it.
|
||||
const MAX_VALUE: f64 = 1e12;
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The command's parameters from the dialog's fields.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
let to_last = fields.bool("toLast").unwrap_or(true);
|
||||
let mut p = json!({
|
||||
"start": fields.number("start").unwrap_or(1.0),
|
||||
"step": fields.number("step").unwrap_or(1.0),
|
||||
"order": fields.text("order").unwrap_or("stacking"),
|
||||
"replace": fields.text("replace").unwrap_or("all"),
|
||||
"shuffle": fields.bool("shuffle").unwrap_or(false),
|
||||
"seed": fields.int("seed").unwrap_or(0),
|
||||
"leadingZeros": fields.bool("leadingZeros").unwrap_or(true),
|
||||
"trailingZeros": fields.bool("trailingZeros").unwrap_or(false),
|
||||
});
|
||||
if !to_last {
|
||||
p["end"] = json!(fields.number("end").unwrap_or(10.0));
|
||||
p["removeUnused"] = json!(fields.bool("removeUnused").unwrap_or(false));
|
||||
}
|
||||
if fields.bool("leadingZeros").unwrap_or(true) && fields.bool("fixedDigits").unwrap_or(false) {
|
||||
p["digits"] = json!(fields.int("digits").unwrap_or(3));
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// The radio choice over `list`'s `(id, label)` pairs, on its first.
|
||||
fn radio(list: &[(&str, &'static str)]) -> ParamKind {
|
||||
ParamKind::radio(list.iter().map(|&(id, label)| (id.to_string(), tl!(label).into())).collect(), list.first().map(|(id, _)| id.to_string()))
|
||||
}
|
||||
|
||||
/// Opens the dialog numbering from 1 by 1 to the last type object, in stacking order, replacing the
|
||||
/// whole text, with a new seed each time the document has changed.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let seed = app.session.active().map_or(0, |st| st.revision % SEEDS);
|
||||
let fields = DialogFields::from_pairs([
|
||||
("start", FieldValue::Number(1.0)),
|
||||
("step", FieldValue::Number(1.0)),
|
||||
("toLast", FieldValue::Bool(true)),
|
||||
("end", FieldValue::Number(10.0)),
|
||||
("removeUnused", FieldValue::Bool(false)),
|
||||
("shuffle", FieldValue::Bool(false)),
|
||||
("seed", FieldValue::Int(i64::try_from(seed).unwrap_or(0))),
|
||||
("leadingZeros", FieldValue::Bool(true)),
|
||||
("fixedDigits", FieldValue::Bool(false)),
|
||||
("digits", FieldValue::Int(3)),
|
||||
("trailingZeros", FieldValue::Bool(false)),
|
||||
("order", FieldValue::Text("stacking".into())),
|
||||
("replace", FieldValue::Text("all".into())),
|
||||
]);
|
||||
dialogs::open(app, &SPEC, fields, |fields| {
|
||||
let value = |key: &'static str, label, start| Param::number(key, label, start, 1.0, 6).bounds(Some(-MAX_VALUE), Some(MAX_VALUE));
|
||||
let last = FieldValue::Bool(false);
|
||||
let rows = vec![
|
||||
Param::section(tl!("Numbers")),
|
||||
value("start", tl!("Start:"), 1.0),
|
||||
value("step", tl!("Step:"), 1.0),
|
||||
Param::new("toLast", tl!("Number to Last Text"), ParamKind::bool(true)),
|
||||
value("end", tl!("End:"), 10.0).enabled_when("toLast", last.clone()),
|
||||
Param::new("removeUnused", tl!("Remove Unused Texts"), ParamKind::bool(false)).enabled_when("toLast", last),
|
||||
Param::new("shuffle", tl!("Shuffle Numbers"), ParamKind::bool(false)),
|
||||
Param::new("seed", tl!("Seed:"), ParamKind::int(Some(0), Some(i64::try_from(SEEDS - 1).unwrap_or(i64::MAX)), 0))
|
||||
.enabled_when("shuffle", FieldValue::Bool(true)),
|
||||
Param::section(tl!("Zeros")),
|
||||
Param::new("leadingZeros", tl!("Leading Zeros"), ParamKind::bool(true)),
|
||||
Param::new("fixedDigits", tl!("Fixed Number of Digits"), ParamKind::bool(false)).enabled_when("leadingZeros", FieldValue::Bool(true)),
|
||||
Param::new("digits", tl!("Digits:"), ParamKind::int(Some(1), Some(30), 3)).enabled_when("fixedDigits", FieldValue::Bool(true)),
|
||||
Param::new("trailingZeros", tl!("Trailing Zeros"), ParamKind::bool(false)),
|
||||
Param::new("order", tl!("Order:"), radio(&ORDERS)).enabled_when("shuffle", FieldValue::Bool(false)),
|
||||
Param::new("replace", tl!("Replace:"), radio(&REPLACES)),
|
||||
];
|
||||
ParamDialog::new(COMMAND, tl!("Make Numbers Sequence"), rows).values(Bind::bound(fields)).previews(true)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,58 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::tests::{confirm, dialog_id, frame, open_item, read, set};
|
||||
|
||||
/// A window's app with three type objects in a column, selected.
|
||||
fn app() -> (VectorcraftApp, Vec<u64>) {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let ids: Vec<u64> = (0..3)
|
||||
.map(|i| app.run("text.create", json!({"x": 40, "y": 60 + 40 * i, "text": "Seat 0", "size": 20})).unwrap()["id"].as_u64().unwrap())
|
||||
.collect();
|
||||
app.run("select.set", json!({"ids": ids})).unwrap();
|
||||
(app, ids)
|
||||
}
|
||||
|
||||
fn texts(app: &VectorcraftApp, ids: &[u64]) -> Vec<String> {
|
||||
let state = app.session.active().unwrap();
|
||||
ids.iter()
|
||||
.map(|id| match &state.doc.node(vectorcraft_doc::NodeId(*id)).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The dialog's fields reach the command: an end and fixed digits only when turned on, and OK
|
||||
/// numbers the objects as one undo step.
|
||||
#[test]
|
||||
fn the_dialog_numbers_the_selection_on_ok() {
|
||||
let (mut app, ids) = app();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
open_item(&mut app, "Type Tools", "Make Numbers Sequence…");
|
||||
let dialog = dialog_id(&app);
|
||||
let p = read(&app, dialog, super::params);
|
||||
assert!(p.get("end").is_none() && p.get("digits").is_none(), "to the last text, auto digits: {p}");
|
||||
for (key, value) in [("start", json!(5.0)), ("replace", json!("numbers")), ("fixedDigits", json!(true)), ("digits", json!(2))] {
|
||||
set(&app, dialog, key, value);
|
||||
}
|
||||
set(&app, dialog, "toLast", json!(false));
|
||||
set(&app, dialog, "end", json!(6.0));
|
||||
frame(&mut app);
|
||||
let p = read(&app, dialog, super::params);
|
||||
assert_eq!(
|
||||
(p["start"].clone(), p["end"].clone(), p["digits"].clone(), p["replace"].clone()),
|
||||
(json!(5.0), json!(6.0), json!(2), json!("numbers"))
|
||||
);
|
||||
let mut expected = self::app();
|
||||
expected.0.run(super::COMMAND, p).unwrap();
|
||||
let want = texts(&expected.0, &expected.1);
|
||||
assert_eq!(want, ["Seat 05", "Seat 06", "Seat 0"]);
|
||||
assert!(confirm(&app, dialog));
|
||||
frame(&mut app);
|
||||
assert!(!app.any_dialog_open());
|
||||
assert_eq!(texts(&app, &ids), want);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
|
||||
}
|
||||
@@ -1544,7 +1544,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
|
||||
@@ -119,9 +119,50 @@ mod tests {
|
||||
#[test]
|
||||
fn the_two_nightly_ids_are_the_contract_ones() {
|
||||
// The package and bundle identity ends in `.nightly`; the window and AUMID in `.nightly-v1`.
|
||||
assert_eq!(NIGHTLY_PACKAGE_ID, "ai.storyteller.vectorcraft.nightly");
|
||||
assert_eq!(NIGHTLY_APP_ID, "ai.storyteller.vectorcraft.nightly-v1");
|
||||
assert_ne!(NIGHTLY_PACKAGE_ID, NIGHTLY_APP_ID);
|
||||
assert_eq!(id_for(LaunchIdentity::NightlyV1), NIGHTLY_APP_ID);
|
||||
assert!(NIGHTLY_PACKAGE_ID.ends_with(".nightly"), "{NIGHTLY_PACKAGE_ID}");
|
||||
assert_eq!(NIGHTLY_APP_ID.strip_suffix("-v1"), Some(NIGHTLY_PACKAGE_ID), "the window id is the package id plus -v1");
|
||||
// The packaging publishes the same package id.
|
||||
let plist = include_str!("../../../packaging/macos/nightly_plist.py");
|
||||
assert_eq!(assigned(plist, "IDENTIFIER", false), Some(NIGHTLY_PACKAGE_ID), "nightly_plist.py");
|
||||
let lib = include_str!("../../../packaging/macos/nightly-lib.sh");
|
||||
assert_eq!(assigned(lib, "MAC_NIGHTLY_ID", true), Some(NIGHTLY_PACKAGE_ID), "nightly-lib.sh");
|
||||
}
|
||||
|
||||
/// The value of the last uncommented top-level `name = value` or `name=value` line, with one pair of
|
||||
/// single or double quotes removed and a trailing `#` comment after the value ignored. With `shell`, a `#`
|
||||
/// after a closing quote starts a comment only when whitespace comes before it; Python needs no whitespace.
|
||||
fn assigned<'a>(source: &'a str, name: &str, shell: bool) -> Option<&'a str> {
|
||||
source
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let rest = line.strip_prefix(name)?.trim_start().strip_prefix('=')?.trim();
|
||||
let quoted = ['\'', '"'].iter().find_map(|q| {
|
||||
let inner = rest.strip_prefix(*q)?;
|
||||
let end = inner.find(*q)?;
|
||||
let after = &inner[end + 1..];
|
||||
let comment = (!shell || after.starts_with(char::is_whitespace)) && after.trim_start().starts_with('#');
|
||||
(after.trim().is_empty() || comment).then(|| &inner[..end])
|
||||
});
|
||||
let bare = rest.split_once(" #").map_or(rest, |(value, _)| value.trim_end());
|
||||
Some(quoted.unwrap_or(bare))
|
||||
})
|
||||
.next_back()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigned_reads_the_active_line_in_either_quote_style() {
|
||||
for shell in [false, true] {
|
||||
assert_eq!(assigned("# ID='old'\nID=\"new\"\n", "ID", shell), Some("new"));
|
||||
assert_eq!(assigned("ID = 'a'\n", "ID", shell), Some("a"));
|
||||
assert_eq!(assigned("IDX='a'\n", "ID", shell), None);
|
||||
assert_eq!(assigned("ID = 'a' # bundle ID\n", "ID", shell), Some("a"));
|
||||
assert_eq!(assigned("ID=\"a\" # bundle ID\n", "ID", shell), Some("a"));
|
||||
assert_eq!(assigned("ID=a # bundle ID\n", "ID", shell), Some("a"));
|
||||
}
|
||||
// In Python a `#` right after the closing quote starts a comment; in a shell it is part of the word.
|
||||
assert_eq!(assigned("ID='a'#b\n", "ID", false), Some("a"));
|
||||
assert_eq!(assigned("ID='a'#b\n", "ID", true), Some("'a'#b"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1111,6 +1111,65 @@ fn a_docked_column_is_never_narrower_than_the_panel_minimum() {
|
||||
assert!(body_width(&h, "Properties") >= PANEL_MIN_WIDTH - 0.5, "saved 100 pt wide: {}", body_width(&h, "Properties"));
|
||||
}
|
||||
|
||||
/// The opaque rects the last frame painted inside `cell`.
|
||||
fn opaque_rects_in(shapes: &[egui::epaint::ClippedShape], cell: Rect) -> Vec<egui::epaint::RectShape> {
|
||||
crate::tests_labels::painted_shapes(shapes)
|
||||
.into_iter()
|
||||
.filter_map(|(shape, transform, _)| match shape {
|
||||
egui::Shape::Rect(r) if r.fill.a() == 255 => {
|
||||
let mut r = r.clone();
|
||||
r.rect = transform * r.rect;
|
||||
cell.expand(0.75).contains_rect(r.rect).then_some(r)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The docked Tools card, in each color scheme and at UI Scaling 100% and 200%: its bar and its body keep to the
|
||||
/// card's rounded top corners. Every opaque surface that reaches a top corner of the card is rounded there at least as
|
||||
/// much as the card's foot is, so no square corner shows past the bar's rounded one.
|
||||
#[test]
|
||||
fn the_docked_tools_card_keeps_its_rounded_top_corners() {
|
||||
let near = |a: f32, b: f32| (a - b).abs() <= 0.75;
|
||||
for scheme in ["classic", "modern"] {
|
||||
for scaling in [1.0, 2.0] {
|
||||
let case = format!("{scheme} at {scaling}");
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.prefs.ui_color_scheme = scheme.into();
|
||||
app.session.prefs.ui_scaling = scaling;
|
||||
Arc::make_mut(&mut app.ui.dock_workspace).replace(builtin_workspace(&[], 2));
|
||||
let ctx = crate::testing::ui_context();
|
||||
let mut shapes = Vec::new();
|
||||
for frame in 0..4 {
|
||||
let input = egui::RawInput { time: Some(f64::from(frame) * 0.05), screen_rect: Some(SCREEN), ..Default::default() };
|
||||
shapes = crate::testing::app_frame(&mut app, &ctx, input).shapes;
|
||||
}
|
||||
let cell = app.dock_rt.columns.iter().find(|(panel, _)| panel == crate::toolbar::TOOLS).map(|(_, rect)| *rect);
|
||||
let cell = cell.unwrap_or_else(|| panic!("{case}: the Tools column is docked"));
|
||||
let rects = opaque_rects_in(&shapes, cell);
|
||||
// The card's foot: the largest surface in the column with rounded lower corners.
|
||||
let foot = rects
|
||||
.iter()
|
||||
.filter(|r| r.corner_radius.sw > 0 && r.corner_radius.se > 0)
|
||||
.max_by(|a, b| a.rect.area().total_cmp(&b.rect.area()))
|
||||
.unwrap_or_else(|| panic!("{case}: the Tools card is painted: {rects:?}"));
|
||||
let spans = |r: &&egui::epaint::RectShape| near(r.rect.left(), foot.rect.left()) && near(r.rect.right(), foot.rect.right());
|
||||
let top = rects.iter().filter(spans).map(|r| r.rect.top()).fold(foot.rect.top(), f32::min);
|
||||
let at_top: Vec<_> = rects.iter().filter(|r| near(r.rect.top(), top)).collect();
|
||||
let left: Vec<_> = at_top.iter().filter(|r| near(r.rect.left(), foot.rect.left())).collect();
|
||||
let right: Vec<_> = at_top.iter().filter(|r| near(r.rect.right(), foot.rect.right())).collect();
|
||||
assert!(!left.is_empty() && !right.is_empty(), "{case}: the card's top is painted: {at_top:?}");
|
||||
for r in left {
|
||||
assert!(r.corner_radius.nw >= foot.corner_radius.sw, "{case}: a square corner shows at the card's top left: {r:?}");
|
||||
}
|
||||
for r in right {
|
||||
assert!(r.corner_radius.ne >= foot.corner_radius.se, "{case}: a square corner shows at the card's top right: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
/// The node with key focus in the last frame.
|
||||
fn focused_node(&self) -> Option<&egui::accesskit::Node> {
|
||||
|
||||
@@ -522,13 +522,14 @@ fn persistent_panels_reopen_at_startup_with_their_settings() {
|
||||
assert_eq!((r["persistent"].as_bool(), r["view"].as_str(), r["showFind"].as_bool()), (Some(true), Some("largeList"), Some(false)));
|
||||
app.run("ui.libraryPanel", json!({"panel": brand, "persistent": true})).unwrap();
|
||||
app.run("window.panel.float", json!({"panel": pastels, "x": 40, "y": 90})).unwrap();
|
||||
let saved = docking(&app).floating.iter().find(|g| g.contains(&pastels)).unwrap().rect;
|
||||
// A persistent panel reopens even when it was closed.
|
||||
app.run("window.panel.close", json!({"panel": brand})).unwrap();
|
||||
let next = restarted(&app);
|
||||
assert!(is_open(&next.ui, &pastels) && is_open(&next.ui, &brand), "{}", next.ui.status);
|
||||
assert!(!is_open(&next.ui, &brights), "a panel that isn't persistent closed with the app");
|
||||
let group = docking(&next).floating.iter().find(|g| g.contains(&pastels)).unwrap();
|
||||
assert_eq!(group.rect.min, Pos2::new(40.0, 90.0), "where it was");
|
||||
assert_eq!(group.rect.min, saved.min, "where it was");
|
||||
let s = settings(&next.ui, "swatches", "pastels").unwrap();
|
||||
assert_eq!((s.view, s.hide_find, s.persistent), (Some(View::LargeList), true, true));
|
||||
let (_, id) = parse(&brand).unwrap();
|
||||
@@ -747,11 +748,12 @@ fn previous_and_next_show_the_neighbouring_library_in_the_same_panel() {
|
||||
let first = panel_of(app.run("window.swatchLibrary", json!({"library": "pastels"})).unwrap());
|
||||
app.run("window.panel.float", json!({"panel": first, "x": 50, "y": 60})).unwrap();
|
||||
app.run("ui.libraryPanel", json!({"panel": first, "persistent": true, "view": "smallList"})).unwrap();
|
||||
let saved = docking(&app).floating.iter().find(|g| g.contains(&first)).unwrap().rect;
|
||||
step::<SwatchLibraries>(&mut app, "pastels", 1);
|
||||
let next = panel_id("swatches", SWATCH_IDS[5]);
|
||||
assert!(!is_open(&app.ui, &first) && is_open(&app.ui, &next), "{}", app.ui.status);
|
||||
let group = docking(&app).floating.iter().find(|g| g.contains(&next)).unwrap();
|
||||
assert_eq!((group.panels().count(), group.rect.min), (1, Pos2::new(50.0, 60.0)), "in its place");
|
||||
assert_eq!((group.panels().count(), group.rect.min), (1, saved.min), "in its place");
|
||||
let s = settings(&app.ui, "swatches", SWATCH_IDS[5]).unwrap();
|
||||
assert_eq!((s.view, s.persistent), (Some(View::SmallList), true), "the panel keeps its settings");
|
||||
assert!(settings(&app.ui, "swatches", "pastels").is_none());
|
||||
|
||||
@@ -1088,6 +1088,9 @@ fn above_text_puts_the_panel_at_the_top_when_below_the_text_does_not_fit() {
|
||||
}
|
||||
let (node, _, span) = current(&app).unwrap();
|
||||
above_text(&mut app, &node, span).unwrap();
|
||||
assert_eq!(tabs_rect(&app).min.y, 0.0, "view centered at y {center_y}");
|
||||
// Neither above the text (off the window) nor below it (inside the canvas): at the window's top.
|
||||
let (top, canvas) = (tabs_rect(&app).min.y, app.canvas_view().unwrap().rect);
|
||||
assert!(canvas.top() > 0.0, "canvas {canvas:?}");
|
||||
assert_eq!(top, 0.0, "view centered at y {center_y}: panel top {top}, canvas {canvas:?}");
|
||||
}
|
||||
}
|
||||
+45
-2
@@ -18288,8 +18288,8 @@ enabled only when a selected image has a mask. → `{changed, ids}`
|
||||
|
||||
## Type Tools add-on
|
||||
|
||||
Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker`, `addon.type.releasePath` and
|
||||
`addon.type.fontSheet`, and in the desktop app it lives in Object › Plug-ins › Type Tools (#4924, #5532). Text Tweaker gives one character attribute to the characters letter by letter,
|
||||
Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker`, `addon.type.releasePath`,
|
||||
`addon.type.fontSheet` and `addon.type.numbers`, and in the desktop app it lives in Object › Plug-ins › Type Tools (#4924, #5532). Text Tweaker gives one character attribute to the characters letter by letter,
|
||||
from a start value to an end value along a shape, as one undo step; the text stays live and editable. Each value is set
|
||||
as `text.setRangeStyle` sets it (the Character panel), in its units and ranges ([formatting type](https://helpx.adobe.com/illustrator/using/formatting-type.html)), so on scaled
|
||||
type it is the size shown.
|
||||
@@ -18414,6 +18414,49 @@ off: switched on, it sets the whole sheet again after each change. OK is off whi
|
||||
{"name":"run_command","arguments":{"command":"addon.type.fontSheet","params":{"families":["Inter","JetBrains Mono"],"allStyles":true,"columns":1}}}
|
||||
```
|
||||
|
||||
### Make Numbers Sequence
|
||||
|
||||
`addon.type.numbers` numbers the type objects among `ids` (or `id`, else the selection), groups included, from `start`
|
||||
by `step`, as one undo step. Each number replaces the object's whole text, every number in it, or every `{%n}`
|
||||
placeholder in it. It is based on Sergey Osokin's MIT-licensed
|
||||
[MakeNumbersSequence](https://github.com/creold/illustrator-scripts/blob/master/md/Text.md#makenumberssequence)
|
||||
script.
|
||||
|
||||
- With `end` omitted the numbers run to the last object. With `end`, they stop past it and the objects after the last
|
||||
number keep their text, or are deleted with `removeUnused`. A type object that is the mask of a clipping group or layer
|
||||
is not deleted. The sign of `step` is set to run toward `end`.
|
||||
- Locked or hidden type, also inside a selected group, is not numbered or deleted.
|
||||
- With `replace` `numbers` or `placeholder`, objects that hold no number or placeholder are skipped and get no number,
|
||||
and `order` leaves them out. The remaining objects are ordered before `end` limits the sequence, so objects past
|
||||
`end` still count for rows and columns. A number is a run of digits with any `.` or `,` between digits,
|
||||
and a `-` before it that does not follow a letter or digit. Replaced text takes the style of the text it replaces;
|
||||
a number or placeholder that already reads the new number keeps its text and style. With `numbers` or
|
||||
`placeholder`, one run replaces at most 10,000 numbers or placeholders; more is an error, and nothing changes.
|
||||
- Values are rounded to the most decimal places among `start`, `step` and `end` (at most 6), so 0.1 by 0.1 gives
|
||||
0.1, 0.2, 0.3.
|
||||
- Objects that already read so are left as they are; when nothing changes no undo step is made.
|
||||
- A frame of threaded type among the objects is an error, and nothing changes.
|
||||
|
||||
| Parameter | Values (default) |
|
||||
|---|---|
|
||||
| `start`, `step` | numbers −1e12…1e12 (1, 1; `step` 0: every object gets `start`) |
|
||||
| `end` | number −1e12…1e12 (omitted: to the last object) |
|
||||
| `order` | `stacking` (from the back), `rows` (top to bottom, each row left to right), `columns` (left to right, each column top to bottom) (`stacking`). Objects whose centers are within half the median height (width for columns) of a row's first object share its row |
|
||||
| `replace` | `all`, `numbers`, `placeholder` (`all`) |
|
||||
| `shuffle`, `seed` | false; true: the numbers go to the objects in random order, the same `seed` (a whole number, 0) giving the same order, and `order` is not used. A `seed` that is not a whole number is an error even with `shuffle` off |
|
||||
| `leadingZeros` | true: non-negative numbers are padded with zeros to the whole digits of the wider of `start` and `end` (or the last number) |
|
||||
| `digits` | 1…30: with `leadingZeros`, at least this many whole digits |
|
||||
| `trailingZeros` | false; true: every number gets as many decimal places as the one with the most |
|
||||
| `removeUnused` | false; true needs `end` |
|
||||
|
||||
→ `{count (objects changed), ids (numbered, in order), removed}`. Make Numbers Sequence… opens a dialog (`ui.menuDialog
|
||||
{command}`, dialog key `addon.type.numbers`) whose fields are the command's parameters, with Preview.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"addon.type.numbers","params":{"start":1,"order":"rows"}}}
|
||||
{"name":"run_command","arguments":{"command":"addon.type.numbers","params":{"start":5,"end":50,"step":5,"replace":"placeholder","digits":3}}}
|
||||
```
|
||||
|
||||
## Unit Converter add-on
|
||||
|
||||
Unit Converter is a built-in add-on that shows one length in every unit at once (#5528): its commands are
|
||||
|
||||
@@ -3195,6 +3195,10 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo
|
||||
|
||||
A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard (or the one `artboard` names; the journal records the active one, so a replay uses the same artboard). Every line is aligned left, right-to-left samples too, so each starts at its column's left edge. When the artboard is full, Add Artboards When Full (on by default) adds new artboards of the same size to its right for the rest; with it off, the rest is laid out in the same places to the right without artboards. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out, listed in `skipped` and named in `warning`. Entries whose font lacks a glyph needed by the sample stay on the sheet, are listed in `fallback` and named in `warning`. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet.
|
||||
|
||||
## Type Tools add-on: Make Numbers Sequence (2026-12-01)
|
||||
|
||||
A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Make Numbers Sequence… numbers the selected type objects from a start value by a step, optionally stopping at an end value, and each number replaces the whole text, every number in it, or every `{%n}` placeholder (#10448). The objects are taken in stacking order, by rows or by columns, or in a seeded random order, with optional leading and trailing zeros, and the objects past the end can be deleted. When numbers or placeholders are replaced, objects that hold none are skipped before the ordering, so they take no number and are never deleted. Locked and hidden type is left alone, a clipping mask is not deleted, and threaded type and bad parameters are refused. A run that changes the document is one undo step, and a run that changes nothing makes none. The dialog has Preview. It is based on Sergey Osokin's MIT-licensed MakeNumbersSequence script. Tests: `cmd::addons::typetools::numbers::tests` in `vectorcraft-engine`, `addons::typetools::numbers::tests` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on.
|
||||
|
||||
## Unit Converter add-on (2026-11-14)
|
||||
|
||||
A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`.
|
||||
|
||||
Reference in new issue
Block a user