wiki-tui 0.4.7

A simple and easy to use Wikipedia Text User Interface
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
use crate::cli::Cli;

use anyhow::{
    Result,
    Context,
    bail
};
use cursive::theme::{BaseColor, Color};
use lazy_static::*;
use log::LevelFilter;
use serde::Deserialize;
use std::{path::PathBuf, str::FromStr};
use structopt::StructOpt;
use toml::from_str;

const CONFIG_FILE: &str = "config.toml";
const CONFIG_DIR: &str = ".config";
const APP_DIR: &str = "wiki-tui";

lazy_static! {
    pub static ref CONFIG: Config = Config::new();
}

pub struct Theme {
    pub text: Color,
    pub title: Color,
    pub highlight: Color,
    pub background: Color,
    pub search_match: Color,
    pub highlight_text: Color,
    pub highlight_inactive: Color,

    pub search_bar: Option<ViewTheme>,
    pub search_results: Option<ViewTheme>,
    pub search_preview: Option<ViewTheme>,

    pub article_view: Option<ViewTheme>,
    pub toc_view: Option<ViewTheme>,
}

impl Theme {
    pub fn to_theme(&self) -> cursive::theme::Theme {
        cursive::theme::Theme {
            palette: {
                let mut custom_palette = cursive::theme::Palette::default();

                custom_palette.set_color("View", self.background);
                custom_palette.set_color("Background", self.background);
                custom_palette.set_color("Primary", self.text);
                custom_palette.set_color("TitlePrimary", self.title);
                custom_palette.set_color("Highlight", self.highlight);
                custom_palette.set_color("HighlightInactive", self.highlight_inactive);
                custom_palette.set_color("HighlightText", self.highlight_text);

                custom_palette
            },
            ..Default::default()
        }
    }
}

pub struct ViewTheme {
    // TODO: Add borders
    pub background: Color,
    pub text: Color,
    pub title: Color,
    pub secondary: Color,
    pub highlight: Color,
    pub highlight_text: Color,
    pub highlight_inactive: Color,
}

impl ViewTheme {
    pub fn to_theme(&self) -> cursive::theme::Theme {
        cursive::theme::Theme {
            palette: {
                let mut custom_palette = cursive::theme::Palette::default();

                custom_palette.set_color("View", self.background);
                custom_palette.set_color("Background", self.background);
                custom_palette.set_color("Primary", self.text);
                custom_palette.set_color("TitlePrimary", self.title);
                custom_palette.set_color("Highlight", self.highlight);
                custom_palette.set_color("HighlightInactive", self.highlight_inactive);
                custom_palette.set_color("HighlightText", self.highlight_text);

                custom_palette
            },
            ..Default::default()
        }
    }
}

#[derive(Clone, Debug)]
pub struct ApiConfig {
    pub base_url: String,
}

pub struct Logging {
    pub enabled: bool,
    pub log_dir: PathBuf,
    pub log_level: LevelFilter,
}

#[derive(Debug)]
pub struct ParserConfig {
    pub toc: bool,
    pub headers: bool,
    pub paragraphs: bool,
    pub lists: bool,
    pub code_blocks: bool,
}

pub struct Features {
    pub links: bool,
    pub headers: bool,
}

pub struct Config {
    pub api_config: ApiConfig,
    pub theme: Theme,
    pub logging: Logging,
    pub parser: ParserConfig,
    pub features: Features,
    config_path: PathBuf,
    args: Cli,
}

#[derive(Deserialize, Debug)]
struct UserConfig {
    api: Option<UserApiConfig>,
    theme: Option<UserTheme>,
    logging: Option<UserLogging>,
    parser: Option<UserParserConfig>,
    features: Option<UserFeatures>,
}

#[derive(Deserialize, Debug)]
struct UserTheme {
    text: Option<String>,
    title: Option<String>,
    highlight: Option<String>,
    background: Option<String>,
    search_match: Option<String>,
    highlight_text: Option<String>,
    highlight_inactive: Option<String>,

    search_bar: Option<UserViewTheme>,
    search_results: Option<UserViewTheme>,
    search_preview: Option<UserViewTheme>,

    article_view: Option<UserViewTheme>,
    toc_view: Option<UserViewTheme>,
}

#[derive(Deserialize, Debug)]
struct UserViewTheme {
    text: Option<String>,
    title: Option<String>,
    highlight: Option<String>,
    background: Option<String>,
    highlight_text: Option<String>,
    highlight_inactive: Option<String>,
}

#[derive(Deserialize, Debug)]
struct UserApiConfig {
    base_url: Option<String>,
}

#[derive(Deserialize, Debug)]
struct UserLogging {
    enabled: Option<bool>,
    log_dir: Option<String>,
    log_level: Option<String>,
}

