wash-cli 0.2.1

wasmcloud Shell (wash) CLI tool
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
use crate::claims::*;
use crate::ctl::*;
use crate::drain::*;
use crate::keys::*;
use crate::par::*;
use crate::reg::*;
use crate::util::{convert_error, Result, WASH_CMD_INFO, WASH_LOG_INFO};
use crossterm::event::{poll, read, DisableMouseCapture, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
use log::{error, info, LevelFilter};
use std::io::{self, Stdout};
use std::sync::{Arc, Mutex};
use std::{cell::RefCell, rc::Rc};
use structopt::{clap::AppSettings, StructOpt};
use tui::{
    backend::CrosstermBackend,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::Span,
    widgets::{Block, Borders, Paragraph, Wrap},
    Frame, Terminal,
};
use tui_logger::*;
use wasmcloud_host::HostBuilder;

const CTL_NS: &str = "default";
const WASH_PROMPT: &str = "wash> ";

#[derive(Debug, StructOpt, Clone)]
#[structopt(
    global_settings(&[AppSettings::ColoredHelp, AppSettings::VersionlessSubcommands]),
    name = "up")]
pub(crate) struct UpCli {
    #[structopt(flatten)]
    command: UpCliCommand,
}

impl UpCli {
    pub(crate) fn command(self) -> UpCliCommand {
        self.command
    }
}

#[derive(StructOpt, Debug, Clone)]
pub(crate) struct UpCliCommand {
    /// Host for lattice connections, defaults to 0.0.0.0
    #[structopt(
        short = "h",
        long = "host",
        default_value = "0.0.0.0",
        env = "WASH_RPC_HOST"
    )]
    rpc_host: String,

    /// Port for lattice connections, defaults to 4222
    #[structopt(
        short = "p",
        long = "port",
        default_value = "4222",
        env = "WASH_RPC_PORT"
    )]
    rpc_port: String,

    /// Log level verbosity, valid values are `error`, `warn`, `info`, `debug`, and `trace`
    #[structopt(short = "l", long = "log-level", default_value = "debug")]
    log_level: LogLevel,
}

#[derive(StructOpt, Debug, Clone, PartialEq)]
enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

impl std::str::FromStr for LogLevel {
    type Err = std::io::Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "error" => Ok(LogLevel::Error),
            "warn" => Ok(LogLevel::Warn),
            "info" => Ok(LogLevel::Info),
            "debug" => Ok(LogLevel::Debug),
            "trace" => Ok(LogLevel::Trace),
            _ => Ok(LogLevel::Trace),
        }
    }
}

pub(crate) async fn handle_command(command: UpCliCommand) -> Result<()> {
    let UpCliCommand { .. } = command;
    handle_up(command).await
}

#[derive(StructOpt, Debug, Clone)]
#[structopt(name = "wash>", global_settings(&[AppSettings::NoBinaryName, AppSettings::DisableVersion, AppSettings::ColorNever]))]
struct ReplCli {
    #[structopt(flatten)]
    cmd: ReplCliCommand,
}

#[derive(StructOpt, Debug, Clone)]
#[structopt(global_settings(&[AppSettings::ColorNever, AppSettings::DisableVersion, AppSettings::VersionlessSubcommands]))]
enum ReplCliCommand {
    // Manage contents of local wasmcloud cache
    #[structopt(name = "drain")]
    Drain(DrainCliCommand),

    /// Interact with a wasmcloud control interface
    #[structopt(name = "ctl")]
    Ctl(CtlCliCommand),

    /// Generate and manage JWTs for wasmcloud Actors
    #[structopt(name = "claims")]
    Claims(ClaimsCliCommand),

    /// Utilities for generating and managing keys
    #[structopt(name = "keys")]
    Keys(KeysCliCommand),

    /// Create, inspect, and modify capability provider archive files
    #[structopt(name = "par")]
    Par(ParCliCommand),

