raventhemer 1.4.4

A theme manager and switcher for desktop linux
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647

pub mod rlib {
    use std::fs;
    use std::fs::{OpenOptions, DirEntry};
    use std::os::unix::fs::OpenOptionsExt;
    use std::io::Read;
    use std::env;
    use std::io::Write;
    use serde_json;
    use std::process::Command;
    use std::io;
    //Returns home directory as string
    fn get_home() -> String {
        return String::from(env::home_dir().unwrap().to_str().unwrap());
    }
    fn default_host() -> String {
        String::from("https://demenses.net")
    }
    pub fn default_screen() -> String {
        String::new()
    }
    fn default_desc() -> String {
        String::from("A raven theme.")
    }
    //Structure for holding theme info, stored in theme.json
    #[derive(Serialize, Deserialize, Debug)]
    pub struct ThemeStore {
        pub name: String,
        pub options: Vec<String>,
        pub enabled: Vec<String>,
        #[serde(default = "default_screen")]
        pub screenshot: String,
        #[serde(default = "default_desc")]
        pub description: String,
    }
    //Structure that holds all methods and data for individual themes.
    pub struct Theme {
        pub name: String,
        pub options: Vec<String>,
        pub monitor: i32,
        pub enabled: Vec<String>,
        pub order: Vec<String>,
    }
    //Config structure for holding all main config options
    #[derive(Serialize, Deserialize, Debug)]
    pub struct Config {
        pub monitors: i32,
        pub polybar: Vec<String>,
        pub menu_command: String,
        pub last: String,
        pub editing: String,
        #[serde(default = "default_host")]
        pub host: String,
    }


    impl Config {
        pub fn default() -> Config {
            Config {
                monitors: 1,
                polybar: vec!["main".to_string(), "other".to_string()],
                menu_command: "rofi -theme sidebar -mesg 'raven:' -p '> ' -dmenu".to_string(),
                last: "".to_string(),
                editing: "".to_string(),
                host: "https://demenses.net".to_string(),
            }
        }
    }
    // Methods for a loaded theme
    impl Theme {
        //Iterates through options and loads them with submethods
        pub fn load_all(&self) {
            let opt = &self.options;
            let mut i = 1;
            let len = opt.len();
            while i <= len {
                let ref option = opt[len - i];
                match option.to_lowercase().as_ref() {
                    "poly" => self.load_poly(self.monitor),
                    "wm" => self.load_i3(true),
                    "i3" => self.load_i3(false),
                    "xres" => self.load_xres(false),
                    "xres_m" => self.load_xres(true),
                    "pywal" => self.load_pywal(),
                    "wall" => self.load_wall(),
                    "ncmpcpp" => self.load_ncm(),
                    "termite" => self.load_termite(),
                    "script" => self.load_script(),
                    "bspwm" => self.load_bspwm(),
                    "rofi" => self.load_rofi(),
                    "ranger" => self.load_ranger(),
                    "lemonbar" => self.load_lemon(),
                    "openbox" => self.load_openbox(),
                    "dunst" => self.load_dunst(),
                    "|" => {}
                    _ => println!("Unknown option"),
                };
                if !option.contains("|") {
                    println!("Loaded option {}", option);
                }
                i += 1;

            }
            println!("Loaded all options for theme {}", self.name);

        }
        pub fn load_rofi(&self) {
            if fs::metadata(get_home() + "/.config/rofi").is_err() {
                fs::create_dir(get_home() + "/.config/rofi").unwrap();
            }
            fs::copy(
                get_home() + "/.config/raven/themes/" + &self.name + "/rofi",
                get_home() + "/.config/rofi/theme.rasi",
            ).expect("Couldn't copy rofi theme");
        }
        pub fn load_pywal(&self) {
            let arg = get_home() + "/.config/raven/themes/" + &self.name + "/pywal";
            Command::new("wal")
                .arg("-n")
                .arg("-i")
                .arg(arg)
                .output()
                .expect("Couldn't run pywal");
        }
        pub fn load_script(&self) {
            Command::new("sh")
                .arg("-c")
                .arg(
                    get_home() + "/.config/raven/themes/" + &self.name + "/script",
                )
                .output()
                .expect("Couldn't run custom script");
        }

