summaryrefslogtreecommitdiffstats
path: root/src/bin.rs
blob: b00be789749c51b82c903db1fd13b78dedb60676 (plain)
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
/*
 * meli - bin.rs
 *
 * Copyright 2017-2018 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli 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.
 *
 * meli 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 meli. If not, see <http://www.gnu.org/licenses/>.
 */

//!
//!  This crate contains the frontend stuff of the application. The application entry way on
//!  `src/bin.rs` creates an event loop and passes input to the `ui` module.
//!
//! The mail handling stuff is done in the `melib` crate which includes all backend needs. The
//! split is done to theoretically be able to create different frontends with the same innards.
//!

use std::alloc::System;
use std::io::Write;
use std::path::{Path, PathBuf};

#[global_allocator]
static GLOBAL: System = System;

use ui;

pub use melib::*;
pub use ui::*;

use nix;
use std::os::raw::c_int;
use xdg;

fn notify(
    signals: &[c_int],
) -> std::result::Result<crossbeam::channel::Receiver<c_int>, std::io::Error> {
    let (s, r) = crossbeam::channel::bounded(100);
    let signals = signal_hook::iterator::Signals::new(signals)?;
    std::thread::spawn(move || {
        for signal in signals.forever() {
            s.send(signal).unwrap();
        }
    });
    Ok(r)
}

macro_rules! error_and_exit {
    ($($err:expr),*) => {{
            eprintln!($($err),*);
            std::process::exit(1);
    }}
}

#[derive(Debug)]
struct CommandLineArguments {
    create_config: Option<String>,
    config: Option<String>,
    help: bool,
    version: bool,
}

