add ui
This commit is contained in:
343
src/calc.rs
Normal file
343
src/calc.rs
Normal file
@@ -0,0 +1,343 @@
|
||||
use std::{fmt::Display, thread::yield_now};
|
||||
|
||||
use evalexpr::*;
|
||||
use ratatui::{
|
||||
layout::{Constraint, Layout, Rect}, style::{Style, palette::material::WHITE, *}, widgets::{Paragraph, Widget}
|
||||
};
|
||||
|
||||
use crate::ctx;
|
||||
|
||||
// if this is very large at all it will overflow the stack
|
||||
const LEN: usize = 100;
|
||||
|
||||
pub struct Grid {
|
||||
// a b c ...
|
||||
// 0
|
||||
// 1
|
||||
// 2
|
||||
// ...
|
||||
cells: [[Option<Box<dyn Cell>>; LEN]; LEN],
|
||||
/// (X, Y)
|
||||
pub selected_cell: (usize, usize),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Grid {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Grid")
|
||||
.field("cells", &"Too many to print")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
pub fn new() -> Self {
|
||||
// TODO this needs to be moved to the heap
|
||||
let b: [[Option<Box<dyn Cell>>; LEN]; LEN] =
|
||||
core::array::from_fn(|_| core::array::from_fn(|_| None));
|
||||
|
||||
Self {
|
||||
cells: b,
|
||||
selected_cell: (0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn evaluate(&self, mut eq: &str) -> Option<f64> {
|
||||
if eq.starts_with('=') {
|
||||
eq = &eq[1..];
|
||||
} else {
|
||||
// Should be evaluating an equation
|
||||
return None
|
||||
}
|
||||
|
||||
let ctx = ctx::CallbackContext::new(&self);
|
||||
// let mut ctx = HashMapContext::<DefaultNumericTypes>::new();
|
||||
|
||||
match eval_with_context(eq, &ctx) {
|
||||
Ok(e) => {
|
||||
let val = e.as_float().expect("Should be float");
|
||||
return Some(val);
|
||||
}
|
||||
Err(e) => match e {
|
||||
EvalexprError::VariableIdentifierNotFound(e) => {
|
||||
// panic!("Will not be able to parse this equation, cell {e} not found")
|
||||
return None
|
||||
}
|
||||
_ => panic!("{}", e),
|
||||
},
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_to_idx(i: &str) -> (usize, usize) {
|
||||
let chars = i
|
||||
.chars()
|
||||
.take_while(|c| c.is_alphabetic())
|
||||
.collect::<Vec<char>>();
|
||||
let nums = i
|
||||
.chars()
|
||||
.skip(chars.len())
|
||||
.take_while(|c| c.is_numeric())
|
||||
.collect::<String>();
|
||||
|
||||
// get the x index from the chars
|
||||
let x_idx = chars
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(Self::char_to_idx)
|
||||
.fold(0, |a, b| a + b);
|
||||
|
||||
// get the y index from the numbers
|
||||
let y_idx = nums
|
||||
.parse::<usize>()
|
||||
.expect("Got non-number character after sorting for just numeric characters");
|
||||
|
||||
(x_idx, y_idx)
|
||||
}
|
||||
|
||||
pub fn set_cell<T: Into<Box<dyn Cell>>>(&mut self, cell_id: &str, val: T) {
|
||||
let loc = Self::parse_to_idx(cell_id);
|
||||
self.set_cell_raw(loc, val);
|
||||
}
|
||||
|
||||
pub fn set_cell_raw<T: Into<Box<dyn Cell>>>(&mut self, (x,y): (usize, usize), val: T) {
|
||||
// TODO check oob
|
||||
self.cells[x][y] = Some(val.into());
|
||||
}
|
||||
|
||||
/// Get cells via text like:
|
||||
/// A6,
|
||||
/// F0,
|
||||
/// etc
|
||||
pub fn get_cell(&self, cell_id: &str) -> &Option<Box<dyn Cell>> {
|
||||
let (x, y) = Self::parse_to_idx(cell_id);
|
||||
self.get_cell_raw(x, y)
|
||||
}
|
||||
|
||||
pub fn get_cell_raw(&self, x: usize, y: usize) -> &Option<Box<dyn Cell>> {
|
||||
// TODO check oob
|
||||
&self.cells[x][y]
|
||||
}
|
||||
|
||||
// this function has unit tests
|
||||
fn char_to_idx((idx, c): (usize, &char)) -> usize {
|
||||
(c.to_ascii_lowercase() as usize - 97) + 26 * idx
|
||||
}
|
||||
|
||||
fn num_to_char(idx: usize) -> String {
|
||||
/*
|
||||
A = 0
|
||||
AA = 26
|
||||
AAA = Not going to worry about it yet
|
||||
*/
|
||||
|
||||
let mut word: [char; 2] = [' '; 2];
|
||||
|
||||
if idx >= 26 {
|
||||
word[0]= ((idx/26) + 65 -1) as u8 as char;
|
||||
}
|
||||
word[1]= ((idx%26) + 65) as u8 as char;
|
||||
|
||||
word.iter().collect()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Default for Grid {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Cell {
|
||||
/// Important! This is IS NOT the return value of an equation.
|
||||
/// This is the raw equation it's self.
|
||||
fn as_raw_string(&self) -> String;
|
||||
fn can_be_number(&self) -> bool;
|
||||
fn as_num(&self) -> f64;
|
||||
fn is_equation(&self) -> bool {
|
||||
self.as_raw_string().starts_with('=')
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for dyn Cell {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
|
||||
let disp = if self.can_be_number() {
|
||||
self.as_num().to_string()
|
||||
} else {
|
||||
self.as_raw_string()
|
||||
};
|
||||
|
||||
write!(f, "{disp}")
|
||||
}
|
||||
}
|
||||
|
||||
impl Cell for f64 {
|
||||
fn as_raw_string(&self) -> String {
|
||||
ToString::to_string(self)
|
||||
}
|
||||
|
||||
fn can_be_number(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn as_num(&self) -> f64 {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Box<dyn Cell>> for f64 {
|
||||
fn into(self) -> Box<dyn Cell> {
|
||||
Box::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Box<dyn Cell>> for String {
|
||||
fn into(self) -> Box<dyn Cell> {
|
||||
Box::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Cell for String {
|
||||
fn as_raw_string(&self) -> String {
|
||||
ToString::to_string(self)
|
||||
}
|
||||
|
||||
fn can_be_number(&self) -> bool {
|
||||
// checking if the string is an equation
|
||||
self.starts_with('=')
|
||||
}
|
||||
|
||||
fn as_num(&self) -> f64 {
|
||||
unimplemented!("&str cannot be used in a numeric context")
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cells() {
|
||||
let mut grid = Grid::new();
|
||||
|
||||
assert!(&grid.cells[0][0].is_none());
|
||||
grid.set_cell("A0", "Hello".to_string());
|
||||
assert!(grid.get_cell("A0").is_some());
|
||||
|
||||
assert_eq!(
|
||||
grid.get_cell("A0").as_ref().unwrap().as_raw_string(),
|
||||
String::from("Hello")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_to_i() {
|
||||
assert_eq!(Grid::char_to_idx((0, &'a')), 0);
|
||||
assert_eq!(Grid::char_to_idx((0, &'A')), 0);
|
||||
assert_eq!(Grid::char_to_idx((0, &'z')), 25);
|
||||
assert_eq!(Grid::char_to_idx((0, &'Z')), 25);
|
||||
assert_eq!(Grid::char_to_idx((1, &'a')), 26);
|
||||
|
||||
assert_eq!(Grid::parse_to_idx("A0"), (0, 0));
|
||||
assert_eq!(Grid::parse_to_idx("AA0"), (26, 0));
|
||||
assert_eq!(Grid::parse_to_idx("A1"), (0, 1));
|
||||
assert_eq!(Grid::parse_to_idx("A10"), (0, 10));
|
||||
assert_eq!(Grid::parse_to_idx("Aa10"), (26, 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn i_to_c() {
|
||||
assert_eq!(Grid::num_to_char(0).trim(), "A");
|
||||
assert_eq!(Grid::num_to_char(25).trim(), "Z");
|
||||
assert_eq!(Grid::num_to_char(26), "AA");
|
||||
assert_eq!(Grid::num_to_char(51), "AZ");
|
||||
assert_eq!(Grid::num_to_char(701), "ZZ");
|
||||
}
|
||||
|
||||
impl Widget for &Grid {
|
||||
fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer) {
|
||||
let len = LEN as u16;
|
||||
|
||||
let cell_height = 1;
|
||||
let cell_length = 5;
|
||||
|
||||
|
||||
let x_max = if area.width / cell_length > len {
|
||||
len - 1
|
||||
} else {
|
||||
area.width / cell_length
|
||||
};
|
||||
let y_max = if area.height / cell_height > len {
|
||||
len - 1
|
||||
} else {
|
||||
area.height / cell_height
|
||||
};
|
||||
|
||||
for x in 0..x_max {
|
||||
for y in 0..y_max {
|
||||
let mut display = String::new();
|
||||
let mut style = Style::new().white();
|
||||
|
||||
const ORANGE1: Color = Color::Rgb(200, 160, 0);
|
||||
const ORANGE2: Color = Color::Rgb(180, 130, 0);
|
||||
|
||||
match (x == 0, y == 0) {
|
||||
(true, true) => {},
|
||||
(true, false) => {
|
||||
// row names
|
||||
display = y.to_string();
|
||||
|
||||
let bg = if y%2==0 {
|
||||
ORANGE1
|
||||
} else {
|
||||
ORANGE2
|
||||
};
|
||||
style = Style::new().fg(Color::White).bg(bg);
|
||||
|
||||
},
|
||||
(false, true) => {
|
||||
// column names
|
||||
display = Grid::num_to_char(x as usize -1);
|
||||
|
||||
let bg = if x%2==0 {
|
||||
ORANGE1
|
||||
} else {
|
||||
ORANGE2
|
||||
};
|
||||
|
||||
style = Style::new().fg(Color::White).bg(bg)
|
||||
},
|
||||
(false, false) => {
|
||||
// minus 1 because of header cells
|
||||
let x_idx = x as usize -1;
|
||||
let y_idx = y as usize -1;
|
||||
|
||||
if let Some(cell) = self.get_cell_raw(x_idx, y_idx) {
|
||||
display = cell.as_raw_string();
|
||||
|
||||
if cell.can_be_number() {
|
||||
if let Some(val) = self.evaluate(&cell.as_raw_string()) {
|
||||
display = val.to_string();
|
||||
} else {
|
||||
// broken formulas
|
||||
if cell.is_equation() {
|
||||
style = Style::new().underline_color(Color::Red).add_modifier(Modifier::UNDERLINED)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (x_idx, y_idx) == self.selected_cell {
|
||||
style = Style::new().fg(Color::Black).bg(Color::White);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let area = Rect::new(
|
||||
area.x + (x * cell_length),
|
||||
area.y + (y * cell_height),
|
||||
cell_length,
|
||||
cell_height,
|
||||
);
|
||||
|
||||
Paragraph::new(display).style(style).render(area, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
113
src/ctx.rs
113
src/ctx.rs
@@ -4,17 +4,16 @@ use evalexpr::{error::EvalexprResultValue, *};
|
||||
|
||||
use crate::Grid;
|
||||
|
||||
pub struct CallbackContext<'a, NumericTypes: EvalexprNumericTypes = DefaultNumericTypes> {
|
||||
variables: Rc<&'a Grid>,
|
||||
functions: HashMap<String, Function<NumericTypes>>,
|
||||
pub struct CallbackContext<'a, T: EvalexprNumericTypes = DefaultNumericTypes> {
|
||||
variables: &'a Grid,
|
||||
functions: HashMap<String, Function<T>>,
|
||||
|
||||
/// True if builtin functions are disabled.
|
||||
without_builtin_functions: bool,
|
||||
}
|
||||
|
||||
impl<'a, NumericTypes: EvalexprNumericTypes> CallbackContext<'a, NumericTypes> {
|
||||
/// Constructs a `HashMapContext` with no mappings.
|
||||
pub fn new(grid: Rc<&'a Grid>) -> Self {
|
||||
pub fn new(grid: &'a Grid) -> Self {
|
||||
Self {
|
||||
variables: grid,
|
||||
functions: Default::default(),
|
||||
@@ -22,55 +21,30 @@ impl<'a, NumericTypes: EvalexprNumericTypes> CallbackContext<'a, NumericTypes> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes all variables from the context.
|
||||
/// This allows to reuse the context without allocating a new HashMap.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # use evalexpr::*;
|
||||
///
|
||||
/// let mut context = HashMapContext::<DefaultNumericTypes>::new();
|
||||
/// context.set_value("abc".into(), "def".into()).unwrap();
|
||||
/// assert_eq!(context.get_value("abc"), Some(&("def".into())));
|
||||
/// context.clear_variables();
|
||||
/// assert_eq!(context.get_value("abc"), None);
|
||||
/// ```
|
||||
pub fn clear_variables(&mut self) {
|
||||
()
|
||||
}
|
||||
|
||||
/// Removes all functions from the context.
|
||||
/// This allows to reuse the context without allocating a new HashMap.
|
||||
pub fn clear_functions(&mut self) {
|
||||
self.functions.clear()
|
||||
}
|
||||
|
||||
/// Removes all variables and functions from the context.
|
||||
/// This allows to reuse the context without allocating a new HashMap.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # use evalexpr::*;
|
||||
///
|
||||
/// let mut context = HashMapContext::<DefaultNumericTypes>::new();
|
||||
/// context.set_value("abc".into(), "def".into()).unwrap();
|
||||
/// assert_eq!(context.get_value("abc"), Some(&("def".into())));
|
||||
/// context.clear();
|
||||
/// assert_eq!(context.get_value("abc"), None);
|
||||
/// ```
|
||||
pub fn clear(&mut self) {
|
||||
self.clear_variables();
|
||||
self.clear_functions();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, NumericTypes: EvalexprNumericTypes> Context for CallbackContext<'a, NumericTypes> {
|
||||
type NumericTypes = NumericTypes;
|
||||
impl<'a> Context for CallbackContext<'a, DefaultNumericTypes> {
|
||||
type NumericTypes = DefaultNumericTypes;
|
||||
|
||||
fn get_value(&self, identifier: &str) -> Option<&Value<Self::NumericTypes>> {
|
||||
return Some(4.);
|
||||
fn get_value(&self, identifier: &str) -> Option<Value<Self::NumericTypes>> {
|
||||
if let Some(v) = self.variables.get_cell(identifier) {
|
||||
if v.can_be_number() {
|
||||
return Some(Value::Float(v.as_num()));
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
fn call_function(
|
||||
@@ -88,67 +62,8 @@ impl<'a, NumericTypes: EvalexprNumericTypes> Context for CallbackContext<'a, Num
|
||||
fn set_builtin_functions_disabled(
|
||||
&mut self,
|
||||
disabled: bool,
|
||||
) -> EvalexprResult<(), NumericTypes> {
|
||||
) -> EvalexprResult<(), Self::NumericTypes> {
|
||||
self.without_builtin_functions = disabled;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, NumericTypes: EvalexprNumericTypes> ContextWithMutableVariables
|
||||
for CallbackContext<'a, NumericTypes>
|
||||
{
|
||||
fn set_value(
|
||||
&mut self,
|
||||
identifier: String,
|
||||
value: Value<Self::NumericTypes>,
|
||||
) -> EvalexprResult<(), NumericTypes> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_value(
|
||||
&mut self,
|
||||
identifier: &str,
|
||||
) -> EvalexprResult<Option<Value<Self::NumericTypes>>, Self::NumericTypes> {
|
||||
// Removes a value from the `self.variables`, returning the value at the key if the key was previously in the map.
|
||||
// Ok(self.variables.remove(identifier))
|
||||
todo!();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, NumericTypes: EvalexprNumericTypes> ContextWithMutableFunctions
|
||||
for CallbackContext<'a, NumericTypes>
|
||||
{
|
||||
fn set_function(
|
||||
&mut self,
|
||||
identifier: String,
|
||||
function: Function<NumericTypes>,
|
||||
) -> EvalexprResult<(), Self::NumericTypes> {
|
||||
self.functions.insert(identifier, function);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b, NumericTypes: EvalexprNumericTypes> IterateVariablesContext for CallbackContext<'b, NumericTypes> {
|
||||
type VariableIterator<'a>
|
||||
= std::iter::Map<
|
||||
std::collections::hash_map::Iter<'a, String, Value<NumericTypes>>,
|
||||
fn((&String, &Value<NumericTypes>)) -> (String, Value<NumericTypes>),
|
||||
>
|
||||
where
|
||||
Self: 'a;
|
||||
type VariableNameIterator<'a>
|
||||
= std::iter::Cloned<std::collections::hash_map::Keys<'a, String, Value<NumericTypes>>>
|
||||
where
|
||||
Self: 'a;
|
||||
|
||||
fn iter_variables(&self) -> Self::VariableIterator<'_> {
|
||||
todo!()
|
||||
// self.variables.iter().map(|(string, value)| (string.clone(), value.clone()))
|
||||
}
|
||||
|
||||
fn iter_variable_names(&self) -> Self::VariableNameIterator<'_> {
|
||||
todo!()
|
||||
// self.variables.keys().cloned()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
357
src/main.rs
357
src/main.rs
@@ -1,205 +1,198 @@
|
||||
// #![feature(impl_trait_in_bindings)]
|
||||
|
||||
mod calc;
|
||||
mod ctx;
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::io;
|
||||
|
||||
use evalexpr::*;
|
||||
use ratatui::{
|
||||
crossterm::event,
|
||||
layout::{Constraint, Layout},
|
||||
text::*,
|
||||
widgets::{Paragraph, Widget},
|
||||
*,
|
||||
};
|
||||
|
||||
// if this is very large at all it will overflow the stack
|
||||
const LEN: usize = 100;
|
||||
|
||||
struct Grid {
|
||||
// a b c ...
|
||||
// 0
|
||||
// 1
|
||||
// 2
|
||||
// ...
|
||||
cells: [[Option<Box<dyn Cell>>; LEN]; LEN],
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Grid {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Grid").field("cells", &"Too many to print").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
fn new() -> Self {
|
||||
let b: [[Option<Box<dyn Cell>>; LEN]; LEN] =
|
||||
core::array::from_fn(|_| core::array::from_fn(|_| None));
|
||||
|
||||
Self { cells: b }
|
||||
}
|
||||
|
||||
fn eval(&self, mut eq: &str) -> f64 {
|
||||
if eq.starts_with('=') {
|
||||
eq = &eq[1..];
|
||||
}
|
||||
|
||||
let mut ctx = ctx::CallbackContext::<DefaultNumericTypes>::new(Rc::new(self));
|
||||
// let mut ctx = HashMapContext::<DefaultNumericTypes>::new();
|
||||
|
||||
let val;
|
||||
loop {
|
||||
match eval_with_context(eq, &ctx) {
|
||||
Ok(e) => {
|
||||
val = e.as_float().expect("Should be float");
|
||||
break;
|
||||
}
|
||||
Err(e) => match e {
|
||||
// TODO this is kinda a slow way to do this, the equation will get parsed
|
||||
// multiple times. Might be good to modify the lib so that you can provide
|
||||
// a callback for variables that are not found.
|
||||
EvalexprError::VariableIdentifierNotFound(e) => {
|
||||
panic!("Will not be able to parse this equation, cell {e} not found")
|
||||
}
|
||||
_ => panic!("{}", e),
|
||||
},
|
||||
}
|
||||
}
|
||||
val
|
||||
}
|
||||
|
||||
fn parse_to_idx(i: &str) -> (usize, usize) {
|
||||
let chars = i
|
||||
.chars()
|
||||
.take_while(|c| c.is_alphabetic())
|
||||
.collect::<Vec<char>>();
|
||||
let nums = i
|
||||
.chars()
|
||||
.skip(chars.len())
|
||||
.take_while(|c| c.is_numeric())
|
||||
.collect::<String>();
|
||||
|
||||
// get the x index from the chars
|
||||
let x_idx = chars
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(Self::char_to_idx)
|
||||
.fold(0, |a, b| a + b);
|
||||
|
||||
// get the y index from the numbers
|
||||
let y_idx = nums
|
||||
.parse::<usize>()
|
||||
.expect("Got non-number character after sorting for just numeric characters");
|
||||
|
||||
(x_idx, y_idx)
|
||||
}
|
||||
|
||||
fn set_cell(&mut self, cell_id: &str, val: Box<dyn Cell>) {
|
||||
let (x, y) = Self::parse_to_idx(cell_id);
|
||||
// TODO check oob
|
||||
self.cells[x][y] = Some(val);
|
||||
}
|
||||
|
||||
/// Get cells via text like:
|
||||
/// A6
|
||||
/// F0
|
||||
fn get_cell(&self, cell_id: &str) -> &Option<Box<dyn Cell>> {
|
||||
let (x, y) = Self::parse_to_idx(cell_id);
|
||||
// TODO check oob
|
||||
&self.cells[x][y]
|
||||
}
|
||||
|
||||
// this function has unit tests
|
||||
fn char_to_idx((idx, c): (usize, &char)) -> usize {
|
||||
(c.to_ascii_lowercase() as usize - 97) + 26 * idx
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Grid {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
trait Cell {
|
||||
fn to_string(&self) -> String;
|
||||
fn can_be_number(&self) -> bool;
|
||||
fn as_num(&self) -> f32;
|
||||
fn is_eq(&self) -> bool {
|
||||
self.to_string().starts_with('=')
|
||||
}
|
||||
}
|
||||
|
||||
impl Cell for f32 {
|
||||
fn to_string(&self) -> String {
|
||||
ToString::to_string(self)
|
||||
}
|
||||
|
||||
fn can_be_number(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn as_num(&self) -> f32 {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl Cell for &str {
|
||||
fn to_string(&self) -> String {
|
||||
ToString::to_string(self)
|
||||
}
|
||||
|
||||
fn can_be_number(&self) -> bool {
|
||||
// checking if the string is an equation
|
||||
self.starts_with('=')
|
||||
}
|
||||
|
||||
fn as_num(&self) -> f32 {
|
||||
unimplemented!("&str cannot be used in a numeric context")
|
||||
}
|
||||
}
|
||||
use crate::calc::Grid;
|
||||
|
||||
#[test]
|
||||
fn test_math() {
|
||||
use evalexpr::*;
|
||||
|
||||
let mut grid = Grid::new();
|
||||
grid.set_cell("A0", Box::new(2.));
|
||||
grid.set_cell("B0", Box::new(1.));
|
||||
grid.set_cell("C0", Box::new("=A0+B0"));
|
||||
grid.set_cell("A0", 2.);
|
||||
grid.set_cell("B0", 1.);
|
||||
grid.set_cell("C0", "=A0+B0".to_string());
|
||||
|
||||
assert_eq!(eval("1+2").unwrap(), Value::Int(3));
|
||||
|
||||
let disp = &grid.get_cell("C0");
|
||||
if let Some(inner) = disp {
|
||||
if inner.is_eq() {
|
||||
println!("{}", inner.to_string());
|
||||
let display = grid.eval(&inner.to_string());
|
||||
assert_eq!(display, 3.);
|
||||
let cell_text = &grid.get_cell("C0");
|
||||
if let Some(text) = cell_text {
|
||||
if text.is_equation() {
|
||||
println!("{}", text.as_raw_string());
|
||||
let display = grid.evaluate(&text.as_raw_string());
|
||||
assert_eq!(display, Some(3.));
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("Should've found the value and returned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cells() {
|
||||
let mut grid = Grid::new();
|
||||
fn main() -> Result<(), std::io::Error> {
|
||||
let term = ratatui::init();
|
||||
let mut app = App::new();
|
||||
app.grid.set_cell("A0", 10.);
|
||||
app.grid.set_cell("B1", 10.);
|
||||
app.grid.set_cell("C2", "=A0+B1".to_string());
|
||||
|
||||
assert!(&grid.cells[0][0].is_none());
|
||||
grid.set_cell("A0", Box::new("Hello"));
|
||||
assert!(grid.get_cell("A0").is_some());
|
||||
|
||||
assert_eq!(
|
||||
grid.get_cell("A0").as_ref().unwrap().to_string(),
|
||||
String::from("Hello")
|
||||
);
|
||||
let res = app.run(term);
|
||||
ratatui::restore();
|
||||
return res;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_to_i() {
|
||||
assert_eq!(Grid::char_to_idx((0, &'a')), 0);
|
||||
assert_eq!(Grid::char_to_idx((0, &'A')), 0);
|
||||
assert_eq!(Grid::char_to_idx((0, &'z')), 25);
|
||||
assert_eq!(Grid::char_to_idx((0, &'Z')), 25);
|
||||
assert_eq!(Grid::char_to_idx((1, &'a')), 26);
|
||||
|
||||
assert_eq!(Grid::parse_to_idx("A0"), (0, 0));
|
||||
assert_eq!(Grid::parse_to_idx("AA0"), (26, 0));
|
||||
assert_eq!(Grid::parse_to_idx("A1"), (0, 1));
|
||||
assert_eq!(Grid::parse_to_idx("A10"), (0, 10));
|
||||
assert_eq!(Grid::parse_to_idx("Aa10"), (26, 10));
|
||||
struct App {
|
||||
exit: bool,
|
||||
grid: Grid,
|
||||
/// Buffer for key-chords
|
||||
chord_buf: String,
|
||||
editor: Option<Editor>,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("Only tests exist atm");
|
||||
impl Widget for &App {
|
||||
fn render(self, area: prelude::Rect, buf: &mut prelude::Buffer) {
|
||||
Paragraph::new("Status").render(area, buf);
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
exit: false,
|
||||
grid: Grid::new(),
|
||||
chord_buf: String::new(),
|
||||
editor: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&mut self, mut term: DefaultTerminal) -> Result<(), std::io::Error> {
|
||||
while !self.exit {
|
||||
term.draw(|frame| self.draw(frame))?;
|
||||
self.handle_events()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn draw(&self, frame: &mut Frame) {
|
||||
|
||||
let layout = Layout::default()
|
||||
.direction(layout::Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(1),
|
||||
Constraint::Min(1),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.split(frame.area());
|
||||
|
||||
if let Some(editor) = &self.editor {
|
||||
frame.render_widget(editor, layout[0]);
|
||||
} else {
|
||||
frame.render_widget(Paragraph::new("sc_rs"), layout[0]);
|
||||
}
|
||||
|
||||
frame.render_widget(&self.grid, layout[1]);
|
||||
frame.render_widget(self, layout[2]);
|
||||
}
|
||||
|
||||
fn handle_events(&mut self) -> io::Result<()> {
|
||||
match event::read()? {
|
||||
event::Event::Key(key_event) => match key_event.code {
|
||||
event::KeyCode::Enter => {
|
||||
if let Some(editor) = &self.editor {
|
||||
let loc= self.grid.selected_cell;
|
||||
|
||||
let val = editor.buf.trim().to_string();
|
||||
|
||||
// insert as number if at all possible
|
||||
if let Ok(val) = val.parse::<f64>() {
|
||||
self.grid.set_cell_raw(loc, val);
|
||||
} else {
|
||||
self.grid.set_cell_raw(loc, val);
|
||||
};
|
||||
|
||||
self.editor = None;
|
||||
}
|
||||
}
|
||||
event::KeyCode::Backspace => {
|
||||
if let Some(editor) = &mut self.editor {
|
||||
editor.buf.pop();
|
||||
}
|
||||
}
|
||||
event::KeyCode::F(_) => todo!(),
|
||||
event::KeyCode::Char(c) => {
|
||||
|
||||
if let Some(editor) = &mut self.editor {
|
||||
editor.buf += &c.to_string();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !self.chord_buf.is_empty() {}
|
||||
|
||||
match c {
|
||||
'q' => self.exit = true,
|
||||
// <
|
||||
'h' => self.grid.selected_cell.0 = self.grid.selected_cell.0.saturating_sub(1),
|
||||
// v
|
||||
'j' => self.grid.selected_cell.1 = self.grid.selected_cell.1.saturating_add(1),
|
||||
// ^
|
||||
'k' => self.grid.selected_cell.1 = self.grid.selected_cell.1.saturating_sub(1),
|
||||
// >
|
||||
'l' => self.grid.selected_cell.0 = self.grid.selected_cell.0.saturating_add(1),
|
||||
// edit cell
|
||||
'i' | 'a' => {
|
||||
let (x,y) = self.grid.selected_cell;
|
||||
let starting_val = if let Some(val) = self.grid.get_cell_raw(x, y) {
|
||||
val.as_raw_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
self.editor = Some(Editor::from(starting_val))
|
||||
},
|
||||
'I' => {/* insert col before */}
|
||||
'A' => {/* insert col after */}
|
||||
'o' => {/* insert row below */}
|
||||
'O' => {/* insert row above */}
|
||||
':' => {/* enter command mode */}
|
||||
c => {
|
||||
// start entering c for words
|
||||
self.chord_buf += &c.to_string();
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
event::Event::Paste(_) => todo!(),
|
||||
event::Event::Resize(_, _) => todo!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Editor {
|
||||
buf: String,
|
||||
cursor: usize,
|
||||
}
|
||||
|
||||
impl From<String> for Editor {
|
||||
fn from(value: String) -> Self {
|
||||
Self {
|
||||
buf: value.to_string(),
|
||||
cursor: value.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for &Editor {
|
||||
fn render(self, area: prelude::Rect, buf: &mut prelude::Buffer) {
|
||||
Paragraph::new(self.buf.clone()).render(area, buf);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user