diff --git a/src/app/app.rs b/src/app/app.rs index 2fab85e..6a9e8b2 100644 --- a/src/app/app.rs +++ b/src/app/app.rs @@ -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, + file_modified_date: SystemTime, pub msg: StatusMessage, pub vars: HashMap, 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 + Clone) -> std::io::Result { 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) } diff --git a/src/app/logic/calc.rs b/src/app/logic/calc.rs index b422ef5..1dee174 100644 --- a/src/app/logic/calc.rs +++ b/src/app/logic/calc.rs @@ -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) -> std::io::Result { + pub fn new_from_file(file: &mut File) -> std::io::Result { 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() { diff --git a/src/app/mode.rs b/src/app/mode.rs index e664633..a516003 100644 --- a/src/app/mode.rs +++ b/src/app/mode.rs @@ -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 {