Fix a few panics and add register

This commit is contained in:
kageru 2020-01-24 11:07:37 +01:00
parent d2c142f65f
commit cc7b8beda9
2 changed files with 32 additions and 13 deletions

@ -1,4 +1,5 @@
use std::io;
use std::default::Default;
use termion::event::Key;
use termion::raw::IntoRawMode;
use termion::input::TermRead;
@ -21,12 +22,13 @@ fn main() -> Result<(), io::Error> {
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let mut tracc = Tracc::open_or_create();
let mut register = std::default::Default::default();
terminal.hide_cursor()?;
terminal.clear()?;
loop {
refresh(&mut terminal, &tracc)?;
// I need to find a better way to handle inputs. This is awful.
let input = inputs.next().unwrap().expect("input ded?");
let input = inputs.next().unwrap()?;
match tracc.mode {
Mode::Normal => match input {
Key::Char('q') => {
@ -36,7 +38,7 @@ fn main() -> Result<(), io::Error> {
Key::Char('j') => tracc.selection_down(),
Key::Char('k') => tracc.selection_up(),
Key::Char('o') => {
tracc.insert();
tracc.insert(Default::default());
tracc.set_mode(Mode::Insert, &mut terminal)?;
}
Key::Char('a') => tracc.set_mode(Mode::Insert, &mut terminal)?,
@ -44,8 +46,13 @@ fn main() -> Result<(), io::Error> {
Key::Char(' ') => tracc.toggle_current(),
// dd
Key::Char('d') => {
if let Key::Char('d') = inputs.next().unwrap().unwrap() {
tracc.remove_current()
if let Key::Char('d') = inputs.next().unwrap()? {
register = tracc.remove_current()
}
}
Key::Char('p') => {
if register.is_some() {
tracc.insert(register.clone().unwrap());
}
}
_ => (),

@ -13,7 +13,7 @@ pub struct Tracc {
pub mode: Mode,
}
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Default, Clone)]
pub struct Todo {
text: String,
done: bool,
@ -61,17 +61,28 @@ impl Tracc {
self.selected = self.selected.map(|i| i.saturating_sub(1));
}
pub fn insert(&mut self) {
self.todos.insert(self.selected.unwrap() + 1, Todo::new(""));
self.selected = self.selected.map(|n| n + 1);
pub fn insert(&mut self, todo: Todo) {
if let Some(position) = self.selected {
if position == self.todos.len().saturating_sub(1) {
self.todos.push(todo);
self.selected = Some(self.todos.len() - 1);
} else {
self.todos.insert(position + 1, todo);
self.selected = Some(position + 1);
}
}
self.mode = Mode::Normal;
}
pub fn remove_current(&mut self) {
if let Some(n) = self.selected {
self.todos.remove(n);
self.selected = Some(n.min(self.todos.len() - 1));
pub fn remove_current(&mut self) -> Option<Todo> {
if self.todos.is_empty() {
return None;
}
if let Some(n) = self.selected {
self.selected = Some(n.min(self.todos.len() - 1));
return Some(self.todos.remove(n));
}
None
}
pub fn toggle_current(&mut self) {
@ -91,7 +102,8 @@ impl Tracc {
Mode::Insert => term.show_cursor()?,
Mode::Normal => {
if self.current().text.is_empty() {
self.remove_current()
self.remove_current();
self.selected.as_mut().map(|n| *n = n.saturating_sub(1));
}
term.hide_cursor()?
}