    /// Launch wasmcloud REPL environment
    #[structopt(name = "reg")]
    Reg(RegCliCommand),

    /// Terminates the REPL environment (also accepts 'exit', 'logout', 'q' and ':q!')
    #[structopt(name = "quit", aliases = &["exit", "logout", "q", ":q!"])]
    Quit,

    /// Clears the REPL input history
    #[structopt(name = "clear")]
    Clear,
}

#[derive(Debug, Clone)]
struct InputState {
    history: Vec<Vec<char>>,
    history_cursor: usize,
    input: Vec<char>,
    input_cursor: usize,
    multiline_history: u16, // amount to offset cursor for multiline inputs
    input_width: usize,
}

impl Default for InputState {
    fn default() -> Self {
        InputState {
            history: vec![],
            history_cursor: 0,
            input: vec![],
            input_cursor: 0,
            multiline_history: 0,
            input_width: 0,
        }
    }
}

impl InputState {
    fn cursor_location(&self) -> (u16, u16) {
        let mut position = (0, 0);

        position.0 += WASH_PROMPT.len();

        for _c in 0..self.input_cursor {
            position.0 += 1;
            if position.0 == self.input_width {
                position.0 = 0;
                position.1 += 1;
            }
        }

        // Offset Y by length of command history and multiline history
        position.1 += self.history.len();
        position.1 += self.multiline_history as usize;

        (position.0 as u16, position.1 as u16)
    }
}

#[derive(Debug, Clone)]
struct OutputState {
    output: Vec<String>,
    output_cursor: usize,
    output_width: usize,
    output_scroll: u16,
}

impl Default for OutputState {
    fn default() -> Self {
        OutputState {
            output: vec![],
            output_cursor: 0,
            output_width: 80,
            output_scroll: 0,
        }
    }
}

struct WashRepl {
    input_state: InputState,
    output_state: Arc<Mutex<OutputState>>,
    tui_dispatcher: Rc<RefCell<Dispatcher<Event>>>,
    tui_state: TuiWidgetState,
}

impl Default for WashRepl {
    fn default() -> Self {
        WashRepl {
            input_state: InputState::default(),
            output_state: Arc::new(Mutex::new(OutputState::default())),
            tui_dispatcher: Rc::new(RefCell::new(Dispatcher::<Event>::new())),
            tui_state: TuiWidgetState::new(),
        }
    }
}

