Save file (#19)

This commit is contained in:
Adrian Woźniak 2019-05-21 21:51:00 +02:00 committed by GitHub
parent 0ae805faec
commit 96597983fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 1 deletions

View File

@ -6,7 +6,8 @@ use crate::ui::*;
use rider_config::*;
use sdl2::rect::Point;
use sdl2::VideoSubsystem as VS;
use std::fs::read_to_string;
use std::fs::{read_to_string, File};
use std::io::Write;
use std::sync::*;
pub struct AppState {
@ -47,6 +48,23 @@ impl AppState {
};
}
pub fn save_file(&self) -> Result<(), String> {
println!("Saving file...");
let editor_file = match self.file_editor.file() {
Some(f) => f,
_ => Err("No buffer found".to_string())?,
};
let mut f = File::create(editor_file.path())
.or_else(|_| Err("File can't be opened".to_string()))?;
f.write_all(editor_file.buffer().as_bytes())
.or_else(|_| Err("Failed to write to file".to_string()))?;
f.flush()
.or_else(|_| Err("Failed to write to file".to_string()))?;
Ok(())
}
pub fn open_directory<R>(&mut self, dir_path: String, renderer: &mut R)
where
R: Renderer + CharacterSizeManager,

View File

@ -48,6 +48,7 @@ pub enum UpdateResult {
OpenDirectory(String),
OpenFileModal,
FileDropped(String),
SaveCurrentFile,
}
#[cfg_attr(tarpaulin, skip)]
@ -201,6 +202,11 @@ impl Application {
UpdateResult::MouseDragStart(_point) => (),
UpdateResult::MouseDragStop(_point) => (),
UpdateResult::FileDropped(_path) => (),
UpdateResult::SaveCurrentFile => {
app_state
.save_file()
.unwrap_or_else(|e| eprintln!("Failed to save {:?}", e));
}
}
}
self.tasks = new_tasks;
@ -286,6 +292,9 @@ impl Application {
Keycode::O if left_control_pressed && !shift_pressed => {
self.tasks.push(UpdateResult::OpenFileModal)
}
Keycode::S if left_control_pressed => {
self.tasks.push(UpdateResult::SaveCurrentFile)
}
_ => {}
},
Event::TextInput { text, .. } => {