nucleo-picker 0.11.0-beta

A performant and Unicode-aware fuzzy picker tui library
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
//! # A generic fuzzy item picker
//! This crate contains a generic picker implementation that allows you to natively incorporate an
//! interactive fuzzy picker TUI (similar in spirit to the very popular
//! [fzf](https://github.com/junegunn/fzf)) directly in your own applications.
//!
//! In short, initialize a [`Picker`] using [`PickerOptions`] and describe how the items
//! should be represented by implementing [`Render`], or use a [built-in renderer](render).
//!
//! For more complex use-cases and integration with an existing application, see the
//! [`event`] module.
//!
//! ## Usage examples
//! For more usage examples, visit the [examples
//! folder](https://github.com/autobib/nucleo-picker/tree/master/examples) on GitHub.
//!
//! ### `fzf` example
//! Run this example with `cat myfile.txt | cargo run --release --example fzf`.
//! ```no_run
#![doc = include_str!("../examples/fzf.rs")]
//! ```
//!
//! ### `find` example
//! Run this example with `cargo run --release --example find ~`.
//! ```no_run
#![doc = include_str!("../examples/find.rs")]
//! ```

#![deny(missing_docs)]
#![warn(rustdoc::unescaped_backticks)]
#![cfg_attr(docsrs, feature(doc_cfg))]

mod component;
pub mod error;
pub mod event;
mod incremental;
mod injector;
mod lazy;
mod match_list;
mod observer;
mod prompt;
pub mod render;
mod util;

use std::{
    borrow::Cow,
    io::{self, BufWriter, IsTerminal, Write},
    iter::Extend,
    num::NonZero,
    panic::{set_hook, take_hook},
    sync::Arc,
    thread::available_parallelism,
    time::{Duration, Instant},
};

use crossterm::{
    ExecutableCommand, QueueableCommand,
    cursor::MoveTo,
    event::{DisableBracketedPaste, EnableBracketedPaste, KeyEvent},
    execute,
    terminal::{
        BeginSynchronizedUpdate, EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen,
        disable_raw_mode, enable_raw_mode, size,
    },
};
use nucleo::{
    self as nc, Nucleo,
    pattern::{CaseMatching as NucleoCaseMatching, Normalization as NucleoNormalization},
};
use observer::{Notifier, Observer};

use crate::{
    component::Status,
    error::PickError,
    event::{Event, EventSource, RecvError, StdinReader, keybind_default},
    lazy::{LazyMatchList, LazyPrompt},
    match_list::{MatchList, MatchListConfig, Queued, SelectedIndices},
    prompt::{Prompt, PromptConfig},
};

pub use crate::injector::Injector;
pub use crate::match_list::Selection;
pub use nucleo;

