aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/app/impl_self.rs41
-rw-r--r--src/app/impl_view.rs19
-rw-r--r--src/command.rs87
-rw-r--r--src/habit/bit.rs17
-rw-r--r--src/habit/count.rs7
-rw-r--r--src/habit/prelude.rs1
-rw-r--r--src/main.rs23
-rw-r--r--src/views.rs18
8 files changed, 168 insertions, 45 deletions
diff --git a/src/app/impl_self.rs b/src/app/impl_self.rs
index 744f906..a806dc5 100644
--- a/src/app/impl_self.rs
+++ b/src/app/impl_self.rs
@@ -37,6 +37,10 @@ impl App {
37 self.habits.push(h); 37 self.habits.push(h);
38 } 38 }
39 39
40 pub fn list_habits(&self) -> Vec<String> {
41 self.habits.iter().map(|x| x.name()).collect::<Vec<_>>()
42 }
43
40 pub fn delete_by_name(&mut self, name: &str) { 44 pub fn delete_by_name(&mut self, name: &str) {
41 let old_len = self.habits.len(); 45 let old_len = self.habits.len();
42 self.habits.retain(|h| h.name() != name); 46 self.habits.retain(|h| h.name() != name);
@@ -118,13 +122,13 @@ impl App {
118 } 122 }
119 123
120 pub fn status(&self) -> StatusLine { 124 pub fn status(&self) -> StatusLine {
121 let today = chrono::Local::now().naive_utc().date(); 125 let today = chrono::Local::now().naive_local().date();
122 let remaining = self.habits.iter().map(|h| h.remaining(today)).sum::<u32>(); 126 let remaining = self.habits.iter().map(|h| h.remaining(today)).sum::<u32>();
123 let total = self.habits.iter().map(|h| h.goal()).sum::<u32>(); 127 let total = self.habits.iter().map(|h| h.goal()).sum::<u32>();
124 let completed = total - remaining; 128 let completed = total - remaining;
125 129
126 let timestamp = if self.view_month_offset == 0 { 130 let timestamp = if self.view_month_offset == 0 {
127 format!("{}", Local::now().date().format("%d/%b/%y"),) 131 format!("{}", Local::now().naive_local().date().format("%d/%b/%y"),)
128 } else { 132 } else {
129 let months = self.view_month_offset; 133 let months = self.view_month_offset;
130 format!("{}", format!("{} months ago", months),) 134 format!("{}", format!("{} months ago", months),)
@@ -207,12 +211,18 @@ impl App {
207 .iter_mut() 211 .iter_mut()
208 .find(|x| x.name() == name && x.is_auto()); 212 .find(|x| x.name() == name && x.is_auto());
209 if let Some(h) = target_habit { 213 if let Some(h) = target_habit {
210 h.modify(Local::now().naive_utc().date(), event); 214 h.modify(Local::now().naive_local().date(), event);
211 } 215 }
212 }; 216 };
213 match result { 217 match result {
214 Ok(c) => match c { 218 Ok(c) => match c {
215 Command::Add(name, goal, auto) => { 219 Command::Add(name, goal, auto) => {
220 if let Some(_) = self.habits.iter().find(|x| x.name() == name) {
221 self.message.set_kind(MessageKind::Error);
222 self.message
223 .set_message(format!("Habit `{}` already exist", &name));
224 return;
225 }
216 let kind = if goal == Some(1) { "bit" } else { "count" }; 226 let kind = if goal == Some(1) { "bit" } else { "count" };
217 if kind == "count" { 227 if kind == "count" {
218 self.add_habit(Box::new(Count::new(name, goal.unwrap_or(0), auto))); 228 self.add_habit(Box::new(Count::new(name, goal.unwrap_or(0), auto)));
@@ -230,7 +240,30 @@ impl App {
230 Command::TrackDown(name) => { 240 Command::TrackDown(name) => {
231 _track(&name, TrackEvent::Decrement); 241 _track(&name, TrackEvent::Decrement);
232 } 242 }
233 Command::Quit => self.save_state(), 243 Command::Help(input) => {
244 if let Some(topic) = input.as_ref().map(String::as_ref) {
245 self.message.set_message(
246 match topic {
247 "a" | "add" => "add <habit-name> [goal] (alias: a)",
248 "aa" | "add-auto" => "add-auto <habit-name> [goal] (alias: aa)",
249 "d" | "delete" => "delete <habit-name> (alias: d)",
250 "mprev" | "month-prev" => "month-prev (alias: mprev)",
251 "mnext" | "month-next" => "month-next (alias: mnext)",
252 "tup" | "track-up" => "track-up <auto-habit-name> (alias: tup)",
253 "tdown" | "track-down" => "track-down <auto-habit-name> (alias: tdown)",
254 "q" | "quit" => "quit",
255 "h"|"?" | "help" => "help [<command>|commands|keys] (aliases: h, ?)",
256 "cmds" | "commands" => "add, add-auto, delete, month-{prev,next}, track-{up,down}, help, quit",
257 "keys" => "TODO", // TODO (view?)
258 _ => "unknown command or help topic.",
259 }
260 )
261 } else {
262 // TODO (view?)
263 self.message.set_message("help <command>|commands|keys")
264 }
265 }
266 Command::Quit | Command::Write => self.save_state(),
234 Command::MonthNext => self.sift_forward(), 267 Command::MonthNext => self.sift_forward(),
235 Command::MonthPrev => self.sift_backward(), 268 Command::MonthPrev => self.sift_backward(),
236 Command::Blank => {} 269 Command::Blank => {}
diff --git a/src/app/impl_view.rs b/src/app/impl_view.rs
index 892b00c..0dfd20b 100644
--- a/src/app/impl_view.rs
+++ b/src/app/impl_view.rs
@@ -102,25 +102,6 @@ impl View for App {
102 self.set_focus(Absolute::Down); 102 self.set_focus(Absolute::Down);
103 return EventResult::Consumed(None); 103 return EventResult::Consumed(None);
104 } 104 }
105 Event::Char('d') => {
106 if self.habits.is_empty() {
107 return EventResult::Consumed(None);
108 }
109 self.habits.remove(self.focus);
110 self.focus = self.focus.checked_sub(1).unwrap_or(0);
111 return EventResult::Consumed(None);
112 }
113 Event::Char('w') => {
114 // helper bind to test write to file
115 let j = serde_json::to_string_pretty(&self.habits).unwrap();
116 let mut file = File::create("foo.txt").unwrap();
117 file.write_all(j.as_bytes()).unwrap();
118 return EventResult::Consumed(None);
119 }
120 Event::Char('q') => {
121 self.save_state();
122 return EventResult::with_cb(|s| s.quit());
123 }
124 Event::Char('v') => { 105 Event::Char('v') => {
125 if self.habits.is_empty() { 106 if self.habits.is_empty() {
126 return EventResult::Consumed(None); 107 return EventResult::Consumed(None);
diff --git a/src/command.rs b/src/command.rs
index f856b00..38d48e9 100644
--- a/src/command.rs
+++ b/src/command.rs
@@ -1,21 +1,75 @@
1use std::fmt; 1use std::fmt;
2 2
3use cursive::event::{Event, EventResult, Key};
3use cursive::theme::{BaseColor, Color, ColorStyle}; 4use cursive::theme::{BaseColor, Color, ColorStyle};
4use cursive::view::Resizable; 5use cursive::view::Resizable;
5use cursive::views::{EditView, LinearLayout, TextView}; 6use cursive::views::{EditView, LinearLayout, OnEventView, TextView};
6use cursive::Cursive; 7use cursive::Cursive;
7 8
8use crate::{app::App, CONFIGURATION}; 9use crate::{app::App, CONFIGURATION};
9 10
11static COMMANDS: &'static [&'static str] = &[
12 "add",
13 "add-auto",
14 "delete",
15 "track-up",
16 "track-down",
17 "month-prev",
18 "month-next",
19 "quit",
20 "write",
21 "help",
22];
23
24fn get_command_completion(prefix: &str) -> Option<String> {
25 let first_match = COMMANDS.iter().filter(|&x| x.starts_with(prefix)).next();
26 return first_match.map(|&x| x.into());
27}
28
29fn get_habit_completion(prefix: &str, habit_names: &[String]) -> Option<String> {
30 let first_match = habit_names.iter().filter(|&x| x.starts_with(prefix)).next();
31 eprintln!("{:?}| {:?}", prefix, first_match);
32 return first_match.map(|x| x.into());
33}
34
10pub fn open_command_window(s: &mut Cursive) { 35pub fn open_command_window(s: &mut Cursive) {
11 let command_window = EditView::new() 36 let habit_list: Vec<String> = s
12 .filler(" ") 37 .call_on_name("Main", |view: &mut App| {
13 .on_submit(call_on_app) 38 return view.list_habits();
14 .style(ColorStyle::new( 39 })
15 Color::Dark(BaseColor::Black), 40 .unwrap();
16 Color::Dark(BaseColor::White), 41 let style = ColorStyle::new(Color::Dark(BaseColor::Black), Color::Dark(BaseColor::White));
17 )) 42 let command_window = OnEventView::new(
18 .fixed_width(CONFIGURATION.view_width * CONFIGURATION.grid_width); 43 EditView::new()
44 .filler(" ")
45 .on_submit(call_on_app)
46 .style(style),
47 )
48 .on_event_inner(
49 Event::Key(Key::Tab),
50 move |view: &mut EditView, _: &Event| {
51 let contents = view.get_content();
52 if !contents.contains(" ") {
53 let completion = get_command_completion(&*contents);
54 if let Some(c) = completion {
55 let cb = view.set_content(c);
56 return Some(EventResult::Consumed(Some(cb)));
57 };
58 return None;
59 } else {
60 let word = contents.split(' ').last().unwrap();
61 let completion = get_habit_completion(word, &habit_list);
62 eprintln!("{:?} | {:?}", completion, contents);
63 if let Some(c) = completion {
64 let cb =
65 view.set_content(format!("{}", contents) + c.strip_prefix(word).unwrap());
66 return Some(EventResult::Consumed(Some(cb)));
67 };
68 return None;
69 }
70 },
71 )
72 .fixed_width(CONFIGURATION.view_width * CONFIGURATION.grid_width);
19 s.call_on_name("Frame", |view: &mut LinearLayout| { 73 s.call_on_name("Frame", |view: &mut LinearLayout| {
20 let mut commandline = LinearLayout::horizontal() 74 let mut commandline = LinearLayout::horizontal()
21 .child(TextView::new(":")) 75 .child(TextView::new(":"))
@@ -59,15 +113,17 @@ pub enum Command {
59 Delete(String), 113 Delete(String),
60 TrackUp(String), 114 TrackUp(String),
61 TrackDown(String), 115 TrackDown(String),
116 Help(Option<String>),
117 Write,
62 Quit, 118 Quit,
63 Blank, 119 Blank,
64} 120}
65 121
66#[derive(Debug)] 122#[derive(Debug)]
67pub enum CommandLineError { 123pub enum CommandLineError {
68 InvalidCommand(String), 124 InvalidCommand(String), // command name
69 InvalidArg(u32), // position 125 InvalidArg(u32), // position
70 NotEnoughArgs(String, u32), 126 NotEnoughArgs(String, u32), // command name, required no. of args
71} 127}
72 128
73impl std::error::Error for CommandLineError {} 129impl std::error::Error for CommandLineError {}
@@ -134,9 +190,16 @@ impl Command {
134 } 190 }
135 return Ok(Command::TrackDown(args[0].to_string())); 191 return Ok(Command::TrackDown(args[0].to_string()));
136 } 192 }
193 "h" | "?" | "help" => {
194 if args.is_empty() {
195 return Ok(Command::Help(None));
196 }
197 return Ok(Command::Help(Some(args[0].to_string())));
198 }
137 "mprev" | "month-prev" => return Ok(Command::MonthPrev), 199 "mprev" | "month-prev" => return Ok(Command::MonthPrev),
138 "mnext" | "month-next" => return Ok(Command::MonthNext), 200 "mnext" | "month-next" => return Ok(Command::MonthNext),
139 "q" | "quit" => return Ok(Command::Quit), 201 "q" | "quit" => return Ok(Command::Quit),
202 "w" | "write" => return Ok(Command::Write),
140 "" => return Ok(Command::Blank), 203 "" => return Ok(Command::Blank),
141 s => return Err(CommandLineError::InvalidCommand(s.into())), 204 s => return Err(CommandLineError::InvalidCommand(s.into())),
142 } 205 }
diff --git a/src/habit/bit.rs b/src/habit/bit.rs
index 3386182..8fa14c2 100644
--- a/src/habit/bit.rs
+++ b/src/habit/bit.rs
@@ -100,11 +100,22 @@ impl Habit for Bit {
100 fn goal(&self) -> u32 { 100 fn goal(&self) -> u32 {
101 return 1; 101 return 1;
102 } 102 }
103 fn modify(&mut self, date: NaiveDate, _: TrackEvent) { 103 fn modify(&mut self, date: NaiveDate, event: TrackEvent) {
104 if let Some(val) = self.stats.get_mut(&date) { 104 if let Some(val) = self.stats.get_mut(&date) {
105 *val = (val.0 ^ true).into(); 105 match event {
106 TrackEvent::Increment => *val = (val.0 ^ true).into(),
107 TrackEvent::Decrement => {
108 if val.0 {
109 *val = false.into();
110 } else {
111 self.stats.remove(&date);
112 }
113 }
114 }
106 } else { 115 } else {
107 self.insert_entry(date, CustomBool(true)); 116 if event == TrackEvent::Increment {
117 self.insert_entry(date, CustomBool(true));
118 }
108 } 119 }
109 } 120 }
110 fn set_view_month_offset(&mut self, offset: u32) { 121 fn set_view_month_offset(&mut self, offset: u32) {
diff --git a/src/habit/count.rs b/src/habit/count.rs
index 1bdf920..d351758 100644
--- a/src/habit/count.rs
+++ b/src/habit/count.rs
@@ -84,12 +84,15 @@ impl Habit for Count {
84 if *val > 0 { 84 if *val > 0 {
85 *val -= 1 85 *val -= 1
86 } else { 86 } else {
87 *val = 0 87 self.stats.remove(&date);
88 }; 88 };
89 } 89 }
90 } 90 }
91 } else { 91 } else {
92 self.insert_entry(date, 1); 92 match event {
93 TrackEvent::Increment => self.insert_entry(date, 1),
94 _ => {}
95 };
93 } 96 }
94 } 97 }
95 fn set_view_month_offset(&mut self, offset: u32) { 98 fn set_view_month_offset(&mut self, offset: u32) {
diff --git a/src/habit/prelude.rs b/src/habit/prelude.rs
index 19b00a7..8335d6c 100644
--- a/src/habit/prelude.rs
+++ b/src/habit/prelude.rs
@@ -2,6 +2,7 @@ use serde::{Deserialize, Serialize};
2use std::default; 2use std::default;
3use std::fmt; 3use std::fmt;
4 4
5#[derive(Debug, PartialEq)]
5pub enum TrackEvent { 6pub enum TrackEvent {
6 Increment, 7 Increment,
7 Decrement, 8 Decrement,
diff --git a/src/main.rs b/src/main.rs
index fb16aaa..dec3156 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -12,7 +12,13 @@ use crate::command::{open_command_window, Command};
12use crate::utils::{load_configuration_file, AppConfig}; 12use crate::utils::{load_configuration_file, AppConfig};
13 13
14use clap::{App as ClapApp, Arg}; 14use clap::{App as ClapApp, Arg};
15
16#[cfg(target_os = "linux")]
17use cursive::termion;
18
19#[cfg(target_os = "windows")]
15use cursive::crossterm; 20use cursive::crossterm;
21
16use cursive::views::{LinearLayout, NamedView}; 22use cursive::views::{LinearLayout, NamedView};
17use lazy_static::lazy_static; 23use lazy_static::lazy_static;
18 24
@@ -33,6 +39,14 @@ fn main() {
33 .value_name("CMD") 39 .value_name("CMD")
34 .help("run a dijo command"), 40 .help("run a dijo command"),
35 ) 41 )
42 .arg(
43 Arg::with_name("list")
44 .short("l")
45 .long("list")
46 .takes_value(false)
47 .help("list dijo habits")
48 .conflicts_with("command"),
49 )
36 .get_matches(); 50 .get_matches();
37 if let Some(c) = matches.value_of("command") { 51 if let Some(c) = matches.value_of("command") {
38 let command = Command::from_string(c); 52 let command = Command::from_string(c);
@@ -49,8 +63,17 @@ fn main() {
49 "Commands other than `track-up` and `track-down` are currently not supported!" 63 "Commands other than `track-up` and `track-down` are currently not supported!"
50 ), 64 ),
51 } 65 }
66 } else if matches.is_present("list") {
67 for h in App::load_state().list_habits() {
68 println!("{}", h);
69 }
52 } else { 70 } else {
71 #[cfg(target_os = "windows")]
53 let mut s = crossterm().unwrap(); 72 let mut s = crossterm().unwrap();
73
74 #[cfg(target_os = "linux")]
75 let mut s = termion().unwrap();
76
54 let app = App::load_state(); 77 let app = App::load_state();
55 let layout = NamedView::new( 78 let layout = NamedView::new(
56 "Frame", 79 "Frame",
diff --git a/src/views.rs b/src/views.rs
index 24c8a4d..da077ac 100644
--- a/src/views.rs
+++ b/src/views.rs
@@ -43,7 +43,7 @@ where
43 let strikethrough = Style::from(Effect::Strikethrough); 43 let strikethrough = Style::from(Effect::Strikethrough);
44 44
45 let goal_status = 45 let goal_status =
46 self.view_month_offset() == 0 && self.reached_goal(Local::now().naive_utc().date()); 46 self.view_month_offset() == 0 && self.reached_goal(Local::now().naive_local().date());
47 47
48 printer.with_style( 48 printer.with_style(
49 Style::merge(&[ 49 Style::merge(&[
@@ -77,12 +77,20 @@ where
77 .collect::<Vec<_>>(); 77 .collect::<Vec<_>>();
78 for (week, line_nr) in days.chunks(7).zip(2..) { 78 for (week, line_nr) in days.chunks(7).zip(2..) {
79 let weekly_goal = self.goal() * week.len() as u32; 79 let weekly_goal = self.goal() * week.len() as u32;
80 let is_this_week = week.contains(&Local::now().naive_utc().date()); 80 let is_this_week = week.contains(&Local::now().naive_local().date());
81 let remaining = week.iter().map(|&i| self.remaining(i)).sum::<u32>(); 81 let remaining = week.iter().map(|&i| self.remaining(i)).sum::<u32>();
82 let completions = weekly_goal - remaining; 82 let completions = weekly_goal - remaining;
83 let full = CONFIGURATION.view_width - 8; 83 let full = CONFIGURATION.view_width - 8;
84 let bars_to_fill = if weekly_goal > 0 {(completions * full as u32) / weekly_goal} else {0}; 84 let bars_to_fill = if weekly_goal > 0 {
85 let percentage = if weekly_goal > 0 {(completions as f64 * 100.) / weekly_goal as f64} else {0.0}; 85 (completions * full as u32) / weekly_goal
86 } else {
87 0
88 };
89 let percentage = if weekly_goal > 0 {
90 (completions as f64 * 100.) / weekly_goal as f64
91 } else {
92 0.0
93 };
86 printer.with_style(future_style, |p| { 94 printer.with_style(future_style, |p| {
87 p.print((4, line_nr), &"─".repeat(full)); 95 p.print((4, line_nr), &"─".repeat(full));
88 }); 96 });
@@ -141,7 +149,7 @@ where
141 } 149 }
142 150
143 fn on_event(&mut self, e: Event) -> EventResult { 151 fn on_event(&mut self, e: Event) -> EventResult {
144 let now = Local::now().naive_utc().date(); 152 let now = Local::now().naive_local().date();
145 if self.is_auto() { 153 if self.is_auto() {
146 return EventResult::Ignored; 154 return EventResult::Ignored;
147 } 155 }