        pub fn load_openbox(&self) {
            let mut base = String::new();
            if fs::metadata(get_home() + "/.config/raven/base_rc.xml").is_ok() {
                fs::File::open(get_home() + "/.config/raven/base_rc.xml")
                    .unwrap()
                    .read_to_string(&mut base)
                    .unwrap();

            }
            let mut rest = String::new();
            fs::File::open(
                get_home() + "/.config/raven/themes/" + &self.name + "/openbox",
            ).unwrap()
                .read_to_string(&mut rest)
                .unwrap();
            base.push_str(&rest);
            fs::remove_file(get_home() + "/.config/openbox/rc.xml").unwrap();
            OpenOptions::new()
                .create(true)
                .write(true)
                .open(get_home() + "/.config/openbox/rc.xml")
                .expect("Couldn't open rc.xml")
                .write_all(base.as_bytes())
                .unwrap();
            Command::new("openbox")
                .arg("--reconfigure")
                .output()
                .expect("Couldn't reload openbox");
        }
        pub fn load_ranger(&self) {
            fs::copy(
                get_home() + "/.config/raven/themes/" + &self.name + "/ranger",
                get_home() + "/.config/ranger/rc.conf",
            ).expect("Couldn't overwrite ranger config");
        }

        pub fn load_dunst(&self) {
            let mut config = String::new();
            if fs::metadata(get_home() + "/.config/raven/base_dunst").is_ok() {
                fs::File::open(get_home() + "/.config/raven/base_dunst")
                    .unwrap()
                    .read_to_string(&mut config)
                    .unwrap();
            }
            let mut app = String::new();
            fs::File::open(
                get_home() + "/.config/raven/themes/" + &self.name + "/dunst",
            ).unwrap()
                .read_to_string(&mut app)
                .unwrap();
            config.push_str(&app);
            fs::remove_file(get_home() + "/.config/dunst/dunstrc").unwrap();
            OpenOptions::new()
                .create(true)
                .write(true)
                .open(get_home() + "/.config/dunst/dunstrc")
                .expect("Couldn't open dunstrc")
                .write_all(config.as_bytes())
                .unwrap();
            Command::new("dunst").spawn().expect("Failed to run dunst");
        }