/// A trait which describes how to render objects for matching and display.
///
/// Some renderers for common types are already implemented in the [`render`] module. In
/// many cases, the [`DisplayRenderer`](render::DisplayRenderer) is particularly easy to use.
/// This trait is also automatically implemented for [closures which return `Cow<'a,
/// str>`](#impl-Render<T>-for-R).
///
/// Rendering *must* be **pure**: for a given render implementation `R` and a item `T`, the call
/// `R::render(&self, &T)` must depend only on the specific render instance and the specific item,
/// and not any other state. Violation of this condition is normally only possible via interior
/// mutability, global state, I/O, or unsafe code.
///
/// If purism is violated, internal index computations which depend on the rendered format
/// will become invalid and the picker may panic or return incorrect results. Note that such
/// errors are encapsulated within the picker and will not result in undefined behaviour.
///
/// ## Examples
/// Here is a basic example for how one would implement a renderer for a `DirEntry` from the
/// [ignore](https://docs.rs/ignore/latest/ignore/) crate.
/// ```
/// use std::borrow::Cow;
///
/// use nucleo_picker::Render;
/// use ignore::DirEntry;
///
/// pub struct DirEntryRenderer;
///
/// impl Render<DirEntry> for DirEntryRenderer {
///     type Str<'a> = Cow<'a, str>;
///
///     fn render<'a>(&self, item: &'a DirEntry) -> Self::Str<'a> {
///         item.path().to_string_lossy()
///     }
/// }
/// ```
/// Here is another example showing that a renderer can use internal (immutable) state to customize
/// the rendered format.
/// ```
/// use nucleo_picker::Render;
///
/// pub struct PrefixRenderer {
///     prefix: String,
/// }
///
/// impl<T: AsRef<str>> Render<T> for PrefixRenderer {
///     type Str<'a> = String
///         where T: 'a;
///
///     fn render<'a>(&self, item: &'a T) -> Self::Str<'a> {
///         let mut rendered = String::new();
///         rendered.push_str(&self.prefix);
///         rendered.push_str(item.as_ref());
///         rendered
///     }
/// }
/// ```
///
/// ## Render considerations
/// The picker is capable of correctly displaying most Unicode data. Internally, Unicode width
/// calculations are performed to keep track of the amount of space that it takes on the screen to
/// display a given item.
///
/// The main exeption is control characters which are not newlines (`\n` or `\r\n`). Even visible
/// control characters, such as tabs (`\t`) will cause issues: width calculations will most likely
/// be incorrect since the amount of space a tab occupies depends on its position within the
/// screen.
///
/// It is best to avoid such characters in your rendered format. If you do not have control
/// over the incoming data, the most robust solution is likely to perform substitutions during
/// rendering.
/// ```
/// # use nucleo_picker::Render;
/// use std::borrow::Cow;
///
/// fn renderable(c: char) -> bool {
///     !c.is_control() || c == '\n'
/// }
///
/// struct ControlReplaceRenderer;
///
/// impl<T: AsRef<str>> Render<T> for ControlReplaceRenderer {
///     type Str<'a>
///         = Cow<'a, str>
///     where
///         T: 'a;
///
///     fn render<'a>(&self, item: &'a T) -> Self::Str<'a> {
///         let mut str = Cow::Borrowed(item.as_ref());
///
///         if str.contains(|c| !renderable(c)) {
///             str.to_mut().retain(renderable);
///         }
///
///         str
///     }
/// }
/// ```
///
/// ## Performance considerations
/// In the majority of situations, performance of the [`Render`] implementation is only relevant
/// when sending the items to the picker, and not for generating the match list interactively. In
/// particular, in the majority of situations, [`Render::render`] is called exactly once per item
/// when it is sent to the picker.
///
/// The **only** exception to this rule occurs the value returned by [`Render::render`] contains
/// non-ASCII characters. In this situation, it can happen that *exceptionally slow* [`Render`]
/// implementations will reduce interactivity. A crude rule of thumb is that rendering a single
/// item should take (in the worst case) at most 100μs. For comparison, display formatting a
/// `f64` takes around 100ns.
///
/// 100μs is an extremely large amount of time in the vast majority of situations. If after
/// benchmarking you determine that this is not the case for your [`Render`] implementation,
/// and moreover your [`Render`] implementation outputs (in the majority of cases) non-ASCII
/// Unicode, you can internally cache the render computation (at the cost of increased memory
/// overhead):
/// ```
/// # use nucleo_picker::Render;
/// pub struct Item<D> {
///     data: D,
///     /// the pre-computed rendered version of `data`
///     rendered: String,
/// }
///
/// pub struct ItemRenderer;
///
/// impl<D> Render<Item<D>> for ItemRenderer {
///     type Str<'a>
///         = &'a str
///     where
///         D: 'a;
///
///     fn render<'a>(&self, item: &'a Item<D>) -> Self::Str<'a> {
///         &item.rendered
///     }
/// }
/// ```
pub trait Render<T> {
    /// The string type that `T` is rendered as, most commonly a [`&'a str`](str), a
    /// [`Cow<'a, str>`](std::borrow::Cow), or a [`String`].
    type Str<'a>: AsRef<str>
    where
        T: 'a;

    /// Render the given item as it should appear in the picker. See the
    /// [trait-level docs](Render) for more detail.
    fn render<'a>(&self, item: &'a T) -> Self::Str<'a>;
}

impl<T, R: for<'a> Fn(&'a T) -> Cow<'a, str>> Render<T> for R {
    type Str<'a>
        = Cow<'a, str>
    where
        T: 'a;

    fn render<'a>(&self, item: &'a T) -> Self::Str<'a> {
        self(item)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
/// How to treat a case mismatch between two characters.
pub enum CaseMatching {
    /// Characters never match their case folded version (`a != A`).
    Respect,
    /// Characters always match their case folded version (`a == A`).
    Ignore,
    /// Act like [`Ignore`](CaseMatching::Ignore) if all characters in a pattern atom are
    /// lowercase and like [`Respect`](CaseMatching::Respect) otherwise.
    #[default]
    Smart,
}

