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
|
use std::io::stdout;
use eyre::Result;
use semver::Version;
use termion::{
event::Event as TermEvent, event::Key, event::MouseButton, event::MouseEvent,
input::MouseTerminal, raw::IntoRawMode, screen::AlternateScreen,
};
use tui::{
backend::{Backend, TermionBackend},
layout::{Alignment, Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Span, Spans, Text},
widgets::{Block, BorderType, Borders, Paragraph},
Frame, Terminal,
};
use unicode_width::UnicodeWidthStr;
use atuin_client::{
database::current_context,
database::Context,
database::Database,
history::History,
settings::{FilterMode, SearchMode, Settings},
};
use super::{
cursor::Cursor,
event::{Event, Events},
history_list::{HistoryList, ListState, PREFIX_LENGTH},
};
use crate::VERSION;
struct State {
history_count: i64,
input: Cursor,
filter_mode: FilterMode,
results_state: ListState,
context: Context,
update_needed: Option<Version>,
}
impl State {
async fn query_results(
&mut self,
search_mode: SearchMode,
db: &mut impl Database,
) -> Result<Vec<History>> {
let i = self.input.as_str();
let results = if i.is_empty() {
db.list(self.filter_mode, &self.context, Some(200), true)
.await?
} else {
db.search(Some(200), search_mode, self.filter_mode, &self.context, i)
.await?
};
self.results_state.select(0);
Ok(results)
}
fn handle_input(&mut self, input: &TermEvent, len: usize) -> Option<usize> {
match input {
TermEvent::Key(Key::Esc | Key::Ctrl('c' | 'd' | 'g')) => return Some(usize::MAX),
TermEvent::Key(Key::Char('\n')) => {
return Some(self.results_state.selected());
}
TermEvent::Key(Key::Alt(c @ '1'..='9')) => {
let c = c.to_digit(10)? as usize;
return Some(self.results_state.selected() + c);
}
TermEvent::Key(Key::Left | Key::Ctrl('h')) => {
self.input.left();
}
TermEvent::Key(Key::Right | Key::Ctrl('l')) => self.input.right(),
TermEvent::Key(Key::Ctrl('a')) => self.input.start(),
TermEvent::Key(Key::Ctrl('e')) => self.input.end(),
TermEvent::Key(Key::Char(c)) => self.input.insert(*c),
TermEvent::Key(Key::Backspace) => {
self.input.back();
}
TermEvent::Key(Key::Ctrl('w')) => {
// remove the first batch of whitespace
while matches!(self.input.back(), Some(c) if c.is_whitespace()) {}
while self.input.left() {
if self.input.char().unwrap().is_whitespace() {
self.input.right(); // found whitespace, go back right
break;
}
self.input.remove();
}
}
TermEvent::Key(Key::Ctrl('u')) => self.input.clear(),
TermEvent::Key(Key::Ctrl('r')) => {
pub static FILTER_MODES: [FilterMode; 4] = [
FilterMode::Global,
FilterMode::Host,
FilterMode::Session,
FilterMode::Directory,
];
let i = self.filter_mode as usize;
let i = (i + 1) % FILTER_MODES.len();
self.filter_mode = FILTER_MODES[i];
}
TermEvent::Key(Key::Down | Key::Ctrl('n' | 'j'))
| TermEvent::Mouse(MouseEvent::Press(MouseButton::WheelDown, _, _)) => {
let i = self.results_state.selected().saturating_sub(1);
self.results_state.select(i);
}
TermEvent::Key(Key::Up | Key::Ctrl('p' | 'k'))
| TermEvent::Mouse(MouseEvent::Press(MouseButton::WheelUp, _, _)) => {
let i = self.results_state.selected() + 1;
self.results_state.select(i.min(len - 1));
}
_ => {}
};
None
}
#[allow(clippy::cast_possible_truncation)]
fn draw<T: Backend>(&mut self, f: &mut Frame<'_, T>, results: &[History]) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(0)
.constraints([
Constraint::Length(3),
Constraint::Min(1),
Constraint::Length(3),
])
.split(f.size());
let top_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50); 2])
.split(chunks[0]);
let top_left_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(1); 3])
.split(top_chunks[0]);
let top_right_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(1); 3])
.split(top_chunks[1]);
let title = if self.update_needed.is_some() {
let version = self.update_needed.clone().unwrap();
Paragraph::new(Text::from(Span::styled(
format!(" Atuin v{VERSION} - UPDATE AVAILABLE {version}"),
Style::default().add_modifier(Modifier::BOLD).fg(Color::Red),
)))
} else {
Paragraph::new(Text::from(Span::styled(
format!(" Atuin v{VERSION}"),
Style::default().add_modifier(Modifier::BOLD),
)))
};
let help = vec![
Span::raw(" Press "),
Span::styled("Esc", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to exit."),
];
let help = Paragraph::new(Text::from(Spans::from(help)));
let stats = Paragraph::new(Text::from(Span::raw(format!(
"history count: {} ",
self.history_count
))));
f.render_widget(title, top_left_chunks[1]);
f.render_widget(help, top_left_chunks[2]);
f.render_widget(stats.alignment(Alignment::Right), top_right_chunks[1]);
let results = HistoryList::new(results).block(
Block::default()
.borders(Borders::TOP | Borders::LEFT | Borders::RIGHT)
.border_type(BorderType::Rounded),
);
f.render_stateful_widget(results, chunks[1], &mut self.results_state);
let input = format!(
"[{:^14}] {}",
self.filter_mode.as_str(),
self.input.as_str(),
);
let input = Paragraph::new(input).block(
Block::default()
.borders(Borders::BOTTOM | Borders::LEFT | Borders::RIGHT)
.border_type(BorderType::Rounded)
.title(format!(
"{:─>width$}",
"",
width = chunks[2].width as usize - 2
)),
);
f.render_widget(input, chunks[2]);
let width = UnicodeWidthStr::width(self.input.substring());
f.set_cursor(
// Put cursor past the end of the input text
chunks[2].x + width as u16 + PREFIX_LENGTH + 2,
// Move one line down, from the border to the input line
chunks[2].y + 1,
);
}
#[allow(clippy::cast_possible_truncation)]
fn draw_compact<T: Backend>(&mut self, f: &mut Frame<'_, T>, results: &[History]) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(0)
.horizontal_margin(1)
.constraints(
[
Constraint::Length(1),
Constraint::Min(1),
Constraint::Length(1),
]
.as_ref(),
)
.split(f.size());
let header_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(
[
Constraint::Ratio(1, 3),
Constraint::Ratio(1, 3),
Constraint::Ratio(1, 3),
]
.as_ref(),
)
.split(chunks[0]);
let title = Paragraph::new(Text::from(Span::styled(
format!("Atuin v{}", VERSION),
Style::default().fg(Color::DarkGray),
)));
let help = Paragraph::new(Text::from(Spans::from(vec![
Span::styled("Esc", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to exit"),
])))
.style(Style::default().fg(Color::DarkGray))
.alignment(Alignment::Center);
let stats = Paragraph::new(Text::from(Span::raw(format!(
"history count: {}",
self.history_count,
))))
.style(Style::default().fg(Color::DarkGray))
.alignment(Alignment::Right);
f.render_widget(title, header_chunks[0]);
f.render_widget(help, header_chunks[1]);
f.render_widget(stats, header_chunks[2]);
let results = HistoryList::new(results);
f.render_stateful_widget(results, chunks[1], &mut self.results_state);
let input = format!(
"[{:^14}] {}",
self.filter_mode.as_str(),
self.input.as_str(),
);
let input = Paragraph::new(input);
f.render_widget(input, chunks[2]);
let extra_width = UnicodeWidthStr::width(self.input.substring());
f.set_cursor(
// Put cursor past the end of the input text
chunks[2].x + extra_width as u16 + PREFIX_LENGTH + 1,
// Move one line down, from the border to the input line
chunks[2].y + 1,
);
}
}
// this is a big blob of horrible! clean it up!
// for now, it works. But it'd be great if it were more easily readable, and
// modular. I'd like to add some more stats and stuff at some point
#[allow(clippy::cast_possible_truncation)]
pub async fn history(
query: &[String],
settings: &Settings,
db: &mut impl Database,
) -> Result<String> {
let stdout = stdout().into_raw_mode()?;
let stdout = MouseTerminal::from(stdout);
let stdout = AlternateScreen::from(stdout);
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Setup event handlers
let events = Events::new();
let mut input = Cursor::from(query.join(" "));
// Put the cursor at the end of the query by default
input.end();
let update_needed = settings.needs_update().await;
let mut app = State {
history_count: db.history_count().await?,
input,
results_state: ListState::default(),
context: current_context(),
filter_mode: settings.filter_mode,
update_needed,
};
let mut results = app.query_results(settings.search_mode, db).await?;
let index = 'render: loop {
let initial_input = app.input.as_str().to_owned();
let initial_filter_mode = app.filter_mode;
// Handle input
if let Event::Input(input) = events.next()? {
if let Some(i) = app.handle_input(&input, results.len()) {
break 'render i;
}
}
// After we receive input process the whole event channel before query/render.
while let Ok(Event::Input(input)) = events.try_next() {
if let Some(i) = app.handle_input(&input, results.len()) {
break 'render i;
}
}
if initial_input != app.input.as_str() || initial_filter_mode != app.filter_mode {
results = app.query_results(settings.search_mode, db).await?;
}
let compact = match settings.style {
atuin_client::settings::Style::Auto => {
terminal.size().map(|size| size.height < 14).unwrap_or(true)
}
atuin_client::settings::Style::Compact => true,
atuin_client::settings::Style::Full => false,
};
if compact {
terminal.draw(|f| app.draw_compact(f, &results))?;
} else {
terminal.draw(|f| app.draw(f, &results))?;
}
};
if index < results.len() {
// index is in bounds so we return that entry
Ok(results.swap_remove(index).command)
} else if index == usize::MAX {
// index is max which implies an early exit
Ok(String::new())
} else {
// out of bounds usually implies no selected entry so we return the input
Ok(app.input.into_inner())
}
}
|