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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//! Configuration manipulation and handling for common browser options
use std::env;
use std::fs::File;
use std::io::Read;
use std::collections::HashMap;

use toml::Value;

use ui::BrowserConfiguration;


pub const DEFAULT_CONFIG: &'static str = r#"
[general]
private-browsing = false

[window]
start-page = "https://delisa.fuller.li"

[new-frame]
opens-in-focused-window = false
"#;

/// Placeholder used in webkitten configuration to represent the configuration
/// property `general.config-dir`.
const CONFIG_DIR: &'static str = "CONFIG_DIR";

const HOME: &'static str = "HOME";

/// Configuration option storage and lookup
///
/// ## Examples
///
/// Using a start page setting for new windows
///
/// ```
/// use webkitten::config::Config;
/// use webkitten::ui::BrowserConfiguration;
///
/// let config = Config::parse(r#"
/// [window]
/// start-page = "file:///path/to/the/page.html"
/// "#).unwrap();
/// let start_page = config.start_page().unwrap();
/// assert_eq!("file:///path/to/the/page.html", &start_page);
/// ```
///
/// Replacing `CONFIG_DIR` in string options with a preferred path
///
/// ```
/// use webkitten::config::Config;
/// use webkitten::ui::BrowserConfiguration;
///
/// let config = Config::parse(r#"
/// [general]
/// config-dir = "/path/to/config"
/// [window]
/// start-page = "file://CONFIG_DIR/page.html"
/// "#).unwrap();
/// let start_page = config.start_page().unwrap();
/// assert_eq!("file:///path/to/config/page.html", &start_page);
/// ```
///
/// Looking up a custom field
///
/// ```
/// use webkitten::config::Config;
/// use webkitten::ui::BrowserConfiguration;
///
/// let config = Config::parse(r#"
/// [dependencies]
/// external-path = "/path/to/bin"
/// "#).unwrap();
/// let path = config.lookup_str("dependencies.external-path").unwrap();
/// assert_eq!("/path/to/bin", &path);
/// ```
///
/// Overriding a field with site-specific options
///
/// ```
/// use webkitten::config::Config;
/// use webkitten::ui::BrowserConfiguration;
///
/// let config = Config::parse(r#"
/// [dessert]
/// pie = false
/// [sites."example.us".dessert]
/// pie = true
/// "#).unwrap();
/// let pie = config.lookup_site_bool("http://example.us/other/stuff.html",
///                                   "dessert.pie");
/// assert_eq!(true, pie.unwrap());
/// ```
///
/// Using global fallback for a missing site-specific option
///
/// ```
/// use webkitten::config::Config;
/// use webkitten::ui::BrowserConfiguration;
///
/// let config = Config::parse(r#"
/// [dependencies]
/// external-path = "/path/to/bin"
/// [sites."example.com".dependencies]
/// external-path = "/path/to/sites-bin"
/// "#).unwrap();
/// let path = config.lookup_site_str("http://example.co.uk/old", "dependencies.external-path");
/// assert_eq!("/path/to/bin", &path.unwrap());
/// ```
pub struct Config {
    value: Value
}

impl BrowserConfiguration for Config {

    fn parse(raw_input: &str) -> Option<Self> {
        match raw_input.parse() {
            Ok(value) => Some(Config { value: value }),
            Err(errors) => {
                for err in errors { error!("Failed to parse toml: {}", err); }
                None
            },
        }
    }