impl CaseMatching {
    pub(crate) const fn convert(self) -> NucleoCaseMatching {
        match self {
            Self::Respect => NucleoCaseMatching::Respect,
            Self::Ignore => NucleoCaseMatching::Ignore,
            Self::Smart => NucleoCaseMatching::Smart,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
/// How to handle Unicode Latin normalization.
pub enum Normalization {
    /// Characters never match their normalized version (`a != ä`).
    Never,
    /// Act like [`Never`](Normalization::Never) if any character would need to be normalized, and
    /// otherwise perform normalization (`a == ä` but `ä != a`).
    #[default]
    Smart,
}

impl Normalization {
    pub(crate) const fn convert(self) -> NucleoNormalization {
        match self {
            Self::Never => NucleoNormalization::Never,
            Self::Smart => NucleoNormalization::Smart,
        }
    }
}

/// Specify configuration options for a [`Picker`].
///
/// Initialize with [`new`](PickerOptions::new) or (equivalently) the
/// [`Default`](PickerOptions::default) implementation, specify options, and then convert to a
/// [`Picker`] using the [`picker`](PickerOptions::picker) method.
///
/// ## Example
/// ```
/// use nucleo_picker::{render::StrRenderer, Picker, PickerOptions};
///
/// let picker: Picker<String, _> = PickerOptions::new()
///     .highlight(true)
///     .query("search")
///     .picker(StrRenderer);
/// ```
///
/// ## Sort order settings
///
/// There are three settings which influence the order in which items appear on the screen.
///
/// The [`reversed`](Self::reversed) setting only influences the layout: by default, the query is
/// placed at the bottom of the screen, with the match list rendered bottom-up. If this is set, the query will be placed at the top of the screen, with the match list rendered top-down.
///
/// The [`reverse_items`](Self::reverse_items) and [`sort_results`](Self::sort_results) are used to
/// determine *the order of the items inside the match list*. The order is defined according to the
/// following table. Here, `Index` refers to the order in which the `picker` received the items
/// from the [`Injector`]s. If you use exactly one injector, this is guaranteed to be the same as
/// the insertion order.
///
/// | `sort_results` | `reverse_items` | Sort priority                              |
/// |----------------|-----------------|--------------------------------------------|
/// | `true`         | `false`         | Score (desc) → Length (asc) → Index (asc)  |
/// | `true`         | `true`          | Score (desc) → Length (asc) → Index (desc) |
/// | `false`        | `false`         | Index (asc)                                |
/// | `false`        | `true`          | Index (desc)                               |
pub struct PickerOptions {
    config: nc::Config,
    query: String,
    threads: Option<NonZero<usize>>,
    max_selection_count: Option<NonZero<u32>>,
    interval: Duration,
    match_list_config: MatchListConfig,
    prompt_config: PromptConfig,
    sort_results: bool,
    reverse_items: bool,
}

impl Default for PickerOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl PickerOptions {
    /// Initialize with default configuration.
    ///
    /// Equivalent to the [`Default`] implementation, but as a `const fn`.
    #[must_use]
    #[inline]
    pub const fn new() -> Self {
        Self {
            config: nc::Config::DEFAULT,
            query: String::new(),
            threads: None,
            max_selection_count: None,
            interval: Duration::from_millis(15),
            match_list_config: MatchListConfig::new(),
            prompt_config: PromptConfig::new(),
            sort_results: true,
            reverse_items: false,
        }
    }

    /// Convert into a [`Picker`].
    #[must_use]
    pub fn picker<T: Send + Sync + 'static, R>(self, render: R) -> Picker<T, R> {
        let engine = Nucleo::with_match_list_config(
            self.config.clone(),
            Arc::new(|| {}),
            // nucleo's API is a bit weird here in that it does not accept `NonZero<usize>`
            self.threads
                .or_else(|| {
                    // Reserve two threads:
                    // 1. for populating the matcher
                    // 2. for rendering the terminal UI and handling user input
                    available_parallelism()
                        .ok()
                        .and_then(|it| it.get().checked_sub(2).and_then(NonZero::new))
                })
                .map(NonZero::get),
            1,
            nc::MatchListConfig {
                sort_results: self.sort_results,
                reverse_items: self.reverse_items,
            },
        );

        let reversed = self.match_list_config.reversed;

        let mut match_list =
            MatchList::new(self.match_list_config, self.config, engine, render.into());

        let mut prompt = Prompt::new(self.prompt_config);

        // set the prompt
        match_list.reparse(&self.query);
        prompt.set_query(self.query);

        Picker {
            match_list,
            prompt,
            interval: self.interval,
            max_selection_count: self.max_selection_count,
            reversed,
            restart_notifier: None,
        }
    }

    /// Set 'reversed' layout.
    ///
    /// Option `false` (default) will put the prompt at the bottom and render items in ascending
    /// order. Option `true` will put the prompt at the top and render items in descending order.
    #[must_use]
    #[inline]
    pub const fn reversed(mut self, reversed: bool) -> Self {
        self.match_list_config.reversed = reversed;
        self
    }

    /// Reverse the item insert order.
    ///
    /// This changes the index tie-break method to prefer later indices rather than earlier
    /// indices. This option is typically used with [`sort_results`](Self::sort_results) set
    /// to `false`, in which case the newest items sent to the picker will be placed
    /// first, rather than last.
    ///
    /// The default is `false`.
    #[must_use]
    #[inline]
    pub const fn reverse_items(mut self, reversed: bool) -> Self {
        self.reverse_items = reversed;
        self
    }

    /// Whether or not to sort matching items by score.
    ///
    /// This option is useful when you just want to filter items, but preserve the original order.
    /// By default, the oldest items will appear at the beginning and the newest items will appear at the end.
    /// This can be swapped by setting [`reverse_items`](Self::reverse_items) to `true`.
    #[must_use]
    #[inline]
    pub const fn sort_results(mut self, sort: bool) -> Self {
        self.sort_results = sort;
        self
    }

    /// The maximum number of items that can be selected in the picker.
    ///
    /// If `None`, no bound is applied; otherwise, use the provided bound. This is a `u32` since
    /// the picker cannot hold more than [`u32::MAX`] items.
    ///
    /// This bound is only relevant when allowing [multiple selections](Picker#multiple-selections)
    /// and has no impact on single selection mode. The returned [`Selection`] will contain at
    /// most `maximum` items. The picker will not allow the selection of additional items if the maximum
    /// is reached.
    ///
    /// The default is `None`.
    #[must_use]
    #[inline]
    pub const fn max_selection_count(mut self, maximum: Option<NonZero<u32>>) -> Self {
        self.max_selection_count = maximum;
        self
    }

    /// Set how long each frame should last.
    ///
    /// This is the reciprocal of the refresh rate. The default value is
    /// `Duration::from_millis(15)`, which corresponds to a refresh rate of approximately 67 frames
    /// per second. It is not recommended to set this to a value less than 8ms (approximately 125
    /// frames per second).
    #[must_use]
    #[inline]
    pub const fn frame_interval(mut self, interval: Duration) -> Self {
        self.interval = interval;
        self
    }

    /// Set the number of threads used by the internal matching engine.
    ///
    /// If `None` (default), use a heuristic choice based on the amount of available
    /// parallelism along with other factors.
    #[must_use]
    #[inline]
    pub const fn threads(mut self, threads: Option<NonZero<usize>>) -> Self {
        self.threads = threads;
        self
    }

    /// Set the internal match engine configuration (default to [`nucleo::Config::DEFAULT`]).
    #[must_use]
    #[inline]
    #[deprecated(
        since = "0.10.0",
        note = "Use native methods `prefer_prefix` and `match_paths`. The `normalize` and `ignore_case` settings are never used; use `normalization` and `case_matching` instead."
    )]
    pub fn config(mut self, config: nc::Config) -> Self {
        self.config = config;
        self
    }