#[derive(Deserialize, Debug)]
struct UserParserConfig {
    toc: Option<bool>,
    headers: Option<bool>,
    paragraphs: Option<bool>,
    lists: Option<bool>,
    code_blocks: Option<bool>,
}

#[derive(Deserialize, Debug)]
struct UserFeatures {
    links: Option<bool>,
    headers: Option<bool>,
}

impl Config {
    pub fn new() -> Config {
        // initialize the configuration with the defaults
        let mut config = Config {
            api_config: ApiConfig {
                base_url: "https://en.wikipedia.org/".to_string(),
            },
            theme: Theme {
                background: Color::Dark(BaseColor::White),
                title: Color::Dark(BaseColor::Red),
                highlight: Color::Dark(BaseColor::Red),
                highlight_inactive: Color::Dark(BaseColor::Blue),
                highlight_text: Color::Dark(BaseColor::White),
                text: Color::Dark(BaseColor::Black),
                search_match: Color::Dark(BaseColor::Red),

                search_bar: None,
                search_results: None,
                search_preview: None,

                article_view: None,
                toc_view: None,
            },
            logging: Logging {
                enabled: true,
                log_dir: PathBuf::from("wiki_tui.log"),
                log_level: LevelFilter::Info,
            },
            parser: ParserConfig {
                toc: true,
                headers: true,
                paragraphs: true,
                lists: true,
                code_blocks: true,
            },
            features: Features {
                links: true,
                headers: true,
            },
            config_path: PathBuf::new(),
            args: Cli::from_args(),
        };

        // load the configuration from the file
        log::info!("loading the config");
        config.load_config();

        // return the config
        config
    }

    fn load_config(&mut self) {
        // load (or create if they don't exist) the config path(s)
        // this function returns true if the config file exists and false if not
        let config_exists = self.load_or_create_config_paths();

        // check, if any errors occured during loading
        if config_exists.is_err() {
            // abort the loading and return the error
            log::warn!("{:?}", config_exists);
            return;
        }

        // read the config file and check if there were any errors
        let config_str = match std::fs::read_to_string(&self.config_path)
            .context("failed reading the config file")
        {
            Ok(config) => {
                log::info!("successfully read the config file");
                config
            }
            Err(error) => {
                log::warn!("{:?}", error);
                return;
            }
        };

        let user_config = match from_str::<UserConfig>(&config_str).context("wrong format") {
            Ok(config) => {
                log::info!("successfully deserialized config");
                config
            }
            Err(error) => {
                log::warn!("deserializing the config file failed, {:?}", error);
                return;
            }
        };

        if let Some(user_theme) = user_config.theme {
            self.load_theme(&user_theme);
        }

        if let Some(user_api_config) = user_config.api {
            self.load_api_config(&user_api_config);
        }

        if let Some(user_logging) = user_config.logging {
            self.load_logging(&user_logging);
        }

        if let Some(user_parser) = user_config.parser {
            self.load_parser(&user_parser);
        }

        if let Some(user_features) = user_config.features {
            self.load_features(&user_features);
        }

        // override the log level
        if let Some(log_level) = self.args.level.as_ref() {
            let level = match log_level {
                0 => LevelFilter::Debug,
                1 => LevelFilter::Info,
                2 => LevelFilter::Warn,
                3 => LevelFilter::Error,
                _ => self.logging.log_level,
            };
            log::info!("overriding the configured log level to '{}'", level);
            self.logging.log_level = level;
        }
    }

    fn load_or_create_config_paths(&mut self) -> Result<bool> {
        // get the platform specific config directory
        let config_dir = match dirs::home_dir() {
            Some(config_dir) => {
                log::info!(
                    "the config directory is {}",
                    config_dir.join(CONFIG_DIR).to_str().unwrap()
                );
                config_dir.join(CONFIG_DIR)
            }
            None => {
                bail!("couldn't find the home directory")
            }
        };

        // build the app config path and the config file path
        let app_config_dir = config_dir.join(APP_DIR);
        let config_file_dir = app_config_dir.join(CONFIG_FILE);

        // create the app config folder if it doesn't exist
        if !app_config_dir.exists() {
            log::info!("the app config directory doesn't exist, creating it now");
            std::fs::create_dir(app_config_dir)
                .context("couldn't create the app config directory")?;
        }

        // check, if the config file exists
        if !config_file_dir.exists() {
            log::info!("the config file doesn't exist");
            return Ok(false);
        }

        // if the config file exists,
        // return true and store the path to it
        log::info!(
            "location of the config file: '{}'",
            // the path can be non unicode so we have to check for that
            config_file_dir.to_str().unwrap_or("UNICODE_ERROR")
        );
        self.config_path = config_file_dir;
        Ok(true)
    }

