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
//! Display the current time
//!
//! #### Examples
//!
//! ```toml
//! [[block]]
//! block = "time"
//! format = "%a %d/%m %R"
//! timezone = "US/Pacific"
//! interval = 60
//! locale = "fr_BE"
//! ```

use std::convert::TryInto;
use std::time::Duration;

use chrono::offset::{Local, Utc};
use chrono::Locale;
use chrono_tz::Tz;
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::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::I3BarWidget;

pub struct Time {
    id: usize,
    time: TextWidget,
    update_interval: Duration,
    format: String,
    timezone: Option<Tz>,
    locale: Option<String>,
}

/// Configuration for the `time` block
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct TimeConfig {
    /// A string to customise the output of this block. See the [chrono docs](https://docs.rs/chrono/0.4/chrono/format/strftime/index.html#specifiers) for all options. Text may need to be escaped, refer to [Escaping Text](#escaping-text).
    ///
    /// The default value is `"%a %d/%m %R"`
    pub format: String,

    /// Update interval in seconds.
    ///
    /// The default value is `5`
    #[serde(deserialize_with = "deserialize_duration")]
    pub interval: Duration,

    /// A timezone specifier (e.g. "Europe/Lisbon").
    ///
    /// By default the local timezone is used
    pub timezone: Option<Tz>,

    /// Locale to apply when formatting the time.
    ///
    /// By default the system locale is used
    pub locale: Option<String>,
}

impl Default for TimeConfig {
    fn default() -> Self {
        Self {
            format: "%a %d/%m %R".to_string(),
            interval: Duration::from_secs(5),
            timezone: None,
            locale: None,
        }
    }
}

impl ConfigBlock for Time {
    type Config = TimeConfig;

    fn new(
        id: usize,
        block_config: Self::Config,
        shared_config: SharedConfig,
        _tx_update_request: Sender<Task>,
    ) -> Result<Self> {
        Ok(Time {
            id,
            time: TextWidget::new(id, 0, shared_config)
                .with_text("")
                .with_icon("time")?,
            update_interval: block_config.interval,
            format: block_config.format,
            timezone: block_config.timezone,
            locale: block_config.locale,
        })
    }
}

impl Block for Time {
    fn update(&mut self) -> Result<Option<Update>> {
        let time = match &self.locale {
            Some(l) => {
                let locale: Locale = l
                    .as_str()
                    .try_into()
                    .block_error("time", "invalid locale")?;
                match self.timezone {
                    Some(tz) => Utc::now()
                        .with_timezone(&tz)
                        .format_localized(&self.format, locale),
                    None => Local::now().format_localized(&self.format, locale),
                }
            }
            None => match self.timezone {
                Some(tz) => Utc::now().with_timezone(&tz).format(&self.format),
                None => Local::now().format(&self.format),
            },
        };
        self.time.set_text(format!("{}", time));
        Ok(Some(self.update_interval.into()))
    }

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

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