    /// How to perform Unicode normalization (defaults to [`Normalization::Smart`]).
    #[must_use]
    #[inline]
    pub const fn normalization(mut self, normalization: Normalization) -> Self {
        self.match_list_config.normalization = normalization.convert();
        self
    }

    /// How to treat case mismatch (defaults to [`CaseMatching::Smart`]).
    #[must_use]
    #[inline]
    pub const fn case_matching(mut self, case_matching: CaseMatching) -> Self {
        self.match_list_config.case_matching = case_matching.convert();
        self
    }

    /// Enable score bonuses appropriate for matching file paths.
    #[must_use]
    #[inline]
    pub const fn match_paths(mut self) -> Self {
        self.config = self.config.match_paths();
        self
    }

    /// Whether to provide a bonus to matches by their distance from the start of the item.
    ///
    /// This is disabled by default and only recommended for autocompletion use-cases, where the expectation is that the user is typing the entire match.
    #[must_use]
    #[inline]
    pub const fn prefer_prefix(mut self, prefer_prefix: bool) -> Self {
        self.config.prefer_prefix = prefer_prefix;
        self
    }

    /// Whether or not to highlight matches (default to `true`).
    #[must_use]
    #[inline]
    pub const fn highlight(mut self, highlight: bool) -> Self {
        self.match_list_config.highlight = highlight;
        self
    }

    /// How much space to leave when rendering match highlighting (default to `3`).
    #[must_use]
    #[inline]
    pub const fn highlight_padding(mut self, size: u16) -> Self {
        self.match_list_config.highlight_padding = size;
        self
    }

    /// How much space to leave around the selection when scrolling (default to `3`).
    #[must_use]
    #[inline]
    pub const fn scroll_padding(mut self, size: u16) -> Self {
        self.match_list_config.scroll_padding = size;
        self
    }

    /// How much space to leave around the cursor (default to `2`).
    #[must_use]
    #[inline]
    pub const fn prompt_padding(mut self, size: u16) -> Self {
        self.prompt_config.padding = size;
        self
    }

    /// Provide an initial query string for the prompt (default to `""`).
    #[must_use]
    #[inline]
    pub fn query<Q: Into<String>>(mut self, query: Q) -> Self {
        self.query = query.into();
        self
    }
}

