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 {
 332                        id: ix,
 333                        string: manifest.name.clone(),
 334                        char_bag: manifest.name.as_str().into(),
 335                    })
 336                    .collect::<Vec<_>>();
 337
 338                let matches = match_strings(
 339                    &match_candidates,
 340                    &search,
 341                    false,
 342                    match_candidates.len(),
 343                    &Default::default(),
 344                    cx.background_executor().clone(),
 345                )
 346                .await;
 347                matches
 348                    .into_iter()
 349                    .map(|mat| dev_extensions[mat.candidate_id].clone())
 350                    .collect()
 351            } else {
 352                dev_extensions
 353            };
 354
 355            let fetch_result = remote_extensions.await;
 356            this.update(&mut cx, |this, cx| {
 357                cx.notify();
 358                this.dev_extension_entries = dev_extensions;
 359                this.is_fetching_extensions = false;
 360                this.remote_extension_entries = fetch_result?;
 361                this.filter_extension_entries(cx);
 362                anyhow::Ok(())
 363            })?
 364        })
 365        .detach_and_log_err(cx);
 366    }
 367
 368    fn render_extensions(
 369        &mut self,
 370        range: Range<usize>,
 371        cx: &mut ViewContext<Self>,
 372    ) -> Vec<ExtensionCard> {
 373        let dev_extension_entries_len = if self.filter.include_dev_extensions() {
 374            self.dev_extension_entries.len()
 375        } else {
 376            0
 377        };
 378        range
 379            .map(|ix| {
 380                if ix < dev_extension_entries_len {
 381                    let extension = &self.dev_extension_entries[ix];
 382                    self.render_dev_extension(extension, cx)
 383                } else {
 384                    let extension_ix =
 385                        self.filtered_remote_extension_indices[ix - dev_extension_entries_len];
 386                    let extension = &self.remote_extension_entries[extension_ix];
 387                    self.render_remote_extension(extension, cx)
 388                }
 389            })
 390            .collect()
 391    }
 392
 393    fn render_dev_extension(
 394        &self,
 395        extension: &ExtensionManifest,
 396        cx: &mut ViewContext<Self>,
 397    ) -> ExtensionCard {
 398        let status = Self::extension_status(&extension.id, cx);
 399
 400        let repository_url = extension.repository.clone();
 401
 402        ExtensionCard::new()
 403            .child(
 404                h_flex()
 405                    .justify_between()
 406                    .child(
 407                        h_flex()
 408                            .gap_2()
 409                            .items_end()
 410                            .child(Headline::new(extension.name.clone()).size(HeadlineSize::Medium))
 411                            .child(
 412                                Headline::new(format!("v{}", extension.version))
 413                                    .size(HeadlineSize::XSmall),
 414                            ),
 415                    )
 416                    .child(
 417                        h_flex()
 418                            .gap_2()
 419                            .justify_between()
 420                            .child(
 421                                Button::new(
 422                                    SharedString::from(format!("rebuild-{}", extension.id)),
 423                                    "Rebuild",
 424                                )
 425                                .on_click({
 426                                    let extension_id = extension.id.clone();
 427                                    move |_, cx| {
 428                                        ExtensionStore::global(cx).update(cx, |store, cx| {
 429                                            store.rebuild_dev_extension(extension_id.clone(), cx)
 430                                        });
 431                                    }
 432                                })
 433                                .color(Color::Accent)
 434                                .disabled(matches!(status, ExtensionStatus::Upgrading)),
 435                            )
 436                            .child(
 437                                Button::new(SharedString::from(extension.id.clone()), "Uninstall")
 438                                    .on_click({
 439                                        let extension_id = extension.id.clone();
 440                                        move |_, cx| {
 441                                            ExtensionStore::global(cx).update(cx, |store, cx| {
 442                                                store.uninstall_extension(extension_id.clone(), cx)
 443                                            });
 444                                        }
 445                                    })
 446                                    .color(Color::Accent)
 447                                    .disabled(matches!(status, ExtensionStatus::Removing)),
 448                            ),
 449                    ),
 450            )
 451            .child(
 452                h_flex()
 453                    .gap_2()
 454                    .justify_between()
 455                    .child(
 456                        div().overflow_x_hidden().text_ellipsis().child(
 457                            Label::new(format!(
 458                                "{}: {}",
 459                                if extension.authors.len() > 1 {
 460                                    "Authors"
 461                                } else {
 462                                    "Author"
 463                                },
 464                                extension.authors.join(", ")
 465                            ))
 466                            .size(LabelSize::Small),
 467                        ),
 468                    )
 469                    .child(Label::new("<>").size(LabelSize::Small)),
 470            )
 471            .child(
 472                h_flex()
 473                    .gap_2()
 474                    .justify_between()
 475                    .children(extension.description.as_ref().map(|description| {
 476                        div().overflow_x_hidden().text_ellipsis().child(
 477                            Label::new(description.clone())
 478                                .size(LabelSize::Small)
 479                                .color(Color::Default),
 480                        )
 481                    }))
 482                    .children(repository_url.map(|repository_url| {
 483                        IconButton::new(
 484                            SharedString::from(format!("repository-{}", extension.id)),
 485                            IconName::Github,
 486                        )
 487                        .icon_color(Color::Accent)
 488                        .icon_size(IconSize::Small)
 489                        .style(ButtonStyle::Filled)
 490                        .on_click(cx.listener({
 491                            let repository_url = repository_url.clone();
 492                            move |_, _, cx| {
 493                                cx.open_url(&repository_url);
 494                            }
 495                        }))
 496                        .tooltip(move |cx| Tooltip::text(repository_url.clone(), cx))
 497                    })),
 498            )
 499    }
 500
 501    fn render_remote_extension(
 502        &self,
 503        extension: &ExtensionMetadata,
 504        cx: &mut ViewContext<Self>,
 505    ) -> ExtensionCard {
 506        let this = cx.view().clone();
 507        let status = Self::extension_status(&extension.id, cx);
 508        let has_dev_extension = Self::dev_extension_exists(&extension.id, cx);
 509
 510        let extension_id = extension.id.clone();
 511        let (install_or_uninstall_button, upgrade_button) =
 512            self.buttons_for_entry(extension, &status, has_dev_extension, cx);
 513        let version = extension.manifest.version.clone();
 514        let repository_url = extension.manifest.repository.clone();
 515
 516        let installed_version = match status {
 517            ExtensionStatus::Installed(installed_version) => Some(installed_version),
 518            _ => None,
 519        };
 520
 521        ExtensionCard::new()
 522            .overridden_by_dev_extension(has_dev_extension)
 523            .child(
 524                h_flex()
 525                    .justify_between()
 526                    .child(
 527                        h_flex()
 528                            .gap_2()
 529                            .items_end()
 530                            .child(
 531                                Headline::new(extension.manifest.name.clone())
 532                                    .size(HeadlineSize::Medium),
 533                            )
 534                            .child(Headline::new(format!("v{version}")).size(HeadlineSize::XSmall))
 535                            .children(
 536                                installed_version
 537                                    .filter(|installed_version| *installed_version != version)
 538                                    .map(|installed_version| {
 539                                        Headline::new(format!("(v{installed_version} installed)",))
 540                                            .size(HeadlineSize::XSmall)
 541                                    }),
 542                            ),
 543                    )
 544                    .child(
 545                        h_flex()
 546                            .gap_2()
 547                            .justify_between()
 548                            .children(upgrade_button)
 549                            .child(install_or_uninstall_button),
 550                    ),
 551            )
 552            .child(
 553                h_flex()
 554                    .gap_2()
 555                    .justify_between()
 556                    .child(
 557                        div().overflow_x_hidden().text_ellipsis().child(
 558                            Label::new(format!(
 559                                "{}: {}",
 560                                if extension.manifest.authors.len() > 1 {
 561                                    "Authors"
 562                                } else {
 563                                    "Author"
 564                                },
 565                                extension.manifest.authors.join(", ")
 566                            ))
 567                            .size(LabelSize::Small),
 568                        ),
 569                    )
 570                    .child(
 571                        Label::new(format!(
 572                            "Downloads: {}",
 573                            extension.download_count.to_formatted_string(&Locale::en)
 574                        ))
 575                        .size(LabelSize::Small),
 576                    ),
 577            )
 578            .child(
 579                h_flex()
 580                    .gap_2()
 581                    .justify_between()
 582                    .children(extension.manifest.description.as_ref().map(|description| {
 583                        div().overflow_x_hidden().text_ellipsis().child(
 584                            Label::new(description.clone())
 585                                .size(LabelSize::Small)
 586                                .color(Color::Default),
 587                        )
 588                    }))
 589                    .child(
 590                        h_flex()
 591                            .gap_2()
 592                            .child(
 593                                IconButton::new(
 594                                    SharedString::from(format!("repository-{}", extension.id)),
 595                                    IconName::Github,
 596                                )
 597                                .icon_color(Color::Accent)
 598                                .icon_size(IconSize::Small)
 599                                .style(ButtonStyle::Filled)
 600                                .on_click(cx.listener({
 601                                    let repository_url = repository_url.clone();
 602                                    move |_, _, cx| {
 603                                        cx.open_url(&repository_url);
 604                                    }
 605                                }))
 606                                .tooltip(move |cx| Tooltip::text(repository_url.clone(), cx)),
 607                            )
 608                            .child(
 609                                PopoverMenu::new(SharedString::from(format!(
 610                                    "more-{}",
 611                                    extension.id
 612                                )))
 613                                .trigger(
 614                                    IconButton::new(
 615                                        SharedString::from(format!("more-{}", extension.id)),
 616                                        IconName::Ellipsis,
 617                                    )
 618                                    .icon_color(Color::Accent)
 619                                    .icon_size(IconSize::Small)
 620                                    .style(ButtonStyle::Filled),
 621                                )
 622                                .menu(move |cx| {
 623                                    Some(Self::render_remote_extension_context_menu(
 624                                        &this,
 625                                        extension_id.clone(),
 626                                        cx,
 627                                    ))
 628                                }),
 629                            ),
 630                    ),
 631            )
 632    }
 633
 634    fn render_remote_extension_context_menu(
 635        this: &View<Self>,
 636        extension_id: Arc<str>,
 637        cx: &mut WindowContext,
 638    ) -> View<ContextMenu> {
 639        let context_menu = ContextMenu::build(cx, |context_menu, cx| {
 640            context_menu
 641                .entry(
 642                    "Install Another Version...",
 643                    None,
 644                    cx.handler_for(this, {
 645                        let extension_id = extension_id.clone();
 646                        move |this, cx| this.show_extension_version_list(extension_id.clone(), cx)
 647                    }),
 648                )
 649                .entry("Copy Extension ID", None, {
 650                    let extension_id = extension_id.clone();
 651                    move |cx| {
 652                        cx.write_to_clipboard(ClipboardItem::new_string(extension_id.to_string()));
 653                    }
 654                })
 655        });
 656
 657        context_menu
 658    }
 659
 660    fn show_extension_version_list(&mut self, extension_id: Arc<str>, cx: &mut ViewContext<Self>) {
 661        let Some(workspace) = self.workspace.upgrade() else {
 662            return;
 663        };
 664
 665        cx.spawn(move |this, mut cx| async move {
 666            let extension_versions_task = this.update(&mut cx, |_, cx| {
 667                let extension_store = ExtensionStore::global(cx);
 668
 669                extension_store.update(cx, |store, cx| {
 670                    store.fetch_extension_versions(&extension_id, cx)
 671                })
 672            })?;
 673
 674            let extension_versions = extension_versions_task.await?;
 675
 676            workspace.update(&mut cx, |workspace, cx| {
 677                let fs = workspace.project().read(cx).fs().clone();
 678                workspace.toggle_modal(cx, |cx| {
 679                    let delegate = ExtensionVersionSelectorDelegate::new(
 680                        fs,
 681                        cx.view().downgrade(),
 682                        extension_versions,
 683                    );
 684
 685                    ExtensionVersionSelector::new(delegate, cx)
 686                });
 687            })?;
 688
 689            anyhow::Ok(())
 690        })
 691        .detach_and_log_err(cx);
 692    }
 693
 694    fn buttons_for_entry(
 695        &self,
 696        extension: &ExtensionMetadata,
 697        status: &ExtensionStatus,
 698        has_dev_extension: bool,
 699        cx: &mut ViewContext<Self>,
 700    ) -> (Button, Option<Button>) {
 701        let is_compatible =
 702            extension_host::is_version_compatible(ReleaseChannel::global(cx), extension);
 703
 704        if has_dev_extension {
 705            // If we have a dev extension for the given extension, just treat it as uninstalled.
 706            // The button here is a placeholder, as it won't be interactable anyways.
 707            return (
 708                Button::new(SharedString::from(extension.id.clone()), "Install"),
 709                None,
 710            );
 711        }
 712
 713        match status.clone() {
 714            ExtensionStatus::NotInstalled => (
 715                Button::new(SharedString::from(extension.id.clone()), "Install").on_click(
 716                    cx.listener({
 717                        let extension_id = extension.id.clone();
 718                        move |this, _, cx| {
 719                            this.telemetry
 720                                .report_app_event("extensions: install extension".to_string());
 721                            ExtensionStore::global(cx).update(cx, |store, cx| {
 722                                store.install_latest_extension(extension_id.clone(), cx)
 723                            });
 724                        }
 725                    }),
 726                ),
 727                None,
 728            ),
 729            ExtensionStatus::Installing => (
 730                Button::new(SharedString::from(extension.id.clone()), "Install").disabled(true),
 731                None,
 732            ),
 733            ExtensionStatus::Upgrading => (
 734                Button::new(SharedString::from(extension.id.clone()), "Uninstall").disabled(true),
 735                Some(
 736                    Button::new(SharedString::from(extension.id.clone()), "Upgrade").disabled(true),
 737                ),
 738            ),
 739            ExtensionStatus::Installed(installed_version) => (
 740                Button::new(SharedString::from(extension.id.clone()), "Uninstall").on_click(
 741                    cx.listener({
 742                        let extension_id = extension.id.clone();
 743                        move |this, _, cx| {
 744                            this.telemetry
 745                                .report_app_event("extensions: uninstall extension".to_string());
 746                            ExtensionStore::global(cx).update(cx, |store, cx| {
 747                                store.uninstall_extension(extension_id.clone(), cx)
 748                            });
 749                        }
 750                    }),
 751                ),
 752                if installed_version == extension.manifest.version {
 753                    None
 754                } else {
 755                    Some(
 756                        Button::new(SharedString::from(extension.id.clone()), "Upgrade")
 757                            .when(!is_compatible, |upgrade_button| {
 758                                upgrade_button.disabled(true).tooltip({
 759                                    let version = extension.manifest.version.clone();
 760                                    move |cx| {
 761                                        Tooltip::text(
 762                                            format!(
 763                                                "v{version} is not compatible with this version of Zed.",
 764                                            ),
 765                                            cx,
 766                                        )
 767                                    }
 768                                })
 769                            })
 770                            .disabled(!is_compatible)
 771                            .on_click(cx.listener({
 772                                let extension_id = extension.id.clone();
 773                                let version = extension.manifest.version.clone();
 774                                move |this, _, cx| {
 775                                    this.telemetry.report_app_event(
 776                                        "extensions: install extension".to_string(),
 777                                    );
 778                                    ExtensionStore::global(cx).update(cx, |store, cx| {
 779                                        store
 780                                            .upgrade_extension(
 781                                                extension_id.clone(),
 782                                                version.clone(),
 783                                                cx,
 784                                            )
 785                                            .detach_and_log_err(cx)
 786                                    });
 787                                }
 788                            })),
 789                    )
 790                },
 791            ),
 792            ExtensionStatus::Removing => (
 793                Button::new(SharedString::from(extension.id.clone()), "Uninstall").disabled(true),
 794                None,
 795            ),
 796        }
 797    }
 798
 799    fn render_search(&self, cx: &mut ViewContext<Self>) -> Div {
 800        let mut key_context = KeyContext::new_with_defaults();
 801        key_context.add("BufferSearchBar");
 802
 803        let editor_border = if self.query_contains_error {
 804            Color::Error.color(cx)
 805        } else {
 806            cx.theme().colors().border
 807        };
 808
 809        h_flex().w_full().gap_2().key_context(key_context).child(
 810            h_flex()
 811                .flex_1()
 812                .px_2()
 813                .py_1()
 814                .gap_2()
 815                .border_1()
 816                .border_color(editor_border)
 817                .min_w(rems_from_px(384.))
 818                .rounded_lg()
 819                .child(Icon::new(IconName::MagnifyingGlass))
 820                .child(self.render_text_input(&self.query_editor, cx)),
 821        )
 822    }
 823
 824    fn render_text_input(&self, editor: &View<Editor>, cx: &ViewContext<Self>) -> impl IntoElement {
 825        let settings = ThemeSettings::get_global(cx);
 826        let text_style = TextStyle {
 827            color: if editor.read(cx).read_only(cx) {
 828                cx.theme().colors().text_disabled
 829            } else {
 830                cx.theme().colors().text
 831            },
 832            font_family: settings.ui_font.family.clone(),
 833            font_features: settings.ui_font.features.clone(),
 834            font_fallbacks: settings.ui_font.fallbacks.clone(),
 835            font_size: rems(0.875).into(),
 836            font_weight: settings.ui_font.weight,
 837            line_height: relative(1.3),
 838            ..Default::default()
 839        };
 840
 841        EditorElement::new(
 842            editor,
 843            EditorStyle {
 844                background: cx.theme().colors().editor_background,
 845                local_player: cx.theme().players().local(),
 846                text: text_style,
 847                ..Default::default()
 848            },
 849        )
 850    }
 851
 852    fn on_query_change(
 853        &mut self,
 854        _: View<Editor>,
 855        event: &editor::EditorEvent,
 856        cx: &mut ViewContext<Self>,
 857    ) {
 858        if let editor::EditorEvent::Edited { .. } = event {
 859            self.query_contains_error = false;
 860            self.fetch_extensions_debounced(cx);
 861            self.refresh_feature_upsells(cx);
 862        }
 863    }
 864
 865    fn fetch_extensions_debounced(&mut self, cx: &mut ViewContext<'_, ExtensionsPage>) {
 866        self.extension_fetch_task = Some(cx.spawn(|this, mut cx| async move {
 867            let search = this
 868                .update(&mut cx, |this, cx| this.search_query(cx))
 869                .ok()
 870                .flatten();
 871
 872            // Only debounce the fetching of extensions if we have a search
 873            // query.
 874            //
 875            // If the search was just cleared then we can just reload the list
 876            // of extensions without a debounce, which allows us to avoid seeing
 877            // an intermittent flash of a "no extensions" state.
 878            if search.is_some() {
 879                cx.background_executor()
 880                    .timer(Duration::from_millis(250))
 881                    .await;
 882            };
 883
 884            this.update(&mut cx, |this, cx| {
 885                this.fetch_extensions(search, cx);
 886            })
 887            .ok();
 888        }));
 889    }
 890
 891    pub fn search_query(&self, cx: &WindowContext) -> Option<String> {
 892        let search = self.query_editor.read(cx).text(cx);
 893        if search.trim().is_empty() {
 894            None
 895        } else {
 896            Some(search)
 897        }
 898    }
 899
 900    fn render_empty_state(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 901        let has_search = self.search_query(cx).is_some();
 902
 903        let message = if self.is_fetching_extensions {
 904            "Loading extensions..."
 905        } else {
 906            match self.filter {
 907                ExtensionFilter::All => {
 908                    if has_search {
 909                        "No extensions that match your search."
 910                    } else {
 911                        "No extensions."
 912                    }
 913                }
 914                ExtensionFilter::Installed => {
 915                    if has_search {
 916                        "No installed extensions that match your search."
 917                    } else {
 918                        "No installed extensions."
 919                    }
 920                }
 921                ExtensionFilter::NotInstalled => {
 922                    if has_search {
 923                        "No not installed extensions that match your search."
 924                    } else {
 925                        "No not installed extensions."
 926                    }
 927                }
 928            }
 929        };
 930
 931        Label::new(message)
 932    }
 933
 934    fn update_settings<T: Settings>(
 935        &mut self,
 936        selection: &Selection,
 937        cx: &mut ViewContext<Self>,
 938        callback: impl 'static + Send + Fn(&mut T::FileContent, bool),
 939    ) {
 940        if let Some(workspace) = self.workspace.upgrade() {
 941            let fs = workspace.read(cx).app_state().fs.clone();
 942            let selection = *selection;
 943            settings::update_settings_file::<T>(fs, cx, move |settings, _| {
 944                let value = match selection {
 945                    Selection::Unselected => false,
 946                    Selection::Selected => true,
 947                    _ => return,
 948                };
 949
 950                callback(settings, value)
 951            });
 952        }
 953    }
 954
 955    fn refresh_feature_upsells(&mut self, cx: &mut ViewContext<Self>) {
 956        let Some(search) = self.search_query(cx) else {
 957            self.upsells.clear();
 958            return;
 959        };
 960
 961        let search = search.to_lowercase();
 962        let search_terms = search
 963            .split_whitespace()
 964            .map(|term| term.trim())
 965            .collect::<Vec<_>>();
 966
 967        for (feature, keywords) in keywords_by_feature() {
 968            if keywords
 969                .iter()
 970                .any(|keyword| search_terms.contains(keyword))
 971            {
 972                self.upsells.insert(*feature);
 973            } else {
 974                self.upsells.remove(feature);
 975            }
 976        }
 977    }
 978
 979    fn render_feature_upsells(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 980        let upsells_count = self.upsells.len();
 981
 982        v_flex().children(self.upsells.iter().enumerate().map(|(ix, feature)| {
 983            let telemetry = self.telemetry.clone();
 984            let upsell = match feature {
 985                Feature::Git => FeatureUpsell::new(
 986                    telemetry,
 987                    "Zed comes with basic Git support. More Git features are coming in the future.",
 988                )
 989                .docs_url("https://zed.dev/docs/git"),
 990                Feature::OpenIn => FeatureUpsell::new(
 991                    telemetry,
 992                    "Zed supports linking to a source line on GitHub and others.",
 993                )
 994                .docs_url("https://zed.dev/docs/git#git-integrations"),
 995                Feature::Vim => FeatureUpsell::new(telemetry, "Vim support is built-in to Zed!")
 996                    .docs_url("https://zed.dev/docs/vim")
 997                    .child(CheckboxWithLabel::new(
 998                        "enable-vim",
 999                        Label::new("Enable vim mode"),
1000                        if VimModeSetting::get_global(cx).0 {
1001                            ui::Selection::Selected
1002                        } else {
1003                            ui::Selection::Unselected
1004                        },
1005                        cx.listener(move |this, selection, cx| {
1006                            this.telemetry
1007                                .report_app_event("feature upsell: toggle vim".to_string());
1008                            this.update_settings::<VimModeSetting>(
1009                                selection,
1010                                cx,
1011                                |setting, value| *setting = Some(value),
1012                            );
1013                        }),
1014                    )),
1015                Feature::LanguageBash => {
1016                    FeatureUpsell::new(telemetry, "Shell support is built-in to Zed!")
1017                        .docs_url("https://zed.dev/docs/languages/bash")
1018                }
1019                Feature::LanguageC => {
1020                    FeatureUpsell::new(telemetry, "C support is built-in to Zed!")
1021                        .docs_url("https://zed.dev/docs/languages/c")
1022                }
1023                Feature::LanguageCpp => {
1024                    FeatureUpsell::new(telemetry, "C++ support is built-in to Zed!")
1025                        .docs_url("https://zed.dev/docs/languages/cpp")
1026                }
1027                Feature::LanguageGo => {
1028                    FeatureUpsell::new(telemetry, "Go support is built-in to Zed!")
1029                        .docs_url("https://zed.dev/docs/languages/go")
1030                }
1031                Feature::LanguagePython => {
1032                    FeatureUpsell::new(telemetry, "Python support is built-in to Zed!")
1033                        .docs_url("https://zed.dev/docs/languages/python")
1034                }
1035                Feature::LanguageReact => {
1036                    FeatureUpsell::new(telemetry, "React support is built-in to Zed!")
1037                        .docs_url("https://zed.dev/docs/languages/typescript")
1038                }
1039                Feature::LanguageRust => {
1040                    FeatureUpsell::new(telemetry, "Rust support is built-in to Zed!")
1041                        .docs_url("https://zed.dev/docs/languages/rust")
1042                }
1043                Feature::LanguageTypescript => {
1044                    FeatureUpsell::new(telemetry, "Typescript support is built-in to Zed!")
1045                        .docs_url("https://zed.dev/docs/languages/typescript")
1046                }
1047            };
1048
1049            upsell.when(ix < upsells_count, |upsell| upsell.border_b_1())
1050        }))
1051    }
1052}
1053
1054impl Render for ExtensionsPage {
1055    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1056        v_flex()
1057            .size_full()
1058            .bg(cx.theme().colors().editor_background)
1059            .child(
1060                v_flex()
1061                    .gap_4()
1062                    .p_4()
1063                    .border_b_1()
1064                    .border_color(cx.theme().colors().border)
1065                    .bg(cx.theme().colors().editor_background)
1066                    .child(
1067                        h_flex()
1068                            .w_full()
1069                            .gap_2()
1070                            .justify_between()
1071                            .child(Headline::new("Extensions").size(HeadlineSize::XLarge))
1072                            .child(
1073                                Button::new("install-dev-extension", "Install Dev Extension")
1074                                    .style(ButtonStyle::Filled)
1075                                    .size(ButtonSize::Large)
1076                                    .on_click(|_event, cx| {
1077                                        cx.dispatch_action(Box::new(InstallDevExtension))
1078                                    }),
1079                            ),
1080                    )
1081                    .child(
1082                        h_flex()
1083                            .w_full()
1084                            .gap_2()
1085                            .justify_between()
1086                            .child(h_flex().child(self.render_search(cx)))
1087                            .child(
1088                                h_flex()
1089                                    .child(
1090                                        ToggleButton::new("filter-all", "All")
1091                                            .style(ButtonStyle::Filled)
1092                                            .size(ButtonSize::Large)
1093                                            .selected(self.filter == ExtensionFilter::All)
1094                                            .on_click(cx.listener(|this, _event, cx| {
1095                                                this.filter = ExtensionFilter::All;
1096                                                this.filter_extension_entries(cx);
1097                                            }))
1098                                            .tooltip(move |cx| {
1099                                                Tooltip::text("Show all extensions", cx)
1100                                            })
1101                                            .first(),
1102                                    )
1103                                    .child(
1104                                        ToggleButton::new("filter-installed", "Installed")
1105                                            .style(ButtonStyle::Filled)
1106                                            .size(ButtonSize::Large)
1107                                            .selected(self.filter == ExtensionFilter::Installed)
1108                                            .on_click(cx.listener(|this, _event, cx| {
1109                                                this.filter = ExtensionFilter::Installed;
1110                                                this.filter_extension_entries(cx);
1111                                            }))
1112                                            .tooltip(move |cx| {
1113                                                Tooltip::text("Show installed extensions", cx)
1114                                            })
1115                                            .middle(),
1116                                    )
1117                                    .child(
1118                                        ToggleButton::new("filter-not-installed", "Not Installed")
1119                                            .style(ButtonStyle::Filled)
1120                                            .size(ButtonSize::Large)
1121                                            .selected(self.filter == ExtensionFilter::NotInstalled)
1122                                            .on_click(cx.listener(|this, _event, cx| {
1123                                                this.filter = ExtensionFilter::NotInstalled;
1124                                                this.filter_extension_entries(cx);
1125                                            }))
1126                                            .tooltip(move |cx| {
1127                                                Tooltip::text("Show not installed extensions", cx)
1128                                            })
1129                                            .last(),
1130                                    ),
1131                            ),
1132                    ),
1133            )
1134            .child(self.render_feature_upsells(cx))
1135            .child(v_flex().px_4().size_full().overflow_y_hidden().map(|this| {
1136                let mut count = self.filtered_remote_extension_indices.len();
1137                if self.filter.include_dev_extensions() {
1138                    count += self.dev_extension_entries.len();
1139                }
1140
1141                if count == 0 {
1142                    return this.py_4().child(self.render_empty_state(cx));
1143                }
1144
1145                let view = cx.view().clone();
1146                let scroll_handle = self.list.clone();
1147                this.child(
1148                    uniform_list(view, "entries", count, Self::render_extensions)
1149                        .flex_grow()
1150                        .pb_4()
1151                        .track_scroll(scroll_handle),
1152                )
1153            }))
1154    }
1155}
1156
1157impl EventEmitter<ItemEvent> for ExtensionsPage {}
1158
1159impl FocusableView for ExtensionsPage {
1160    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
1161        self.query_editor.read(cx).focus_handle(cx)
1162    }
1163}
1164
1165impl Item for ExtensionsPage {
1166    type Event = ItemEvent;
1167
1168    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
1169        Some("Extensions".into())
1170    }
1171
1172    fn telemetry_event_text(&self) -> Option<&'static str> {
1173        Some("extensions page")
1174    }
1175
1176    fn show_toolbar(&self) -> bool {
1177        false
1178    }
1179
1180    fn clone_on_split(
1181        &self,
1182        _workspace_id: Option<WorkspaceId>,
1183        _: &mut ViewContext<Self>,
1184    ) -> Option<View<Self>> {
1185        None
1186    }
1187
1188    fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
1189        f(*event)
1190    }
1191}