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
// Copyright 2020 Tibor Schneider
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # Rofi ui manager
//! Spawn rofi windows, and parse the result appropriately.
//!
//! ## Simple example
//!
//! ```
//! use rofi;
//! use std::{fs, env};
//!
//! let dir_entries = fs::read_dir(env::current_dir().unwrap())
//!     .unwrap()
//!     .map(|d| format!("{:?}", d.unwrap().path()))
//!     .collect::<Vec<String>>();
//!
//! match rofi::Rofi::new(&dir_entries).run() {
//!     Ok(choice) => println!("Choice: {}", choice),
//!     Err(rofi::Error::Interrupted) => println!("Interrupted"),
//!     Err(e) => println!("Error: {}", e)
//! }
//! ```
//!
//! ## Example of returning an index
//! `rofi` can also be used to return an index of the selected item:
//!
//! ```
//! use rofi;
//! use std::{fs, env};
//!
//! let dir_entries = fs::read_dir(env::current_dir().unwrap())
//!     .unwrap()
//!     .map(|d| format!("{:?}", d.unwrap().path()))
//!     .collect::<Vec<String>>();
//!
//! match rofi::Rofi::new(&dir_entries).run_index() {
//!     Ok(element) => println!("Choice: {}", element),
//!     Err(rofi::Error::Interrupted) => println!("Interrupted"),
//!     Err(rofi::Error::NotFound) => println!("User input was not found"),
//!     Err(e) => println!("Error: {}", e)
//! }
//! ```
//!
//! ## Example of using pango formatted strings
//! `rofi` can display pango format. Here is a simple example (you have to call
//! the `self..pango` function).
//!
//! ```
//! use rofi;
//! use rofi::pango::{Pango, FontSize};
//! use std::{fs, env};
//!
//! let entries: Vec<String> = vec![
//!     Pango::new("Option 1").size(FontSize::Small).fg_color("#666000").build(),
//!     Pango::new("Option 2").size(FontSize::Large).fg_color("#deadbe").build(),
//! ];
//!
//! match rofi::Rofi::new(&entries).pango().run() {
//!     Ok(element) => println!("Choice: {}", element),
//!     Err(rofi::Error::Interrupted) => println!("Interrupted"),
//!     Err(e) => println!("Error: {}", e)
//! }
//! ```
//!
//! ## Example of using custom keyboard shortcuts with rofi
//!
//! ```
//! use rofi;
//! use std::{fs, env};
//!
//! let dir_entries = fs::read_dir(env::current_dir().unwrap())
//!     .unwrap()
//!     .map(|d| format!("{:?}", d.unwrap().path()))
//!     .collect::<Vec<String>>();
//! let mut r = rofi::Rofi::new(&dir_entries);
//! match r.kb_custom(1, "Alt+n").unwrap().run() {
//!     Ok(choice) => println!("Choice: {}", choice),
//!     Err(rofi::Error::CustomKeyboardShortcut(exit_code)) => println!("exit code: {:?}", exit_code),
//!     Err(rofi::Error::Interrupted) => println!("Interrupted"),
//!     Err(e) => println!("Error: {}", e)
//! }
//! ```

#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)]

pub mod pango;

use std::io::{Read, Write};
use std::process::{Child, Command, Stdio};
use thiserror::Error;

/// # Rofi Window Builder
/// Rofi struct for displaying user interfaces. This struct is build after the
/// non-consuming builder pattern. You can prepare a window, and draw it
/// multiple times without reconstruction and reallocation. You can choose to
/// return a handle to the child process `RofiChild`, which allows you to kill
/// the process.
#[derive(Debug, Clone)]
pub struct Rofi<'a, T>
where
    T: AsRef<str>,
{
    elements: &'a [T],
    case_sensitive: bool,
    lines: Option<usize>,
    message: Option<String>,
    width: Width,
    format: Format,
    args: Vec<String>,
    sort: bool,
}

/// Rofi child process.
#[derive(Debug)]
pub struct RofiChild<T> {
    num_elements: T,
    p: Child,
}

impl<T> RofiChild<T> {
    fn new(p: Child, arg: T) -> Self {
        Self {
            num_elements: arg,
            p,
        }
    }
    /// Kill the Rofi process
    pub fn kill(&mut self) -> Result<(), Error> {
        Ok(self.p.kill()?)
    }
}