/// A fuzzy matching interactive item picker.
///
/// The parameter `T` is the item type and the parameter `R` is the [renderer](Render), which
/// describes how to represent `T` in the match list.
///
/// Initialize a picker with [`Picker::new`], or with custom configuration using
/// [`PickerOptions`], and add elements to the picker using an [`Injector`] returned
/// by the [`Picker::injector`] method.
/// ```
/// use nucleo_picker::{render::StrRenderer, Picker};
///
/// // Initialize a picker using default settings, with item type `String`
/// let picker: Picker<String, _> = Picker::new(StrRenderer);
/// ```
///
/// See also the [usage
/// examples](https://github.com/autobib/nucleo-picker/tree/master/examples).
///
/// ## Picker variants
///
/// The picker can be run in a number of different modes.
///
/// 1. The simplest (and most common) method is to use [`Picker::pick`].
/// 2. If you wish to customize keybindings, use [`Picker::pick_with_keybind`].
/// 3. If you wish to customize all IO to the picker, use [`Picker::pick_with_io`].
///
/// These methods return `Option<&T>` as the return type, where `None` indicates that no items were
/// selected.
///
/// ### Multiple selections
///
/// If you wish to permit the user to make multiple selections, use one of the similarly named
/// methods:
///
/// 1. [`Picker::pick_multi`]
/// 2. [`Picker::pick_multi_with_keybind`]
/// 3. [`Picker::pick_multi_with_io`]
///
/// These methods are analogous to their single-selection variants, except additional items can be
/// queued with the [`MatchListEvent::ToggleDown`](crate::event::MatchListEvent::ToggleDown) and
/// [`MatchListEvent::ToggleUp`](crate::event::MatchListEvent::ToggleUp) events. The [default
/// keybindings](keybind_default) bind these to `⇥` and `shift + ⇥` respectively. In this case, an
/// [`Event::Select`] is handled slightly differently: if there are no queued selections, this
/// picks the highlighted item, but if there are queued selections, then only the queued selections
/// are returned.
///
/// The selected items are returned as a [`Selection`], which is empty if picker exited with
/// [`Event::Quit`] (or [`Event::QuitPromptEmpty`]), and non-empty if not.
///
/// ## A note on memory usage
/// Initializing a picker is a relatively expensive operation since the internal match engine uses
/// an arena-based memory approach to minimize allocator costs, and this memory is initialized when
/// the picker is created.
///
/// To re-use the picker without additional start-up costs, use the [`Picker::restart`] method.
///
/// # Example
/// Run the picker on [`Stdout`](std::io::Stdout) with no interactivity checks, and quitting
/// gracefully on `ctrl + c`.
/// ```no_run
#[doc = include_str!("../examples/custom_io.rs")]
/// ```
pub struct Picker<T: Send + Sync + 'static, R> {
    match_list: MatchList<T, R>,
    max_selection_count: Option<NonZero<u32>>,
    prompt: Prompt,
    interval: Duration,
    reversed: bool,
    restart_notifier: Option<Notifier<Injector<T, R>>>,
}

impl<T: Send + Sync + 'static, R: Render<T>> Extend<T> for Picker<T, R> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let injector = self.injector();
        for it in iter {
            injector.push(it);
        }
    }
}