        pub fn load_ncm(&self) {
            if fs::metadata(get_home() + "/.config/ncmpcpp").is_ok() {
                fs::copy(
                    get_home() + "/.config/raven/themes/" + &self.name + "/ncmpcpp",
                    get_home() + "/.config/ncmpcpp/config",
                ).expect("Couldn't overwrite ncmpcpp config");
            } else if fs::metadata(get_home() + "/.ncmpcpp").is_ok() {
                fs::copy(
                    get_home() + "/.config/raven/themes/" + &self.name + "/ncmpcpp",
                    get_home() + "/.ncmpcpp/config",
                ).expect("Couldn't overwrite ncmpcpp config");
            } else {
                println!(
                    "Couldn't detect a ncmpcpp config directory in ~/.config/ncmppcp or ~/.ncmpcpp."
                );
            }

        }
        pub fn load_bspwm(&self) {
            let mut config = String::new();
            if fs::metadata(get_home() + "/.config/raven/base_bspwm").is_ok() {
                fs::File::open(get_home() + "/.config/raven/base_bspwm")
                    .unwrap()
                    .read_to_string(&mut config)
                    .unwrap();
            }
            let mut app = String::new();
            fs::File::open(
                get_home() + "/.config/raven/themes/" + &self.name + "/bspwm",
            ).unwrap()
                .read_to_string(&mut app)
                .unwrap();

            config.push_str(&app);
            fs::remove_file(get_home() + "/.config/bspwm/bspwmrc").unwrap();
            OpenOptions::new()
                .create(true)
                .write(true)
                .mode(0o744)
                .open(get_home() + "/.config/bspwm/bspwmrc")
                .expect("Couldn't open bspwmrc file")
                .write_all(config.as_bytes())
                .unwrap();
            Command::new("sh")
                .arg("-c")
                .arg(get_home() + "/.config/bspwm/bspwmrc")
                .output()
                .expect("Couldn't reload bspwm");
        }
        pub fn load_i3(&self, isw: bool) {
            let mut config = String::new();
            if fs::metadata(get_home() + "/.config/raven/base_i3").is_ok() {
                fs::File::open(get_home() + "/.config/raven/base_i3")
                    .unwrap()
                    .read_to_string(&mut config)
                    .unwrap();
            }
            let mut app = String::new();
            if isw {
                fs::File::open(get_home() + "/.config/raven/themes/" + &self.name + "/wm")
                    .unwrap()
                    .read_to_string(&mut app)
                    .unwrap();
            } else {
                fs::File::open(get_home() + "/.config/raven/themes/" + &self.name + "/i3")
                    .unwrap()
                    .read_to_string(&mut app)
                    .unwrap();
            }
            config.push_str(&app);
            if fs::metadata(get_home()+"/.config/i3").is_err() {
                fs::create_dir(get_home()+"/.config/i3").expect("Couldn't create i3 config dir");
            }
            if fs::metadata(get_home() + "/.config/i3/config").is_ok() {
                fs::remove_file(get_home() + "/.config/i3/config").expect("Couldn't remove previous i3 config");
            }
            OpenOptions::new()
                .create(true)
                .write(true)
                .open(get_home() + "/.config/i3/config")
                .expect("Couldn't open i3 file")
                .write_all(config.as_bytes())
                .unwrap();
            Command::new("i3-msg").arg("reload").output().expect(
                "Couldn't reload i3",
            );
        }
        pub fn load_termite(&self) {
            fs::copy(
                get_home() + "/.config/raven/themes/" + &self.name + "/termite",
                get_home() + "/.config/termite/config",
            ).expect("Couldn't overwrite termite config");
            Command::new("pkill")
                .arg("-SIGUSR1")
                .arg("termite")
                .output()
                .expect("Couldn't reload termite");
        }
        pub fn load_poly(&self, monitor: i32) {
            for number in 0..monitor {
                Command::new("sh")
                    .arg("-c")
                    .arg(
                        String::from("polybar --config=") + &get_home() +
                            "/.config/raven/themes/" + &self.name +
                            "/poly " + &self.order[number as usize] +
                            " > /dev/null 2> /dev/null",
                    )
                    .spawn()
                    .expect("Failed to run polybar");
            }
        }
        fn load_lemon(&self) {
            Command::new("sh")
                .arg(
                    get_home() + "/.config/raven/themes/" + &self.name + "/lemonbar",
                )
                .spawn()
                .expect("Failed to run lemonbar script");
        }
        fn load_wall(&self) {
            Command::new("feh")
                .arg("--bg-scale")
                .arg(get_home() + "/.config/raven/themes/" + &self.name + "/wall")
                .output()
                .expect("Failed to change wallpaper");
        }
        fn load_xres(&self, merge: bool) {
            let mut xres = Command::new("xrdb");
            let mut name = String::from("xres");
            if merge {
                name.push_str("_m");
                xres.arg("-merge");
            }
            xres.arg(
                get_home() + "/.config/raven/themes/" + &self.name + "/" + &name,
            ).output()
                .expect("Could not run xrdb");

        }
    }
    //Checks to see if base config/directories need to be initialized
    pub fn check_init() -> bool {
        if fs::metadata(get_home() + "/.config/raven").is_err() ||
            fs::metadata(get_home() + "/.config/raven/config.json").is_err() ||
            fs::metadata(get_home() + "/.config/raven/themes").is_err()
        {
            true
        } else {
            false
        }
    }
    //Check to see if there are themes still using the old format
    pub fn check_themes() {
        let entries = get_themes();
        for entry in entries {
            if fs::metadata(get_home() + "/.config/raven/themes/" + &entry + "/theme").is_ok() {
                convert_theme(&entry);
            }
        }
    }
    pub fn init() {
        //Create base raven directories and config file(s)
        if fs::metadata(get_home() + "/.config/raven/config").is_err() {
            fs::create_dir(get_home() + "/.config/raven").unwrap();
            fs::create_dir(get_home() + "/.config/raven/themes").unwrap();
        } else {
            println!(
                "The config file format has changed. Please check ~/.config/raven/config.json to reconfigure raven."
            );
        }
        let mut file = OpenOptions::new()
            .create(true)
            .write(true)
            .open(get_home() + "/.config/raven/config.json")
            .unwrap();
        let default = serde_json::to_string(&Config::default()).unwrap();
        file.write_all(default.as_bytes()).unwrap();
        println!("Correctly initialized base config. Please run again to use raven.");
    }
    //Start ravend
    pub fn start_daemon() {
        Command::new("sh").arg("-c").arg("ravend").spawn().expect(
            "Couldn't start daemon.",
        );
        println!("Started cycle daemon.");

    }
    pub fn stop_daemon() {
        Command::new("pkill")
            .arg("-SIGKILL")
            .arg("ravend")
            .output()
            .expect("Couldn't stop daemon.");
        println!("Stopped cycle daemon.");
    }
    pub fn check_daemon() -> bool {
        let out = Command::new("ps").arg("aux").output().expect(
            "Couldn't find daemon",
        );
        let form_out = String::from_utf8_lossy(&out.stdout);
        let line_num = form_out.lines().filter(|x| x.contains("ravend")).count();
        if line_num > 0 { true } else { false }
    }
    pub fn edit(theme_name: &str) {
        //Add and rm commands will affect the theme you are currently editing
        if fs::metadata(get_home() + "/.config/raven/themes/" + &theme_name).is_ok() {
            let mut conf = get_config();
            conf.editing = theme_name.to_string();
            up_config(conf);
            println!("You are now editing the theme {}", &theme_name);
        } else {
            println!("That theme does not exist");
        }
    }
    pub fn clear_prev() {
        Command::new("pkill").arg("polybar").output().unwrap();
        Command::new("pkill").arg("lemonbar").output().unwrap();
        Command::new("pkill").arg("dunst").output().unwrap();
    }
    pub fn del_theme(theme_name: &str) {
        fs::remove_dir_all(get_home() + "/.config/raven/themes/" + &theme_name)
            .expect("Couldn't delete theme");;
    }
    pub fn refresh_theme(last: String) {
        //Load last loaded theme
        if last.chars().count() > 0 {
            run_theme(load_theme(last.trim()).unwrap());
        } else {

            println!("No last theme saved. Cannot refresh.");
        }
    }
    pub fn proc_path(path: DirEntry) -> String {
        //Converts DirEntry into a fully processed file/directory name
        let base = path.file_name().into_string().unwrap();
        return base;
    }
    pub fn new_theme(theme_name: &str) {
        //Create new theme directory and 'theme' file
        let res = fs::create_dir(get_home() + "/.config/raven/themes/" + &theme_name);
        if res.is_ok() {
            res.unwrap();
            let mut file = OpenOptions::new()
                .create(true)
                .write(true)
                .open(
                    get_home() + "/.config/raven/themes/" + &theme_name + "/theme.json",
                )
                .expect("can open");
            let stdef = ThemeStore {
                name: String::from(theme_name),
                options: vec![],
                enabled: vec![],
                screenshot: default_screen(),
                description: default_desc(),
            };
            let st = serde_json::to_string(&stdef).unwrap();
            file.write_all(st.as_bytes()).unwrap();
            edit(&theme_name);
        } else {
            println!("Theme {} already exists", &theme_name);
        }
    }


