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
use std::{any::Any, sync::Arc};

use gpui::{
    AnyView, AppContext, EventEmitter, Subscription, Task, View, ViewContext, WeakView,
    WindowContext,
};
use project2::search::SearchQuery;

use crate::{
    item::{Item, WeakItemHandle},
    ItemHandle,
};

#[derive(Debug)]
pub enum SearchEvent {
    MatchesInvalidated,
    ActiveMatchChanged,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Direction {
    Prev,
    Next,
}

#[derive(Clone, Copy, Debug, Default)]
pub struct SearchOptions {
    pub case: bool,
    pub word: bool,
    pub regex: bool,
    /// Specifies whether the item supports search & replace.
    pub replacement: bool,
}

pub trait SearchableItem: Item + EventEmitter<SearchEvent> {
    type Match: Any + Sync + Send + Clone;

    fn supported_options() -> SearchOptions {
        SearchOptions {
            case: true,
            word: true,
            regex: true,
            replacement: true,
        }
    }

    fn clear_matches(&mut self, cx: &mut ViewContext<Self>);
    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>);
    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String;
    fn activate_match(
        &mut self,
        index: usize,
        matches: Vec<Self::Match>,
        cx: &mut ViewContext<Self>,
    );
    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>);
    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>);
    fn match_index_for_direction(
        &mut self,
        matches: &Vec<Self::Match>,
        current_index: usize,
        direction: Direction,
        count: usize,
        _: &mut ViewContext<Self>,
    ) -> usize {
        match direction {
            Direction::Prev => {
                let count = count % matches.len();
                if current_index >= count {
                    current_index - count
                } else {
                    matches.len() - (count - current_index)
                }
            }
            Direction::Next => (current_index + count) % matches.len(),
        }
    }
    fn find_matches(
        &mut self,
        query: Arc<SearchQuery>,
        cx: &mut ViewContext<Self>,
    ) -> Task<Vec<Self::Match>>;
    fn active_match_index(
        &mut self,
        matches: Vec<Self::Match>,
        cx: &mut ViewContext<Self>,
    ) -> Option<usize>;
}

pub trait SearchableItemHandle: ItemHandle {
    fn downgrade(&self) -> Box<dyn WeakSearchableItemHandle>;
    fn boxed_clone(&self) -> Box<dyn SearchableItemHandle>;
    fn supported_options(&self) -> SearchOptions;
    fn subscribe_to_search_events(
        &self,
        cx: &mut WindowContext,
        handler: Box<dyn Fn(&SearchEvent, &mut WindowContext) + Send>,
    ) -> Subscription;
    fn clear_matches(&self, cx: &mut WindowContext);
    fn update_matches(&self, matches: &Vec<Box<dyn Any + Send>>, cx: &mut WindowContext);
    fn query_suggestion(&self, cx: &mut WindowContext) -> String;
    fn activate_match(
        &self,
        index: usize,
        matches: &Vec<Box<dyn Any + Send>>,
        cx: &mut WindowContext,
    );
    fn select_matches(&self, matches: &Vec<Box<dyn Any + Send>>, cx: &mut WindowContext);
    fn replace(&self, _: &Box<dyn Any + Send>, _: &SearchQuery, _: &mut WindowContext);
    fn match_index_for_direction(
        &self,
        matches: &Vec<Box<dyn Any + Send>>,
        current_index: usize,
        direction: Direction,
        count: usize,
        cx: &mut WindowContext,
    ) -> usize;
    fn find_matches(
        &self,
        query: Arc<SearchQuery>,
        cx: &mut WindowContext,
    ) -> Task<Vec<Box<dyn Any + Send>>>;
    fn active_match_index(
        &self,
        matches: &Vec<Box<dyn Any + Send>>,
        cx: &mut WindowContext,
    ) -> Option<usize>;
}

// todo!("here is where we need to use AnyWeakView");
impl<T: SearchableItem> SearchableItemHandle for View<T> {
    fn downgrade(&self) -> Box<dyn WeakSearchableItemHandle> {
        Box::new(self.downgrade())
    }

    fn boxed_clone(&self) -> Box<dyn SearchableItemHandle> {
        Box::new(self.clone())
    }

    fn supported_options(&self) -> SearchOptions {
        T::supported_options()
    }

