klask 1.0.0

Automatically create GUI for clap apps
Documentation
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
#![warn(missing_docs)]
//! You can use [`run_app`] for [`App`]s created manually or generated from yaml and
//! [`run_derived`] for [`App`]s derived from a struct. Both of these functions take
//! a closure that contains the code that would normally be in `main`. They should be
//! the last thing you call in `main`.
//!
//! For example
//! ```no_run
//! # use clap::{App, Arg};
//! # use klask::Settings;
//! fn main() {
//!     let app = App::new("Example").arg(Arg::new("debug").short('d'));
//!     klask::run_app(app, Settings::default(), |matches| {
//!        println!("{}", matches.is_present("debug"))
//!     });
//! }
//! ```
//! corresponds to
//! ```no_run
//! # use clap::{App, Arg};
//! fn main() {
//!     let app = App::new("Example").arg(Arg::new("debug").short('d'));
//!     let matches = app.get_matches();
//!     println!("{}", matches.is_present("debug"))
//! }
//! ```

mod app_state;
mod arg_state;
mod child_app;
mod error;
/// Additional options for output like progress bars.
pub mod output;
mod settings;

use app_state::AppState;
use child_app::{ChildApp, StdinType};
use clap::{App, ArgMatches, FromArgMatches, IntoApp};
use eframe::{
    egui::{
        self, style::Spacing, Button, Color32, CtxRef, FontDefinitions, Grid, Style, TextEdit, Ui,
    },
    epi,
};
use error::ExecutionError;
use native_dialog::FileDialog;

use output::Output;
pub use settings::Settings;
use std::{borrow::Cow, hash::Hash};

const CHILD_APP_ENV_VAR: &str = "KLASK_CHILD_APP";

/// Call with an [`App`] and a closure that contains the code that would normally be in `main`.
/// ```no_run
/// # use clap::{App, Arg};
/// # use klask::Settings;
/// let app = App::new("Example").arg(Arg::new("debug").short('d'));

/// klask::run_app(app, Settings::default(), |matches| {
///    println!("{}", matches.is_present("debug"))
/// });
/// ```
pub fn run_app(app: App<'static>, settings: Settings, f: impl FnOnce(&ArgMatches)) {
    if std::env::var(CHILD_APP_ENV_VAR).is_ok() {
        std::env::remove_var(CHILD_APP_ENV_VAR);

        let matches = app
            .try_get_matches()
            .expect("Internal error, arguments should've been verified by the GUI app");

        f(&matches)
    } else {
        // During validation we don't pass in a binary name
        let app = app.setting(clap::AppSettings::NoBinaryName);

        let klask = Klask {
            state: AppState::new(&app),
            tab: Tab::Arguments,
            env: settings.enable_env.map(|desc| (desc, vec![])),
            stdin: settings
                .enable_stdin
                .map(|desc| (desc, StdinType::Text(String::new()))),
            working_dir: settings
                .enable_working_dir
                .map(|desc| (desc, String::new())),
            output: Output::None,
            app,
            custom_font: settings.custom_font.map(Cow::from),
        };
        let native_options = eframe::NativeOptions::default();
        eframe::run_native(Box::new(klask), native_options);
    }
}

/// Can be used with a struct deriving [`clap::Clap`]. Call with a closure that contains the code that would normally be in `main`.
/// It's just a wrapper over [`run_app`].
/// ```no_run
/// # use clap::{App, Arg, Parser};
/// # use klask::Settings;
/// #[derive(Parser)]
/// struct Example {
///     #[clap(short)]
///     debug: bool,
/// }
///
/// klask::run_derived::<Example, _>(Settings::default(), |example|{
///     println!("{}", example.debug);
/// });
/// ```
pub fn run_derived<C, F>(settings: Settings, f: F)
where
    C: IntoApp + FromArgMatches,
    F: FnOnce(C),
{
    run_app(C::into_app(), settings, |m| {
        let matches = C::from_arg_matches(m)
            .expect("Internal error, C::from_arg_matches should always succeed");
        f(matches);
    });
}

