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
// Copyright (C) 2021  Tassilo Horn <tsdh@gnu.org>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program.  If not, see <https://www.gnu.org/licenses/>.

//! TOML configuration for swayr.

use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::DirBuilder;
use std::fs::OpenOptions;
use std::io::{Read, Write};
use std::path::Path;

#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    pub menu: Option<Menu>,
    pub format: Option<Format>,
    pub layout: Option<Layout>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Menu {
    pub executable: Option<String>,
    pub args: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Format {
    pub window_format: Option<String>,
    pub workspace_format: Option<String>,
    pub urgency_start: Option<String>,
    pub urgency_end: Option<String>,
    pub icon_dirs: Option<Vec<String>>,
    pub fallback_icon: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Layout {
    pub auto_tile: Option<bool>,
    pub auto_tile_min_window_width_per_output_width: Option<Vec<[i32; 2]>>,
}

impl Layout {
    pub fn auto_tile_min_window_width_per_output_width_as_map(
        &self,
    ) -> Option<HashMap<i32, i32>> {
        if let Some(vec) = &self.auto_tile_min_window_width_per_output_width {
            let mut map = HashMap::new();
            for tup in vec {
                map.insert(tup[0], tup[1]);
            }
            Some(map)
        } else {
            None
        }
    }
}

impl Default for Menu {
    fn default() -> Self {
        Menu {
            executable: Some("wofi".to_string()),
            args: Some(vec![
                "--show=dmenu".to_string(),
                "--allow-markup".to_string(),
                "--allow-images".to_string(),
                "--insensitive".to_string(),
                "--cache-file=/dev/null".to_string(),
                "--parse-search".to_string(),
                "--prompt={prompt}".to_string(),
            ]),
        }
    }
}

impl Default for Format {
    fn default() -> Self {
        Format {
            window_format: Some(
                "{urgency_start}<b>“{title}”</b>{urgency_end} \
                 — <i>{app_name}</i> on workspace {workspace_name}   \
                 <span alpha=\"20000\">({id})</span>"
                    .to_string(),
            ),
            workspace_format: Some(
                "<b>Workspace {name}</b>   \
                 <span alpha=\"20000\">({id})</span>"
                    .to_string(),
            ),
            urgency_start: Some(
                "<span background=\"darkred\" foreground=\"yellow\">"
                    .to_string(),
            ),
            urgency_end: Some("</span>".to_string()),
            icon_dirs: Some(vec![
                "/usr/share/icons/hicolor/scalable/apps".to_string(),
                "/usr/share/icons/hicolor/48x48/apps".to_string(),
                "/usr/share/pixmaps".to_string(),
            ]),
            fallback_icon: None,
        }
    }
}

impl Default for Layout {
    fn default() -> Layout {
        let resolution_min_width_vec = vec![
            [1024, 500],
            [1280, 600],
            [1400, 680],
            [1440, 700],
            [1600, 780],
            [1920, 920],
            [2560, 1000],
            [3440, 1000],
            [4096, 1200],
        ];

        Layout {
            auto_tile: Some(false),
            auto_tile_min_window_width_per_output_width: Some(
                resolution_min_width_vec,
            ),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            menu: Some(Menu::default()),
            format: Some(Format::default()),
            layout: Some(Layout::default()),
        }
    }
}

fn get_config_file_path() -> Box<Path> {
    let proj_dirs = ProjectDirs::from("", "", "swayr").expect("");
    let config_dir = proj_dirs.config_dir();
    if !config_dir.exists() {
        DirBuilder::new()
            .recursive(true)
            .create(config_dir)
            .unwrap();
    }
    config_dir.join("config.toml").into_boxed_path()
}

pub fn save_config(cfg: Config) {
    let path = get_config_file_path();
    let content =
        toml::to_string_pretty(&cfg).expect("Cannot serialize config.");
    let mut file = OpenOptions::new()
        .read(false)
        .write(true)
        .create(true)
        .open(path)
        .unwrap();
    file.write_all(content.as_str().as_bytes()).unwrap();
}

pub fn load_config() -> Config {
    let path = get_config_file_path();
    if !path.exists() {
        save_config(Config::default());
        // Tell the user that a fresh default config has been created.
        std::process::Command::new("swaynag")
            .arg("--background")
            .arg("00FF44")
            .arg("--text")
            .arg("0000CC")
            .arg("--message")
            .arg(
                "Welcome to swayr! ".to_owned()
                    + "I've created a fresh config for use with wofi for you in "
                    + &path.to_string_lossy()
                    + ". Adapt it to your needs.",
            )
            .arg("--type")
            .arg("warning")
            .arg("--dismiss-button")
            .arg("Thanks!")
            .spawn()
            .ok();
    }
    let mut file = OpenOptions::new()
        .read(true)
        .write(false)
        .create(false)
        .open(path)
        .unwrap();
    let mut buf: String = String::new();
    file.read_to_string(&mut buf).unwrap();
    toml::from_str(&buf).expect("Invalid config.")
}

#[test]
fn test_load_config() {
    let cfg = load_config();
    println!("{:?}", cfg);
}