Compare commits

...

3 Commits

Author SHA1 Message Date
d5ccb9b8c6 close #42 2025-11-14 15:30:36 -07:00
a03794e69f prepwork for #41 2025-11-14 14:26:04 -07:00
98215e42af update 2025-11-14 10:45:02 -07:00
5 changed files with 107 additions and 68 deletions

View File

@@ -3,22 +3,6 @@
*New* Spreadsheet Calculator Improved
Based loosely off sc-im (spreadsheet calculator improvised), which has dumb keybinds and not many features.
## Improvements from sc-im
* Cell type (string, function, value) are all "the same" and use polymorphism to detect what you are trying to do.
The logic is more or less:
```cpp
if value.can_be_a_number() {
return value.as_number()
} else if value.starts_with('=') {
return value.as_equation()
} else {
return value.as_string()
}
```
* Keybinds are closer to vim keying (i/a start inserting into a cell)
## Keybinds
@@ -141,6 +125,19 @@ if value.can_be_a_number() {
> Any time a function takes a variable amount of inputs, a range can be specified: `avg(B:B)`.
## Improvements from sc-im
* Cell type (string, function, value) are all "the same" and use polymorphism to detect what you are trying to do.
If the cell can be a number (parsed into a float) it will be, if not, then if the string starts with "=", then treats it as an equation, otherwise, it's a string.
* Cell references move with copy / paste
* =A0: Will translate
* =$A0: Will translate Y only
* =$A0: Will translate X only
* =$A$0: No translation
* Keybinds are closer to vim keying (i/a start inserting into a cell)
## FAQ:
* Every number is a float (or will end up as a float)

View File

@@ -1,8 +1,5 @@
use std::{
cmp::{max, min},
collections::HashMap,
io,
path::PathBuf,
cmp::{max, min}, collections::HashMap, fs, io, path::PathBuf, time::SystemTime
};
use ratatui::{
@@ -27,6 +24,7 @@ pub struct App {
pub grid: Grid,
pub mode: Mode,
pub file: Option<PathBuf>,
file_modified_date: SystemTime,
pub msg: StatusMessage,
pub vars: HashMap<String, String>,
pub screen: ScreenSpace,
@@ -211,13 +209,24 @@ impl App {
screen: ScreenSpace::new(),
marks: HashMap::new(),
clipboard: Clipboard::new(),
file_modified_date: SystemTime::now(),
}
}
pub fn new_with_file(file: impl Into<PathBuf> + Clone) -> std::io::Result<Self> {
let mut app = Self::new();
app.file = Some(file.clone().into());
app.grid = Grid::new_from_file(file.into())?;
let mut file = fs::OpenOptions::new().read(true).open(file.into())?;
let metadata = file.metadata()?;
// Not all systems support this, apparently.
if let Ok(time) = metadata.modified() {
app.file_modified_date = time;
} else {
// Default is to just assume it was modified when we opened it.
}
app.grid = Grid::new_from_file(&mut file)?;
Ok(app)
}

View File

@@ -1,8 +1,8 @@
use std::{
cmp::{max, min},
fs,
fs::{self, File},
io::{Read, Write},
path::PathBuf,
path::PathBuf
};
use evalexpr::*;
@@ -58,10 +58,9 @@ impl Grid {
}
}
pub fn new_from_file(path: impl Into<PathBuf>) -> std::io::Result<Self> {
pub fn new_from_file(file: &mut File) -> std::io::Result<Self> {
let mut grid = Self::new();
let mut file = fs::OpenOptions::new().read(true).open(path.into())?;
let mut buf = String::new();
file.read_to_string(&mut buf)?;
for (yi, line) in buf.lines().enumerate() {
@@ -937,3 +936,29 @@ fn insert_row_above_3() {
let cell = grid.get_cell("B1").as_ref().expect("Just set it");
assert_eq!(cell.to_string(), "=A1");
}
#[test]
fn cell_eval_depth() {
use crate::app::mode::*;
let mut app= App::new();
app.grid.set_cell("A0", 1.);
app.grid.set_cell("A1", "=A0+$A$0".to_string());
app.grid.mv_cursor_to(0, 1);
app.mode = Mode::Chord(Chord::new('y'));
Mode::process_key(&mut app, 'y');
Mode::process_key(&mut app, 'j');
app.mode = Mode::Chord(Chord::new('5'));
Mode::process_key(&mut app, 'p');
assert_eq!(app.grid.cursor(), (0, 7));
let c = app.grid.get_cell("A6").as_ref().expect("Just set it");
assert_eq!(c.to_string(), "=A5+$A$0");
let res = app.grid.evaluate(&c.to_string()).expect("Should evaluate");
assert_eq!(res, 7.);
}

View File

@@ -6,7 +6,8 @@ use crate::app::logic::{calc::Grid, cell::CellType};
pub struct CallbackContext<'a> {
variables: &'a Grid,
eval_depth: RwLock<usize>,
eval_breadcrumbs: RwLock<Vec<String>>,
compute_cache: RwLock<HashMap<String, Value>>,
functions: HashMap<String, Function<DefaultNumericTypes>>,
/// True if builtin functions are disabled.
@@ -139,10 +140,11 @@ impl<'a> CallbackContext<'a> {
pub fn new(grid: &'a Grid) -> Self {
Self {
eval_depth: RwLock::new(0),
variables: grid,
functions: Self::get_functions(),
without_builtin_functions: false,
eval_breadcrumbs: RwLock::new(Vec::new()),
compute_cache: RwLock::new(HashMap::new()),
}
}
}
@@ -151,27 +153,46 @@ impl<'a> Context for CallbackContext<'a> {
type NumericTypes = DefaultNumericTypes;
fn get_value(&self, identifier: &str) -> Option<Value<Self::NumericTypes>> {
const RECURSION_DEPTH_LIMIT: usize = 20;
// check cache
if let Ok(cc) = self.compute_cache.read() {
if let Some(hit) = cc.get(identifier) {
return Some(hit.clone());
}
}
if let Ok(mut trail) = self.eval_breadcrumbs.write() {
let find = trail.iter().filter(|id| *id == identifier).collect::<Vec<&String>>();
if find.len() > 0 {
// recursion detected
return None;
} else {
trail.push(identifier.to_owned(), );
}
}
let pre_return = |v: Value| {
if let Ok(mut cc) = self.compute_cache.write() {
cc.insert(identifier.to_owned(), v.clone());
}
Some(v)
};
if let Some(v) = self.variables.get_cell(identifier) {
match v {
CellType::Number(n) => return Some(Value::Float(n.to_owned())),
CellType::String(s) => return Some(Value::String(s.to_owned())),
CellType::Equation(eq) => {
if let Ok(mut depth) = self.eval_depth.write() {
*depth += 1;
if *depth > RECURSION_DEPTH_LIMIT {
return None;
}
} else {
// It would be unsafe to continue to process without knowing how
// deep we've gone.
return None;
}
CellType::Number(n) => {
return pre_return(Value::Float(n.to_owned()));
},
CellType::String(s) => {
return pre_return(Value::String(s.to_owned()));
},
CellType::Equation(eq) => {
// remove the equals sign from the beginning, as that
// tries to set variables with our evaluation lib
match eval_with_context(&eq[1..], self) {
Ok(e) => return Some(e),
Ok(e) => {
return pre_return(e)
},
Err(e) => {
match e {
EvalexprError::VariableIdentifierNotFound(_) => {
@@ -196,14 +217,6 @@ impl<'a> Context for CallbackContext<'a> {
CellType::Number(e) => vals.push(Value::Float(*e)),
CellType::String(s) => vals.push(Value::String(s.to_owned())),
CellType::Equation(eq) => {
if let Ok(mut depth) = self.eval_depth.write() {
*depth += 1;
if *depth > RECURSION_DEPTH_LIMIT {
return None;
}
} else {
return None;
}
if let Ok(val) = eval_with_context(&eq[1..], self) {
vals.push(val);
}
@@ -239,8 +252,6 @@ impl<'a> Context for CallbackContext<'a> {
}
}
/// DOES NOT EVALUATE EQUATIONS!!
///
/// This is used as a pseudo-context, just used for
@@ -259,18 +270,10 @@ impl ExtractionContext {
}
}
pub fn dump_vars(&self) -> Vec<String> {
if let Ok(r) = self.var_registry.read() {
r.clone()
} else {
Vec::new()
}
if let Ok(r) = self.var_registry.read() { r.clone() } else { Vec::new() }
}
pub fn dump_fns(&self) -> Vec<String> {
if let Ok(r) = self.fn_registry.read() {
r.clone()
} else {
Vec::new()
}
if let Ok(r) = self.fn_registry.read() { r.clone() } else { Vec::new() }
}
}
@@ -280,7 +283,9 @@ impl Context for ExtractionContext {
fn get_value(&self, identifier: &str) -> Option<Value<Self::NumericTypes>> {
if let Ok(mut registry) = self.var_registry.write() {
registry.push(identifier.to_owned());
} else { panic!("The RwLock should always be write-able") }
} else {
panic!("The RwLock should always be write-able")
}
Some(Value::Int(1))
}
@@ -293,7 +298,9 @@ impl Context for ExtractionContext {
let _ = argument;
if let Ok(mut registry) = self.fn_registry.write() {
registry.push(identifier.to_owned())
} else { panic!("The RwLock should always be write-able") }
} else {
panic!("The RwLock should always be write-able")
}
// Ok(Value::Int(1))
unimplemented!("Extracting function identifier not implemented yet")
}

View File

@@ -1,7 +1,5 @@
use std::{
cmp::{max, min},
fmt::Display,
path::PathBuf,
cmp::{max, min}, fmt::Display, fs, path::PathBuf
};
use ratatui::{
@@ -83,6 +81,9 @@ impl Mode {
}
};
// TODO Check if the file exists, but the program wasn't opened with it. We might be accidentally overwriting something else.
// let mut file = fs::OpenOptions::new().write(true).append(false).truncate(true).create(true).open(path)?;
if let Err(e) = app.grid.save_to(&path) {
app.msg = StatusMessage::error(format!("{e}"));
} else {