#[derive(Debug)]
struct Klask {
    state: AppState,
    tab: Tab,
    /// First string is a description
    env: Option<(String, Vec<(String, String)>)>,
    /// First string is a description
    stdin: Option<(String, StdinType)>,
    /// First string is a description
    working_dir: Option<(String, String)>,
    output: Output,
    // This isn't a generic lifetime because eframe::run_native() requires
    // a 'static lifetime because boxed trait objects default to 'static
    app: App<'static>,

    custom_font: Option<Cow<'static, [u8]>>,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
enum Tab {
    Arguments,
    Env,
    Stdin,
}

impl epi::App for Klask {
    fn name(&self) -> &str {
        self.app.get_name()
    }

    fn update(&mut self, ctx: &CtxRef, _frame: &mut epi::Frame<'_>) {
        egui::CentralPanel::default().show(ctx, |ui| {
            egui::ScrollArea::vertical().show(ui, |ui| {
                // Tab selection
                let tab_count = 1
                    + if self.env.is_some() { 1 } else { 0 }
                    + if self.stdin.is_some() { 1 } else { 0 };

                if tab_count > 1 {
                    ui.columns(tab_count, |ui| {
                        let mut index = 0;

                        ui[index].selectable_value(&mut self.tab, Tab::Arguments, "Arguments");
                        index += 1;

                        if self.env.is_some() {
                            ui[index].selectable_value(
                                &mut self.tab,
                                Tab::Env,
                                "Environment variables",
                            );
                            index += 1;
                        }
                        if self.stdin.is_some() {
                            ui[index].selectable_value(&mut self.tab, Tab::Stdin, "Input");
                        }
                    });

                    ui.separator();
                }

                // Display selected tab
                match self.tab {
                    Tab::Arguments => {
                        ui.add(&mut self.state);

                        // Working dir
                        if let Some((ref desc, path)) = &mut self.working_dir {
                            if !desc.is_empty() {
                                ui.label(desc);
                            }

                            ui.horizontal(|ui| {
                                if ui.button("Select directory...").clicked() {
                                    if let Some(file) =
                                        FileDialog::new().show_open_single_dir().ok().flatten()
                                    {
                                        *path = file.to_string_lossy().into_owned();
                                    }
                                }
                                ui.add(TextEdit::singleline(path).hint_text("Working directory"))
                            });
                            ui.add_space(10.0);
                        }
                    }
                    Tab::Env => self.update_env(ui),
                    Tab::Stdin => self.update_stdin(ui),
                }

                // Run button row
                ui.horizontal(|ui| {
                    if ui
                        .add_enabled(!self.is_child_running(), Button::new("Run!"))
                        .clicked()
                    {
                        match self.try_start_execution() {
                            Ok(child) => {
                                // Reset
                                self.state.update_validation_error("", "");
                                self.output = Output::new_with_child(child);
                            }
                            Err(err) => {
                                if let ExecutionError::ValidationError { name, message } = &err {
                                    self.state.update_validation_error(name, message);
                                }
                                self.output = Output::Err(err);
                            }
                        }
                    }

                    if self.is_child_running() && ui.button("Kill").clicked() {
                        self.kill_child();
                    }

                    if self.is_child_running() {
                        let mut running_text = String::from("Running");
                        for _ in 0..((2.0 * ui.input().time) as i32 % 4) {
                            running_text.push('.')
                        }
                        ui.label(running_text);
                    }
                });

                ui.add(&mut self.output);
            });
        });
    }

    fn setup(&mut self, ctx: &CtxRef, _: &mut epi::Frame<'_>, _: Option<&dyn epi::Storage>) {
        ctx.set_style(Klask::klask_style());

        if let Some(custom_font) = self.custom_font.take() {
            let mut fonts = FontDefinitions::default();
            fonts
                .font_data
                .insert(String::from("custom_font"), custom_font);

            fonts
                .fonts_for_family
                .get_mut(&egui::FontFamily::Proportional)
                .expect("fonts_for_family should include FontFamily::Proportional")
                .insert(0, String::from("custom_font"));

            fonts
                .fonts_for_family
                .get_mut(&egui::FontFamily::Monospace)
                .expect("fonts_for_family should include FontFamily::Monospace")
                .push(String::from("custom_font"));

            ctx.set_fonts(fonts);
        }
    }
}

impl Klask {
    fn try_start_execution(&mut self) -> Result<ChildApp, ExecutionError> {
        let args = self.state.get_cmd_args(vec![])?;

        // Check for validation errors
        self.app.try_get_matches_from_mut(args.iter())?;

        if self
            .env
            .as_ref()
            .and_then(|(_, v)| v.iter().find(|(key, _)| key.is_empty()))
            .is_some()
        {
            return Err("Environment variable can't be empty".into());
        }

        ChildApp::run(
            args,
            self.env.clone().map(|(_, env)| env),
            self.stdin.clone().map(|(_, stdin)| stdin),
            self.working_dir.clone().map(|(_, dir)| dir),
        )
    }

