1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use std::process::Command;
use std::time::Duration;

use crossbeam_channel::Sender;
use serde_derive::Deserialize;

use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::de::deserialize_duration;
use crate::errors::*;
use crate::formatting::value::Value;
use crate::formatting::FormatTemplate;
use crate::input::{I3BarEvent, MouseButton};
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::{I3BarWidget, State};

pub struct Taskwarrior {
    id: usize,
    output: TextWidget,
    update_interval: Duration,
    warning_threshold: u32,
    critical_threshold: u32,
    filters: Vec<Filter>,
    filter_index: usize,
    format: FormatTemplate,
    format_singular: FormatTemplate,
    format_everything_done: FormatTemplate,
}

#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct Filter {
    pub name: String,
    pub filter: String,
}

impl Filter {
    pub fn new(name: String, filter: String) -> Self {
        Filter { name, filter }
    }

    pub fn legacy(name: String, tags: &[String]) -> Self {
        let tags = tags
            .iter()
            .map(|element| format!("+{}", element))
            .collect::<Vec<String>>()
            .join(" ");
        let filter = format!("-COMPLETED -DELETED {}", tags);
        Self::new(name, filter)
    }
}

#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct TaskwarriorConfig {
    /// Update interval in seconds
    #[serde(
        default = "TaskwarriorConfig::default_interval",
        deserialize_with = "deserialize_duration"
    )]
    pub interval: Duration,

    /// Threshold from which on the block is marked with a warning indicator
    #[serde(default = "TaskwarriorConfig::default_threshold_warning")]
    pub warning_threshold: u32,

    /// Threshold from which on the block is marked with a critical indicator
    #[serde(default = "TaskwarriorConfig::default_threshold_critical")]
    pub critical_threshold: u32,

    /// A list of tags a task has to have before it's used for counting pending tasks
    /// (DEPRECATED) use filters instead
    #[serde(default = "TaskwarriorConfig::default_filter_tags")]
    pub filter_tags: Vec<String>,

    /// A list of named filter criteria which must be fulfilled to be counted towards
    /// the total, when that filter is active.
    #[serde(default = "TaskwarriorConfig::default_filters")]
    pub filters: Vec<Filter>,

    /// Format override
    #[serde(default = "TaskwarriorConfig::default_format")]
    pub format: String,

    /// Format override if the count is one
    #[serde(default = "TaskwarriorConfig::default_format")]
    pub format_singular: String,

    /// Format override if the count is zero
    #[serde(default = "TaskwarriorConfig::default_format")]
    pub format_everything_done: String,
}

impl TaskwarriorConfig {
    fn default_interval() -> Duration {
        Duration::from_secs(600)
    }

    fn default_threshold_warning() -> u32 {
        10
    }

    fn default_threshold_critical() -> u32 {
        20
    }

    fn default_filter_tags() -> Vec<String> {
        vec![]
    }

    fn default_filters() -> Vec<Filter> {
        vec![Filter::new(
            "pending".to_string(),
            "-COMPLETED -DELETED".to_string(),
        )]
    }

    fn default_format() -> String {
        "{count}".to_owned()
    }
}

impl ConfigBlock for Taskwarrior {
    type Config = TaskwarriorConfig;

    fn new(
        id: usize,
        block_config: Self::Config,
        shared_config: SharedConfig,
        _tx_update_request: Sender<Task>,
    ) -> Result<Self> {
        let output = TextWidget::new(id, 0, shared_config)
            .with_icon("tasks")?
            .with_text("-");
        // If the deprecated `filter_tags` option has been set,
        // convert it to the new `filter` format.
        let filters = if !block_config.filter_tags.is_empty() {
            vec![
                Filter::legacy("filtered".to_string(), &block_config.filter_tags),
                Filter::legacy("all".to_string(), &[]),
            ]
        } else {
            block_config.filters
        };

        Ok(Taskwarrior {
            id,
            update_interval: block_config.interval,
            warning_threshold: block_config.warning_threshold,
            critical_threshold: block_config.critical_threshold,
            format: FormatTemplate::from_string(&block_config.format).block_error(
                "taskwarrior",
                "Invalid format specified for taskwarrior::format",
            )?,
            format_singular: FormatTemplate::from_string(&block_config.format_singular)
                .block_error(
                    "taskwarrior",
                    "Invalid format specified for taskwarrior::format_singular",
                )?,
            format_everything_done: FormatTemplate::from_string(
                &block_config.format_everything_done,
            )
            .block_error(
                "taskwarrior",
                "Invalid format specified for taskwarrior::format_everything_done",
            )?,
            filter_index: 0,
            filters,
            output,
        })
    }
}

fn has_taskwarrior() -> Result<bool> {
    Ok(String::from_utf8(
        Command::new("sh")
            .args(&["-c", "type -P task"])
            .output()
            .block_error(
                "taskwarrior",
                "failed to start command to check for taskwarrior",
            )?
            .stdout,
    )
    .block_error("taskwarrior", "failed to check for taskwarrior")?
    .trim()
        != "")
}

fn get_number_of_tasks(filter: &str) -> Result<u32> {
    String::from_utf8(
        Command::new("sh")
            .args(&["-c", &format!("task rc.gc=off {} count", filter)])
            .output()
            .block_error(
                "taskwarrior",
                "failed to run taskwarrior for getting the number of tasks",
            )?
            .stdout,
    )
    .block_error(
        "taskwarrior",
        "failed to get the number of tasks from taskwarrior",
    )?
    .trim()
    .parse::<u32>()
    .block_error("taskwarrior", "could not parse the result of taskwarrior")
}

impl Block for Taskwarrior {
    fn update(&mut self) -> Result<Option<Update>> {
        if !has_taskwarrior()? {
            self.output.set_text("?".to_string())
        } else {
            let filter = self.filters.get(self.filter_index).block_error(
                "taskwarrior",
                &format!("Filter at index {} does not exist", self.filter_index),
            )?;
            let number_of_tasks = get_number_of_tasks(&filter.filter)?;
            let values = map!(
                "count" => Value::from_integer(number_of_tasks as i64),
                "filter_name" => Value::from_string(filter.name.clone()),
            );
            self.output.set_text(match number_of_tasks {
                0 => self.format_everything_done.render(&values)?,
                1 => self.format_singular.render(&values)?,
                _ => self.format.render(&values)?,
            });
            if number_of_tasks >= self.critical_threshold {
                self.output.set_state(State::Critical);
            } else if number_of_tasks >= self.warning_threshold {
                self.output.set_state(State::Warning);
            } else {
                self.output.set_state(State::Idle);
            }
        }

        // continue updating the block in the configured interval
        Ok(Some(self.update_interval.into()))
    }

    fn view(&self) -> Vec<&dyn I3BarWidget> {
        vec![&self.output]
    }

    fn click(&mut self, event: &I3BarEvent) -> Result<()> {
        match event.button {
            MouseButton::Left => {
                self.update()?;
            }
            MouseButton::Right => {
                // Increment the filter_index, rotating at the end
                self.filter_index = (self.filter_index + 1) % self.filters.len();
                self.update()?;
            }
            _ => {}
        }

        Ok(())
    }

    fn id(&self) -> usize {
        self.id
    }
}