    pub fn add_to_theme(theme_name: &str, option: &str, path: &str) {
        //Add an option to a theme
        let cur_theme = load_theme(theme_name).unwrap();
        let cur_st = load_store(String::from(theme_name));
        let mut new_themes = ThemeStore {
            name: theme_name.to_string(),
            options: cur_theme.options,
            enabled: cur_theme.enabled,
            screenshot: cur_st.screenshot,
            description: cur_st.description,
        };
        let mut already_used = false;
        for opt in &new_themes.options {
            if opt == option {
                already_used = true;
            }
        }
        if !already_used {
            new_themes.options.push(String::from(option));
            up_theme(new_themes);
        }
        let mut totpath = env::current_dir().unwrap();
        totpath.push(path);
        fs::copy(
            totpath,
            get_home() + "/.config/raven/themes/" + &theme_name + "/" + &option,
        ).expect("Couldn't copy config in");

    }
    pub fn rm_from_theme(theme_name: &str, option: &str) {
        //Remove an option from a theme
        let cur_theme = load_theme(theme_name).unwrap();
        let cur_st = load_store(String::from(theme_name));
        let mut new_themes = ThemeStore {
            name: theme_name.to_string(),
            options: cur_theme.options,
            enabled: cur_theme.enabled,
            screenshot: cur_st.screenshot,
            description: cur_st.description,
        };
        let mut found = false;
        let mut i = 0;
        while i < new_themes.options.len() {
            if &new_themes.options[i] == option {
                println!("Found option {}", option);
                found = true;
                new_themes.options.remove(i);
            }
            i += 1;
        }
        if found {
            up_theme(new_themes);
        } else {
            println!("Couldn't find option {}", option);
        }
    }
    pub fn run_theme(new_theme: Theme) {
        //Run/refresh a loaded Theme
        new_theme.load_all();
        let mut conf = get_config();
        conf.last = new_theme.name;
        up_config(conf);
    }
    pub fn up_config(conf: Config) {
        OpenOptions::new()
            .create(true)
            .write(true)
            .open(get_home() + "/.config/raven/~config.json")
            .expect("Couldn't open last theme file")
            .write_all(serde_json::to_string(&conf).unwrap().as_bytes())
            .expect("Couldn't write to last theme file");
        fs::copy(
            get_home() + "/.config/raven/~config.json",
            get_home() + "/.config/raven/config.json",
        ).unwrap();
        fs::remove_file(get_home() + "/.config/raven/~config.json").unwrap();
    }
    pub fn up_theme(theme: ThemeStore) {
        let wthemepath = get_home() + "/.config/raven/themes/" + &theme.name + "/~theme.json";
        let themepath = get_home() + "/.config/raven/themes/" + &theme.name + "/theme.json";
        OpenOptions::new()
            .create(true)
            .write(true)
            .open(&wthemepath)
            .expect("Couldn't open theme file")
            .write_all(serde_json::to_string(&theme).unwrap().as_bytes())
            .expect("Couldn't write to theme file");
        fs::copy(&wthemepath, &themepath).unwrap();
        fs::remove_file(&wthemepath).unwrap();
    }

