thag_rs 0.2.1

A versatile cross-platform playground and REPL for Rust snippets, expressions and programs. Accepts a script file or dynamic options.
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
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
/*[toml]
[dependencies]
crossterm = "0.29"
lazy_static = "1.4.0"
mockall = "0.13.0"
ratatui = "0.29"
regex = "1.10.4"
scopeguard = "1.2.0"
serde = "1.0.219"
serde_json = "1.0.132"
thag_profiler = { version = "0.1, thag-auto", features = ["full_profiling"] }
thag_rs = { version = "0.2, thag-auto", default-features = false, features = ["tui", "simplelog"] }
tui-textarea = { version = "0.7", features = ["search"] }
*/

#![allow(clippy::uninlined_format_args)]

use lazy_static::lazy_static;
use mockall::{automock, predicate::str};
/**

A version of a previous version of `demo/stdin_main.rs` instrumented for profiling with `thag_profiler`.
**Caution**: For memory profiling of the `Ctrl+L: keys` action, this particular example is painfully slow,
even though the original is not. As detailed memory profiling shows, this is because a great deal of memory
allocation is taking place in the `cassowary` solver algorithm that calculates the layout. All allocations
are less than 4KB and almost half the profiled allocations are under 64B. No fingers are being pointed here
since GUI layout is fiendishly difficult - but it is something out of our control without a radical redesign
- which wouldn't be justified because the normal response is still sub-second. But it does illustrate how
and why memory profiling can be slow in some cases.

E.g. `THAG_PROFILER=both,,announce,true thag demo/stdin_main_instr.rs`
*/
//# Purpose: Debugging.
//# Categories: testing, tui
use ratatui::crossterm::{
    event::{
        DisableMouseCapture,
        EnableBracketedPaste,
        EnableMouseCapture,
        Event::{self, Paste},
        // KeyCode, KeyEvent, KeyModifiers,
    },
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Alignment, Constraint, Direction, Layout, Margin},
    prelude::Rect,
    style::{Color, Modifier, Style, Stylize},
    widgets::{block::Title, Block, Borders, Clear, Paragraph},
    Terminal,
};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json;
use std::io::{self, BufRead, IsTerminal};
use std::{collections::VecDeque, fs, path::PathBuf};
use thag_rs::{errors::ThagError, vprtln, Verbosity};
use tui_textarea::{CursorMove, Input, Key, TextArea};

use thag_profiler::*;

#[derive(Default, Serialize, Deserialize)]
struct History {
    entries: VecDeque<String>,
    current_index: Option<usize>,
}

impl History {
    #[profiled]
    fn new() -> Self {
        Self {
            entries: VecDeque::with_capacity(20),
            current_index: None,
        }
    }

    #[profiled]
    fn load_from_file(path: &PathBuf) -> Self {
        fs::read_to_string(path).map_or_else(
            |_| Self::default(),
            |data| serde_json::from_str(&data).unwrap_or_else(|_| Self::new()),
        )
    }

    #[profiled]
    fn save_to_file(&self, path: &PathBuf) {
        if let Ok(data) = serde_json::to_string(self) {
            let _ = fs::write(path, data);
        }
    }

    #[profiled]
    fn add_entry(&mut self, entry: String) {
        // Remove prior duplicates
        self.entries.retain(|f| f != &entry);
        self.entries.push_front(entry);
    }

    #[profiled]
    fn get_current(&mut self) -> Option<&String> {
        if self.entries.is_empty() {
            return None;
        }

        self.current_index = self.current_index.map_or(Some(0), |index| Some(index + 1));
        self.entries.front()
    }

    #[profiled]
    fn get_previous(&mut self) -> Option<&String> {
        if self.entries.is_empty() {
            return None;
        }

        self.current_index = self.current_index.map_or(Some(0), |index| Some(index + 1));
        self.current_index.and_then(|index| self.entries.get(index))
    }

    #[profiled]
    fn get_next(&mut self) -> Option<&String> {
        if self.entries.is_empty() {
            return None;
        }

        self.current_index = match self.current_index {
            Some(index) if index > 0 => Some(index - 1),
            Some(index) if index == 0 => Some(index + self.entries.len() - 1),
            _ => Some(self.entries.len() - 1),
        };

        self.current_index.and_then(|index| self.entries.get(index))
    }
}

// A trait to allow mocking of the event reader for testing purposes.
#[automock]
pub trait EventReader {
    // Read a `crossterm` event.
    // # Errors
    //
    // If the timeout expires then an error is returned and buf is unchanged.
    fn read_event(&self) -> Result<Event, std::io::Error>;
}

