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
use std::fmt;

use crate::word_database::{WordDatabase, WordIndicesIter};

#[derive(Clone, Copy)]
pub enum EntrySource {
    Custom(usize),
    WordDatabase(usize),
}

struct FilteredEntry {
    pub source: EntrySource,
    pub score: u32,
}

#[derive(Default)]
pub struct Picker {
    fuzzy_matcher: FuzzyMatcher,
    custom_entries_len: usize,
    custom_entries_buffer: Vec<String>,
    filtered_entries: Vec<FilteredEntry>,

    cursor: Option<usize>,
    scroll: usize,
}

impl Picker {
    pub fn cursor(&self) -> Option<usize> {
        self.cursor
    }

    pub fn scroll(&self) -> usize {
        self.scroll
    }

    pub fn len(&self) -> usize {
        self.filtered_entries.len()
    }

    pub fn clear_cursor(&mut self) {
        self.cursor = None;
    }

    pub fn move_cursor(&mut self, offset: isize) {
        let end_index = match self.filtered_entries.len().checked_sub(1) {
            Some(i) => i,
            None => return,
        };

        match &mut self.cursor {
            Some(cursor) => {
                let mut index = *cursor as isize;
                index = index + offset;
                index = index.max(0);

                *cursor = end_index.min(index as _);
            }
            None => {
                if self.len() > 0 {
                    self.cursor = Some(0);
                }
            }
        };
    }

    pub fn update_scroll(&mut self, max_height: usize) -> usize {
        let height = self.len().min(max_height);
        let cursor = self.cursor.unwrap_or(0);
        if cursor < self.scroll {
            self.scroll = cursor;
        } else if cursor >= self.scroll + height {
            self.scroll = cursor + 1 - height;
        }
        self.scroll = self
            .scroll
            .min(self.filtered_entries.len().saturating_sub(height));
        height
    }

    pub fn clear(&mut self) {
        self.custom_entries_len = 0;
        self.filtered_entries.clear();
        self.cursor = None;
        self.scroll = 0;
    }

    fn new_custom_entry(&mut self) -> &mut String {
        if self.custom_entries_len == self.custom_entries_buffer.len() {
            self.custom_entries_buffer.push(String::new());
        }
        let entry = &mut self.custom_entries_buffer[self.custom_entries_len];
        self.custom_entries_len += 1;
        entry.clear();
        entry
    }

    pub fn add_custom_entry(&mut self, name: &str) {
        let entry = self.new_custom_entry();
        entry.push_str(name);
    }

    pub fn add_custom_entry_fmt(&mut self, args: fmt::Arguments) {
        let entry = self.new_custom_entry();
        let _ = fmt::write(entry, args);
    }

    pub fn add_custom_filtered_entries<'picker, 'pattern>(
        &'picker mut self,
        pattern: &'pattern str,
    ) -> AddCustomFilteredEntryGuard<'picker, 'pattern> {
        AddCustomFilteredEntryGuard {
            picker: self,
            pattern,
            needs_sorting: false,
        }
    }

    pub fn sort_filtered_entries(&mut self) {
        self.filtered_entries
            .sort_unstable_by(|a, b| b.score.cmp(&a.score));
    }

    pub fn filter(&mut self, word_indices: WordIndicesIter, pattern: &str) {
        self.filtered_entries.clear();

        for (i, word) in word_indices {
            let score = self.fuzzy_matcher.score(word, pattern);
            if score != 0 {
                self.filtered_entries.push(FilteredEntry {
                    source: EntrySource::WordDatabase(i),
                    score,
                });
            }
        }

        for i in 0..self.custom_entries_len {
            self.filter_custom_entry(i, pattern);
        }

        self.filtered_entries
            .sort_unstable_by(|a, b| b.score.cmp(&a.score));

        let len = self.filtered_entries.len();
        if len > 0 {
            self.cursor = self.cursor.map(|c| c.min(len - 1));
        } else {
            self.cursor = None;
        }
    }

