This commit is contained in:
2026-02-07 20:30:19 -07:00
parent 53dcf2ffc9
commit 6ec7d90ac5
4 changed files with 110 additions and 105 deletions

View File

@@ -18,7 +18,10 @@ use ratatui::{
use crate::app::{
clipboard::Clipboard,
error_msg::StatusMessage,
logic::{calc::{Grid, get_header_size}, cell::CellType},
logic::{
calc::{Grid, get_header_size},
cell::CellType,
},
mode::Mode,
screen::ScreenSpace,
};
@@ -42,7 +45,7 @@ impl Widget for &App {
let (x_max, y_max) = self.screen.how_many_cells_fit_in(&area, &self.vars);
let is_selected = |x: usize, y: usize| -> bool {
if let Mode::Visual((mut x1, mut y1)) | Mode::VisualCmd((mut x1, mut y1), _)= self.mode {
if let Mode::Visual((mut x1, mut y1)) | Mode::VisualCmd((mut x1, mut y1), _) = self.mode {
let (mut x2, mut y2) = self.grid.cursor();
x1 += 1;
y1 += 1;
@@ -78,7 +81,7 @@ impl Widget for &App {
let mut x_idx: usize = 0;
let mut y_idx: usize = 0;
if x != 0 {
x_idx = x as usize -1 + self.screen.scroll_x();
x_idx = x as usize - 1 + self.screen.scroll_x();
}
if y != 0 {
y_idx = y as usize - 1 + self.screen.scroll_y();
@@ -93,9 +96,9 @@ impl Widget for &App {
/// Center the text "99 " -> " 99 "
fn center_text(text: &str, avaliable_space: i32) -> String {
let margin = avaliable_space - text.len() as i32;
let margin = margin/2;
let l_margin = (0..margin).into_iter().map(|_| ' ').collect::<String>();
let r_margin = (0..(margin-(l_margin.len() as i32))).into_iter().map(|_| ' ').collect::<String>();
let margin = margin / 2;
let l_margin = (0..margin).into_iter().map(|_| ' ').collect::<String>();
let r_margin = (0..(margin - (l_margin.len() as i32))).into_iter().map(|_| ' ').collect::<String>();
format!("{l_margin}{text}{r_margin}")
}
@@ -214,7 +217,7 @@ impl Widget for &App {
}
// If this is the row header column
let area = if x==0 && y != 0 {
let area = if x == 0 && y != 0 {
Rect::new(x_off, y_off, row_header_width, cell_height)
} else if let Some(suggestion) = suggest_upper_bound {
let max_available_width = area.width - x_off;
@@ -387,17 +390,20 @@ impl App {
event::KeyCode::Enter => {
let v = editor.as_string();
// try to insert as a float
if let Ok(v) = v.parse::<f64>() {
self.grid.set_cell_raw(self.grid.cursor(), Some(v));
} else {
// if you can't, then insert as a string
if !v.is_empty() {
self.grid.set_cell_raw(self.grid.cursor(), Some(v));
let cursor = self.grid.cursor();
self.grid.transact_on_grid(|grid| {
// try to insert as a float
if let Ok(v) = v.parse::<f64>() {
grid.set_cell_raw(cursor, Some(v));
} else {
self.grid.set_cell_raw::<CellType>(self.grid.cursor(), None);
// if you can't, then insert as a string
if !v.is_empty() {
grid.set_cell_raw(cursor, Some(v.to_owned()));
} else {
grid.set_cell_raw::<CellType>(cursor, None);
}
}
}
});
self.mode = Mode::Normal;
}

View File

@@ -18,12 +18,7 @@ pub struct Clipboard {
impl Clipboard {
pub fn new() -> Self {
Self {
clipboard: Vec::new(),
last_paste_cell: (0, 0),
momentum: (0, 1),
source_cell: (0, 0),
}
Self { clipboard: Vec::new(), last_paste_cell: (0, 0), momentum: (0, 1), source_cell: (0, 0) }
}
/// Panics if clipboard is 0 length (if you call after you
@@ -49,25 +44,28 @@ impl Clipboard {
// cursor
let (cx, cy) = into.cursor();
// iterate thru the clipbaord's cells
for (x, row) in self.clipboard.iter().enumerate() {
for (y, cell) in row.iter().enumerate() {
let idx = (x + cx, y + cy);
let cursor = into.cursor();
into.transact_on_grid(|grid| {
// iterate thru the clipbaord's cells
for (x, row) in self.clipboard.iter().enumerate() {
for (y, cell) in row.iter().enumerate() {
let idx = (x + cx, y + cy);
if translate {
if let Some(cell) = cell {
let trans = cell.translate_cell(self.source_cell, into.cursor());
into.set_cell_raw(idx, Some(trans));
if translate {
if let Some(cell) = cell {
let trans = cell.translate_cell(self.source_cell, cursor);
grid.set_cell_raw(idx, Some(trans));
} else {
// The cell at this location doesn't exist (empty)
grid.set_cell_raw::<CellType>(idx, None);
}
} else {
// The cell at this location doesn't exist (empty)
into.set_cell_raw::<CellType>(idx, None);
// translate = false
grid.set_cell_raw::<CellType>(idx, cell.clone());
}
} else {
// translate = false
into.set_cell_raw::<CellType>(idx, cell.clone());
}
}
}
});
let (lx, ly) = self.last_paste_cell;
self.momentum = (cx as i32 - lx as i32, cy as i32 - ly as i32);
@@ -109,16 +107,19 @@ impl Clipboard {
// size the clipboard appropriately
self.clipboard.clear();
// clone data into clipboard
for x in low_x..=hi_x {
let mut col = Vec::new();
for y in low_y..=hi_y {
let a = from.get_cell_raw(x, y);
col.push(a.clone());
from.set_cell_raw::<CellType>((x, y), None);
from.transact_on_grid(|grid| {
// clone data into clipboard
for x in low_x..=hi_x {
let mut col = Vec::new();
for y in low_y..=hi_y {
let a = grid.get_cell_raw(x, y);
col.push(a.clone());
grid.set_cell_raw::<CellType>((x, y), None);
}
self.clipboard.push(col);
}
self.clipboard.push(col);
}
});
self.last_paste_cell = (low_x, low_y);
}
}
@@ -394,5 +395,4 @@ fn copy_paste_range_in_function() {
let a = app.grid.get_cell("B1").as_ref().expect("Should've been set by paste");
assert_eq!(a.to_string(), "=sum(A:A)");
}

View File

@@ -7,10 +7,10 @@ use std::{
use evalexpr::*;
use crate::app::{
logic::{
calc::internal::CellGrid, cell::{CSV_DELIMITER, CellType}, ctx
}
use crate::app::logic::{
calc::internal::CellGrid,
cell::{CSV_DELIMITER, CellType},
ctx,
};
#[cfg(test)]
@@ -154,14 +154,17 @@ impl Grid {
let mut buf = String::new();
file.read_to_string(&mut buf)?;
for (yi, line) in buf.lines().enumerate() {
let cells = Self::parse_csv_line(line);
for (xi, cell) in cells.into_iter().enumerate() {
// This gets automatically duck-typed
grid.set_cell_raw((xi, yi), cell);
grid.transact_on_grid(|grid| {
for (yi, line) in buf.lines().enumerate() {
let cells = Self::parse_csv_line(line);
for (xi, cell) in cells.into_iter().enumerate() {
// This gets automatically duck-typed
grid.set_cell_raw((xi, yi), cell);
}
}
}
});
// force dirty back off, we just read the data so it's gtg
grid.dirty = false;
@@ -236,14 +239,14 @@ impl Grid {
&mut self.grid_history[self.current_grid]
}
fn undo(&mut self) {
self.current_grid.saturating_sub(1);
pub fn undo(&mut self) {
self.current_grid = self.current_grid.saturating_sub(1);
}
fn redo(&mut self) {
pub fn redo(&mut self) {
self.current_grid += 1;
}
fn transact_on_grid<F>(&mut self, mut action: F)
pub fn transact_on_grid<F>(&mut self, mut action: F)
where
F: FnMut(&mut CellGrid) -> (),
{
@@ -253,10 +256,10 @@ impl Grid {
self.current_grid += 1;
// delete the other fork of the history
for i in self.current_grid+1..self.grid_history.len() {
for i in self.current_grid + 1..self.grid_history.len() {
self.grid_history.remove(i);
}
action(&mut self.grid_history[self.current_grid]);
self.dirty = true;
@@ -505,19 +508,11 @@ impl Grid {
/// transactions on the grid instead of direct access.
pub fn set_cell<T: Into<CellType>>(&mut self, cell_id: &str, val: T) {
if let Some(loc) = Self::parse_to_idx(cell_id) {
self.set_cell_raw(loc, Some(val));
self.get_grid_mut().set_cell_raw(loc, Some(val))
}
self.dirty = true;
}
#[deprecated]
/// You should get the grid then transact on the grid it's self
pub fn set_cell_raw<T: Into<CellType>>(&mut self, (x, y): (usize, usize), val: Option<T>) {
// TODO check oob
self.get_grid_mut().set_cell_raw((x,y), val.map(|v| v.into()));
self.dirty = true;
}
/// Get cells via text like:
/// A6,
/// F0,
@@ -533,7 +528,7 @@ impl Grid {
if x >= LEN || y >= LEN {
return &None;
}
&self.get_grid().get_cell_raw(x,y)
&self.get_grid().get_cell_raw(x, y)
}
pub fn num_to_char(idx: usize) -> String {
@@ -651,7 +646,7 @@ fn saving_neoscim() {
fn cell_strings() {
let mut grid = Grid::new();
assert!(&grid.get_grid().get_cell_raw(0,0).is_none());
assert!(&grid.get_grid().get_cell_raw(0, 0).is_none());
grid.set_cell("A0", "Hello".to_string());
assert!(grid.get_cell("A0").is_some());

View File

@@ -2,7 +2,8 @@ use std::{
cmp::{max, min},
fmt::Display,
fs,
path::PathBuf, process::Command,
path::PathBuf,
process::Command,
};
use ratatui::{
@@ -153,11 +154,13 @@ impl Mode {
let mut save_range = |to: &str| {
let mut g = Grid::new();
for (i, x) in (low_x..=hi_x).enumerate() {
for (j, y) in (low_y..=hi_y).enumerate() {
g.set_cell_raw((i, j), app.grid.get_cell_raw(x, y).clone());
g.transact_on_grid(|grid| {
for (i, x) in (low_x..=hi_x).enumerate() {
for (j, y) in (low_y..=hi_y).enumerate() {
grid.set_cell_raw((i, j), grid.get_cell_raw(x, y).clone());
}
}
}
});
if let Err(_e) = g.save_to(to) {
app.msg = StatusMessage::error("Failed to save file");
}
@@ -171,22 +174,24 @@ impl Mode {
}
}
}
return "unknown"
return "unknown";
};
match args[0] {
"f" | "fill" => {
for (i, x) in (low_x..=hi_x).enumerate() {
for (j, y) in (low_y..=hi_y).enumerate() {
let arg = args.get(1)
.map(|s| s.replace("xi", &i.to_string()))
.map(|s| s.replace("yi", &j.to_string()))
.map(|s| s.replace("x", &x.to_string()))
.map(|s| s.replace("y", &y.to_string()))
;
app.grid.set_cell_raw((x,y), arg);
app.grid.transact_on_grid(|grid| {
for (i, x) in (low_x..=hi_x).enumerate() {
for (j, y) in (low_y..=hi_y).enumerate() {
let arg = args
.get(1)
.map(|s| s.replace("xi", &i.to_string()))
.map(|s| s.replace("yi", &j.to_string()))
.map(|s| s.replace("x", &x.to_string()))
.map(|s| s.replace("y", &y.to_string()));
grid.set_cell_raw((x, y), arg);
}
}
}
});
app.mode = Mode::Normal
}
@@ -202,11 +207,7 @@ impl Mode {
// Use gnuplot to plot the selected data.
// * Temp data will be stored in /tmp/
// * Output will either be plot.png or a name that you pass in
let output_filename = if let Some(arg1) = args.get(1) {
arg1
} else {
"plot.png"
};
let output_filename = if let Some(arg1) = args.get(1) { arg1 } else { "plot.png" };
save_range("/tmp/plot.csv");
let plot = include_str!("../../template.gnuplot");
@@ -217,10 +218,12 @@ impl Mode {
let s = s.replace("$OUTPUT", "/tmp/output.png");
let _ = fs::write("/tmp/plot.p", s);
let cmd_res= Command::new("gnuplot").arg("/tmp/plot.p").output();
let cmd_res = Command::new("gnuplot").arg("/tmp/plot.p").output();
if let Err(err) = cmd_res {
match err.kind() {
std::io::ErrorKind::NotFound => app.msg = StatusMessage::error("Error - Is gnuplot installed?"),
std::io::ErrorKind::NotFound => {
app.msg = StatusMessage::error("Error - Is gnuplot installed?")
}
_ => app.msg = StatusMessage::error(format!("{err}")),
};
} else {
@@ -276,7 +279,7 @@ impl Mode {
// Go to bottom of column
'G' => {
let (x, _) = app.grid.cursor();
app.grid.mv_cursor_to(x, super::logic::calc::LEN,);
app.grid.mv_cursor_to(x, super::logic::calc::LEN);
return;
}
// edit cell
@@ -319,6 +322,11 @@ impl Mode {
app.mode = Mode::Command(Chord::new(':'))
}
}
// undo
'u' => {
app.grid.undo();
}
// paste
'p' => {
app.clipboard.paste(&mut app.grid, true);
app.grid.apply_momentum(app.clipboard.momentum());
@@ -398,7 +406,7 @@ impl Mode {
let (_, y_height) = app.screen.get_screen_size(&app.vars);
let y_origin = app.screen.scroll_y();
app.grid.mv_cursor_to(x, y_origin+y_height);
app.grid.mv_cursor_to(x, y_origin + y_height);
app.mode = Mode::Normal;
return;
}
@@ -408,7 +416,7 @@ impl Mode {
let (x_width, _) = app.screen.get_screen_size(&app.vars);
let x_origin = app.screen.scroll_x();
app.grid.mv_cursor_to(x_origin+x_width, y);
app.grid.mv_cursor_to(x_origin + x_width, y);
app.mode = Mode::Normal;
}
// Go to the left edge of the current window
@@ -508,9 +516,7 @@ pub struct Chord {
impl From<String> for Chord {
fn from(value: String) -> Self {
let b = value.as_bytes().iter().map(|f| *f as char).collect();
Chord {
buf: b,
}
Chord { buf: b }
}
}
@@ -519,9 +525,7 @@ impl Chord {
let mut buf = Vec::new();
buf.push(inital);
Self {
buf,
}
Self { buf }
}
pub fn backspace(&mut self) {