impl RofiChild<String> {
    /// Wait for the result and return the output as a String.
    fn wait_with_output(&mut self) -> Result<String, Error> {
        let status = self.p.wait()?;
        let code = status.code().ok_or(Error::IoError(std::io::Error::new(
            std::io::ErrorKind::Interrupted,
            "Rofi process was interrupted",
        )))?;
        if status.success() {
            let mut buffer = String::new();
            if let Some(mut reader) = self.p.stdout.take() {
                reader.read_to_string(&mut buffer)?;
            }
            if buffer.ends_with('\n') {
                buffer.pop();
            }
            if buffer.is_empty() {
                Err(Error::Blank {})
            } else {
                Ok(buffer)
            }
        } else if (10..=28).contains(&code) {
            Err(Error::CustomKeyboardShortcut(code - 9))
        } else {
            Err(Error::Interrupted {})
        }
    }
}

impl RofiChild<usize> {
    /// Wait for the result and return the output as an usize.
    fn wait_with_output(&mut self) -> Result<usize, Error> {
        let status = self.p.wait()?;
        let code = status.code().ok_or(Error::IoError(std::io::Error::new(
            std::io::ErrorKind::Interrupted,
            "Rofi process was interrupted",
        )))?;
        if status.success() {
            let mut buffer = String::new();
            if let Some(mut reader) = self.p.stdout.take() {
                reader.read_to_string(&mut buffer)?;
            }
            if buffer.ends_with('\n') {
                buffer.pop();
            }
            if buffer.is_empty() {
                Err(Error::Blank {})
            } else {
                let idx: isize = buffer.parse::<isize>()?;
                if idx < 0 || idx > self.num_elements as isize {
                    Err(Error::NotFound {})
                } else {
                    Ok(idx as usize)
                }
            }
        } else if (10..=28).contains(&code) {
            Err(Error::CustomKeyboardShortcut(code - 9))
        } else {
            Err(Error::Interrupted {})
        }
    }
}