    fn lookup_bool<'a>(&'a self, key: &'a str) -> Option<bool> {
        self.lookup(key)
            .and_then(|value| value.as_bool())
    }

    fn lookup_raw_str<'a>(&'a self, key: &'a str) -> Option<String> {
        self.lookup(key)
            .and_then(|value| value.as_str())
            .and_then(|value| Some(String::from(value)))
    }

    fn lookup_str<'a>(&'a self, key: &'a str) -> Option<String> {
        self.lookup_raw_str(key)
            .and_then(|value| Some(self.parse_path(&value)))
    }

    fn lookup_integer<'a>(&'a self, key: &'a str) -> Option<i64> {
        self.lookup(key)
            .and_then(|value| value.as_integer())
    }

    fn lookup_str_table(&self, key: &str) -> Option<HashMap<String, String>> {
        if let Some(table) = self.lookup(key).and_then(|value| value.as_table()) {
            let mut map: HashMap<String, String> = HashMap::new();
            for (key, raw_value) in table {
                if let Some(value) = raw_value.as_str() {
                    map.insert(key.to_owned(), value.to_owned());
                }
            }
            return Some(map);
        }
        None
    }

    fn lookup_str_vec(&self, key: &str) -> Option<Vec<String>> {
        self.lookup(key)
            .and_then(|value| value.as_slice())
            .and_then(|values| {
                let mut str_values: Vec<String> = vec![];
                for value in values {
                    if let Some(value) = value.as_str() {
                        str_values.push(self.parse_path(value))
                    }
                }
                Some(str_values)
            })
    }
}

impl Config {

    /// Create a `Configuration` with the default options
    pub fn default() -> Option<Self> {
        Config::parse(DEFAULT_CONFIG)
    }

    /// Reload cached configuration from disk returns true if parsing is
    /// successful
    pub fn load(&mut self, path: &str) -> bool {
        if let Some(update) = Config::parse_file(path) {
            self.value = update.value;
            true
        } else {
            false
        }
    }

    /// Parse a file at a path and create a `Configuration` if possible
    pub fn parse_file(path: &str) -> Option<Self> {
        let mut buffer = String::new();
        File::open(path).ok()
            .and_then(|mut file| file.read_to_string(&mut buffer).ok())
            .and_then(|_| Config::parse(buffer.as_str()))
    }

    /// Look up the raw TOML value for a key
    fn lookup<'a>(&'a self, key: &'a str) -> Option<&Value> {
        self.value.lookup(&key.clone())
    }

    fn parse_path(&self, value: &str) -> String {
        self.replace_config_dir(&self.replace_home(value))
    }

    fn replace_config_dir<'a>(&self, value: &'a str) -> String {
        self.config_dir()
            .and_then(|dir| Some(value.replace(CONFIG_DIR, &dir)))
            .unwrap_or(String::from(value))
    }

    fn replace_home(&self, value: &str) -> String {
        if let Some(home) = env::home_dir() {
            if let Some(home) = home.to_str() {
                return value.replace(HOME, &home)
            }
        }
        String::from(value)
    }
}

#[cfg(test)]
mod tests {

    use super::Config;
    use ui::{BrowserConfiguration,BufferEvent};

    #[test]
    fn lookup_fail_uri_commands() {
        let config = Config::parse(r#"
        [commands]
        on-fail-uri = ["bob","refresh"]
        "#).unwrap();
        let commands = config.on_buffer_event_commands(&BufferEvent::Fail(String::new()));
        assert_eq!(2, commands.len());
        assert_eq!(String::from("bob"), commands[0]);
        assert_eq!(String::from("refresh"), commands[1]);
    }

    #[test]
    fn lookup_request_uri_commands() {
        let config = Config::parse(r#"
        [commands]
        on-request-uri = ["bob","refresh"]
        "#).unwrap();
        let commands = config.on_buffer_event_commands(&BufferEvent::Request);
        assert_eq!(2, commands.len());
        assert_eq!(String::from("bob"), commands[0]);
        assert_eq!(String::from("refresh"), commands[1]);
    }

    #[test]
    fn lookup_load_uri_commands() {
        let config = Config::parse(r#"
        [commands]
        on-load-uri = ["bob","refresh"]
        "#).unwrap();
        let commands = config.on_buffer_event_commands(&BufferEvent::Load);
        assert_eq!(2, commands.len());
        assert_eq!(String::from("bob"), commands[0]);
        assert_eq!(String::from("refresh"), commands[1]);
    }

    #[test]
    fn lookup_site_override_vec() {
        let config = Config::parse(r#"
        [commands]
        on-load-uri = ["bob","refresh"]
        [sites."example.com".commands]
        on-load-uri = ["frut"]
        "#).unwrap();
        let commands = config.lookup_site_str_vec("example.com/page.html",
                                                  "commands.on-load-uri").unwrap();
        assert_eq!(1, commands.len());
        assert_eq!(String::from("frut"), commands[0]);
    }
}