impl WashRepl {
    /// Using the state of the REPL, display information in the terminal window
    fn draw_ui(
        &mut self,
        terminal: &mut Terminal<tui::backend::CrosstermBackend<std::io::Stdout>>,
    ) -> Result<()> {
        terminal.draw(|frame| {
            let main_chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Percentage(67), Constraint::Min(5)].as_ref())
                .split(frame.size());

            let io_chunks = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Percentage(40), Constraint::Min(10)])
                .split(main_chunks[0]);

            draw_input_panel(frame, &mut self.input_state, io_chunks[0]);
            draw_output_panel(frame, Arc::clone(&self.output_state), io_chunks[1]);
            draw_smart_logger(frame, main_chunks[1], &self.tui_state, &self.tui_dispatcher);
        })?;
        Ok(())
    }

    /// Handles key input by the user into the REPL
    async fn handle_key(&mut self, code: KeyCode, modifier: KeyModifiers) -> Result<()> {
        match code {
            KeyCode::Char(c) => {
                self.input_state
                    .input
                    .insert(self.input_state.input_cursor, c);
                self.input_state.input_cursor += 1;
            }
            KeyCode::Left => {
                if self.input_state.input_cursor > 0 {
                    self.input_state.input_cursor -= 1
                }
            }
            KeyCode::Right => {
                if self.input_state.input_cursor < self.input_state.input.len() {
                    self.input_state.input_cursor += 1
                }
            }
            KeyCode::Up => {
                if modifier == KeyModifiers::SHIFT {
                    let mut state = self.output_state.lock().unwrap();
                    if state.output_cursor > 0 && state.output_scroll > 0 {
                        state.output_cursor -= 1;
                    }
                } else if self.input_state.history_cursor > 0 && modifier == KeyModifiers::NONE {
                    self.input_state.history_cursor -= 1;
                    self.input_state.input =
                        self.input_state.history[self.input_state.history_cursor].clone();
                    self.input_state.input_cursor = self.input_state.input.len();
                }
            }
            KeyCode::Down => {
                if modifier == KeyModifiers::SHIFT {
                    let mut state = self.output_state.lock().unwrap();
                    if state.output_cursor < state.output.len() {
                        state.output_cursor += 1;
                    }
                } else if modifier == KeyModifiers::NONE {
                    if self.input_state.history.is_empty() {
                        return Ok(());
                    };
                    if self.input_state.history_cursor < self.input_state.history.len() - 1
                        && self.input_state.history_cursor > 0
                    {
                        self.input_state.history_cursor += 1;
                        self.input_state.input =
                            self.input_state.history[self.input_state.history_cursor].clone();
                        self.input_state.input_cursor = self.input_state.input.len();
                    } else if self.input_state.history_cursor >= self.input_state.history.len() - 1
                    {
                        self.input_state.history_cursor = self.input_state.history.len();
                        self.input_state.input.clear();
                        self.input_state.input_cursor = 0;
                    }
                }
            }
            KeyCode::Backspace => {
                if self.input_state.input_cursor > 0
                    && self.input_state.input_cursor <= self.input_state.input.len()
                {
                    self.input_state.input_cursor -= 1;
                    self.input_state.input.remove(self.input_state.input_cursor);
                };
            }
            KeyCode::Enter => {
                let cmd: String = self.input_state.input.iter().collect();
                let iter = cmd.split_ascii_whitespace();
                let cli = ReplCli::from_iter_safe(iter);

                let multilines = self.input_state.input.len() / self.input_state.input_width;
                if multilines >= 1 {
                    self.input_state.multiline_history += multilines as u16;
                };

                self.input_state
                    .history
                    .push(self.input_state.input.clone());
                self.input_state.history_cursor = self.input_state.history.len();
                self.input_state.input.clear();
                self.input_state.input_cursor = 0;

                match cli {
                    Ok(ReplCli { cmd }) => {
                        use ReplCliCommand::*;
                        match cmd {
                            Clear => {
                                info!(target: WASH_LOG_INFO, "Clearing REPL history");
                                self.input_state = InputState::default();
                            }
                            Quit => {
                                info!(target: WASH_CMD_INFO, "Goodbye");
                                return Err("REPL Quit".into());
                            }
                            ReplCliCommand::Drain(draincmd) => {
                                let output_state = Arc::clone(&self.output_state);
                                std::thread::spawn(|| {
                                    match handle_drain(draincmd, output_state) {
                                        Ok(r) => r,
                                        Err(e) => error!("Error handling drain: {}", e),
                                    };
                                });
                            }
                            ReplCliCommand::Claims(claimscmd) => {
                                let output_state = Arc::clone(&self.output_state);
                                std::thread::spawn(|| {
                                    let mut rt = actix_rt::System::new("cmd");
                                    rt.block_on(async {
                                        match handle_claims(claimscmd, output_state).await {
                                            Ok(r) => r,
                                            Err(e) => error!("Error handling claims: {}", e),
                                        };
                                    });
                                });
                            }
                            ReplCliCommand::Ctl(ctlcmd) => {
                                let output_state = Arc::clone(&self.output_state);
                                std::thread::spawn(|| {
                                    let mut rt = actix_rt::System::new("cmd");
                                    rt.block_on(async {
                                        match handle_ctl(ctlcmd, output_state).await {
                                            Ok(r) => r,
                                            Err(e) => error!("Error handling ctl: {}", e),
                                        };
                                    });
                                });
                            }
                            ReplCliCommand::Keys(keyscmd) => {
                                let output_state = Arc::clone(&self.output_state);
                                std::thread::spawn(|| {
                                    let mut rt = actix_rt::System::new("cmd");
                                    rt.block_on(async {
                                        match handle_keys(keyscmd, output_state).await {
                                            Ok(r) => r,
                                            Err(e) => error!("Error handling key: {}", e),
                                        };
                                    });
                                });
                            }
                            ReplCliCommand::Par(parcmd) => {
                                let output_state = Arc::clone(&self.output_state);
                                std::thread::spawn(|| {
                                    let mut rt = actix_rt::System::new("cmd");
                                    rt.block_on(async {
                                        match handle_par(parcmd, output_state).await {
                                            Ok(r) => r,
                                            Err(e) => error!("Error handling par: {}", e),
                                        };
                                    });
                                });
                            }
                            ReplCliCommand::Reg(regcmd) => {
                                let output_state = Arc::clone(&self.output_state);
                                std::thread::spawn(|| {
                                    let mut rt = actix_rt::System::new("cmd");
                                    rt.block_on(async {
                                        match handle_reg(regcmd, output_state).await {
                                            Ok(r) => r,
                                            Err(e) => error!("Error handling reg: {}", e),
                                        };
                                    });
                                });
                            }
                        }
                    }
                    Err(e) => {
                        use structopt::clap::ErrorKind::*;
                        // HelpDisplayed is the StructOpt help text error, which should be displayed as info
                        match e.kind {
                            HelpDisplayed => info!(target: WASH_CMD_INFO, "{}", e.message),
                            _ => error!(target: WASH_CMD_INFO, "{}", e.message),
                        }
                    }
                };
            }
            _ => (),
        };
        Ok(())
    }
}

