Run cargo fmt

This commit is contained in:
Dheepak Krishnamurthy 2021-02-11 01:24:41 -07:00
parent f133ec219b
commit e222b147cc
6 changed files with 114 additions and 63 deletions

View file

@ -4,8 +4,8 @@ use crate::context::Context;
use crate::help::Help; use crate::help::Help;
use crate::table::{Row, Table, TableState}; use crate::table::{Row, Table, TableState};
use crate::task_report::TaskReportTable; use crate::task_report::TaskReportTable;
use crate::util::{Events, Event};
use crate::util::Key; use crate::util::Key;
use crate::util::{Event, Events};
use std::cmp::Ordering; use std::cmp::Ordering;
use std::convert::TryInto; use std::convert::TryInto;
@ -29,7 +29,7 @@ use std::sync::{Arc, Mutex};
use std::{sync::mpsc, thread, time::Duration}; use std::{sync::mpsc, thread, time::Duration};
use tui::{ use tui::{
backend::Backend, backend::Backend,
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin}, layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
style::{Color, Modifier, Style}, style::{Color, Modifier, Style},
terminal::Frame, terminal::Frame,
text::{Span, Spans, Text}, text::{Span, Spans, Text},
@ -290,7 +290,7 @@ impl TTApp {
for (i, (_i, g)) in self.filter.as_str().grapheme_indices(true).enumerate() { for (i, (_i, g)) in self.filter.as_str().grapheme_indices(true).enumerate() {
if _i == self.filter.pos() { if _i == self.filter.pos() {
position = i; position = i;
break break;
} }
} }
f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1); f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1);
@ -307,7 +307,7 @@ impl TTApp {
for (i, (_i, g)) in self.modify.as_str().grapheme_indices(true).enumerate() { for (i, (_i, g)) in self.modify.as_str().grapheme_indices(true).enumerate() {
if _i == self.modify.pos() { if _i == self.modify.pos() {
position = i; position = i;
break break;
} }
} }
f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1); f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1);
@ -327,7 +327,7 @@ impl TTApp {
for (i, (_i, g)) in self.command.as_str().grapheme_indices(true).enumerate() { for (i, (_i, g)) in self.command.as_str().grapheme_indices(true).enumerate() {
if _i == self.command.pos() { if _i == self.command.pos() {
position = i; position = i;
break break;
} }
} }
f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1); f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1);
@ -344,7 +344,7 @@ impl TTApp {
for (i, (_i, g)) in self.command.as_str().grapheme_indices(true).enumerate() { for (i, (_i, g)) in self.command.as_str().grapheme_indices(true).enumerate() {
if _i == self.command.pos() { if _i == self.command.pos() {
position = i; position = i;
break break;
} }
} }
f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1); f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1);
@ -361,7 +361,7 @@ impl TTApp {
for (i, (_i, g)) in self.command.as_str().grapheme_indices(true).enumerate() { for (i, (_i, g)) in self.command.as_str().grapheme_indices(true).enumerate() {
if _i == self.command.pos() { if _i == self.command.pos() {
position = i; position = i;
break break;
} }
} }
f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1); f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1);
@ -381,7 +381,7 @@ impl TTApp {
for (i, (_i, g)) in self.command.as_str().grapheme_indices(true).enumerate() { for (i, (_i, g)) in self.command.as_str().grapheme_indices(true).enumerate() {
if _i == self.command.pos() { if _i == self.command.pos() {
position = i; position = i;
break break;
} }
} }
f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1); f.set_cursor(rects[1].x + position as u16 + 1, rects[1].y + 1);
@ -430,9 +430,13 @@ impl TTApp {
let area = centered_rect(80, 50, f.size()); let area = centered_rect(80, 50, f.size());
f.render_widget(Clear, area.inner(&Margin { f.render_widget(
vertical: 0, horizontal: 0, Clear,
})); area.inner(&Margin {
vertical: 0,
horizontal: 0,
}),
);
let (contexts, headers) = self.get_all_contexts(); let (contexts, headers) = self.get_all_contexts();
@ -467,9 +471,10 @@ impl TTApp {
Block::default() Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.border_type(BorderType::Rounded) .border_type(BorderType::Rounded)
.title(Spans::from(vec![ .title(Spans::from(vec![Span::styled(
Span::styled("Context", Style::default().add_modifier(Modifier::BOLD)), "Context",
])), Style::default().add_modifier(Modifier::BOLD),
)])),
) )
.header_style(Style::default().add_modifier(Modifier::UNDERLINED)) .header_style(Style::default().add_modifier(Modifier::UNDERLINED))
.highlight_style(highlight_style) .highlight_style(highlight_style)
@ -506,7 +511,10 @@ impl TTApp {
let selected = self.task_table_state.selected().unwrap_or_default(); let selected = self.task_table_state.selected().unwrap_or_default();
let task_id = self.tasks.lock().unwrap()[selected].id().unwrap_or_default(); let task_id = self.tasks.lock().unwrap()[selected].id().unwrap_or_default();
let task_uuid = self.tasks.lock().unwrap()[selected].uuid().clone(); let task_uuid = self.tasks.lock().unwrap()[selected].uuid().clone();
let output = Command::new("task").arg("rc.color=off").arg(format!("{}", task_uuid)).output(); let output = Command::new("task")
.arg("rc.color=off")
.arg(format!("{}", task_uuid))
.output();
if let Ok(output) = output { if let Ok(output) = output {
let data = String::from_utf8_lossy(&output.stdout); let data = String::from_utf8_lossy(&output.stdout);
let p = Paragraph::new(Text::from(&data[..])).block( let p = Paragraph::new(Text::from(&data[..])).block(
@ -561,8 +569,12 @@ impl TTApp {
style style
} }
pub fn calculate_widths(&self, tasks: &Vec<Vec<String>>, headers: &Vec<String>, maximum_column_width: u16) -> Vec<usize> { pub fn calculate_widths(
&self,
tasks: &Vec<Vec<String>>,
headers: &Vec<String>,
maximum_column_width: u16,
) -> Vec<usize> {
// naive implementation of calculate widths // naive implementation of calculate widths
let mut widths = headers.iter().map(|s| s.len()).collect::<Vec<usize>>(); let mut widths = headers.iter().map(|s| s.len()).collect::<Vec<usize>>();
@ -576,7 +588,7 @@ impl TTApp {
if header == "Description" || header == "Definition" { if header == "Description" || header == "Definition" {
// always give description or definition the most room to breath // always give description or definition the most room to breath
widths[i] = maximum_column_width as usize; widths[i] = maximum_column_width as usize;
break break;
} }
} }
for (i, header) in headers.iter().enumerate() { for (i, header) in headers.iter().enumerate() {
@ -590,12 +602,12 @@ impl TTApp {
while (widths.iter().sum::<usize>() as u16) >= maximum_column_width - (headers.len()) as u16 { while (widths.iter().sum::<usize>() as u16) >= maximum_column_width - (headers.len()) as u16 {
let index = widths.iter().position(|i| i == widths.iter().max().unwrap()).unwrap(); let index = widths.iter().position(|i| i == widths.iter().max().unwrap()).unwrap();
if widths[index] == 1 { if widths[index] == 1 {
break break;
} }
widths[index] -= 1; widths[index] -= 1;
} }
return widths return widths;
} }
fn draw_task_report(&mut self, f: &mut Frame<impl Backend>, rect: Rect) { fn draw_task_report(&mut self, f: &mut Frame<impl Backend>, rect: Rect) {
@ -626,7 +638,7 @@ impl TTApp {
for (i, header) in headers.iter().enumerate() { for (i, header) in headers.iter().enumerate() {
if header == "Description" || header == "Definition" { if header == "Description" || header == "Definition" {
self.task_report_table.description_width = widths[i] - 1; self.task_report_table.description_width = widths[i] - 1;
break break;
} }
} }
@ -684,7 +696,11 @@ impl TTApp {
} }
pub fn get_all_contexts(&self) -> (Vec<Vec<String>>, Vec<String>) { pub fn get_all_contexts(&self) -> (Vec<Vec<String>>, Vec<String>) {
let contexts = self.contexts.iter().map(|c| vec![c.name.clone(), c.description.clone(), c.active.clone()]).collect(); let contexts = self
.contexts
.iter()
.map(|c| vec![c.name.clone(), c.description.clone(), c.active.clone()])
.collect();
let headers = vec!["Name".to_string(), "Description".to_string(), "Active".to_string()]; let headers = vec!["Name".to_string(), "Description".to_string(), "Active".to_string()];
(contexts, headers) (contexts, headers)
} }
@ -715,7 +731,7 @@ impl TTApp {
} else { } else {
i + 1 i + 1
} }
}, }
None => 0, None => 0,
}; };
self.context_table_state.select(Some(i)); self.context_table_state.select(Some(i));
@ -737,10 +753,7 @@ impl TTApp {
pub fn context_select(&mut self) { pub fn context_select(&mut self) {
let i = self.context_table_state.selected().unwrap(); let i = self.context_table_state.selected().unwrap();
let output = Command::new("task") let output = Command::new("task").arg("context").arg(&self.contexts[i].name).output();
.arg("context")
.arg(&self.contexts[i].name)
.output();
} }
pub fn task_report_top(&mut self) { pub fn task_report_top(&mut self) {
@ -856,16 +869,18 @@ impl TTApp {
let definition = line.replacen(name, "", 1); let definition = line.replacen(name, "", 1);
let definition = definition.strip_suffix(active).unwrap(); let definition = definition.strip_suffix(active).unwrap();
if i == 0 || i == 1 { if i == 0 || i == 1 {
continue continue;
} else { } else {
let context = Context::new(name.to_string(), definition.trim().to_string(), active.to_string()); let context = Context::new(name.to_string(), definition.trim().to_string(), active.to_string());
self.contexts.push(context); self.contexts.push(context);
} }
} }
if self.contexts.iter().any(|r| r.active != "no") { if self.contexts.iter().any(|r| r.active != "no") {
self.contexts.insert(0, Context::new("none".to_string(), "".to_string(), "no".to_string())) self.contexts
.insert(0, Context::new("none".to_string(), "".to_string(), "no".to_string()))
} else { } else {
self.contexts.insert(0, Context::new("none".to_string(), "".to_string(), "yes".to_string())) self.contexts
.insert(0, Context::new("none".to_string(), "".to_string(), "yes".to_string()))
} }
Ok(()) Ok(())
@ -998,7 +1013,11 @@ impl TTApp {
self.modify.update("", 0); self.modify.update("", 0);
Ok(()) Ok(())
} else { } else {
Err(format!("Unable to modify task with uuid {}. Failed with status code {}", task_uuid, o.status.code().unwrap())) Err(format!(
"Unable to modify task with uuid {}. Failed with status code {}",
task_uuid,
o.status.code().unwrap()
))
} }
} }
Err(_) => Err(format!( Err(_) => Err(format!(
@ -1038,7 +1057,11 @@ impl TTApp {
self.command.update("", 0); self.command.update("", 0);
Ok(()) Ok(())
} else { } else {
Err(format!("Unable to annotate task with uuid {}. Failed with status code {}", task_uuid, o.status.code().unwrap())) Err(format!(
"Unable to annotate task with uuid {}. Failed with status code {}",
task_uuid,
o.status.code().unwrap()
))
} }
} }
Err(_) => Err(format!( Err(_) => Err(format!(
@ -1348,7 +1371,7 @@ impl TTApp {
Key::Char('g') => match events.next()? { Key::Char('g') => match events.next()? {
Event::Input(Key::Char('g')) => self.task_report_top(), Event::Input(Key::Char('g')) => self.task_report_top(),
_ => (), _ => (),
} },
Key::Down | Key::Char('j') => self.task_report_next(), Key::Down | Key::Char('j') => self.task_report_next(),
Key::Up | Key::Char('k') => self.task_report_previous(), Key::Up | Key::Char('k') => self.task_report_previous(),
Key::PageDown | Key::Char('J') => self.task_report_next_page(), Key::PageDown | Key::Char('J') => self.task_report_next_page(),
@ -1435,7 +1458,7 @@ impl TTApp {
AppMode::TaskContextMenu => match input { AppMode::TaskContextMenu => match input {
Key::Esc | Key::Char('q') => { Key::Esc | Key::Char('q') => {
self.mode = AppMode::TaskReport; self.mode = AppMode::TaskReport;
}, }
Key::Down | Key::Char('j') => self.context_next(), Key::Down | Key::Char('j') => self.context_next(),
Key::Up | Key::Char('k') => self.context_previous(), Key::Up | Key::Char('k') => self.context_previous(),
Key::Char('\n') => { Key::Char('\n') => {
@ -1641,6 +1664,5 @@ mod tests {
fn test_app() { fn test_app() {
let app = TTApp::new().unwrap(); let app = TTApp::new().unwrap();
assert!(app.task_by_index(0).is_some()) assert!(app.task_by_index(0).is_some())
} }
} }

View file

@ -27,9 +27,7 @@ impl TColor {
} }
pub fn new(fg: Color, bg: Color, modifiers: Vec<Modifier>) -> Self { pub fn new(fg: Color, bg: Color, modifiers: Vec<Modifier>) -> Self {
Self { Self { fg, bg, modifiers }
fg, bg, modifiers,
}
} }
} }
@ -61,7 +59,6 @@ impl TaskWarriorBool for str {
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Config { pub struct Config {
pub enabled: bool, pub enabled: bool,
@ -98,10 +95,16 @@ impl Config {
uda_selection_dim: Self::get_uda_selection_dim(), uda_selection_dim: Self::get_uda_selection_dim(),
uda_selection_blink: Self::get_uda_selection_blink(), uda_selection_blink: Self::get_uda_selection_blink(),
uda_calendar_months_per_row: Self::get_uda_months_per_row(), uda_calendar_months_per_row: Self::get_uda_months_per_row(),
uda_style_calendar_title: Self::get_uda_style("calendar.title") uda_style_calendar_title: Self::get_uda_style("calendar.title").unwrap_or(TColor::new(
.unwrap_or(TColor::new(Color::Reset, Color::Reset, vec![])), Color::Reset,
uda_style_context_active: Self::get_uda_style("context.active") Color::Reset,
.unwrap_or(TColor::new(Color::Reset, Color::Reset, vec![])), vec![],
)),
uda_style_context_active: Self::get_uda_style("context.active").unwrap_or(TColor::new(
Color::Reset,
Color::Reset,
vec![],
)),
}) })
} }

View file

@ -16,8 +16,8 @@ use clap::{App, Arg};
use std::env; use std::env;
use std::error::Error; use std::error::Error;
use std::io::Write; use std::io::Write;
use std::time::Duration;
use std::panic; use std::panic;
use std::time::Duration;
use crate::util::Key; use crate::util::Key;
use app::{AppMode, TTApp}; use app::{AppMode, TTApp};
@ -120,13 +120,12 @@ fn tui_main(_config: &str) -> Result<(), Box<dyn Error>> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::util::{destruct_terminal, setup_terminal, Event, EventConfig, Events};
use crate::util::Key; use crate::util::Key;
use crate::util::{destruct_terminal, setup_terminal, Event, EventConfig, Events};
use std::time::Duration; use std::time::Duration;
#[test] #[test]
fn test_main() { fn test_main() {
let mut terminal = setup_terminal(); let mut terminal = setup_terminal();
terminal.clear().unwrap(); terminal.clear().unwrap();
// Setup event handlers // Setup event handlers
@ -141,15 +140,15 @@ mod tests {
Event::Input(Key::Char('g')) => events.resume_ticker(), Event::Input(Key::Char('g')) => events.resume_ticker(),
_ => (), _ => (),
} }
}, }
Event::Input(input) => { Event::Input(input) => {
print!("\r\n"); print!("\r\n");
dbg!(input); dbg!(input);
}, }
Event::Tick => { Event::Tick => {
print!("\r\n"); print!("\r\n");
dbg!("tick"); dbg!("tick");
}, }
}; };
destruct_terminal(); destruct_terminal();

View file

@ -14,9 +14,9 @@ use tui::{
style::Style, style::Style,
widgets::{Block, StatefulWidget, Widget}, widgets::{Block, StatefulWidget, Widget},
}; };
use unicode_width::UnicodeWidthStr;
use unicode_segmentation::Graphemes; use unicode_segmentation::Graphemes;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct TableState { pub struct TableState {
@ -278,9 +278,21 @@ where
let mut index = 0; let mut index = 0;
if y < table_area.bottom() { if y < table_area.bottom() {
for (w, t) in solved_widths.iter().zip(self.header.by_ref()) { for (w, t) in solved_widths.iter().zip(self.header.by_ref()) {
buf.set_stringn(x, y, format!("{symbol:>width$}", symbol=" ", width=*w as usize), *w as usize, self.header_style); buf.set_stringn(
x,
y,
format!("{symbol:>width$}", symbol = " ", width = *w as usize),
*w as usize,
self.header_style,
);
if t.to_string() == "ID" { if t.to_string() == "ID" {
buf.set_stringn(x, y, format!("{symbol:>width$}", symbol=t, width=*w as usize), *w as usize, self.header_style); buf.set_stringn(
x,
y,
format!("{symbol:>width$}", symbol = t, width = *w as usize),
*w as usize,
self.header_style,
);
header_index = index; header_index = index;
} else { } else {
buf.set_stringn(x, y, format!("{}", t), *w as usize, self.header_style); buf.set_stringn(x, y, format!("{}", t), *w as usize, self.header_style);
@ -335,9 +347,19 @@ where
style, style,
); );
if c == header_index { if c == header_index {
format!("{symbol}{elt:>width$}", symbol = symbol, elt = elt, width = *w as usize - symbol.to_string().graphemes(true).count()) format!(
"{symbol}{elt:>width$}",
symbol = symbol,
elt = elt,
width = *w as usize - symbol.to_string().graphemes(true).count()
)
} else { } else {
format!("{symbol}{elt:<width$}", symbol = symbol, elt = elt, width = *w as usize - symbol.to_string().graphemes(true).count()) format!(
"{symbol}{elt:<width$}",
symbol = symbol,
elt = elt,
width = *w as usize - symbol.to_string().graphemes(true).count()
)
} }
} else { } else {
buf.set_stringn( buf.set_stringn(

View file

@ -122,7 +122,7 @@ impl TaskReportTable {
// get all tasks as their string representation // get all tasks as their string representation
for task in tasks { for task in tasks {
if self.columns.len() == 0 { if self.columns.len() == 0 {
break break;
} }
let mut item = vec![]; let mut item = vec![];
for name in &self.columns { for name in &self.columns {
@ -231,7 +231,7 @@ impl TaskReportTable {
None => format!(""), None => format!(""),
}; };
format!("{} {}", task.description().to_string(), c) format!("{} {}", task.description().to_string(), c)
}, }
"description.truncated_count" => { "description.truncated_count" => {
let c = match task.annotations() { let c = match task.annotations() {
Some(a) => format!(" [{}]", a.iter().count()), Some(a) => format!(" [{}]", a.iter().count()),
@ -250,7 +250,7 @@ impl TaskReportTable {
d = format!("{}", d); d = format!("{}", d);
} }
format!("{}{}", d, c) format!("{}{}", d, c)
}, }
"description.truncated" => { "description.truncated" => {
let mut d = task.description().to_string(); let mut d = task.description().to_string();
let mut end = self.description_width; let mut end = self.description_width;
@ -262,7 +262,7 @@ impl TaskReportTable {
d = format!("{}", d); d = format!("{}", d);
} }
format!("{}", d) format!("{}", d)
}, }
"description" => task.description().to_string(), "description" => task.description().to_string(),
"urgency" => match &task.urgency() { "urgency" => match &task.urgency() {
Some(f) => format!("{:.2}", *f), Some(f) => format!("{:.2}", *f),
@ -279,7 +279,7 @@ impl TaskReportTable {
UDAValue::F64(f) => f.to_string(), UDAValue::F64(f) => f.to_string(),
UDAValue::U64(u) => u.to_string(), UDAValue::U64(u) => u.to_string(),
} }
}, }
} }
} }
} }

View file

@ -1,8 +1,8 @@
use crossterm::{ use crossterm::{
cursor,
event::{self, DisableMouseCapture, EnableMouseCapture}, event::{self, DisableMouseCapture, EnableMouseCapture},
execute, execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, Clear, ClearType}, terminal::{disable_raw_mode, enable_raw_mode, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
cursor,
}; };
use tui::{backend::CrosstermBackend, Terminal}; use tui::{backend::CrosstermBackend, Terminal};
@ -129,7 +129,12 @@ impl Events {
}) })
}; };
Events { rx, tx, pause_stdin, pause_ticker } Events {
rx,
tx,
pause_stdin,
pause_ticker,
}
} }
/// Attempts to read an event. /// Attempts to read an event.