    fn filter_custom_entry(&mut self, index: usize, pattern: &str) -> bool {
        let entry = &self.custom_entries_buffer[index];
        let score = self.fuzzy_matcher.score(entry, pattern);
        if score == 0 {
            return false;
        }

        self.filtered_entries.push(FilteredEntry {
            source: EntrySource::Custom(index),
            score,
        });
        true
    }

    pub fn current_entry<'a>(&'a self, words: &'a WordDatabase) -> Option<(EntrySource, &'a str)> {
        let entry = &self.filtered_entries[self.cursor?];
        let source = entry.source;
        let entry = filtered_to_picker_entry(entry, &self.custom_entries_buffer, words);
        Some((source, entry))
    }

    pub fn entries<'a>(
        &'a self,
        words: &'a WordDatabase,
    ) -> impl 'a + ExactSizeIterator<Item = &'a str> {
        let custom_entries = &self.custom_entries_buffer[..];
        self.filtered_entries
            .iter()
            .map(move |e| filtered_to_picker_entry(e, custom_entries, words))
    }
}

fn filtered_to_picker_entry<'a>(
    entry: &FilteredEntry,
    custom_entries: &'a [String],
    words: &'a WordDatabase,
) -> &'a str {
    match entry.source {
        EntrySource::Custom(i) => &custom_entries[i],
        EntrySource::WordDatabase(i) => words.word_at(i),
    }
}

pub struct AddCustomFilteredEntryGuard<'picker, 'pattern> {
    picker: &'picker mut Picker,
    pattern: &'pattern str,
    needs_sorting: bool,
}
impl<'picker, 'pattern> AddCustomFilteredEntryGuard<'picker, 'pattern> {
    pub fn add(&mut self, name: &str) {
        self.picker.add_custom_entry(name);
        let matched = self
            .picker
            .filter_custom_entry(self.picker.custom_entries_len - 1, self.pattern);
        self.needs_sorting = self.needs_sorting || matched;
    }
}
impl<'picker, 'pattern> Drop for AddCustomFilteredEntryGuard<'picker, 'pattern> {
    fn drop(&mut self) {
        if self.needs_sorting {
            self.picker
                .filtered_entries
                .sort_unstable_by(|a, b| b.score.cmp(&a.score));
        }
    }
}

const FIRST_CHAR_SCORE: u32 = 1;
const WORD_BOUNDARY_MATCH_SCORE: u32 = 2;
const CONSECUTIVE_MATCH_SCORE: u32 = 3;

struct FuzzyMatch {
    rest_index: u32,
    score: u32,
}

