diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-07-25 00:40:37 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-07-25 00:40:37 +0200 |
| commit | 58b305b9f6d13007d2ea62775054c95177f81092 (patch) | |
| tree | 2123cb5379aa69476b1e549e0bcacc08d67fba71 /src/sheet/mod.rs | |
first sketch
Diffstat (limited to 'src/sheet/mod.rs')
| -rw-r--r-- | src/sheet/mod.rs | 98 |
1 files changed, 98 insertions, 0 deletions
diff --git a/src/sheet/mod.rs b/src/sheet/mod.rs new file mode 100644 index 0000000..015e3d8 --- /dev/null +++ b/src/sheet/mod.rs @@ -0,0 +1,98 @@ +use cell::{Cell, CellRef}; +use mlua::{IntoLua, UserData, Value}; +use register::{Register, SheetId}; + +pub mod cell; +pub mod register; + +#[derive(Debug, Default, Clone)] +pub struct Sheet { + id: register::SheetId, + rows: Vec<Vec<Cell>>, +} + +impl Sheet { + pub(self) fn new(width: usize, height: usize, id: register::SheetId) -> Self { + Self { + id, + rows: vec![vec![Cell::new_empty(); width]; height], + } + } + + pub fn set_cell(&mut self, row: usize, column: usize, cell: Cell) { + if row < self.height() && column < self.width() { + self.rows[row][column] = cell + } + } + + pub fn get_cell<'a>(&'a self, row: usize, column: usize) -> Option<&'a Cell> { + if let Some(r) = self.rows.get(row) { + if let Some(_) = r.get(column) { + return Some(&self.rows[row][column]); + } + } + + None + } + + pub fn get_ref(&self, row: usize, column: usize) -> Option<CellRef> { + CellRef::new(self.id, row, column) + } + + pub fn height(&self) -> usize { + self.rows.len() + } + + pub fn set_height(&mut self, mut height: usize) { + height = height.max(1); + self.rows + .resize(height, vec![Cell::new_empty(); self.width()]) + } + + pub fn width(&self) -> usize { + self.rows.get(0).map(|r| r.len()).unwrap_or(1) + } + + pub fn set_width(&mut self, mut width: usize) { + width = width.max(1); + for row in self.rows.iter_mut() { + row.resize(width, Cell::new_empty()); + } + } + + pub fn id(&self) -> register::SheetId { + self.id + } +} + +struct SheetLuaRef { + id: SheetId, +} + +impl SheetLuaRef { + pub fn new(id: SheetId) -> Self { + Self { id } + } +} + +impl UserData for SheetLuaRef { + fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(fields: &mut F) { + fields.add_field_method_get("width", |_, luaref| { + Ok(Register::get(luaref.id).unwrap().read().unwrap().width()) + }); + + fields.add_field_method_get("height", |_, luaref| { + Ok(Register::get(luaref.id).unwrap().read().unwrap().height()) + }); + } + + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_method_mut("cell", |lua, luaref, (row, column): (usize, usize)| { + if let Some(_) = Register::get(luaref.id) { + Ok(CellRef::new(luaref.id, row, column).into_lua(lua).unwrap()) + } else { + Ok(Value::Nil) + } + }) + } +} |