/// Launches REPL environment
async fn handle_up(cmd: UpCliCommand) -> Result<()> {
    // Initialize logger at default level based on user input. Defaults to Debug
    // Trace is very noisy and should be used only for intense debugging
    use LogLevel::*;
    let filter = match cmd.log_level {
        Error => LevelFilter::Error,
        Warn => LevelFilter::Warn,
        Info => LevelFilter::Info,
        Debug => LevelFilter::Debug,
        Trace => LevelFilter::Trace,
    };
    init_logger(filter).unwrap();
    set_default_level(filter);

    // Set global variable to show we're in REPL mode
    // This ensures the rest of the modules can properly format output information
    crate::util::REPL_MODE.set("true".to_string()).unwrap();

    // Initialize terminal
    let backend = {
        crossterm::terminal::enable_raw_mode().unwrap();
        let mut stdout = io::stdout();
        crossterm::execute!(stdout, EnterAlternateScreen).unwrap();
        CrosstermBackend::new(stdout)
    };
    let mut terminal = Terminal::new(backend).unwrap();
    terminal.clear().unwrap();
    terminal.hide_cursor().unwrap();

    // Start REPL
    let mut repl = WashRepl::default();
    repl.draw_ui(&mut terminal)?;
    info!(target: WASH_LOG_INFO, "Initializing REPL...");
    // Sending SPACE event to tui logger to hide disabled logs
    let evt = Event::Key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE));
    repl.tui_dispatcher.borrow_mut().dispatch(&evt);
    repl.draw_ui(&mut terminal)?;

    // Launch host in separate thread to avoid blocking host operations
    std::thread::spawn(move || {
        let mut rt = actix_rt::System::new("replhost");
        rt.block_on(async move {
            let nc_rpc =
                match nats::asynk::connect(&format!("{}:{}", cmd.rpc_host, cmd.rpc_port)).await {
                    Ok(conn) => conn,
                    Err(_e) => {
                        error!(
                            target: WASH_CMD_INFO,
                            "Error connecting to NATS at {}:{}",
                            cmd.rpc_host,
                            cmd.rpc_port
                        );
                        error!(target: WASH_CMD_INFO, "NATS is required to run control interface (ctl) commands. Please refer to
https://www.wasmcloud.dev/overview/getting-started/#starting-nats for instructions on how to launch NATS");
                        return;
                    }
                };
            let nc_control =
                match nats::asynk::connect(&format!("{}:{}", cmd.rpc_host, cmd.rpc_port)).await {
                    Ok(conn) => conn,
                    Err(_e) => {
                        error!(
                            target: WASH_CMD_INFO,
                            "Error connecting to NATS at {}:{}",
                            cmd.rpc_host,
                            cmd.rpc_port
                        );
                        error!(target: WASH_CMD_INFO, "NATS is required to run control interface (ctl) commands. Please refer to
https://www.wasmcloud.dev/overview/getting-started/#starting-nats for instructions on how to launch NATS");
                        return;
                    }
                };
            let host = HostBuilder::new()
                .with_namespace(CTL_NS)
                .with_rpc_client(nc_rpc)
                .with_control_client(nc_control)
                .with_label("repl_mode", "true")
                .oci_allow_latest()
                .oci_allow_insecure(vec!["localhost:5000".to_string()])
                .enable_live_updates()
                .build();
            if let Err(_e) = host.start().await.map_err(convert_error) {
                error!(target: WASH_LOG_INFO, "Error launching REPL host");
            } else {
                info!(
                    target: WASH_LOG_INFO,
                    "Host ({}) started in namespace ({})",
                    host.id(),
                    CTL_NS
                );
            };
            // Since CTRL+C won't be captured by this thread, host will stop when REPL exits
            actix_rt::signal::ctrl_c().await.unwrap();
            host.stop().await;
        });
    });

    repl.draw_ui(&mut terminal)?;
    let mut repl_focus = true;
    loop {
        // Polling here results in a nonblocking wait for events
        if poll(std::time::Duration::from_millis(50))? {
            let res = match read()? {
                // Tab toggles input focus between REPL and Tui logger selector
                Event::Key(KeyEvent {
                    code: KeyCode::Tab, ..
                }) => {
                    repl_focus = !repl_focus;
                    info!(
                        target: WASH_CMD_INFO,
                        "Switched command focus to {}",
                        if repl_focus {
                            "REPL"
                        } else {
                            "Logger selector"
                        }
                    );
                    Ok(())
                }
                // Dispatch events for REPL interpretation
                Event::Key(KeyEvent { code, modifiers }) if repl_focus => {
                    repl.handle_key(code, modifiers).await
                }
                // Dispatch events for Tui Target interpretation
                evt => {
                    repl.tui_dispatcher.borrow_mut().dispatch(&evt);
                    Ok(())
                }
            };
            repl.draw_ui(&mut terminal)?;

            // Exit the terminal gracefully
            if res.is_err() {
                cleanup_terminal(&mut terminal);
                break;
            }
        } else {
            // If no events occur, draw UI to show asynchronous logs
            repl.draw_ui(&mut terminal)?;
        }
    }
    cleanup_terminal(&mut terminal);
    Ok(())
}

fn handle_drain(drain_cmd: DrainCliCommand, output_state: Arc<Mutex<OutputState>>) -> Result<()> {
    let output = crate::drain::handle_command(drain_cmd)?;
    log_to_output(output_state, output);
    Ok(())
}

async fn handle_claims(
    claims_cmd: ClaimsCliCommand,
    output_state: Arc<Mutex<OutputState>>,
) -> Result<()> {
    let output = crate::claims::handle_command(claims_cmd).await?;
    log_to_output(output_state, output);
    Ok(())
}

async fn handle_ctl(ctl_cmd: CtlCliCommand, output_state: Arc<Mutex<OutputState>>) -> Result<()> {
    let output = crate::ctl::handle_command(ctl_cmd).await?;
    log_to_output(output_state, output);
    Ok(())
}

async fn handle_keys(
    keys_cmd: KeysCliCommand,
    output_state: Arc<Mutex<OutputState>>,
) -> Result<()> {
    let output = crate::keys::handle_command(keys_cmd)?;
    log_to_output(output_state, output);
    Ok(())
}

async fn handle_par(par_cmd: ParCliCommand, output_state: Arc<Mutex<OutputState>>) -> Result<()> {
    let output = crate::par::handle_command(par_cmd).await?;
    log_to_output(output_state, output);
    Ok(())
}

async fn handle_reg(reg_cmd: RegCliCommand, output_state: Arc<Mutex<OutputState>>) -> Result<()> {
    let output = crate::reg::handle_command(reg_cmd).await?;
    log_to_output(output_state, output);
    Ok(())
}

/// Helper function to exit the alternate tui terminal without corrupting the user terminal
fn cleanup_terminal(terminal: &mut Terminal<tui::backend::CrosstermBackend<std::io::Stdout>>) {
    terminal.show_cursor().unwrap();
    terminal.clear().unwrap();
    crossterm::execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture).unwrap();
    terminal::disable_raw_mode().unwrap();
}