fn main() -> std::result::Result<(), std::io::Error> {
    enum CommandLineFlags {
        CreateConfig,
        Config,
    }
    use CommandLineFlags::*;
    let mut prev: Option<CommandLineFlags> = None;
    let mut args = CommandLineArguments {
        create_config: None,
        config: None,
        help: false,
        version: false,
    };

    for i in std::env::args().skip(1) {
        match i.as_str() {
            "--create-config" => match prev {
                None => prev = Some(CreateConfig),
                Some(CreateConfig) => error_and_exit!("invalid value for flag `--create-config`"),
                Some(Config) => error_and_exit!("invalid value for flag `--config`"),
            },
            "--config" | "-c" => match prev {
                None => prev = Some(Config),
                Some(CreateConfig) if args.create_config.is_none() => {
                    args.config = Some(String::new());
                    prev = Some(Config);
                }
                Some(CreateConfig) => error_and_exit!("Duplicate value for flag `--create-config`"),
                Some(Config) => error_and_exit!("invalid value for flag `--config`"),
            },
            "--help" | "-h" => {
                args.help = true;
            }
            "--version" | "-v" => {
                args.version = true;
            }
            e => match prev {
                None => error_and_exit!("error: value without command {}", e),
                Some(CreateConfig) if args.create_config.is_none() => {
                    args.create_config = Some(i);
                    prev = None;
                }
                Some(Config) if args.config.is_none() => {
                    args.config = Some(i);
                    prev = None;
                }
                Some(CreateConfig) => error_and_exit!("Duplicate value for flag `--create-config`"),
                Some(Config) => error_and_exit!("Duplicate value for flag `--config`"),
            },
        }
    }

    if args.help {
        println!("usage:\tmeli [--create-config[ PATH]] [--config[ PATH]|-c[ PATH]]");
        println!("\tmeli --help");
        println!("\tmeli --version");
        println!("");
        println!("\t--help, -h\t\tshow this message and exit");
        println!("\t--version, -v\t\tprint version and exit");
        println!("\t--create-config[ PATH]\tCreate a sample configuration file with available configuration options. If PATH is not specified, meli will try to create it in $XDG_CONFIG_HOME/meli/config");
        println!("\t--config PATH, -c PATH\tUse specified configuration file");
        std::process::exit(0);
    }

    if args.version {
        println!("meli {}", option_env!("CARGO_PKG_VERSION").unwrap_or("0.0"));
        std::process::exit(0);
    }

    match prev {
        None => {}
        Some(CreateConfig) if args.create_config.is_none() => args.create_config = Some("".into()),
        Some(CreateConfig) => error_and_exit!("Duplicate value for flag `--create-config`"),
        Some(Config) => error_and_exit!("error: flag without value: --config"),
    };

    if let Some(config_path) = args.create_config.as_mut() {
        let config_path: PathBuf = if config_path.is_empty() {
            let xdg_dirs = xdg::BaseDirectories::with_prefix("meli").unwrap();
            xdg_dirs.place_config_file("config").unwrap_or_else(|e| {
                error_and_exit!("Cannot create configuration directory:\n{}", e)
            })
        } else {
            Path::new(config_path).to_path_buf()
        };
        if config_path.exists() {
            println!("File `{}` already exists.\nMaybe you meant to specify another path with --create-config=PATH", config_path.display());
            std::process::exit(1);
        }
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(config_path.as_path())
            .unwrap_or_else(|e| error_and_exit!("Could not create config file:\n{}", e));
        file.write_all(include_bytes!("../sample-config"))
            .unwrap_or_else(|e| error_and_exit!("Could not write to config file:\n{}", e));
        println!("Written example configuration to {}", config_path.display());
        std::process::exit(0);
    }

    if let Some(config_location) = args.config.as_ref() {
        std::env::set_var("MELI_CONFIG", config_location);
    }

    /* Catch SIGWINCH to handle terminal resizing */
    let signals = &[
        /* Catch SIGWINCH to handle terminal resizing */
        signal_hook::SIGWINCH,
    ];

    let signal_recvr = notify(signals)?;

    /* Create the application State. This is the 'System' part of an ECS architecture */
    let mut state = State::new();

    let receiver = state.receiver();

    /* Register some reasonably useful interfaces */
    let window = Box::new(Tabbed::new(vec![
        Box::new(listing::Listing::new(&state.context.accounts)),
        Box::new(AccountsPanel::new(&state.context)),
        Box::new(ContactList::default()),
    ]));

    let status_bar = Box::new(StatusBar::new(window));
    state.register_component(status_bar);

    let xdg_notifications = Box::new(ui::components::notifications::XDGNotifications {});
    state.register_component(xdg_notifications);
    state.register_component(Box::new(
        ui::components::notifications::NotificationFilter {},
    ));

    /* Keep track of the input mode. See ui::UIMode for details */
    'main: loop {
        state.render();

        'inner: loop {
            /* Check if any components have sent reply events to State. */
            let events: Vec<UIEvent> = state.context.replies();
            for e in events {
                state.rcv_event(e);
            }
            state.redraw();

            /* Poll on all channels. Currently we have the input channel for stdin, watching events and the signal watcher. */
            crossbeam::select! {
                recv(receiver) -> r => {
                    match debug!(r.unwrap()) {
                        ThreadEvent::Input(Key::Ctrl('z')) => {
                            state.switch_to_main_screen();
                            //_thread_handler.join().expect("Couldn't join on the associated thread");
                            let self_pid = nix::unistd::Pid::this();
                            nix::sys::signal::kill(self_pid, nix::sys::signal::Signal::SIGSTOP).unwrap();
                            state.switch_to_alternate_screen();
                            state.restore_input();
                            // BUG: thread sends input event after one received key
                            state.update_size();
                            state.render();
                            state.redraw();
                        },
                        ThreadEvent::Input(k) => {
                            match state.mode {
                                UIMode::Normal => {
                                    match k {
                                        Key::Char('q') | Key::Char('Q') => {
                                            drop(state);
                                            break 'main;
                                        },
                                        Key::Char(' ') => {
                                            <