#[derive(Default)]
struct FuzzyMatcher {
    previous_matches: Vec<FuzzyMatch>,
    next_matches: Vec<FuzzyMatch>,
}
impl FuzzyMatcher {
    pub fn score(&mut self, text: &str, pattern: &str) -> u32 {
        if pattern.is_empty() {
            return 1;
        }

        self.previous_matches.clear();
        self.previous_matches.push(FuzzyMatch {
            rest_index: 0,
            score: 0,
        });

        for pattern_char in pattern.chars() {
            self.next_matches.clear();

            for previous_match in &self.previous_matches {
                let mut previous_text_char = '\0';
                for (i, text_char) in text[previous_match.rest_index as usize..].char_indices() {
                    if text_char.eq_ignore_ascii_case(&pattern_char) {
                        let (matched, mut score) = if i == 0 && previous_match.rest_index != 0 {
                            (true, CONSECUTIVE_MATCH_SCORE)
                        } else if !text_char.is_ascii_alphanumeric() {
                            (true, 0)
                        } else {
                            let is_word_boundary = (!previous_text_char.is_ascii_alphanumeric()
                                && text_char.is_ascii_alphanumeric())
                                || (previous_text_char.is_ascii_lowercase()
                                    && text_char.is_ascii_uppercase());
                            (is_word_boundary, WORD_BOUNDARY_MATCH_SCORE)
                        };

                        if matched {
                            if i == 0 && previous_match.rest_index == 0 {
                                score += FIRST_CHAR_SCORE;
                            }

                            let rest_index =
                                previous_match.rest_index + (i + text_char.len_utf8()) as u32;
                            let score = previous_match.score + score;
                            self.next_matches.push(FuzzyMatch { rest_index, score });
                        }
                    }

                    previous_text_char = text_char;
                }
            }

            if self.next_matches.is_empty() {
                return 0;
            }
            std::mem::swap(&mut self.previous_matches, &mut self.next_matches);
        }

        let mut best_score = 0;
        for previous_match in &self.previous_matches {
            if best_score < previous_match.score {
                best_score = previous_match.score;
            }
        }
        if best_score > 0 {
            best_score += (text.len() == pattern.len()) as u32;
        }
        best_score
    }
}

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

    #[test]
    fn fuzzy_matcher_test() {
        let mut fuzzy_matcher = FuzzyMatcher::default();

        assert_eq!(1, fuzzy_matcher.score("", ""));
        assert_eq!(1, fuzzy_matcher.score("abc", ""));
        assert_eq!(0, fuzzy_matcher.score("", "abc"));
        assert_eq!(0, fuzzy_matcher.score("abc", "z"));
        assert_eq!(0, fuzzy_matcher.score("a", "xyz"));

        assert_eq!(
            FIRST_CHAR_SCORE + WORD_BOUNDARY_MATCH_SCORE + CONSECUTIVE_MATCH_SCORE * 3 + 1,
            fuzzy_matcher.score("word", "word"),
        );

        assert_eq!(
            FIRST_CHAR_SCORE + WORD_BOUNDARY_MATCH_SCORE + CONSECUTIVE_MATCH_SCORE * 2,
            fuzzy_matcher.score("word", "wor"),
        );

        assert_eq!(0, fuzzy_matcher.score("word", "wrd"),);

        assert_eq!(
            FIRST_CHAR_SCORE + WORD_BOUNDARY_MATCH_SCORE + CONSECUTIVE_MATCH_SCORE,
            fuzzy_matcher.score("first/second", "f/s")
        );

        assert_eq!(
            FIRST_CHAR_SCORE + (WORD_BOUNDARY_MATCH_SCORE + CONSECUTIVE_MATCH_SCORE) * 2,
            fuzzy_matcher.score("camelCase", "caca"),
        );

        assert_eq!(
            FIRST_CHAR_SCORE + WORD_BOUNDARY_MATCH_SCORE * 3,
            fuzzy_matcher.score("ababAbA", "aaa")
        );
        assert_eq!(
            FIRST_CHAR_SCORE + WORD_BOUNDARY_MATCH_SCORE * 2,
            fuzzy_matcher.score("abc cde", "ac"),
        );
        assert_eq!(WORD_BOUNDARY_MATCH_SCORE, fuzzy_matcher.score("abc x", "x"));

        assert_eq!(
            WORD_BOUNDARY_MATCH_SCORE + CONSECUTIVE_MATCH_SCORE * 3,
            fuzzy_matcher.score("AxxBxx Abcd", "abcd")
        );

        assert_eq!(
            FIRST_CHAR_SCORE + WORD_BOUNDARY_MATCH_SCORE,
            fuzzy_matcher.score("abc", "a")
        );
        assert_eq!(
            WORD_BOUNDARY_MATCH_SCORE,
            fuzzy_matcher.score("xyz-abc", "a")
        );

        let repetition_count = 100;
        let big_repetitive_text = "a".repeat(repetition_count);
        assert_eq!(
            FIRST_CHAR_SCORE
                + WORD_BOUNDARY_MATCH_SCORE
                + CONSECUTIVE_MATCH_SCORE * (repetition_count - 1) as u32
                + 1,
            fuzzy_matcher.score(&big_repetitive_text, &big_repetitive_text),
        );
    }
}