mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 19:36:16 +00:00
Variables: Import Data Sets reads % columns of graph data files
dataset.import refused every header cell that starts with % unless it was a variable's exact name, so the five-column example on the data source set-up page did not import. A %Name header now defines the graph variable Name, or names it when the document has it, and each cell of the column is the path of a graph data file. The file is read as the Graph Data window's Import Data reads one, and the data becomes the data set's graph value, which applies as graph.setData applies it. A relative path is taken from the new base parameter, else from the folder of the CSV file at path. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and % columns that hold more than 256 MB in all refuse the import with the line and the column, and the document is left as it was. Each file is read once per import. Import Data's text decoding, cell splitting and sheet-to-data steps move from the Graph Data dialog to the engine (graph/data.rs), so both imports read a file the same way. dataset.export's warning now lists a % header over values as refused and a %-prefixed variable of another kind as read back with another kind.
This commit is contained in:
@@ -896,6 +896,10 @@ pub use brushsym::reset_transformation_changes;
|
||||
/// Data window reads files by it too).
|
||||
pub use variablecmds::utf16_order_without_mark;
|
||||
|
||||
/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data
|
||||
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
|
||||
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
|
||||
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
|
||||
/// They run as before but the command palette leaves them out (it lists the command once).
|
||||
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
|
||||
|
||||
@@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values};
|
||||
#[cfg(test)]
|
||||
use columns::{fill_totals, total_text};
|
||||
pub use commands::specs;
|
||||
pub(crate) use data::{apply_csv, parse_csv};
|
||||
pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, to_csv};
|
||||
pub(crate) use edit::{graphs_holding, keep_placed};
|
||||
|
||||
@@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String {
|
||||
g.to_csv()
|
||||
}
|
||||
|
||||
// ---------- graph data files ----------
|
||||
|
||||
/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns
|
||||
/// read, 1 MB (1,048,576 bytes).
|
||||
pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20;
|
||||
|
||||
/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels
|
||||
/// before its series; a cell's longest text.
|
||||
const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1;
|
||||
const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1;
|
||||
const SHEET_CELL: usize = 256;
|
||||
|
||||
/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode
|
||||
/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives
|
||||
/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one.
|
||||
/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired
|
||||
/// surrogate reads as U+FFFD.
|
||||
pub fn graph_data_text(bytes: &[u8]) -> String {
|
||||
let utf16 = |rest: &[u8], le: bool| {
|
||||
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
};
|
||||
match bytes {
|
||||
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
|
||||
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
|
||||
_ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() {
|
||||
Some(le) => utf16(bytes, le),
|
||||
None => String::from_utf8_lossy(bytes).into_owned(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256
|
||||
/// characters.
|
||||
pub fn graph_cell_text(s: &str) -> String {
|
||||
s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect()
|
||||
}
|
||||
|
||||
/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds
|
||||
/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file
|
||||
/// stays whole), at most a graph's rows and columns.
|
||||
pub fn graph_grid_from_text(text: &str) -> Vec<Vec<String>> {
|
||||
let sep = if text.contains('\t') { '\t' } else { ',' };
|
||||
text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect()
|
||||
}
|
||||
|
||||
/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the
|
||||
/// first column the category labels (none when all are blank), and the other cells the values (a
|
||||
/// blank cell, or text that isn't a number, has none), without the empty rows and columns past
|
||||
/// the data.
|
||||
pub fn graph_data_from_grid(grid: &[Vec<String>]) -> Value {
|
||||
let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default();
|
||||
let filled = |s: &String| !s.trim().is_empty();
|
||||
// At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by
|
||||
// automation is any size, and the values are their product.
|
||||
let grid = &grid[..grid.len().min(SHEET_ROWS)];
|
||||
let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1);
|
||||
let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1);
|
||||
let label = |s: &str| {
|
||||
let s = s.trim();
|
||||
// A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside.
|
||||
s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string()
|
||||
};
|
||||
// Series labels up to the last one given (none when all are blank).
|
||||
let mut series: Vec<String> = (1..cols).map(|c| label(&cell(0, c))).collect();
|
||||
while series.last().is_some_and(String::is_empty) {
|
||||
series.pop();
|
||||
}
|
||||
let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(r, 0))).collect();
|
||||
if categories.iter().all(String::is_empty) {
|
||||
categories.clear();
|
||||
}
|
||||
let values: Vec<Vec<Value>> = (1..rows)
|
||||
.map(|r| {
|
||||
(1..cols)
|
||||
.map(|c| {
|
||||
let t = cell(r, c);
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
json!({ "series": series, "categories": categories, "rows": values })
|
||||
}
|
||||
|
||||
/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph
|
||||
/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the
|
||||
/// value gives a graph the data that Import Data and Apply give it.
|
||||
pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result<String> {
|
||||
let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes)));
|
||||
let mut spec = GraphSpec::default();
|
||||
apply_data(&mut spec, &data, "dataset.import")?;
|
||||
Ok(spec.to_csv())
|
||||
}
|
||||
|
||||
/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with
|
||||
/// `csv` does. Data the graph already holds leaves the graph as it is.
|
||||
pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! variable name per column, which export writes with `#` before a visibility variable and `@`
|
||||
//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…,
|
||||
//! also reads tab-separated files, and reads header cells that define new variables (`#` for
|
||||
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! visibility, `@` for image, `%` for graph, whose cells name graph data files, no prefix for
|
||||
//! text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! variables and data sets of a variable library, the XML file of the reference app's Save
|
||||
//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one.
|
||||
//! Agents reach every command through `run_command`, like all engine commands.
|
||||
@@ -868,7 +869,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Data Sets…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
"{path? | data? | dataBase64? | csv?, base?: folder} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, `%Name` defines a graph variable, and a header without a prefix defines a text variable. A `%Name` column's cells are paths of graph data files, each read as Graph Data's Import Data reads one (at most 1 MB; tab-separated when a line holds a tab, else comma-separated; UTF-16 by dataset.import's rule, else UTF-8, with bytes that aren't UTF-8 read as replacement characters; the first row holds the series labels and the first column the category labels) and kept as the data set's graph value, which applies as graph.setData applies it. A relative path is taken from `base`, else from the folder of the CSV file at `path`; with neither, it is refused. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all (each file counted once, each cell's value every time) refuse the import, naming the line and the column. A prefixed header whose name is a variable of another kind is refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
has_doc,
|
||||
dataset_import
|
||||
),
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
json, read_file_head, str_param, variables_unlocked, write_file,
|
||||
};
|
||||
use crate::cmd::place::text::windows_1252;
|
||||
use crate::cmd::{MAX_GRAPH_DATA_FILE, text_param};
|
||||
|
||||
/// Cap on a graph variable's CSV (MCP and files are untrusted).
|
||||
pub(super) const MAX_GRAPH_CSV: usize = 256 * 1024;
|
||||
@@ -268,10 +269,11 @@ fn export_header(v: &Variable) -> String {
|
||||
|
||||
/// What [`dataset_import`] does with each variable's column of the CSV that [`datasets_to_csv`]
|
||||
/// writes, in a document without the variables: the first list names the variables whose header
|
||||
/// or values it refuses, so it doesn't import the file (a `%` header, a `#` header whose values
|
||||
/// aren't true or false, a header that names a variable an earlier column named), and the second
|
||||
/// the variables it reads as another variable (a text variable whose name starts with `#` or `@`,
|
||||
/// and a graph variable, which no header cell defines).
|
||||
/// or values it refuses, so it doesn't import the file (a `%` header over values, which it reads as
|
||||
/// paths of graph data files, a `#` header whose values aren't true or false, a header that names
|
||||
/// a variable an earlier column named), and the second the variables it reads as another variable
|
||||
/// (a variable whose name starts with `#`, `@` or `%` and isn't of that prefix's kind, and a graph
|
||||
/// variable, which the export writes without `%`).
|
||||
fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
const C: &str = "dataset.import";
|
||||
let none = BTreeMap::new();
|
||||
@@ -287,9 +289,11 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
refused.push(v.name.as_str());
|
||||
continue;
|
||||
};
|
||||
// A `%` header's cells are paths of graph data files, which the values the export writes aren't.
|
||||
let files = kind == VariableKind::Graph && name != cell;
|
||||
let cells_read = vars.datasets.iter().filter_map(|d| d.values.get(&v.name)).all(|val| {
|
||||
let cell = value_to_cell(val);
|
||||
cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok()
|
||||
if files { cell.trim().is_empty() } else { cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() }
|
||||
});
|
||||
if !cells_read {
|
||||
refused.push(v.name.as_str());
|
||||
@@ -340,7 +344,9 @@ fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result<String> {
|
||||
/// that earlier columns define) names that variable. Otherwise `#` before the name makes it a
|
||||
/// visibility variable, `@` makes it an image variable, and a cell without a prefix names a text
|
||||
/// variable. A prefixed name that is already a variable must be one of the prefix's kind; a new
|
||||
/// name is added to `defined`. A `%` cell that names no variable (graph data files) is refused.
|
||||
/// name is added to `defined`. `%` before a name makes it a graph variable whose column holds the
|
||||
/// paths of graph data files ([`graph_file_value`]); [`dataset_import`] tells such a column apart
|
||||
/// by a returned name that is not the cell.
|
||||
fn header_variable(
|
||||
cell: &str,
|
||||
column: usize,
|
||||
@@ -356,8 +362,8 @@ fn header_variable(
|
||||
(rest.trim(), VariableKind::Visibility)
|
||||
} else if let Some(rest) = cell.strip_prefix('@') {
|
||||
(rest.trim(), VariableKind::Image)
|
||||
} else if cell.starts_with('%') {
|
||||
return Err(bad(cmd, format!("column {column}: `{cell}` is a `%` column of graph data files, which are not read")));
|
||||
} else if let Some(rest) = cell.strip_prefix('%') {
|
||||
(rest.trim(), VariableKind::Graph)
|
||||
} else {
|
||||
(cell, VariableKind::Text)
|
||||
};
|
||||
@@ -375,13 +381,90 @@ fn header_variable(
|
||||
}
|
||||
}
|
||||
|
||||
/// The most bytes the `%` columns of one import read from graph data files and keep as graph
|
||||
/// values, counted together: each file's bytes once (it is read once, however many cells name it),
|
||||
/// and the graph value of every cell, which each data set holds a copy of.
|
||||
const MAX_GRAPH_FILES_TOTAL: usize = 256 * 1_048_576;
|
||||
|
||||
/// The graph data files the `%` columns of one import have read, by path, and the bytes counted
|
||||
/// against [`MAX_GRAPH_FILES_TOTAL`] so far.
|
||||
#[derive(Default)]
|
||||
struct GraphFiles {
|
||||
read: BTreeMap<String, String>,
|
||||
total: usize,
|
||||
}
|
||||
|
||||
/// The graph value of a `%` column's cell `path` on file line `line`, in 1-based `column`, for the
|
||||
/// graph variable `var`: the graph data file at `path` (taken from the folder `base` when
|
||||
/// relative), read as Graph Data's Import Data reads one ([`crate::cmd::graph::graph_csv_from_file`]),
|
||||
/// or no value for an empty cell. A relative path without `base`, a file that can't be read or is
|
||||
/// larger than 1 MB, a file that gives a graph value longer than [`MAX_GRAPH_CSV`] bytes and more
|
||||
/// than [`MAX_GRAPH_FILES_TOTAL`] bytes in all are refused, with the line and the column.
|
||||
fn graph_file_value(files: &mut GraphFiles, path: &str, base: Option<&str>, var: &str, (line, column): (usize, usize)) -> Result<Option<DataValue>> {
|
||||
const C: &str = "dataset.import";
|
||||
let path = path.trim();
|
||||
if path.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let full = match base {
|
||||
_ if std::path::Path::new(path).is_absolute() => path.to_string(),
|
||||
Some(base) => std::path::Path::new(base).join(path).to_string_lossy().into_owned(),
|
||||
None => {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path"
|
||||
),
|
||||
));
|
||||
}
|
||||
};
|
||||
let csv = match files.read.get(&full) {
|
||||
Some(csv) => csv.clone(),
|
||||
None => {
|
||||
// One byte past the limit is enough to refuse the file.
|
||||
let bytes = read_file_head(&full, MAX_GRAPH_DATA_FILE + 1)
|
||||
.map_err(|e| bad(C, format!("line {line}, column {column}: the graph data file for `{var}` can't be read: {e}")))?;
|
||||
if bytes.len() > MAX_GRAPH_DATA_FILE {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes"),
|
||||
));
|
||||
}
|
||||
let csv = crate::cmd::graph::graph_csv_from_file(&bytes)?;
|
||||
if csv.len() > MAX_GRAPH_CSV {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes"
|
||||
),
|
||||
));
|
||||
}
|
||||
files.total += bytes.len();
|
||||
files.read.insert(full, csv.clone());
|
||||
csv
|
||||
}
|
||||
};
|
||||
files.total += csv.len();
|
||||
if files.total > MAX_GRAPH_FILES_TOTAL {
|
||||
return Err(bad(C, format!("line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all")));
|
||||
}
|
||||
Ok(Some(DataValue::Graph(csv)))
|
||||
}
|
||||
|
||||
/// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it,
|
||||
/// and the variables the document doesn't define yet are defined, unbound. Two headers that name
|
||||
/// one variable are refused. The rows replace every dataset of the document and are named "Data
|
||||
/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// one variable are refused. The cells of a `%` column are paths of graph data files
|
||||
/// ([`graph_file_value`]); a relative one is taken from the folder `base` gives, else from the
|
||||
/// folder of the file `path` names. The rows replace every dataset of the document and are named
|
||||
/// "Data Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// stay. One undo step, and none when the variables and datasets stay as they were.
|
||||
pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "dataset.import";
|
||||
let base = match text_param(p, "base", C)? {
|
||||
Some("") => return Err(bad(C, "`base` is empty")),
|
||||
Some(base) => Some(absolute_path(base)),
|
||||
None => str_param(p, "path").and_then(|path| std::path::Path::new(&absolute_path(path)).parent().map(|d| d.to_string_lossy().into_owned())),
|
||||
};
|
||||
let (bytes, given_as_text) = datasets_csv_bytes(p, C)?;
|
||||
// `data` and `csv` are already text, NUL characters included (`dataset.export` writes them).
|
||||
let text = if given_as_text { String::from_utf8(bytes).map_err(|_| bad(C, "CSV is not UTF-8"))? } else { datasets_csv_text(&bytes, C)? };
|
||||
@@ -390,7 +473,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV is empty"));
|
||||
};
|
||||
let kinds: BTreeMap<String, VariableKind> = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect();
|
||||
let mut columns: Vec<(usize, String, VariableKind)> = Vec::new();
|
||||
// Each column: its index, its variable and kind, and whether its cells are graph data files.
|
||||
let mut columns: Vec<(usize, String, VariableKind, bool)> = Vec::new();
|
||||
let mut defined: Vec<Variable> = Vec::new();
|
||||
for (i, h) in header.iter().enumerate() {
|
||||
let cell = h.trim();
|
||||
@@ -398,11 +482,12 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("empty header in column {}", i + 1)));
|
||||
}
|
||||
let (name, kind) = header_variable(cell, i + 1, &kinds, &mut defined, C)?;
|
||||
if let Some(&(first, ..)) = columns.iter().find(|(_, n, _)| *n == name) {
|
||||
if let Some(&(first, ..)) = columns.iter().find(|(_, n, ..)| *n == name) {
|
||||
let (first, column) = (first + 1, i + 1);
|
||||
return Err(bad(C, format!("columns {first} and {column} both name the variable `{name}`")));
|
||||
}
|
||||
columns.push((i, name, kind));
|
||||
let files = kind == VariableKind::Graph && name != cell;
|
||||
columns.push((i, name, kind, files));
|
||||
}
|
||||
// Lock Variables refuses New Variable, so the import is refused when a header would define one.
|
||||
if !defined.is_empty() {
|
||||
@@ -412,13 +497,19 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV has a header but no data rows"));
|
||||
}
|
||||
let mut parsed: Vec<DataSet> = Vec::new();
|
||||
let mut files = GraphFiles::default();
|
||||
for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() {
|
||||
let name = format!("Data Set {}", n + 1);
|
||||
let mut values = BTreeMap::new();
|
||||
for &(col, ref var, kind) in &columns {
|
||||
for &(col, ref var, kind, from_files) in &columns {
|
||||
let cell = row.get(col).map(String::as_str).unwrap_or("");
|
||||
let was_quoted = quoted.get(col).copied().unwrap_or(false);
|
||||
if let Some(v) = cell_to_value(kind, cell, was_quoted, var, line, C)? {
|
||||
let value = if from_files {
|
||||
graph_file_value(&mut files, cell, base.as_deref(), var, (line, col + 1))?
|
||||
} else {
|
||||
cell_to_value(kind, cell, was_quoted, var, line, C)?
|
||||
};
|
||||
if let Some(v) = value {
|
||||
values.insert(var.clone(), v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1958,8 +1958,8 @@ fn datasets_csv_export_imports_back_to_the_same_data_sets() {
|
||||
}
|
||||
|
||||
/// The export's `warning` names the variables whose column a document without the variables
|
||||
/// refuses, so it doesn't import the file: a `%` header, a `#` header whose values aren't true or
|
||||
/// false, and a header that names a variable an earlier column defined with another kind. A
|
||||
/// refuses, so it doesn't import the file: a `%` header over values, a `#` header whose values
|
||||
/// aren't true or false, and a header that names a variable an earlier column defined with another kind. A
|
||||
/// header that names such a variable with its kind is read with that kind, and is listed as one
|
||||
/// read back with another kind.
|
||||
#[test]
|
||||
@@ -1977,7 +1977,9 @@ fn datasets_csv_export_warns_of_headers_a_new_document_refuses() {
|
||||
let refuses = |names: &str| format!("a new document refuses this file because of these variables: {names}");
|
||||
let loses = |names: &str| format!("a new document won't read these variables back with their kind: {names}");
|
||||
|
||||
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (refuses("`%Rate`"), true));
|
||||
// A `%` header's cells are read as paths of graph data files.
|
||||
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({"%Rate": "5"})), (refuses("`%Rate`"), true));
|
||||
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (loses("`%Rate`, `Chart`"), false));
|
||||
assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "hello"})), (refuses("`#Tag`"), true));
|
||||
assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "yes"})), (loses("`#Tag`"), false));
|
||||
assert_eq!(export(&[("#Seen", "text"), ("Seen", "image")], json!({})), (refuses("`Seen`"), true));
|
||||
@@ -2005,18 +2007,122 @@ fn datasets_csv_export_refuses_a_header_that_names_another_variable() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `%` header cell that isn't a variable's name (graph data files) is refused with its column,
|
||||
/// and the import defines nothing.
|
||||
/// The data `graph.setData` reports for the graph `g`: series, categories and rows.
|
||||
fn graph_data(s: &mut Session, g: NodeId) -> Value {
|
||||
let v = s.execute("graph.setData", &json!({"id": g.0})).unwrap();
|
||||
json!({"series": v["series"], "categories": v["categories"], "rows": v["rows"]})
|
||||
}
|
||||
|
||||
/// A `%` header defines a graph variable, and each of its cells is the path of a graph data file,
|
||||
/// as the set-up page's five-column example has them. A relative path is taken from the CSV file's
|
||||
/// folder. Selecting a data set gives the bound graph the data that Graph Data's Import Data and
|
||||
/// Apply give it for the same file: tab- or comma-separated, the first row the series labels and the
|
||||
/// first column the category labels, in UTF-16 too. An empty cell is no value.
|
||||
#[test]
|
||||
fn datasets_csv_refuses_graph_data_file_columns() {
|
||||
fn datasets_csv_reads_graph_data_files_in_percent_columns() {
|
||||
let dir = Folder::new("vars-csv-graph-files");
|
||||
let tabs: &[u8] = b"\t2024\t2025\nQ1\t3\t4\nQ2\t5\t6\n";
|
||||
let commas: &[u8] = b",North\nJan,7\nFeb,8\n";
|
||||
let utf16: Vec<u8> = [0xFF, 0xFE].into_iter().chain(",A\r\nX,9\r\n".encode_utf16().flat_map(u16::to_le_bytes)).collect();
|
||||
write(&dir.file("graphs/bill.txt"), tabs);
|
||||
write(&dir.file("dat.csv"), commas);
|
||||
write(&dir.file("ruiz.txt"), &utf16);
|
||||
let absolute = dir.file("dat.csv");
|
||||
let csv = format!(
|
||||
"Name,Age,@Photos,%Graphs,#Visibility\nBill,36,b.jpg,graphs/bill.txt,true\nDat,53,d.jpg,{absolute},true\nMaria,26,r.jpg,ruiz.txt,false\nNone,1,n.jpg,,true\n"
|
||||
);
|
||||
let path = dir.file("data.csv");
|
||||
write(&path, csv.as_bytes());
|
||||
|
||||
let mut s = session();
|
||||
let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string();
|
||||
let named = error(&mut s, "Name,Title,%Sales\nA,x,sales.txt");
|
||||
assert!(named.contains("column 3:") && named.contains("`%Sales`"), "{named}");
|
||||
let unnamed = error(&mut s, "%Sales\tTitle\nsales.txt\tx");
|
||||
assert!(unnamed.contains("column 1:") && unnamed.contains("`%Sales`"), "{unnamed}");
|
||||
let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"})).unwrap();
|
||||
let g = NodeId(graph["id"].as_u64().unwrap());
|
||||
let imp = s.execute("dataset.import", &json!({"path": path})).unwrap();
|
||||
assert_eq!(imp["defined"], json!(["Name", "Age", "Photos", "Graphs", "Visibility"]));
|
||||
assert_eq!(imp["imported"], 4);
|
||||
let listed = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(listed["variables"][3], json!({"name": "Graphs", "kind": "graph", "bindings": 0}));
|
||||
s.execute("variable.bind", &json!({"variable": "Graphs", "ids": [g.0]})).unwrap();
|
||||
|
||||
// What Import Data and Apply give the graph for each file.
|
||||
let sheet = |bytes: &[u8]| {
|
||||
let data = crate::cmd::graph_data_from_grid(&crate::cmd::graph_grid_from_text(&crate::cmd::graph_data_text(bytes)));
|
||||
let mut probe = session();
|
||||
let p = json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"});
|
||||
let id = NodeId(probe.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let mut set = data.clone();
|
||||
set["id"] = json!(id.0);
|
||||
probe.execute("graph.setData", &set).unwrap();
|
||||
graph_data(&mut probe, id)
|
||||
};
|
||||
for (set, bytes) in ["Data Set 1", "Data Set 2", "Data Set 3"].into_iter().zip([tabs, commas, utf16.as_slice()]) {
|
||||
s.execute("dataset.select", &json!({"name": set})).unwrap();
|
||||
assert_eq!(graph_data(&mut s, g), sheet(bytes), "{set}");
|
||||
}
|
||||
assert_eq!(graph_data(&mut s, g), json!({"series": ["A"], "categories": ["X"], "rows": [[9.0]]}));
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert!(vars.variables.is_empty() && vars.datasets.is_empty());
|
||||
assert_eq!(vars.datasets[3].values.get("Graphs"), None, "an empty cell is no value");
|
||||
|
||||
// A `%` header names a graph variable the document has, and `base` sets the folder of
|
||||
// relative paths when the CSV comes as text.
|
||||
let mut t = session();
|
||||
t.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap();
|
||||
let base = dir.0.to_string_lossy().into_owned();
|
||||
let imp = t.execute("dataset.import", &json!({"csv": "% Sales\ndat.csv", "base": base})).unwrap();
|
||||
assert_eq!(imp["defined"], json!([]));
|
||||
let value = t.doc().unwrap().doc.variables.datasets[0].values.get("Sales").cloned();
|
||||
assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains("North") && c.contains("Feb")), "{value:?}");
|
||||
}
|
||||
|
||||
/// A `%` column's file that is missing, a folder, larger than 1 MB, or gives a graph value longer
|
||||
/// than 256 KB, a relative path with no
|
||||
/// folder to take it from, a `base` that isn't a folder path, and a `%` header whose name is a
|
||||
/// variable of another kind refuse the import with the line and column, and leave the variables and
|
||||
/// data sets as they were. A file of exactly 1 MB is read, and a file named by many cells is read
|
||||
/// once.
|
||||
#[test]
|
||||
fn datasets_csv_refuses_unreadable_graph_data_files() {
|
||||
let dir = Folder::new("vars-csv-graph-refused");
|
||||
write(&dir.file("ok.txt"), b"\tA\nX\t1\n");
|
||||
write(&dir.file("big.txt"), &vec![b'1'; crate::cmd::MAX_GRAPH_DATA_FILE + 1]);
|
||||
let at_limit = [b"\tA\nX\t2\n".as_slice(), &vec![b' '; crate::cmd::MAX_GRAPH_DATA_FILE - 7]].concat();
|
||||
write(&dir.file("limit.txt"), &at_limit);
|
||||
std::fs::create_dir_all(dir.file("folder.txt")).unwrap();
|
||||
// 10,000 categories with long labels: under 1 MB, but a graph value over 256 KB.
|
||||
let long: String = (0..10_000).map(|i| format!("category label number {i:05}\t{i}\n")).collect();
|
||||
write(&dir.file("long.txt"), format!("\tA\n{long}").as_bytes());
|
||||
let base = dir.0.to_string_lossy().into_owned();
|
||||
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": "Title\nkept"})).unwrap();
|
||||
let before = s.doc().unwrap().doc.variables.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let cases = [
|
||||
(json!({"csv": "Name,%Chart\na,ok.txt\nb,missing.txt", "base": base}), "line 3, column 2: the graph data file for `Chart` can't be read"),
|
||||
(json!({"csv": "Name,%Chart\na,folder.txt", "base": base}), "line 2, column 2: the graph data file for `Chart` can't be read"),
|
||||
(json!({"csv": "%Chart\nbig.txt", "base": base}), "line 2, column 1: the graph data file `big.txt` for `Chart` is larger than 1048576 bytes"),
|
||||
(
|
||||
json!({"csv": "Name,%Chart\na,long.txt", "base": base}),
|
||||
"line 2, column 2: the graph data file `long.txt` for `Chart` gives a graph value longer than 262144 bytes",
|
||||
),
|
||||
(json!({"csv": "%Chart\nok.txt"}), "line 2, column 1: the graph data file `ok.txt` for `Chart` is a relative path"),
|
||||
(json!({"csv": "%Chart\nok.txt", "base": ""}), "`base` is empty"),
|
||||
(json!({"csv": "%Chart\nok.txt", "base": 3}), "`base` must be a string"),
|
||||
(json!({"csv": "%Title\nok.txt", "base": base}), "column 1: `%Title` names `Title`, which is a text variable"),
|
||||
];
|
||||
for (p, want) in cases {
|
||||
let e = s.execute("dataset.import", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
assert_eq!(s.doc().unwrap().doc.variables, before, "{p}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{p}");
|
||||
}
|
||||
|
||||
let rows: String = (0..300).map(|_| "limit.txt\n").collect();
|
||||
let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{rows}"), "base": base})).unwrap();
|
||||
assert_eq!(imp["imported"], 300, "a 1 MB file named by 300 cells counts once against the import's limit");
|
||||
let value = s.doc().unwrap().doc.variables.datasets[299].values.get("Chart").cloned();
|
||||
assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('2')), "{value:?}");
|
||||
}
|
||||
|
||||
/// Two header cells that name one variable, by the same name or by a name and its prefix, are
|
||||
|
||||
Reference in New Issue
Block a user