    fn load_api_config(&mut self, user_api_config: &UserApiConfig) {
        log::info!("loading the api configuration");

        // define the macro for loading individual api settings
        macro_rules! to_api_setting {
            ($setting: ident) => {
                if user_api_config.$setting.is_some() {
                    self.api_config.$setting =
                        user_api_config.$setting.as_ref().unwrap().to_string();
                }
            };
        }

        to_api_setting!(base_url);
    }

    fn load_theme(&mut self, user_theme: &UserTheme) {
        log::info!("loading the theme configuration");

        // define the macro for loading individual color settings
        macro_rules! to_theme_color {
            ($color: ident) => {
                if user_theme.$color.is_some() {
                    match parse_color(user_theme.$color.as_ref().unwrap().to_string()) {
                        Ok(color) => {
                            self.theme.$color = color;
                        }
                        Err(error) => {
                            log::warn!("{}", error);
                        }
                    };
                }
            };
        }

        // now load the settings
        to_theme_color!(text);
        to_theme_color!(title);
        to_theme_color!(highlight);
        to_theme_color!(background);
        to_theme_color!(search_match);
        to_theme_color!(highlight_text);
        to_theme_color!(highlight_inactive);

        if let Some(search_bar) = &user_theme.search_bar {
            let background_changed: bool = search_bar.background.is_some();

            let mut search_bar_theme = self.load_view_theme(search_bar);
            if background_changed {
                search_bar_theme.secondary = search_bar_theme.background;
            }

            self.theme.search_bar = Some(search_bar_theme);
        }

        if let Some(search_results) = &user_theme.search_results {
            self.theme.search_results = Some(self.load_view_theme(search_results));
        }

        if let Some(search_preview) = &user_theme.search_preview {
            self.theme.search_preview = Some(self.load_view_theme(search_preview));
        }

        if let Some(article_view) = &user_theme.article_view {
            self.theme.article_view = Some(self.load_view_theme(article_view));
        }

        if let Some(toc_view) = &user_theme.toc_view {
            self.theme.toc_view = Some(self.load_view_theme(toc_view));
        }
    }

    fn load_view_theme(&self, user_view_theme: &UserViewTheme) -> ViewTheme {
        let mut view_theme = self.create_view_theme();

        macro_rules! to_view_theme {
            ($color: ident) => {
                if user_view_theme.$color.is_some() {
                    match parse_color(user_view_theme.$color.as_ref().unwrap().to_string()) {
                        Ok(color) => {
                            view_theme.$color = color;
                        }
                        Err(error) => {
                            log::warn!("{}", error);
                        }
                    };
                }
            };
        }

        to_view_theme!(text);
        to_view_theme!(title);
        to_view_theme!(highlight);
        to_view_theme!(background);
        to_view_theme!(highlight_text);
        to_view_theme!(highlight_inactive);

        view_theme
    }

    fn create_view_theme(&self) -> ViewTheme {
        ViewTheme {
            background: self.theme.background,
            text: self.theme.text,
            title: self.theme.title,
            secondary: Color::parse("blue").unwrap(),
            highlight: self.theme.highlight,
            highlight_text: self.theme.highlight_text,
            highlight_inactive: self.theme.highlight_inactive,
        }
    }

    fn load_logging(&mut self, user_logging: &UserLogging) {
        log::info!("loading the logging configuration");

        if let Some(enabled) = user_logging.enabled {
            self.logging.enabled = enabled;
        }

        if let Some(log_dir) = user_logging.log_dir.as_ref() {
            if let Ok(path) = PathBuf::from_str(log_dir) {
                self.logging.log_dir = path;
            }
        }

        if let Some(log_level) = user_logging.log_level.as_ref() {
            if let Ok(level) = LevelFilter::from_str(log_level) {
                self.logging.log_level = level;
            }
        }
    }

    fn load_parser(&mut self, user_parser: &UserParserConfig) {
        log::info!("loading the parser configuration");

        if let Some(toc) = user_parser.toc {
            self.parser.toc = toc;
        }
        if let Some(headers) = user_parser.headers {
            self.parser.headers = headers;
        }
        if let Some(paragraphs) = user_parser.paragraphs {
            self.parser.paragraphs = paragraphs;
        }
        if let Some(lists) = user_parser.lists {
            self.parser.lists = lists;
        }
        if let Some(code_blocks) = user_parser.code_blocks {
            self.parser.code_blocks = code_blocks;
        }
    }

    fn load_features(&mut self, user_features: &UserFeatures) {
        log::info!("loading the article features");

        if let Some(links) = user_features.links {
            self.features.links = links;
        }

        if let Some(headers) = user_features.headers {
            self.features.headers = headers;
        }
    }

    pub fn get_args(&self) -> &Cli {
        &self.args
    }
}

fn parse_color(color: String) -> Result<Color> {
    Color::parse(&color.to_lowercase()).context("Failed loading the color")
}

impl Default for Config {
    fn default() -> Self {
        Self::new()
    }
}