1mod completion_provider;
2pub(crate) mod fetch_context_picker;
3pub(crate) mod file_context_picker;
4pub(crate) mod rules_context_picker;
5pub(crate) mod symbol_context_picker;
6pub(crate) mod thread_context_picker;
7
8use std::ops::Range;
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12use anyhow::{Result, anyhow};
13use collections::HashSet;
14pub use completion_provider::ContextPickerCompletionProvider;
15use editor::display_map::{Crease, CreaseId, CreaseMetadata, FoldId};
16use editor::{Anchor, Editor, ExcerptId, FoldPlaceholder, ToOffset};
17use fetch_context_picker::FetchContextPicker;
18use file_context_picker::FileContextPicker;
19use file_context_picker::render_file_context_entry;
20use gpui::{
21 App, DismissEvent, Empty, Entity, EventEmitter, FocusHandle, Focusable, Subscription, Task,
22 WeakEntity,
23};
24use language::Buffer;
25use multi_buffer::MultiBufferRow;
26use paths::contexts_dir;
27use project::{Entry, ProjectPath};
28use prompt_store::{PromptStore, UserPromptId};
29use rules_context_picker::{RulesContextEntry, RulesContextPicker};
30use symbol_context_picker::SymbolContextPicker;
31use thread_context_picker::{
32 ThreadContextEntry, ThreadContextPicker, render_thread_context_entry, unordered_thread_entries,
33};
34use ui::{
35 ButtonLike, ContextMenu, ContextMenuEntry, ContextMenuItem, Disclosure, TintColor, prelude::*,
36};
37use uuid::Uuid;
38use workspace::{Workspace, notifications::NotifyResultExt};
39
40use crate::AgentPanel;
41use agent::{
42 ThreadId,
43 context::RULES_ICON,
44 context_store::ContextStore,
45 thread_store::{TextThreadStore, ThreadStore},
46};
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub(crate) enum ContextPickerEntry {
50 Mode(ContextPickerMode),
51 Action(ContextPickerAction),
52}
53
54impl ContextPickerEntry {
55 pub fn keyword(&self) -> &'static str {
56 match self {
57 Self::Mode(mode) => mode.keyword(),
58 Self::Action(action) => action.keyword(),
59 }
60 }
61
62 pub fn label(&self) -> &'static str {
63 match self {
64 Self::Mode(mode) => mode.label(),
65 Self::Action(action) => action.label(),
66 }
67 }
68
69 pub fn icon(&self) -> IconName {
70 match self {
71 Self::Mode(mode) => mode.icon(),
72 Self::Action(action) => action.icon(),
73 }
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub(crate) enum ContextPickerMode {
79 File,
80 Symbol,
81 Fetch,
82 Thread,
83 Rules,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub(crate) enum ContextPickerAction {
88 AddSelections,
89}
90
91impl ContextPickerAction {
92 pub fn keyword(&self) -> &'static str {
93 match self {
94 Self::AddSelections => "selection",
95 }
96 }
97
98 pub fn label(&self) -> &'static str {
99 match self {
100 Self::AddSelections => "Selection",
101 }
102 }
103
104 pub fn icon(&self) -> IconName {
105 match self {
106 Self::AddSelections => IconName::Reader,
107 }
108 }
109}
110
111impl TryFrom<&str> for ContextPickerMode {
112 type Error = String;
113
114 fn try_from(value: &str) -> Result<Self, Self::Error> {
115 match value {
116 "file" => Ok(Self::File),
117 "symbol" => Ok(Self::Symbol),
118 "fetch" => Ok(Self::Fetch),
119 "thread" => Ok(Self::Thread),
120 "rule" => Ok(Self::Rules),
121 _ => Err(format!("Invalid context picker mode: {}", value)),
122 }
123 }
124}
125
126impl ContextPickerMode {
127 pub fn keyword(&self) -> &'static str {
128 match self {
129 Self::File => "file",
130 Self::Symbol => "symbol",
131 Self::Fetch => "fetch",
132 Self::Thread => "thread",
133 Self::Rules => "rule",
134 }
135 }
136
137 pub fn label(&self) -> &'static str {
138 match self {
139 Self::File => "Files & Directories",
140 Self::Symbol => "Symbols",
141 Self::Fetch => "Fetch",
142 Self::Thread => "Threads",
143 Self::Rules => "Rules",
144 }
145 }
146
147 pub fn icon(&self) -> IconName {
148 match self {
149 Self::File => IconName::File,
150 Self::Symbol => IconName::Code,
151 Self::Fetch => IconName::ToolWeb,
152 Self::Thread => IconName::Thread,
153 Self::Rules => RULES_ICON,
154 }
155 }
156}
157
158#[derive(Debug, Clone)]
159enum ContextPickerState {
160 Default(Entity<ContextMenu>),
161 File(Entity<FileContextPicker>),
162 Symbol(Entity<SymbolContextPicker>),
163 Fetch(Entity<FetchContextPicker>),
164 Thread(Entity<ThreadContextPicker>),
165 Rules(Entity<RulesContextPicker>),
166}
167
168pub(super) struct ContextPicker {
169 mode: ContextPickerState,
170 workspace: WeakEntity<Workspace>,
171 context_store: WeakEntity<ContextStore>,
172 thread_store: Option<WeakEntity<ThreadStore>>,
173 text_thread_store: Option<WeakEntity<TextThreadStore>>,
174 prompt_store: Option<Entity<PromptStore>>,
175 _subscriptions: Vec<Subscription>,
176}
177
178impl ContextPicker {
179 pub fn new(
180 workspace: WeakEntity<Workspace>,
181 thread_store: Option<WeakEntity<ThreadStore>>,
182 text_thread_store: Option<WeakEntity<TextThreadStore>>,
183 context_store: WeakEntity<ContextStore>,
184 window: &mut Window,
185 cx: &mut Context<Self>,
186 ) -> Self {
187 let subscriptions = context_store
188 .upgrade()
189 .map(|context_store| {
190 cx.observe(&context_store, |this, _, cx| this.notify_current_picker(cx))
191 })
192 .into_iter()
193 .chain(
194 thread_store
195 .as_ref()
196 .and_then(|thread_store| thread_store.upgrade())
197 .map(|thread_store| {
198 cx.observe(&thread_store, |this, _, cx| this.notify_current_picker(cx))
199 }),
200 )
201 .collect::<Vec<Subscription>>();
202
203 let prompt_store = thread_store.as_ref().and_then(|thread_store| {
204 thread_store
205 .read_with(cx, |thread_store, _cx| thread_store.prompt_store().clone())
206 .ok()
207 .flatten()
208 });
209
210 ContextPicker {
211 mode: ContextPickerState::Default(ContextMenu::build(
212 window,
213 cx,
214 |menu, _window, _cx| menu,
215 )),
216 workspace,
217 context_store,
218 thread_store,
219 text_thread_store,
220 prompt_store,
221 _subscriptions: subscriptions,
222 }
223 }
224
225 pub fn init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
226 self.mode = ContextPickerState::Default(self.build_menu(window, cx));
227 cx.notify();
228 }
229
230 fn build_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<ContextMenu> {
231 let context_picker = cx.entity();
232
233 let menu = ContextMenu::build(window, cx, move |menu, _window, cx| {
234 let recent = self.recent_entries(cx);
235 let has_recent = !recent.is_empty();
236 let recent_entries = recent
237 .into_iter()
238 .enumerate()
239 .map(|(ix, entry)| self.recent_menu_item(context_picker.clone(), ix, entry));
240
241 let entries = self
242 .workspace
243 .upgrade()
244 .map(|workspace| {
245 available_context_picker_entries(
246 &self.prompt_store,
247 &self.thread_store,
248 &workspace,
249 cx,
250 )
251 })
252 .unwrap_or_default();
253
254 menu.when(has_recent, |menu| {
255 menu.custom_row(|_, _| {
256 div()
257 .mb_1()
258 .child(
259 Label::new("Recent")
260 .color(Color::Muted)
261 .size(LabelSize::Small),
262 )
263 .into_any_element()
264 })
265 })
266 .extend(recent_entries)
267 .when(has_recent, |menu| menu.separator())
268 .extend(entries.into_iter().map(|entry| {
269 let context_picker = context_picker.clone();
270
271 ContextMenuEntry::new(entry.label())
272 .icon(entry.icon())
273 .icon_size(IconSize::XSmall)
274 .icon_color(Color::Muted)
275 .handler(move |window, cx| {
276 context_picker.update(cx, |this, cx| this.select_entry(entry, window, cx))
277 })
278 }))
279 .keep_open_on_confirm(true)
280 });
281
282 cx.subscribe(&menu, move |_, _, _: &DismissEvent, cx| {
283 cx.emit(DismissEvent);
284 })
285 .detach();
286
287 menu
288 }
289
290 /// Whether threads are allowed as context.
291 pub fn allow_threads(&self) -> bool {
292 self.thread_store.is_some()
293 }
294
295 fn select_entry(
296 &mut self,
297 entry: ContextPickerEntry,
298 window: &mut Window,
299 cx: &mut Context<Self>,
300 ) {
301 let context_picker = cx.entity().downgrade();
302
303 match entry {
304 ContextPickerEntry::Mode(mode) => match mode {
305 ContextPickerMode::File => {
306 self.mode = ContextPickerState::File(cx.new(|cx| {
307 FileContextPicker::new(
308 context_picker.clone(),
309 self.workspace.clone(),
310 self.context_store.clone(),
311 window,
312 cx,
313 )
314 }));
315 }
316 ContextPickerMode::Symbol => {
317 self.mode = ContextPickerState::Symbol(cx.new(|cx| {
318 SymbolContextPicker::new(
319 context_picker.clone(),
320 self.workspace.clone(),
321 self.context_store.clone(),
322 window,
323 cx,
324 )
325 }));
326 }
327 ContextPickerMode::Rules => {
328 if let Some(prompt_store) = self.prompt_store.as_ref() {
329 self.mode = ContextPickerState::Rules(cx.new(|cx| {
330 RulesContextPicker::new(
331 prompt_store.clone(),
332 context_picker.clone(),
333 self.context_store.clone(),
334 window,
335 cx,
336 )
337 }));
338 }
339 }
340 ContextPickerMode::Fetch => {
341 self.mode = ContextPickerState::Fetch(cx.new(|cx| {
342 FetchContextPicker::new(
343 context_picker.clone(),
344 self.workspace.clone(),
345 self.context_store.clone(),
346 window,
347 cx,
348 )
349 }));
350 }
351 ContextPickerMode::Thread => {
352 if let Some((thread_store, text_thread_store)) = self
353 .thread_store
354 .as_ref()
355 .zip(self.text_thread_store.as_ref())
356 {
357 self.mode = ContextPickerState::Thread(cx.new(|cx| {
358 ThreadContextPicker::new(
359 thread_store.clone(),
360 text_thread_store.clone(),
361 context_picker.clone(),
362 self.context_store.clone(),
363 window,
364 cx,
365 )
366 }));
367 }
368 }
369 },
370 ContextPickerEntry::Action(action) => match action {
371 ContextPickerAction::AddSelections => {
372 if let Some((context_store, workspace)) =
373 self.context_store.upgrade().zip(self.workspace.upgrade())
374 {
375 add_selections_as_context(&context_store, &workspace, cx);
376 }
377
378 cx.emit(DismissEvent);
379 }
380 },
381 }
382
383 cx.notify();
384 cx.focus_self(window);
385 }
386
387 pub fn select_first(&mut self, window: &mut Window, cx: &mut Context<Self>) {
388 // Other variants already select their first entry on open automatically
389 if let ContextPickerState::Default(entity) = &self.mode {
390 entity.update(cx, |entity, cx| {
391 entity.select_first(&Default::default(), window, cx)
392 })
393 }
394 }
395
396 fn recent_menu_item(
397 &self,
398 context_picker: Entity<ContextPicker>,
399 ix: usize,
400 entry: RecentEntry,
401 ) -> ContextMenuItem {
402 match entry {
403 RecentEntry::File {
404 project_path,
405 path_prefix,
406 } => {
407 let context_store = self.context_store.clone();
408 let worktree_id = project_path.worktree_id;
409 let path = project_path.path.clone();
410
411 ContextMenuItem::custom_entry(
412 move |_window, cx| {
413 render_file_context_entry(
414 ElementId::named_usize("ctx-recent", ix),
415 worktree_id,
416 &path,
417 &path_prefix,
418 false,
419 context_store.clone(),
420 cx,
421 )
422 .into_any()
423 },
424 move |window, cx| {
425 context_picker.update(cx, |this, cx| {
426 this.add_recent_file(project_path.clone(), window, cx);
427 })
428 },
429 None,
430 )
431 }
432 RecentEntry::Thread(thread) => {
433 let context_store = self.context_store.clone();
434 let view_thread = thread.clone();
435
436 ContextMenuItem::custom_entry(
437 move |_window, cx| {
438 render_thread_context_entry(&view_thread, context_store.clone(), cx)
439 .into_any()
440 },
441 move |window, cx| {
442 context_picker.update(cx, |this, cx| {
443 this.add_recent_thread(thread.clone(), window, cx)
444 .detach_and_log_err(cx);
445 })
446 },
447 None,
448 )
449 }
450 }
451 }
452
453 fn add_recent_file(
454 &self,
455 project_path: ProjectPath,
456 window: &mut Window,
457 cx: &mut Context<Self>,
458 ) {
459 let Some(context_store) = self.context_store.upgrade() else {
460 return;
461 };
462
463 let task = context_store.update(cx, |context_store, cx| {
464 context_store.add_file_from_path(project_path.clone(), true, cx)
465 });
466
467 cx.spawn_in(window, async move |_, cx| task.await.notify_async_err(cx))
468 .detach();
469
470 cx.notify();
471 }
472
473 fn add_recent_thread(
474 &self,
475 entry: ThreadContextEntry,
476 window: &mut Window,
477 cx: &mut Context<Self>,
478 ) -> Task<Result<()>> {
479 let Some(context_store) = self.context_store.upgrade() else {
480 return Task::ready(Err(anyhow!("context store not available")));
481 };
482
483 match entry {
484 ThreadContextEntry::Thread { id, .. } => {
485 let Some(thread_store) = self
486 .thread_store
487 .as_ref()
488 .and_then(|thread_store| thread_store.upgrade())
489 else {
490 return Task::ready(Err(anyhow!("thread store not available")));
491 };
492
493 let open_thread_task =
494 thread_store.update(cx, |this, cx| this.open_thread(&id, window, cx));
495 cx.spawn(async move |this, cx| {
496 let thread = open_thread_task.await?;
497 context_store.update(cx, |context_store, cx| {
498 context_store.add_thread(thread, true, cx);
499 })?;
500 this.update(cx, |_this, cx| cx.notify())
501 })
502 }
503 ThreadContextEntry::Context { path, .. } => {
504 let Some(text_thread_store) = self
505 .text_thread_store
506 .as_ref()
507 .and_then(|thread_store| thread_store.upgrade())
508 else {
509 return Task::ready(Err(anyhow!("text thread store not available")));
510 };
511
512 let task = text_thread_store
513 .update(cx, |this, cx| this.open_local_context(path.clone(), cx));
514 cx.spawn(async move |this, cx| {
515 let thread = task.await?;
516 context_store.update(cx, |context_store, cx| {
517 context_store.add_text_thread(thread, true, cx);
518 })?;
519 this.update(cx, |_this, cx| cx.notify())
520 })
521 }
522 }
523 }
524
525 fn recent_entries(&self, cx: &mut App) -> Vec<RecentEntry> {
526 let Some(workspace) = self.workspace.upgrade() else {
527 return vec![];
528 };
529
530 let Some(context_store) = self.context_store.upgrade() else {
531 return vec![];
532 };
533
534 recent_context_picker_entries_with_store(
535 context_store,
536 self.thread_store.clone(),
537 self.text_thread_store.clone(),
538 workspace,
539 None,
540 cx,
541 )
542 }
543
544 fn notify_current_picker(&mut self, cx: &mut Context<Self>) {
545 match &self.mode {
546 ContextPickerState::Default(entity) => entity.update(cx, |_, cx| cx.notify()),
547 ContextPickerState::File(entity) => entity.update(cx, |_, cx| cx.notify()),
548 ContextPickerState::Symbol(entity) => entity.update(cx, |_, cx| cx.notify()),
549 ContextPickerState::Fetch(entity) => entity.update(cx, |_, cx| cx.notify()),
550 ContextPickerState::Thread(entity) => entity.update(cx, |_, cx| cx.notify()),
551 ContextPickerState::Rules(entity) => entity.update(cx, |_, cx| cx.notify()),
552 }
553 }
554}
555
556impl EventEmitter<DismissEvent> for ContextPicker {}
557
558impl Focusable for ContextPicker {
559 fn focus_handle(&self, cx: &App) -> FocusHandle {
560 match &self.mode {
561 ContextPickerState::Default(menu) => menu.focus_handle(cx),
562 ContextPickerState::File(file_picker) => file_picker.focus_handle(cx),
563 ContextPickerState::Symbol(symbol_picker) => symbol_picker.focus_handle(cx),
564 ContextPickerState::Fetch(fetch_picker) => fetch_picker.focus_handle(cx),
565 ContextPickerState::Thread(thread_picker) => thread_picker.focus_handle(cx),
566 ContextPickerState::Rules(user_rules_picker) => user_rules_picker.focus_handle(cx),
567 }
568 }
569}
570
571impl Render for ContextPicker {
572 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
573 v_flex()
574 .w(px(400.))
575 .min_w(px(400.))
576 .map(|parent| match &self.mode {
577 ContextPickerState::Default(menu) => parent.child(menu.clone()),
578 ContextPickerState::File(file_picker) => parent.child(file_picker.clone()),
579 ContextPickerState::Symbol(symbol_picker) => parent.child(symbol_picker.clone()),
580 ContextPickerState::Fetch(fetch_picker) => parent.child(fetch_picker.clone()),
581 ContextPickerState::Thread(thread_picker) => parent.child(thread_picker.clone()),
582 ContextPickerState::Rules(user_rules_picker) => {
583 parent.child(user_rules_picker.clone())
584 }
585 })
586 }
587}
588
589pub(crate) enum RecentEntry {
590 File {
591 project_path: ProjectPath,
592 path_prefix: Arc<str>,
593 },
594 Thread(ThreadContextEntry),
595}
596
597pub(crate) fn available_context_picker_entries(
598 prompt_store: &Option<Entity<PromptStore>>,
599 thread_store: &Option<WeakEntity<ThreadStore>>,
600 workspace: &Entity<Workspace>,
601 cx: &mut App,
602) -> Vec<ContextPickerEntry> {
603 let mut entries = vec![
604 ContextPickerEntry::Mode(ContextPickerMode::File),
605 ContextPickerEntry::Mode(ContextPickerMode::Symbol),
606 ];
607
608 let has_selection = workspace
609 .read(cx)
610 .active_item(cx)
611 .and_then(|item| item.downcast::<Editor>())
612 .is_some_and(|editor| editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx)));
613 if has_selection {
614 entries.push(ContextPickerEntry::Action(
615 ContextPickerAction::AddSelections,
616 ));
617 }
618
619 if thread_store.is_some() {
620 entries.push(ContextPickerEntry::Mode(ContextPickerMode::Thread));
621 }
622
623 if prompt_store.is_some() {
624 entries.push(ContextPickerEntry::Mode(ContextPickerMode::Rules));
625 }
626
627 entries.push(ContextPickerEntry::Mode(ContextPickerMode::Fetch));
628
629 entries
630}
631
632fn recent_context_picker_entries_with_store(
633 context_store: Entity<ContextStore>,
634 thread_store: Option<WeakEntity<ThreadStore>>,
635 text_thread_store: Option<WeakEntity<TextThreadStore>>,
636 workspace: Entity<Workspace>,
637 exclude_path: Option<ProjectPath>,
638 cx: &App,
639) -> Vec<RecentEntry> {
640 let project = workspace.read(cx).project();
641
642 let mut exclude_paths = context_store.read(cx).file_paths(cx);
643 exclude_paths.extend(exclude_path);
644
645 let exclude_paths = exclude_paths
646 .into_iter()
647 .filter_map(|project_path| project.read(cx).absolute_path(&project_path, cx))
648 .collect();
649
650 let exclude_threads = context_store.read(cx).thread_ids();
651
652 recent_context_picker_entries(
653 thread_store,
654 text_thread_store,
655 workspace,
656 &exclude_paths,
657 exclude_threads,
658 cx,
659 )
660}
661
662pub(crate) fn recent_context_picker_entries(
663 thread_store: Option<WeakEntity<ThreadStore>>,
664 text_thread_store: Option<WeakEntity<TextThreadStore>>,
665 workspace: Entity<Workspace>,
666 exclude_paths: &HashSet<PathBuf>,
667 exclude_threads: &HashSet<ThreadId>,
668 cx: &App,
669) -> Vec<RecentEntry> {
670 let mut recent = Vec::with_capacity(6);
671 let workspace = workspace.read(cx);
672 let project = workspace.project().read(cx);
673
674 recent.extend(
675 workspace
676 .recent_navigation_history_iter(cx)
677 .filter(|(_, abs_path)| {
678 abs_path
679 .as_ref()
680 .is_none_or(|path| !exclude_paths.contains(path.as_path()))
681 })
682 .take(4)
683 .filter_map(|(project_path, _)| {
684 project
685 .worktree_for_id(project_path.worktree_id, cx)
686 .map(|worktree| RecentEntry::File {
687 project_path,
688 path_prefix: worktree.read(cx).root_name().into(),
689 })
690 }),
691 );
692
693 let active_thread_id = workspace
694 .panel::<AgentPanel>(cx)
695 .and_then(|panel| Some(panel.read(cx).active_thread(cx)?.read(cx).id()));
696
697 if let Some((thread_store, text_thread_store)) = thread_store
698 .and_then(|store| store.upgrade())
699 .zip(text_thread_store.and_then(|store| store.upgrade()))
700 {
701 let mut threads = unordered_thread_entries(thread_store, text_thread_store, cx)
702 .filter(|(_, thread)| match thread {
703 ThreadContextEntry::Thread { id, .. } => {
704 Some(id) != active_thread_id && !exclude_threads.contains(id)
705 }
706 ThreadContextEntry::Context { .. } => true,
707 })
708 .collect::<Vec<_>>();
709
710 const RECENT_COUNT: usize = 2;
711 if threads.len() > RECENT_COUNT {
712 threads.select_nth_unstable_by_key(RECENT_COUNT - 1, |(updated_at, _)| {
713 std::cmp::Reverse(*updated_at)
714 });
715 threads.truncate(RECENT_COUNT);
716 }
717 threads.sort_unstable_by_key(|(updated_at, _)| std::cmp::Reverse(*updated_at));
718
719 recent.extend(
720 threads
721 .into_iter()
722 .map(|(_, thread)| RecentEntry::Thread(thread)),
723 );
724 }
725
726 recent
727}
728
729fn add_selections_as_context(
730 context_store: &Entity<ContextStore>,
731 workspace: &Entity<Workspace>,
732 cx: &mut App,
733) {
734 let selection_ranges = selection_ranges(workspace, cx);
735 context_store.update(cx, |context_store, cx| {
736 for (buffer, range) in selection_ranges {
737 context_store.add_selection(buffer, range, cx);
738 }
739 })
740}
741
742pub(crate) fn selection_ranges(
743 workspace: &Entity<Workspace>,
744 cx: &mut App,
745) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
746 let Some(editor) = workspace
747 .read(cx)
748 .active_item(cx)
749 .and_then(|item| item.act_as::<Editor>(cx))
750 else {
751 return Vec::new();
752 };
753
754 editor.update(cx, |editor, cx| {
755 let selections = editor.selections.all_adjusted(cx);
756
757 let buffer = editor.buffer().clone().read(cx);
758 let snapshot = buffer.snapshot(cx);
759
760 selections
761 .into_iter()
762 .map(|s| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
763 .flat_map(|range| {
764 let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
765 let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
766 if start_buffer != end_buffer {
767 return None;
768 }
769 Some((start_buffer, start..end))
770 })
771 .collect::<Vec<_>>()
772 })
773}
774
775pub(crate) fn insert_crease_for_mention(
776 excerpt_id: ExcerptId,
777 crease_start: text::Anchor,
778 content_len: usize,
779 crease_label: SharedString,
780 crease_icon_path: SharedString,
781 editor_entity: Entity<Editor>,
782 window: &mut Window,
783 cx: &mut App,
784) -> Option<CreaseId> {
785 editor_entity.update(cx, |editor, cx| {
786 let snapshot = editor.buffer().read(cx).snapshot(cx);
787
788 let start = snapshot.anchor_in_excerpt(excerpt_id, crease_start)?;
789
790 let start = start.bias_right(&snapshot);
791 let end = snapshot.anchor_before(start.to_offset(&snapshot) + content_len);
792
793 let crease = crease_for_mention(
794 crease_label,
795 crease_icon_path,
796 start..end,
797 editor_entity.downgrade(),
798 );
799
800 let ids = editor.insert_creases(vec![crease.clone()], cx);
801 editor.fold_creases(vec![crease], false, window, cx);
802
803 Some(ids[0])
804 })
805}
806
807pub fn crease_for_mention(
808 label: SharedString,
809 icon_path: SharedString,
810 range: Range<Anchor>,
811 editor_entity: WeakEntity<Editor>,
812) -> Crease<Anchor> {
813 let placeholder = FoldPlaceholder {
814 render: render_fold_icon_button(icon_path.clone(), label.clone(), editor_entity),
815 merge_adjacent: false,
816 ..Default::default()
817 };
818
819 let render_trailer = move |_row, _unfold, _window: &mut Window, _cx: &mut App| Empty.into_any();
820
821 Crease::inline(range, placeholder, fold_toggle("mention"), render_trailer)
822 .with_metadata(CreaseMetadata { icon_path, label })
823}
824
825fn render_fold_icon_button(
826 icon_path: SharedString,
827 label: SharedString,
828 editor: WeakEntity<Editor>,
829) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
830 Arc::new({
831 move |fold_id, fold_range, cx| {
832 let is_in_text_selection = editor
833 .update(cx, |editor, cx| editor.is_range_selected(&fold_range, cx))
834 .unwrap_or_default();
835
836 ButtonLike::new(fold_id)
837 .style(ButtonStyle::Filled)
838 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
839 .toggle_state(is_in_text_selection)
840 .child(
841 h_flex()
842 .gap_1()
843 .child(
844 Icon::from_path(icon_path.clone())
845 .size(IconSize::XSmall)
846 .color(Color::Muted),
847 )
848 .child(
849 Label::new(label.clone())
850 .size(LabelSize::Small)
851 .buffer_font(cx)
852 .single_line(),
853 ),
854 )
855 .into_any_element()
856 }
857 })
858}
859
860fn fold_toggle(
861 name: &'static str,
862) -> impl Fn(
863 MultiBufferRow,
864 bool,
865 Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
866 &mut Window,
867 &mut App,
868) -> AnyElement {
869 move |row, is_folded, fold, _window, _cx| {
870 Disclosure::new((name, row.0 as u64), !is_folded)
871 .toggle_state(is_folded)
872 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
873 .into_any_element()
874 }
875}
876
877pub enum MentionLink {
878 File(ProjectPath, Entry),
879 Symbol(ProjectPath, String),
880 Selection(ProjectPath, Range<usize>),
881 Fetch(String),
882 Thread(ThreadId),
883 TextThread(Arc<Path>),
884 Rule(UserPromptId),
885}
886
887impl MentionLink {
888 const FILE: &str = "@file";
889 const SYMBOL: &str = "@symbol";
890 const SELECTION: &str = "@selection";
891 const THREAD: &str = "@thread";
892 const FETCH: &str = "@fetch";
893 const RULE: &str = "@rule";
894
895 const TEXT_THREAD_URL_PREFIX: &str = "text-thread://";
896
897 const SEPARATOR: &str = ":";
898
899 pub fn is_valid(url: &str) -> bool {
900 url.starts_with(Self::FILE)
901 || url.starts_with(Self::SYMBOL)
902 || url.starts_with(Self::FETCH)
903 || url.starts_with(Self::SELECTION)
904 || url.starts_with(Self::THREAD)
905 || url.starts_with(Self::RULE)
906 }
907
908 pub fn for_file(file_name: &str, full_path: &str) -> String {
909 format!("[@{}]({}:{})", file_name, Self::FILE, full_path)
910 }
911
912 pub fn for_symbol(symbol_name: &str, full_path: &str) -> String {
913 format!(
914 "[@{}]({}:{}:{})",
915 symbol_name,
916 Self::SYMBOL,
917 full_path,
918 symbol_name
919 )
920 }
921
922 pub fn for_selection(file_name: &str, full_path: &str, line_range: Range<usize>) -> String {
923 format!(
924 "[@{} ({}-{})]({}:{}:{}-{})",
925 file_name,
926 line_range.start + 1,
927 line_range.end + 1,
928 Self::SELECTION,
929 full_path,
930 line_range.start,
931 line_range.end
932 )
933 }
934
935 pub fn for_thread(thread: &ThreadContextEntry) -> String {
936 match thread {
937 ThreadContextEntry::Thread { id, title } => {
938 format!("[@{}]({}:{})", title, Self::THREAD, id)
939 }
940 ThreadContextEntry::Context { path, title } => {
941 let filename = path.file_name().unwrap_or_default().to_string_lossy();
942 let escaped_filename = urlencoding::encode(&filename);
943 format!(
944 "[@{}]({}:{}{})",
945 title,
946 Self::THREAD,
947 Self::TEXT_THREAD_URL_PREFIX,
948 escaped_filename
949 )
950 }
951 }
952 }
953
954 pub fn for_fetch(url: &str) -> String {
955 format!("[@{}]({}:{})", url, Self::FETCH, url)
956 }
957
958 pub fn for_rule(rule: &RulesContextEntry) -> String {
959 format!("[@{}]({}:{})", rule.title, Self::RULE, rule.prompt_id.0)
960 }
961
962 pub fn try_parse(link: &str, workspace: &Entity<Workspace>, cx: &App) -> Option<Self> {
963 fn extract_project_path_from_link(
964 path: &str,
965 workspace: &Entity<Workspace>,
966 cx: &App,
967 ) -> Option<ProjectPath> {
968 let path = PathBuf::from(path);
969 let worktree_name = path.iter().next()?;
970 let path: PathBuf = path.iter().skip(1).collect();
971 let worktree_id = workspace
972 .read(cx)
973 .visible_worktrees(cx)
974 .find(|worktree| worktree.read(cx).root_name() == worktree_name)
975 .map(|worktree| worktree.read(cx).id())?;
976 Some(ProjectPath {
977 worktree_id,
978 path: path.into(),
979 })
980 }
981
982 let (prefix, argument) = link.split_once(Self::SEPARATOR)?;
983 match prefix {
984 Self::FILE => {
985 let project_path = extract_project_path_from_link(argument, workspace, cx)?;
986 let entry = workspace
987 .read(cx)
988 .project()
989 .read(cx)
990 .entry_for_path(&project_path, cx)?
991 .clone();
992 Some(MentionLink::File(project_path, entry))
993 }
994 Self::SYMBOL => {
995 let (path, symbol) = argument.split_once(Self::SEPARATOR)?;
996 let project_path = extract_project_path_from_link(path, workspace, cx)?;
997 Some(MentionLink::Symbol(project_path, symbol.to_string()))
998 }
999 Self::SELECTION => {
1000 let (path, line_args) = argument.split_once(Self::SEPARATOR)?;
1001 let project_path = extract_project_path_from_link(path, workspace, cx)?;
1002
1003 let line_range = {
1004 let (start, end) = line_args
1005 .trim_start_matches('(')
1006 .trim_end_matches(')')
1007 .split_once('-')?;
1008 start.parse::<usize>().ok()?..end.parse::<usize>().ok()?
1009 };
1010
1011 Some(MentionLink::Selection(project_path, line_range))
1012 }
1013 Self::THREAD => {
1014 if let Some(encoded_filename) = argument.strip_prefix(Self::TEXT_THREAD_URL_PREFIX)
1015 {
1016 let filename = urlencoding::decode(encoded_filename).ok()?;
1017 let path = contexts_dir().join(filename.as_ref()).into();
1018 Some(MentionLink::TextThread(path))
1019 } else {
1020 let thread_id = ThreadId::from(argument);
1021 Some(MentionLink::Thread(thread_id))
1022 }
1023 }
1024 Self::FETCH => Some(MentionLink::Fetch(argument.to_string())),
1025 Self::RULE => {
1026 let prompt_id = UserPromptId(Uuid::try_parse(argument).ok()?);
1027 Some(MentionLink::Rule(prompt_id))
1028 }
1029 _ => None,
1030 }
1031 }
1032}