1mod capability_granter;
2pub mod extension_settings;
3pub mod headless_host;
4pub mod wasm_host;
5
6#[cfg(test)]
7mod extension_store_test;
8
9use anyhow::{Context as _, Result, anyhow, bail};
10use async_compression::futures::bufread::GzipDecoder;
11use async_tar::Archive;
12use client::ExtensionProvides;
13use client::{Client, ExtensionMetadata, GetExtensionsResponse, proto, telemetry::Telemetry};
14use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
15pub use extension::ExtensionManifest;
16use extension::extension_builder::{CompileExtensionOptions, ExtensionBuilder};
17use extension::{
18 ExtensionContextServerProxy, ExtensionDebugAdapterProviderProxy, ExtensionEvents,
19 ExtensionGrammarProxy, ExtensionHostProxy, ExtensionLanguageProxy,
20 ExtensionLanguageServerProxy, ExtensionSlashCommandProxy, ExtensionSnippetProxy,
21 ExtensionThemeProxy,
22};
23use fs::{Fs, RemoveOptions};
24use futures::future::join_all;
25use futures::{
26 AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
27 channel::{
28 mpsc::{UnboundedSender, unbounded},
29 oneshot,
30 },
31 io::BufReader,
32 select_biased,
33};
34use gpui::{
35 App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, Task, WeakEntity,
36 Window, actions,
37};
38use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
39use language::{
40 LanguageConfig, LanguageMatcher, LanguageName, LanguageQueries, LoadedLanguage,
41 QUERY_FILENAME_PREFIXES, Rope,
42};
43use node_runtime::NodeRuntime;
44use project::ContextProviderWithTasks;
45use release_channel::ReleaseChannel;
46use remote::{RemoteClient, RemoteConnectionOptions};
47use semantic_version::SemanticVersion;
48use serde::{Deserialize, Serialize};
49use settings::Settings;
50use std::ops::RangeInclusive;
51use std::str::FromStr;
52use std::{
53 cmp::Ordering,
54 path::{self, Path, PathBuf},
55 sync::Arc,
56 time::{Duration, Instant},
57};
58use task::SpawnInTerminal;
59use url::Url;
60use util::{ResultExt, paths::RemotePathBuf};
61use wasm_host::{
62 WasmExtension, WasmHost,
63 wit::{is_supported_wasm_api_version, wasm_api_version_range},
64};
65use workspace::Workspace;
66
67pub use extension::{
68 ExtensionLibraryKind, GrammarManifestEntry, OldExtensionManifest, SchemaVersion,
69};
70pub use extension_settings::ExtensionSettings;
71
72pub const RELOAD_DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
73const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
74
75/// The current extension [`SchemaVersion`] supported by Zed.
76const CURRENT_SCHEMA_VERSION: SchemaVersion = SchemaVersion(1);
77
78/// Returns the [`SchemaVersion`] range that is compatible with this version of Zed.
79pub fn schema_version_range() -> RangeInclusive<SchemaVersion> {
80 SchemaVersion::ZERO..=CURRENT_SCHEMA_VERSION
81}
82
83/// Returns whether the given extension version is compatible with this version of Zed.
84pub fn is_version_compatible(
85 release_channel: ReleaseChannel,
86 extension_version: &ExtensionMetadata,
87) -> bool {
88 let schema_version = extension_version.manifest.schema_version.unwrap_or(0);
89 if CURRENT_SCHEMA_VERSION.0 < schema_version {
90 return false;
91 }
92
93 if let Some(wasm_api_version) = extension_version
94 .manifest
95 .wasm_api_version
96 .as_ref()
97 .and_then(|wasm_api_version| SemanticVersion::from_str(wasm_api_version).ok())
98 && !is_supported_wasm_api_version(release_channel, wasm_api_version)
99 {
100 return false;
101 }
102
103 true
104}
105
106pub struct ExtensionStore {
107 pub proxy: Arc<ExtensionHostProxy>,
108 pub builder: Arc<ExtensionBuilder>,
109 pub extension_index: ExtensionIndex,
110 pub fs: Arc<dyn Fs>,
111 pub http_client: Arc<HttpClientWithUrl>,
112 pub telemetry: Option<Arc<Telemetry>>,
113 pub reload_tx: UnboundedSender<Option<Arc<str>>>,
114 pub reload_complete_senders: Vec<oneshot::Sender<()>>,
115 pub installed_dir: PathBuf,
116 pub outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
117 pub index_path: PathBuf,
118 pub modified_extensions: HashSet<Arc<str>>,
119 pub wasm_host: Arc<WasmHost>,
120 pub wasm_extensions: Vec<(Arc<ExtensionManifest>, WasmExtension)>,
121 pub tasks: Vec<Task<()>>,
122 pub remote_clients: HashMap<RemoteConnectionOptions, WeakEntity<RemoteClient>>,
123 pub ssh_registered_tx: UnboundedSender<()>,
124}
125
126#[derive(Clone, Copy)]
127pub enum ExtensionOperation {
128 Upgrade,
129 Install,
130 Remove,
131}
132
133#[derive(Clone)]
134pub enum Event {
135 ExtensionsUpdated,
136 StartedReloading,
137 ExtensionInstalled(Arc<str>),
138 ExtensionUninstalled(Arc<str>),
139 ExtensionFailedToLoad(Arc<str>),
140}
141
142impl EventEmitter<Event> for ExtensionStore {}
143
144struct GlobalExtensionStore(Entity<ExtensionStore>);
145
146impl Global for GlobalExtensionStore {}
147
148#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
149pub struct ExtensionIndex {
150 pub extensions: BTreeMap<Arc<str>, ExtensionIndexEntry>,
151 pub themes: BTreeMap<Arc<str>, ExtensionIndexThemeEntry>,
152 #[serde(default)]
153 pub icon_themes: BTreeMap<Arc<str>, ExtensionIndexIconThemeEntry>,
154 pub languages: BTreeMap<LanguageName, ExtensionIndexLanguageEntry>,
155}
156
157#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
158pub struct ExtensionIndexEntry {
159 pub manifest: Arc<ExtensionManifest>,
160 pub dev: bool,
161}
162
163#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
164pub struct ExtensionIndexThemeEntry {
165 pub extension: Arc<str>,
166 pub path: PathBuf,
167}
168
169#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
170pub struct ExtensionIndexIconThemeEntry {
171 pub extension: Arc<str>,
172 pub path: PathBuf,
173}
174
175#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
176pub struct ExtensionIndexLanguageEntry {
177 pub extension: Arc<str>,
178 pub path: PathBuf,
179 pub matcher: LanguageMatcher,
180 pub hidden: bool,
181 pub grammar: Option<Arc<str>>,
182}
183
184actions!(
185 zed,
186 [
187 /// Reloads all installed extensions.
188 ReloadExtensions
189 ]
190);
191
192pub fn init(
193 extension_host_proxy: Arc<ExtensionHostProxy>,
194 fs: Arc<dyn Fs>,
195 client: Arc<Client>,
196 node_runtime: NodeRuntime,
197 cx: &mut App,
198) {
199 ExtensionSettings::register(cx);
200
201 let store = cx.new(move |cx| {
202 ExtensionStore::new(
203 paths::extensions_dir().clone(),
204 None,
205 extension_host_proxy,
206 fs,
207 client.http_client(),
208 client.http_client(),
209 Some(client.telemetry().clone()),
210 node_runtime,
211 cx,
212 )
213 });
214
215 cx.on_action(|_: &ReloadExtensions, cx| {
216 let store = cx.global::<GlobalExtensionStore>().0.clone();
217 store.update(cx, |store, cx| drop(store.reload(None, cx)));
218 });
219
220 cx.set_global(GlobalExtensionStore(store));
221}
222
223impl ExtensionStore {
224 pub fn try_global(cx: &App) -> Option<Entity<Self>> {
225 cx.try_global::<GlobalExtensionStore>()
226 .map(|store| store.0.clone())
227 }
228
229 pub fn global(cx: &App) -> Entity<Self> {
230 cx.global::<GlobalExtensionStore>().0.clone()
231 }
232
233 pub fn new(
234 extensions_dir: PathBuf,
235 build_dir: Option<PathBuf>,
236 extension_host_proxy: Arc<ExtensionHostProxy>,
237 fs: Arc<dyn Fs>,
238 http_client: Arc<HttpClientWithUrl>,
239 builder_client: Arc<dyn HttpClient>,
240 telemetry: Option<Arc<Telemetry>>,
241 node_runtime: NodeRuntime,
242 cx: &mut Context<Self>,
243 ) -> Self {
244 let work_dir = extensions_dir.join("work");
245 let build_dir = build_dir.unwrap_or_else(|| extensions_dir.join("build"));
246 let installed_dir = extensions_dir.join("installed");
247 let index_path = extensions_dir.join("index.json");
248
249 let (reload_tx, mut reload_rx) = unbounded();
250 let (connection_registered_tx, mut connection_registered_rx) = unbounded();
251 let mut this = Self {
252 proxy: extension_host_proxy.clone(),
253 extension_index: Default::default(),
254 installed_dir,
255 index_path,
256 builder: Arc::new(ExtensionBuilder::new(builder_client, build_dir)),
257 outstanding_operations: Default::default(),
258 modified_extensions: Default::default(),
259 reload_complete_senders: Vec::new(),
260 wasm_host: WasmHost::new(
261 fs.clone(),
262 http_client.clone(),
263 node_runtime,
264 extension_host_proxy,
265 work_dir,
266 cx,
267 ),
268 wasm_extensions: Vec::new(),
269 fs,
270 http_client,
271 telemetry,
272 reload_tx,
273 tasks: Vec::new(),
274
275 remote_clients: HashMap::default(),
276 ssh_registered_tx: connection_registered_tx,
277 };
278
279 // The extensions store maintains an index file, which contains a complete
280 // list of the installed extensions and the resources that they provide.
281 // This index is loaded synchronously on startup.
282 let (index_content, index_metadata, extensions_metadata) =
283 cx.background_executor().block(async {
284 futures::join!(
285 this.fs.load(&this.index_path),
286 this.fs.metadata(&this.index_path),
287 this.fs.metadata(&this.installed_dir),
288 )
289 });
290
291 // Normally, there is no need to rebuild the index. But if the index file
292 // is invalid or is out-of-date according to the filesystem mtimes, then
293 // it must be asynchronously rebuilt.
294 let mut extension_index = ExtensionIndex::default();
295 let mut extension_index_needs_rebuild = true;
296 if let Ok(index_content) = index_content
297 && let Some(index) = serde_json::from_str(&index_content).log_err()
298 {
299 extension_index = index;
300 if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
301 (index_metadata, extensions_metadata)
302 && index_metadata
303 .mtime
304 .bad_is_greater_than(extensions_metadata.mtime)
305 {
306 extension_index_needs_rebuild = false;
307 }
308 }
309
310 // Immediately load all of the extensions in the initial manifest. If the
311 // index needs to be rebuild, then enqueue
312 let load_initial_extensions = this.extensions_updated(extension_index, cx);
313 let mut reload_future = None;
314 if extension_index_needs_rebuild {
315 reload_future = Some(this.reload(None, cx));
316 }
317
318 cx.spawn(async move |this, cx| {
319 if let Some(future) = reload_future {
320 future.await;
321 }
322 this.update(cx, |this, cx| this.auto_install_extensions(cx))
323 .ok();
324 this.update(cx, |this, cx| this.check_for_updates(cx)).ok();
325 })
326 .detach();
327
328 // Perform all extension loading in a single task to ensure that we
329 // never attempt to simultaneously load/unload extensions from multiple
330 // parallel tasks.
331 this.tasks.push(cx.spawn(async move |this, cx| {
332 async move {
333 load_initial_extensions.await;
334
335 let mut index_changed = false;
336 let mut debounce_timer = cx.background_spawn(futures::future::pending()).fuse();
337 loop {
338 select_biased! {
339 _ = debounce_timer => {
340 if index_changed {
341 let index = this
342 .update(cx, |this, cx| this.rebuild_extension_index(cx))?
343 .await;
344 this.update( cx, |this, cx| this.extensions_updated(index, cx))?
345 .await;
346 index_changed = false;
347 }
348
349 Self::update_ssh_clients(&this, cx).await?;
350 }
351 _ = connection_registered_rx.next() => {
352 debounce_timer = cx
353 .background_executor()
354 .timer(RELOAD_DEBOUNCE_DURATION)
355 .fuse();
356 }
357 extension_id = reload_rx.next() => {
358 let Some(extension_id) = extension_id else { break; };
359 this.update( cx, |this, _| {
360 this.modified_extensions.extend(extension_id);
361 })?;
362 index_changed = true;
363 debounce_timer = cx
364 .background_executor()
365 .timer(RELOAD_DEBOUNCE_DURATION)
366 .fuse();
367 }
368 }
369 }
370
371 anyhow::Ok(())
372 }
373 .map(drop)
374 .await;
375 }));
376
377 // Watch the installed extensions directory for changes. Whenever changes are
378 // detected, rebuild the extension index, and load/unload any extensions that
379 // have been added, removed, or modified.
380 this.tasks.push(cx.background_spawn({
381 let fs = this.fs.clone();
382 let reload_tx = this.reload_tx.clone();
383 let installed_dir = this.installed_dir.clone();
384 async move {
385 let (mut paths, _) = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
386 while let Some(events) = paths.next().await {
387 for event in events {
388 let Ok(event_path) = event.path.strip_prefix(&installed_dir) else {
389 continue;
390 };
391
392 if let Some(path::Component::Normal(extension_dir_name)) =
393 event_path.components().next()
394 && let Some(extension_id) = extension_dir_name.to_str()
395 {
396 reload_tx.unbounded_send(Some(extension_id.into())).ok();
397 }
398 }
399 }
400 }
401 }));
402
403 this
404 }
405
406 pub fn reload(
407 &mut self,
408 modified_extension: Option<Arc<str>>,
409 cx: &mut Context<Self>,
410 ) -> impl Future<Output = ()> + use<> {
411 let (tx, rx) = oneshot::channel();
412 self.reload_complete_senders.push(tx);
413 self.reload_tx
414 .unbounded_send(modified_extension)
415 .expect("reload task exited");
416 cx.emit(Event::StartedReloading);
417
418 async move {
419 rx.await.ok();
420 }
421 }
422
423 fn extensions_dir(&self) -> PathBuf {
424 self.installed_dir.clone()
425 }
426
427 pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
428 &self.outstanding_operations
429 }
430
431 pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
432 &self.extension_index.extensions
433 }
434
435 pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
436 self.extension_index
437 .extensions
438 .values()
439 .filter_map(|extension| extension.dev.then_some(&extension.manifest))
440 }
441
442 pub fn extension_manifest_for_id(&self, extension_id: &str) -> Option<&Arc<ExtensionManifest>> {
443 self.extension_index
444 .extensions
445 .get(extension_id)
446 .map(|extension| &extension.manifest)
447 }
448
449 /// Returns the names of themes provided by extensions.
450 pub fn extension_themes<'a>(
451 &'a self,
452 extension_id: &'a str,
453 ) -> impl Iterator<Item = &'a Arc<str>> {
454 self.extension_index
455 .themes
456 .iter()
457 .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
458 }
459
460 /// Returns the path to the theme file within an extension, if there is an
461 /// extension that provides the theme.
462 pub fn path_to_extension_theme(&self, theme_name: &str) -> Option<PathBuf> {
463 let entry = self.extension_index.themes.get(theme_name)?;
464
465 Some(
466 self.extensions_dir()
467 .join(entry.extension.as_ref())
468 .join(&entry.path),
469 )
470 }
471
472 /// Returns the names of icon themes provided by extensions.
473 pub fn extension_icon_themes<'a>(
474 &'a self,
475 extension_id: &'a str,
476 ) -> impl Iterator<Item = &'a Arc<str>> {
477 self.extension_index
478 .icon_themes
479 .iter()
480 .filter_map(|(name, icon_theme)| {
481 icon_theme
482 .extension
483 .as_ref()
484 .eq(extension_id)
485 .then_some(name)
486 })
487 }
488
489 /// Returns the path to the icon theme file within an extension, if there is
490 /// an extension that provides the icon theme.
491 pub fn path_to_extension_icon_theme(
492 &self,
493 icon_theme_name: &str,
494 ) -> Option<(PathBuf, PathBuf)> {
495 let entry = self.extension_index.icon_themes.get(icon_theme_name)?;
496
497 let icon_theme_path = self
498 .extensions_dir()
499 .join(entry.extension.as_ref())
500 .join(&entry.path);
501 let icons_root_path = self.extensions_dir().join(entry.extension.as_ref());
502
503 Some((icon_theme_path, icons_root_path))
504 }
505
506 pub fn fetch_extensions(
507 &self,
508 search: Option<&str>,
509 provides_filter: Option<&BTreeSet<ExtensionProvides>>,
510 cx: &mut Context<Self>,
511 ) -> Task<Result<Vec<ExtensionMetadata>>> {
512 let version = CURRENT_SCHEMA_VERSION.to_string();
513 let mut query = vec![("max_schema_version", version.as_str())];
514 if let Some(search) = search {
515 query.push(("filter", search));
516 }
517
518 let provides_filter = provides_filter.map(|provides_filter| {
519 provides_filter
520 .iter()
521 .map(|provides| provides.to_string())
522 .collect::<Vec<_>>()
523 .join(",")
524 });
525 if let Some(provides_filter) = provides_filter.as_deref() {
526 query.push(("provides", provides_filter));
527 }
528
529 self.fetch_extensions_from_api("/extensions", &query, cx)
530 }
531
532 pub fn fetch_extensions_with_update_available(
533 &mut self,
534 cx: &mut Context<Self>,
535 ) -> Task<Result<Vec<ExtensionMetadata>>> {
536 let schema_versions = schema_version_range();
537 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
538 let extension_settings = ExtensionSettings::get_global(cx);
539 let extension_ids = self
540 .extension_index
541 .extensions
542 .iter()
543 .filter(|(id, entry)| !entry.dev && extension_settings.should_auto_update(id))
544 .map(|(id, _)| id.as_ref())
545 .collect::<Vec<_>>()
546 .join(",");
547 let task = self.fetch_extensions_from_api(
548 "/extensions/updates",
549 &[
550 ("min_schema_version", &schema_versions.start().to_string()),
551 ("max_schema_version", &schema_versions.end().to_string()),
552 (
553 "min_wasm_api_version",
554 &wasm_api_versions.start().to_string(),
555 ),
556 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
557 ("ids", &extension_ids),
558 ],
559 cx,
560 );
561 cx.spawn(async move |this, cx| {
562 let extensions = task.await?;
563 this.update(cx, |this, _cx| {
564 extensions
565 .into_iter()
566 .filter(|extension| {
567 this.extension_index
568 .extensions
569 .get(&extension.id)
570 .is_none_or(|installed_extension| {
571 installed_extension.manifest.version != extension.manifest.version
572 })
573 })
574 .collect()
575 })
576 })
577 }
578
579 pub fn fetch_extension_versions(
580 &self,
581 extension_id: &str,
582 cx: &mut Context<Self>,
583 ) -> Task<Result<Vec<ExtensionMetadata>>> {
584 self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
585 }
586
587 /// Installs any extensions that should be included with Zed by default.
588 ///
589 /// This can be used to make certain functionality provided by extensions
590 /// available out-of-the-box.
591 pub fn auto_install_extensions(&mut self, cx: &mut Context<Self>) {
592 let extension_settings = ExtensionSettings::get_global(cx);
593
594 let extensions_to_install = extension_settings
595 .auto_install_extensions
596 .keys()
597 .filter(|extension_id| extension_settings.should_auto_install(extension_id))
598 .filter(|extension_id| {
599 let is_already_installed = self
600 .extension_index
601 .extensions
602 .contains_key(extension_id.as_ref());
603 !is_already_installed
604 })
605 .cloned()
606 .collect::<Vec<_>>();
607
608 cx.spawn(async move |this, cx| {
609 for extension_id in extensions_to_install {
610 this.update(cx, |this, cx| {
611 this.install_latest_extension(extension_id.clone(), cx);
612 })
613 .ok();
614 }
615 })
616 .detach();
617 }
618
619 pub fn check_for_updates(&mut self, cx: &mut Context<Self>) {
620 let task = self.fetch_extensions_with_update_available(cx);
621 cx.spawn(async move |this, cx| Self::upgrade_extensions(this, task.await?, cx).await)
622 .detach();
623 }
624
625 async fn upgrade_extensions(
626 this: WeakEntity<Self>,
627 extensions: Vec<ExtensionMetadata>,
628 cx: &mut AsyncApp,
629 ) -> Result<()> {
630 for extension in extensions {
631 let task = this.update(cx, |this, cx| {
632 if let Some(installed_extension) =
633 this.extension_index.extensions.get(&extension.id)
634 {
635 let installed_version =
636 SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
637 let latest_version =
638 SemanticVersion::from_str(&extension.manifest.version).ok()?;
639
640 if installed_version >= latest_version {
641 return None;
642 }
643 }
644
645 Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
646 })?;
647
648 if let Some(task) = task {
649 task.await.log_err();
650 }
651 }
652 anyhow::Ok(())
653 }
654
655 fn fetch_extensions_from_api(
656 &self,
657 path: &str,
658 query: &[(&str, &str)],
659 cx: &mut Context<ExtensionStore>,
660 ) -> Task<Result<Vec<ExtensionMetadata>>> {
661 let url = self.http_client.build_zed_api_url(path, query);
662 let http_client = self.http_client.clone();
663 cx.spawn(async move |_, _| {
664 let mut response = http_client
665 .get(url?.as_ref(), AsyncBody::empty(), true)
666 .await?;
667
668 let mut body = Vec::new();
669 response
670 .body_mut()
671 .read_to_end(&mut body)
672 .await
673 .context("error reading extensions")?;
674
675 if response.status().is_client_error() {
676 let text = String::from_utf8_lossy(body.as_slice());
677 bail!(
678 "status error {}, response: {text:?}",
679 response.status().as_u16()
680 );
681 }
682
683 let response: GetExtensionsResponse = serde_json::from_slice(&body)?;
684 Ok(response.data)
685 })
686 }
687
688 pub fn install_extension(
689 &mut self,
690 extension_id: Arc<str>,
691 version: Arc<str>,
692 cx: &mut Context<Self>,
693 ) {
694 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
695 .detach_and_log_err(cx);
696 }
697
698 fn install_or_upgrade_extension_at_endpoint(
699 &mut self,
700 extension_id: Arc<str>,
701 url: Url,
702 operation: ExtensionOperation,
703 cx: &mut Context<Self>,
704 ) -> Task<Result<()>> {
705 let extension_dir = self.installed_dir.join(extension_id.as_ref());
706 let http_client = self.http_client.clone();
707 let fs = self.fs.clone();
708
709 match self.outstanding_operations.entry(extension_id.clone()) {
710 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
711 btree_map::Entry::Vacant(e) => e.insert(operation),
712 };
713 cx.notify();
714
715 cx.spawn(async move |this, cx| {
716 let _finish = cx.on_drop(&this, {
717 let extension_id = extension_id.clone();
718 move |this, cx| {
719 this.outstanding_operations.remove(extension_id.as_ref());
720 cx.notify();
721 }
722 });
723
724 let mut response = http_client
725 .get(url.as_ref(), Default::default(), true)
726 .await
727 .context("downloading extension")?;
728
729 fs.remove_dir(
730 &extension_dir,
731 RemoveOptions {
732 recursive: true,
733 ignore_if_not_exists: true,
734 },
735 )
736 .await?;
737
738 let content_length = response
739 .headers()
740 .get(http_client::http::header::CONTENT_LENGTH)
741 .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
742
743 let mut body = BufReader::new(response.body_mut());
744 let mut tar_gz_bytes = Vec::new();
745 body.read_to_end(&mut tar_gz_bytes).await?;
746
747 if let Some(content_length) = content_length {
748 let actual_len = tar_gz_bytes.len();
749 if content_length != actual_len {
750 bail!("downloaded extension size {actual_len} does not match content length {content_length}");
751 }
752 }
753 let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
754 let archive = Archive::new(decompressed_bytes);
755 archive.unpack(extension_dir).await?;
756 this.update( cx, |this, cx| {
757 this.reload(Some(extension_id.clone()), cx)
758 })?
759 .await;
760
761 if let ExtensionOperation::Install = operation {
762 this.update( cx, |this, cx| {
763 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
764 if let Some(events) = ExtensionEvents::try_global(cx)
765 && let Some(manifest) = this.extension_manifest_for_id(&extension_id) {
766 events.update(cx, |this, cx| {
767 this.emit(
768 extension::Event::ExtensionInstalled(manifest.clone()),
769 cx,
770 )
771 });
772 }
773 })
774 .ok();
775 }
776
777 anyhow::Ok(())
778 })
779 }
780
781 pub fn install_latest_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
782 log::info!("installing extension {extension_id} latest version");
783
784 let schema_versions = schema_version_range();
785 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
786
787 let Some(url) = self
788 .http_client
789 .build_zed_api_url(
790 &format!("/extensions/{extension_id}/download"),
791 &[
792 ("min_schema_version", &schema_versions.start().to_string()),
793 ("max_schema_version", &schema_versions.end().to_string()),
794 (
795 "min_wasm_api_version",
796 &wasm_api_versions.start().to_string(),
797 ),
798 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
799 ],
800 )
801 .log_err()
802 else {
803 return;
804 };
805
806 self.install_or_upgrade_extension_at_endpoint(
807 extension_id,
808 url,
809 ExtensionOperation::Install,
810 cx,
811 )
812 .detach_and_log_err(cx);
813 }
814
815 pub fn upgrade_extension(
816 &mut self,
817 extension_id: Arc<str>,
818 version: Arc<str>,
819 cx: &mut Context<Self>,
820 ) -> Task<Result<()>> {
821 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
822 }
823
824 fn install_or_upgrade_extension(
825 &mut self,
826 extension_id: Arc<str>,
827 version: Arc<str>,
828 operation: ExtensionOperation,
829 cx: &mut Context<Self>,
830 ) -> Task<Result<()>> {
831 log::info!("installing extension {extension_id} {version}");
832 let Some(url) = self
833 .http_client
834 .build_zed_api_url(
835 &format!("/extensions/{extension_id}/{version}/download"),
836 &[],
837 )
838 .log_err()
839 else {
840 return Task::ready(Ok(()));
841 };
842
843 self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
844 }
845
846 pub fn uninstall_extension(
847 &mut self,
848 extension_id: Arc<str>,
849 cx: &mut Context<Self>,
850 ) -> Task<Result<()>> {
851 let extension_dir = self.installed_dir.join(extension_id.as_ref());
852 let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
853 let fs = self.fs.clone();
854
855 let extension_manifest = self.extension_manifest_for_id(&extension_id).cloned();
856
857 match self.outstanding_operations.entry(extension_id.clone()) {
858 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
859 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
860 };
861
862 cx.spawn(async move |extension_store, cx| {
863 let _finish = cx.on_drop(&extension_store, {
864 let extension_id = extension_id.clone();
865 move |this, cx| {
866 this.outstanding_operations.remove(extension_id.as_ref());
867 cx.notify();
868 }
869 });
870
871 fs.remove_dir(
872 &extension_dir,
873 RemoveOptions {
874 recursive: true,
875 ignore_if_not_exists: true,
876 },
877 )
878 .await
879 .with_context(|| format!("Removing extension dir {extension_dir:?}"))?;
880
881 extension_store
882 .update(cx, |extension_store, cx| extension_store.reload(None, cx))?
883 .await;
884
885 // There's a race between wasm extension fully stopping and the directory removal.
886 // On Windows, it's impossible to remove a directory that has a process running in it.
887 for i in 0..3 {
888 cx.background_executor()
889 .timer(Duration::from_millis(i * 100))
890 .await;
891 let removal_result = fs
892 .remove_dir(
893 &work_dir,
894 RemoveOptions {
895 recursive: true,
896 ignore_if_not_exists: true,
897 },
898 )
899 .await;
900 match removal_result {
901 Ok(()) => break,
902 Err(e) => {
903 if i == 2 {
904 log::error!("Failed to remove extension work dir {work_dir:?} : {e}");
905 }
906 }
907 }
908 }
909
910 extension_store.update(cx, |_, cx| {
911 cx.emit(Event::ExtensionUninstalled(extension_id.clone()));
912 if let Some(events) = ExtensionEvents::try_global(cx)
913 && let Some(manifest) = extension_manifest
914 {
915 events.update(cx, |this, cx| {
916 this.emit(extension::Event::ExtensionUninstalled(manifest.clone()), cx)
917 });
918 }
919 })?;
920
921 anyhow::Ok(())
922 })
923 }
924
925 pub fn install_dev_extension(
926 &mut self,
927 extension_source_path: PathBuf,
928 cx: &mut Context<Self>,
929 ) -> Task<Result<()>> {
930 let extensions_dir = self.extensions_dir();
931 let fs = self.fs.clone();
932 let builder = self.builder.clone();
933
934 cx.spawn(async move |this, cx| {
935 let mut extension_manifest =
936 ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
937 let extension_id = extension_manifest.id.clone();
938
939 if !this.update(cx, |this, cx| {
940 match this.outstanding_operations.entry(extension_id.clone()) {
941 btree_map::Entry::Occupied(_) => return false,
942 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
943 };
944 cx.notify();
945 true
946 })? {
947 return Ok(());
948 }
949
950 let _finish = cx.on_drop(&this, {
951 let extension_id = extension_id.clone();
952 move |this, cx| {
953 this.outstanding_operations.remove(extension_id.as_ref());
954 cx.notify();
955 }
956 });
957
958 cx.background_spawn({
959 let extension_source_path = extension_source_path.clone();
960 async move {
961 builder
962 .compile_extension(
963 &extension_source_path,
964 &mut extension_manifest,
965 CompileExtensionOptions { release: false },
966 )
967 .await
968 }
969 })
970 .await
971 .inspect_err(|error| {
972 util::log_err(error);
973 })?;
974
975 let output_path = &extensions_dir.join(extension_id.as_ref());
976 if let Some(metadata) = fs.metadata(output_path).await? {
977 if metadata.is_symlink {
978 fs.remove_file(
979 output_path,
980 RemoveOptions {
981 recursive: false,
982 ignore_if_not_exists: true,
983 },
984 )
985 .await?;
986 } else {
987 bail!("extension {extension_id} is already installed");
988 }
989 }
990
991 fs.create_symlink(output_path, extension_source_path)
992 .await?;
993
994 this.update(cx, |this, cx| this.reload(None, cx))?.await;
995 this.update(cx, |this, cx| {
996 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
997 if let Some(events) = ExtensionEvents::try_global(cx)
998 && let Some(manifest) = this.extension_manifest_for_id(&extension_id)
999 {
1000 events.update(cx, |this, cx| {
1001 this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
1002 });
1003 }
1004 })?;
1005
1006 Ok(())
1007 })
1008 }
1009
1010 pub fn rebuild_dev_extension(
1011 &mut self,
1012 extension_id: Arc<str>,
1013 window: &mut Window,
1014 cx: &mut Context<Self>,
1015 ) {
1016 let Some(Some(workspace)) = window.root::<Workspace>() else {
1017 return;
1018 };
1019 let path = self.installed_dir.join(extension_id.as_ref());
1020 let compile = workspace.update(cx, |workspace, cx| {
1021 workspace.spawn_in_terminal(
1022 SpawnInTerminal {
1023 id: task::TaskId(format!("rebuild-{}", extension_id)),
1024 full_label: format!("Rebuild extension {}", extension_id),
1025 label: format!("Rebuild extension {}", extension_id),
1026 command: None,
1027 args: Default::default(),
1028 command_label: format!("Rebuild extension {}", extension_id),
1029 cwd: Some(path.clone()),
1030 env: [("RUST_LOG".into(), "info".into())].into_iter().collect(),
1031 use_new_terminal: false,
1032 allow_concurrent_runs: false,
1033 reveal: task::RevealStrategy::Always,
1034 reveal_target: task::RevealTarget::Dock,
1035 hide: task::HideStrategy::Never,
1036 shell: task::Shell::WithArguments {
1037 // todo!()
1038 program: std::env::current_exe()
1039 .ok()
1040 .map(|p| p.to_string_lossy().to_string())
1041 .unwrap(),
1042 args: dbg!(vec![
1043 "--build-extension".into(),
1044 path.to_string_lossy().to_string(),
1045 ]),
1046 title_override: None,
1047 },
1048 show_summary: true,
1049 show_command: true,
1050 show_rerun: true,
1051 },
1052 window,
1053 cx,
1054 )
1055 });
1056 match self.outstanding_operations.entry(extension_id.clone()) {
1057 btree_map::Entry::Occupied(_) => return,
1058 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
1059 };
1060
1061 cx.notify();
1062
1063 cx.spawn(async move |this, cx| {
1064 let result = compile.await;
1065
1066 this.update(cx, |this, cx| {
1067 this.outstanding_operations.remove(&extension_id);
1068 cx.notify();
1069 })?;
1070
1071 if let Some(Ok(_)) = &result {
1072 this.update(cx, |this, cx| this.reload(Some(extension_id), cx))?
1073 .await;
1074 }
1075
1076 result.ok_or_else(|| anyhow!("rebuild cancelled"))?
1077 })
1078 .detach_and_log_err(cx)
1079 }
1080
1081 /// Updates the set of installed extensions.
1082 ///
1083 /// First, this unloads any themes, languages, or grammars that are
1084 /// no longer in the manifest, or whose files have changed on disk.
1085 /// Then it loads any themes, languages, or grammars that are newly
1086 /// added to the manifest, or whose files have changed on disk.
1087 fn extensions_updated(
1088 &mut self,
1089 mut new_index: ExtensionIndex,
1090 cx: &mut Context<Self>,
1091 ) -> Task<()> {
1092 let old_index = &self.extension_index;
1093
1094 // Determine which extensions need to be loaded and unloaded, based
1095 // on the changes to the manifest and the extensions that we know have been
1096 // modified.
1097 let mut extensions_to_unload = Vec::default();
1098 let mut extensions_to_load = Vec::default();
1099 {
1100 let mut old_keys = old_index.extensions.iter().peekable();
1101 let mut new_keys = new_index.extensions.iter().peekable();
1102 loop {
1103 match (old_keys.peek(), new_keys.peek()) {
1104 (None, None) => break,
1105 (None, Some(_)) => {
1106 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1107 }
1108 (Some(_), None) => {
1109 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1110 }
1111 (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1112 Ordering::Equal => {
1113 let (old_key, old_value) = old_keys.next().unwrap();
1114 let (new_key, new_value) = new_keys.next().unwrap();
1115 if old_value != new_value || self.modified_extensions.contains(old_key)
1116 {
1117 extensions_to_unload.push(old_key.clone());
1118 extensions_to_load.push(new_key.clone());
1119 }
1120 }
1121 Ordering::Less => {
1122 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1123 }
1124 Ordering::Greater => {
1125 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1126 }
1127 },
1128 }
1129 }
1130 self.modified_extensions.clear();
1131 }
1132
1133 if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1134 return Task::ready(());
1135 }
1136
1137 let reload_count = extensions_to_unload
1138 .iter()
1139 .filter(|id| extensions_to_load.contains(id))
1140 .count();
1141
1142 log::info!(
1143 "extensions updated. loading {}, reloading {}, unloading {}",
1144 extensions_to_load.len() - reload_count,
1145 reload_count,
1146 extensions_to_unload.len() - reload_count
1147 );
1148
1149 let extension_ids = extensions_to_load
1150 .iter()
1151 .filter_map(|id| {
1152 Some((
1153 id.clone(),
1154 new_index.extensions.get(id)?.manifest.version.clone(),
1155 ))
1156 })
1157 .collect::<Vec<_>>();
1158
1159 telemetry::event!("Extensions Loaded", id_and_versions = extension_ids);
1160
1161 let themes_to_remove = old_index
1162 .themes
1163 .iter()
1164 .filter_map(|(name, entry)| {
1165 if extensions_to_unload.contains(&entry.extension) {
1166 Some(name.clone().into())
1167 } else {
1168 None
1169 }
1170 })
1171 .collect::<Vec<_>>();
1172 let icon_themes_to_remove = old_index
1173 .icon_themes
1174 .iter()
1175 .filter_map(|(name, entry)| {
1176 if extensions_to_unload.contains(&entry.extension) {
1177 Some(name.clone().into())
1178 } else {
1179 None
1180 }
1181 })
1182 .collect::<Vec<_>>();
1183 let languages_to_remove = old_index
1184 .languages
1185 .iter()
1186 .filter_map(|(name, entry)| {
1187 if extensions_to_unload.contains(&entry.extension) {
1188 Some(name.clone())
1189 } else {
1190 None
1191 }
1192 })
1193 .collect::<Vec<_>>();
1194 let mut grammars_to_remove = Vec::new();
1195 let mut server_removal_tasks = Vec::with_capacity(extensions_to_unload.len());
1196 for extension_id in &extensions_to_unload {
1197 let Some(extension) = old_index.extensions.get(extension_id) else {
1198 continue;
1199 };
1200 grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1201 for (language_server_name, config) in &extension.manifest.language_servers {
1202 for language in config.languages() {
1203 server_removal_tasks.push(self.proxy.remove_language_server(
1204 &language,
1205 language_server_name,
1206 cx,
1207 ));
1208 }
1209 }
1210
1211 for server_id in extension.manifest.context_servers.keys() {
1212 self.proxy.unregister_context_server(server_id.clone(), cx);
1213 }
1214 for adapter in extension.manifest.debug_adapters.keys() {
1215 self.proxy.unregister_debug_adapter(adapter.clone());
1216 }
1217 for locator in extension.manifest.debug_locators.keys() {
1218 self.proxy.unregister_debug_locator(locator.clone());
1219 }
1220 for command_name in extension.manifest.slash_commands.keys() {
1221 self.proxy.unregister_slash_command(command_name.clone());
1222 }
1223 }
1224
1225 self.wasm_extensions
1226 .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1227 self.proxy.remove_user_themes(themes_to_remove);
1228 self.proxy.remove_icon_themes(icon_themes_to_remove);
1229 self.proxy
1230 .remove_languages(&languages_to_remove, &grammars_to_remove);
1231
1232 let mut grammars_to_add = Vec::new();
1233 let mut themes_to_add = Vec::new();
1234 let mut icon_themes_to_add = Vec::new();
1235 let mut snippets_to_add = Vec::new();
1236 for extension_id in &extensions_to_load {
1237 let Some(extension) = new_index.extensions.get(extension_id) else {
1238 continue;
1239 };
1240
1241 grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1242 let mut grammar_path = self.installed_dir.clone();
1243 grammar_path.extend([extension_id.as_ref(), "grammars"]);
1244 grammar_path.push(grammar_name.as_ref());
1245 grammar_path.set_extension("wasm");
1246 (grammar_name.clone(), grammar_path)
1247 }));
1248 themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1249 let mut path = self.installed_dir.clone();
1250 path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1251 path
1252 }));
1253 icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1254 |icon_theme_path| {
1255 let mut path = self.installed_dir.clone();
1256 path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1257
1258 let mut icons_root_path = self.installed_dir.clone();
1259 icons_root_path.extend([Path::new(extension_id.as_ref())]);
1260
1261 (path, icons_root_path)
1262 },
1263 ));
1264 snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1265 let mut path = self.installed_dir.clone();
1266 path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1267 path
1268 }));
1269 }
1270
1271 self.proxy.register_grammars(grammars_to_add);
1272 let languages_to_add = new_index
1273 .languages
1274 .iter_mut()
1275 .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1276 .collect::<Vec<_>>();
1277 for (language_name, language) in languages_to_add {
1278 let mut language_path = self.installed_dir.clone();
1279 language_path.extend([
1280 Path::new(language.extension.as_ref()),
1281 language.path.as_path(),
1282 ]);
1283 self.proxy.register_language(
1284 language_name.clone(),
1285 language.grammar.clone(),
1286 language.matcher.clone(),
1287 language.hidden,
1288 Arc::new(move || {
1289 let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1290 let config: LanguageConfig = ::toml::from_str(&config)?;
1291 let queries = load_plugin_queries(&language_path);
1292 let context_provider =
1293 std::fs::read_to_string(language_path.join("tasks.json"))
1294 .ok()
1295 .and_then(|contents| {
1296 let definitions =
1297 serde_json_lenient::from_str(&contents).log_err()?;
1298 Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1299 });
1300
1301 Ok(LoadedLanguage {
1302 config,
1303 queries,
1304 context_provider,
1305 toolchain_provider: None,
1306 manifest_name: None,
1307 })
1308 }),
1309 );
1310 }
1311
1312 let fs = self.fs.clone();
1313 let wasm_host = self.wasm_host.clone();
1314 let root_dir = self.installed_dir.clone();
1315 let proxy = self.proxy.clone();
1316 let extension_entries = extensions_to_load
1317 .iter()
1318 .filter_map(|name| new_index.extensions.get(name).cloned())
1319 .collect::<Vec<_>>();
1320 self.extension_index = new_index;
1321 cx.notify();
1322 cx.emit(Event::ExtensionsUpdated);
1323
1324 cx.spawn(async move |this, cx| {
1325 cx.background_spawn({
1326 let fs = fs.clone();
1327 async move {
1328 let _ = join_all(server_removal_tasks).await;
1329 for theme_path in themes_to_add {
1330 proxy
1331 .load_user_theme(theme_path, fs.clone())
1332 .await
1333 .log_err();
1334 }
1335
1336 for (icon_theme_path, icons_root_path) in icon_themes_to_add {
1337 proxy
1338 .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1339 .await
1340 .log_err();
1341 }
1342
1343 for snippets_path in &snippets_to_add {
1344 match fs
1345 .load(snippets_path)
1346 .await
1347 .with_context(|| format!("Loading snippets from {snippets_path:?}"))
1348 {
1349 Ok(snippets_contents) => {
1350 proxy
1351 .register_snippet(snippets_path, &snippets_contents)
1352 .log_err();
1353 }
1354 Err(e) => log::error!("Cannot load snippets: {e:#}"),
1355 }
1356 }
1357 }
1358 })
1359 .await;
1360
1361 let mut wasm_extensions = Vec::new();
1362 for extension in extension_entries {
1363 if extension.manifest.lib.kind.is_none() {
1364 continue;
1365 };
1366
1367 let extension_path = root_dir.join(extension.manifest.id.as_ref());
1368 let wasm_extension = WasmExtension::load(
1369 &extension_path,
1370 &extension.manifest,
1371 wasm_host.clone(),
1372 cx,
1373 )
1374 .await
1375 .with_context(|| format!("Loading extension from {extension_path:?}"));
1376
1377 match wasm_extension {
1378 Ok(wasm_extension) => {
1379 wasm_extensions.push((extension.manifest.clone(), wasm_extension))
1380 }
1381 Err(e) => {
1382 log::error!("Failed to load extension: {e:#}");
1383 this.update(cx, |_, cx| {
1384 cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1385 })
1386 .ok();
1387 }
1388 }
1389 }
1390
1391 this.update(cx, |this, cx| {
1392 this.reload_complete_senders.clear();
1393
1394 for (manifest, wasm_extension) in &wasm_extensions {
1395 let extension = Arc::new(wasm_extension.clone());
1396
1397 for (language_server_id, language_server_config) in &manifest.language_servers {
1398 for language in language_server_config.languages() {
1399 this.proxy.register_language_server(
1400 extension.clone(),
1401 language_server_id.clone(),
1402 language.clone(),
1403 );
1404 }
1405 }
1406
1407 for (slash_command_name, slash_command) in &manifest.slash_commands {
1408 this.proxy.register_slash_command(
1409 extension.clone(),
1410 extension::SlashCommand {
1411 name: slash_command_name.to_string(),
1412 description: slash_command.description.to_string(),
1413 // We don't currently expose this as a configurable option, as it currently drives
1414 // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1415 // defined in extensions, as they are not able to be added to the menu.
1416 tooltip_text: String::new(),
1417 requires_argument: slash_command.requires_argument,
1418 },
1419 );
1420 }
1421
1422 for id in manifest.context_servers.keys() {
1423 this.proxy
1424 .register_context_server(extension.clone(), id.clone(), cx);
1425 }
1426
1427 for (debug_adapter, meta) in &manifest.debug_adapters {
1428 let mut path = root_dir.clone();
1429 path.push(Path::new(manifest.id.as_ref()));
1430 if let Some(schema_path) = &meta.schema_path {
1431 path.push(schema_path);
1432 } else {
1433 path.push("debug_adapter_schemas");
1434 path.push(Path::new(debug_adapter.as_ref()).with_extension("json"));
1435 }
1436
1437 this.proxy.register_debug_adapter(
1438 extension.clone(),
1439 debug_adapter.clone(),
1440 &path,
1441 );
1442 }
1443
1444 for debug_adapter in manifest.debug_locators.keys() {
1445 this.proxy
1446 .register_debug_locator(extension.clone(), debug_adapter.clone());
1447 }
1448 }
1449
1450 this.wasm_extensions.extend(wasm_extensions);
1451 this.proxy.set_extensions_loaded();
1452 this.proxy.reload_current_theme(cx);
1453 this.proxy.reload_current_icon_theme(cx);
1454
1455 if let Some(events) = ExtensionEvents::try_global(cx) {
1456 events.update(cx, |this, cx| {
1457 this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1458 });
1459 }
1460 })
1461 .ok();
1462 })
1463 }
1464
1465 fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1466 let fs = self.fs.clone();
1467 let work_dir = self.wasm_host.work_dir.clone();
1468 let extensions_dir = self.installed_dir.clone();
1469 let index_path = self.index_path.clone();
1470 let proxy = self.proxy.clone();
1471 cx.background_spawn(async move {
1472 let start_time = Instant::now();
1473 let mut index = ExtensionIndex::default();
1474
1475 fs.create_dir(&work_dir).await.log_err();
1476 fs.create_dir(&extensions_dir).await.log_err();
1477
1478 let extension_paths = fs.read_dir(&extensions_dir).await;
1479 if let Ok(mut extension_paths) = extension_paths {
1480 while let Some(extension_dir) = extension_paths.next().await {
1481 let Ok(extension_dir) = extension_dir else {
1482 continue;
1483 };
1484
1485 if extension_dir
1486 .file_name()
1487 .is_some_and(|file_name| file_name == ".DS_Store")
1488 {
1489 continue;
1490 }
1491
1492 Self::add_extension_to_index(
1493 fs.clone(),
1494 extension_dir,
1495 &mut index,
1496 proxy.clone(),
1497 )
1498 .await
1499 .log_err();
1500 }
1501 }
1502
1503 if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1504 fs.save(&index_path, &index_json.as_str().into(), Default::default())
1505 .await
1506 .context("failed to save extension index")
1507 .log_err();
1508 }
1509
1510 log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1511 index
1512 })
1513 }
1514
1515 async fn add_extension_to_index(
1516 fs: Arc<dyn Fs>,
1517 extension_dir: PathBuf,
1518 index: &mut ExtensionIndex,
1519 proxy: Arc<ExtensionHostProxy>,
1520 ) -> Result<()> {
1521 let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1522 let extension_id = extension_manifest.id.clone();
1523
1524 // TODO: distinguish dev extensions more explicitly, by the absence
1525 // of a checksum file that we'll create when downloading normal extensions.
1526 let is_dev = fs
1527 .metadata(&extension_dir)
1528 .await?
1529 .context("directory does not exist")?
1530 .is_symlink;
1531
1532 if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1533 while let Some(language_path) = language_paths.next().await {
1534 let language_path = language_path?;
1535 let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1536 continue;
1537 };
1538 let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1539 continue;
1540 };
1541 if !fs_metadata.is_dir {
1542 continue;
1543 }
1544 let config = fs.load(&language_path.join("config.toml")).await?;
1545 let config = ::toml::from_str::<LanguageConfig>(&config)?;
1546
1547 let relative_path = relative_path.to_path_buf();
1548 if !extension_manifest.languages.contains(&relative_path) {
1549 extension_manifest.languages.push(relative_path.clone());
1550 }
1551
1552 index.languages.insert(
1553 config.name.clone(),
1554 ExtensionIndexLanguageEntry {
1555 extension: extension_id.clone(),
1556 path: relative_path,
1557 matcher: config.matcher,
1558 hidden: config.hidden,
1559 grammar: config.grammar,
1560 },
1561 );
1562 }
1563 }
1564
1565 if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1566 while let Some(theme_path) = theme_paths.next().await {
1567 let theme_path = theme_path?;
1568 let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1569 continue;
1570 };
1571
1572 let Some(theme_families) = proxy
1573 .list_theme_names(theme_path.clone(), fs.clone())
1574 .await
1575 .log_err()
1576 else {
1577 continue;
1578 };
1579
1580 let relative_path = relative_path.to_path_buf();
1581 if !extension_manifest.themes.contains(&relative_path) {
1582 extension_manifest.themes.push(relative_path.clone());
1583 }
1584
1585 for theme_name in theme_families {
1586 index.themes.insert(
1587 theme_name.into(),
1588 ExtensionIndexThemeEntry {
1589 extension: extension_id.clone(),
1590 path: relative_path.clone(),
1591 },
1592 );
1593 }
1594 }
1595 }
1596
1597 if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1598 while let Some(icon_theme_path) = icon_theme_paths.next().await {
1599 let icon_theme_path = icon_theme_path?;
1600 let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1601 continue;
1602 };
1603
1604 let Some(icon_theme_families) = proxy
1605 .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1606 .await
1607 .log_err()
1608 else {
1609 continue;
1610 };
1611
1612 let relative_path = relative_path.to_path_buf();
1613 if !extension_manifest.icon_themes.contains(&relative_path) {
1614 extension_manifest.icon_themes.push(relative_path.clone());
1615 }
1616
1617 for icon_theme_name in icon_theme_families {
1618 index.icon_themes.insert(
1619 icon_theme_name.into(),
1620 ExtensionIndexIconThemeEntry {
1621 extension: extension_id.clone(),
1622 path: relative_path.clone(),
1623 },
1624 );
1625 }
1626 }
1627 }
1628
1629 let extension_wasm_path = extension_dir.join("extension.wasm");
1630 if fs.is_file(&extension_wasm_path).await {
1631 extension_manifest
1632 .lib
1633 .kind
1634 .get_or_insert(ExtensionLibraryKind::Rust);
1635 }
1636
1637 index.extensions.insert(
1638 extension_id.clone(),
1639 ExtensionIndexEntry {
1640 dev: is_dev,
1641 manifest: Arc::new(extension_manifest),
1642 },
1643 );
1644
1645 Ok(())
1646 }
1647
1648 fn prepare_remote_extension(
1649 &mut self,
1650 extension_id: Arc<str>,
1651 is_dev: bool,
1652 tmp_dir: PathBuf,
1653 cx: &mut Context<Self>,
1654 ) -> Task<Result<()>> {
1655 let src_dir = self.extensions_dir().join(extension_id.as_ref());
1656 let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1657 else {
1658 return Task::ready(Err(anyhow!("extension no longer installed")));
1659 };
1660 let fs = self.fs.clone();
1661 cx.background_spawn(async move {
1662 const EXTENSION_TOML: &str = "extension.toml";
1663 const EXTENSION_WASM: &str = "extension.wasm";
1664 const CONFIG_TOML: &str = "config.toml";
1665
1666 if is_dev {
1667 let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1668 fs.save(
1669 &tmp_dir.join(EXTENSION_TOML),
1670 &Rope::from(manifest_toml),
1671 language::LineEnding::Unix,
1672 )
1673 .await?;
1674 } else {
1675 fs.copy_file(
1676 &src_dir.join(EXTENSION_TOML),
1677 &tmp_dir.join(EXTENSION_TOML),
1678 fs::CopyOptions::default(),
1679 )
1680 .await?
1681 }
1682
1683 if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1684 fs.copy_file(
1685 &src_dir.join(EXTENSION_WASM),
1686 &tmp_dir.join(EXTENSION_WASM),
1687 fs::CopyOptions::default(),
1688 )
1689 .await?
1690 }
1691
1692 for language_path in loaded_extension.manifest.languages.iter() {
1693 if fs
1694 .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1695 .await
1696 {
1697 fs.create_dir(&tmp_dir.join(language_path)).await?;
1698 fs.copy_file(
1699 &src_dir.join(language_path).join(CONFIG_TOML),
1700 &tmp_dir.join(language_path).join(CONFIG_TOML),
1701 fs::CopyOptions::default(),
1702 )
1703 .await?
1704 }
1705 }
1706
1707 for (adapter_name, meta) in loaded_extension.manifest.debug_adapters.iter() {
1708 let schema_path = &extension::build_debug_adapter_schema_path(adapter_name, meta);
1709
1710 if fs.is_file(&src_dir.join(schema_path)).await {
1711 if let Some(parent) = schema_path.parent() {
1712 fs.create_dir(&tmp_dir.join(parent)).await?
1713 }
1714 fs.copy_file(
1715 &src_dir.join(schema_path),
1716 &tmp_dir.join(schema_path),
1717 fs::CopyOptions::default(),
1718 )
1719 .await?
1720 }
1721 }
1722
1723 Ok(())
1724 })
1725 }
1726
1727 async fn sync_extensions_over_ssh(
1728 this: &WeakEntity<Self>,
1729 client: WeakEntity<RemoteClient>,
1730 cx: &mut AsyncApp,
1731 ) -> Result<()> {
1732 let extensions = this.update(cx, |this, _cx| {
1733 this.extension_index
1734 .extensions
1735 .iter()
1736 .filter_map(|(id, entry)| {
1737 if !entry.manifest.allow_remote_load() {
1738 return None;
1739 }
1740 Some(proto::Extension {
1741 id: id.to_string(),
1742 version: entry.manifest.version.to_string(),
1743 dev: entry.dev,
1744 })
1745 })
1746 .collect()
1747 })?;
1748
1749 let response = client
1750 .update(cx, |client, _cx| {
1751 client
1752 .proto_client()
1753 .request(proto::SyncExtensions { extensions })
1754 })?
1755 .await?;
1756 let path_style = client.read_with(cx, |client, _| client.path_style())?;
1757
1758 for missing_extension in response.missing_extensions.into_iter() {
1759 let tmp_dir = tempfile::tempdir()?;
1760 this.update(cx, |this, cx| {
1761 this.prepare_remote_extension(
1762 missing_extension.id.clone().into(),
1763 missing_extension.dev,
1764 tmp_dir.path().to_owned(),
1765 cx,
1766 )
1767 })?
1768 .await?;
1769 let dest_dir = RemotePathBuf::new(
1770 PathBuf::from(&response.tmp_dir).join(missing_extension.clone().id),
1771 path_style,
1772 );
1773 log::info!("Uploading extension {}", missing_extension.clone().id);
1774
1775 client
1776 .update(cx, |client, cx| {
1777 client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
1778 })?
1779 .await?;
1780
1781 log::info!(
1782 "Finished uploading extension {}",
1783 missing_extension.clone().id
1784 );
1785
1786 client
1787 .update(cx, |client, _cx| {
1788 client.proto_client().request(proto::InstallExtension {
1789 tmp_dir: dest_dir.to_proto(),
1790 extension: Some(missing_extension),
1791 })
1792 })?
1793 .await?;
1794 }
1795
1796 anyhow::Ok(())
1797 }
1798
1799 pub async fn update_ssh_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
1800 let clients = this.update(cx, |this, _cx| {
1801 this.remote_clients.retain(|_k, v| v.upgrade().is_some());
1802 this.remote_clients.values().cloned().collect::<Vec<_>>()
1803 })?;
1804
1805 for client in clients {
1806 Self::sync_extensions_over_ssh(this, client, cx)
1807 .await
1808 .log_err();
1809 }
1810
1811 anyhow::Ok(())
1812 }
1813
1814 pub fn register_remote_client(&mut self, client: Entity<RemoteClient>, cx: &mut Context<Self>) {
1815 let options = client.read(cx).connection_options();
1816
1817 if let Some(existing_client) = self.remote_clients.get(&options)
1818 && existing_client.upgrade().is_some()
1819 {
1820 return;
1821 }
1822
1823 self.remote_clients.insert(options, client.downgrade());
1824 self.ssh_registered_tx.unbounded_send(()).ok();
1825 }
1826}
1827
1828fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1829 let mut result = LanguageQueries::default();
1830 if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1831 for entry in entries {
1832 let Some(entry) = entry.log_err() else {
1833 continue;
1834 };
1835 let path = entry.path();
1836 if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1837 if !remainder.ends_with(".scm") {
1838 continue;
1839 }
1840 for (name, query) in QUERY_FILENAME_PREFIXES {
1841 if remainder.starts_with(name) {
1842 if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1843 match query(&mut result) {
1844 None => *query(&mut result) = Some(contents.into()),
1845 Some(r) => r.to_mut().push_str(contents.as_ref()),
1846 }
1847 }
1848 break;
1849 }
1850 }
1851 }
1852 }
1853 }
1854 result
1855}