impl<T: Send + Sync + 'static, R> Picker<T, R> {
    /// Initialize a new picker with default configuration and the provided renderer.
    #[must_use]
    pub fn new(render: R) -> Self
    where
        R: Render<T>,
    {
        PickerOptions::default().picker(render)
    }

    /// Update the default query string. This is mainly useful for modifying the query string
    /// before re-using the [`Picker`].
    ///
    /// See the [`PickerOptions::query`] method to set the query during initialization, and
    /// [`PromptEvent::Reset`](event::PromptEvent::Reset) to reset the query during interactive
    /// use.
    #[inline]
    pub fn update_query<Q: Into<String>>(&mut self, query: Q) {
        self.prompt.set_query(query);
        self.match_list.reparse(self.prompt.contents());
    }

    /// Returns the contents of the query string internal to the picker.
    ///
    /// If called after running `Picker::pick`, this will contain the contents of the query string
    /// at the moment that the item was selected or the picker quit.
    #[must_use]
    pub fn query(&self) -> &str {
        self.prompt.contents()
    }

    /// Returns an [`Observer`] containing up-to-date [`Injector`]s for this picker. For example,
    /// this is the channel to which new injectors will be sent when the picker processes a
    /// [restart event](Event::Restart). See the [`Event`] documentation for more detail.
    ///
    /// Restart events are not generated by this library. You only need this channel if you
    /// generate restart events in your own code.
    ///
    /// If `with_injector` is `true`, the channel is intialized with an injector currently valid
    /// for the picker on creation.
    #[must_use]
    pub fn injector_observer(&mut self, with_injector: bool) -> Observer<Injector<T, R>> {
        let (notifier, observer) = if with_injector {
            observer::occupied_channel(self.injector())
        } else {
            observer::channel()
        };
        self.restart_notifier = Some(notifier);
        observer
    }

    /// Update the internal nucleo configuration.
    #[inline]
    pub fn update_config(&mut self, config: nc::Config) {
        self.match_list.update_nucleo_config(config);
    }

    /// Restart the match engine, disconnecting all active injectors and clearing the existing
    /// search query.
    ///
    /// All items are removed immediately. Existing injectors will continue to function but the
    /// items will no longer be received by this instance. The old items will only be dropped when
    /// all injectors are dropped.
    ///
    /// This method is mainly useful for re-using the picker for multiple matches since the
    /// internal memory buffers are preserved. To restart the picker during interactive use, see
    /// the [`Event`] documentation or the [restart
    /// example](https://github.com/autobib/nucleo-picker/blob/master/examples/restart.rs).
    pub fn restart(&mut self) {
        self.match_list.restart();
        self.update_query("");
    }

    /// Restart the match engine, disconnecting all active injectors and replacing the internal
    /// renderer.
    ///
    /// The provided [`Render`] implementation must be the same type as the one originally
    /// provided; this is most useful for stateful renderers.
    ///
    /// See [`Picker::restart`] for more detail. Note that method *does not* clear the query.
    pub fn reset_renderer(&mut self, render: R) {
        self.match_list.reset_renderer(render);
    }

    /// Get an [`Injector`] to send items to the picker.
    #[must_use]
    pub fn injector(&self) -> Injector<T, R> {
        self.match_list.injector()
    }

    /// A convenience method to add a batch of items directly to the picker.
    ///
    /// The number of items in the iterator must be known exactly. This is a convenience wrapper
    /// around [`Injector::extend_exact`].
    pub fn extend_exact<I>(&self, iter: I)
    where
        R: Render<T>,
        I: IntoIterator<Item = T>,
        <I as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        self.injector().extend_exact(iter);
    }

    /// A convenience method to obtain the rendered version of an item as it would appear in the
    /// picker.
    ///
    /// This is the same as calling [`Render::render`] on the [`Render`] implementation internal
    /// to the picker.
    #[inline]
    pub fn render<'a>(&self, item: &'a T) -> <R as Render<T>>::Str<'a>
    where
        R: Render<T>,
    {
        self.match_list.render(item)
    }

    /// Open the interactive picker prompt and return the picked item, if any.
    ///
    /// ## Stderr lock
    /// The picker prompt is rendered in an alternate screen using the `stderr` file handle. In
    /// order to prevent screen corruption, a lock is acquired to `stderr`; see
    /// [`StderrLock`](std::io::StderrLock) for more detail.
    ///
    /// In particular, while the picker is interactive, any other thread which attempts to write to
    /// stderr will block. Note that `stdin` and `stdout` will remain fully interactive.
    ///
    /// ## IO customization
    ///
    /// To further customize the IO behaviour of the picker, such as to provide your own writer
    /// (for instance to write to [`Stdout`](std::io::Stdout) instead) or use custom keybindings,
    /// see the [`pick_with_io`](Self::pick_with_io)  and
    /// [`pick_with_keybind`](Self::pick_with_keybind) methods.
    ///
    /// # Errors
    /// Underlying IO errors from the standard library or [`crossterm`] will be propagated with the
    /// [`PickError::IO`] variant.
    ///
    /// This method also fails with:
    ///
    /// 1. [`PickError::NotInteractive`] if stderr is not interactive.
    /// 2. [`PickError::UserInterrupted`] if the user presses `ctrl + c`.
    ///
    /// This method will **never** return [`PickError::Disconnected`].
    #[inline]
    pub fn pick(&mut self) -> Result<Option<&T>, PickError>
    where
        R: Render<T>,
    {
        self.pick_with_keybind(keybind_default)
    }

    /// Open the interactive picker prompt and return the picked items, if any.
    ///
    /// This method permits the user to select multiple items, but is otherwise identical to [`pick`](Self::pick). See those docs as well as the
    /// [docs on multiple selections](Picker#multiple-selections) for more detail.
    #[inline]
    pub fn pick_multi(&mut self) -> Result<Selection<'_, T>, PickError>
    where
        R: Render<T>,
    {
        self.pick_multi_with_keybind(keybind_default)
    }

    /// Open the interactive picker prompt and return the picked item, if any. Uses the provided
    /// keybindings for the interactive picker.
    ///
    /// The picker prompt is rendered in an alternate screen using the `stderr` file handle. See
    /// the [`pick`](Self::pick) method for more detail.
    ///
    /// To further customize event generation, see the [`pick_with_io`](Self::pick_with_io) method.
    /// The [`pick`](Self::pick) method is internally a call to this method with keybindings
    /// provided by [`keybind_default`].
    ///
    /// # Errors
    ///
    /// Underlying IO errors from the standard library or [`crossterm`] will be propagated with the
    /// [`PickError::IO`] variant.
    ///
    /// This method also fails with:
    ///
    /// 1. [`PickError::NotInteractive`] if stderr is not interactive.
    /// 2. [`PickError::UserInterrupted`] if a keybinding results in a [`Event::UserInterrupt`],
    ///
    /// This method will **never** return [`PickError::Disconnected`].
    #[inline]
    pub fn pick_with_keybind<F: FnMut(KeyEvent) -> Option<Event>>(
        &mut self,
        keybind: F,
    ) -> Result<Option<&T>, PickError>
    where
        R: Render<T>,
    {
        let stderr = io::stderr().lock();
        if stderr.is_terminal() {
            self.pick_with_io(StdinReader::new(keybind), &mut BufWriter::new(stderr))
        } else {
            Err(PickError::NotInteractive)
        }
    }

    /// Open the interactive picker prompt and return the picked items, if any. Uses the provided
    /// keybindings for the interactive picker.
    ///
    /// This method permits the user to select multiple items, but is otherwise identical to [`pick_with_keybind`](Self::pick_with_keybind). See those docs as well as the
    /// [docs on multiple selections](Picker#multiple-selections) for more detail.
    #[inline]
    pub fn pick_multi_with_keybind<F: FnMut(KeyEvent) -> Option<Event>>(
        &mut self,
        keybind: F,
    ) -> Result<Selection<'_, T>, PickError>
    where
        R: Render<T>,
    {
        let stderr = io::stderr().lock();
        if stderr.is_terminal() {
            self.pick_multi_with_io(StdinReader::new(keybind), &mut BufWriter::new(stderr))
        } else {
            Err(PickError::NotInteractive)
        }
    }

    /// Run the picker interactively with a custom event source and writer.
    ///
    /// The picker is rendered using the given writer. In most situations, you want to check that
    /// the writer is interactive using, for instance, [`IsTerminal`]. The picker reads
    /// events from the [`EventSource`] to update the screen. See the docs for [`EventSource`]
    /// for more detail.
    ///
    /// # Errors
    /// Underlying IO errors from the standard library or [`crossterm`] will be propagated with the
    /// [`PickError::IO`] variant.
    ///
    /// Whether or not this fails with another [`PickError`] variant depends on the [`EventSource`]
    /// implementation:
    ///
    /// 1. If [`EventSource::recv_timeout`] fails with a [`RecvError::Disconnected`], the error
    ///    returned will be [`PickError::Disconnected`].
    /// 2. The error will be [`PickError::UserInterrupted`] if the [`Picker`] receives an
    ///    [`Event::UserInterrupt`].
    /// 3. The error will be [`PickError::Aborted`] if the [`Picker`] receives an
    ///    [`Event::Abort`].
    ///
    /// This method will **never** return [`PickError::NotInteractive`] since interactivity checks
    /// are not done.
    pub fn pick_with_io<E, W>(
        &mut self,
        event_source: E,
        writer: &mut W,
    ) -> Result<Option<&T>, PickError<<E as EventSource>::AbortErr>>
    where
        R: Render<T>,
        E: EventSource,
        W: io::Write,
    {
        self.pick_impl::<_, _, ()>(event_source, writer)
    }

    /// Run the picker interactively with a custom event source and writer, allowing the user to
    /// select multiple items.
    ///
    /// This is otherwise identical to [`pick_with_io`](Self::pick_with_io); see those docs as well
    /// as the [docs on multiple selections](Picker#multiple-selections) for more detail.
    pub fn pick_multi_with_io<E, W>(
        &mut self,
        event_source: E,
        writer: &mut W,
    ) -> Result<Selection<'_, T>, PickError<<E as EventSource>::AbortErr>>
    where
        R: Render<T>,
        E: EventSource,
        W: io::Write,
    {
        self.pick_impl::<_, _, SelectedIndices>(event_source, writer)
    }

    /// Initialize the alternate screen.
    #[inline]
    fn init_screen<W: Write>(writer: &mut W) -> io::Result<()> {
        enable_raw_mode()?;
        execute!(writer, EnterAlternateScreen, EnableBracketedPaste)?;
        Ok(())
    }

    /// Cleanup the alternate screen when finished.
    #[inline]
    fn cleanup_screen<W: Write>(writer: &mut W) -> io::Result<()> {
        disable_raw_mode()?;
        execute!(writer, DisableBracketedPaste, LeaveAlternateScreen)?;
        Ok(())
    }

    /// Render the frame, specifying which parts of the frame need to be re-drawn.
    #[inline]
    fn render_frame<W: Write, Q: Queued>(
        &mut self,
        writer: &mut W,
        redraw_prompt: bool,
        redraw_match_list: bool,
        queued_items: &Q,
    ) -> io::Result<()>
    where
        R: Render<T>,
    {
        let (width, height) = size()?;

        let (prompt_row, match_list_row) = if self.reversed {
            (0, 1)
        } else {
            (height - 1, 0)
        };

        if width >= 1 && (redraw_prompt || redraw_match_list) {
            writer.execute(BeginSynchronizedUpdate)?;

            if redraw_match_list && height >= 2 {
                writer.queue(MoveTo(0, match_list_row))?;

                self.match_list
                    .draw(width, height - 1, writer, |idx| queued_items.is_queued(idx))?;
            }

            if redraw_prompt && height >= 1 {
                writer.queue(MoveTo(0, prompt_row))?;

                self.prompt.draw(width, 1, writer)?;
            }

            writer.queue(MoveTo(self.prompt.screen_offset() + 2, prompt_row))?;

            // flush to terminal
            writer.flush()?;
            writer.execute(EndSynchronizedUpdate)?;
        };

        Ok(())
    }

    fn pick_impl<E, W, Q: Queued>(
        &mut self,
        mut event_source: E,
        writer: &mut W,
    ) -> Result<Q::Output<'_, T>, PickError<<E as EventSource>::AbortErr>>
    where
        R: Render<T>,
        E: EventSource,
        W: io::Write,
    {
        // set panic hook in case the `Render` implementation panics
        let original_hook = take_hook();
        set_hook(Box::new(move |panic_info| {
            // intentionally ignore errors here since we're already panicking
            let _ = Self::cleanup_screen(&mut io::stderr());
            original_hook(panic_info);
        }));

        let mut queued_items = Q::init(self.max_selection_count);

        Self::init_screen(writer)?;

        let mut frame_start = Instant::now();

        // render the first frame
        self.match_list.update(5);
        self.render_frame(writer, true, true, &queued_items)?;

        let mut redraw_prompt = false;
        let mut redraw_match_list = false;

        let selection = 'selection: loop {
            let mut lazy_match_list = LazyMatchList::new(&mut self.match_list, &mut queued_items);
            let mut lazy_prompt = LazyPrompt::new(&mut self.prompt);

            // process new events, but do not exceed the frame interval
            'event: loop {
                match event_source.recv_timeout(frame_start + self.interval - Instant::now()) {
                    Ok(event) => match event {
                        Event::Prompt(prompt_event) => {
                            lazy_prompt.handle(prompt_event);
                        }
                        Event::MatchList(match_list_event) => {
                            lazy_match_list.handle(match_list_event);
                        }
                        Event::Redraw => {
                            redraw_prompt = true;
                            redraw_match_list = true;
                        }
                        Event::Quit => {
                            break 'selection Ok(self.match_list.select_none(queued_items));
                        }
                        Event::QuitPromptEmpty => {
                            if lazy_prompt.is_empty() {
                                break 'selection Ok(self.match_list.select_none(queued_items));
                            }
                        }
                        Event::Select => {
                            if lazy_match_list.has_queued_items() {
                                break 'selection Ok(self.match_list.select_queued(queued_items));
                            }

                            if let Some(n) = lazy_match_list.selection() {
                                break 'selection Ok(self.match_list.select_one(queued_items, n));
                            }
                        }
                        Event::Restart => match self.restart_notifier {
                            Some(ref notifier) => {
                                if notifier.push(lazy_match_list.restart()).is_err() {
                                    break 'selection Err(PickError::Disconnected);
                                } else {
                                    redraw_match_list = true;
                                }
                            }
                            None => break 'selection Err(PickError::Disconnected),
                        },
                        Event::UserInterrupt => {
                            break 'selection Err(PickError::UserInterrupted);
                        }
                        Event::Abort(err) => {
                            break 'selection Err(PickError::Aborted(err));
                        }
                    },
                    Err(RecvError::Timeout) => break 'event,
                    Err(RecvError::Disconnected) => {
                        break 'selection Err(PickError::Disconnected);
                    }
                    Err(RecvError::IO(io_err)) => break 'selection Err(PickError::IO(io_err)),
                }
            }

            // we have to set 'frame_start' immediately after processing events, so that the
            // render time is also included
            frame_start = Instant::now();

            // clear out any buffered events
            let prompt_status = lazy_prompt.finish();
            let match_list_status = lazy_match_list.finish();

            // update draw status
            redraw_prompt |= prompt_status.needs_redraw();
            redraw_match_list |= match_list_status.needs_redraw();

            // check if the prompt changed: if so, reparse the match list
            if prompt_status.contents_changed {
                self.match_list.reparse(self.prompt.contents());
                redraw_match_list = true;
            }

            // update the item list
            redraw_match_list |= self
                .match_list
                .update(2 * self.interval.as_millis() as u64 / 3)
                .needs_redraw();

            // render the frame
            self.render_frame(writer, redraw_prompt, redraw_match_list, &queued_items)?;

            // reset the redraw markers
            redraw_prompt = false;
            redraw_match_list = false;
        };

        Self::cleanup_screen(writer)?;
        selection
    }
}