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 true,
478 match_candidates.len(),
479 &Default::default(),
480 cx.background_executor().clone(),
481 )
482 .await;
483 matches
484 .into_iter()
485 .map(|mat| dev_extensions[mat.candidate_id].clone())
486 .collect()
487 } else {
488 dev_extensions
489 };
490
491 let fetch_result = remote_extensions.await;
492 this.update(cx, |this, cx| {
493 cx.notify();
494 this.dev_extension_entries = dev_extensions;
495 this.is_fetching_extensions = false;
496 this.remote_extension_entries = fetch_result?;
497 this.filter_extension_entries(cx);
498 if let Some(callback) = on_complete {
499 callback(this, cx);
500 }
501 anyhow::Ok(())
502 })?
503 })
504 .detach_and_log_err(cx);
505 }
506
507 fn render_extensions(
508 &mut self,
509 range: Range<usize>,
510 _: &mut Window,
511 cx: &mut Context<Self>,
512 ) -> Vec<ExtensionCard> {
513 let dev_extension_entries_len = if self.filter.include_dev_extensions() {
514 self.dev_extension_entries.len()
515 } else {
516 0
517 };
518 range
519 .map(|ix| {
520 if ix < dev_extension_entries_len {
521 let extension = &self.dev_extension_entries[ix];
522 self.render_dev_extension(extension, cx)
523 } else {
524 let extension_ix =
525 self.filtered_remote_extension_indices[ix - dev_extension_entries_len];
526 let extension = &self.remote_extension_entries[extension_ix];
527 self.render_remote_extension(extension, cx)
528 }
529 })
530 .collect()
531 }
532
533 fn render_dev_extension(
534 &self,
535 extension: &ExtensionManifest,
536 cx: &mut Context<Self>,
537 ) -> ExtensionCard {
538 let status = Self::extension_status(&extension.id, cx);
539
540 let repository_url = extension.repository.clone();
541
542 let can_configure = !extension.context_servers.is_empty();
543
544 ExtensionCard::new()
545 .child(
546 h_flex()
547 .justify_between()
548 .child(
549 h_flex()
550 .gap_2()
551 .items_end()
552 .child(Headline::new(extension.name.clone()).size(HeadlineSize::Medium))
553 .child(
554 Headline::new(format!("v{}", extension.version))
555 .size(HeadlineSize::XSmall),
556 ),
557 )
558 .child(
559 h_flex()
560 .gap_1()
561 .justify_between()
562 .child(
563 Button::new(
564 SharedString::from(format!("rebuild-{}", extension.id)),
565 "Rebuild",
566 )
567 .color(Color::Accent)
568 .disabled(matches!(status, ExtensionStatus::Upgrading))
569 .on_click({
570 let extension_id = extension.id.clone();
571 move |_, _, cx| {
572 ExtensionStore::global(cx).update(cx, |store, cx| {
573 store.rebuild_dev_extension(extension_id.clone(), cx)
574 });
575 }
576 }),
577 )
578 .child(
579 Button::new(SharedString::from(extension.id.clone()), "Uninstall")
580 .color(Color::Accent)
581 .disabled(matches!(status, ExtensionStatus::Removing))
582 .on_click({
583 let extension_id = extension.id.clone();
584 move |_, _, cx| {
585 ExtensionStore::global(cx).update(cx, |store, cx| {
586 store.uninstall_extension(extension_id.clone(), cx)
587 });
588 }
589 }),
590 )
591 .when(can_configure, |this| {
592 this.child(
593 Button::new(
594 SharedString::from(format!("configure-{}", extension.id)),
595 "Configure",
596 )
597 .color(Color::Accent)
598 .disabled(matches!(status, ExtensionStatus::Installing))
599 .on_click({
600 let manifest = Arc::new(extension.clone());
601 move |_, _, cx| {
602 if let Some(events) =
603 extension::ExtensionEvents::try_global(cx)
604 {
605 events.update(cx, |this, cx| {
606 this.emit(
607 extension::Event::ConfigureExtensionRequested(
608 manifest.clone(),
609 ),
610 cx,
611 )
612 });
613 }
614 }
615 }),
616 )
617 }),
618 ),
619 )
620 .child(
621 h_flex()
622 .gap_2()
623 .justify_between()
624 .child(
625 Label::new(format!(
626 "{}: {}",
627 if extension.authors.len() > 1 {
628 "Authors"
629 } else {
630 "Author"
631 },
632 extension.authors.join(", ")
633 ))
634 .size(LabelSize::Small)
635 .color(Color::Muted)
636 .truncate(),
637 )
638 .child(Label::new("<>").size(LabelSize::Small)),
639 )
640 .child(
641 h_flex()
642 .gap_2()
643 .justify_between()
644 .children(extension.description.as_ref().map(|description| {
645 Label::new(description.clone())
646 .size(LabelSize::Small)
647 .color(Color::Default)
648 .truncate()
649 }))
650 .children(repository_url.map(|repository_url| {
651 IconButton::new(
652 SharedString::from(format!("repository-{}", extension.id)),
653 IconName::Github,
654 )
655 .icon_color(Color::Accent)
656 .icon_size(IconSize::Small)
657 .on_click(cx.listener({
658 let repository_url = repository_url.clone();
659 move |_, _, _, cx| {
660 cx.open_url(&repository_url);
661 }
662 }))
663 .tooltip(Tooltip::text(repository_url.clone()))
664 })),
665 )
666 }
667
668 fn render_remote_extension(
669 &self,
670 extension: &ExtensionMetadata,
671 cx: &mut Context<Self>,
672 ) -> ExtensionCard {
673 let this = cx.entity().clone();
674 let status = Self::extension_status(&extension.id, cx);
675 let has_dev_extension = Self::dev_extension_exists(&extension.id, cx);
676
677 let extension_id = extension.id.clone();
678 let buttons = self.buttons_for_entry(extension, &status, has_dev_extension, cx);
679 let version = extension.manifest.version.clone();
680 let repository_url = extension.manifest.repository.clone();
681 let authors = extension.manifest.authors.clone();
682
683 let installed_version = match status {
684 ExtensionStatus::Installed(installed_version) => Some(installed_version),
685 _ => None,
686 };
687
688 ExtensionCard::new()
689 .overridden_by_dev_extension(has_dev_extension)
690 .child(
691 h_flex()
692 .justify_between()
693 .child(
694 h_flex()
695 .gap_2()
696 .child(
697 Headline::new(extension.manifest.name.clone())
698 .size(HeadlineSize::Medium),
699 )
700 .child(Headline::new(format!("v{version}")).size(HeadlineSize::XSmall))
701 .children(
702 installed_version
703 .filter(|installed_version| *installed_version != version)
704 .map(|installed_version| {
705 Headline::new(format!("(v{installed_version} installed)",))
706 .size(HeadlineSize::XSmall)
707 }),
708 )
709 .map(|parent| {
710 if extension.manifest.provides.is_empty() {
711 return parent;
712 }
713
714 parent.child(
715 h_flex().gap_2().children(
716 extension
717 .manifest
718 .provides
719 .iter()
720 .map(|provides| {
721 div()
722 .bg(cx.theme().colors().element_background)
723 .px_0p5()
724 .border_1()
725 .border_color(cx.theme().colors().border)
726 .rounded_sm()
727 .child(
728 Label::new(extension_provides_label(
729 *provides,
730 ))
731 .size(LabelSize::XSmall),
732 )
733 })
734 .collect::<Vec<_>>(),
735 ),
736 )
737 }),
738 )
739 .child(
740 h_flex()
741 .gap_2()
742 .justify_between()
743 .children(buttons.upgrade)
744 .children(buttons.configure)
745 .child(buttons.install_or_uninstall),
746 ),
747 )
748 .child(
749 h_flex()
750 .gap_2()
751 .justify_between()
752 .child(
753 Label::new(format!(
754 "{}: {}",
755 if extension.manifest.authors.len() > 1 {
756 "Authors"
757 } else {
758 "Author"
759 },
760 extension.manifest.authors.join(", ")
761 ))
762 .size(LabelSize::Small)
763 .color(Color::Muted)
764 .truncate(),
765 )
766 .child(
767 Label::new(format!(
768 "Downloads: {}",
769 extension.download_count.to_formatted_string(&Locale::en)
770 ))
771 .size(LabelSize::Small),
772 ),
773 )
774 .child(
775 h_flex()
776 .gap_2()
777 .justify_between()
778 .children(extension.manifest.description.as_ref().map(|description| {
779 Label::new(description.clone())
780 .size(LabelSize::Small)
781 .color(Color::Default)
782 .truncate()
783 }))
784 .child(
785 h_flex()
786 .gap_2()
787 .child(
788 IconButton::new(
789 SharedString::from(format!("repository-{}", extension.id)),
790 IconName::Github,
791 )
792 .icon_color(Color::Accent)
793 .icon_size(IconSize::Small)
794 .on_click(cx.listener({
795 let repository_url = repository_url.clone();
796 move |_, _, _, cx| {
797 cx.open_url(&repository_url);
798 }
799 }))
800 .tooltip(Tooltip::text(repository_url.clone())),
801 )
802 .child(
803 PopoverMenu::new(SharedString::from(format!(
804 "more-{}",
805 extension.id
806 )))
807 .trigger(
808 IconButton::new(
809 SharedString::from(format!("more-{}", extension.id)),
810 IconName::Ellipsis,
811 )
812 .icon_color(Color::Accent)
813 .icon_size(IconSize::Small),
814 )
815 .menu(move |window, cx| {
816 Some(Self::render_remote_extension_context_menu(
817 &this,
818 extension_id.clone(),
819 authors.clone(),
820 window,
821 cx,
822 ))
823 }),
824 ),
825 ),
826 )
827 }
828
829 fn render_remote_extension_context_menu(
830 this: &Entity<Self>,
831 extension_id: Arc<str>,
832 authors: Vec<String>,
833 window: &mut Window,
834 cx: &mut App,
835 ) -> Entity<ContextMenu> {
836 let context_menu = ContextMenu::build(window, cx, |context_menu, window, _| {
837 context_menu
838 .entry(
839 "Install Another Version...",
840 None,
841 window.handler_for(this, {
842 let extension_id = extension_id.clone();
843 move |this, window, cx| {
844 this.show_extension_version_list(extension_id.clone(), window, cx)
845 }
846 }),
847 )
848 .entry("Copy Extension ID", None, {
849 let extension_id = extension_id.clone();
850 move |_, cx| {
851 cx.write_to_clipboard(ClipboardItem::new_string(extension_id.to_string()));
852 }
853 })
854 .entry("Copy Author Info", None, {
855 let authors = authors.clone();
856 move |_, cx| {
857 cx.write_to_clipboard(ClipboardItem::new_string(authors.join(", ")));
858 }
859 })
860 });
861
862 context_menu
863 }
864
865 fn show_extension_version_list(
866 &mut self,
867 extension_id: Arc<str>,
868 window: &mut Window,
869 cx: &mut Context<Self>,
870 ) {
871 let Some(workspace) = self.workspace.upgrade() else {
872 return;
873 };
874
875 cx.spawn_in(window, async move |this, cx| {
876 let extension_versions_task = this.update(cx, |_, cx| {
877 let extension_store = ExtensionStore::global(cx);
878
879 extension_store.update(cx, |store, cx| {
880 store.fetch_extension_versions(&extension_id, cx)
881 })
882 })?;
883
884 let extension_versions = extension_versions_task.await?;
885
886 workspace.update_in(cx, |workspace, window, cx| {
887 let fs = workspace.project().read(cx).fs().clone();
888 workspace.toggle_modal(window, cx, |window, cx| {
889 let delegate = ExtensionVersionSelectorDelegate::new(
890 fs,
891 cx.entity().downgrade(),
892 extension_versions,
893 );
894
895 ExtensionVersionSelector::new(delegate, window, cx)
896 });
897 })?;
898
899 anyhow::Ok(())
900 })
901 .detach_and_log_err(cx);
902 }
903
904 fn buttons_for_entry(
905 &self,
906 extension: &ExtensionMetadata,
907 status: &ExtensionStatus,
908 has_dev_extension: bool,
909 cx: &mut Context<Self>,
910 ) -> ExtensionCardButtons {
911 let is_compatible =
912 extension_host::is_version_compatible(ReleaseChannel::global(cx), extension);
913
914 if has_dev_extension {
915 // If we have a dev extension for the given extension, just treat it as uninstalled.
916 // The button here is a placeholder, as it won't be interactable anyways.
917 return ExtensionCardButtons {
918 install_or_uninstall: Button::new(
919 SharedString::from(extension.id.clone()),
920 "Install",
921 ),
922 configure: None,
923 upgrade: None,
924 };
925 }
926
927 let is_configurable = extension
928 .manifest
929 .provides
930 .contains(&ExtensionProvides::ContextServers);
931
932 match status.clone() {
933 ExtensionStatus::NotInstalled => ExtensionCardButtons {
934 install_or_uninstall: Button::new(
935 SharedString::from(extension.id.clone()),
936 "Install",
937 )
938 .on_click({
939 let extension_id = extension.id.clone();
940 move |_, _, cx| {
941 telemetry::event!("Extension Installed");
942 ExtensionStore::global(cx).update(cx, |store, cx| {
943 store.install_latest_extension(extension_id.clone(), cx)
944 });
945 }
946 }),
947 configure: None,
948 upgrade: None,
949 },
950 ExtensionStatus::Installing => ExtensionCardButtons {
951 install_or_uninstall: Button::new(
952 SharedString::from(extension.id.clone()),
953 "Install",
954 )
955 .disabled(true),
956 configure: None,
957 upgrade: None,
958 },
959 ExtensionStatus::Upgrading => ExtensionCardButtons {
960 install_or_uninstall: Button::new(
961 SharedString::from(extension.id.clone()),
962 "Uninstall",
963 )
964 .disabled(true),
965 configure: is_configurable.then(|| {
966 Button::new(
967 SharedString::from(format!("configure-{}", extension.id)),
968 "Configure",
969 )
970 .disabled(true)
971 }),
972 upgrade: Some(
973 Button::new(SharedString::from(extension.id.clone()), "Upgrade").disabled(true),
974 ),
975 },
976 ExtensionStatus::Installed(installed_version) => ExtensionCardButtons {
977 install_or_uninstall: Button::new(
978 SharedString::from(extension.id.clone()),
979 "Uninstall",
980 )
981 .on_click({
982 let extension_id = extension.id.clone();
983 move |_, _, cx| {
984 telemetry::event!("Extension Uninstalled", extension_id);
985 ExtensionStore::global(cx).update(cx, |store, cx| {
986 store.uninstall_extension(extension_id.clone(), cx)
987 });
988 }
989 }),
990 configure: is_configurable.then(|| {
991 Button::new(
992 SharedString::from(format!("configure-{}", extension.id)),
993 "Configure",
994 )
995 .on_click({
996 let extension_id = extension.id.clone();
997 move |_, _, cx| {
998 if let Some(manifest) = ExtensionStore::global(cx)
999 .read(cx)
1000 .extension_manifest_for_id(&extension_id)
1001 .cloned()
1002 {
1003 if let Some(events) = extension::ExtensionEvents::try_global(cx) {
1004 events.update(cx, |this, cx| {
1005 this.emit(
1006 extension::Event::ConfigureExtensionRequested(manifest),
1007 cx,
1008 )
1009 });
1010 }
1011 }
1012 }
1013 })
1014 }),
1015 upgrade: if installed_version == extension.manifest.version {
1016 None
1017 } else {
1018 Some(
1019 Button::new(SharedString::from(extension.id.clone()), "Upgrade")
1020 .when(!is_compatible, |upgrade_button| {
1021 upgrade_button.disabled(true).tooltip({
1022 let version = extension.manifest.version.clone();
1023 move |_, cx| {
1024 Tooltip::simple(
1025 format!(
1026 "v{version} is not compatible with this version of Zed.",
1027 ),
1028 cx,
1029 )
1030 }
1031 })
1032 })
1033 .disabled(!is_compatible)
1034 .on_click({
1035 let extension_id = extension.id.clone();
1036 let version = extension.manifest.version.clone();
1037 move |_, _, cx| {
1038 telemetry::event!("Extension Installed", extension_id, version);
1039 ExtensionStore::global(cx).update(cx, |store, cx| {
1040 store
1041 .upgrade_extension(
1042 extension_id.clone(),
1043 version.clone(),
1044 cx,
1045 )
1046 .detach_and_log_err(cx)
1047 });
1048 }
1049 }),
1050 )
1051 },
1052 },
1053 ExtensionStatus::Removing => ExtensionCardButtons {
1054 install_or_uninstall: Button::new(
1055 SharedString::from(extension.id.clone()),
1056 "Uninstall",
1057 )
1058 .disabled(true),
1059 configure: is_configurable.then(|| {
1060 Button::new(
1061 SharedString::from(format!("configure-{}", extension.id)),
1062 "Configure",
1063 )
1064 .disabled(true)
1065 }),
1066 upgrade: None,
1067 },
1068 }
1069 }
1070
1071 fn render_search(&self, cx: &mut Context<Self>) -> Div {
1072 let mut key_context = KeyContext::new_with_defaults();
1073 key_context.add("BufferSearchBar");
1074
1075 let editor_border = if self.query_contains_error {
1076 Color::Error.color(cx)
1077 } else {
1078 cx.theme().colors().border
1079 };
1080
1081 h_flex()
1082 .key_context(key_context)
1083 .h_8()
1084 .flex_1()
1085 .min_w(rems_from_px(384.))
1086 .pl_1p5()
1087 .pr_2()
1088 .py_1()
1089 .gap_2()
1090 .border_1()
1091 .border_color(editor_border)
1092 .rounded_lg()
1093 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1094 .child(self.render_text_input(&self.query_editor, cx))
1095 }
1096
1097 fn render_text_input(
1098 &self,
1099 editor: &Entity<Editor>,
1100 cx: &mut Context<Self>,
1101 ) -> impl IntoElement {
1102 let settings = ThemeSettings::get_global(cx);
1103 let text_style = TextStyle {
1104 color: if editor.read(cx).read_only(cx) {
1105 cx.theme().colors().text_disabled
1106 } else {
1107 cx.theme().colors().text
1108 },
1109 font_family: settings.ui_font.family.clone(),
1110 font_features: settings.ui_font.features.clone(),
1111 font_fallbacks: settings.ui_font.fallbacks.clone(),
1112 font_size: rems(0.875).into(),
1113 font_weight: settings.ui_font.weight,
1114 line_height: relative(1.3),
1115 ..Default::default()
1116 };
1117
1118 EditorElement::new(
1119 editor,
1120 EditorStyle {
1121 background: cx.theme().colors().editor_background,
1122 local_player: cx.theme().players().local(),
1123 text: text_style,
1124 ..Default::default()
1125 },
1126 )
1127 }
1128
1129 fn on_query_change(
1130 &mut self,
1131 _: Entity<Editor>,
1132 event: &editor::EditorEvent,
1133 cx: &mut Context<Self>,
1134 ) {
1135 if let editor::EditorEvent::Edited { .. } = event {
1136 self.query_contains_error = false;
1137 self.refresh_search(cx);
1138 }
1139 }
1140
1141 fn refresh_search(&mut self, cx: &mut Context<Self>) {
1142 self.fetch_extensions_debounced(
1143 Some(Box::new(|this, cx| {
1144 this.scroll_to_top(cx);
1145 })),
1146 cx,
1147 );
1148 self.refresh_feature_upsells(cx);
1149 }
1150
1151 pub fn change_provides_filter(
1152 &mut self,
1153 provides_filter: Option<ExtensionProvides>,
1154 cx: &mut Context<Self>,
1155 ) {
1156 self.provides_filter = provides_filter;
1157 self.refresh_search(cx);
1158 }
1159
1160 fn fetch_extensions_debounced(
1161 &mut self,
1162 on_complete: Option<Box<dyn FnOnce(&mut Self, &mut Context<Self>) + Send>>,
1163 cx: &mut Context<ExtensionsPage>,
1164 ) {
1165 self.extension_fetch_task = Some(cx.spawn(async move |this, cx| {
1166 let search = this
1167 .update(cx, |this, cx| this.search_query(cx))
1168 .ok()
1169 .flatten();
1170
1171 // Only debounce the fetching of extensions if we have a search
1172 // query.
1173 //
1174 // If the search was just cleared then we can just reload the list
1175 // of extensions without a debounce, which allows us to avoid seeing
1176 // an intermittent flash of a "no extensions" state.
1177 if search.is_some() {
1178 cx.background_executor()
1179 .timer(Duration::from_millis(250))
1180 .await;
1181 };
1182
1183 this.update(cx, |this, cx| {
1184 this.fetch_extensions(
1185 search,
1186 Some(BTreeSet::from_iter(this.provides_filter)),
1187 on_complete,
1188 cx,
1189 );
1190 })
1191 .ok();
1192 }));
1193 }
1194
1195 pub fn search_query(&self, cx: &mut App) -> Option<String> {
1196 let search = self.query_editor.read(cx).text(cx);
1197 if search.trim().is_empty() {
1198 None
1199 } else {
1200 Some(search)
1201 }
1202 }
1203
1204 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
1205 let has_search = self.search_query(cx).is_some();
1206
1207 let message = if self.is_fetching_extensions {
1208 "Loading extensions..."
1209 } else {
1210 match self.filter {
1211 ExtensionFilter::All => {
1212 if has_search {
1213 "No extensions that match your search."
1214 } else {
1215 "No extensions."
1216 }
1217 }
1218 ExtensionFilter::Installed => {
1219 if has_search {
1220 "No installed extensions that match your search."
1221 } else {
1222 "No installed extensions."
1223 }
1224 }
1225 ExtensionFilter::NotInstalled => {
1226 if has_search {
1227 "No not installed extensions that match your search."
1228 } else {
1229 "No not installed extensions."
1230 }
1231 }
1232 }
1233 };
1234
1235 Label::new(message)
1236 }
1237
1238 fn update_settings<T: Settings>(
1239 &mut self,
1240 selection: &ToggleState,
1241
1242 cx: &mut Context<Self>,
1243 callback: impl 'static + Send + Fn(&mut T::FileContent, bool),
1244 ) {
1245 if let Some(workspace) = self.workspace.upgrade() {
1246 let fs = workspace.read(cx).app_state().fs.clone();
1247 let selection = *selection;
1248 settings::update_settings_file::<T>(fs, cx, move |settings, _| {
1249 let value = match selection {
1250 ToggleState::Unselected => false,
1251 ToggleState::Selected => true,
1252 _ => return,
1253 };
1254
1255 callback(settings, value)
1256 });
1257 }
1258 }
1259
1260 fn refresh_feature_upsells(&mut self, cx: &mut Context<Self>) {
1261 let Some(search) = self.search_query(cx) else {
1262 self.upsells.clear();
1263 return;
1264 };
1265
1266 let search = search.to_lowercase();
1267 let search_terms = search
1268 .split_whitespace()
1269 .map(|term| term.trim())
1270 .collect::<Vec<_>>();
1271
1272 for (feature, keywords) in keywords_by_feature() {
1273 if keywords
1274 .iter()
1275 .any(|keyword| search_terms.contains(keyword))
1276 {
1277 self.upsells.insert(*feature);
1278 } else {
1279 self.upsells.remove(feature);
1280 }
1281 }
1282 }
1283
1284 fn render_feature_upsells(&self, cx: &mut Context<Self>) -> impl IntoElement {
1285 let upsells_count = self.upsells.len();
1286
1287 v_flex().children(self.upsells.iter().enumerate().map(|(ix, feature)| {
1288 let upsell = match feature {
1289 Feature::Git => FeatureUpsell::new(
1290 "Zed comes with basic Git support. More Git features are coming in the future.",
1291 )
1292 .docs_url("https://zed.dev/docs/git"),
1293 Feature::OpenIn => FeatureUpsell::new(
1294 "Zed supports linking to a source line on GitHub and others.",
1295 )
1296 .docs_url("https://zed.dev/docs/git#git-integrations"),
1297 Feature::Vim => FeatureUpsell::new("Vim support is built-in to Zed!")
1298 .docs_url("https://zed.dev/docs/vim")
1299 .child(CheckboxWithLabel::new(
1300 "enable-vim",
1301 Label::new("Enable vim mode"),
1302 if VimModeSetting::get_global(cx).0 {
1303 ui::ToggleState::Selected
1304 } else {
1305 ui::ToggleState::Unselected
1306 },
1307 cx.listener(move |this, selection, _, cx| {
1308 telemetry::event!("Vim Mode Toggled", source = "Feature Upsell");
1309 this.update_settings::<VimModeSetting>(
1310 selection,
1311 cx,
1312 |setting, value| *setting = Some(value),
1313 );
1314 }),
1315 )),
1316 Feature::LanguageBash => FeatureUpsell::new("Shell support is built-in to Zed!")
1317 .docs_url("https://zed.dev/docs/languages/bash"),
1318 Feature::LanguageC => FeatureUpsell::new("C support is built-in to Zed!")
1319 .docs_url("https://zed.dev/docs/languages/c"),
1320 Feature::LanguageCpp => FeatureUpsell::new("C++ support is built-in to Zed!")
1321 .docs_url("https://zed.dev/docs/languages/cpp"),
1322 Feature::LanguageGo => FeatureUpsell::new("Go support is built-in to Zed!")
1323 .docs_url("https://zed.dev/docs/languages/go"),
1324 Feature::LanguagePython => FeatureUpsell::new("Python support is built-in to Zed!")
1325 .docs_url("https://zed.dev/docs/languages/python"),
1326 Feature::LanguageReact => FeatureUpsell::new("React support is built-in to Zed!")
1327 .docs_url("https://zed.dev/docs/languages/typescript"),
1328 Feature::LanguageRust => FeatureUpsell::new("Rust support is built-in to Zed!")
1329 .docs_url("https://zed.dev/docs/languages/rust"),
1330 Feature::LanguageTypescript => {
1331 FeatureUpsell::new("Typescript support is built-in to Zed!")
1332 .docs_url("https://zed.dev/docs/languages/typescript")
1333 }
1334 };
1335
1336 upsell.when(ix < upsells_count, |upsell| upsell.border_b_1())
1337 }))
1338 }
1339}
1340
1341impl Render for ExtensionsPage {
1342 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1343 v_flex()
1344 .size_full()
1345 .bg(cx.theme().colors().editor_background)
1346 .child(
1347 v_flex()
1348 .gap_4()
1349 .pt_4()
1350 .px_4()
1351 .bg(cx.theme().colors().editor_background)
1352 .child(
1353 h_flex()
1354 .w_full()
1355 .gap_2()
1356 .justify_between()
1357 .child(Headline::new("Extensions").size(HeadlineSize::XLarge))
1358 .child(
1359 Button::new("install-dev-extension", "Install Dev Extension")
1360 .style(ButtonStyle::Filled)
1361 .size(ButtonSize::Large)
1362 .on_click(|_event, window, cx| {
1363 window.dispatch_action(Box::new(InstallDevExtension), cx)
1364 }),
1365 ),
1366 )
1367 .child(
1368 h_flex()
1369 .w_full()
1370 .gap_4()
1371 .flex_wrap()
1372 .child(self.render_search(cx))
1373 .child(
1374 h_flex()
1375 .child(
1376 ToggleButton::new("filter-all", "All")
1377 .style(ButtonStyle::Filled)
1378 .size(ButtonSize::Large)
1379 .toggle_state(self.filter == ExtensionFilter::All)
1380 .on_click(cx.listener(|this, _event, _, cx| {
1381 this.filter = ExtensionFilter::All;
1382 this.filter_extension_entries(cx);
1383 this.scroll_to_top(cx);
1384 }))
1385 .tooltip(move |_, cx| {
1386 Tooltip::simple("Show all extensions", cx)
1387 })
1388 .first(),
1389 )
1390 .child(
1391 ToggleButton::new("filter-installed", "Installed")
1392 .style(ButtonStyle::Filled)
1393 .size(ButtonSize::Large)
1394 .toggle_state(self.filter == ExtensionFilter::Installed)
1395 .on_click(cx.listener(|this, _event, _, cx| {
1396 this.filter = ExtensionFilter::Installed;
1397 this.filter_extension_entries(cx);
1398 this.scroll_to_top(cx);
1399 }))
1400 .tooltip(move |_, cx| {
1401 Tooltip::simple("Show installed extensions", cx)
1402 })
1403 .middle(),
1404 )
1405 .child(
1406 ToggleButton::new("filter-not-installed", "Not Installed")
1407 .style(ButtonStyle::Filled)
1408 .size(ButtonSize::Large)
1409 .toggle_state(
1410 self.filter == ExtensionFilter::NotInstalled,
1411 )
1412 .on_click(cx.listener(|this, _event, _, cx| {
1413 this.filter = ExtensionFilter::NotInstalled;
1414 this.filter_extension_entries(cx);
1415 this.scroll_to_top(cx);
1416 }))
1417 .tooltip(move |_, cx| {
1418 Tooltip::simple("Show not installed extensions", cx)
1419 })
1420 .last(),
1421 ),
1422 ),
1423 ),
1424 )
1425 .child(
1426 h_flex()
1427 .id("filter-row")
1428 .gap_2()
1429 .py_2p5()
1430 .px_4()
1431 .border_b_1()
1432 .border_color(cx.theme().colors().border_variant)
1433 .overflow_x_scroll()
1434 .child(
1435 Button::new("filter-all-categories", "All")
1436 .when(self.provides_filter.is_none(), |button| {
1437 button.style(ButtonStyle::Filled)
1438 })
1439 .when(self.provides_filter.is_some(), |button| {
1440 button.style(ButtonStyle::Subtle)
1441 })
1442 .toggle_state(self.provides_filter.is_none())
1443 .on_click(cx.listener(|this, _event, _, cx| {
1444 this.change_provides_filter(None, cx);
1445 })),
1446 )
1447 .children(ExtensionProvides::iter().map(|provides| {
1448 let label = extension_provides_label(provides);
1449 Button::new(
1450 SharedString::from(format!("filter-category-{}", label)),
1451 label,
1452 )
1453 .style(if self.provides_filter == Some(provides) {
1454 ButtonStyle::Filled
1455 } else {
1456 ButtonStyle::Subtle
1457 })
1458 .toggle_state(self.provides_filter == Some(provides))
1459 .on_click({
1460 cx.listener(move |this, _event, _, cx| {
1461 this.change_provides_filter(Some(provides), cx);
1462 })
1463 })
1464 })),
1465 )
1466 .child(self.render_feature_upsells(cx))
1467 .child(
1468 v_flex()
1469 .pl_4()
1470 .pr_6()
1471 .size_full()
1472 .overflow_y_hidden()
1473 .map(|this| {
1474 let mut count = self.filtered_remote_extension_indices.len();
1475 if self.filter.include_dev_extensions() {
1476 count += self.dev_extension_entries.len();
1477 }
1478
1479 if count == 0 {
1480 return this.py_4().child(self.render_empty_state(cx));
1481 }
1482
1483 let scroll_handle = self.list.clone();
1484 this.child(
1485 uniform_list("entries", count, cx.processor(Self::render_extensions))
1486 .flex_grow()
1487 .pb_4()
1488 .track_scroll(scroll_handle),
1489 )
1490 .child(
1491 div()
1492 .absolute()
1493 .right_1()
1494 .top_0()
1495 .bottom_0()
1496 .w(px(12.))
1497 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1498 )
1499 }),
1500 )
1501 }
1502}
1503
1504impl EventEmitter<ItemEvent> for ExtensionsPage {}
1505
1506impl Focusable for ExtensionsPage {
1507 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1508 self.query_editor.read(cx).focus_handle(cx)
1509 }
1510}
1511
1512impl Item for ExtensionsPage {
1513 type Event = ItemEvent;
1514
1515 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1516 "Extensions".into()
1517 }
1518
1519 fn telemetry_event_text(&self) -> Option<&'static str> {
1520 Some("Extensions Page Opened")
1521 }
1522
1523 fn show_toolbar(&self) -> bool {
1524 false
1525 }
1526
1527 fn clone_on_split(
1528 &self,
1529 _workspace_id: Option<WorkspaceId>,
1530 _window: &mut Window,
1531 _: &mut Context<Self>,
1532 ) -> Option<Entity<Self>> {
1533 None
1534 }
1535
1536 fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
1537 f(*event)
1538 }
1539}