    fn kill_child(&mut self) {
        if let Output::Output(child, _) = &mut self.output {
            child.kill();
        }
    }

    fn is_child_running(&self) -> bool {
        match &self.output {
            Output::Output(child, _) => child.is_running(),
            _ => false,
        }
    }

    fn update_env(&mut self, ui: &mut Ui) {
        let (ref desc, env) = self.env.as_mut().unwrap();

        if !desc.is_empty() {
            ui.label(desc);
        }

        if !env.is_empty() {
            let mut remove_index = None;

            Grid::new(Tab::Env)
                .striped(true)
                // We can't just divide by 2, without taking spacing into account
                // Instead we just set num_columns, and the second column will fill
                .min_col_width(ui.available_width() / 3.0)
                .num_columns(2)
                .show(ui, |ui| {
                    for (index, (key, value)) in env.iter_mut().enumerate() {
                        ui.horizontal(|ui| {
                            if ui.small_button("-").clicked() {
                                remove_index = Some(index);
                            }

                            if key.is_empty() {
                                ui.set_style(Klask::error_style());
                            }

                            ui.text_edit_singleline(key);

                            if key.is_empty() {
                                ui.set_style(Klask::klask_style());
                            }
                        });

                        ui.horizontal(|ui| {
                            ui.label("=");
                            ui.text_edit_singleline(value);
                        });

                        ui.end_row();
                    }
                });

            if let Some(remove_index) = remove_index {
                env.remove(remove_index);
            }
        }

        if ui.button("New").clicked() {
            env.push(Default::default());
        }

        ui.separator();
    }

    fn update_stdin(&mut self, ui: &mut Ui) {
        let (ref desc, stdin) = self.stdin.as_mut().unwrap();

        if !desc.is_empty() {
            ui.label(desc);
        }

        ui.columns(2, |ui| {
            if ui[0]
                .selectable_label(matches!(stdin, StdinType::Text(_)), "Text")
                .clicked()
                && matches!(stdin, StdinType::File(_))
            {
                *stdin = StdinType::Text(String::new());
            }
            if ui[1]
                .selectable_label(matches!(stdin, StdinType::File(_)), "File")
                .clicked()
                && matches!(stdin, StdinType::Text(_))
            {
                *stdin = StdinType::File(String::new());
            }
        });

        match stdin {
            StdinType::File(path) => {
                ui.horizontal(|ui| {
                    if ui.button("Select file...").clicked() {
                        if let Some(file) = FileDialog::new().show_open_single_file().ok().flatten()
                        {
                            *path = file.to_string_lossy().into_owned();
                        }
                    }
                    ui.text_edit_singleline(path);
                });
            }
            StdinType::Text(text) => {
                ui.text_edit_multiline(text);
            }
        };
    }

    fn klask_style() -> Style {
        Style {
            spacing: Spacing {
                text_edit_width: f32::MAX,
                item_spacing: egui::vec2(8.0, 8.0),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    fn error_style() -> Style {
        let mut style = Self::klask_style();
        style.visuals.widgets.inactive.bg_stroke.color = Color32::RED;
        style.visuals.widgets.inactive.bg_stroke.width = 1.0;
        style.visuals.widgets.hovered.bg_stroke.color = Color32::RED;
        style.visuals.widgets.active.bg_stroke.color = Color32::RED;
        style.visuals.widgets.open.bg_stroke.color = Color32::RED;
        style.visuals.widgets.noninteractive.bg_stroke.color = Color32::RED;
        style.visuals.selection.stroke.color = Color32::RED;
        style
    }
}