    pub fn convert_theme(theme_name: &str) {
        let mut theme = String::new();
        fs::File::open(
            get_home() + "/.config/raven/themes/" + theme_name + "/theme",
        ).expect("Couldn't read theme")
            .read_to_string(&mut theme)
            .unwrap();
        let options = theme
            .split('|')
            .map(|x| String::from(String::from(x).trim()))
            .filter(|x| x.len() > 0)
            .filter(|x| x != "|")
            .collect::<Vec<String>>();
        let themes = ThemeStore {
            name: theme_name.to_string(),
            enabled: Vec::new(),
            options: options,
            screenshot: default_screen(),
            description: default_desc(),
        };
        fs::remove_file(
            get_home() + "/.config/raven/themes/" + theme_name + "/theme",
        ).unwrap();
        OpenOptions::new()
            .create(true)
            .write(true)
            .open(
                get_home() + "/.config/raven/themes/" + theme_name + "/theme.json",
            )
            .expect("Can't open theme.json")
            .write_all(serde_json::to_string(&themes).unwrap().as_bytes())
            .unwrap();
    }
    pub fn load_store(theme: String) -> ThemeStore {
        let mut st = String::new();
        fs::File::open(
            get_home() + "/.config/raven/themes/" + &theme + "/theme.json",
        ).unwrap()
            .read_to_string(&mut st)
            .unwrap();
        let thinf: ThemeStore = serde_json::from_str(&st).unwrap();
        thinf
    }
    pub fn load_theme(theme_name: &str) -> Result<Theme, &'static str> {
        //Load in data for and run loading methods for a specific theme
        let conf = get_config();
        let ent_res = fs::read_dir(get_home() + "/.config/raven/themes/" + &theme_name);
        if ent_res.is_ok() {
            println!("Found theme {}", theme_name);
            if fs::metadata(
                get_home() + "/.config/raven/themes/" + &theme_name + "/theme.json",
            ).is_ok()
            {
                let theme_info = load_store(String::from(theme_name));
                let opts: Vec<String> = theme_info.options;
                let new_theme = Theme {
                    name: String::from(theme_name),
                    options: opts,
                    monitor: conf.monitors,
                    enabled: theme_info.enabled,
                    order: conf.polybar.clone(),
                };
                Ok(new_theme)
            } else {

                Err("Can't find Theme data")
            }
        } else {
            println!("Theme does not exist.");
            ::std::process::exit(64);
        }

    }

    pub fn get_config() -> Config {
        //Retrieve config settings from file
        let mut conf = String::new();
        fs::File::open(get_home() + "/.config/raven/config.json")
            .expect("Couldn't read config")
            .read_to_string(&mut conf)
            .unwrap();
        let config: Config = serde_json::from_str(&conf).expect("Couldn't read config file");
        config
    }
    pub fn get_themes() -> Vec<String> {
        let mut entries = fs::read_dir(get_home() + "/.config/raven/themes")
            .expect("Couldn't read themes")
            .collect::<Vec<io::Result<DirEntry>>>()
            .into_iter()
            .map(|x| proc_path(x.unwrap()))
            .collect::<Vec<String>>();
        return entries;
    }
}