extensions_ui.rs

   1mod components;
   2mod extension_suggest;
   3mod extension_version_selector;
   4
   5use std::ops::DerefMut;
   6use std::sync::OnceLock;
   7use std::time::Duration;
   8use std::{ops::Range, sync::Arc};
   9
  10use client::telemetry::Telemetry;
  11use client::ExtensionMetadata;
  12use collections::{BTreeMap, BTreeSet};
  13use editor::{Editor, EditorElement, EditorStyle};
  14use extension_host::{ExtensionManifest, ExtensionOperation, ExtensionStore};
  15use fuzzy::{match_strings, StringMatchCandidate};
  16use gpui::{
  17    actions, uniform_list, Action, AppContext, ClipboardItem, EventEmitter, Flatten, FocusableView,
  18    InteractiveElement, KeyContext, ParentElement, Render, Styled, Task, TextStyle,
  19    UniformListScrollHandle, View, ViewContext, VisualContext, WeakView, WindowContext,
  20};
  21use num_format::{Locale, ToFormattedString};
  22use project::DirectoryLister;
  23use release_channel::ReleaseChannel;
  24use settings::Settings;
  25use theme::ThemeSettings;
  26use ui::{prelude::*, CheckboxWithLabel, ContextMenu, PopoverMenu, ToggleButton, Tooltip};
  27use vim_mode_setting::VimModeSetting;
  28use workspace::{
  29    item::{Item, ItemEvent},
  30    Workspace, WorkspaceId,
  31};
  32
  33use crate::components::{ExtensionCard, FeatureUpsell};
  34use crate::extension_version_selector::{
  35    ExtensionVersionSelector, ExtensionVersionSelectorDelegate,
  36};
  37
  38actions!(zed, [InstallDevExtension]);
  39
  40pub fn init(cx: &mut AppContext) {
  41    cx.observe_new_views(move |workspace: &mut Workspace, cx| {
  42        workspace
  43            .register_action(move |workspace, _: &zed_actions::Extensions, cx| {
  44                let existing = workspace
  45                    .active_pane()
  46                    .read(cx)
  47                    .items()
  48                    .find_map(|item| item.downcast::<ExtensionsPage>());
  49
  50                if let Some(existing) = existing {
  51                    workspace.activate_item(&existing, true, true, cx);
  52                } else {
  53                    let extensions_page = ExtensionsPage::new(workspace, cx);
  54                    workspace.add_item_to_active_pane(Box::new(extensions_page), None, true, cx)
  55                }
  56            })
  57            .register_action(move |workspace, _: &InstallDevExtension, cx| {
  58                let store = ExtensionStore::global(cx);
  59                let prompt = workspace.prompt_for_open_path(
  60                    gpui::PathPromptOptions {
  61                        files: false,
  62                        directories: true,
  63                        multiple: false,
  64                    },
  65                    DirectoryLister::Local(workspace.app_state().fs.clone()),
  66                    cx,
  67                );
  68
  69                let workspace_handle = cx.view().downgrade();
  70                cx.deref_mut()
  71                    .spawn(|mut cx| async move {
  72                        let extension_path =
  73                            match Flatten::flatten(prompt.await.map_err(|e| e.into())) {
  74                                Ok(Some(mut paths)) => paths.pop()?,
  75                                Ok(None) => return None,
  76                                Err(err) => {
  77                                    workspace_handle
  78                                        .update(&mut cx, |workspace, cx| {
  79                                            workspace.show_portal_error(err.to_string(), cx);
  80                                        })
  81                                        .ok();
  82                                    return None;
  83                                }
  84                            };
  85
  86                        store
  87                            .update(&mut cx, |store, cx| {
  88                                store
  89                                    .install_dev_extension(extension_path, cx)
  90                                    .detach_and_log_err(cx)
  91                            })
  92                            .ok()?;
  93                        Some(())
  94                    })
  95                    .detach();
  96            });
  97
  98        cx.subscribe(workspace.project(), |_, _, event, cx| {
  99            if let project::Event::LanguageNotFound(buffer) = event {
 100                extension_suggest::suggest(buffer.clone(), cx);
 101            }
 102        })
 103        .detach();
 104    })
 105    .detach();
 106}
 107
 108#[derive(Clone)]
 109pub enum ExtensionStatus {
 110    NotInstalled,
 111    Installing,
 112    Upgrading,
 113    Installed(Arc<str>),
 114    Removing,
 115}
 116
 117#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 118enum ExtensionFilter {
 119    All,
 120    Installed,
 121    NotInstalled,
 122}
 123
 124impl ExtensionFilter {
 125    pub fn include_dev_extensions(&self) -> bool {
 126        match self {
 127            Self::All | Self::Installed => true,
 128            Self::NotInstalled => false,
 129        }
 130    }
 131}
 132
 133#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 134enum Feature {
 135    Git,
 136    OpenIn,
 137    Vim,
 138    LanguageBash,
 139    LanguageC,
 140    LanguageCpp,
 141    LanguageGo,
 142    LanguagePython,
 143    LanguageReact,
 144    LanguageRust,
 145    LanguageTypescript,
 146}
 147
 148fn keywords_by_feature() -> &'static BTreeMap<Feature, Vec<&'static str>> {
 149    static KEYWORDS_BY_FEATURE: OnceLock<BTreeMap<Feature, Vec<&'static str>>> = OnceLock::new();
 150    KEYWORDS_BY_FEATURE.get_or_init(|| {
 151        BTreeMap::from_iter([
 152            (Feature::Git, vec!["git"]),
 153            (
 154                Feature::OpenIn,
 155                vec![
 156                    "github",
 157                    "gitlab",
 158                    "bitbucket",
 159                    "codeberg",
 160                    "sourcehut",
 161                    "permalink",
 162                    "link",
 163                    "open in",
 164                ],
 165            ),
 166            (Feature::Vim, vec!["vim"]),
 167            (Feature::LanguageBash, vec!["sh", "bash"]),
 168            (Feature::LanguageC, vec!["c", "clang"]),
 169            (Feature::LanguageCpp, vec!["c++", "cpp", "clang"]),
 170            (Feature::LanguageGo, vec!["go", "golang"]),
 171            (Feature::LanguagePython, vec!["python", "py"]),
 172            (Feature::LanguageReact, vec!["react"]),
 173            (Feature::LanguageRust, vec!["rust", "rs"]),
 174            (
 175                Feature::LanguageTypescript,
 176                vec!["type", "typescript", "ts"],
 177            ),
 178        ])
 179    })
 180}
 181
 182pub struct ExtensionsPage {
 183    workspace: WeakView<Workspace>,
 184    list: UniformListScrollHandle,
 185    telemetry: Arc<Telemetry>,
 186    is_fetching_extensions: bool,
 187    filter: ExtensionFilter,
 188    remote_extension_entries: Vec<ExtensionMetadata>,
 189    dev_extension_entries: Vec<Arc<ExtensionManifest>>,
 190    filtered_remote_extension_indices: Vec<usize>,
 191    query_editor: View<Editor>,
 192    query_contains_error: bool,
 193    _subscriptions: [gpui::Subscription; 2],
 194    extension_fetch_task: Option<Task<()>>,
 195    upsells: BTreeSet<Feature>,
 196}
 197
 198impl ExtensionsPage {
 199    pub fn new(workspace: &Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
 200        cx.new_view(|cx: &mut ViewContext<Self>| {
 201            let store = ExtensionStore::global(cx);
 202            let workspace_handle = workspace.weak_handle();
 203            let subscriptions = [
 204                cx.observe(&store, |_, _, cx| cx.notify()),
 205                cx.subscribe(&store, move |this, _, event, cx| match event {
 206                    extension_host::Event::ExtensionsUpdated => this.fetch_extensions_debounced(cx),
 207                    extension_host::Event::ExtensionInstalled(extension_id) => {
 208                        this.on_extension_installed(workspace_handle.clone(), extension_id, cx)
 209                    }
 210                    _ => {}
 211                }),
 212            ];
 213
 214            let query_editor = cx.new_view(|cx| {
 215                let mut input = Editor::single_line(cx);
 216                input.set_placeholder_text("Search extensions...", cx);
 217                input
 218            });
 219            cx.subscribe(&query_editor, Self::on_query_change).detach();
 220
 221            let mut this = Self {
 222                workspace: workspace.weak_handle(),
 223                list: UniformListScrollHandle::new(),
 224                telemetry: workspace.client().telemetry().clone(),
 225                is_fetching_extensions: false,
 226                filter: ExtensionFilter::All,
 227                dev_extension_entries: Vec::new(),
 228                filtered_remote_extension_indices: Vec::new(),
 229                remote_extension_entries: Vec::new(),
 230                query_contains_error: false,
 231                extension_fetch_task: None,
 232                _subscriptions: subscriptions,
 233                query_editor,
 234                upsells: BTreeSet::default(),
 235            };
 236            this.fetch_extensions(None, cx);
 237            this
 238        })
 239    }
 240
 241    fn on_extension_installed(
 242        &mut self,
 243        workspace: WeakView<Workspace>,
 244        extension_id: &str,
 245        cx: &mut ViewContext<Self>,
 246    ) {
 247        let extension_store = ExtensionStore::global(cx).read(cx);
 248        let themes = extension_store
 249            .extension_themes(extension_id)
 250            .map(|name| name.to_string())
 251            .collect::<Vec<_>>();
 252        if !themes.is_empty() {
 253            workspace
 254                .update(cx, |_workspace, cx| {
 255                    cx.dispatch_action(
 256                        zed_actions::theme_selector::Toggle {
 257                            themes_filter: Some(themes),
 258                        }
 259                        .boxed_clone(),
 260                    );
 261                })
 262                .ok();
 263        }
 264    }
 265
 266    /// Returns whether a dev extension currently exists for the extension with the given ID.
 267    fn dev_extension_exists(extension_id: &str, cx: &mut ViewContext<Self>) -> bool {
 268        let extension_store = ExtensionStore::global(cx).read(cx);
 269
 270        extension_store
 271            .dev_extensions()
 272            .any(|dev_extension| dev_extension.id.as_ref() == extension_id)
 273    }
 274
 275    fn extension_status(extension_id: &str, cx: &mut ViewContext<Self>) -> ExtensionStatus {
 276        let extension_store = ExtensionStore::global(cx).read(cx);
 277
 278        match extension_store.outstanding_operations().get(extension_id) {
 279            Some(ExtensionOperation::Install) => ExtensionStatus::Installing,
 280            Some(ExtensionOperation::Remove) => ExtensionStatus::Removing,
 281            Some(ExtensionOperation::Upgrade) => ExtensionStatus::Upgrading,
 282            None => match extension_store.installed_extensions().get(extension_id) {
 283                Some(extension) => ExtensionStatus::Installed(extension.manifest.version.clone()),
 284                None => ExtensionStatus::NotInstalled,
 285            },
 286        }
 287    }
 288
 289    fn filter_extension_entries(&mut self, cx: &mut ViewContext<Self>) {
 290        self.filtered_remote_extension_indices.clear();
 291        self.filtered_remote_extension_indices.extend(
 292            self.remote_extension_entries
 293                .iter()
 294                .enumerate()
 295                .filter(|(_, extension)| match self.filter {
 296                    ExtensionFilter::All => true,
 297                    ExtensionFilter::Installed => {
 298                        let status = Self::extension_status(&extension.id, cx);
 299                        matches!(status, ExtensionStatus::Installed(_))
 300                    }
 301                    ExtensionFilter::NotInstalled => {
 302                        let status = Self::extension_status(&extension.id, cx);
 303
 304                        matches!(status, ExtensionStatus::NotInstalled)
 305                    }
 306                })
 307                .map(|(ix, _)| ix),
 308        );
 309        cx.notify();
 310    }
 311
 312    fn fetch_extensions(&mut self, search: Option<String>, cx: &mut ViewContext<Self>) {
 313        self.is_fetching_extensions = true;
 314        cx.notify();
 315
 316        let extension_store = ExtensionStore::global(cx);
 317
 318        let dev_extensions = extension_store.update(cx, |store, _| {
 319            store.dev_extensions().cloned().collect::<Vec<_>>()
 320        });
 321
 322        let remote_extensions = extension_store.update(cx, |store, cx| {
 323            store.fetch_extensions(search.as_deref(), cx)
 324        });
 325
 326        cx.spawn(move |this, mut cx| async move {
 327            let dev_extensions = if let Some(search) = search {
 328                let match_candidates = dev_extensions
 329                    .iter()
 330                    .enumerate()
 331                    .map(|(ix, manifest)| StringMatchCandidate::new(ix, &manifest.name))
 332                    .collect::<Vec<_>>();
 333
 334                let matches = match_strings(
 335                    &match_candidates,
 336                    &search,
 337                    false,
 338                    match_candidates.len(),
 339                    &Default::default(),
 340                    cx.background_executor().clone(),
 341                )
 342                .await;
 343                matches
 344                    .into_iter()
 345                    .map(|mat| dev_extensions[mat.candidate_id].clone())
 346                    .collect()
 347            } else {
 348                dev_extensions
 349            };
 350
 351            let fetch_result = remote_extensions.await;
 352            this.update(&mut cx, |this, cx| {
 353                cx.notify();
 354                this.dev_extension_entries = dev_extensions;
 355                this.is_fetching_extensions = false;
 356                this.remote_extension_entries = fetch_result?;
 357                this.filter_extension_entries(cx);
 358                anyhow::Ok(())
 359            })?
 360        })
 361        .detach_and_log_err(cx);
 362    }
 363
 364    fn render_extensions(
 365        &mut self,
 366        range: Range<usize>,
 367        cx: &mut ViewContext<Self>,
 368    ) -> Vec<ExtensionCard> {
 369        let dev_extension_entries_len = if self.filter.include_dev_extensions() {
 370            self.dev_extension_entries.len()
 371        } else {
 372            0
 373        };
 374        range
 375            .map(|ix| {
 376                if ix < dev_extension_entries_len {
 377                    let extension = &self.dev_extension_entries[ix];
 378                    self.render_dev_extension(extension, cx)
 379                } else {
 380                    let extension_ix =
 381                        self.filtered_remote_extension_indices[ix - dev_extension_entries_len];
 382                    let extension = &self.remote_extension_entries[extension_ix];
 383                    self.render_remote_extension(extension, cx)
 384                }
 385            })
 386            .collect()
 387    }
 388
 389    fn render_dev_extension(
 390        &self,
 391        extension: &ExtensionManifest,
 392        cx: &mut ViewContext<Self>,
 393    ) -> ExtensionCard {
 394        let status = Self::extension_status(&extension.id, cx);
 395
 396        let repository_url = extension.repository.clone();
 397
 398        ExtensionCard::new()
 399            .child(
 400                h_flex()
 401                    .justify_between()
 402                    .child(
 403                        h_flex()
 404                            .gap_2()
 405                            .items_end()
 406                            .child(Headline::new(extension.name.clone()).size(HeadlineSize::Medium))
 407                            .child(
 408                                Headline::new(format!("v{}", extension.version))
 409                                    .size(HeadlineSize::XSmall),
 410                            ),
 411                    )
 412                    .child(
 413                        h_flex()
 414                            .gap_2()
 415                            .justify_between()
 416                            .child(
 417                                Button::new(
 418                                    SharedString::from(format!("rebuild-{}", extension.id)),
 419                                    "Rebuild",
 420                                )
 421                                .on_click({
 422                                    let extension_id = extension.id.clone();
 423                                    move |_, cx| {
 424                                        ExtensionStore::global(cx).update(cx, |store, cx| {
 425                                            store.rebuild_dev_extension(extension_id.clone(), cx)
 426                                        });
 427                                    }
 428                                })
 429                                .color(Color::Accent)
 430                                .disabled(matches!(status, ExtensionStatus::Upgrading)),
 431                            )
 432                            .child(
 433                                Button::new(SharedString::from(extension.id.clone()), "Uninstall")
 434                                    .on_click({
 435                                        let extension_id = extension.id.clone();
 436                                        move |_, cx| {
 437                                            ExtensionStore::global(cx).update(cx, |store, cx| {
 438                                                store.uninstall_extension(extension_id.clone(), cx)
 439                                            });
 440                                        }
 441                                    })
 442                                    .color(Color::Accent)
 443                                    .disabled(matches!(status, ExtensionStatus::Removing)),
 444                            ),
 445                    ),
 446            )
 447            .child(
 448                h_flex()
 449                    .gap_2()
 450                    .justify_between()
 451                    .child(
 452                        div().overflow_x_hidden().text_ellipsis().child(
 453                            Label::new(format!(
 454                                "{}: {}",
 455                                if extension.authors.len() > 1 {
 456                                    "Authors"
 457                                } else {
 458                                    "Author"
 459                                },
 460                                extension.authors.join(", ")
 461                            ))
 462                            .size(LabelSize::Small),
 463                        ),
 464                    )
 465                    .child(Label::new("<>").size(LabelSize::Small)),
 466            )
 467            .child(
 468                h_flex()
 469                    .gap_2()
 470                    .justify_between()
 471                    .children(extension.description.as_ref().map(|description| {
 472                        div().overflow_x_hidden().text_ellipsis().child(
 473                            Label::new(description.clone())
 474                                .size(LabelSize::Small)
 475                                .color(Color::Default),
 476                        )
 477                    }))
 478                    .children(repository_url.map(|repository_url| {
 479                        IconButton::new(
 480                            SharedString::from(format!("repository-{}", extension.id)),
 481                            IconName::Github,
 482                        )
 483                        .icon_color(Color::Accent)
 484                        .icon_size(IconSize::Small)
 485                        .style(ButtonStyle::Filled)
 486                        .on_click(cx.listener({
 487                            let repository_url = repository_url.clone();
 488                            move |_, _, cx| {
 489                                cx.open_url(&repository_url);
 490                            }
 491                        }))
 492                        .tooltip(move |cx| Tooltip::text(repository_url.clone(), cx))
 493                    })),
 494            )
 495    }
 496
 497    fn render_remote_extension(
 498        &self,
 499        extension: &ExtensionMetadata,
 500        cx: &mut ViewContext<Self>,
 501    ) -> ExtensionCard {
 502        let this = cx.view().clone();
 503        let status = Self::extension_status(&extension.id, cx);
 504        let has_dev_extension = Self::dev_extension_exists(&extension.id, cx);
 505
 506        let extension_id = extension.id.clone();
 507        let (install_or_uninstall_button, upgrade_button) =
 508            self.buttons_for_entry(extension, &status, has_dev_extension, cx);
 509        let version = extension.manifest.version.clone();
 510        let repository_url = extension.manifest.repository.clone();
 511
 512        let installed_version = match status {
 513            ExtensionStatus::Installed(installed_version) => Some(installed_version),
 514            _ => None,
 515        };
 516
 517        ExtensionCard::new()
 518            .overridden_by_dev_extension(has_dev_extension)
 519            .child(
 520                h_flex()
 521                    .justify_between()
 522                    .child(
 523                        h_flex()
 524                            .gap_2()
 525                            .items_end()
 526                            .child(
 527                                Headline::new(extension.manifest.name.clone())
 528                                    .size(HeadlineSize::Medium),
 529                            )
 530                            .child(Headline::new(format!("v{version}")).size(HeadlineSize::XSmall))
 531                            .children(
 532                                installed_version
 533                                    .filter(|installed_version| *installed_version != version)
 534                                    .map(|installed_version| {
 535                                        Headline::new(format!("(v{installed_version} installed)",))
 536                                            .size(HeadlineSize::XSmall)
 537                                    }),
 538                            ),
 539                    )
 540                    .child(
 541                        h_flex()
 542                            .gap_2()
 543                            .justify_between()
 544                            .children(upgrade_button)
 545                            .child(install_or_uninstall_button),
 546                    ),
 547            )
 548            .child(
 549                h_flex()
 550                    .gap_2()
 551                    .justify_between()
 552                    .child(
 553                        div().overflow_x_hidden().text_ellipsis().child(
 554                            Label::new(format!(
 555                                "{}: {}",
 556                                if extension.manifest.authors.len() > 1 {
 557                                    "Authors"
 558                                } else {
 559                                    "Author"
 560                                },
 561                                extension.manifest.authors.join(", ")
 562                            ))
 563                            .size(LabelSize::Small),
 564                        ),
 565                    )
 566                    .child(
 567                        Label::new(format!(
 568                            "Downloads: {}",
 569                            extension.download_count.to_formatted_string(&Locale::en)
 570                        ))
 571                        .size(LabelSize::Small),
 572                    ),
 573            )
 574            .child(
 575                h_flex()
 576                    .gap_2()
 577                    .justify_between()
 578                    .children(extension.manifest.description.as_ref().map(|description| {
 579                        div().overflow_x_hidden().text_ellipsis().child(
 580                            Label::new(description.clone())
 581                                .size(LabelSize::Small)
 582                                .color(Color::Default),
 583                        )
 584                    }))
 585                    .child(
 586                        h_flex()
 587                            .gap_2()
 588                            .child(
 589                                IconButton::new(
 590                                    SharedString::from(format!("repository-{}", extension.id)),
 591                                    IconName::Github,
 592                                )
 593                                .icon_color(Color::Accent)
 594                                .icon_size(IconSize::Small)
 595                                .style(ButtonStyle::Filled)
 596                                .on_click(cx.listener({
 597                                    let repository_url = repository_url.clone();
 598                                    move |_, _, cx| {
 599                                        cx.open_url(&repository_url);
 600                                    }
 601                                }))
 602                                .tooltip(move |cx| Tooltip::text(repository_url.clone(), cx)),
 603                            )
 604                            .child(
 605                                PopoverMenu::new(SharedString::from(format!(
 606                                    "more-{}",
 607                                    extension.id
 608                                )))
 609                                .trigger(
 610                                    IconButton::new(
 611                                        SharedString::from(format!("more-{}", extension.id)),
 612                                        IconName::Ellipsis,
 613                                    )
 614                                    .icon_color(Color::Accent)
 615                                    .icon_size(IconSize::Small)
 616                                    .style(ButtonStyle::Filled),
 617                                )
 618                                .menu(move |cx| {
 619                                    Some(Self::render_remote_extension_context_menu(
 620                                        &this,
 621                                        extension_id.clone(),
 622                                        cx,
 623                                    ))
 624                                }),
 625                            ),
 626                    ),
 627            )
 628    }
 629
 630    fn render_remote_extension_context_menu(
 631        this: &View<Self>,
 632        extension_id: Arc<str>,
 633        cx: &mut WindowContext,
 634    ) -> View<ContextMenu> {
 635        let context_menu = ContextMenu::build(cx, |context_menu, cx| {
 636            context_menu
 637                .entry(
 638                    "Install Another Version...",
 639                    None,
 640                    cx.handler_for(this, {
 641                        let extension_id = extension_id.clone();
 642                        move |this, cx| this.show_extension_version_list(extension_id.clone(), cx)
 643                    }),
 644                )
 645                .entry("Copy Extension ID", None, {
 646                    let extension_id = extension_id.clone();
 647                    move |cx| {
 648                        cx.write_to_clipboard(ClipboardItem::new_string(extension_id.to_string()));
 649                    }
 650                })
 651        });
 652
 653        context_menu
 654    }
 655
 656    fn show_extension_version_list(&mut self, extension_id: Arc<str>, cx: &mut ViewContext<Self>) {
 657        let Some(workspace) = self.workspace.upgrade() else {
 658            return;
 659        };
 660
 661        cx.spawn(move |this, mut cx| async move {
 662            let extension_versions_task = this.update(&mut cx, |_, cx| {
 663                let extension_store = ExtensionStore::global(cx);
 664
 665                extension_store.update(cx, |store, cx| {
 666                    store.fetch_extension_versions(&extension_id, cx)
 667                })
 668            })?;
 669
 670            let extension_versions = extension_versions_task.await?;
 671
 672            workspace.update(&mut cx, |workspace, cx| {
 673                let fs = workspace.project().read(cx).fs().clone();
 674                workspace.toggle_modal(cx, |cx| {
 675                    let delegate = ExtensionVersionSelectorDelegate::new(
 676                        fs,
 677                        cx.view().downgrade(),
 678                        extension_versions,
 679                    );
 680
 681                    ExtensionVersionSelector::new(delegate, cx)
 682                });
 683            })?;
 684
 685            anyhow::Ok(())
 686        })
 687        .detach_and_log_err(cx);
 688    }
 689
 690    fn buttons_for_entry(
 691        &self,
 692        extension: &ExtensionMetadata,
 693        status: &ExtensionStatus,
 694        has_dev_extension: bool,
 695        cx: &mut ViewContext<Self>,
 696    ) -> (Button, Option<Button>) {
 697        let is_compatible =
 698            extension_host::is_version_compatible(ReleaseChannel::global(cx), extension);
 699
 700        if has_dev_extension {
 701            // If we have a dev extension for the given extension, just treat it as uninstalled.
 702            // The button here is a placeholder, as it won't be interactable anyways.
 703            return (
 704                Button::new(SharedString::from(extension.id.clone()), "Install"),
 705                None,
 706            );
 707        }
 708
 709        match status.clone() {
 710            ExtensionStatus::NotInstalled => (
 711                Button::new(SharedString::from(extension.id.clone()), "Install").on_click(
 712                    cx.listener({
 713                        let extension_id = extension.id.clone();
 714                        move |this, _, cx| {
 715                            this.telemetry
 716                                .report_app_event("extensions: install extension".to_string());
 717                            ExtensionStore::global(cx).update(cx, |store, cx| {
 718                                store.install_latest_extension(extension_id.clone(), cx)
 719                            });
 720                        }
 721                    }),
 722                ),
 723                None,
 724            ),
 725            ExtensionStatus::Installing => (
 726                Button::new(SharedString::from(extension.id.clone()), "Install").disabled(true),
 727                None,
 728            ),
 729            ExtensionStatus::Upgrading => (
 730                Button::new(SharedString::from(extension.id.clone()), "Uninstall").disabled(true),
 731                Some(
 732                    Button::new(SharedString::from(extension.id.clone()), "Upgrade").disabled(true),
 733                ),
 734            ),
 735            ExtensionStatus::Installed(installed_version) => (
 736                Button::new(SharedString::from(extension.id.clone()), "Uninstall").on_click(
 737                    cx.listener({
 738                        let extension_id = extension.id.clone();
 739                        move |this, _, cx| {
 740                            this.telemetry
 741                                .report_app_event("extensions: uninstall extension".to_string());
 742                            ExtensionStore::global(cx).update(cx, |store, cx| {
 743                                store.uninstall_extension(extension_id.clone(), cx)
 744                            });
 745                        }
 746                    }),
 747                ),
 748                if installed_version == extension.manifest.version {
 749                    None
 750                } else {
 751                    Some(
 752                        Button::new(SharedString::from(extension.id.clone()), "Upgrade")
 753                            .when(!is_compatible, |upgrade_button| {
 754                                upgrade_button.disabled(true).tooltip({
 755                                    let version = extension.manifest.version.clone();
 756                                    move |cx| {
 757                                        Tooltip::text(
 758                                            format!(
 759                                                "v{version} is not compatible with this version of Zed.",
 760                                            ),
 761                                            cx,
 762                                        )
 763                                    }
 764                                })
 765                            })
 766                            .disabled(!is_compatible)
 767                            .on_click(cx.listener({
 768                                let extension_id = extension.id.clone();
 769                                let version = extension.manifest.version.clone();
 770                                move |this, _, cx| {
 771                                    this.telemetry.report_app_event(
 772                                        "extensions: install extension".to_string(),
 773                                    );
 774                                    ExtensionStore::global(cx).update(cx, |store, cx| {
 775                                        store
 776                                            .upgrade_extension(
 777                                                extension_id.clone(),
 778                                                version.clone(),
 779                                                cx,
 780                                            )
 781                                            .detach_and_log_err(cx)
 782                                    });
 783                                }
 784                            })),
 785                    )
 786                },
 787            ),
 788            ExtensionStatus::Removing => (
 789                Button::new(SharedString::from(extension.id.clone()), "Uninstall").disabled(true),
 790                None,
 791            ),
 792        }
 793    }
 794
 795    fn render_search(&self, cx: &mut ViewContext<Self>) -> Div {
 796        let mut key_context = KeyContext::new_with_defaults();
 797        key_context.add("BufferSearchBar");
 798
 799        let editor_border = if self.query_contains_error {
 800            Color::Error.color(cx)
 801        } else {
 802            cx.theme().colors().border
 803        };
 804
 805        h_flex().w_full().gap_2().key_context(key_context).child(
 806            h_flex()
 807                .flex_1()
 808                .px_2()
 809                .py_1()
 810                .gap_2()
 811                .border_1()
 812                .border_color(editor_border)
 813                .min_w(rems_from_px(384.))
 814                .rounded_lg()
 815                .child(Icon::new(IconName::MagnifyingGlass))
 816                .child(self.render_text_input(&self.query_editor, cx)),
 817        )
 818    }
 819
 820    fn render_text_input(&self, editor: &View<Editor>, cx: &ViewContext<Self>) -> impl IntoElement {
 821        let settings = ThemeSettings::get_global(cx);
 822        let text_style = TextStyle {
 823            color: if editor.read(cx).read_only(cx) {
 824                cx.theme().colors().text_disabled
 825            } else {
 826                cx.theme().colors().text
 827            },
 828            font_family: settings.ui_font.family.clone(),
 829            font_features: settings.ui_font.features.clone(),
 830            font_fallbacks: settings.ui_font.fallbacks.clone(),
 831            font_size: rems(0.875).into(),
 832            font_weight: settings.ui_font.weight,
 833            line_height: relative(1.3),
 834            ..Default::default()
 835        };
 836
 837        EditorElement::new(
 838            editor,
 839            EditorStyle {
 840                background: cx.theme().colors().editor_background,
 841                local_player: cx.theme().players().local(),
 842                text: text_style,
 843                ..Default::default()
 844            },
 845        )
 846    }
 847
 848    fn on_query_change(
 849        &mut self,
 850        _: View<Editor>,
 851        event: &editor::EditorEvent,
 852        cx: &mut ViewContext<Self>,
 853    ) {
 854        if let editor::EditorEvent::Edited { .. } = event {
 855            self.query_contains_error = false;
 856            self.fetch_extensions_debounced(cx);
 857            self.refresh_feature_upsells(cx);
 858        }
 859    }
 860
 861    fn fetch_extensions_debounced(&mut self, cx: &mut ViewContext<'_, ExtensionsPage>) {
 862        self.extension_fetch_task = Some(cx.spawn(|this, mut cx| async move {
 863            let search = this
 864                .update(&mut cx, |this, cx| this.search_query(cx))
 865                .ok()
 866                .flatten();
 867
 868            // Only debounce the fetching of extensions if we have a search
 869            // query.
 870            //
 871            // If the search was just cleared then we can just reload the list
 872            // of extensions without a debounce, which allows us to avoid seeing
 873            // an intermittent flash of a "no extensions" state.
 874            if search.is_some() {
 875                cx.background_executor()
 876                    .timer(Duration::from_millis(250))
 877                    .await;
 878            };
 879
 880            this.update(&mut cx, |this, cx| {
 881                this.fetch_extensions(search, cx);
 882            })
 883            .ok();
 884        }));
 885    }
 886
 887    pub fn search_query(&self, cx: &WindowContext) -> Option<String> {
 888        let search = self.query_editor.read(cx).text(cx);
 889        if search.trim().is_empty() {
 890            None
 891        } else {
 892            Some(search)
 893        }
 894    }
 895
 896    fn render_empty_state(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 897        let has_search = self.search_query(cx).is_some();
 898
 899        let message = if self.is_fetching_extensions {
 900            "Loading extensions..."
 901        } else {
 902            match self.filter {
 903                ExtensionFilter::All => {
 904                    if has_search {
 905                        "No extensions that match your search."
 906                    } else {
 907                        "No extensions."
 908                    }
 909                }
 910                ExtensionFilter::Installed => {
 911                    if has_search {
 912                        "No installed extensions that match your search."
 913                    } else {
 914                        "No installed extensions."
 915                    }
 916                }
 917                ExtensionFilter::NotInstalled => {
 918                    if has_search {
 919                        "No not installed extensions that match your search."
 920                    } else {
 921                        "No not installed extensions."
 922                    }
 923                }
 924            }
 925        };
 926
 927        Label::new(message)
 928    }
 929
 930    fn update_settings<T: Settings>(
 931        &mut self,
 932        selection: &ToggleState,
 933        cx: &mut ViewContext<Self>,
 934        callback: impl 'static + Send + Fn(&mut T::FileContent, bool),
 935    ) {
 936        if let Some(workspace) = self.workspace.upgrade() {
 937            let fs = workspace.read(cx).app_state().fs.clone();
 938            let selection = *selection;
 939            settings::update_settings_file::<T>(fs, cx, move |settings, _| {
 940                let value = match selection {
 941                    ToggleState::Unselected => false,
 942                    ToggleState::Selected => true,
 943                    _ => return,
 944                };
 945
 946                callback(settings, value)
 947            });
 948        }
 949    }
 950
 951    fn refresh_feature_upsells(&mut self, cx: &mut ViewContext<Self>) {
 952        let Some(search) = self.search_query(cx) else {
 953            self.upsells.clear();
 954            return;
 955        };
 956
 957        let search = search.to_lowercase();
 958        let search_terms = search
 959            .split_whitespace()
 960            .map(|term| term.trim())
 961            .collect::<Vec<_>>();
 962
 963        for (feature, keywords) in keywords_by_feature() {
 964            if keywords
 965                .iter()
 966                .any(|keyword| search_terms.contains(keyword))
 967            {
 968                self.upsells.insert(*feature);
 969            } else {
 970                self.upsells.remove(feature);
 971            }
 972        }
 973    }
 974
 975    fn render_feature_upsells(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 976        let upsells_count = self.upsells.len();
 977
 978        v_flex().children(self.upsells.iter().enumerate().map(|(ix, feature)| {
 979            let telemetry = self.telemetry.clone();
 980            let upsell = match feature {
 981                Feature::Git => FeatureUpsell::new(
 982                    telemetry,
 983                    "Zed comes with basic Git support. More Git features are coming in the future.",
 984                )
 985                .docs_url("https://zed.dev/docs/git"),
 986                Feature::OpenIn => FeatureUpsell::new(
 987                    telemetry,
 988                    "Zed supports linking to a source line on GitHub and others.",
 989                )
 990                .docs_url("https://zed.dev/docs/git#git-integrations"),
 991                Feature::Vim => FeatureUpsell::new(telemetry, "Vim support is built-in to Zed!")
 992                    .docs_url("https://zed.dev/docs/vim")
 993                    .child(CheckboxWithLabel::new(
 994                        "enable-vim",
 995                        Label::new("Enable vim mode"),
 996                        if VimModeSetting::get_global(cx).0 {
 997                            ui::ToggleState::Selected
 998                        } else {
 999                            ui::ToggleState::Unselected
1000                        },
1001                        cx.listener(move |this, selection, cx| {
1002                            this.telemetry
1003                                .report_app_event("feature upsell: toggle vim".to_string());
1004                            this.update_settings::<VimModeSetting>(
1005                                selection,
1006                                cx,
1007                                |setting, value| *setting = Some(value),
1008                            );
1009                        }),
1010                    )),
1011                Feature::LanguageBash => {
1012                    FeatureUpsell::new(telemetry, "Shell support is built-in to Zed!")
1013                        .docs_url("https://zed.dev/docs/languages/bash")
1014                }
1015                Feature::LanguageC => {
1016                    FeatureUpsell::new(telemetry, "C support is built-in to Zed!")
1017                        .docs_url("https://zed.dev/docs/languages/c")
1018                }
1019                Feature::LanguageCpp => {
1020                    FeatureUpsell::new(telemetry, "C++ support is built-in to Zed!")
1021                        .docs_url("https://zed.dev/docs/languages/cpp")
1022                }
1023                Feature::LanguageGo => {
1024                    FeatureUpsell::new(telemetry, "Go support is built-in to Zed!")
1025                        .docs_url("https://zed.dev/docs/languages/go")
1026                }
1027                Feature::LanguagePython => {
1028                    FeatureUpsell::new(telemetry, "Python support is built-in to Zed!")
1029                        .docs_url("https://zed.dev/docs/languages/python")
1030                }
1031                Feature::LanguageReact => {
1032                    FeatureUpsell::new(telemetry, "React support is built-in to Zed!")
1033                        .docs_url("https://zed.dev/docs/languages/typescript")
1034                }
1035                Feature::LanguageRust => {
1036                    FeatureUpsell::new(telemetry, "Rust support is built-in to Zed!")
1037                        .docs_url("https://zed.dev/docs/languages/rust")
1038                }
1039                Feature::LanguageTypescript => {
1040                    FeatureUpsell::new(telemetry, "Typescript support is built-in to Zed!")
1041                        .docs_url("https://zed.dev/docs/languages/typescript")
1042                }
1043            };
1044
1045            upsell.when(ix < upsells_count, |upsell| upsell.border_b_1())
1046        }))
1047    }
1048}
1049
1050impl Render for ExtensionsPage {
1051    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1052        v_flex()
1053            .size_full()
1054            .bg(cx.theme().colors().editor_background)
1055            .child(
1056                v_flex()
1057                    .gap_4()
1058                    .p_4()
1059                    .border_b_1()
1060                    .border_color(cx.theme().colors().border)
1061                    .bg(cx.theme().colors().editor_background)
1062                    .child(
1063                        h_flex()
1064                            .w_full()
1065                            .gap_2()
1066                            .justify_between()
1067                            .child(Headline::new("Extensions").size(HeadlineSize::XLarge))
1068                            .child(
1069                                Button::new("install-dev-extension", "Install Dev Extension")
1070                                    .style(ButtonStyle::Filled)
1071                                    .size(ButtonSize::Large)
1072                                    .on_click(|_event, cx| {
1073                                        cx.dispatch_action(Box::new(InstallDevExtension))
1074                                    }),
1075                            ),
1076                    )
1077                    .child(
1078                        h_flex()
1079                            .w_full()
1080                            .gap_2()
1081                            .justify_between()
1082                            .child(h_flex().child(self.render_search(cx)))
1083                            .child(
1084                                h_flex()
1085                                    .child(
1086                                        ToggleButton::new("filter-all", "All")
1087                                            .style(ButtonStyle::Filled)
1088                                            .size(ButtonSize::Large)
1089                                            .toggle_state(self.filter == ExtensionFilter::All)
1090                                            .on_click(cx.listener(|this, _event, cx| {
1091                                                this.filter = ExtensionFilter::All;
1092                                                this.filter_extension_entries(cx);
1093                                            }))
1094                                            .tooltip(move |cx| {
1095                                                Tooltip::text("Show all extensions", cx)
1096                                            })
1097                                            .first(),
1098                                    )
1099                                    .child(
1100                                        ToggleButton::new("filter-installed", "Installed")
1101                                            .style(ButtonStyle::Filled)
1102                                            .size(ButtonSize::Large)
1103                                            .toggle_state(self.filter == ExtensionFilter::Installed)
1104                                            .on_click(cx.listener(|this, _event, cx| {
1105                                                this.filter = ExtensionFilter::Installed;
1106                                                this.filter_extension_entries(cx);
1107                                            }))
1108                                            .tooltip(move |cx| {
1109                                                Tooltip::text("Show installed extensions", cx)
1110                                            })
1111                                            .middle(),
1112                                    )
1113                                    .child(
1114                                        ToggleButton::new("filter-not-installed", "Not Installed")
1115                                            .style(ButtonStyle::Filled)
1116                                            .size(ButtonSize::Large)
1117                                            .toggle_state(
1118                                                self.filter == ExtensionFilter::NotInstalled,
1119                                            )
1120                                            .on_click(cx.listener(|this, _event, cx| {
1121                                                this.filter = ExtensionFilter::NotInstalled;
1122                                                this.filter_extension_entries(cx);
1123                                            }))
1124                                            .tooltip(move |cx| {
1125                                                Tooltip::text("Show not installed extensions", cx)
1126                                            })
1127                                            .last(),
1128                                    ),
1129                            ),
1130                    ),
1131            )
1132            .child(self.render_feature_upsells(cx))
1133            .child(v_flex().px_4().size_full().overflow_y_hidden().map(|this| {
1134                let mut count = self.filtered_remote_extension_indices.len();
1135                if self.filter.include_dev_extensions() {
1136                    count += self.dev_extension_entries.len();
1137                }
1138
1139                if count == 0 {
1140                    return this.py_4().child(self.render_empty_state(cx));
1141                }
1142
1143                let view = cx.view().clone();
1144                let scroll_handle = self.list.clone();
1145                this.child(
1146                    uniform_list(view, "entries", count, Self::render_extensions)
1147                        .flex_grow()
1148                        .pb_4()
1149                        .track_scroll(scroll_handle),
1150                )
1151            }))
1152    }
1153}
1154
1155impl EventEmitter<ItemEvent> for ExtensionsPage {}
1156
1157impl FocusableView for ExtensionsPage {
1158    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
1159        self.query_editor.read(cx).focus_handle(cx)
1160    }
1161}
1162
1163impl Item for ExtensionsPage {
1164    type Event = ItemEvent;
1165
1166    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
1167        Some("Extensions".into())
1168    }
1169
1170    fn telemetry_event_text(&self) -> Option<&'static str> {
1171        Some("extensions page")
1172    }
1173
1174    fn show_toolbar(&self) -> bool {
1175        false
1176    }
1177
1178    fn clone_on_split(
1179        &self,
1180        _workspace_id: Option<WorkspaceId>,
1181        _: &mut ViewContext<Self>,
1182    ) -> Option<View<Self>> {
1183        None
1184    }
1185
1186    fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
1187        f(*event)
1188    }
1189}