/// Append a message to the output log
fn log_to_output(state: Arc<Mutex<OutputState>>, out: String) {
    // Reset output scroll to bottom
    let mut state = state.lock().unwrap();
    state.output_cursor = state.output.len();

    let output_width = state.output_width - 2;

    // Newlines are used here for accurate scrolling in the Output pane
    out.split('\n').for_each(|line| {
        let line_len = line.chars().count();
        if line_len > output_width {
            let mut offset = 0;
            // Div and round up
            let n_lines = (line_len + (output_width - 1)) / output_width;
            for _ in 0..n_lines {
                let sub_line = line.chars().skip(offset).take(output_width).collect();
                state.output.push(sub_line);
                offset += output_width
            }
            state.output_cursor += n_lines;
        } else {
            state.output.push(line.to_string());
            state.output_cursor += 1;
        }
    });
    state.output.push("".to_string());
    state.output_cursor += 1;
}

/// Helper function to delimit an input vec by newlines for proper REPL display
fn format_input_for_display(input_vec: Vec<char>, input_width: usize) -> String {
    let mut input = String::new();
    let mut index = WASH_PROMPT.len() - 1;
    let disp_iter = input_vec.iter();
    for c in disp_iter {
        if index == input_width - 1 {
            input.push('\n');
            input.push(*c);
            index = 0;
        } else {
            input.push(*c);
            index += 1;
        }
    }
    input
}

