Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T05:06:13.083Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

snippets_ui.rs

369 lines · 11.8 KB · rust
1use file_icons::FileIcons;
2use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
3use gpui::{
4    App, Context, DismissEvent, Entity, EventEmitter, Focusable, ParentElement, Render, Styled,
5    TaskExt, WeakEntity, Window, actions,
6};
7use language::{LanguageMatcher, LanguageName, LanguageRegistry};
8use open_path_prompt::file_finder_settings::FileFinderSettings;
9use paths::snippets_dir;
10use picker::{Picker, PickerDelegate};
11use settings::Settings;
12use std::{
13    borrow::{Borrow, Cow},
14    collections::HashSet,
15    fs,
16    path::Path,
17    sync::Arc,
18};
19use ui::{HighlightedLabel, ListItem, ListItemSpacing, prelude::*};
20use util::ResultExt;
21use workspace::{ModalView, OpenOptions, OpenVisible, Workspace, notifications::NotifyResultExt};
22
23#[derive(Eq, Hash, PartialEq)]
24struct ScopeName(Cow<'static, str>);
25
26struct ScopeFileName(Cow<'static, str>);
27
28impl ScopeFileName {
29    fn with_extension(self) -> String {
30        format!("{}.json", self.0)
31    }
32}
33
34const GLOBAL_SCOPE_NAME: &str = "global";
35const GLOBAL_SCOPE_FILE_NAME: &str = "snippets";
36
37impl From<ScopeName> for ScopeFileName {
38    fn from(value: ScopeName) -> Self {
39        if value.0 == GLOBAL_SCOPE_NAME {
40            ScopeFileName(Cow::Borrowed(GLOBAL_SCOPE_FILE_NAME))
41        } else {
42            ScopeFileName(value.0)
43        }
44    }
45}
46
47impl From<ScopeFileName> for ScopeName {
48    fn from(value: ScopeFileName) -> Self {
49        if value.0 == GLOBAL_SCOPE_FILE_NAME {
50            ScopeName(Cow::Borrowed(GLOBAL_SCOPE_NAME))
51        } else {
52            ScopeName(value.0)
53        }
54    }
55}
56
57actions!(
58    snippets,
59    [
60        /// Opens the snippets configuration file.
61        ConfigureSnippets,
62        /// Opens the snippets folder in the file manager.
63        OpenFolder
64    ]
65);
66
67pub fn init(cx: &mut App) {
68    cx.observe_new(register).detach();
69}
70
71fn register(workspace: &mut Workspace, _window: Option<&mut Window>, _: &mut Context<Workspace>) {
72    workspace.register_action(configure_snippets);
73    workspace.register_action(open_folder);
74}
75
76fn configure_snippets(
77    workspace: &mut Workspace,
78    _: &ConfigureSnippets,
79    window: &mut Window,
80    cx: &mut Context<Workspace>,
81) {
82    let language_registry = workspace.app_state().languages.clone();
83    let workspace_handle = workspace.weak_handle();
84
85    workspace.toggle_modal(window, cx, move |window, cx| {
86        ScopeSelector::new(language_registry, workspace_handle, window, cx)
87    });
88}
89
90fn open_folder(
91    workspace: &mut Workspace,
92    _: &OpenFolder,
93    _: &mut Window,
94    cx: &mut Context<Workspace>,
95) {
96    fs::create_dir_all(snippets_dir()).notify_err(workspace, cx);
97    cx.open_with_system(snippets_dir().borrow());
98}
99
100pub struct ScopeSelector {
101    picker: Entity<Picker<ScopeSelectorDelegate>>,
102}
103
104impl ScopeSelector {
105    fn new(
106        language_registry: Arc<LanguageRegistry>,
107        workspace: WeakEntity<Workspace>,
108        window: &mut Window,
109        cx: &mut Context<Self>,
110    ) -> Self {
111        let delegate =
112            ScopeSelectorDelegate::new(workspace, cx.entity().downgrade(), language_registry);
113
114        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
115
116        Self { picker }
117    }
118}
119
120impl ModalView for ScopeSelector {}
121
122impl EventEmitter<DismissEvent> for ScopeSelector {}
123
124impl Focusable for ScopeSelector {
125    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
126        self.picker.focus_handle(cx)
127    }
128}
129
130impl Render for ScopeSelector {
131    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
132        v_flex().child(self.picker.clone())
133    }
134}
135
136pub struct ScopeSelectorDelegate {
137    workspace: WeakEntity<Workspace>,
138    scope_selector: WeakEntity<ScopeSelector>,
139    language_registry: Arc<LanguageRegistry>,
140    candidates: Vec<StringMatchCandidate>,
141    matches: Vec<StringMatch>,
142    selected_index: usize,
143    existing_scopes: HashSet<ScopeName>,
144}
145
146impl ScopeSelectorDelegate {
147    fn new(
148        workspace: WeakEntity<Workspace>,
149        scope_selector: WeakEntity<ScopeSelector>,
150        language_registry: Arc<LanguageRegistry>,
151    ) -> Self {
152        let languages = language_registry.language_names().into_iter();
153
154        let candidates = std::iter::once(LanguageName::new(GLOBAL_SCOPE_NAME))
155            .chain(languages)
156            .enumerate()
157            .map(|(candidate_id, name)| StringMatchCandidate::new(candidate_id, name.as_ref()))
158            .collect::<Vec<_>>();
159
160        let mut existing_scopes = HashSet::new();
161
162        if let Some(read_dir) = fs::read_dir(snippets_dir()).log_err() {
163            for entry in read_dir {
164                if let Some(entry) = entry.log_err() {
165                    let path = entry.path();
166                    if let (Some(stem), Some(extension)) = (path.file_stem(), path.extension())
167                        && extension.to_os_string().to_str() == Some("json")
168                        && let Ok(file_name) = stem.to_os_string().into_string()
169                    {
170                        existing_scopes
171                            .insert(ScopeName::from(ScopeFileName(Cow::Owned(file_name))));
172                    }
173                }
174            }
175        }
176
177        Self {
178            workspace,
179            scope_selector,
180            language_registry,
181            candidates,
182            matches: Vec::new(),
183            selected_index: 0,
184            existing_scopes,
185        }
186    }
187
188    fn scope_icon(&self, matcher: &LanguageMatcher, cx: &App) -> Option<Icon> {
189        matcher
190            .path_suffixes
191            .iter()
192            .find_map(|extension| FileIcons::get_icon(Path::new(extension), cx))
193            .or(FileIcons::get(cx).get_icon_for_type("default", cx))
194            .map(Icon::from_path)
195            .map(|icon| icon.color(Color::Muted))
196    }
197}
198
199impl PickerDelegate for ScopeSelectorDelegate {
200    type ListItem = ListItem;
201
202    fn name() -> &'static str {
203        "snippet scope selector"
204    }
205
206    fn placeholder_text(&self, _window: &mut Window, _: &mut App) -> Arc<str> {
207        "Select snippet scope...".into()
208    }
209
210    fn match_count(&self) -> usize {
211        self.matches.len()
212    }
213
214    fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
215        if let Some(mat) = self.matches.get(self.selected_index) {
216            let scope_name = self.candidates[mat.candidate_id].string.clone();
217            let language = self.language_registry.language_for_name(&scope_name);
218
219            if let Some(workspace) = self.workspace.upgrade() {
220                cx.spawn_in(window, async move |_, cx| {
221                    let scope_file_name = ScopeFileName(match scope_name.to_lowercase().as_str() {
222                        GLOBAL_SCOPE_NAME => Cow::Borrowed(GLOBAL_SCOPE_FILE_NAME),
223                        _ => Cow::Owned(language.await?.snippet_scope_id()),
224                    });
225
226                    workspace.update_in(cx, |workspace, window, cx| {
227                        workspace
228                            .with_local_workspace(window, cx, |workspace, window, cx| {
229                                workspace
230                                    .open_abs_path(
231                                        snippets_dir().join(scope_file_name.with_extension()),
232                                        OpenOptions {
233                                            visible: Some(OpenVisible::None),
234                                            ..Default::default()
235                                        },
236                                        window,
237                                        cx,
238                                    )
239                                    .detach();
240                            })
241                            .detach();
242                    })
243                })
244                .detach_and_log_err(cx);
245            };
246        }
247        self.dismissed(window, cx);
248    }
249
250    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
251        self.scope_selector
252            .update(cx, |_, cx| cx.emit(DismissEvent))
253            .log_err();
254    }
255
256    fn selected_index(&self) -> usize {
257        self.selected_index
258    }
259
260    fn set_selected_index(
261        &mut self,
262        ix: usize,
263        _window: &mut Window,
264        _: &mut Context<Picker<Self>>,
265    ) {
266        self.selected_index = ix;
267    }
268
269    fn update_matches(
270        &mut self,
271        query: String,
272        window: &mut Window,
273        cx: &mut Context<Picker<Self>>,
274    ) -> gpui::Task<()> {
275        let background = cx.background_executor().clone();
276        let candidates = self.candidates.clone();
277        cx.spawn_in(window, async move |this, cx| {
278            let matches = if query.is_empty() {
279                candidates
280                    .into_iter()
281                    .enumerate()
282                    .map(|(index, candidate)| StringMatch {
283                        candidate_id: index,
284                        string: candidate.string,
285                        positions: Vec::new(),
286                        score: 0.0,
287                    })
288                    .collect()
289            } else {
290                match_strings(
291                    &candidates,
292                    &query,
293                    false,
294                    true,
295                    100,
296                    &Default::default(),
297                    background,
298                )
299                .await
300            };
301
302            this.update(cx, |this, cx| {
303                let delegate = &mut this.delegate;
304                delegate.matches = matches;
305                delegate.selected_index = delegate
306                    .selected_index
307                    .min(delegate.matches.len().saturating_sub(1));
308                cx.notify();
309            })
310            .log_err();
311        })
312    }
313
314    fn render_match(
315        &self,
316        ix: usize,
317        selected: bool,
318        _window: &mut Window,
319        cx: &mut Context<Picker<Self>>,
320    ) -> Option<Self::ListItem> {
321        let mat = &self.matches.get(ix)?;
322        let name_label = mat.string.clone();
323
324        let scope_name = ScopeName(Cow::Owned(
325            LanguageName::new(&self.candidates[mat.candidate_id].string).snippet_scope_id(),
326        ));
327        let file_label = if self.existing_scopes.contains(&scope_name) {
328            Some(ScopeFileName::from(scope_name).with_extension())
329        } else {
330            None
331        };
332
333        let language_icon = if FileFinderSettings::get_global(cx).file_icons {
334            let language_name = LanguageName::new(mat.string.as_str());
335            self.language_registry
336                .available_language_for_name(language_name.as_ref())
337                .and_then(|available_language| self.scope_icon(available_language.matcher(), cx))
338                .or_else(|| {
339                    Some(
340                        Icon::from_path(IconName::ToolWeb.path())
341                            .map(|icon| icon.color(Color::Muted)),
342                    )
343                })
344        } else {
345            None
346        };
347
348        Some(
349            ListItem::new(ix)
350                .inset(true)
351                .spacing(ListItemSpacing::Sparse)
352                .toggle_state(selected)
353                .start_slot::<Icon>(language_icon)
354                .child(
355                    h_flex()
356                        .gap_x_2()
357                        .child(HighlightedLabel::new(name_label, mat.positions.clone()))
358                        .when_some(file_label, |item, path_label| {
359                            item.child(
360                                Label::new(path_label)
361                                    .color(Color::Muted)
362                                    .size(LabelSize::Small),
363                            )
364                        }),
365                ),
366        )
367    }
368}
369
Served at tenant.openagents/omega Member data and write actions are omitted.