// A struct to implement real-world use of the event reader, as opposed to use in testing.
pub struct CrosstermEventReader;

impl EventReader for CrosstermEventReader {
    #[profiled]
    fn read_event(&self) -> Result<Event, std::io::Error> {
        ratatui::crossterm::event::read()
    }
}

#[allow(dead_code)]
#[enable_profiling(runtime)]
fn main() -> Result<(), ThagError> {
    let event_reader = CrosstermEventReader;
    for line in &edit(&event_reader)? {
        vprtln!(Verbosity::Normal, "{line}");
    }
    Ok(())
}

// Edit the stdin stream.
//
//
// # Examples
//
// ```no_run
// use thag_rs::stdin::{edit, CrosstermEventReader};
// use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers };
// # use thag_rs::stdin::MockEventReader;
//
// # let mut event_reader = MockEventReader::new();
// # event_reader.expect_read_event().return_once(|| {
// #     Ok(Event::Key(KeyEvent::new(
// #         KeyCode::Char('d'),
// #         KeyModifiers::CONTROL,
// #     )))
// # });
// let actual = edit(&event_reader);
// let buf = vec![""];
// assert!(matches!(actual, Ok(buf)));
// ```
// # Errors
//
// If the data in this stream is not valid UTF-8 then an error is returned and buf is unchanged.
// # Panics
//
// If the terminal cannot be reset.
#[allow(clippy::too_many_lines)]
#[profiled]
pub fn edit<R: EventReader>(event_reader: &R) -> Result<Vec<String>, ThagError> {
    let input = std::io::stdin();
    let cargo_home = std::env::var("CARGO_HOME").unwrap_or_else(|_| ".".into());
    let history_path = PathBuf::from(cargo_home).join("rs_stdin_history.json");

    let mut history = History::load_from_file(&history_path);

    let mut saved_to_history = false;

    let initial_content = if input.is_terminal() {
        String::new()
    } else {
        read()?
    };

    let mut popup = false;
    let mut alt_highlights = false;

    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    enable_raw_mode()?;

    ratatui::crossterm::execute!(
        stdout,
        EnterAlternateScreen,
        EnableMouseCapture,
        EnableBracketedPaste
    )
    .map_err(|e| {
        // println!("Error executing terminal commands: {:?}", e);
        e
    })?;
    let backend = CrosstermBackend::new(stdout);
    let terminal = Terminal::new(backend)?; // Ensure terminal will get reset when it goes out of scope.
    let mut term = scopeguard::guard(terminal, |term| {
        reset_term(term).expect("Error resetting terminal");
    });

    let mut textarea = TextArea::from(initial_content.lines());

    textarea.set_block(
        Block::default()
            .borders(Borders::NONE)
            .title("Enter / paste / edit Rust script. Ctrl+D: submit  Ctrl+Q: quit  Ctrl+L: keys")
            .title_style(Style::default().fg(Color::Yellow).bold().italic()),
    );
    textarea.set_line_number_style(Style::default().fg(Color::DarkGray));
    textarea.set_selection_style(Style::default().bg(Color::Blue));
    textarea.set_cursor_style(Style::default().on_magenta());
    textarea.set_cursor_line_style(Style::default().on_dark_gray());

    textarea.move_cursor(CursorMove::Bottom);

    apply_highlights(alt_highlights, &mut textarea);

    loop {
        term.draw(|f| {
            f.render_widget(&textarea, f.area());
            if popup {
                show_popup(f);
            }
            apply_highlights(alt_highlights, &mut textarea);
        })
        .map_err(|e| {
            println!("Error drawing terminal: {:?}", e);
            e
        })?;
        let event = event_reader.read_event().map_err(|e| {
            println!("Error reading event: {:?}", e);
            e
        })?;
        if let Paste(ref data) = event {
            textarea.insert_str(normalize_newlines(data));
        } else {
            let input = Input::from(event);
            match input {
                Input {
                    key: Key::Char('q'),
                    ctrl: true,
                    ..
                } => {
                    return Err(ThagError::Cancelled);
                }
                Input {
                    key: Key::Char('d'),
                    ctrl: true,
                    ..
                } => {
                    // 6 >5,4,3,2,1 -> 6 >6,5,4,3,2,1
                    history.add_entry(textarea.lines().to_vec().join("\n"));
                    history.current_index = Some(0);
                    history.save_to_file(&history_path);
                    break;
                }
                Input {
                    key: Key::Char('l'),
                    ctrl: true,
                    ..
                } => popup = !popup,
                Input {
                    key: Key::Char('t'),
                    ctrl: true,
                    ..
                } => {
                    alt_highlights = !alt_highlights;
                    term.draw(|_| {
                        apply_highlights(alt_highlights, &mut textarea);
                    })?;
                }
                Input { key: Key::F(1), .. } => {
                    let mut found = false;
                    // 6 5,4,3,2,1 -> >5,4,3,2,1
                    if saved_to_history {
                        if let Some(entry) = history.get_previous() {
                            // 5
                            found = true;
                            textarea.select_all();
                            textarea.cut(); // 6
                            textarea.insert_str(entry); // 5
                        }
                    } else {
                        // println!("Not already saved to history: calling history.get_current()");
                        if let Some(entry) = history.get_current() {
                            found = true;
                            textarea.select_all();
                            textarea.cut(); // 6
                            textarea.insert_str(entry); // 5
                        }
                    }
                    if found && !saved_to_history && !textarea.yank_text().is_empty() {
                        // 5 >5,4,3,2,1 -> 5 6,>5,4,3,2,1
                        history
                            .add_entry(textarea.yank_text().lines().collect::<Vec<_>>().join("\n"));
                        saved_to_history = true;
                    }
                }
                Input { key: Key::F(2), .. } => {
                    // 5 >6,5,4,3,2,1 ->
                    if let Some(entry) = history.get_next() {
                        textarea.select_all();
                        textarea.cut();
                        textarea.insert_str(entry);
                    }
                }
                input => {
                    textarea.input(input);
                }
            }
        }
    }

    Ok(textarea.lines().to_vec())
}