/// Display the wash REPL in the provided panel, automatically scroll with overflow
fn draw_input_panel(
    frame: &mut Frame<CrosstermBackend<Stdout>>,
    state: &mut InputState,
    chunk: Rect,
) {
    let history: String = state
        .history
        .iter()
        .map(|h| {
            format!(
                "{}{}\n",
                WASH_PROMPT,
                format_input_for_display(h.to_vec(), state.input_width)
            )
        })
        .collect();
    let prompt: String = WASH_PROMPT.to_string();

    let display = format!(
        "{}{}{}",
        history,
        prompt,
        format_input_for_display(state.input.clone(), state.input_width)
    );

    // 5 is the offset from the bottom of the chunk (3) plus 2 lines for buffer
    let scroll_offset = if state.history.len() as u16 + state.multiline_history >= chunk.height - 3
    {
        state.multiline_history + state.history.len() as u16 + 5 - chunk.height
    } else {
        0
    };
    // 3 is chunk size minus borders minus buffer space
    state.input_width = chunk.width as usize - 3;

    // Draw REPL panel
    let input_panel = Paragraph::new(display)
        .block(Block::default().borders(Borders::ALL).title(Span::styled(
            " REPL ",
            Style::default().add_modifier(Modifier::BOLD),
        )))
        .style(Style::default().fg(Color::White))
        .alignment(Alignment::Left)
        .scroll((scroll_offset, 0));
    frame.render_widget(input_panel, chunk);

    let input_cursor = state.cursor_location();

    // Draw cursor on screen
    frame.set_cursor(
        chunk.x + 1 + input_cursor.0,
        chunk.y + 1 + input_cursor.1 - scroll_offset,
    )
}

