//! Object › Graph › Data…: the Graph Data window, a worksheet of the graph's data. //! //! The first row holds the series labels (the legend), the first column the category labels, the //! top-left cell stays blank; the other cells are values (a blank cell has none). A cell is picked //! with a click and edited in the entry box above the sheet: Enter writes the text into the cell and //! moves down, Tab off the box moves right, Shift with either the other way, and the arrow keys move //! between the sheet's cells. Pasting tab- or line-separated text into the sheet fills the cells from //! the picked one. Import Data reads a tab-separated text file, Transpose row/column swaps rows and //! columns, Switch x/y swaps a scatter graph's y and x columns, Cell Style sets the number of //! decimals the sheet shows and the width of every column, dragging a column's right edge sets that //! column's width (in whole digits, 0 to 20, as Cell Style), and Revert reads the graph's data //! again. Apply (`graph.setData` with its series, categories and rows) redraws the graph and leaves //! the window open. //! //! Fields (`ui.inspect`, `ui.dialog.set`): `grid` (rows of cell texts), `sel` ([row, column]), //! `entry` (the picked cell's text being edited), `decimals` (null: as typed), `width` (digits) and //! `widths` (a column's own width in digits by its index, null or missing: `width`; setting `width` //! empties it). use std::collections::BTreeMap; use std::sync::Arc; use craft::behavior::{EditEvent, NumberCodec}; use craft::host::{PickRequest, Picked}; use craft::table::ui::{ CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions, }; use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, PaintUi, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{ DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field, }; use craft::ui::display::Text; use craft::ui::layout_components::Row; use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::FormDialog; use craft::ui::primitives::TextRun; use craft::ui::runtime::env::{Env, Label, Units}; use craft::ui::runtime::focus::Initial; use craft::ui::style::TypeRole; use craft::ui::text::{NumberField, TextField}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_doc::{MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES}; use crate::VectorcraftApp; use crate::file_asks::{self, Owner}; /// The dialog kind of Graph Data, the key of its dialog on the host. pub const KIND: &str = "graphData"; const WRONG_DOCUMENT: &str = "Graph Data belongs to the document that opened this sheet."; const REVERTED_DOCUMENT: &str = "Reopen Graph Data after reverting the drawing."; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its /// series; the least rows it shows. const MAX_ROWS: usize = MAX_GRAPH_CATEGORIES + 1; const MAX_COLS: usize = MAX_GRAPH_SERIES + 1; const MIN_ROWS: usize = 8; /// The largest file Import Data reads, 1 MB (1,048,576 bytes), the same as Import Data Sets'. const MAX_IMPORT_BYTES: usize = vectorcraft_engine::cmd::MAX_GRAPH_DATA_FILE; /// The Cell Style limits (Adjust column width and decimal digits), and what they start at. const MAX_DECIMALS: u64 = 10; const MAX_WIDTH: u64 = 20; const DEFAULT_DECIMALS: u64 = 2; const DEFAULT_WIDTH: u64 = 7; /// A cell's height on the sheet. const ROW_H: f32 = 19.0; /// Open Graph Data for the selected graph. pub fn open(app: &mut VectorcraftApp) -> Result { // The query fails without a graph selected, with the engine's own message. let v = app.session.execute("graph.setData", &json!({})).map_err(|e| e.to_string())?; let st = app.session.active().ok_or("no document open")?; let graph = st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)); let scatter = graph .is_some_and(|id| st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter)); let dialog = GraphDataDialog::new(grid_from_data(&v), st.uid, st.reverts, graph.map(|id| id.0), scatter, can_import(app)); let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; dialogs.with(|host| host.open(dialog)); Ok(Value::Null) } /// The graph `id` belongs to (itself, or the graph its parts are in). fn graph_of(doc: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId) -> Option { let mut cur = Some(id); while let Some(c) = cur { if doc.node(c).is_some_and(|n| n.extras().graph.is_some()) { return Some(c); } cur = doc.parent_of(c); } None } // ---------- the worksheet ---------- type Grid = Vec>; /// The values the window edits: the cells and Cell Style. What `FormDialog` binds and what Apply sends. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub(crate) struct Sheet { /// The cells by row; a row or cell past them is blank. grid: Grid, /// The decimals a number cell shows; `None` shows the text as typed. decimals: Option, /// Cell Style's Column Width in digits. width: u64, /// A column's own width in digits by its index; `None` takes `width`. widths: Vec>, } impl Default for Sheet { fn default() -> Self { Sheet { grid: Grid::new(), decimals: None, width: DEFAULT_WIDTH, widths: Vec::new() } } } /// A button's work that needs the app, done by [`pump`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Action { /// Import Data…: ask for a file. Import, /// Revert: read the graph's data again. Revert, } /// The entry box: the text of the cell `at`, which it writes into the sheet when the cell is left. #[derive(Clone, Debug, PartialEq)] struct Entry { text: String, at: (usize, usize), } /// The row and column lines the grid lays out, rebuilt only when the rows shown or the column widths change. struct Lines { key: Option<(usize, u64, Vec>)>, rows: LineIndex, columns: LineIndex, /// The own width of the column whose edge a drag holds, as it was when the drag began. resize_from: Option>, } impl Lines { fn new() -> Self { Lines { key: None, rows: LineIndex::uniform(ROW_H, 0), columns: LineIndex::uniform(digits_px(DEFAULT_WIDTH), MAX_COLS as u32), resize_from: None, } } /// Lays out `rows` rows and every column of `sheet` at its width. fn sync(&mut self, rows: usize, sheet: &Sheet) { if self.key.as_ref().is_some_and(|(r, w, ws)| *r == rows && *w == sheet.width && *ws == sheet.widths) { return; } let own: BTreeMap = sheet.widths.iter().enumerate().filter_map(|(c, w)| Some((u32::try_from(c).ok()?, digits_px((*w)?)))).collect(); self.rows = LineIndex::uniform(ROW_H, u32::try_from(rows).unwrap_or(u32::MAX)); self.columns = LineIndex::new(&own, digits_px(width(sheet)), MAX_COLS as u32); self.key = Some((rows, sheet.width, sheet.widths.clone())); } } /// The sheet as the grid reads it. struct SheetModel<'a> { sheet: &'a Sheet, rows: &'a LineIndex, columns: &'a LineIndex, } impl GridModel for SheetModel<'_> { fn rows(&self) -> &LineIndex { self.rows } fn columns(&self) -> &LineIndex { self.columns } fn selectable(&self, cell: CellAt) -> bool { selectable(cell) } fn last_used(&self) -> CellAt { let column = self.sheet.grid.iter().filter_map(|r| r.iter().rposition(|c| !c.trim().is_empty())).max().unwrap_or(0); CellAt::new(data_rows(self.sheet) as u32, column as u32) } fn paint_cell(&self, ui: &mut PaintUi<'_>, rect: egui::Rect, cell: CellAt, _zoom: f32) { let text = shown(&self.cell_text(cell), self.sheet.decimals); ui.draw().text(rect, &TextRun::new(text).role(TypeRole::Mono).elide()); } fn cell_text(&self, cell: CellAt) -> String { cell_of(&self.sheet.grid, cell.row as usize, cell.column as usize) } } /// The top-left cell stays blank: no pick lands on it. fn selectable(cell: CellAt) -> bool { (cell.row, cell.column) != (0, 0) } /// Runs `f` with the rules the picked cell moves by: the sheet's full size, whatever it shows. fn with_space(f: impl FnOnce(&CellSpace<'_, u32>) -> R) -> R { let rows = Positions::new(MAX_ROWS as u32); f(&CellSpace::new(&rows, MAX_COLS as u32).selectable(&selectable)) } /// The cells' text of a grid, or an empty text past it. fn cell_of(grid: &[Vec], r: usize, c: usize) -> String { grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default() } /// The picked cell of the sheet view ([row, column]). fn active(state: &GridState) -> (usize, usize) { state.selection.active().map_or((0, 1), |c| (c.row as usize, c.column as usize)) } /// Picks cell `to`; `false` when the sheet has no such cell or it is the blank one. fn select(state: &mut GridState, to: (usize, usize)) -> bool { let (Ok(row), Ok(column)) = (u32::try_from(to.0), u32::try_from(to.1)) else { return false }; with_space(|space| state.selection.select(CellAt::new(row, column), space)) } /// The sheet's cells from the `graph.setData` query: the series in the first row, each category's /// label then values below (the label column is there, blank, when the graph has no labels). pub(crate) fn grid_from_data(v: &Value) -> Grid { let strings = |k: &str| -> Vec { v[k].as_array().map(|a| a.iter().map(|s| s.as_str().unwrap_or_default().to_string()).collect()).unwrap_or_default() }; let (series, categories) = (strings("series"), strings("categories")); let rows: Vec> = v["rows"].as_array().map(|a| a.iter().map(|r| r.as_array().cloned().unwrap_or_default()).collect()).unwrap_or_default(); let mut grid: Grid = vec![std::iter::once(String::new()).chain(series).collect()]; for (c, row) in rows.iter().enumerate() { let label = categories.get(c).cloned().unwrap_or_default(); grid.push(std::iter::once(label).chain(row.iter().map(|x| x.as_f64().map(|f| f.to_string()).unwrap_or_default())).collect()); } grid } /// The sheet as `graph.setData` takes it ([`vectorcraft_engine::cmd::graph_data_from_grid`]), /// which Import Data Sets' `%` columns also use. pub(crate) fn data_from_grid(grid: &Grid) -> Value { vectorcraft_engine::cmd::graph_data_from_grid(grid) } /// Text from a file or the clipboard as cells ([`vectorcraft_engine::cmd::graph_grid_from_text`]). pub(crate) fn grid_from_text(text: &str) -> Grid { vectorcraft_engine::cmd::graph_grid_from_text(text) } /// A text file's bytes as text ([`vectorcraft_engine::cmd::graph_data_text`]). pub(crate) fn decode(bytes: &[u8]) -> String { vectorcraft_engine::cmd::graph_data_text(bytes) } /// A cell's text ([`vectorcraft_engine::cmd::graph_cell_text`]). fn clean(s: &str) -> String { vectorcraft_engine::cmd::graph_cell_text(s) } /// Set cell `(r, c)` of the sheet, growing it as needed (within the sheet's size). fn set_cell_at(sheet: &mut Sheet, r: usize, c: usize, text: &str) { if r >= MAX_ROWS || c >= MAX_COLS { return; } if sheet.grid.len() <= r { sheet.grid.resize(r + 1, Vec::new()); } let Some(row) = sheet.grid.get_mut(r) else { return }; if row.len() <= c { row.resize(c + 1, String::new()); } if let Some(cell) = row.get_mut(c) { *cell = clean(text); } } /// Transpose row/column: the sheet's rows become its columns. pub(crate) fn transpose(grid: &Grid) -> Grid { let cols = grid.iter().map(Vec::len).max().unwrap_or(0); (0..cols).map(|c| grid.iter().map(|r| r.get(c).cloned().unwrap_or_default()).collect()).collect() } /// Switch x/y: each scatter series' y and x columns (1 and 2, 3 and 4…) trade places, labels too; a /// last y column without its x stays where it is. pub(crate) fn switch_xy(grid: &Grid) -> Grid { // Every row as wide as the widest, so a label row shorter than the data swaps with it. let width = grid.iter().map(Vec::len).max().unwrap_or(0); grid.iter() .map(|r| { let mut r = r.clone(); r.resize(width, String::new()); let mut c = 1; while c + 1 < r.len() { r.swap(c, c + 1); c += 2; } r }) .collect() } /// How many rows of the sheet hold data (below the labels' row). fn data_rows(sheet: &Sheet) -> usize { sheet.grid.iter().rposition(|r| r.iter().any(|c| !c.trim().is_empty())).unwrap_or(0) } /// How many rows the sheet draws: the data, a spare row, the picked cell's, and at least MIN_ROWS. fn extent(sheet: &Sheet, sel: (usize, usize)) -> usize { (sheet.grid.len() + 1).max(MIN_ROWS).max(sel.0 + 2).min(MAX_ROWS) } /// A cell as the sheet shows it: a number with `decimals` places when Cell Style sets them, else as /// typed (the number Apply sends is as typed either way). pub(crate) fn shown(text: &str, decimals: Option) -> String { match (decimals, text.trim().parse::()) { (Some(d), Ok(v)) if v.is_finite() && !text.trim().starts_with('"') => format!("{v:.*}", d.min(MAX_DECIMALS) as usize), _ => text.to_string(), } } /// The sheet's cells replaced by `g`. fn replace_grid(sheet: &mut Sheet, g: Grid) { sheet.grid = g; } /// Paste: text with tabs or line breaks fills the cells from the cell `at`. fn paste_block(sheet: &mut Sheet, at: (usize, usize), text: &str) { for (r, row) in grid_from_text(text).into_iter().enumerate() { for (c, t) in row.into_iter().enumerate() { set_cell_at(sheet, at.0 + r, at.1 + c, &t); } } } /// Keeps what a field set on the sheet may hold within the sheet's size. fn limit(sheet: &mut Sheet) { sheet.grid.truncate(MAX_ROWS); for row in &mut sheet.grid { row.truncate(MAX_COLS); } sheet.widths.truncate(MAX_COLS); sheet.width = sheet.width.min(MAX_WIDTH); sheet.decimals = sheet.decimals.map(|d| d.min(MAX_DECIMALS)); } /// The entry box's text into its cell. fn commit_text(sheet: &mut Sheet, entry: &Entry) { if cell_of(&sheet.grid, entry.at.0, entry.at.1) != entry.text { set_cell_at(sheet, entry.at.0, entry.at.1, &entry.text); } } /// The entry box shows the picked cell's text. fn load(sheet: &Sheet, state: &GridState, entry: &mut Entry) { entry.at = active(state); entry.text = cell_of(&sheet.grid, entry.at.0, entry.at.1); } /// The picked cell moved since the entry box loaded: the box's text goes into the cell it left and /// the box loads the new one. fn follow(sheet: &mut Sheet, state: &GridState, entry: &mut Entry) { if active(state) != entry.at { commit_text(sheet, entry); load(sheet, state, entry); } } /// Enter, Tab or Shift with either in the entry box: its text into the picked cell, then the pick moves /// one cell toward `step` (it stays at the sheet's edge and off the blank cell) and the box loads that cell. fn commit_entry(sheet: &mut Sheet, state: &mut GridState, entry: &mut Entry, step: CellDirection) { commit_text(sheet, entry); with_space(|space| state.selection.step(step, space)); load(sheet, state, entry); } /// Apply: the sheet's data to the graph. fn apply(app: &mut VectorcraftApp, sheet: &Sheet, graph: Option) -> Result { // The graph the sheet opened on (else the selected one). let mut p = data_from_grid(&sheet.grid); p["id"] = json!(graph); app.run("graph.setData", p) } /// The graph's data as sheet cells. fn graph_grid(app: &mut VectorcraftApp, graph: Option) -> Result { let v = app.session.execute("graph.setData", &json!({ "id": graph })).map_err(|e| e.to_string())?; Ok(grid_from_data(&v)) } /// Browser picks carry their contents; native picks need a path reader. fn can_import(app: &VectorcraftApp) -> bool { file_asks::can(app, craft::host::PickKind::Open) && (app.host.files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some()) } /// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result { let Some(dialogs) = app.dialogs() else { return Ok(Value::Null) }; if !dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, owner))) { return Ok(Value::Null); } let bytes = match picked { Picked::Paths(paths) => { let Some(path) = paths.first().map(|p| p.to_string_lossy().into_owned()) else { return Ok(Value::Null) }; // One byte past the limit tells a larger file apart without reading all of it. match (&app.services.read_head, &app.services.read) { (Some(read_head), _) => read_head(&path, MAX_IMPORT_BYTES + 1)?, (None, Some(read)) => read(&path)?, // The button is off where files can't be read. (None, None) => return Ok(Value::Null), } } // The web build answers with the file's bytes. Picked::Contents(files) => match files.into_iter().next() { Some((_, bytes)) => bytes, None => return Ok(Value::Null), }, // Cancelled, or no picker could be shown: nothing to say. _ => return Ok(Value::Null), }; if bytes.len() > MAX_IMPORT_BYTES { return Err("the file is larger than 1 MB".into()); } let grid = grid_from_text(&decode(&bytes)); dialogs.with(|host| host.get_mut::().filter(|d| Arc::ptr_eq(&d.import_owner, owner)).map(|d| d.replace(grid))); Ok(Value::Null) } /// What the window asked of the app since the last [`pump`]. struct Asks { document: u64, reverts: u64, graph: Option, import_owner: Arc<()>, apply: Option, actions: Vec, } /// Runs once per frame after the shell: answers what the open Graph Data window asked (Apply, Import, /// Revert) and tells it whether Import can ask for a file. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let can = can_import(app); let active = app.session.active().map(|doc| (doc.uid, doc.reverts)); let asked = dialogs.with(|host| { host.get_mut::().map(|d| { d.can_import = can; if active == Some((d.document, d.reverts)) { d.held.clear_refusal(); } d.take_asks() }) }); let Some(Asks { document, reverts, graph, import_owner, apply: filed, actions }) = asked else { return }; let refusal = match active { Some((uid, current_reverts)) if uid == document => (current_reverts != reverts).then_some(tl!(REVERTED_DOCUMENT)), _ => Some(tl!(WRONG_DOCUMENT)), }; if let Some(sheet) = filed { let answer = if let Some(reason) = refusal { Err(Label::from(reason)) } else { if let Err(e) = apply(app, &sheet, graph) { app.status(e); } Ok(()) }; dialogs.with(|host| host.get_mut::().map(|dialog| dialog.applied(answer))); } for action in actions { match action { Action::Import => { let request = PickRequest::open("document").filter("Text", &["txt", "tsv", "csv"]); let owner = import_owner.clone(); let current = import_owner.clone(); file_asks::ask_while( app, request, Owner::Document, move |app| { app.dialogs().is_some_and(|dialogs| { dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, ¤t))) }) }, move |app, picked| import(app, &owner, picked), ); } Action::Revert => { if let Some(reason) = refusal { app.status(reason.to_owned()); } else { match graph_grid(app, graph) { Ok(grid) => { dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); } Err(e) => app.status(e), } } } } } } // ---------- Cell Style ---------- /// Cell Style's Column Width in digits. fn width(sheet: &Sheet) -> u64 { sheet.width.min(MAX_WIDTH) } /// A column's width in digits: its own when its edge was dragged, else Cell Style's. fn col_digits(sheet: &Sheet, c: usize) -> u64 { sheet.widths.get(c).copied().flatten().unwrap_or_else(|| width(sheet)).min(MAX_WIDTH) } /// Cell Style's Column Width: every column `n` digits wide, the ones given their own width too. fn set_width(sheet: &mut Sheet, n: u64) { sheet.width = n.min(MAX_WIDTH); sheet.widths.clear(); } /// Set column `c`'s own width in digits (at most MAX_WIDTH). fn set_col_digits(sheet: &mut Sheet, c: usize, n: u64) { if c >= MAX_COLS { return; } if sheet.widths.len() <= c { sheet.widths.resize(c + 1, None); } if let Some(w) = sheet.widths.get_mut(c) { *w = Some(n.min(MAX_WIDTH)); } } /// A column `n` digits wide, in points on the sheet. fn digits_px(n: u64) -> f32 { (n.min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0) } /// The width in digits nearest to `px` points, within Cell Style's 0 to MAX_WIDTH. fn px_digits(px: f32) -> u64 { if px.is_finite() { ((px - 10.0) / 7.0).round().clamp(0.0, MAX_WIDTH as f32) as u64 } else { 0 } } /// A column's edge dragged: the width the drag gives it in whole digits, on every update and at the commit; a /// cancel gives back the width it began with (`began`, kept at the begin). A drag that stays where it began changes /// nothing. fn handle_edit(sheet: &mut Sheet, began: &mut Option>, column: u32, width: &EditEvent) { let c = column as usize; match width { EditEvent::Begin { .. } => *began = Some(sheet.widths.get(c).copied().flatten()), // The grid's cancel carries no starting width: the one kept at the begin goes back. EditEvent::Cancel { .. } => { if let (Some(own), Some(w)) = (began.take(), sheet.widths.get_mut(c)) { *w = own; } return; } _ => {} } let Some(px) = width.landed() else { return }; let n = px_digits(*px); if n != col_digits(sheet, c) { set_col_digits(sheet, c, n); } } // ---------- the window ---------- /// What the body edits besides the sheet. struct Pane<'a> { state: &'a mut GridState, entry: &'a mut Entry, lines: &'a mut Lines, actions: &'a mut Vec, scatter: bool, can_import: bool, } /// A whole number field of `units` named `label`, from 0 to `max`. fn whole(units: &Units, label: impl Into