summaryrefslogtreecommitdiff
path: root/src/vtcol.rs
blob: 369475340cf16327ab89396c7e2702543b6b3b2c (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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
pub mod lib;

use vtcol::{Console, Fade, Palette, Scheme};

use anyhow::{anyhow, Result};
use std::{io::{self, BufWriter},
          sync::atomic::{AtomicBool, Ordering},
          time::Duration};

static VERBOSITY: AtomicBool = AtomicBool::new(false);

const DEFAULT_FADE_DURATION_MS: u64 = 500;
const DEFAULT_FADE_UPDATE_HZ: u8 = 25;

macro_rules! vrb {
    ( $( $e:expr ),* ) => {(
            if VERBOSITY.load(Ordering::SeqCst) { println!( $( $e ),* ) }
    )}
}

/* struct Job -- Runtime parameters.
 */
#[derive(Debug)]
enum Job
{
    /** List available schemes. */
    List,
    /** Dump a scheme. */
    Dump(Scheme),
    /** Switch to color scheme. */
    Set(Scheme),
    /** Get currently active scheme. */
    Get,
    /** Toggle between two schemes. */
    Toggle(Scheme, Scheme),
    /** Fade from current scheme to another. */
    Fade(Option<Scheme>, Scheme, Duration, u8),
}

impl<'a> Job
{
    pub fn from_argv() -> Result<Job>
    {
        use clap::{App, Arg, SubCommand};

        let app = App::new(clap::crate_name!())
            .version(clap::crate_version!())
            .author(clap::crate_authors!())
            .about(clap::crate_description!())
            .subcommand(
                SubCommand::with_name("dump").about("dump a color scheme").arg(
                    Arg::with_name("scheme")
                        .help("name of the scheme")
                        .required(true)
                        .value_name("NAME")
                        .takes_value(true),
                ),
            )
            .subcommand(
                SubCommand::with_name("list").about("list available schemes"),
            )
            .subcommand(
                SubCommand::with_name("set")
                    .about("apply color scheme to current terminal")
                    .arg(
                        Arg::with_name("scheme")
                            .value_name("NAME")
                            .help("predefined color scheme")
                            .takes_value(true)
                            .conflicts_with("file"),
                    )
                    .arg(
                        Arg::with_name("file")
                            .short("f")
                            .long("file")
                            .value_name("PATH")
                            .help("apply scheme from file")
                            .takes_value(true),
                    ),
            )
            .subcommand(
                SubCommand::with_name("get").about("get current color scheme"),
            )
            .subcommand(
                SubCommand::with_name("toggle")
                    .about("toggle between two schemes")
                    .arg(
                        Arg::with_name("one")
                            .value_name("NAME1")
                            .help("predefined color scheme")
                            .takes_value(true),
                    )
                    .arg(
                        Arg::with_name("two")
                            .value_name("NAME2")
                            .help("predefined color scheme")
                            .takes_value(true),
                    ),
            )
            .subcommand(
                SubCommand::with_name("fade")
                    .about("fade from one scheme to another")
                    .arg(
                        Arg::with_name("from")
                            .short("f")
                            .long("from")
                            .value_name("NAME1")
                            .help("initial color scheme (default: current)")
                            .takes_value(true),
                    )
                    .arg(
                        Arg::with_name("to")
                            .short("t")
                            .long("to")
                            .value_name("NAME2")
                            .help("final color scheme")
                            .takes_value(true)
                            .required(true),
                    )
                    .arg(
                        Arg::with_name("ms")
                            .value_name("MS")
                            .short("m")
                            .long("ms")
                            .help("how long (in ms) the fade should take")
                            .takes_value(true),
                    )
                    .arg(
                        Arg::with_name("frequency")
                            .value_name("HZ")
                            .short("h")
                            .long("frequency")
                            .help("rate (HZ/s) of intermediate scheme changes")
                            .takes_value(true),
                    ),
            )
            .arg(
                Arg::with_name("verbose")
                    .short("v")
                    .long("verbose")
                    .help("enable extra diagnostics")
                    .takes_value(false),
            );

        let matches = app.get_matches();

        if matches.is_present("verbose") {
            VERBOSITY.store(true, Ordering::SeqCst);
        }

        match matches.subcommand() {
            ("dump", Some(subm)) => {
                if let Some(name) = subm.value_of("scheme") {
                    let scm = Scheme::from(name);
                    return Ok(Self::Dump(scm));
                }
                Err(anyhow!("dump requires an argument"))
            },
            ("list", _) => Ok(Self::List),
            ("set", Some(subm)) => {
                let scheme = match subm.value_of("scheme") {
                    Some("-") => Self::read_scheme_from_stdin(),
                    Some(name) => {
                        vrb!("pick predefined scheme [{}]", name);
                        Scheme::from(name)
                    },
                    None =>
                        match subm.value_of("file") {
                            None | Some("-") => Self::read_scheme_from_stdin(),
                            Some(fname) => {
                                vrb!(
                                    "read custom scheme from file [{}]",
                                    fname
                                );
                                Scheme::from_path(fname)
                            },
                        },
                };
                Ok(Self::Set(scheme))
            },
            ("get", _) => Ok(Self::Get),
            ("toggle", Some(subm)) => {
                match (subm.value_of("one"), subm.value_of("two")) {
                    (Some(one), Some(two)) => {
                        vrb!("toggle schemes [{}] and [{}]", one, two);
                        Ok(Self::Toggle(Scheme::from(one), Scheme::from(two)))
                    },
                    _ =>
                        Err(anyhow!(
                            "please supply two schemes to toggle between"
                        )),
                }
            },
            ("fade", Some(subm)) => {
                let dur: u64 = if let Some(ms) = subm.value_of("ms") {
                    ms.parse()?
                } else {
                    DEFAULT_FADE_DURATION_MS
                };
                let hz: u8 = if let Some(ms) = subm.value_of("frequency") {
                    ms.parse()?
                } else {
                    DEFAULT_FADE_UPDATE_HZ
                };
                let dur = Duration::from_millis(dur);

                match (subm.value_of("from"), subm.value_of("to")) {
                    (_, None) =>
                        Err(anyhow!("please supply color scheme to fade to")),
                    (from, Some(to)) =>
                        Ok(Self::Fade(
                            from.map(Scheme::from),
                            Scheme::from(to),
                            dur,
                            hz,
                        )),
                }
            },
            (junk, _) =>
                Err(anyhow!(
                    "invalid subcommand [{}]; try ``{} --help``",
                    junk,
                    clap::crate_name!()
                )),
        }
    }

    fn list_schemes()
    {
        println!("{} color schemes available:", vtcol::BUILTIN_SCHEMES.len());
        for s in vtcol::BUILTIN_SCHEMES {
            println!("      * {}", s.name());
        }
    }

    fn read_scheme_from_stdin() -> Scheme
    {
        vrb!("Go ahead, type your color scheme …");
        vrb!("vtcol>");
        Scheme::from_stdin()
    }

    fn dump(scm: Scheme) -> Result<()>
    {
        vrb!("Dumping color scheme {}", scm);
        let mut out = BufWriter::new(io::stdout());

        match scm {
            Scheme::Builtin(bltn) =>
                Palette::from(bltn.palette()).dump(&mut out).map_err(|e| {
                    anyhow!(
                        "error loading builtin scheme {}: {}",
                        bltn.name(),
                        e
                    )
                }),
            Scheme::Custom(None) =>
                Palette::from_stdin()?.dump(&mut out).map_err(|e| {
                    anyhow!("error loading palette from stdin: {}", e)
                }),
            Scheme::Custom(Some(fname)) =>
                Palette::from_file(&fname)?.dump(&mut out).map_err(|e| {
                    anyhow!(
                        "error loading palette from file [{}]: {}",
                        fname.display(),
                        e
                    )
                }),
            Scheme::Palette(pal) =>
                pal.dump(&mut out)
                    .map_err(|e| anyhow!("error dumping palette: {}", e)),
        }
    }

    fn run(self) -> Result<()>
    {
        match self {
            Self::Dump(scm) => Self::dump(scm)?,
            Self::List => Self::list_schemes(),
            Self::Set(scm) => Self::set_scheme(scm)?,
            Self::Get => Self::get_scheme()?,
            Self::Toggle(one, two) => Self::toggle_scheme(one, two)?,
            Self::Fade(from, to, ms, hz) => Self::fade(from, to, ms, hz)?,
        }

        Ok(())
    }

    fn set_scheme(scheme: Scheme) -> Result<()>
    {
        let con = Console::current()?;
        vrb!("console fd: {}", con);

        con.apply_scheme(&scheme)?;
        con.clear()?;

        vrb!("successfully enabled scheme {:?}", scheme);
        /* It’s fine to leak the fd, the kernel will clean up anyways. */
        Ok(())
    }

    fn get_scheme() -> Result<()>
    {
        let fd = Console::current()?;
        vrb!("console fd: {}", fd);

        let scm = fd.current_scheme()?;

        vrb!("active scheme:");
        println!("{}", scm);

        Ok(())
    }

    /** Toggle between two schemes. Defaults to ``one`` in case neither scheme
    is active.
    */
    fn toggle_scheme(one: Scheme, two: Scheme) -> Result<()>
    {
        let fd = Console::current()?;
        vrb!("console fd: {}", fd);

        if fd.current_palette()? == Palette::try_from(&one)? {
            Self::set_scheme(two)
        } else {
            Self::set_scheme(one)
        }
    }

    /** Fade from one scheme to another.

    If ``from`` is ``None``, the current palette is used as starting point. */
    fn fade(
        from: Option<Scheme>,
        to: Scheme,
        dur: Duration,
        hz: u8,
    ) -> Result<()>
    {
        let fd = Console::current()?;
        vrb!("console fd: {}", fd);

        let from = if let Some(from) = from {
            Palette::try_from(&from)?
        } else {
            fd.current_palette()?
        };
        let to = Palette::try_from(&to)?;

        let fade = Fade::new(from, to, dur, hz);

        fade.commence(&fd)?;
        Ok(())
    }
} /* [impl Job] */

fn main() -> Result<()>
{
    let job = Job::from_argv()?;
    vrb!("job parms: {:?}", job);

    job.run()
}