/// Display command output in the provided panel
fn draw_output_panel(
    frame: &mut Frame<CrosstermBackend<Stdout>>,
    state: Arc<Mutex<OutputState>>,
    chunk: Rect,
) {
    let mut state = state.lock().unwrap();
    let output_logs: String = state.output.iter().map(|h| format!(" {}\n", h)).collect();

    // Autoscroll if output overflows chunk height, adjusting for manual scroll with output_cursor
    let output_length = state.output.len() as u16;
    let output_cursor = state.output_cursor as u16;
    state.output_scroll = if output_length >= chunk.height - 3 {
        if output_cursor >= chunk.height {
            output_cursor as u16 + 1 - chunk.height
        } else {
            0
        }
    } else {
        0
    };
    state.output_width = chunk.width as usize - 1;

    // Draw REPL panel
    let output_panel = Paragraph::new(output_logs)
        .block(Block::default().borders(Borders::ALL).title(Span::styled(
            " OUTPUT (SHIFT+UP/DOWN to scroll) ",
            Style::default().add_modifier(Modifier::BOLD),
        )))
        .style(Style::default().fg(Color::White))
        .alignment(Alignment::Left)
        .scroll((state.output_scroll, 0))
        .wrap(Wrap { trim: false });
    frame.render_widget(output_panel, chunk);
}