    fn subscribe_to_search_events(
        &self,
        cx: &mut WindowContext,
        handler: Box<dyn Fn(&SearchEvent, &mut WindowContext) + Send>,
    ) -> Subscription {
        cx.subscribe(self, move |_, event: &SearchEvent, cx| handler(event, cx))
    }

    fn clear_matches(&self, cx: &mut WindowContext) {
        self.update(cx, |this, cx| this.clear_matches(cx));
    }
    fn update_matches(&self, matches: &Vec<Box<dyn Any + Send>>, cx: &mut WindowContext) {
        let matches = downcast_matches(matches);
        self.update(cx, |this, cx| this.update_matches(matches, cx));
    }
    fn query_suggestion(&self, cx: &mut WindowContext) -> String {
        self.update(cx, |this, cx| this.query_suggestion(cx))
    }
    fn activate_match(
        &self,
        index: usize,
        matches: &Vec<Box<dyn Any + Send>>,
        cx: &mut WindowContext,
    ) {
        let matches = downcast_matches(matches);
        self.update(cx, |this, cx| this.activate_match(index, matches, cx));
    }

    fn select_matches(&self, matches: &Vec<Box<dyn Any + Send>>, cx: &mut WindowContext) {
        let matches = downcast_matches(matches);
        self.update(cx, |this, cx| this.select_matches(matches, cx));
    }

    fn match_index_for_direction(
        &self,
        matches: &Vec<Box<dyn Any + Send>>,
        current_index: usize,
        direction: Direction,
        count: usize,
        cx: &mut WindowContext,
    ) -> usize {
        let matches = downcast_matches(matches);
        self.update(cx, |this, cx| {
            this.match_index_for_direction(&matches, current_index, direction, count, cx)
        })
    }
    fn find_matches(
        &self,
        query: Arc<SearchQuery>,
        cx: &mut WindowContext,
    ) -> Task<Vec<Box<dyn Any + Send>>> {
        let matches = self.update(cx, |this, cx| this.find_matches(query, cx));
        cx.spawn(|cx| async {
            let matches = matches.await;
            matches
                .into_iter()
                .map::<Box<dyn Any + Send>, _>(|range| Box::new(range))
                .collect()
        })
    }
    fn active_match_index(
        &self,
        matches: &Vec<Box<dyn Any + Send>>,
        cx: &mut WindowContext,
    ) -> Option<usize> {
        let matches = downcast_matches(matches);
        self.update(cx, |this, cx| this.active_match_index(matches, cx))
    }

    fn replace(&self, matches: &Box<dyn Any + Send>, query: &SearchQuery, cx: &mut WindowContext) {
        let matches = matches.downcast_ref().unwrap();
        self.update(cx, |this, cx| this.replace(matches, query, cx))
    }
}

fn downcast_matches<T: Any + Clone>(matches: &Vec<Box<dyn Any + Send>>) -> Vec<T> {
    matches
        .iter()
        .map(|range| range.downcast_ref::<T>().cloned())
        .collect::<Option<Vec<_>>>()
        .expect(
            "SearchableItemHandle function called with vec of matches of a different type than expected",
        )
}

impl From<Box<dyn SearchableItemHandle>> for AnyView {
    fn from(this: Box<dyn SearchableItemHandle>) -> Self {
        this.to_any().clone()
    }
}

impl From<&Box<dyn SearchableItemHandle>> for AnyView {
    fn from(this: &Box<dyn SearchableItemHandle>) -> Self {
        this.to_any().clone()
    }
}

impl PartialEq for Box<dyn SearchableItemHandle> {
    fn eq(&self, other: &Self) -> bool {
        self.item_id() == other.item_id()
    }
}

impl Eq for Box<dyn SearchableItemHandle> {}

pub trait WeakSearchableItemHandle: WeakItemHandle {
    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;

    // fn into_any(self) -> AnyWeakView;
}

impl<T: SearchableItem> WeakSearchableItemHandle for WeakView<T> {
    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
        Some(Box::new(self.upgrade()?))
    }

    // fn into_any(self) -> AnyView {
    //     self.into_any()
    // }
}

impl PartialEq for Box<dyn WeakSearchableItemHandle> {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl Eq for Box<dyn WeakSearchableItemHandle> {}

impl std::hash::Hash for Box<dyn WeakSearchableItemHandle> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id().hash(state)
    }
}