-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmod.rs
323 lines (280 loc) · 11.2 KB
/
mod.rs
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
// Copyright (c) 2023 RBB S.r.l
// opensource@mintlayer.org
// SPDX-License-Identifier: MIT
// Licensed under the MIT License;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/mintlayer/mintlayer-core/blob/master/LICENSE
//
// 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.
mod key_bindings;
pub mod log;
mod wallet_completions;
mod wallet_prompt;
use std::path::PathBuf;
use clap::Command;
use itertools::{FoldWhile, Itertools};
use reedline::{
default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings,
ColumnarMenu, DefaultValidator, EditMode, Emacs, FileBackedHistory, ListMenu, MenuBuilder,
Reedline, ReedlineMenu, Signal, Vi,
};
use tokio::sync::{mpsc, oneshot};
use wallet_cli_commands::{get_repl_command, parse_input, ConsoleCommand};
use wallet_rpc_lib::types::NodeInterface;
use crate::{
cli_event_loop::Event, console::ConsoleOutput, errors::WalletCliError,
repl::interactive::key_bindings::add_menu_keybindings,
};
const HISTORY_MAX_LINES: usize = 1000;
const HISTORY_MENU_NAME: &str = "history_menu";
const COMPLETION_MENU_NAME: &str = "completion_menu";
fn create_line_editor<N: NodeInterface>(
printer: reedline::ExternalPrinter<String>,
repl_command: super::Command,
history_file: Option<PathBuf>,
vi_mode: bool,
) -> Result<Reedline, WalletCliError<N>> {
let commands = repl_command
.get_subcommands()
.filter(|command| !command.is_hide_set())
.map(|command| command.get_name().to_owned())
.chain(std::iter::once("help".to_owned()))
.collect::<Vec<_>>();
let completer = Box::new(wallet_completions::WalletCompletions::new(commands));
let mut line_editor = Reedline::create()
.with_external_printer(printer)
.with_completer(completer)
.with_quick_completions(false)
.with_partial_completions(true)
.with_validator(Box::new(DefaultValidator))
.with_ansi_colors(true);
if let Some(file_name) = history_file {
let history = Box::new(
FileBackedHistory::with_file(HISTORY_MAX_LINES, file_name.clone())
.map_err(|e| WalletCliError::FileError(file_name, e.to_string()))?,
);
line_editor = line_editor.with_history(history);
}
// Adding default menus for the compiled reedline
line_editor = line_editor
.with_menu(ReedlineMenu::EngineCompleter(Box::new(
ColumnarMenu::default().with_name(COMPLETION_MENU_NAME),
)))
.with_menu(ReedlineMenu::HistoryMenu(Box::new(
ListMenu::default().with_name(HISTORY_MENU_NAME),
)));
let edit_mode: Box<dyn EditMode> = if vi_mode {
let mut normal_keybindings = default_vi_normal_keybindings();
let mut insert_keybindings = default_vi_insert_keybindings();
add_menu_keybindings(&mut normal_keybindings);
add_menu_keybindings(&mut insert_keybindings);
Box::new(Vi::new(insert_keybindings, normal_keybindings))
} else {
let mut keybindings = default_emacs_keybindings();
add_menu_keybindings(&mut keybindings);
Box::new(Emacs::new(keybindings))
};
line_editor = line_editor.with_edit_mode(edit_mode);
Ok(line_editor)
}
fn process_line<N: NodeInterface>(
repl_command: &Command,
event_tx: &mpsc::UnboundedSender<Event<N>>,
sig: reedline::Signal,
) -> Result<Option<ConsoleCommand>, WalletCliError<N>> {
let line = match sig {
Signal::Success(line) => line,
Signal::CtrlC => {
// Prompt has been cleared and should start on the next line
return Ok(None);
}
Signal::CtrlD => {
return Ok(Some(ConsoleCommand::Exit));
}
};
let command_opt = parse_input(&line, repl_command)?;
let command = match command_opt {
Some(command) => command,
None => return Ok(None),
};
super::run_command_blocking(event_tx, command).map(Option::Some)
}
#[allow(clippy::too_many_arguments)]
pub fn run<N: NodeInterface>(
mut console: impl ConsoleOutput,
event_tx: mpsc::UnboundedSender<Event<N>>,
exit_on_error: bool,
logger: log::InteractiveLogger,
history_file: Option<PathBuf>,
vi_mode: bool,
startup_command_futures: Vec<oneshot::Receiver<Result<ConsoleCommand, WalletCliError<N>>>>,
cold_wallet: bool,
) -> Result<(), WalletCliError<N>> {
let repl_command = get_repl_command(cold_wallet, true);
let mut line_editor = create_line_editor(
logger.printer().clone(),
repl_command.clone(),
history_file,
vi_mode,
)?;
let mut prompt = wallet_prompt::WalletPrompt::new();
// first wait for the results of any startup command before processing the rest
for res_rx in startup_command_futures {
let res = res_rx.blocking_recv().expect("Channel must be open");
if let Some(value) = handle_response(
res.map(Some),
&mut console,
&mut prompt,
&mut line_editor,
true,
) {
return value;
}
}
console.print_line("Use 'help' to see all available commands.");
console.print_line("Use 'help <command>' to learn more about the parameters of the command.");
console.print_line("Press TAB on your keyboard to auto-complete any command you write.");
console.print_line("Use 'exit' or Ctrl-D to quit.");
loop {
logger.set_print_directly(false);
let sig = line_editor.read_line(&prompt).expect("Should not fail normally");
logger.set_print_directly(true);
let res = process_line(&repl_command, &event_tx, sig);
if let Some(value) = handle_response(
res,
&mut console,
&mut prompt,
&mut line_editor,
exit_on_error,
) {
return value;
}
}
}
fn handle_response<N: NodeInterface>(
res: Result<Option<ConsoleCommand>, WalletCliError<N>>,
console: &mut impl ConsoleOutput,
prompt: &mut wallet_prompt::WalletPrompt,
line_editor: &mut Reedline,
exit_on_error: bool,
) -> Option<Result<(), WalletCliError<N>>> {
match res {
Ok(Some(ConsoleCommand::Print(text))) => {
console.print_line(&text);
}
Ok(Some(ConsoleCommand::PaginatedPrint { header, body })) => {
paginate_output(header, body, line_editor, console);
}
Ok(Some(ConsoleCommand::SetStatus {
status,
print_message,
})) => {
prompt.set_status(status);
console.print_line(&print_message);
}
Ok(Some(ConsoleCommand::ClearScreen)) => {
line_editor.clear_scrollback().expect("Should not fail normally");
}
Ok(Some(ConsoleCommand::ClearHistory)) => {
line_editor.history_mut().clear().expect("Should not fail normally");
}
Ok(Some(ConsoleCommand::PrintHistory)) => {
line_editor.print_history().expect("Should not fail normally");
}
Ok(Some(ConsoleCommand::Exit)) => return Some(Ok(())),
Ok(None) => {}
Err(err) => {
if exit_on_error {
return Some(Err(err));
}
console.print_error(err);
}
}
None
}
fn paginate_output(
header: String,
body: String,
line_editor: &mut Reedline,
console: &mut impl ConsoleOutput,
) {
let mut current_index = 0;
let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
let cols = cols as usize;
let page_rows = (rows - 4) as usize; // make room for the header and prompt
loop {
line_editor.clear_screen().expect("Should not fail normally");
let limit = compute_visible_text_limit(
body.get(current_index..).expect("safe point").lines(),
cols,
page_rows,
);
let end_index = std::cmp::min(current_index + limit, body.len());
console.print_line(&header);
console.print_line(body.get(current_index..end_index).expect("safe point"));
let commands = match (current_index, end_index) {
(0, end) if end == body.len() => "Press 'q' to quit",
(0, _) => "Press 'j' for down, 'q' to quit",
(_, end) if end == body.len() => "Press 'k' for previous, 'q' to quit",
(_, _) => "Press 'j' for next, 'k' for previous, 'q' to quit",
};
console.print_line(commands);
// Wait for user input.
crossterm::terminal::enable_raw_mode().expect("Should not fail normally");
let event = crossterm::event::read().expect("Should not fail normally");
crossterm::terminal::disable_raw_mode().expect("Should not fail normally");
if let crossterm::event::Event::Key(key_event) = event {
match key_event.code {
reedline::KeyCode::Char('j') | reedline::KeyCode::Down
if end_index < body.len() =>
{
let next_text = body.get(current_index..).expect("safe point").lines();
let limit = compute_visible_text_limit(next_text, cols, 1);
current_index = std::cmp::min(body.len(), current_index + limit);
}
reedline::KeyCode::Char('k') | reedline::KeyCode::Up if current_index > 0 => {
let prev_text = body.get(..current_index).expect("safe point").lines().rev();
let limit = compute_visible_text_limit(prev_text, cols, 1);
current_index = current_index.saturating_sub(limit);
}
reedline::KeyCode::Char('q') | reedline::KeyCode::Esc => {
break; // Exit pagination
}
_ => {} // Ignore other keys
}
}
}
line_editor.clear_screen().expect("Should not fail normally");
}
fn compute_visible_text_limit<'a, I>(mut lines: I, cols: usize, page_rows: usize) -> usize
where
I: Iterator<Item = &'a str>,
{
let (_, end_index) = lines
.fold_while((0, 0), |(current_rows, current_index), line| {
let new_rows = line.len().div_ceil(cols);
if current_rows + new_rows <= page_rows {
let new_total_rows = current_rows + new_rows;
let new_end_index = current_index + line.len() + 1;
FoldWhile::Continue((new_total_rows, new_end_index))
} else {
let rows_available = page_rows - current_rows;
// make sure we cut it on the start of a utf-8 char boundary
let new_end_index = current_index
+ (1..=rows_available * cols)
.rev()
.find(|&i| line.is_char_boundary(i))
// 0 is always a safe char boundary
.unwrap_or(0);
FoldWhile::Done((page_rows, new_end_index))
}
})
.into_inner();
end_index
}