/// Draws the Tui smart logger widget in the provided frame
fn draw_smart_logger(
    frame: &mut Frame<CrosstermBackend<Stdout>>,
    chunk: Rect,
    state: &TuiWidgetState,
    dispatcher: &Rc<RefCell<Dispatcher<Event>>>,
) {
    dispatcher.borrow_mut().clear();
    let selector_panel = TuiLoggerSmartWidget::default()
        .style_error(Style::default().fg(Color::Red))
        .style_debug(Style::default().fg(Color::Green))
        .style_warn(Style::default().fg(Color::Yellow))
        .style_trace(Style::default().fg(Color::Magenta))
        .style_info(Style::default().fg(Color::Cyan))
        .state(state)
        .dispatcher(dispatcher.clone());
    // These loggers are far too noisy and don't provide any value to a wasmcloud user
    set_level_for_target("tui_logger::dispatcher", LevelFilter::Off);
    set_level_for_target("mio::poll", LevelFilter::Off);
    set_level_for_target("mio::sys::unix::kqueue", LevelFilter::Off);
    set_level_for_target("polling", LevelFilter::Off);
    set_level_for_target("polling::kqueue", LevelFilter::Off);
    set_level_for_target("async_io::driver", LevelFilter::Off);
    set_level_for_target("async_io::reactor", LevelFilter::Off);

    frame.render_widget(selector_panel, chunk);
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    /// Enumerates multiple options of the `up` command to ensure API doesn't
    /// change between versions. This test will fail if `wash up`
    /// changes syntax, ordering of required elements, or flags.
    fn test_up_comprehensive() -> Result<()> {
        const LOG_LEVEL: &str = "info";
        const RPC_HOST: &str = "0.0.0.0";
        const RPC_PORT: &str = "4222";

        let up_all_options = UpCli::from_iter_safe(&[
            "up",
            "--log-level",
            LOG_LEVEL,
            "--host",
            RPC_HOST,
            "--port",
            RPC_PORT,
        ])?;
        let up_all_short_options =
            UpCli::from_iter_safe(&["up", "-l", LOG_LEVEL, "-h", RPC_HOST, "-p", RPC_PORT])?;

        #[allow(unreachable_patterns)]
        match up_all_options.command {
            UpCliCommand {
                rpc_host,
                rpc_port,
                log_level,
            } => {
                assert_eq!(rpc_host, RPC_HOST);
                assert_eq!(rpc_port, RPC_PORT);
                assert_eq!(log_level, LogLevel::Info);
            }
            cmd => panic!("up generated other command {:?}", cmd),
        }

        #[allow(unreachable_patterns)]
        match up_all_short_options.command {
            UpCliCommand {
                rpc_host,
                rpc_port,
                log_level,
            } => {
                assert_eq!(rpc_host, RPC_HOST);
                assert_eq!(rpc_port, RPC_PORT);
                assert_eq!(log_level, LogLevel::Info);
            }
            cmd => panic!("up generated other command {:?}", cmd),
        }

        Ok(())
    }

    #[test]
    fn test_up_input_format() {
        const CALL_INPUT: &str = "ctl call MBCFOPM6JW2APJLXJD3Z5O4CN7CPYJ2B4FTKLJUR5YR5MITIU7HD3WD5 HandleRequest {\"method\": \"GET\", \"path\": \"/\", \"body\": \"\", \"queryString\":\"\", \"header\":{}}";
        const START_ACTOR_INPUT: &str = "ctl start actor wasmcloud.azurecr.io/echo:0.2.0";
        const LINK_INPUT: &str = "ctl link MCFMFDWFHGKELOXPCNCDXKK5OFLHBVEWRAOXR5JSQUD2TOFRE3DFPM7E VAG3QITQQ2ODAOWB5TTQSDJ53XK3SHBEIFNK4AYJ5RKAX2UNSCAPHA5M wasmcloud:httpserver PORT=8080";
        const TERMINAL_WIDTH: usize = 80;
        let prompt_length = super::WASH_PROMPT.len(); // `wash> `

        let (call_first_line, call_second_line) =
            CALL_INPUT.split_at(TERMINAL_WIDTH - prompt_length);
        let call_input_display =
            format_input_for_display(CALL_INPUT.chars().collect(), TERMINAL_WIDTH);
        let mut call_iter = call_input_display.split('\n');
        assert_eq!(call_first_line, call_iter.next().unwrap());
        assert_eq!(call_second_line, call_iter.next().unwrap());

        assert!(START_ACTOR_INPUT.len() < TERMINAL_WIDTH - prompt_length);
        let start_input_display =
            format_input_for_display(START_ACTOR_INPUT.chars().collect(), TERMINAL_WIDTH);
        let mut start_iter = start_input_display.split('\n');
        assert_eq!(START_ACTOR_INPUT, start_iter.next().unwrap());

        let (link_first_line, link_second_line) =
            LINK_INPUT.split_at(TERMINAL_WIDTH - prompt_length);
        let link_input_display =
            format_input_for_display(LINK_INPUT.chars().collect(), TERMINAL_WIDTH);
        let mut link_iter = link_input_display.split('\n');
        assert_eq!(link_first_line, link_iter.next().unwrap());
        assert_eq!(link_second_line, link_iter.next().unwrap());
    }

    #[test]
    //TODO(brooksmtownsend): Write this test after merging in tui_logger changes. This changes the API
    fn test_key_events() {
        // let repl = WashRepl::default();
        // repl.handle_key(code: KeyCode, modifier: KeyModifiers)
    }

    #[test]
    fn test_log_level_from_str() -> Result<()> {
        use std::str::FromStr;
        const ERROR: &str = "error";
        const WARN: &str = "warn";
        const DEBUG: &str = "debug";
        const INFO: &str = "info";
        const TRACE: &str = "trace";
        const FOO: &str = "foo";

        assert_eq!(LogLevel::from_str(ERROR)?, LogLevel::Error);
        assert_eq!(LogLevel::from_str(WARN)?, LogLevel::Warn);
        assert_eq!(LogLevel::from_str(DEBUG)?, LogLevel::Debug);
        assert_eq!(LogLevel::from_str(INFO)?, LogLevel::Info);
        assert_eq!(LogLevel::from_str(TRACE)?, LogLevel::Trace);
        assert_eq!(LogLevel::from_str(FOO)?, LogLevel::Trace);
        Ok(())
    }
}