summaryrefslogtreecommitdiffstats
path: root/src/command/client/search/core.rs
blob: f5d25c12ccca65a42adcc15c7aa381e8fab53015 (plain)
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
use std::{
    ops::{ControlFlow, Deref},
    sync::Arc,
};

use eyre::Result;
use semver::Version;

use atuin_client::{
    database::Context,
    database::{current_context, Database},
    history::History,
    settings::{ExitMode, FilterMode, SearchMode, Settings},
};
use skim::SkimItem;

use super::{cursor::Cursor, history_list::ListState};

pub struct State<DB: Database> {
    pub db: DB,
    pub results_state: ListState,
    pub history: Vec<Arc<HistoryWrapper>>,
    pub history_count: i64,
    pub settings: Settings,
    pub update_needed: Option<Version>,

    pub search: SearchState,

    // only allocated if using skim
    pub all_history: Vec<Arc<HistoryWrapper>>,
}

pub struct SearchState {
    pub input: Cursor,
    pub filter_mode: FilterMode,
    pub search_mode: SearchMode,
    /// Store if the user has _just_ changed the search mode.
    /// If so, we change the UI to show the search mode instead
    /// of the filter mode until user starts typing again.
    switched_search_mode: bool,
    pub context: Context,
}

pub struct HistoryWrapper {
    history: History,
    pub count: i32,
}
impl Deref for HistoryWrapper {
    type Target = History;

    fn deref(&self) -> &Self::Target {
        &self.history
    }
}
impl SkimItem for HistoryWrapper {
    fn text(&self) -> std::borrow::Cow<str> {
        std::borrow::Cow::Borrowed(self.history.command.as_str())
    }
}

pub struct BatchGuard<DB: Database> {
    initial_input: String,
    initial_filter_mode: FilterMode,
    inner: State<DB>,
}

#[derive(Clone)]
pub enum Line {
    Up,
    Down,
}
#[derive(Clone)]
pub enum For {
    Page,
    SingleLine,
}
#[derive(Clone)]
pub enum Towards {
    Left,
    Right,
}
#[derive(Clone)]
pub enum To {
    Word,
    Char,
    Edge,
}

#[derive(Clone)]
pub enum Event {
    Input(char),
    InputStr(String),
    Selection(Line, For),
    Cursor(Towards, To),
    Delete(Towards, To),
    Clear,
    Exit,
    UpdateNeeded(Version),
    Cancel,
    SelectN(u32),
    CycleFilterMode,
    CycleSearchMode,
}

impl<DB: Database> State<DB> {
    /// Create a new core state
    pub async fn new(query: &[String], settings: Settings, db: DB) -> Result<Self> {
        let mut input = Cursor::from(query.join(" "));
        // Put the cursor at the end of the query by default
        input.end();

        let mut core = Self {
            history_count: db.history_count().await?,
            results_state: ListState::default(),
            update_needed: None,
            history: Vec::new(),
            db,
            all_history: Vec::new(),
            search: SearchState {
                input,
                context: current_context(),
                filter_mode: if settings.shell_up_key_binding {
                    settings
                        .filter_mode_shell_up_key_binding
                        .unwrap_or(settings.filter_mode)
                } else {
                    settings.filter_mode
                },
                search_mode: settings.search_mode,
                switched_search_mode: false,
            },
            settings,
        };
        core.refresh_query().await?;
        Ok(core)
    }

    async fn refresh_query(&mut self) -> Result<()> {
        let i = self.search.input.as_str();
        let results = if i.is_empty() {
            self.db
                .list(
                    self.search.filter_mode,
                    &self.search.context,
                    Some(200),
                    true,
                )
                .await?
                .into_iter()
                .map(|history| HistoryWrapper { history, count: 1 })
                .map(Arc::new)
                .collect::<Vec<_>>()
        } else if self.search.search_mode == SearchMode::Skim {
            if self.all_history.is_empty() {
                self.all_history = self
                    .db
                    .all_with_count()
                    .await
                    .unwrap()
                    .into_iter()
                    .map(|(history, count)| HistoryWrapper { history, count })
                    .map(Arc::new)
                    .collect::<Vec<_>>();
            }

            super::skim_impl::fuzzy_search(&self.search, &self.all_history).await
        } else {
            self.db
                .search(
                    self.search.search_mode,
                    self.search.filter_mode,
                    &self.search.context,
                    i,
                    Some(200),
                    None,
                    None,
                )
                .await?
                .into_iter()
                .map(|history| HistoryWrapper { history, count: 1 })
                .map(Arc::new)
                .collect::<Vec<_>>()
        };

        self.results_state.select(0);
        self.history = results;
        Ok(())
    }

    fn handle(mut self, event: Event) -> ControlFlow<String, Self> {
        // reset the state, will be set to true later if user really did change it
        self.search.switched_search_mode = false;
        let len = self.history.len();
        match event {
            // moving the selection up and down
            Event::Selection(Line::Up, For::SingleLine) => {
                let i = self.results_state.selected() + 1;
                self.results_state.select(i.min(len - 1));
            }
            Event::Selection(Line::Down, For::SingleLine) => {
                let Some(i) = self.results_state.selected().checked_sub(1) else {
                    return ControlFlow::Break(String::new())
                };
                self.results_state.select(i);
            }
            Event::Selection(Line::Down, For::Page) => {
                let scroll_len =
                    self.results_state.max_entries() - self.settings.scroll_context_lines;
                let i = self.results_state.selected().saturating_sub(scroll_len);
                self.results_state.select(i);
            }
            Event::Selection(Line::Up, For::Page) => {
                let scroll_len =
                    self.results_state.max_entries() - self.settings.scroll_context_lines;
                let i = self.results_state.selected() + scroll_len;
                self.results_state.select(i.min(len - 1));
            }

            // moving the search cursor left and right
            Event::Cursor(Towards::Left, To::Char) => {
                self.search.input.left();
            }
            Event::Cursor(Towards::Right, To::Char) => self.search.input.right(),
            Event::Cursor(Towards::Left, To::Word) => self
                .search
                .input
                .prev_word(&self.settings.word_chars, self.settings.word_jump_mode),
            Event::Cursor(Towards::Right, To::Word) => self
                .search
                .input
                .next_word(&self.settings.word_chars, self.settings.word_jump_mode),
            Event::Cursor(Towards::Left, To::Edge) => self.search.input.start(),
            Event::Cursor(Towards::Right, To::Edge) => self.search.input.end