impl<'a, T> Rofi<'a, T>
where
    T: AsRef<str>,
{
    /// Generate a new, unconfigured Rofi window based on the elements provided.
    pub fn new(elements: &'a [T]) -> Self {
        Self {
            elements,
            case_sensitive: false,
            lines: None,
            width: Width::None,
            format: Format::Text,
            args: Vec::new(),
            sort: false,
            message: None,
        }
    }

    /// Show the window, and return the selected string, including pango
    /// formatting if available
    pub fn run(&self) -> Result<String, Error> {
        self.spawn()?.wait_with_output()
    }

    /// show the window, and return the index of the selected string This
    /// function will overwrite any subsequent calls to `self.format`.
    pub fn run_index(&mut self) -> Result<usize, Error> {
        self.spawn_index()?.wait_with_output()
    }

    /// Set sort flag
    pub fn set_sort(&mut self) -> &mut Self {
        self.sort = true;
        self
    }

    /// enable pango markup
    pub fn pango(&mut self) -> &mut Self {
        self.args.push("-markup-rows".to_string());
        self
    }

    /// enable password mode
    pub fn password(&mut self) -> &mut Self {
        self.args.push("-password".to_string());
        self
    }

    /// enable message dialog mode (-e)
    pub fn message_only(&mut self, message: impl Into<String>) -> Result<&mut Self, Error> {
        if !self.elements.is_empty() {
            return Err(Error::ConfigErrorMessageAndOptions);
        }
        self.message = Some(message.into());
        Ok(self)
    }

    /// Sets the number of lines.
    /// If this function is not called, use the number of lines provided in the
    /// elements vector.
    pub fn lines(&mut self, l: usize) -> &mut Self {
        self.lines = Some(l);
        self
    }

    /// Set the width of the window (overwrite the theme settings)
    pub fn width(&mut self, w: Width) -> Result<&mut Self, Error> {
        w.check()?;
        self.width = w;
        Ok(self)
    }

    /// Sets the case sensitivity (disabled by default)
    pub fn case_sensitive(&mut self, sensitivity: bool) -> &mut Self {
        self.case_sensitive = sensitivity;
        self
    }

    /// Set the prompt of the rofi window
    pub fn prompt(&mut self, prompt: impl Into<String>) -> &mut Self {
        self.args.push("-p".to_string());
        self.args.push(prompt.into());
        self
    }

    /// Set the message of the rofi window (-mesg). Only available in dmenu mode.
    /// Docs: <https://github.com/davatorium/rofi/blob/next/doc/rofi-dmenu.5.markdown#dmenu-specific-commandline-flags>
    pub fn message(&mut self, message: impl Into<String>) -> &mut Self {
        self.args.push("-mesg".to_string());
        self.args.push(message.into());
        self
    }

    /// Set the rofi theme
    /// This will make sure that rofi uses `~/.config/rofi/{theme}.rasi`
    pub fn theme(&mut self, theme: Option<impl Into<String>>) -> &mut Self {
        if let Some(t) = theme {
            self.args.push("-theme".to_string());
            self.args.push(t.into());
        }
        self
    }

    /// Set the return format of the rofi call. Default is `Format::Text`. If
    /// you call `self.spawn_index` later, the format will be overwritten with
    /// `Format::Index`.
    pub fn return_format(&mut self, format: Format) -> &mut Self {
        self.format = format;
        self
    }

    /// Set a custom keyboard shortcut. Rofi supports up to 19 custom keyboard shortcuts.
    ///
    /// `id` must be in the \[1,19\] range and identifies the keyboard shortcut
    ///
    /// `shortcut` can be any modifiers separated by `"+"`, with a letter or number at the end.
    /// Ex: "Control+Shift+n", "Alt+s", "Control+Alt+Shift+1
    ///
    /// [https://github.com/davatorium/rofi/blob/next/source/keyb.c#L211](https://github.com/davatorium/rofi/blob/next/source/keyb.c#L211)
    pub fn kb_custom(&mut self, id: u32, shortcut: &str) -> Result<&mut Self, String> {
        if !(1..=19).contains(&id) {
            return Err(format!("Attempting to set custom keyboard shortcut with invalid id: {}. Valid range is: [1,19]", id));
        }
        self.args.push(format!("-kb-custom-{}", id));
        self.args.push(shortcut.to_string());
        Ok(self)
    }

    /// Returns a child process with the pre-prepared rofi window
    /// The child will produce the exact output as provided in the elements vector.
    pub fn spawn(&self) -> Result<RofiChild<String>, std::io::Error> {
        Ok(RofiChild::new(self.spawn_child()?, String::new()))
    }

    /// Returns a child process with the pre-prepared rofi window.
    /// The child will produce the index of the chosen element in the vector.
    /// This function will overwrite any subsequent calls to `self.format`.
    pub fn spawn_index(&mut self) -> Result<RofiChild<usize>, std::io::Error> {
        self.format = Format::Index;
        Ok(RofiChild::new(self.spawn_child()?, self.elements.len()))
    }

    fn spawn_child(&self) -> Result<Child, std::io::Error> {
        let mut child = Command::new("rofi")
            .args(match &self.message {
                Some(msg) => vec!["-e", msg],
                None => vec!["-dmenu"],
            })
            .args(&self.args)
            .arg("-format")
            .arg(self.format.as_arg())
            .arg("-l")
            .arg(match self.lines.as_ref() {
                Some(s) => format!("{}", s),
                None => format!("{}", self.elements.len()),
            })
            .arg(match self.case_sensitive {
                true => "-case-sensitive",
                false => "-i",
            })
            .args(match self.width {
                Width::None => vec![],
                Width::Percentage(x) => vec![
                    "-theme-str".to_string(),
                    format!("window {{width: {}%;}}", x),
                ],
                Width::Pixels(x) => vec![
                    "-theme-str".to_string(),
                    format!("window {{width: {}px;}}", x),
                ],
            })
            .arg(match self.sort {
                true => "-sort",
                false => "",
            })
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;

        if let Some(mut writer) = child.stdin.take() {
            for element in self.elements {
                writer.write_all(element.as_ref().as_bytes())?;
                writer.write_all(b"\n")?;
            }
        }

        Ok(child)
    }
}

static EMPTY_OPTIONS: Vec<String> = vec![];

impl<'a> Rofi<'a, String> {
    /// Generate a new, Rofi window in "message only" mode with the given message.
    pub fn new_message(message: impl Into<String>) -> Self {
        let mut rofi = Self::new(&EMPTY_OPTIONS);
        rofi.message_only(message)
            .expect("Invariant: provided empty options so it is safe to unwrap message_only");
        rofi
    }
}