// Prompt for and read Rust source code from stdin.
//
// # Examples
//
// ```
// use thag_rs::stdin::read;
//
// let hello = String::from("Hello world!");
// assert!(matches!(read(), Ok(hello)));
// ```
// # Errors
//
// If the data in this stream is not valid UTF-8 then an error is returned and buf is unchanged.
#[profiled]
pub fn read() -> Result<String, std::io::Error> {
    vprtln!(Verbosity::Normal, "Enter or paste lines of Rust source code at the prompt and press Ctrl-D on a new line when done");
    let buffer = read_to_string(&mut std::io::stdin().lock())?;
    Ok(buffer)
}

// Read the input from a `BufRead` implementing item into a String.
//
// # Examples
//
// ```
// use thag_rs::stdin::read_to_string;
//
// let stdin = std::io::stdin();
// let mut input = stdin.lock();
// let hello = String::from("Hello world!");
// assert!(matches!(read_to_string(&mut input), Ok(hello)));
// ```
//
// # Errors
//
// If the data in this stream is not valid UTF-8 then an error is returned and buf is unchanged.
#[profiled]
pub fn read_to_string<R: BufRead>(input: &mut R) -> Result<String, io::Error> {
    let mut buffer = String::new();
    input.read_to_string(&mut buffer)?;
    Ok(buffer)
}

// Convert the different newline sequences for Windows and other platforms into the common
// standard sequence of `"\n"` (backslash + 'n', as opposed to the '\n' (0xa) character for which
// it stands).
#[must_use]
#[profiled]
pub fn normalize_newlines(input: &str) -> String {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"\r\n?").unwrap();
    }
    RE.replace_all(input, "\n").to_string()
}

/// Apply highlights to the text depending on the light or dark theme as detected, configured
/// or defaulted, or as toggled by the user with Ctrl-t.
#[profiled]
pub fn apply_highlights(alt_highlights: bool, textarea: &mut TextArea) {
    if alt_highlights {
        // Dark theme-friendly colors
        textarea.set_selection_style(Style::default().bg(Color::Cyan).fg(Color::Black));
        textarea.set_cursor_style(Style::default().bg(Color::LightYellow).fg(Color::Black));
        textarea.set_cursor_line_style(Style::default().bg(Color::DarkGray).fg(Color::White));
    } else {
        // Light theme-friendly colors
        textarea.set_selection_style(Style::default().bg(Color::Blue).fg(Color::White));
        textarea.set_cursor_style(Style::default().bg(Color::LightRed).fg(Color::White));
        textarea.set_cursor_line_style(Style::default().bg(Color::Gray).fg(Color::Black));
    }
}

