1mod components;
2mod extension_suggest;
3mod extension_version_selector;
4
5use std::sync::OnceLock;
6use std::time::Duration;
7use std::{ops::Range, sync::Arc};
8
9use client::{ExtensionMetadata, ExtensionProvides};
10use collections::{BTreeMap, BTreeSet};
11use editor::{Editor, EditorElement, EditorStyle};
12use extension_host::{ExtensionManifest, ExtensionOperation, ExtensionStore};
13use fuzzy::{StringMatchCandidate, match_strings};
14use gpui::{
15 Action, App, ClipboardItem, Context, Entity, EventEmitter, Flatten, Focusable,
16 InteractiveElement, KeyContext, ParentElement, Render, Styled, Task, TextStyle,
17 UniformListScrollHandle, WeakEntity, Window, actions, point, uniform_list,
18};
19use num_format::{Locale, ToFormattedString};
20use project::DirectoryLister;
21use release_channel::ReleaseChannel;
22use settings::Settings;
23use strum::IntoEnumIterator as _;
24use theme::ThemeSettings;
25use ui::{
26 CheckboxWithLabel, ContextMenu, PopoverMenu, ScrollableHandle, Scrollbar, ScrollbarState,
27 ToggleButton, Tooltip, prelude::*,
28};
29use vim_mode_setting::VimModeSetting;
30use workspace::{
31 Workspace, WorkspaceId,
32 item::{Item, ItemEvent},
33};
34use zed_actions::ExtensionCategoryFilter;
35
36use crate::components::{ExtensionCard, FeatureUpsell};
37use crate::extension_version_selector::{
38 ExtensionVersionSelector, ExtensionVersionSelectorDelegate,
39};
40
41actions!(zed, [InstallDevExtension]);
42
43pub fn init(cx: &mut App) {
44 cx.observe_new(move |workspace: &mut Workspace, window, cx| {
45 let Some(window) = window else {
46 return;
47 };
48 workspace
49 .register_action(
50 move |workspace, action: &zed_actions::Extensions, window, cx| {
51 let provides_filter = action.category_filter.map(|category| match category {
52 ExtensionCategoryFilter::Themes => ExtensionProvides::Themes,
53 ExtensionCategoryFilter::IconThemes => ExtensionProvides::IconThemes,
54 ExtensionCategoryFilter::Languages => ExtensionProvides::Languages,
55 ExtensionCategoryFilter::Grammars => ExtensionProvides::Grammars,
56 ExtensionCategoryFilter::LanguageServers => {
57 ExtensionProvides::LanguageServers
58 }
59 ExtensionCategoryFilter::ContextServers => {
60 ExtensionProvides::ContextServers
61 }
62 ExtensionCategoryFilter::SlashCommands => ExtensionProvides::SlashCommands,
63 ExtensionCategoryFilter::IndexedDocsProviders => {
64 ExtensionProvides::IndexedDocsProviders
65 }
66 ExtensionCategoryFilter::Snippets => ExtensionProvides::Snippets,
67 ExtensionCategoryFilter::DebugAdapters => ExtensionProvides::DebugAdapters,
68 });
69
70 let existing = workspace
71 .active_pane()
72 .read(cx)
73 .items()
74 .find_map(|item| item.downcast::<ExtensionsPage>());
75
76 if let Some(existing) = existing {
77 if provides_filter.is_some() {
78 existing.update(cx, |extensions_page, cx| {
79 extensions_page.change_provides_filter(provides_filter, cx);
80 });
81 }
82
83 workspace.activate_item(&existing, true, true, window, cx);
84 } else {
85 let extensions_page =
86 ExtensionsPage::new(workspace, provides_filter, window, cx);
87 workspace.add_item_to_active_pane(
88 Box::new(extensions_page),
89 None,
90 true,
91 window,
92 cx,
93 )
94 }
95 },
96 )
97 .register_action(move |workspace, _: &InstallDevExtension, window, cx| {
98 let store = ExtensionStore::global(cx);
99 let prompt = workspace.prompt_for_open_path(
100 gpui::PathPromptOptions {
101 files: false,
102 directories: true,
103 multiple: false,
104 },
105 DirectoryLister::Local(
106 workspace.project().clone(),
107 workspace.app_state().fs.clone(),
108 ),
109 window,
110 cx,
111 );
112
113 let workspace_handle = cx.entity().downgrade();
114 window
115 .spawn(cx, async move |cx| {
116 let extension_path =
117 match Flatten::flatten(prompt.await.map_err(|e| e.into())) {
118 Ok(Some(mut paths)) => paths.pop()?,
119 Ok(None) => return None,
120 Err(err) => {
121 workspace_handle
122 .update(cx, |workspace, cx| {
123 workspace.show_portal_error(err.to_string(), cx);
124 })
125 .ok();
126 return None;
127 }
128 };
129
130 let install_task = store
131 .update(cx, |store, cx| {
132 store.install_dev_extension(extension_path, cx)
133 })
134 .ok()?;
135
136 match install_task.await {
137 Ok(_) => {}
138 Err(err) => {
139 log::error!("Failed to install dev extension: {:?}", err);
140 workspace_handle
141 .update(cx, |workspace, cx| {
142 workspace.show_error(
143 // NOTE: using `anyhow::context` here ends up not printing
144 // the error
145 &format!("Failed to install dev extension: {}", err),
146 cx,
147 );
148 })
149 .ok();
150 }
151 }
152
153 Some(())
154 })
155 .detach();
156 });
157
158 cx.subscribe_in(workspace.project(), window, |_, _, event, window, cx| {
159 if let project::Event::LanguageNotFound(buffer) = event {
160 extension_suggest::suggest(buffer.clone(), window, cx);
161 }
162 })
163 .detach();
164 })
165 .detach();
166}
167
168fn extension_provides_label(provides: ExtensionProvides) -> &'static str {
169 match provides {
170 ExtensionProvides::Themes => "Themes",
171 ExtensionProvides::IconThemes => "Icon Themes",
172 ExtensionProvides::Languages => "Languages",
173 ExtensionProvides::Grammars => "Grammars",
174 ExtensionProvides::LanguageServers => "Language Servers",
175 ExtensionProvides::ContextServers => "MCP Servers",
176 ExtensionProvides::SlashCommands => "Slash Commands",
177 ExtensionProvides::IndexedDocsProviders => "Indexed Docs Providers",
178 ExtensionProvides::Snippets => "Snippets",
179 ExtensionProvides::DebugAdapters => "Debug Adapters",
180 }
181}
182
183#[derive(Clone)]
184pub enum ExtensionStatus {
185 NotInstalled,
186 Installing,
187 Upgrading,
188 Installed(Arc<str>),
189 Removing,
190}
191
192#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
193enum ExtensionFilter {
194 All,
195 Installed,
196 NotInstalled,
197}
198
199impl ExtensionFilter {
200 pub fn include_dev_extensions(&self) -> bool {
201 match self {
202 Self::All | Self::Installed => true,
203 Self::NotInstalled => false,
204 }
205 }
206}
207
208#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
209enum Feature {
210 Git,
211 OpenIn,
212 Vim,
213 LanguageBash,
214 LanguageC,
215 LanguageCpp,
216 LanguageGo,
217 LanguagePython,
218 LanguageReact,
219 LanguageRust,
220 LanguageTypescript,
221}
222
223fn keywords_by_feature() -> &'static BTreeMap<Feature, Vec<&'static str>> {
224 static KEYWORDS_BY_FEATURE: OnceLock<BTreeMap<Feature, Vec<&'static str>>> = OnceLock::new();
225 KEYWORDS_BY_FEATURE.get_or_init(|| {
226 BTreeMap::from_iter([
227 (Feature::Git, vec!["git"]),
228 (
229 Feature::OpenIn,
230 vec![
231 "github",
232 "gitlab",
233 "bitbucket",
234 "codeberg",
235 "sourcehut",
236 "permalink",
237 "link",
238 "open in",
239 ],
240 ),
241 (Feature::Vim, vec!["vim"]),
242 (Feature::LanguageBash, vec!["sh", "bash"]),
243 (Feature::LanguageC, vec!["c", "clang"]),
244 (Feature::LanguageCpp, vec!["c++", "cpp", "clang"]),
245 (Feature::LanguageGo, vec!["go", "golang"]),
246 (Feature::LanguagePython, vec!["python", "py"]),
247 (Feature::LanguageReact, vec!["react"]),
248 (Feature::LanguageRust, vec!["rust", "rs"]),
249 (
250 Feature::LanguageTypescript,
251 vec!["type", "typescript", "ts"],
252 ),
253 ])
254 })
255}
256
257struct ExtensionCardButtons {
258 install_or_uninstall: Button,
259 upgrade: Option<Button>,
260 configure: Option<Button>,
261}
262
263pub struct ExtensionsPage {
264 workspace: WeakEntity<Workspace>,
265 list: UniformListScrollHandle,
266 is_fetching_extensions: bool,
267 filter: ExtensionFilter,
268 remote_extension_entries: Vec<ExtensionMetadata>,
269 dev_extension_entries: Vec<Arc<ExtensionManifest>>,
270 filtered_remote_extension_indices: Vec<usize>,
271 query_editor: Entity<Editor>,
272 query_contains_error: bool,
273 provides_filter: Option<ExtensionProvides>,
274 _subscriptions: [gpui::Subscription; 2],
275 extension_fetch_task: Option<Task<()>>,
276 upsells: BTreeSet<Feature>,
277 scrollbar_state: ScrollbarState,
278}
279
280impl ExtensionsPage {
281 pub fn new(
282 workspace: &Workspace,
283 provides_filter: Option<ExtensionProvides>,
284 window: &mut Window,
285 cx: &mut Context<Workspace>,
286 ) -> Entity<Self> {
287 cx.new(|cx| {
288 let store = ExtensionStore::global(cx);
289 let workspace_handle = workspace.weak_handle();
290 let subscriptions = [
291 cx.observe(&store, |_: &mut Self, _, cx| cx.notify()),
292 cx.subscribe_in(
293 &store,
294 window,
295 move |this, _, event, window, cx| match event {
296 extension_host::Event::ExtensionsUpdated => {
297 this.fetch_extensions_debounced(None, cx)
298 }
299 extension_host::Event::ExtensionInstalled(extension_id) => this
300 .on_extension_installed(
301 workspace_handle.clone(),
302 extension_id,
303 window,
304 cx,
305 ),
306 _ => {}
307 },
308 ),
309 ];
310
311 let query_editor = cx.new(|cx| {
312 let mut input = Editor::single_line(window, cx);
313 input.set_placeholder_text("Search extensions...", cx);
314 input
315 });
316 cx.subscribe(&query_editor, Self::on_query_change).detach();
317
318 let scroll_handle = UniformListScrollHandle::new();
319
320 let mut this = Self {
321 workspace: workspace.weak_handle(),
322 list: scroll_handle.clone(),
323 is_fetching_extensions: false,
324 filter: ExtensionFilter::All,
325 dev_extension_entries: Vec::new(),
326 filtered_remote_extension_indices: Vec::new(),
327 remote_extension_entries: Vec::new(),
328 query_contains_error: false,
329 provides_filter,
330 extension_fetch_task: None,
331 _subscriptions: subscriptions,
332 query_editor,
333 upsells: BTreeSet::default(),
334 scrollbar_state: ScrollbarState::new(scroll_handle),
335 };
336 this.fetch_extensions(
337 None,
338 Some(BTreeSet::from_iter(this.provides_filter)),
339 None,
340 cx,
341 );
342 this
343 })
344 }
345
346 fn on_extension_installed(
347 &mut self,
348 workspace: WeakEntity<Workspace>,
349 extension_id: &str,
350 window: &mut Window,
351 cx: &mut Context<Self>,
352 ) {
353 let extension_store = ExtensionStore::global(cx).read(cx);
354 let themes = extension_store
355 .extension_themes(extension_id)
356 .map(|name| name.to_string())
357 .collect::<Vec<_>>();
358 if !themes.is_empty() {
359 workspace
360 .update(cx, |_workspace, cx| {
361 window.dispatch_action(
362 zed_actions::theme_selector::Toggle {
363 themes_filter: Some(themes),
364 }
365 .boxed_clone(),
366 cx,
367 );
368 })
369 .ok();
370 return;
371 }
372
373 let icon_themes = extension_store
374 .extension_icon_themes(extension_id)
375 .map(|name| name.to_string())
376 .collect::<Vec<_>>();
377 if !icon_themes.is_empty() {
378 workspace
379 .update(cx, |_workspace, cx| {
380 window.dispatch_action(
381 zed_actions::icon_theme_selector::Toggle {
382 themes_filter: Some(icon_themes),
383 }
384 .boxed_clone(),
385 cx,
386 );
387 })
388 .ok();
389 }
390 }
391
392 /// Returns whether a dev extension currently exists for the extension with the given ID.
393 fn dev_extension_exists(extension_id: &str, cx: &mut Context<Self>) -> bool {
394 let extension_store = ExtensionStore::global(cx).read(cx);
395
396 extension_store
397 .dev_extensions()
398 .any(|dev_extension| dev_extension.id.as_ref() == extension_id)
399 }
400
401 fn extension_status(extension_id: &str, cx: &mut Context<Self>) -> ExtensionStatus {
402 let extension_store = ExtensionStore::global(cx).read(cx);
403
404 match extension_store.outstanding_operations().get(extension_id) {
405 Some(ExtensionOperation::Install) => ExtensionStatus::Installing,
406 Some(ExtensionOperation::Remove) => ExtensionStatus::Removing,
407 Some(ExtensionOperation::Upgrade) => ExtensionStatus::Upgrading,
408 None => match extension_store.installed_extensions().get(extension_id) {
409 Some(extension) => ExtensionStatus::Installed(extension.manifest.version.clone()),
410 None => ExtensionStatus::NotInstalled,
411 },
412 }
413 }
414
415 fn filter_extension_entries(&mut self, cx: &mut Context<Self>) {
416 self.filtered_remote_extension_indices.clear();
417 self.filtered_remote_extension_indices.extend(
418 self.remote_extension_entries
419 .iter()
420 .enumerate()
421 .filter(|(_, extension)| match self.filter {
422 ExtensionFilter::All => true,
423 ExtensionFilter::Installed => {
424 let status = Self::extension_status(&extension.id, cx);
425 matches!(status, ExtensionStatus::Installed(_))
426 }
427 ExtensionFilter::NotInstalled => {
428 let status = Self::extension_status(&extension.id, cx);
429
430 matches!(status, ExtensionStatus::NotInstalled)
431 }
432 })
433 .map(|(ix, _)| ix),
434 );
435 cx.notify();
436 }
437
438 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
439 self.list.set_offset(point(px(0.), px(0.)));
440 cx.notify();
441 }
442
443 fn fetch_extensions(
444 &mut self,
445 search: Option<String>,
446 provides_filter: Option<BTreeSet<ExtensionProvides>>,
447 on_complete: Option<Box<dyn FnOnce(&mut Self, &mut Context<Self>) + Send>>,
448 cx: &mut Context<Self>,
449 ) {
450 self.is_fetching_extensions = true;
451 cx.notify();
452
453 let extension_store = ExtensionStore::global(cx);
454
455 let dev_extensions = extension_store
456 .read(cx)
457 .dev_extensions()
458 .cloned()
459 .collect::<Vec<_>>();
460
461 let remote_extensions = extension_store.update(cx, |store, cx| {
462 store.fetch_extensions(search.as_deref(), provides_filter.as_ref(), cx)
463 });
464
465 cx.spawn(async move |this, cx| {
466 let dev_extensions = if let Some(search) = search {
467 let match_candidates = dev_extensions
468 .iter()
469 .enumerate()
470 .map(|(ix, manifest)| StringMatchCandidate::new(ix, &manifest.name))
471 .collect::<Vec<_>>();
472
473 let matches = match_strings(
474 &match_candidates,
475 &search,
476 false,
477 match_candidates.len(),
478 &Default::default(),
479 cx.background_executor().clone(),
480 )
481 .await;
482 matches
483 .into_iter()
484 .map(|mat| dev_extensions[mat.candidate_id].clone())
485 .collect()
486 } else {
487 dev_extensions
488 };
489
490 let fetch_result = remote_extensions.await;
491 this.update(cx, |this, cx| {
492 cx.notify();
493 this.dev_extension_entries = dev_extensions;
494 this.is_fetching_extensions = false;
495 this.remote_extension_entries = fetch_result?;
496 this.filter_extension_entries(cx);
497 if let Some(callback) = on_complete {
498 callback(this, cx);
499 }
500 anyhow::Ok(())
501 })?
502 })
503 .detach_and_log_err(cx);
504 }
505
506 fn render_extensions(
507 &mut self,
508 range: Range<usize>,
509 _: &mut Window,
510 cx: &mut Context<Self>,
511 ) -> Vec<ExtensionCard> {
512 let dev_extension_entries_len = if self.filter.include_dev_extensions() {
513 self.dev_extension_entries.len()
514 } else {
515 0
516 };
517 range
518 .map(|ix| {
519 if ix < dev_extension_entries_len {
520 let extension = &self.dev_extension_entries[ix];
521 self.render_dev_extension(extension, cx)
522 } else {
523 let extension_ix =
524 self.filtered_remote_extension_indices[ix - dev_extension_entries_len];
525 let extension = &self.remote_extension_entries[extension_ix];
526 self.render_remote_extension(extension, cx)
527 }
528 })
529 .collect()
530 }
531
532 fn render_dev_extension(
533 &self,
534 extension: &ExtensionManifest,
535 cx: &mut Context<Self>,
536 ) -> ExtensionCard {
537 let status = Self::extension_status(&extension.id, cx);
538
539 let repository_url = extension.repository.clone();
540
541 let can_configure = !extension.context_servers.is_empty();
542
543 ExtensionCard::new()
544 .child(
545 h_flex()
546 .justify_between()
547 .child(
548 h_flex()
549 .gap_2()
550 .items_end()
551 .child(Headline::new(extension.name.clone()).size(HeadlineSize::Medium))
552 .child(
553 Headline::new(format!("v{}", extension.version))
554 .size(HeadlineSize::XSmall),
555 ),
556 )
557 .child(
558 h_flex()
559 .gap_1()
560 .justify_between()
561 .child(
562 Button::new(
563 SharedString::from(format!("rebuild-{}", extension.id)),
564 "Rebuild",
565 )
566 .color(Color::Accent)
567 .disabled(matches!(status, ExtensionStatus::Upgrading))
568 .on_click({
569 let extension_id = extension.id.clone();
570 move |_, _, cx| {
571 ExtensionStore::global(cx).update(cx, |store, cx| {
572 store.rebuild_dev_extension(extension_id.clone(), cx)
573 });
574 }
575 }),
576 )
577 .child(
578 Button::new(SharedString::from(extension.id.clone()), "Uninstall")
579 .color(Color::Accent)
580 .disabled(matches!(status, ExtensionStatus::Removing))
581 .on_click({
582 let extension_id = extension.id.clone();
583 move |_, _, cx| {
584 ExtensionStore::global(cx).update(cx, |store, cx| {
585 store.uninstall_extension(extension_id.clone(), cx)
586 });
587 }
588 }),
589 )
590 .when(can_configure, |this| {
591 this.child(
592 Button::new(
593 SharedString::from(format!("configure-{}", extension.id)),
594 "Configure",
595 )
596 .color(Color::Accent)
597 .disabled(matches!(status, ExtensionStatus::Installing))
598 .on_click({
599 let manifest = Arc::new(extension.clone());
600 move |_, _, cx| {
601 if let Some(events) =
602 extension::ExtensionEvents::try_global(cx)
603 {
604 events.update(cx, |this, cx| {
605 this.emit(
606 extension::Event::ConfigureExtensionRequested(
607 manifest.clone(),
608 ),
609 cx,
610 )
611 });
612 }
613 }
614 }),
615 )
616 }),
617 ),
618 )
619 .child(
620 h_flex()
621 .gap_2()
622 .justify_between()
623 .child(
624 Label::new(format!(
625 "{}: {}",
626 if extension.authors.len() > 1 {
627 "Authors"
628 } else {
629 "Author"
630 },
631 extension.authors.join(", ")
632 ))
633 .size(LabelSize::Small)
634 .color(Color::Muted)
635 .truncate(),
636 )
637 .child(Label::new("<>").size(LabelSize::Small)),
638 )
639 .child(
640 h_flex()
641 .gap_2()
642 .justify_between()
643 .children(extension.description.as_ref().map(|description| {
644 Label::new(description.clone())
645 .size(LabelSize::Small)
646 .color(Color::Default)
647 .truncate()
648 }))
649 .children(repository_url.map(|repository_url| {
650 IconButton::new(
651 SharedString::from(format!("repository-{}", extension.id)),
652 IconName::Github,
653 )
654 .icon_color(Color::Accent)
655 .icon_size(IconSize::Small)
656 .on_click(cx.listener({
657 let repository_url = repository_url.clone();
658 move |_, _, _, cx| {
659 cx.open_url(&repository_url);
660 }
661 }))
662 .tooltip(Tooltip::text(repository_url.clone()))
663 })),
664 )
665 }
666
667 fn render_remote_extension(
668 &self,
669 extension: &ExtensionMetadata,
670 cx: &mut Context<Self>,
671 ) -> ExtensionCard {
672 let this = cx.entity().clone();
673 let status = Self::extension_status(&extension.id, cx);
674 let has_dev_extension = Self::dev_extension_exists(&extension.id, cx);
675
676 let extension_id = extension.id.clone();
677 let buttons = self.buttons_for_entry(extension, &status, has_dev_extension, cx);
678 let version = extension.manifest.version.clone();
679 let repository_url = extension.manifest.repository.clone();
680 let authors = extension.manifest.authors.clone();
681
682 let installed_version = match status {
683 ExtensionStatus::Installed(installed_version) => Some(installed_version),
684 _ => None,
685 };
686
687 ExtensionCard::new()
688 .overridden_by_dev_extension(has_dev_extension)
689 .child(
690 h_flex()
691 .justify_between()
692 .child(
693 h_flex()
694 .gap_2()
695 .child(
696 Headline::new(extension.manifest.name.clone())
697 .size(HeadlineSize::Medium),
698 )
699 .child(Headline::new(format!("v{version}")).size(HeadlineSize::XSmall))
700 .children(
701 installed_version
702 .filter(|installed_version| *installed_version != version)
703 .map(|installed_version| {
704 Headline::new(format!("(v{installed_version} installed)",))
705 .size(HeadlineSize::XSmall)
706 }),
707 )
708 .map(|parent| {
709 if extension.manifest.provides.is_empty() {
710 return parent;
711 }
712
713 parent.child(
714 h_flex().gap_2().children(
715 extension
716 .manifest
717 .provides
718 .iter()
719 .map(|provides| {
720 div()
721 .bg(cx.theme().colors().element_background)
722 .px_0p5()
723 .border_1()
724 .border_color(cx.theme().colors().border)
725 .rounded_sm()
726 .child(
727 Label::new(extension_provides_label(
728 *provides,
729 ))
730 .size(LabelSize::XSmall),
731 )
732 })
733 .collect::<Vec<_>>(),
734 ),
735 )
736 }),
737 )
738 .child(
739 h_flex()
740 .gap_2()
741 .justify_between()
742 .children(buttons.upgrade)
743 .children(buttons.configure)
744 .child(buttons.install_or_uninstall),
745 ),
746 )
747 .child(
748 h_flex()
749 .gap_2()
750 .justify_between()
751 .child(
752 Label::new(format!(
753 "{}: {}",
754 if extension.manifest.authors.len() > 1 {
755 "Authors"
756 } else {
757 "Author"
758 },
759 extension.manifest.authors.join(", ")
760 ))
761 .size(LabelSize::Small)
762 .color(Color::Muted)
763 .truncate(),
764 )
765 .child(
766 Label::new(format!(
767 "Downloads: {}",
768 extension.download_count.to_formatted_string(&Locale::en)
769 ))
770 .size(LabelSize::Small),
771 ),
772 )
773 .child(
774 h_flex()
775 .gap_2()
776 .justify_between()
777 .children(extension.manifest.description.as_ref().map(|description| {
778 Label::new(description.clone())
779 .size(LabelSize::Small)
780 .color(Color::Default)
781 .truncate()
782 }))
783 .child(
784 h_flex()
785 .gap_2()
786 .child(
787 IconButton::new(
788 SharedString::from(format!("repository-{}", extension.id)),
789 IconName::Github,
790 )
791 .icon_color(Color::Accent)
792 .icon_size(IconSize::Small)
793 .on_click(cx.listener({
794 let repository_url = repository_url.clone();
795 move |_, _, _, cx| {
796 cx.open_url(&repository_url);
797 }
798 }))
799 .tooltip(Tooltip::text(repository_url.clone())),
800 )
801 .child(
802 PopoverMenu::new(SharedString::from(format!(
803 "more-{}",
804 extension.id
805 )))
806 .trigger(
807 IconButton::new(
808 SharedString::from(format!("more-{}", extension.id)),
809 IconName::Ellipsis,
810 )
811 .icon_color(Color::Accent)
812 .icon_size(IconSize::Small),
813 )
814 .menu(move |window, cx| {
815 Some(Self::render_remote_extension_context_menu(
816 &this,
817 extension_id.clone(),
818 authors.clone(),
819 window,
820 cx,
821 ))
822 }),
823 ),
824 ),
825 )
826 }
827
828 fn render_remote_extension_context_menu(
829 this: &Entity<Self>,
830 extension_id: Arc<str>,
831 authors: Vec<String>,
832 window: &mut Window,
833 cx: &mut App,
834 ) -> Entity<ContextMenu> {
835 let context_menu = ContextMenu::build(window, cx, |context_menu, window, _| {
836 context_menu
837 .entry(
838 "Install Another Version...",
839 None,
840 window.handler_for(this, {
841 let extension_id = extension_id.clone();
842 move |this, window, cx| {
843 this.show_extension_version_list(extension_id.clone(), window, cx)
844 }
845 }),
846 )
847 .entry("Copy Extension ID", None, {
848 let extension_id = extension_id.clone();
849 move |_, cx| {
850 cx.write_to_clipboard(ClipboardItem::new_string(extension_id.to_string()));
851 }
852 })
853 .entry("Copy Author Info", None, {
854 let authors = authors.clone();
855 move |_, cx| {
856 cx.write_to_clipboard(ClipboardItem::new_string(authors.join(", ")));
857 }
858 })
859 });
860
861 context_menu
862 }
863
864 fn show_extension_version_list(
865 &mut self,
866 extension_id: Arc<str>,
867 window: &mut Window,
868 cx: &mut Context<Self>,
869 ) {
870 let Some(workspace) = self.workspace.upgrade() else {
871 return;
872 };
873
874 cx.spawn_in(window, async move |this, cx| {
875 let extension_versions_task = this.update(cx, |_, cx| {
876 let extension_store = ExtensionStore::global(cx);
877
878 extension_store.update(cx, |store, cx| {
879 store.fetch_extension_versions(&extension_id, cx)
880 })
881 })?;
882
883 let extension_versions = extension_versions_task.await?;
884
885 workspace.update_in(cx, |workspace, window, cx| {
886 let fs = workspace.project().read(cx).fs().clone();
887 workspace.toggle_modal(window, cx, |window, cx| {
888 let delegate = ExtensionVersionSelectorDelegate::new(
889 fs,
890 cx.entity().downgrade(),
891 extension_versions,
892 );
893
894 ExtensionVersionSelector::new(delegate, window, cx)
895 });
896 })?;
897
898 anyhow::Ok(())
899 })
900 .detach_and_log_err(cx);
901 }
902
903 fn buttons_for_entry(
904 &self,
905 extension: &ExtensionMetadata,
906 status: &ExtensionStatus,
907 has_dev_extension: bool,
908 cx: &mut Context<Self>,
909 ) -> ExtensionCardButtons {
910 let is_compatible =
911 extension_host::is_version_compatible(ReleaseChannel::global(cx), extension);
912
913 if has_dev_extension {
914 // If we have a dev extension for the given extension, just treat it as uninstalled.
915 // The button here is a placeholder, as it won't be interactable anyways.
916 return ExtensionCardButtons {
917 install_or_uninstall: Button::new(
918 SharedString::from(extension.id.clone()),
919 "Install",
920 ),
921 configure: None,
922 upgrade: None,
923 };
924 }
925
926 let is_configurable = extension
927 .manifest
928 .provides
929 .contains(&ExtensionProvides::ContextServers);
930
931 match status.clone() {
932 ExtensionStatus::NotInstalled => ExtensionCardButtons {
933 install_or_uninstall: Button::new(
934 SharedString::from(extension.id.clone()),
935 "Install",
936 )
937 .on_click({
938 let extension_id = extension.id.clone();
939 move |_, _, cx| {
940 telemetry::event!("Extension Installed");
941 ExtensionStore::global(cx).update(cx, |store, cx| {
942 store.install_latest_extension(extension_id.clone(), cx)
943 });
944 }
945 }),
946 configure: None,
947 upgrade: None,
948 },
949 ExtensionStatus::Installing => ExtensionCardButtons {
950 install_or_uninstall: Button::new(
951 SharedString::from(extension.id.clone()),
952 "Install",
953 )
954 .disabled(true),
955 configure: None,
956 upgrade: None,
957 },
958 ExtensionStatus::Upgrading => ExtensionCardButtons {
959 install_or_uninstall: Button::new(
960 SharedString::from(extension.id.clone()),
961 "Uninstall",
962 )
963 .disabled(true),
964 configure: is_configurable.then(|| {
965 Button::new(
966 SharedString::from(format!("configure-{}", extension.id)),
967 "Configure",
968 )
969 .disabled(true)
970 }),
971 upgrade: Some(
972 Button::new(SharedString::from(extension.id.clone()), "Upgrade").disabled(true),
973 ),
974 },
975 ExtensionStatus::Installed(installed_version) => ExtensionCardButtons {
976 install_or_uninstall: Button::new(
977 SharedString::from(extension.id.clone()),
978 "Uninstall",
979 )
980 .on_click({
981 let extension_id = extension.id.clone();
982 move |_, _, cx| {
983 telemetry::event!("Extension Uninstalled", extension_id);
984 ExtensionStore::global(cx).update(cx, |store, cx| {
985 store.uninstall_extension(extension_id.clone(), cx)
986 });
987 }
988 }),
989 configure: is_configurable.then(|| {
990 Button::new(
991 SharedString::from(format!("configure-{}", extension.id)),
992 "Configure",
993 )
994 .on_click({
995 let extension_id = extension.id.clone();
996 move |_, _, cx| {
997 if let Some(manifest) = ExtensionStore::global(cx)
998 .read(cx)
999 .extension_manifest_for_id(&extension_id)
1000 .cloned()
1001 {
1002 if let Some(events) = extension::ExtensionEvents::try_global(cx) {
1003 events.update(cx, |this, cx| {
1004 this.emit(
1005 extension::Event::ConfigureExtensionRequested(manifest),
1006 cx,
1007 )
1008 });
1009 }
1010 }
1011 }
1012 })
1013 }),
1014 upgrade: if installed_version == extension.manifest.version {
1015 None
1016 } else {
1017 Some(
1018 Button::new(SharedString::from(extension.id.clone()), "Upgrade")
1019 .when(!is_compatible, |upgrade_button| {
1020 upgrade_button.disabled(true).tooltip({
1021 let version = extension.manifest.version.clone();
1022 move |_, cx| {
1023 Tooltip::simple(
1024 format!(
1025 "v{version} is not compatible with this version of Zed.",
1026 ),
1027 cx,
1028 )
1029 }
1030 })
1031 })
1032 .disabled(!is_compatible)
1033 .on_click({
1034 let extension_id = extension.id.clone();
1035 let version = extension.manifest.version.clone();
1036 move |_, _, cx| {
1037 telemetry::event!("Extension Installed", extension_id, version);
1038 ExtensionStore::global(cx).update(cx, |store, cx| {
1039 store
1040 .upgrade_extension(
1041 extension_id.clone(),
1042 version.clone(),
1043 cx,
1044 )
1045 .detach_and_log_err(cx)
1046 });
1047 }
1048 }),
1049 )
1050 },
1051 },
1052 ExtensionStatus::Removing => ExtensionCardButtons {
1053 install_or_uninstall: Button::new(
1054 SharedString::from(extension.id.clone()),
1055 "Uninstall",
1056 )
1057 .disabled(true),
1058 configure: is_configurable.then(|| {
1059 Button::new(
1060 SharedString::from(format!("configure-{}", extension.id)),
1061 "Configure",
1062 )
1063 .disabled(true)
1064 }),
1065 upgrade: None,
1066 },
1067 }
1068 }
1069
1070 fn render_search(&self, cx: &mut Context<Self>) -> Div {
1071 let mut key_context = KeyContext::new_with_defaults();
1072 key_context.add("BufferSearchBar");
1073
1074 let editor_border = if self.query_contains_error {
1075 Color::Error.color(cx)
1076 } else {
1077 cx.theme().colors().border
1078 };
1079
1080 h_flex()
1081 .key_context(key_context)
1082 .h_8()
1083 .flex_1()
1084 .min_w(rems_from_px(384.))
1085 .pl_1p5()
1086 .pr_2()
1087 .py_1()
1088 .gap_2()
1089 .border_1()
1090 .border_color(editor_border)
1091 .rounded_lg()
1092 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1093 .child(self.render_text_input(&self.query_editor, cx))
1094 }
1095
1096 fn render_text_input(
1097 &self,
1098 editor: &Entity<Editor>,
1099 cx: &mut Context<Self>,
1100 ) -> impl IntoElement {
1101 let settings = ThemeSettings::get_global(cx);
1102 let text_style = TextStyle {
1103 color: if editor.read(cx).read_only(cx) {
1104 cx.theme().colors().text_disabled
1105 } else {
1106 cx.theme().colors().text
1107 },
1108 font_family: settings.ui_font.family.clone(),
1109 font_features: settings.ui_font.features.clone(),
1110 font_fallbacks: settings.ui_font.fallbacks.clone(),
1111 font_size: rems(0.875).into(),
1112 font_weight: settings.ui_font.weight,
1113 line_height: relative(1.3),
1114 ..Default::default()
1115 };
1116
1117 EditorElement::new(
1118 editor,
1119 EditorStyle {
1120 background: cx.theme().colors().editor_background,
1121 local_player: cx.theme().players().local(),
1122 text: text_style,
1123 ..Default::default()
1124 },
1125 )
1126 }
1127
1128 fn on_query_change(
1129 &mut self,
1130 _: Entity<Editor>,
1131 event: &editor::EditorEvent,
1132 cx: &mut Context<Self>,
1133 ) {
1134 if let editor::EditorEvent::Edited { .. } = event {
1135 self.query_contains_error = false;
1136 self.refresh_search(cx);
1137 }
1138 }
1139
1140 fn refresh_search(&mut self, cx: &mut Context<Self>) {
1141 self.fetch_extensions_debounced(
1142 Some(Box::new(|this, cx| {
1143 this.scroll_to_top(cx);
1144 })),
1145 cx,
1146 );
1147 self.refresh_feature_upsells(cx);
1148 }
1149
1150 pub fn change_provides_filter(
1151 &mut self,
1152 provides_filter: Option<ExtensionProvides>,
1153 cx: &mut Context<Self>,
1154 ) {
1155 self.provides_filter = provides_filter;
1156 self.refresh_search(cx);
1157 }
1158
1159 fn fetch_extensions_debounced(
1160 &mut self,
1161 on_complete: Option<Box<dyn FnOnce(&mut Self, &mut Context<Self>) + Send>>,
1162 cx: &mut Context<ExtensionsPage>,
1163 ) {
1164 self.extension_fetch_task = Some(cx.spawn(async move |this, cx| {
1165 let search = this
1166 .update(cx, |this, cx| this.search_query(cx))
1167 .ok()
1168 .flatten();
1169
1170 // Only debounce the fetching of extensions if we have a search
1171 // query.
1172 //
1173 // If the search was just cleared then we can just reload the list
1174 // of extensions without a debounce, which allows us to avoid seeing
1175 // an intermittent flash of a "no extensions" state.
1176 if search.is_some() {
1177 cx.background_executor()
1178 .timer(Duration::from_millis(250))
1179 .await;
1180 };
1181
1182 this.update(cx, |this, cx| {
1183 this.fetch_extensions(
1184 search,
1185 Some(BTreeSet::from_iter(this.provides_filter)),
1186 on_complete,
1187 cx,
1188 );
1189 })
1190 .ok();
1191 }));
1192 }
1193
1194 pub fn search_query(&self, cx: &mut App) -> Option<String> {
1195 let search = self.query_editor.read(cx).text(cx);
1196 if search.trim().is_empty() {
1197 None
1198 } else {
1199 Some(search)
1200 }
1201 }
1202
1203 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
1204 let has_search = self.search_query(cx).is_some();
1205
1206 let message = if self.is_fetching_extensions {
1207 "Loading extensions..."
1208 } else {
1209 match self.filter {
1210 ExtensionFilter::All => {
1211 if has_search {
1212 "No extensions that match your search."
1213 } else {
1214 "No extensions."
1215 }
1216 }
1217 ExtensionFilter::Installed => {
1218 if has_search {
1219 "No installed extensions that match your search."
1220 } else {
1221 "No installed extensions."
1222 }
1223 }
1224 ExtensionFilter::NotInstalled => {
1225 if has_search {
1226 "No not installed extensions that match your search."
1227 } else {
1228 "No not installed extensions."
1229 }
1230 }
1231 }
1232 };
1233
1234 Label::new(message)
1235 }
1236
1237 fn update_settings<T: Settings>(
1238 &mut self,
1239 selection: &ToggleState,
1240
1241 cx: &mut Context<Self>,
1242 callback: impl 'static + Send + Fn(&mut T::FileContent, bool),
1243 ) {
1244 if let Some(workspace) = self.workspace.upgrade() {
1245 let fs = workspace.read(cx).app_state().fs.clone();
1246 let selection = *selection;
1247 settings::update_settings_file::<T>(fs, cx, move |settings, _| {
1248 let value = match selection {
1249 ToggleState::Unselected => false,
1250 ToggleState::Selected => true,
1251 _ => return,
1252 };
1253
1254 callback(settings, value)
1255 });
1256 }
1257 }
1258
1259 fn refresh_feature_upsells(&mut self, cx: &mut Context<Self>) {
1260 let Some(search) = self.search_query(cx) else {
1261 self.upsells.clear();
1262 return;
1263 };
1264
1265 let search = search.to_lowercase();
1266 let search_terms = search
1267 .split_whitespace()
1268 .map(|term| term.trim())
1269 .collect::<Vec<_>>();
1270
1271 for (feature, keywords) in keywords_by_feature() {
1272 if keywords
1273 .iter()
1274 .any(|keyword| search_terms.contains(keyword))
1275 {
1276 self.upsells.insert(*feature);
1277 } else {
1278 self.upsells.remove(feature);
1279 }
1280 }
1281 }
1282
1283 fn render_feature_upsells(&self, cx: &mut Context<Self>) -> impl IntoElement {
1284 let upsells_count = self.upsells.len();
1285
1286 v_flex().children(self.upsells.iter().enumerate().map(|(ix, feature)| {
1287 let upsell = match feature {
1288 Feature::Git => FeatureUpsell::new(
1289 "Zed comes with basic Git support. More Git features are coming in the future.",
1290 )
1291 .docs_url("https://zed.dev/docs/git"),
1292 Feature::OpenIn => FeatureUpsell::new(
1293 "Zed supports linking to a source line on GitHub and others.",
1294 )
1295 .docs_url("https://zed.dev/docs/git#git-integrations"),
1296 Feature::Vim => FeatureUpsell::new("Vim support is built-in to Zed!")
1297 .docs_url("https://zed.dev/docs/vim")
1298 .child(CheckboxWithLabel::new(
1299 "enable-vim",
1300 Label::new("Enable vim mode"),
1301 if VimModeSetting::get_global(cx).0 {
1302 ui::ToggleState::Selected
1303 } else {
1304 ui::ToggleState::Unselected
1305 },
1306 cx.listener(move |this, selection, _, cx| {
1307 telemetry::event!("Vim Mode Toggled", source = "Feature Upsell");
1308 this.update_settings::<VimModeSetting>(
1309 selection,
1310 cx,
1311 |setting, value| *setting = Some(value),
1312 );
1313 }),
1314 )),
1315 Feature::LanguageBash => FeatureUpsell::new("Shell support is built-in to Zed!")
1316 .docs_url("https://zed.dev/docs/languages/bash"),
1317 Feature::LanguageC => FeatureUpsell::new("C support is built-in to Zed!")
1318 .docs_url("https://zed.dev/docs/languages/c"),
1319 Feature::LanguageCpp => FeatureUpsell::new("C++ support is built-in to Zed!")
1320 .docs_url("https://zed.dev/docs/languages/cpp"),
1321 Feature::LanguageGo => FeatureUpsell::new("Go support is built-in to Zed!")
1322 .docs_url("https://zed.dev/docs/languages/go"),
1323 Feature::LanguagePython => FeatureUpsell::new("Python support is built-in to Zed!")
1324 .docs_url("https://zed.dev/docs/languages/python"),
1325 Feature::LanguageReact => FeatureUpsell::new("React support is built-in to Zed!")
1326 .docs_url("https://zed.dev/docs/languages/typescript"),
1327 Feature::LanguageRust => FeatureUpsell::new("Rust support is built-in to Zed!")
1328 .docs_url("https://zed.dev/docs/languages/rust"),
1329 Feature::LanguageTypescript => {
1330 FeatureUpsell::new("Typescript support is built-in to Zed!")
1331 .docs_url("https://zed.dev/docs/languages/typescript")
1332 }
1333 };
1334
1335 upsell.when(ix < upsells_count, |upsell| upsell.border_b_1())
1336 }))
1337 }
1338}
1339
1340impl Render for ExtensionsPage {
1341 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1342 v_flex()
1343 .size_full()
1344 .bg(cx.theme().colors().editor_background)
1345 .child(
1346 v_flex()
1347 .gap_4()
1348 .pt_4()
1349 .px_4()
1350 .bg(cx.theme().colors().editor_background)
1351 .child(
1352 h_flex()
1353 .w_full()
1354 .gap_2()
1355 .justify_between()
1356 .child(Headline::new("Extensions").size(HeadlineSize::XLarge))
1357 .child(
1358 Button::new("install-dev-extension", "Install Dev Extension")
1359 .style(ButtonStyle::Filled)
1360 .size(ButtonSize::Large)
1361 .on_click(|_event, window, cx| {
1362 window.dispatch_action(Box::new(InstallDevExtension), cx)
1363 }),
1364 ),
1365 )
1366 .child(
1367 h_flex()
1368 .w_full()
1369 .gap_4()
1370 .flex_wrap()
1371 .child(self.render_search(cx))
1372 .child(
1373 h_flex()
1374 .child(
1375 ToggleButton::new("filter-all", "All")
1376 .style(ButtonStyle::Filled)
1377 .size(ButtonSize::Large)
1378 .toggle_state(self.filter == ExtensionFilter::All)
1379 .on_click(cx.listener(|this, _event, _, cx| {
1380 this.filter = ExtensionFilter::All;
1381 this.filter_extension_entries(cx);
1382 this.scroll_to_top(cx);
1383 }))
1384 .tooltip(move |_, cx| {
1385 Tooltip::simple("Show all extensions", cx)
1386 })
1387 .first(),
1388 )
1389 .child(
1390 ToggleButton::new("filter-installed", "Installed")
1391 .style(ButtonStyle::Filled)
1392 .size(ButtonSize::Large)
1393 .toggle_state(self.filter == ExtensionFilter::Installed)
1394 .on_click(cx.listener(|this, _event, _, cx| {
1395 this.filter = ExtensionFilter::Installed;
1396 this.filter_extension_entries(cx);
1397 this.scroll_to_top(cx);
1398 }))
1399 .tooltip(move |_, cx| {
1400 Tooltip::simple("Show installed extensions", cx)
1401 })
1402 .middle(),
1403 )
1404 .child(
1405 ToggleButton::new("filter-not-installed", "Not Installed")
1406 .style(ButtonStyle::Filled)
1407 .size(ButtonSize::Large)
1408 .toggle_state(
1409 self.filter == ExtensionFilter::NotInstalled,
1410 )
1411 .on_click(cx.listener(|this, _event, _, cx| {
1412 this.filter = ExtensionFilter::NotInstalled;
1413 this.filter_extension_entries(cx);
1414 this.scroll_to_top(cx);
1415 }))
1416 .tooltip(move |_, cx| {
1417 Tooltip::simple("Show not installed extensions", cx)
1418 })
1419 .last(),
1420 ),
1421 ),
1422 ),
1423 )
1424 .child(
1425 h_flex()
1426 .id("filter-row")
1427 .gap_2()
1428 .py_2p5()
1429 .px_4()
1430 .border_b_1()
1431 .border_color(cx.theme().colors().border_variant)
1432 .overflow_x_scroll()
1433 .child(
1434 Button::new("filter-all-categories", "All")
1435 .when(self.provides_filter.is_none(), |button| {
1436 button.style(ButtonStyle::Filled)
1437 })
1438 .when(self.provides_filter.is_some(), |button| {
1439 button.style(ButtonStyle::Subtle)
1440 })
1441 .toggle_state(self.provides_filter.is_none())
1442 .on_click(cx.listener(|this, _event, _, cx| {
1443 this.change_provides_filter(None, cx);
1444 })),
1445 )
1446 .children(ExtensionProvides::iter().map(|provides| {
1447 let label = extension_provides_label(provides);
1448 Button::new(
1449 SharedString::from(format!("filter-category-{}", label)),
1450 label,
1451 )
1452 .style(if self.provides_filter == Some(provides) {
1453 ButtonStyle::Filled
1454 } else {
1455 ButtonStyle::Subtle
1456 })
1457 .toggle_state(self.provides_filter == Some(provides))
1458 .on_click({
1459 cx.listener(move |this, _event, _, cx| {
1460 this.change_provides_filter(Some(provides), cx);
1461 })
1462 })
1463 })),
1464 )
1465 .child(self.render_feature_upsells(cx))
1466 .child(
1467 v_flex()
1468 .pl_4()
1469 .pr_6()
1470 .size_full()
1471 .overflow_y_hidden()
1472 .map(|this| {
1473 let mut count = self.filtered_remote_extension_indices.len();
1474 if self.filter.include_dev_extensions() {
1475 count += self.dev_extension_entries.len();
1476 }
1477
1478 if count == 0 {
1479 return this.py_4().child(self.render_empty_state(cx));
1480 }
1481
1482 let scroll_handle = self.list.clone();
1483 this.child(
1484 uniform_list("entries", count, cx.processor(Self::render_extensions))
1485 .flex_grow()
1486 .pb_4()
1487 .track_scroll(scroll_handle),
1488 )
1489 .child(
1490 div()
1491 .absolute()
1492 .right_1()
1493 .top_0()
1494 .bottom_0()
1495 .w(px(12.))
1496 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1497 )
1498 }),
1499 )
1500 }
1501}
1502
1503impl EventEmitter<ItemEvent> for ExtensionsPage {}
1504
1505impl Focusable for ExtensionsPage {
1506 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1507 self.query_editor.read(cx).focus_handle(cx)
1508 }
1509}
1510
1511impl Item for ExtensionsPage {
1512 type Event = ItemEvent;
1513
1514 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1515 "Extensions".into()
1516 }
1517
1518 fn telemetry_event_text(&self) -> Option<&'static str> {
1519 Some("Extensions Page Opened")
1520 }
1521
1522 fn show_toolbar(&self) -> bool {
1523 false
1524 }
1525
1526 fn clone_on_split(
1527 &self,
1528 _workspace_id: Option<WorkspaceId>,
1529 _window: &mut Window,
1530 _: &mut Context<Self>,
1531 ) -> Option<Entity<Self>> {
1532 None
1533 }
1534
1535 fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
1536 f(*event)
1537 }
1538}