/// Width of the rofi window to overwrite the default width from the rogi theme.
#[derive(Debug, Clone, Copy)]
pub enum Width {
    /// No width specified, use the default one from the theme
    None,
    /// Width in percentage of the screen, must be between 0 and 100
    Percentage(usize),
    /// Width in pixels, must be greater than 100
    Pixels(usize),
}

impl Width {
    fn check(&self) -> Result<(), Error> {
        match self {
            Self::Percentage(x) => {
                if *x > 100 {
                    Err(Error::InvalidWidth("Percentage must be between 0 and 100"))
                } else {
                    Ok(())
                }
            }
            Self::Pixels(x) => {
                if *x <= 100 {
                    Err(Error::InvalidWidth("Pixels must be larger than 100"))
                } else {
                    Ok(())
                }
            }
            _ => Ok(()),
        }
    }
}

/// Different modes, how rofi should return the results
#[derive(Debug, Clone, Copy)]
pub enum Format {
    /// Regular text, including markup
    #[allow(dead_code)]
    Text,
    /// Text, where the markup is removed
    StrippedText,
    /// Text with the exact user input
    UserInput,
    /// Index of the chosen element
    Index,
}

impl Format {
    fn as_arg(&self) -> &'static str {
        match self {
            Format::Text => "s",
            Format::StrippedText => "p",
            Format::UserInput => "f",
            Format::Index => "i",
        }
    }
}

/// Rofi Error Type
#[derive(Error, Debug)]
pub enum Error {
    /// IO Error
    #[error("IO Error: {0}")]
    IoError(#[from] std::io::Error),
    /// Parse Int Error, only occurs when getting the index.
    #[error("Parse Int Error: {0}")]
    ParseIntError(#[from] std::num::ParseIntError),
    /// Error returned when the user has interrupted the action
    #[error("User interrupted the action")]
    Interrupted,
    /// Error returned when the user chose a blank option
    #[error("User chose a blank line")]
    Blank,
    /// Error returned the width is invalid, only returned in Rofi::width()
    #[error("Invalid width: {0}")]
    InvalidWidth(&'static str),
    /// Error, when the input of the user is not found. This only occurs when
    /// getting the index.
    #[error("User input was not found")]
    NotFound,
    /// Incompatible configuration: cannot specify non-empty options and message_only.
    #[error("Can't specify non-empty options and message_only")]
    ConfigErrorMessageAndOptions,
    /// A custom keyboard shortcut was used
    #[error("User used a custom keyboard shortcut")]
    CustomKeyboardShortcut(i32),
}

#[cfg(test)]
mod rofitest {
    use super::*;
    #[test]
    fn simple_test() {
        let options = vec!["a", "b", "c", "d"];
        let empty_options: Vec<String> = Vec::new();
        match Rofi::new(&options).prompt("choose c").run() {
            Ok(ret) => assert!(ret == "c"),
            _ => assert!(false),
        }
        match Rofi::new(&options).prompt("chose c").run_index() {
            Ok(ret) => assert!(ret == 2),
            _ => assert!(false),
        }
        match Rofi::new(&options)
            .prompt("press escape")
            .width(Width::Percentage(15))
            .unwrap()
            .run_index()
        {
            Err(Error::Interrupted) => assert!(true),
            _ => assert!(false),
        }
        match Rofi::new(&options)
            .prompt("Enter something wrong")
            .run_index()
        {
            Err(Error::NotFound) => assert!(true),
            _ => assert!(false),
        }
        match Rofi::new(&empty_options)
            .prompt("Enter password")
            .password()
            .return_format(Format::UserInput)
            .run()
        {
            Ok(ret) => assert!(ret == "password"),
            _ => assert!(false),
        }
        match Rofi::new_message("A message with no input").run() {
            Err(Error::Blank) => (), // ok
            _ => assert!(false),
        }

        let mut r = Rofi::new(&options);
        match r
            .message("Press Alt+n")
            .kb_custom(1, "Alt+n")
            .unwrap()
            .run()
        {
            Err(Error::CustomKeyboardShortcut(exit_code)) => {
                assert_eq!(exit_code, 1)
            }
            _ => assert!(false),
        }
    }
}