context_strip.rs

  1use std::rc::Rc;
  2
  3use collections::HashSet;
  4use editor::Editor;
  5use file_icons::FileIcons;
  6use gpui::{
  7    AppContext, Bounds, DismissEvent, EventEmitter, FocusHandle, FocusableView, Model,
  8    Subscription, View, WeakModel, WeakView,
  9};
 10use itertools::Itertools;
 11use language::Buffer;
 12use ui::{prelude::*, KeyBinding, PopoverMenu, PopoverMenuHandle, Tooltip};
 13use workspace::{notifications::NotifyResultExt, Workspace};
 14
 15use crate::context::ContextKind;
 16use crate::context_picker::{ConfirmBehavior, ContextPicker};
 17use crate::context_store::ContextStore;
 18use crate::thread::Thread;
 19use crate::thread_store::ThreadStore;
 20use crate::ui::ContextPill;
 21use crate::{
 22    AcceptSuggestedContext, AssistantPanel, FocusDown, FocusLeft, FocusRight, FocusUp,
 23    RemoveAllContext, RemoveFocusedContext, ToggleContextPicker,
 24};
 25
 26pub struct ContextStrip {
 27    context_store: Model<ContextStore>,
 28    pub context_picker: View<ContextPicker>,
 29    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 30    focus_handle: FocusHandle,
 31    suggest_context_kind: SuggestContextKind,
 32    workspace: WeakView<Workspace>,
 33    _subscriptions: Vec<Subscription>,
 34    focused_index: Option<usize>,
 35    children_bounds: Option<Vec<Bounds<Pixels>>>,
 36}
 37
 38impl ContextStrip {
 39    pub fn new(
 40        context_store: Model<ContextStore>,
 41        workspace: WeakView<Workspace>,
 42        thread_store: Option<WeakModel<ThreadStore>>,
 43        context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 44        suggest_context_kind: SuggestContextKind,
 45        cx: &mut ViewContext<Self>,
 46    ) -> Self {
 47        let context_picker = cx.new_view(|cx| {
 48            ContextPicker::new(
 49                workspace.clone(),
 50                thread_store.clone(),
 51                context_store.downgrade(),
 52                ConfirmBehavior::KeepOpen,
 53                cx,
 54            )
 55        });
 56
 57        let focus_handle = cx.focus_handle();
 58
 59        let subscriptions = vec![
 60            cx.subscribe(&context_picker, Self::handle_context_picker_event),
 61            cx.on_focus(&focus_handle, Self::handle_focus),
 62            cx.on_blur(&focus_handle, Self::handle_blur),
 63        ];
 64
 65        Self {
 66            context_store: context_store.clone(),
 67            context_picker,
 68            context_picker_menu_handle,
 69            focus_handle,
 70            suggest_context_kind,
 71            workspace,
 72            _subscriptions: subscriptions,
 73            focused_index: None,
 74            children_bounds: None,
 75        }
 76    }
 77
 78    fn suggested_context(&self, cx: &ViewContext<Self>) -> Option<SuggestedContext> {
 79        match self.suggest_context_kind {
 80            SuggestContextKind::File => self.suggested_file(cx),
 81            SuggestContextKind::Thread => self.suggested_thread(cx),
 82        }
 83    }
 84
 85    fn suggested_file(&self, cx: &ViewContext<Self>) -> Option<SuggestedContext> {
 86        let workspace = self.workspace.upgrade()?;
 87        let active_item = workspace.read(cx).active_item(cx)?;
 88
 89        let editor = active_item.to_any().downcast::<Editor>().ok()?.read(cx);
 90        let active_buffer_model = editor.buffer().read(cx).as_singleton()?;
 91        let active_buffer = active_buffer_model.read(cx);
 92
 93        let path = active_buffer.file()?.path();
 94
 95        if self
 96            .context_store
 97            .read(cx)
 98            .will_include_buffer(active_buffer.remote_id(), path)
 99            .is_some()
100        {
101            return None;
102        }
103
104        let name = match path.file_name() {
105            Some(name) => name.to_string_lossy().into_owned().into(),
106            None => path.to_string_lossy().into_owned().into(),
107        };
108
109        let icon_path = FileIcons::get_icon(path, cx);
110
111        Some(SuggestedContext::File {
112            name,
113            buffer: active_buffer_model.downgrade(),
114            icon_path,
115        })
116    }
117
118    fn suggested_thread(&self, cx: &ViewContext<Self>) -> Option<SuggestedContext> {
119        let workspace = self.workspace.upgrade()?;
120        let active_thread = workspace
121            .read(cx)
122            .panel::<AssistantPanel>(cx)?
123            .read(cx)
124            .active_thread(cx);
125        let weak_active_thread = active_thread.downgrade();
126
127        let active_thread = active_thread.read(cx);
128
129        if self
130            .context_store
131            .read(cx)
132            .includes_thread(active_thread.id())
133            .is_some()
134        {
135            return None;
136        }
137
138        Some(SuggestedContext::Thread {
139            name: active_thread.summary_or_default(),
140            thread: weak_active_thread,
141        })
142    }
143
144    fn handle_context_picker_event(
145        &mut self,
146        _picker: View<ContextPicker>,
147        _event: &DismissEvent,
148        cx: &mut ViewContext<Self>,
149    ) {
150        cx.emit(ContextStripEvent::PickerDismissed);
151    }
152
153    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
154        self.focused_index = self.last_pill_index();
155        cx.notify();
156    }
157
158    fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
159        self.focused_index = None;
160        cx.notify();
161    }
162
163    fn focus_left(&mut self, _: &FocusLeft, cx: &mut ViewContext<Self>) {
164        self.focused_index = match self.focused_index {
165            Some(index) if index > 0 => Some(index - 1),
166            _ => self.last_pill_index(),
167        };
168
169        cx.notify();
170    }
171
172    fn focus_right(&mut self, _: &FocusRight, cx: &mut ViewContext<Self>) {
173        let Some(last_index) = self.last_pill_index() else {
174            return;
175        };
176
177        self.focused_index = match self.focused_index {
178            Some(index) if index < last_index => Some(index + 1),
179            _ => Some(0),
180        };
181
182        cx.notify();
183    }
184
185    fn focus_up(&mut self, _: &FocusUp, cx: &mut ViewContext<Self>) {
186        let Some(focused_index) = self.focused_index else {
187            return;
188        };
189
190        if focused_index == 0 {
191            return cx.emit(ContextStripEvent::BlurredUp);
192        }
193
194        let Some((focused, pills)) = self.focused_bounds(focused_index) else {
195            return;
196        };
197
198        let iter = pills[..focused_index].iter().enumerate().rev();
199        self.focused_index = Self::find_best_horizontal_match(focused, iter).or(Some(0));
200        cx.notify();
201    }
202
203    fn focus_down(&mut self, _: &FocusDown, cx: &mut ViewContext<Self>) {
204        let Some(focused_index) = self.focused_index else {
205            return;
206        };
207
208        let last_index = self.last_pill_index();
209
210        if self.focused_index == last_index {
211            return cx.emit(ContextStripEvent::BlurredDown);
212        }
213
214        let Some((focused, pills)) = self.focused_bounds(focused_index) else {
215            return;
216        };
217
218        let iter = pills.iter().enumerate().skip(focused_index + 1);
219        self.focused_index = Self::find_best_horizontal_match(focused, iter).or(last_index);
220        cx.notify();
221    }
222
223    fn focused_bounds(&self, focused: usize) -> Option<(&Bounds<Pixels>, &[Bounds<Pixels>])> {
224        let pill_bounds = self.pill_bounds()?;
225        let focused = pill_bounds.get(focused)?;
226
227        Some((focused, pill_bounds))
228    }
229
230    fn pill_bounds(&self) -> Option<&[Bounds<Pixels>]> {
231        let bounds = self.children_bounds.as_ref()?;
232        let eraser = if bounds.len() < 3 { 0 } else { 1 };
233        let pills = &bounds[1..bounds.len() - eraser];
234
235        if pills.is_empty() {
236            None
237        } else {
238            Some(pills)
239        }
240    }
241
242    fn last_pill_index(&self) -> Option<usize> {
243        Some(self.pill_bounds()?.len() - 1)
244    }
245
246    fn find_best_horizontal_match<'a>(
247        focused: &'a Bounds<Pixels>,
248        iter: impl Iterator<Item = (usize, &'a Bounds<Pixels>)>,
249    ) -> Option<usize> {
250        let mut best = None;
251
252        let focused_left = focused.left();
253        let focused_right = focused.right();
254
255        for (index, probe) in iter {
256            if probe.origin.y == focused.origin.y {
257                continue;
258            }
259
260            let overlap = probe.right().min(focused_right) - probe.left().max(focused_left);
261
262            best = match best {
263                Some((_, prev_overlap, y)) if probe.origin.y != y || prev_overlap > overlap => {
264                    break;
265                }
266                Some(_) | None => Some((index, overlap, probe.origin.y)),
267            };
268        }
269
270        best.map(|(index, _, _)| index)
271    }
272
273    fn remove_focused_context(&mut self, _: &RemoveFocusedContext, cx: &mut ViewContext<Self>) {
274        if let Some(index) = self.focused_index {
275            let mut is_empty = false;
276
277            self.context_store.update(cx, |this, _cx| {
278                if let Some(item) = this.context().get(index) {
279                    this.remove_context(item.id());
280                }
281
282                is_empty = this.context().is_empty();
283            });
284
285            if is_empty {
286                cx.emit(ContextStripEvent::BlurredEmpty);
287            } else {
288                self.focused_index = Some(index.saturating_sub(1));
289                cx.notify();
290            }
291        }
292    }
293
294    fn is_suggested_focused<T>(&self, context: &Vec<T>) -> bool {
295        // We only suggest one item after the actual context
296        self.focused_index == Some(context.len())
297    }
298
299    fn accept_suggested_context(&mut self, _: &AcceptSuggestedContext, cx: &mut ViewContext<Self>) {
300        if let Some(suggested) = self.suggested_context(cx) {
301            let context_store = self.context_store.read(cx);
302
303            if self.is_suggested_focused(context_store.context()) {
304                self.add_suggested_context(&suggested, cx);
305            }
306        }
307    }
308
309    fn add_suggested_context(&mut self, suggested: &SuggestedContext, cx: &mut ViewContext<Self>) {
310        let task = self.context_store.update(cx, |context_store, cx| {
311            context_store.accept_suggested_context(&suggested, cx)
312        });
313
314        cx.spawn(|this, mut cx| async move {
315            match task.await.notify_async_err(&mut cx) {
316                None => {}
317                Some(()) => {
318                    if let Some(this) = this.upgrade() {
319                        this.update(&mut cx, |_, cx| cx.notify())?;
320                    }
321                }
322            }
323            anyhow::Ok(())
324        })
325        .detach_and_log_err(cx);
326
327        cx.notify();
328    }
329}
330
331impl FocusableView for ContextStrip {
332    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
333        self.focus_handle.clone()
334    }
335}
336
337impl Render for ContextStrip {
338    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
339        let context_store = self.context_store.read(cx);
340        let context = context_store
341            .context()
342            .iter()
343            .flat_map(|context| context.snapshot(cx))
344            .collect::<Vec<_>>();
345        let context_picker = self.context_picker.clone();
346        let focus_handle = self.focus_handle.clone();
347
348        let suggested_context = self.suggested_context(cx);
349
350        let dupe_names = context
351            .iter()
352            .map(|context| context.name.clone())
353            .sorted()
354            .tuple_windows()
355            .filter(|(a, b)| a == b)
356            .map(|(a, _)| a)
357            .collect::<HashSet<SharedString>>();
358
359        h_flex()
360            .flex_wrap()
361            .gap_1()
362            .track_focus(&focus_handle)
363            .key_context("ContextStrip")
364            .on_action(cx.listener(Self::focus_up))
365            .on_action(cx.listener(Self::focus_right))
366            .on_action(cx.listener(Self::focus_down))
367            .on_action(cx.listener(Self::focus_left))
368            .on_action(cx.listener(Self::remove_focused_context))
369            .on_action(cx.listener(Self::accept_suggested_context))
370            .on_children_prepainted({
371                let view = cx.view().downgrade();
372                move |children_bounds, cx| {
373                    view.update(cx, |this, _| {
374                        this.children_bounds = Some(children_bounds);
375                    })
376                    .ok();
377                }
378            })
379            .child(
380                PopoverMenu::new("context-picker")
381                    .menu(move |cx| {
382                        context_picker.update(cx, |this, cx| {
383                            this.init(cx);
384                        });
385
386                        Some(context_picker.clone())
387                    })
388                    .trigger(
389                        IconButton::new("add-context", IconName::Plus)
390                            .icon_size(IconSize::Small)
391                            .style(ui::ButtonStyle::Filled)
392                            .tooltip({
393                                let focus_handle = focus_handle.clone();
394
395                                move |cx| {
396                                    Tooltip::for_action_in(
397                                        "Add Context",
398                                        &ToggleContextPicker,
399                                        &focus_handle,
400                                        cx,
401                                    )
402                                }
403                            }),
404                    )
405                    .attach(gpui::Corner::TopLeft)
406                    .anchor(gpui::Corner::BottomLeft)
407                    .offset(gpui::Point {
408                        x: px(0.0),
409                        y: px(-2.0),
410                    })
411                    .with_handle(self.context_picker_menu_handle.clone()),
412            )
413            .when(context.is_empty() && suggested_context.is_none(), {
414                |parent| {
415                    parent.child(
416                        h_flex()
417                            .ml_1p5()
418                            .gap_2()
419                            .child(
420                                Label::new("Add Context")
421                                    .size(LabelSize::Small)
422                                    .color(Color::Muted),
423                            )
424                            .opacity(0.5)
425                            .children(
426                                KeyBinding::for_action_in(&ToggleContextPicker, &focus_handle, cx)
427                                    .map(|binding| binding.into_any_element()),
428                            ),
429                    )
430                }
431            })
432            .children(context.iter().enumerate().map(|(i, context)| {
433                ContextPill::new_added(
434                    context.clone(),
435                    dupe_names.contains(&context.name),
436                    self.focused_index == Some(i),
437                    Some({
438                        let id = context.id;
439                        let context_store = self.context_store.clone();
440                        Rc::new(cx.listener(move |_this, _event, cx| {
441                            context_store.update(cx, |this, _cx| {
442                                this.remove_context(id);
443                            });
444                            cx.notify();
445                        }))
446                    }),
447                )
448                .on_click(Rc::new(cx.listener(move |this, _, cx| {
449                    this.focused_index = Some(i);
450                    cx.notify();
451                })))
452            }))
453            .when_some(suggested_context, |el, suggested| {
454                el.child(
455                    ContextPill::new_suggested(
456                        suggested.name().clone(),
457                        suggested.icon_path(),
458                        suggested.kind(),
459                        self.is_suggested_focused(&context),
460                    )
461                    .on_click(Rc::new(cx.listener(move |this, _event, cx| {
462                        this.add_suggested_context(&suggested, cx);
463                    }))),
464                )
465            })
466            .when(!context.is_empty(), {
467                move |parent| {
468                    parent.child(
469                        IconButton::new("remove-all-context", IconName::Eraser)
470                            .icon_size(IconSize::Small)
471                            .tooltip({
472                                let focus_handle = focus_handle.clone();
473                                move |cx| {
474                                    Tooltip::for_action_in(
475                                        "Remove All Context",
476                                        &RemoveAllContext,
477                                        &focus_handle,
478                                        cx,
479                                    )
480                                }
481                            })
482                            .on_click(cx.listener({
483                                let focus_handle = focus_handle.clone();
484                                move |_this, _event, cx| {
485                                    focus_handle.dispatch_action(&RemoveAllContext, cx);
486                                }
487                            })),
488                    )
489                }
490            })
491    }
492}
493
494pub enum ContextStripEvent {
495    PickerDismissed,
496    BlurredEmpty,
497    BlurredDown,
498    BlurredUp,
499}
500
501impl EventEmitter<ContextStripEvent> for ContextStrip {}
502
503pub enum SuggestContextKind {
504    File,
505    Thread,
506}
507
508#[derive(Clone)]
509pub enum SuggestedContext {
510    File {
511        name: SharedString,
512        icon_path: Option<SharedString>,
513        buffer: WeakModel<Buffer>,
514    },
515    Thread {
516        name: SharedString,
517        thread: WeakModel<Thread>,
518    },
519}
520
521impl SuggestedContext {
522    pub fn name(&self) -> &SharedString {
523        match self {
524            Self::File { name, .. } => name,
525            Self::Thread { name, .. } => name,
526        }
527    }
528
529    pub fn icon_path(&self) -> Option<SharedString> {
530        match self {
531            Self::File { icon_path, .. } => icon_path.clone(),
532            Self::Thread { .. } => None,
533        }
534    }
535
536    pub fn kind(&self) -> ContextKind {
537        match self {
538            Self::File { .. } => ContextKind::File,
539            Self::Thread { .. } => ContextKind::Thread,
540        }
541    }
542}