#[profiled]
fn reset_term(mut term: Terminal<CrosstermBackend<io::StdoutLock<'_>>>) -> Result<(), ThagError> {
    disable_raw_mode()?;
    ratatui::crossterm::execute!(
        term.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    term.show_cursor()?;
    Ok(())
}

#[allow(clippy::cast_possible_truncation)]
#[profiled]
fn show_popup(f: &mut ratatui::prelude::Frame) {
    profile!(s1_area);
    let area = centered_rect(90, NUM_ROWS as u16 + 5, f.area());
    let inner = area.inner(Margin {
        vertical: 2,
        horizontal: 2,
    });
    end!(s1_area);
    profile!(s2_block);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(Title::from("Platform-dependent key mappings (YMMV)"))
        .title(Title::from("(Ctrl+L to toggle)"))
        .title_alignment(Alignment::Center)
        .add_modifier(Modifier::BOLD);
    end!(s2_block);
    profile!(s3a_clear);
    f.render_widget(Clear, area);
    //this clears out the background
    end!(s3a_clear);
    profile!(s3b_clear);
    f.render_widget(block, area);
    end!(s3b_clear);
    profile!(s4_row_layout);
    let row_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints(std::iter::repeat(Constraint::Ratio(1, NUM_ROWS as u32)).take(NUM_ROWS));
    end!(s4_row_layout);
    profile!(s5_row_layout_split, time, mem_summary, mem_detail);
    let rows = row_layout.split(inner);
    end!(s5_row_layout_split);

    profile!(s6_render, time, mem_summary, mem_detail);
    for (i, row) in rows.iter().enumerate() {
        let col_layout = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(45), Constraint::Length(43)].as_ref());
        let cells = col_layout.split(*row);
        for n in 0..=1 {
            let mut widget = Paragraph::new(MAPPINGS[i][n]);
            if i == 0 {
                widget = widget.add_modifier(Modifier::BOLD);
            } else {
                widget = widget.remove_modifier(Modifier::BOLD);
            }
            f.render_widget(widget, cells[n]);
        }
    }
    end!(s6_render);
}

#[profiled]
fn centered_rect(max_width: u16, max_height: u16, r: Rect) -> Rect {
    let popup_layout = Layout::vertical([
        Constraint::Fill(1),
        Constraint::Max(max_height),
        Constraint::Fill(1),
    ])
    .split(r);

    Layout::horizontal([
        Constraint::Fill(1),
        Constraint::Max(max_width),
        Constraint::Fill(1),
    ])
    .split(popup_layout[1])[1]
}

const MAPPINGS: &[[&str; 2]; 35] = &[
    ["Key bindings", "Description"],
    ["Shift+arrow keys", "Select/deselect ← chars→  / ↑ lines↓"],
    [
        "Shift+Ctrl+arrow keys",
        "Select/deselect ← words→  / ↑ paras↓",
    ],
    ["Ctrl+D", "Submit"],
    ["Ctrl+Q", "Cancel and quit"],
    ["Ctrl+H, Backspace", "Delete character before cursor"],
    ["Ctrl+I, Tab", "Indent"],
    ["Ctrl+M, Enter", "Insert newline"],
    ["Ctrl+K", "Delete from cursor to end of line"],
    ["Ctrl+J", "Delete from cursor to start of line"],
    ["Ctrl+W, Alt+<, Backspace", "Delete one word before cursor"],
    ["Alt+D, Delete", "Delete one word from cursor position"],
    ["Ctrl+U", "Undo"],
    ["Ctrl+R", "Redo"],
    ["Ctrl+C", "Copy (yank) selected text"],
    ["Ctrl+X", "Cut (yank) selected text"],
    ["Ctrl+Y", "Paste yanked text"],
    ["Ctrl+V, Shift+Ins, Cmd+V", "Paste from system clipboard"],
    ["Ctrl+F, →", "Move cursor forward one character"],
    ["Ctrl+B, ←", "Move cursor backward one character"],
    ["Ctrl+P, ↑", "Move cursor up one line"],
    ["Ctrl+N, ↓", "Move cursor down one line"],
    ["Alt+F, Ctrl+→", "Move cursor forward one word"],
    ["Atl+B, Ctrl+←", "Move cursor backward one word"],
    ["Alt+] or P, Ctrl+↑", "Move cursor up one paragraph"],
    ["Alt+[ or N, Ctrl+↓", "Move cursor down one paragraph"],
    [
        "Ctrl+E, End, Ctrl+Alt+F or → , Cmd+→",
        "Move cursor to end of line",
    ],
    [
        "Ctrl+A, Home, Ctrl+Alt+B or ← , Cmd+←",
        "Move cursor to start of line",
    ],
    ["Alt+<, Ctrl+Alt+P or ↑", "Move cursor to top of file"],
    ["Alt+>, Ctrl+Alt+N or↓", "Move cursor to bottom of file"],
    ["PageDown, Cmd+↓", "Page down"],
    ["Alt+V, PageUp, Cmd+↑", "Page up"],
    ["Ctrl+T", "Toggle selection highlight colours"],
    ["F1", "Previous in history"],
    ["F2", "Next in history"],
];
const NUM_ROWS: usize = MAPPINGS.len();