1mod ignore;
2mod lsp_command;
3pub mod search;
4pub mod terminals;
5pub mod worktree;
6
7#[cfg(test)]
8mod project_tests;
9
10use anyhow::{anyhow, Context, Result};
11use client::{proto, Client, TypedEnvelope, UserStore};
12use clock::ReplicaId;
13use collections::{hash_map, BTreeMap, HashMap, HashSet};
14use copilot::Copilot;
15use futures::{
16 channel::mpsc::{self, UnboundedReceiver},
17 future::{try_join_all, Shared},
18 AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
19};
20use globset::{Glob, GlobSet, GlobSetBuilder};
21use gpui::{
22 AnyModelHandle, AppContext, AsyncAppContext, BorrowAppContext, Entity, ModelContext,
23 ModelHandle, Task, WeakModelHandle,
24};
25use language::{
26 point_to_lsp,
27 proto::{
28 deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
29 serialize_anchor, serialize_version,
30 },
31 range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CachedLspAdapter, CodeAction, CodeLabel,
32 Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Event as BufferEvent, File as _,
33 Language, LanguageRegistry, LanguageServerName, LocalFile, OffsetRangeExt, Operation, Patch,
34 PendingLanguageServer, PointUtf16, RopeFingerprint, TextBufferSnapshot, ToOffset, ToPointUtf16,
35 Transaction, Unclipped,
36};
37use lsp::{
38 DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
39 DocumentHighlightKind, LanguageServer, LanguageServerId,
40};
41use lsp_command::*;
42use postage::watch;
43use rand::prelude::*;
44use search::SearchQuery;
45use serde::Serialize;
46use settings::{FormatOnSave, Formatter, Settings};
47use sha2::{Digest, Sha256};
48use similar::{ChangeTag, TextDiff};
49use std::{
50 cell::RefCell,
51 cmp::{self, Ordering},
52 convert::TryInto,
53 hash::Hash,
54 mem,
55 num::NonZeroU32,
56 ops::Range,
57 path::{Component, Path, PathBuf},
58 rc::Rc,
59 str,
60 sync::{
61 atomic::{AtomicUsize, Ordering::SeqCst},
62 Arc,
63 },
64 time::{Duration, Instant, SystemTime},
65};
66
67use terminals::Terminals;
68
69use util::{debug_panic, defer, merge_json_value_into, post_inc, ResultExt, TryFutureExt as _};
70
71pub use fs::*;
72pub use worktree::*;
73
74pub trait Item {
75 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
76 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
77}
78
79// Language server state is stored across 3 collections:
80// language_servers =>
81// a mapping from unique server id to LanguageServerState which can either be a task for a
82// server in the process of starting, or a running server with adapter and language server arcs
83// language_server_ids => a mapping from worktreeId and server name to the unique server id
84// language_server_statuses => a mapping from unique server id to the current server status
85//
86// Multiple worktrees can map to the same language server for example when you jump to the definition
87// of a file in the standard library. So language_server_ids is used to look up which server is active
88// for a given worktree and language server name
89//
90// When starting a language server, first the id map is checked to make sure a server isn't already available
91// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
92// the Starting variant of LanguageServerState is stored in the language_servers map.
93pub struct Project {
94 worktrees: Vec<WorktreeHandle>,
95 active_entry: Option<ProjectEntryId>,
96 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
97 languages: Arc<LanguageRegistry>,
98 language_servers: HashMap<LanguageServerId, LanguageServerState>,
99 language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
100 language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
101 last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
102 client: Arc<client::Client>,
103 next_entry_id: Arc<AtomicUsize>,
104 join_project_response_message_id: u32,
105 next_diagnostic_group_id: usize,
106 user_store: ModelHandle<UserStore>,
107 fs: Arc<dyn Fs>,
108 client_state: Option<ProjectClientState>,
109 collaborators: HashMap<proto::PeerId, Collaborator>,
110 client_subscriptions: Vec<client::Subscription>,
111 _subscriptions: Vec<gpui::Subscription>,
112 next_buffer_id: u64,
113 opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
114 shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
115 #[allow(clippy::type_complexity)]
116 loading_buffers_by_path: HashMap<
117 ProjectPath,
118 postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
119 >,
120 #[allow(clippy::type_complexity)]
121 loading_local_worktrees:
122 HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
123 opened_buffers: HashMap<u64, OpenBuffer>,
124 local_buffer_ids_by_path: HashMap<ProjectPath, u64>,
125 local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, u64>,
126 /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
127 /// Used for re-issuing buffer requests when peers temporarily disconnect
128 incomplete_remote_buffers: HashMap<u64, Option<ModelHandle<Buffer>>>,
129 buffer_snapshots: HashMap<u64, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
130 buffers_being_formatted: HashSet<u64>,
131 nonce: u128,
132 _maintain_buffer_languages: Task<()>,
133 _maintain_workspace_config: Task<()>,
134 terminals: Terminals,
135 copilot_enabled: bool,
136}
137
138struct LspBufferSnapshot {
139 version: i32,
140 snapshot: TextBufferSnapshot,
141}
142
143/// Message ordered with respect to buffer operations
144enum BufferOrderedMessage {
145 Operation {
146 buffer_id: u64,
147 operation: proto::Operation,
148 },
149 LanguageServerUpdate {
150 language_server_id: LanguageServerId,
151 message: proto::update_language_server::Variant,
152 },
153 Resync,
154}
155
156enum LocalProjectUpdate {
157 WorktreesChanged,
158 CreateBufferForPeer {
159 peer_id: proto::PeerId,
160 buffer_id: u64,
161 },
162}
163
164enum OpenBuffer {
165 Strong(ModelHandle<Buffer>),
166 Weak(WeakModelHandle<Buffer>),
167 Operations(Vec<Operation>),
168}
169
170enum WorktreeHandle {
171 Strong(ModelHandle<Worktree>),
172 Weak(WeakModelHandle<Worktree>),
173}
174
175enum ProjectClientState {
176 Local {
177 remote_id: u64,
178 updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
179 _send_updates: Task<()>,
180 },
181 Remote {
182 sharing_has_stopped: bool,
183 remote_id: u64,
184 replica_id: ReplicaId,
185 },
186}
187
188#[derive(Clone, Debug)]
189pub struct Collaborator {
190 pub peer_id: proto::PeerId,
191 pub replica_id: ReplicaId,
192}
193
194#[derive(Clone, Debug, PartialEq, Eq)]
195pub enum Event {
196 LanguageServerAdded(LanguageServerId),
197 LanguageServerRemoved(LanguageServerId),
198 ActiveEntryChanged(Option<ProjectEntryId>),
199 WorktreeAdded,
200 WorktreeRemoved(WorktreeId),
201 DiskBasedDiagnosticsStarted {
202 language_server_id: LanguageServerId,
203 },
204 DiskBasedDiagnosticsFinished {
205 language_server_id: LanguageServerId,
206 },
207 DiagnosticsUpdated {
208 path: ProjectPath,
209 language_server_id: LanguageServerId,
210 },
211 RemoteIdChanged(Option<u64>),
212 DisconnectedFromHost,
213 Closed,
214 CollaboratorUpdated {
215 old_peer_id: proto::PeerId,
216 new_peer_id: proto::PeerId,
217 },
218 CollaboratorLeft(proto::PeerId),
219}
220
221pub enum LanguageServerState {
222 Starting(Task<Option<Arc<LanguageServer>>>),
223 Running {
224 language: Arc<Language>,
225 adapter: Arc<CachedLspAdapter>,
226 server: Arc<LanguageServer>,
227 watched_paths: HashMap<WorktreeId, GlobSet>,
228 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
229 },
230}
231
232#[derive(Serialize)]
233pub struct LanguageServerStatus {
234 pub name: String,
235 pub pending_work: BTreeMap<String, LanguageServerProgress>,
236 pub has_pending_diagnostic_updates: bool,
237 progress_tokens: HashSet<String>,
238}
239
240#[derive(Clone, Debug, Serialize)]
241pub struct LanguageServerProgress {
242 pub message: Option<String>,
243 pub percentage: Option<usize>,
244 #[serde(skip_serializing)]
245 pub last_update_at: Instant,
246}
247
248#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
249pub struct ProjectPath {
250 pub worktree_id: WorktreeId,
251 pub path: Arc<Path>,
252}
253
254#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
255pub struct DiagnosticSummary {
256 pub error_count: usize,
257 pub warning_count: usize,
258}
259
260#[derive(Debug, Clone)]
261pub struct Location {
262 pub buffer: ModelHandle<Buffer>,
263 pub range: Range<language::Anchor>,
264}
265
266#[derive(Debug, Clone)]
267pub struct LocationLink {
268 pub origin: Option<Location>,
269 pub target: Location,
270}
271
272#[derive(Debug)]
273pub struct DocumentHighlight {
274 pub range: Range<language::Anchor>,
275 pub kind: DocumentHighlightKind,
276}
277
278#[derive(Clone, Debug)]
279pub struct Symbol {
280 pub language_server_name: LanguageServerName,
281 pub source_worktree_id: WorktreeId,
282 pub path: ProjectPath,
283 pub label: CodeLabel,
284 pub name: String,
285 pub kind: lsp::SymbolKind,
286 pub range: Range<Unclipped<PointUtf16>>,
287 pub signature: [u8; 32],
288}
289
290#[derive(Clone, Debug, PartialEq)]
291pub struct HoverBlock {
292 pub text: String,
293 pub kind: HoverBlockKind,
294}
295
296#[derive(Clone, Debug, PartialEq)]
297pub enum HoverBlockKind {
298 PlainText,
299 Markdown,
300 Code { language: String },
301}
302
303#[derive(Debug)]
304pub struct Hover {
305 pub contents: Vec<HoverBlock>,
306 pub range: Option<Range<language::Anchor>>,
307}
308
309#[derive(Default)]
310pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
311
312impl DiagnosticSummary {
313 fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
314 let mut this = Self {
315 error_count: 0,
316 warning_count: 0,
317 };
318
319 for entry in diagnostics {
320 if entry.diagnostic.is_primary {
321 match entry.diagnostic.severity {
322 DiagnosticSeverity::ERROR => this.error_count += 1,
323 DiagnosticSeverity::WARNING => this.warning_count += 1,
324 _ => {}
325 }
326 }
327 }
328
329 this
330 }
331
332 pub fn is_empty(&self) -> bool {
333 self.error_count == 0 && self.warning_count == 0
334 }
335
336 pub fn to_proto(
337 &self,
338 language_server_id: LanguageServerId,
339 path: &Path,
340 ) -> proto::DiagnosticSummary {
341 proto::DiagnosticSummary {
342 path: path.to_string_lossy().to_string(),
343 language_server_id: language_server_id.0 as u64,
344 error_count: self.error_count as u32,
345 warning_count: self.warning_count as u32,
346 }
347 }
348}
349
350#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
351pub struct ProjectEntryId(usize);
352
353impl ProjectEntryId {
354 pub const MAX: Self = Self(usize::MAX);
355
356 pub fn new(counter: &AtomicUsize) -> Self {
357 Self(counter.fetch_add(1, SeqCst))
358 }
359
360 pub fn from_proto(id: u64) -> Self {
361 Self(id as usize)
362 }
363
364 pub fn to_proto(&self) -> u64 {
365 self.0 as u64
366 }
367
368 pub fn to_usize(&self) -> usize {
369 self.0
370 }
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum FormatTrigger {
375 Save,
376 Manual,
377}
378
379impl FormatTrigger {
380 fn from_proto(value: i32) -> FormatTrigger {
381 match value {
382 0 => FormatTrigger::Save,
383 1 => FormatTrigger::Manual,
384 _ => FormatTrigger::Save,
385 }
386 }
387}
388
389impl Project {
390 pub fn init(client: &Arc<Client>) {
391 client.add_model_message_handler(Self::handle_add_collaborator);
392 client.add_model_message_handler(Self::handle_update_project_collaborator);
393 client.add_model_message_handler(Self::handle_remove_collaborator);
394 client.add_model_message_handler(Self::handle_buffer_reloaded);
395 client.add_model_message_handler(Self::handle_buffer_saved);
396 client.add_model_message_handler(Self::handle_start_language_server);
397 client.add_model_message_handler(Self::handle_update_language_server);
398 client.add_model_message_handler(Self::handle_update_project);
399 client.add_model_message_handler(Self::handle_unshare_project);
400 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
401 client.add_model_message_handler(Self::handle_update_buffer_file);
402 client.add_model_request_handler(Self::handle_update_buffer);
403 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
404 client.add_model_message_handler(Self::handle_update_worktree);
405 client.add_model_request_handler(Self::handle_create_project_entry);
406 client.add_model_request_handler(Self::handle_rename_project_entry);
407 client.add_model_request_handler(Self::handle_copy_project_entry);
408 client.add_model_request_handler(Self::handle_delete_project_entry);
409 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
410 client.add_model_request_handler(Self::handle_apply_code_action);
411 client.add_model_request_handler(Self::handle_reload_buffers);
412 client.add_model_request_handler(Self::handle_synchronize_buffers);
413 client.add_model_request_handler(Self::handle_format_buffers);
414 client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
415 client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
416 client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
417 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
418 client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
419 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
420 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
421 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
422 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
423 client.add_model_request_handler(Self::handle_search_project);
424 client.add_model_request_handler(Self::handle_get_project_symbols);
425 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
426 client.add_model_request_handler(Self::handle_open_buffer_by_id);
427 client.add_model_request_handler(Self::handle_open_buffer_by_path);
428 client.add_model_request_handler(Self::handle_save_buffer);
429 client.add_model_message_handler(Self::handle_update_diff_base);
430 }
431
432 pub fn local(
433 client: Arc<Client>,
434 user_store: ModelHandle<UserStore>,
435 languages: Arc<LanguageRegistry>,
436 fs: Arc<dyn Fs>,
437 cx: &mut AppContext,
438 ) -> ModelHandle<Self> {
439 cx.add_model(|cx: &mut ModelContext<Self>| {
440 let (tx, rx) = mpsc::unbounded();
441 cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
442 .detach();
443 Self {
444 worktrees: Default::default(),
445 buffer_ordered_messages_tx: tx,
446 collaborators: Default::default(),
447 next_buffer_id: 0,
448 opened_buffers: Default::default(),
449 shared_buffers: Default::default(),
450 incomplete_remote_buffers: Default::default(),
451 loading_buffers_by_path: Default::default(),
452 loading_local_worktrees: Default::default(),
453 local_buffer_ids_by_path: Default::default(),
454 local_buffer_ids_by_entry_id: Default::default(),
455 buffer_snapshots: Default::default(),
456 join_project_response_message_id: 0,
457 client_state: None,
458 opened_buffer: watch::channel(),
459 client_subscriptions: Vec::new(),
460 _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
461 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
462 _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
463 active_entry: None,
464 languages,
465 client,
466 user_store,
467 fs,
468 next_entry_id: Default::default(),
469 next_diagnostic_group_id: Default::default(),
470 language_servers: Default::default(),
471 language_server_ids: Default::default(),
472 language_server_statuses: Default::default(),
473 last_workspace_edits_by_language_server: Default::default(),
474 buffers_being_formatted: Default::default(),
475 nonce: StdRng::from_entropy().gen(),
476 terminals: Terminals {
477 local_handles: Vec::new(),
478 },
479 copilot_enabled: Copilot::global(cx).is_some(),
480 }
481 })
482 }
483
484 pub async fn remote(
485 remote_id: u64,
486 client: Arc<Client>,
487 user_store: ModelHandle<UserStore>,
488 languages: Arc<LanguageRegistry>,
489 fs: Arc<dyn Fs>,
490 mut cx: AsyncAppContext,
491 ) -> Result<ModelHandle<Self>> {
492 client.authenticate_and_connect(true, &cx).await?;
493
494 let subscription = client.subscribe_to_entity(remote_id)?;
495 let response = client
496 .request_envelope(proto::JoinProject {
497 project_id: remote_id,
498 })
499 .await?;
500 let this = cx.add_model(|cx| {
501 let replica_id = response.payload.replica_id as ReplicaId;
502
503 let mut worktrees = Vec::new();
504 for worktree in response.payload.worktrees {
505 let worktree = cx.update(|cx| {
506 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
507 });
508 worktrees.push(worktree);
509 }
510
511 let (tx, rx) = mpsc::unbounded();
512 cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
513 .detach();
514 let mut this = Self {
515 worktrees: Vec::new(),
516 buffer_ordered_messages_tx: tx,
517 loading_buffers_by_path: Default::default(),
518 next_buffer_id: 0,
519 opened_buffer: watch::channel(),
520 shared_buffers: Default::default(),
521 incomplete_remote_buffers: Default::default(),
522 loading_local_worktrees: Default::default(),
523 local_buffer_ids_by_path: Default::default(),
524 local_buffer_ids_by_entry_id: Default::default(),
525 active_entry: None,
526 collaborators: Default::default(),
527 join_project_response_message_id: response.message_id,
528 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
529 _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
530 languages,
531 user_store: user_store.clone(),
532 fs,
533 next_entry_id: Default::default(),
534 next_diagnostic_group_id: Default::default(),
535 client_subscriptions: Default::default(),
536 _subscriptions: Default::default(),
537 client: client.clone(),
538 client_state: Some(ProjectClientState::Remote {
539 sharing_has_stopped: false,
540 remote_id,
541 replica_id,
542 }),
543 language_servers: Default::default(),
544 language_server_ids: Default::default(),
545 language_server_statuses: response
546 .payload
547 .language_servers
548 .into_iter()
549 .map(|server| {
550 (
551 LanguageServerId(server.id as usize),
552 LanguageServerStatus {
553 name: server.name,
554 pending_work: Default::default(),
555 has_pending_diagnostic_updates: false,
556 progress_tokens: Default::default(),
557 },
558 )
559 })
560 .collect(),
561 last_workspace_edits_by_language_server: Default::default(),
562 opened_buffers: Default::default(),
563 buffers_being_formatted: Default::default(),
564 buffer_snapshots: Default::default(),
565 nonce: StdRng::from_entropy().gen(),
566 terminals: Terminals {
567 local_handles: Vec::new(),
568 },
569 copilot_enabled: Copilot::global(cx).is_some(),
570 };
571 for worktree in worktrees {
572 let _ = this.add_worktree(&worktree, cx);
573 }
574 this
575 });
576 let subscription = subscription.set_model(&this, &mut cx);
577
578 let user_ids = response
579 .payload
580 .collaborators
581 .iter()
582 .map(|peer| peer.user_id)
583 .collect();
584 user_store
585 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
586 .await?;
587
588 this.update(&mut cx, |this, cx| {
589 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
590 this.client_subscriptions.push(subscription);
591 anyhow::Ok(())
592 })?;
593
594 Ok(this)
595 }
596
597 #[cfg(any(test, feature = "test-support"))]
598 pub async fn test(
599 fs: Arc<dyn Fs>,
600 root_paths: impl IntoIterator<Item = &Path>,
601 cx: &mut gpui::TestAppContext,
602 ) -> ModelHandle<Project> {
603 if !cx.read(|cx| cx.has_global::<Settings>()) {
604 cx.update(|cx| {
605 cx.set_global(Settings::test(cx));
606 });
607 }
608
609 let mut languages = LanguageRegistry::test();
610 languages.set_executor(cx.background());
611 let http_client = util::http::FakeHttpClient::with_404_response();
612 let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
613 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
614 let project =
615 cx.update(|cx| Project::local(client, user_store, Arc::new(languages), fs, cx));
616 for path in root_paths {
617 let (tree, _) = project
618 .update(cx, |project, cx| {
619 project.find_or_create_local_worktree(path, true, cx)
620 })
621 .await
622 .unwrap();
623 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
624 .await;
625 }
626 project
627 }
628
629 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
630 let settings = cx.global::<Settings>();
631
632 let mut language_servers_to_start = Vec::new();
633 for buffer in self.opened_buffers.values() {
634 if let Some(buffer) = buffer.upgrade(cx) {
635 let buffer = buffer.read(cx);
636 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
637 {
638 if settings.enable_language_server(Some(&language.name())) {
639 let worktree = file.worktree.read(cx);
640 language_servers_to_start.push((
641 worktree.id(),
642 worktree.as_local().unwrap().abs_path().clone(),
643 language.clone(),
644 ));
645 }
646 }
647 }
648 }
649
650 let mut language_servers_to_stop = Vec::new();
651 for language in self.languages.to_vec() {
652 for lsp_adapter in language.lsp_adapters() {
653 if !settings.enable_language_server(Some(&language.name())) {
654 let lsp_name = &lsp_adapter.name;
655 for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
656 if lsp_name == started_lsp_name {
657 language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
658 }
659 }
660 }
661 }
662 }
663
664 // Stop all newly-disabled language servers.
665 for (worktree_id, adapter_name) in language_servers_to_stop {
666 self.stop_language_server(worktree_id, adapter_name, cx)
667 .detach();
668 }
669
670 // Start all the newly-enabled language servers.
671 for (worktree_id, worktree_path, language) in language_servers_to_start {
672 self.start_language_servers(worktree_id, worktree_path, language, cx);
673 }
674
675 if !self.copilot_enabled && Copilot::global(cx).is_some() {
676 self.copilot_enabled = true;
677 for buffer in self.opened_buffers.values() {
678 if let Some(buffer) = buffer.upgrade(cx) {
679 self.register_buffer_with_copilot(&buffer, cx);
680 }
681 }
682 }
683
684 cx.notify();
685 }
686
687 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
688 self.opened_buffers
689 .get(&remote_id)
690 .and_then(|buffer| buffer.upgrade(cx))
691 }
692
693 pub fn languages(&self) -> &Arc<LanguageRegistry> {
694 &self.languages
695 }
696
697 pub fn client(&self) -> Arc<Client> {
698 self.client.clone()
699 }
700
701 pub fn user_store(&self) -> ModelHandle<UserStore> {
702 self.user_store.clone()
703 }
704
705 #[cfg(any(test, feature = "test-support"))]
706 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<ModelHandle<Buffer>> {
707 self.opened_buffers
708 .values()
709 .filter_map(|b| b.upgrade(cx))
710 .collect()
711 }
712
713 #[cfg(any(test, feature = "test-support"))]
714 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
715 let path = path.into();
716 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
717 self.opened_buffers.iter().any(|(_, buffer)| {
718 if let Some(buffer) = buffer.upgrade(cx) {
719 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
720 if file.worktree == worktree && file.path() == &path.path {
721 return true;
722 }
723 }
724 }
725 false
726 })
727 } else {
728 false
729 }
730 }
731
732 pub fn fs(&self) -> &Arc<dyn Fs> {
733 &self.fs
734 }
735
736 pub fn remote_id(&self) -> Option<u64> {
737 match self.client_state.as_ref()? {
738 ProjectClientState::Local { remote_id, .. }
739 | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
740 }
741 }
742
743 pub fn replica_id(&self) -> ReplicaId {
744 match &self.client_state {
745 Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
746 _ => 0,
747 }
748 }
749
750 fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
751 if let Some(ProjectClientState::Local { updates_tx, .. }) = &mut self.client_state {
752 updates_tx
753 .unbounded_send(LocalProjectUpdate::WorktreesChanged)
754 .ok();
755 }
756 cx.notify();
757 }
758
759 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
760 &self.collaborators
761 }
762
763 /// Collect all worktrees, including ones that don't appear in the project panel
764 pub fn worktrees<'a>(
765 &'a self,
766 cx: &'a AppContext,
767 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
768 self.worktrees
769 .iter()
770 .filter_map(move |worktree| worktree.upgrade(cx))
771 }
772
773 /// Collect all user-visible worktrees, the ones that appear in the project panel
774 pub fn visible_worktrees<'a>(
775 &'a self,
776 cx: &'a AppContext,
777 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
778 self.worktrees.iter().filter_map(|worktree| {
779 worktree.upgrade(cx).and_then(|worktree| {
780 if worktree.read(cx).is_visible() {
781 Some(worktree)
782 } else {
783 None
784 }
785 })
786 })
787 }
788
789 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
790 self.visible_worktrees(cx)
791 .map(|tree| tree.read(cx).root_name())
792 }
793
794 pub fn worktree_for_id(
795 &self,
796 id: WorktreeId,
797 cx: &AppContext,
798 ) -> Option<ModelHandle<Worktree>> {
799 self.worktrees(cx)
800 .find(|worktree| worktree.read(cx).id() == id)
801 }
802
803 pub fn worktree_for_entry(
804 &self,
805 entry_id: ProjectEntryId,
806 cx: &AppContext,
807 ) -> Option<ModelHandle<Worktree>> {
808 self.worktrees(cx)
809 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
810 }
811
812 pub fn worktree_id_for_entry(
813 &self,
814 entry_id: ProjectEntryId,
815 cx: &AppContext,
816 ) -> Option<WorktreeId> {
817 self.worktree_for_entry(entry_id, cx)
818 .map(|worktree| worktree.read(cx).id())
819 }
820
821 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
822 paths.iter().all(|path| self.contains_path(path, cx))
823 }
824
825 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
826 for worktree in self.worktrees(cx) {
827 let worktree = worktree.read(cx).as_local();
828 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
829 return true;
830 }
831 }
832 false
833 }
834
835 pub fn create_entry(
836 &mut self,
837 project_path: impl Into<ProjectPath>,
838 is_directory: bool,
839 cx: &mut ModelContext<Self>,
840 ) -> Option<Task<Result<Entry>>> {
841 let project_path = project_path.into();
842 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
843 if self.is_local() {
844 Some(worktree.update(cx, |worktree, cx| {
845 worktree
846 .as_local_mut()
847 .unwrap()
848 .create_entry(project_path.path, is_directory, cx)
849 }))
850 } else {
851 let client = self.client.clone();
852 let project_id = self.remote_id().unwrap();
853 Some(cx.spawn_weak(|_, mut cx| async move {
854 let response = client
855 .request(proto::CreateProjectEntry {
856 worktree_id: project_path.worktree_id.to_proto(),
857 project_id,
858 path: project_path.path.to_string_lossy().into(),
859 is_directory,
860 })
861 .await?;
862 let entry = response
863 .entry
864 .ok_or_else(|| anyhow!("missing entry in response"))?;
865 worktree
866 .update(&mut cx, |worktree, cx| {
867 worktree.as_remote_mut().unwrap().insert_entry(
868 entry,
869 response.worktree_scan_id as usize,
870 cx,
871 )
872 })
873 .await
874 }))
875 }
876 }
877
878 pub fn copy_entry(
879 &mut self,
880 entry_id: ProjectEntryId,
881 new_path: impl Into<Arc<Path>>,
882 cx: &mut ModelContext<Self>,
883 ) -> Option<Task<Result<Entry>>> {
884 let worktree = self.worktree_for_entry(entry_id, cx)?;
885 let new_path = new_path.into();
886 if self.is_local() {
887 worktree.update(cx, |worktree, cx| {
888 worktree
889 .as_local_mut()
890 .unwrap()
891 .copy_entry(entry_id, new_path, cx)
892 })
893 } else {
894 let client = self.client.clone();
895 let project_id = self.remote_id().unwrap();
896
897 Some(cx.spawn_weak(|_, mut cx| async move {
898 let response = client
899 .request(proto::CopyProjectEntry {
900 project_id,
901 entry_id: entry_id.to_proto(),
902 new_path: new_path.to_string_lossy().into(),
903 })
904 .await?;
905 let entry = response
906 .entry
907 .ok_or_else(|| anyhow!("missing entry in response"))?;
908 worktree
909 .update(&mut cx, |worktree, cx| {
910 worktree.as_remote_mut().unwrap().insert_entry(
911 entry,
912 response.worktree_scan_id as usize,
913 cx,
914 )
915 })
916 .await
917 }))
918 }
919 }
920
921 pub fn rename_entry(
922 &mut self,
923 entry_id: ProjectEntryId,
924 new_path: impl Into<Arc<Path>>,
925 cx: &mut ModelContext<Self>,
926 ) -> Option<Task<Result<Entry>>> {
927 let worktree = self.worktree_for_entry(entry_id, cx)?;
928 let new_path = new_path.into();
929 if self.is_local() {
930 worktree.update(cx, |worktree, cx| {
931 worktree
932 .as_local_mut()
933 .unwrap()
934 .rename_entry(entry_id, new_path, cx)
935 })
936 } else {
937 let client = self.client.clone();
938 let project_id = self.remote_id().unwrap();
939
940 Some(cx.spawn_weak(|_, mut cx| async move {
941 let response = client
942 .request(proto::RenameProjectEntry {
943 project_id,
944 entry_id: entry_id.to_proto(),
945 new_path: new_path.to_string_lossy().into(),
946 })
947 .await?;
948 let entry = response
949 .entry
950 .ok_or_else(|| anyhow!("missing entry in response"))?;
951 worktree
952 .update(&mut cx, |worktree, cx| {
953 worktree.as_remote_mut().unwrap().insert_entry(
954 entry,
955 response.worktree_scan_id as usize,
956 cx,
957 )
958 })
959 .await
960 }))
961 }
962 }
963
964 pub fn delete_entry(
965 &mut self,
966 entry_id: ProjectEntryId,
967 cx: &mut ModelContext<Self>,
968 ) -> Option<Task<Result<()>>> {
969 let worktree = self.worktree_for_entry(entry_id, cx)?;
970 if self.is_local() {
971 worktree.update(cx, |worktree, cx| {
972 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
973 })
974 } else {
975 let client = self.client.clone();
976 let project_id = self.remote_id().unwrap();
977 Some(cx.spawn_weak(|_, mut cx| async move {
978 let response = client
979 .request(proto::DeleteProjectEntry {
980 project_id,
981 entry_id: entry_id.to_proto(),
982 })
983 .await?;
984 worktree
985 .update(&mut cx, move |worktree, cx| {
986 worktree.as_remote_mut().unwrap().delete_entry(
987 entry_id,
988 response.worktree_scan_id as usize,
989 cx,
990 )
991 })
992 .await
993 }))
994 }
995 }
996
997 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
998 if self.client_state.is_some() {
999 return Err(anyhow!("project was already shared"));
1000 }
1001 self.client_subscriptions.push(
1002 self.client
1003 .subscribe_to_entity(project_id)?
1004 .set_model(&cx.handle(), &mut cx.to_async()),
1005 );
1006
1007 for open_buffer in self.opened_buffers.values_mut() {
1008 match open_buffer {
1009 OpenBuffer::Strong(_) => {}
1010 OpenBuffer::Weak(buffer) => {
1011 if let Some(buffer) = buffer.upgrade(cx) {
1012 *open_buffer = OpenBuffer::Strong(buffer);
1013 }
1014 }
1015 OpenBuffer::Operations(_) => unreachable!(),
1016 }
1017 }
1018
1019 for worktree_handle in self.worktrees.iter_mut() {
1020 match worktree_handle {
1021 WorktreeHandle::Strong(_) => {}
1022 WorktreeHandle::Weak(worktree) => {
1023 if let Some(worktree) = worktree.upgrade(cx) {
1024 *worktree_handle = WorktreeHandle::Strong(worktree);
1025 }
1026 }
1027 }
1028 }
1029
1030 for (server_id, status) in &self.language_server_statuses {
1031 self.client
1032 .send(proto::StartLanguageServer {
1033 project_id,
1034 server: Some(proto::LanguageServer {
1035 id: server_id.0 as u64,
1036 name: status.name.clone(),
1037 }),
1038 })
1039 .log_err();
1040 }
1041
1042 let (updates_tx, mut updates_rx) = mpsc::unbounded();
1043 let client = self.client.clone();
1044 self.client_state = Some(ProjectClientState::Local {
1045 remote_id: project_id,
1046 updates_tx,
1047 _send_updates: cx.spawn_weak(move |this, mut cx| async move {
1048 while let Some(update) = updates_rx.next().await {
1049 let Some(this) = this.upgrade(&cx) else { break };
1050
1051 match update {
1052 LocalProjectUpdate::WorktreesChanged => {
1053 let worktrees = this
1054 .read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1055 let update_project = this
1056 .read_with(&cx, |this, cx| {
1057 this.client.request(proto::UpdateProject {
1058 project_id,
1059 worktrees: this.worktree_metadata_protos(cx),
1060 })
1061 })
1062 .await;
1063 if update_project.is_ok() {
1064 for worktree in worktrees {
1065 worktree.update(&mut cx, |worktree, cx| {
1066 let worktree = worktree.as_local_mut().unwrap();
1067 worktree.share(project_id, cx).detach_and_log_err(cx)
1068 });
1069 }
1070 }
1071 }
1072 LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1073 let buffer = this.update(&mut cx, |this, _| {
1074 let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1075 let shared_buffers =
1076 this.shared_buffers.entry(peer_id).or_default();
1077 if shared_buffers.insert(buffer_id) {
1078 if let OpenBuffer::Strong(buffer) = buffer {
1079 Some(buffer.clone())
1080 } else {
1081 None
1082 }
1083 } else {
1084 None
1085 }
1086 });
1087
1088 let Some(buffer) = buffer else { continue };
1089 let operations =
1090 buffer.read_with(&cx, |b, cx| b.serialize_ops(None, cx));
1091 let operations = operations.await;
1092 let state = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
1093
1094 let initial_state = proto::CreateBufferForPeer {
1095 project_id,
1096 peer_id: Some(peer_id),
1097 variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1098 };
1099 if client.send(initial_state).log_err().is_some() {
1100 let client = client.clone();
1101 cx.background()
1102 .spawn(async move {
1103 let mut chunks = split_operations(operations).peekable();
1104 while let Some(chunk) = chunks.next() {
1105 let is_last = chunks.peek().is_none();
1106 client.send(proto::CreateBufferForPeer {
1107 project_id,
1108 peer_id: Some(peer_id),
1109 variant: Some(
1110 proto::create_buffer_for_peer::Variant::Chunk(
1111 proto::BufferChunk {
1112 buffer_id,
1113 operations: chunk,
1114 is_last,
1115 },
1116 ),
1117 ),
1118 })?;
1119 }
1120 anyhow::Ok(())
1121 })
1122 .await
1123 .log_err();
1124 }
1125 }
1126 }
1127 }
1128 }),
1129 });
1130
1131 self.metadata_changed(cx);
1132 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1133 cx.notify();
1134 Ok(())
1135 }
1136
1137 pub fn reshared(
1138 &mut self,
1139 message: proto::ResharedProject,
1140 cx: &mut ModelContext<Self>,
1141 ) -> Result<()> {
1142 self.shared_buffers.clear();
1143 self.set_collaborators_from_proto(message.collaborators, cx)?;
1144 self.metadata_changed(cx);
1145 Ok(())
1146 }
1147
1148 pub fn rejoined(
1149 &mut self,
1150 message: proto::RejoinedProject,
1151 message_id: u32,
1152 cx: &mut ModelContext<Self>,
1153 ) -> Result<()> {
1154 self.join_project_response_message_id = message_id;
1155 self.set_worktrees_from_proto(message.worktrees, cx)?;
1156 self.set_collaborators_from_proto(message.collaborators, cx)?;
1157 self.language_server_statuses = message
1158 .language_servers
1159 .into_iter()
1160 .map(|server| {
1161 (
1162 LanguageServerId(server.id as usize),
1163 LanguageServerStatus {
1164 name: server.name,
1165 pending_work: Default::default(),
1166 has_pending_diagnostic_updates: false,
1167 progress_tokens: Default::default(),
1168 },
1169 )
1170 })
1171 .collect();
1172 self.buffer_ordered_messages_tx
1173 .unbounded_send(BufferOrderedMessage::Resync)
1174 .unwrap();
1175 cx.notify();
1176 Ok(())
1177 }
1178
1179 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1180 self.unshare_internal(cx)?;
1181 self.metadata_changed(cx);
1182 cx.notify();
1183 Ok(())
1184 }
1185
1186 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1187 if self.is_remote() {
1188 return Err(anyhow!("attempted to unshare a remote project"));
1189 }
1190
1191 if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1192 self.collaborators.clear();
1193 self.shared_buffers.clear();
1194 self.client_subscriptions.clear();
1195
1196 for worktree_handle in self.worktrees.iter_mut() {
1197 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1198 let is_visible = worktree.update(cx, |worktree, _| {
1199 worktree.as_local_mut().unwrap().unshare();
1200 worktree.is_visible()
1201 });
1202 if !is_visible {
1203 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1204 }
1205 }
1206 }
1207
1208 for open_buffer in self.opened_buffers.values_mut() {
1209 // Wake up any tasks waiting for peers' edits to this buffer.
1210 if let Some(buffer) = open_buffer.upgrade(cx) {
1211 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1212 }
1213
1214 if let OpenBuffer::Strong(buffer) = open_buffer {
1215 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1216 }
1217 }
1218
1219 self.client.send(proto::UnshareProject {
1220 project_id: remote_id,
1221 })?;
1222
1223 Ok(())
1224 } else {
1225 Err(anyhow!("attempted to unshare an unshared project"))
1226 }
1227 }
1228
1229 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1230 self.disconnected_from_host_internal(cx);
1231 cx.emit(Event::DisconnectedFromHost);
1232 cx.notify();
1233 }
1234
1235 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1236 if let Some(ProjectClientState::Remote {
1237 sharing_has_stopped,
1238 ..
1239 }) = &mut self.client_state
1240 {
1241 *sharing_has_stopped = true;
1242
1243 self.collaborators.clear();
1244
1245 for worktree in &self.worktrees {
1246 if let Some(worktree) = worktree.upgrade(cx) {
1247 worktree.update(cx, |worktree, _| {
1248 if let Some(worktree) = worktree.as_remote_mut() {
1249 worktree.disconnected_from_host();
1250 }
1251 });
1252 }
1253 }
1254
1255 for open_buffer in self.opened_buffers.values_mut() {
1256 // Wake up any tasks waiting for peers' edits to this buffer.
1257 if let Some(buffer) = open_buffer.upgrade(cx) {
1258 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1259 }
1260
1261 if let OpenBuffer::Strong(buffer) = open_buffer {
1262 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1263 }
1264 }
1265
1266 // Wake up all futures currently waiting on a buffer to get opened,
1267 // to give them a chance to fail now that we've disconnected.
1268 *self.opened_buffer.0.borrow_mut() = ();
1269 }
1270 }
1271
1272 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1273 cx.emit(Event::Closed);
1274 }
1275
1276 pub fn is_read_only(&self) -> bool {
1277 match &self.client_state {
1278 Some(ProjectClientState::Remote {
1279 sharing_has_stopped,
1280 ..
1281 }) => *sharing_has_stopped,
1282 _ => false,
1283 }
1284 }
1285
1286 pub fn is_local(&self) -> bool {
1287 match &self.client_state {
1288 Some(ProjectClientState::Remote { .. }) => false,
1289 _ => true,
1290 }
1291 }
1292
1293 pub fn is_remote(&self) -> bool {
1294 !self.is_local()
1295 }
1296
1297 pub fn create_buffer(
1298 &mut self,
1299 text: &str,
1300 language: Option<Arc<Language>>,
1301 cx: &mut ModelContext<Self>,
1302 ) -> Result<ModelHandle<Buffer>> {
1303 if self.is_remote() {
1304 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1305 }
1306
1307 let buffer = cx.add_model(|cx| {
1308 Buffer::new(self.replica_id(), text, cx)
1309 .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1310 });
1311 self.register_buffer(&buffer, cx)?;
1312 Ok(buffer)
1313 }
1314
1315 pub fn open_path(
1316 &mut self,
1317 path: impl Into<ProjectPath>,
1318 cx: &mut ModelContext<Self>,
1319 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1320 let task = self.open_buffer(path, cx);
1321 cx.spawn_weak(|_, cx| async move {
1322 let buffer = task.await?;
1323 let project_entry_id = buffer
1324 .read_with(&cx, |buffer, cx| {
1325 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1326 })
1327 .ok_or_else(|| anyhow!("no project entry"))?;
1328
1329 let buffer: &AnyModelHandle = &buffer;
1330 Ok((project_entry_id, buffer.clone()))
1331 })
1332 }
1333
1334 pub fn open_local_buffer(
1335 &mut self,
1336 abs_path: impl AsRef<Path>,
1337 cx: &mut ModelContext<Self>,
1338 ) -> Task<Result<ModelHandle<Buffer>>> {
1339 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1340 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1341 } else {
1342 Task::ready(Err(anyhow!("no such path")))
1343 }
1344 }
1345
1346 pub fn open_buffer(
1347 &mut self,
1348 path: impl Into<ProjectPath>,
1349 cx: &mut ModelContext<Self>,
1350 ) -> Task<Result<ModelHandle<Buffer>>> {
1351 let project_path = path.into();
1352 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1353 worktree
1354 } else {
1355 return Task::ready(Err(anyhow!("no such worktree")));
1356 };
1357
1358 // If there is already a buffer for the given path, then return it.
1359 let existing_buffer = self.get_open_buffer(&project_path, cx);
1360 if let Some(existing_buffer) = existing_buffer {
1361 return Task::ready(Ok(existing_buffer));
1362 }
1363
1364 let mut loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1365 // If the given path is already being loaded, then wait for that existing
1366 // task to complete and return the same buffer.
1367 hash_map::Entry::Occupied(e) => e.get().clone(),
1368
1369 // Otherwise, record the fact that this path is now being loaded.
1370 hash_map::Entry::Vacant(entry) => {
1371 let (mut tx, rx) = postage::watch::channel();
1372 entry.insert(rx.clone());
1373
1374 let load_buffer = if worktree.read(cx).is_local() {
1375 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1376 } else {
1377 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1378 };
1379
1380 cx.spawn(move |this, mut cx| async move {
1381 let load_result = load_buffer.await;
1382 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1383 // Record the fact that the buffer is no longer loading.
1384 this.loading_buffers_by_path.remove(&project_path);
1385 let buffer = load_result.map_err(Arc::new)?;
1386 Ok(buffer)
1387 }));
1388 })
1389 .detach();
1390 rx
1391 }
1392 };
1393
1394 cx.foreground().spawn(async move {
1395 loop {
1396 if let Some(result) = loading_watch.borrow().as_ref() {
1397 match result {
1398 Ok(buffer) => return Ok(buffer.clone()),
1399 Err(error) => return Err(anyhow!("{}", error)),
1400 }
1401 }
1402 loading_watch.next().await;
1403 }
1404 })
1405 }
1406
1407 fn open_local_buffer_internal(
1408 &mut self,
1409 path: &Arc<Path>,
1410 worktree: &ModelHandle<Worktree>,
1411 cx: &mut ModelContext<Self>,
1412 ) -> Task<Result<ModelHandle<Buffer>>> {
1413 let buffer_id = post_inc(&mut self.next_buffer_id);
1414 let load_buffer = worktree.update(cx, |worktree, cx| {
1415 let worktree = worktree.as_local_mut().unwrap();
1416 worktree.load_buffer(buffer_id, path, cx)
1417 });
1418 cx.spawn(|this, mut cx| async move {
1419 let buffer = load_buffer.await?;
1420 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1421 Ok(buffer)
1422 })
1423 }
1424
1425 fn open_remote_buffer_internal(
1426 &mut self,
1427 path: &Arc<Path>,
1428 worktree: &ModelHandle<Worktree>,
1429 cx: &mut ModelContext<Self>,
1430 ) -> Task<Result<ModelHandle<Buffer>>> {
1431 let rpc = self.client.clone();
1432 let project_id = self.remote_id().unwrap();
1433 let remote_worktree_id = worktree.read(cx).id();
1434 let path = path.clone();
1435 let path_string = path.to_string_lossy().to_string();
1436 cx.spawn(|this, mut cx| async move {
1437 let response = rpc
1438 .request(proto::OpenBufferByPath {
1439 project_id,
1440 worktree_id: remote_worktree_id.to_proto(),
1441 path: path_string,
1442 })
1443 .await?;
1444 this.update(&mut cx, |this, cx| {
1445 this.wait_for_remote_buffer(response.buffer_id, cx)
1446 })
1447 .await
1448 })
1449 }
1450
1451 /// LanguageServerName is owned, because it is inserted into a map
1452 fn open_local_buffer_via_lsp(
1453 &mut self,
1454 abs_path: lsp::Url,
1455 language_server_id: LanguageServerId,
1456 language_server_name: LanguageServerName,
1457 cx: &mut ModelContext<Self>,
1458 ) -> Task<Result<ModelHandle<Buffer>>> {
1459 cx.spawn(|this, mut cx| async move {
1460 let abs_path = abs_path
1461 .to_file_path()
1462 .map_err(|_| anyhow!("can't convert URI to path"))?;
1463 let (worktree, relative_path) = if let Some(result) =
1464 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1465 {
1466 result
1467 } else {
1468 let worktree = this
1469 .update(&mut cx, |this, cx| {
1470 this.create_local_worktree(&abs_path, false, cx)
1471 })
1472 .await?;
1473 this.update(&mut cx, |this, cx| {
1474 this.language_server_ids.insert(
1475 (worktree.read(cx).id(), language_server_name),
1476 language_server_id,
1477 );
1478 });
1479 (worktree, PathBuf::new())
1480 };
1481
1482 let project_path = ProjectPath {
1483 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1484 path: relative_path.into(),
1485 };
1486 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1487 .await
1488 })
1489 }
1490
1491 pub fn open_buffer_by_id(
1492 &mut self,
1493 id: u64,
1494 cx: &mut ModelContext<Self>,
1495 ) -> Task<Result<ModelHandle<Buffer>>> {
1496 if let Some(buffer) = self.buffer_for_id(id, cx) {
1497 Task::ready(Ok(buffer))
1498 } else if self.is_local() {
1499 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1500 } else if let Some(project_id) = self.remote_id() {
1501 let request = self
1502 .client
1503 .request(proto::OpenBufferById { project_id, id });
1504 cx.spawn(|this, mut cx| async move {
1505 let buffer_id = request.await?.buffer_id;
1506 this.update(&mut cx, |this, cx| {
1507 this.wait_for_remote_buffer(buffer_id, cx)
1508 })
1509 .await
1510 })
1511 } else {
1512 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1513 }
1514 }
1515
1516 pub fn save_buffers(
1517 &self,
1518 buffers: HashSet<ModelHandle<Buffer>>,
1519 cx: &mut ModelContext<Self>,
1520 ) -> Task<Result<()>> {
1521 cx.spawn(|this, mut cx| async move {
1522 let save_tasks = buffers
1523 .into_iter()
1524 .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1525 try_join_all(save_tasks).await?;
1526 Ok(())
1527 })
1528 }
1529
1530 pub fn save_buffer(
1531 &self,
1532 buffer: ModelHandle<Buffer>,
1533 cx: &mut ModelContext<Self>,
1534 ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1535 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1536 return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1537 };
1538 let worktree = file.worktree.clone();
1539 let path = file.path.clone();
1540 worktree.update(cx, |worktree, cx| match worktree {
1541 Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1542 Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1543 })
1544 }
1545
1546 pub fn save_buffer_as(
1547 &mut self,
1548 buffer: ModelHandle<Buffer>,
1549 abs_path: PathBuf,
1550 cx: &mut ModelContext<Self>,
1551 ) -> Task<Result<()>> {
1552 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1553 let old_file = File::from_dyn(buffer.read(cx).file())
1554 .filter(|f| f.is_local())
1555 .cloned();
1556 cx.spawn(|this, mut cx| async move {
1557 if let Some(old_file) = &old_file {
1558 this.update(&mut cx, |this, cx| {
1559 this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1560 });
1561 }
1562 let (worktree, path) = worktree_task.await?;
1563 worktree
1564 .update(&mut cx, |worktree, cx| match worktree {
1565 Worktree::Local(worktree) => {
1566 worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1567 }
1568 Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1569 })
1570 .await?;
1571 this.update(&mut cx, |this, cx| {
1572 this.detect_language_for_buffer(&buffer, cx);
1573 this.register_buffer_with_language_servers(&buffer, cx);
1574 });
1575 Ok(())
1576 })
1577 }
1578
1579 pub fn get_open_buffer(
1580 &mut self,
1581 path: &ProjectPath,
1582 cx: &mut ModelContext<Self>,
1583 ) -> Option<ModelHandle<Buffer>> {
1584 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1585 self.opened_buffers.values().find_map(|buffer| {
1586 let buffer = buffer.upgrade(cx)?;
1587 let file = File::from_dyn(buffer.read(cx).file())?;
1588 if file.worktree == worktree && file.path() == &path.path {
1589 Some(buffer)
1590 } else {
1591 None
1592 }
1593 })
1594 }
1595
1596 fn register_buffer(
1597 &mut self,
1598 buffer: &ModelHandle<Buffer>,
1599 cx: &mut ModelContext<Self>,
1600 ) -> Result<()> {
1601 buffer.update(cx, |buffer, _| {
1602 buffer.set_language_registry(self.languages.clone())
1603 });
1604
1605 let remote_id = buffer.read(cx).remote_id();
1606 let is_remote = self.is_remote();
1607 let open_buffer = if is_remote || self.is_shared() {
1608 OpenBuffer::Strong(buffer.clone())
1609 } else {
1610 OpenBuffer::Weak(buffer.downgrade())
1611 };
1612
1613 match self.opened_buffers.entry(remote_id) {
1614 hash_map::Entry::Vacant(entry) => {
1615 entry.insert(open_buffer);
1616 }
1617 hash_map::Entry::Occupied(mut entry) => {
1618 if let OpenBuffer::Operations(operations) = entry.get_mut() {
1619 buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
1620 } else if entry.get().upgrade(cx).is_some() {
1621 if is_remote {
1622 return Ok(());
1623 } else {
1624 debug_panic!("buffer {} was already registered", remote_id);
1625 Err(anyhow!("buffer {} was already registered", remote_id))?;
1626 }
1627 }
1628 entry.insert(open_buffer);
1629 }
1630 }
1631 cx.subscribe(buffer, |this, buffer, event, cx| {
1632 this.on_buffer_event(buffer, event, cx);
1633 })
1634 .detach();
1635
1636 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1637 if file.is_local {
1638 self.local_buffer_ids_by_path.insert(
1639 ProjectPath {
1640 worktree_id: file.worktree_id(cx),
1641 path: file.path.clone(),
1642 },
1643 remote_id,
1644 );
1645
1646 self.local_buffer_ids_by_entry_id
1647 .insert(file.entry_id, remote_id);
1648 }
1649 }
1650
1651 self.detect_language_for_buffer(buffer, cx);
1652 self.register_buffer_with_language_servers(buffer, cx);
1653 self.register_buffer_with_copilot(buffer, cx);
1654 cx.observe_release(buffer, |this, buffer, cx| {
1655 if let Some(file) = File::from_dyn(buffer.file()) {
1656 if file.is_local() {
1657 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1658 for server in this.language_servers_for_buffer(buffer, cx) {
1659 server
1660 .1
1661 .notify::<lsp::notification::DidCloseTextDocument>(
1662 lsp::DidCloseTextDocumentParams {
1663 text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1664 },
1665 )
1666 .log_err();
1667 }
1668 }
1669 }
1670 })
1671 .detach();
1672
1673 *self.opened_buffer.0.borrow_mut() = ();
1674 Ok(())
1675 }
1676
1677 fn register_buffer_with_language_servers(
1678 &mut self,
1679 buffer_handle: &ModelHandle<Buffer>,
1680 cx: &mut ModelContext<Self>,
1681 ) {
1682 let buffer = buffer_handle.read(cx);
1683 let buffer_id = buffer.remote_id();
1684
1685 if let Some(file) = File::from_dyn(buffer.file()) {
1686 if !file.is_local() {
1687 return;
1688 }
1689
1690 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1691 let initial_snapshot = buffer.text_snapshot();
1692 let language = buffer.language().cloned();
1693 let worktree_id = file.worktree_id(cx);
1694
1695 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1696 for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
1697 self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
1698 .log_err();
1699 }
1700 }
1701
1702 if let Some(language) = language {
1703 for adapter in language.lsp_adapters() {
1704 let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1705 let server = self
1706 .language_server_ids
1707 .get(&(worktree_id, adapter.name.clone()))
1708 .and_then(|id| self.language_servers.get(id))
1709 .and_then(|server_state| {
1710 if let LanguageServerState::Running { server, .. } = server_state {
1711 Some(server.clone())
1712 } else {
1713 None
1714 }
1715 });
1716 let server = match server {
1717 Some(server) => server,
1718 None => continue,
1719 };
1720
1721 server
1722 .notify::<lsp::notification::DidOpenTextDocument>(
1723 lsp::DidOpenTextDocumentParams {
1724 text_document: lsp::TextDocumentItem::new(
1725 uri.clone(),
1726 language_id.unwrap_or_default(),
1727 0,
1728 initial_snapshot.text(),
1729 ),
1730 },
1731 )
1732 .log_err();
1733
1734 buffer_handle.update(cx, |buffer, cx| {
1735 buffer.set_completion_triggers(
1736 server
1737 .capabilities()
1738 .completion_provider
1739 .as_ref()
1740 .and_then(|provider| provider.trigger_characters.clone())
1741 .unwrap_or_default(),
1742 cx,
1743 );
1744 });
1745
1746 let snapshot = LspBufferSnapshot {
1747 version: 0,
1748 snapshot: initial_snapshot.clone(),
1749 };
1750 self.buffer_snapshots
1751 .entry(buffer_id)
1752 .or_default()
1753 .insert(server.server_id(), vec![snapshot]);
1754 }
1755 }
1756 }
1757 }
1758
1759 fn unregister_buffer_from_language_servers(
1760 &mut self,
1761 buffer: &ModelHandle<Buffer>,
1762 old_file: &File,
1763 cx: &mut ModelContext<Self>,
1764 ) {
1765 let old_path = match old_file.as_local() {
1766 Some(local) => local.abs_path(cx),
1767 None => return,
1768 };
1769
1770 buffer.update(cx, |buffer, cx| {
1771 let worktree_id = old_file.worktree_id(cx);
1772 let ids = &self.language_server_ids;
1773
1774 let language = buffer.language().cloned();
1775 let adapters = language.iter().flat_map(|language| language.lsp_adapters());
1776 for &server_id in adapters.flat_map(|a| ids.get(&(worktree_id, a.name.clone()))) {
1777 buffer.update_diagnostics(server_id, Default::default(), cx);
1778 }
1779
1780 self.buffer_snapshots.remove(&buffer.remote_id());
1781 let file_url = lsp::Url::from_file_path(old_path).unwrap();
1782 for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
1783 language_server
1784 .notify::<lsp::notification::DidCloseTextDocument>(
1785 lsp::DidCloseTextDocumentParams {
1786 text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
1787 },
1788 )
1789 .log_err();
1790 }
1791 });
1792 }
1793
1794 fn register_buffer_with_copilot(
1795 &self,
1796 buffer_handle: &ModelHandle<Buffer>,
1797 cx: &mut ModelContext<Self>,
1798 ) {
1799 if let Some(copilot) = Copilot::global(cx) {
1800 copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
1801 }
1802 }
1803
1804 async fn send_buffer_ordered_messages(
1805 this: WeakModelHandle<Self>,
1806 rx: UnboundedReceiver<BufferOrderedMessage>,
1807 mut cx: AsyncAppContext,
1808 ) -> Option<()> {
1809 const MAX_BATCH_SIZE: usize = 128;
1810
1811 let mut operations_by_buffer_id = HashMap::default();
1812 async fn flush_operations(
1813 this: &ModelHandle<Project>,
1814 operations_by_buffer_id: &mut HashMap<u64, Vec<proto::Operation>>,
1815 needs_resync_with_host: &mut bool,
1816 is_local: bool,
1817 cx: &AsyncAppContext,
1818 ) {
1819 for (buffer_id, operations) in operations_by_buffer_id.drain() {
1820 let request = this.read_with(cx, |this, _| {
1821 let project_id = this.remote_id()?;
1822 Some(this.client.request(proto::UpdateBuffer {
1823 buffer_id,
1824 project_id,
1825 operations,
1826 }))
1827 });
1828 if let Some(request) = request {
1829 if request.await.is_err() && !is_local {
1830 *needs_resync_with_host = true;
1831 break;
1832 }
1833 }
1834 }
1835 }
1836
1837 let mut needs_resync_with_host = false;
1838 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1839
1840 while let Some(changes) = changes.next().await {
1841 let this = this.upgrade(&mut cx)?;
1842 let is_local = this.read_with(&cx, |this, _| this.is_local());
1843
1844 for change in changes {
1845 match change {
1846 BufferOrderedMessage::Operation {
1847 buffer_id,
1848 operation,
1849 } => {
1850 if needs_resync_with_host {
1851 continue;
1852 }
1853
1854 operations_by_buffer_id
1855 .entry(buffer_id)
1856 .or_insert(Vec::new())
1857 .push(operation);
1858 }
1859
1860 BufferOrderedMessage::Resync => {
1861 operations_by_buffer_id.clear();
1862 if this
1863 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))
1864 .await
1865 .is_ok()
1866 {
1867 needs_resync_with_host = false;
1868 }
1869 }
1870
1871 BufferOrderedMessage::LanguageServerUpdate {
1872 language_server_id,
1873 message,
1874 } => {
1875 flush_operations(
1876 &this,
1877 &mut operations_by_buffer_id,
1878 &mut needs_resync_with_host,
1879 is_local,
1880 &cx,
1881 )
1882 .await;
1883
1884 this.read_with(&cx, |this, _| {
1885 if let Some(project_id) = this.remote_id() {
1886 this.client
1887 .send(proto::UpdateLanguageServer {
1888 project_id,
1889 language_server_id: language_server_id.0 as u64,
1890 variant: Some(message),
1891 })
1892 .log_err();
1893 }
1894 });
1895 }
1896 }
1897 }
1898
1899 flush_operations(
1900 &this,
1901 &mut operations_by_buffer_id,
1902 &mut needs_resync_with_host,
1903 is_local,
1904 &cx,
1905 )
1906 .await;
1907 }
1908
1909 None
1910 }
1911
1912 fn on_buffer_event(
1913 &mut self,
1914 buffer: ModelHandle<Buffer>,
1915 event: &BufferEvent,
1916 cx: &mut ModelContext<Self>,
1917 ) -> Option<()> {
1918 match event {
1919 BufferEvent::Operation(operation) => {
1920 self.buffer_ordered_messages_tx
1921 .unbounded_send(BufferOrderedMessage::Operation {
1922 buffer_id: buffer.read(cx).remote_id(),
1923 operation: language::proto::serialize_operation(operation),
1924 })
1925 .ok();
1926 }
1927
1928 BufferEvent::Edited { .. } => {
1929 let buffer = buffer.read(cx);
1930 let file = File::from_dyn(buffer.file())?;
1931 let abs_path = file.as_local()?.abs_path(cx);
1932 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1933 let next_snapshot = buffer.text_snapshot();
1934
1935 let language_servers: Vec<_> = self
1936 .language_servers_for_buffer(buffer, cx)
1937 .map(|i| i.1.clone())
1938 .collect();
1939
1940 for language_server in language_servers {
1941 let language_server = language_server.clone();
1942
1943 let buffer_snapshots = self
1944 .buffer_snapshots
1945 .get_mut(&buffer.remote_id())
1946 .and_then(|m| m.get_mut(&language_server.server_id()))?;
1947 let previous_snapshot = buffer_snapshots.last()?;
1948 let next_version = previous_snapshot.version + 1;
1949
1950 let content_changes = buffer
1951 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
1952 .map(|edit| {
1953 let edit_start = edit.new.start.0;
1954 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1955 let new_text = next_snapshot
1956 .text_for_range(edit.new.start.1..edit.new.end.1)
1957 .collect();
1958 lsp::TextDocumentContentChangeEvent {
1959 range: Some(lsp::Range::new(
1960 point_to_lsp(edit_start),
1961 point_to_lsp(edit_end),
1962 )),
1963 range_length: None,
1964 text: new_text,
1965 }
1966 })
1967 .collect();
1968
1969 buffer_snapshots.push(LspBufferSnapshot {
1970 version: next_version,
1971 snapshot: next_snapshot.clone(),
1972 });
1973
1974 language_server
1975 .notify::<lsp::notification::DidChangeTextDocument>(
1976 lsp::DidChangeTextDocumentParams {
1977 text_document: lsp::VersionedTextDocumentIdentifier::new(
1978 uri.clone(),
1979 next_version,
1980 ),
1981 content_changes,
1982 },
1983 )
1984 .log_err();
1985 }
1986 }
1987
1988 BufferEvent::Saved => {
1989 let file = File::from_dyn(buffer.read(cx).file())?;
1990 let worktree_id = file.worktree_id(cx);
1991 let abs_path = file.as_local()?.abs_path(cx);
1992 let text_document = lsp::TextDocumentIdentifier {
1993 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1994 };
1995
1996 for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1997 server
1998 .notify::<lsp::notification::DidSaveTextDocument>(
1999 lsp::DidSaveTextDocumentParams {
2000 text_document: text_document.clone(),
2001 text: None,
2002 },
2003 )
2004 .log_err();
2005 }
2006
2007 let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2008 for language_server_id in language_server_ids {
2009 if let Some(LanguageServerState::Running {
2010 adapter,
2011 simulate_disk_based_diagnostics_completion,
2012 ..
2013 }) = self.language_servers.get_mut(&language_server_id)
2014 {
2015 // After saving a buffer using a language server that doesn't provide
2016 // a disk-based progress token, kick off a timer that will reset every
2017 // time the buffer is saved. If the timer eventually fires, simulate
2018 // disk-based diagnostics being finished so that other pieces of UI
2019 // (e.g., project diagnostics view, diagnostic status bar) can update.
2020 // We don't emit an event right away because the language server might take
2021 // some time to publish diagnostics.
2022 if adapter.disk_based_diagnostics_progress_token.is_none() {
2023 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2024 Duration::from_secs(1);
2025
2026 let task = cx.spawn_weak(|this, mut cx| async move {
2027 cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2028 if let Some(this) = this.upgrade(&cx) {
2029 this.update(&mut cx, |this, cx| {
2030 this.disk_based_diagnostics_finished(
2031 language_server_id,
2032 cx,
2033 );
2034 this.buffer_ordered_messages_tx
2035 .unbounded_send(
2036 BufferOrderedMessage::LanguageServerUpdate {
2037 language_server_id,
2038 message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2039 },
2040 )
2041 .ok();
2042 });
2043 }
2044 });
2045 *simulate_disk_based_diagnostics_completion = Some(task);
2046 }
2047 }
2048 }
2049 }
2050
2051 _ => {}
2052 }
2053
2054 None
2055 }
2056
2057 fn language_servers_for_worktree(
2058 &self,
2059 worktree_id: WorktreeId,
2060 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2061 self.language_server_ids
2062 .iter()
2063 .filter_map(move |((language_server_worktree_id, _), id)| {
2064 if *language_server_worktree_id == worktree_id {
2065 if let Some(LanguageServerState::Running {
2066 adapter,
2067 language,
2068 server,
2069 ..
2070 }) = self.language_servers.get(id)
2071 {
2072 return Some((adapter, language, server));
2073 }
2074 }
2075 None
2076 })
2077 }
2078
2079 fn maintain_buffer_languages(
2080 languages: &LanguageRegistry,
2081 cx: &mut ModelContext<Project>,
2082 ) -> Task<()> {
2083 let mut subscription = languages.subscribe();
2084 cx.spawn_weak(|project, mut cx| async move {
2085 while let Some(()) = subscription.next().await {
2086 if let Some(project) = project.upgrade(&cx) {
2087 project.update(&mut cx, |project, cx| {
2088 let mut plain_text_buffers = Vec::new();
2089 let mut buffers_with_unknown_injections = Vec::new();
2090 for buffer in project.opened_buffers.values() {
2091 if let Some(handle) = buffer.upgrade(cx) {
2092 let buffer = &handle.read(cx);
2093 if buffer.language().is_none()
2094 || buffer.language() == Some(&*language::PLAIN_TEXT)
2095 {
2096 plain_text_buffers.push(handle);
2097 } else if buffer.contains_unknown_injections() {
2098 buffers_with_unknown_injections.push(handle);
2099 }
2100 }
2101 }
2102
2103 for buffer in plain_text_buffers {
2104 project.detect_language_for_buffer(&buffer, cx);
2105 project.register_buffer_with_language_servers(&buffer, cx);
2106 }
2107
2108 for buffer in buffers_with_unknown_injections {
2109 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2110 }
2111 });
2112 }
2113 }
2114 })
2115 }
2116
2117 fn maintain_workspace_config(
2118 languages: Arc<LanguageRegistry>,
2119 cx: &mut ModelContext<Project>,
2120 ) -> Task<()> {
2121 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2122 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2123
2124 let settings_observation = cx.observe_global::<Settings, _>(move |_, _| {
2125 *settings_changed_tx.borrow_mut() = ();
2126 });
2127 cx.spawn_weak(|this, mut cx| async move {
2128 while let Some(_) = settings_changed_rx.next().await {
2129 let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2130 if let Some(this) = this.upgrade(&cx) {
2131 this.read_with(&cx, |this, _| {
2132 for server_state in this.language_servers.values() {
2133 if let LanguageServerState::Running { server, .. } = server_state {
2134 server
2135 .notify::<lsp::notification::DidChangeConfiguration>(
2136 lsp::DidChangeConfigurationParams {
2137 settings: workspace_config.clone(),
2138 },
2139 )
2140 .ok();
2141 }
2142 }
2143 })
2144 } else {
2145 break;
2146 }
2147 }
2148
2149 drop(settings_observation);
2150 })
2151 }
2152
2153 fn detect_language_for_buffer(
2154 &mut self,
2155 buffer_handle: &ModelHandle<Buffer>,
2156 cx: &mut ModelContext<Self>,
2157 ) -> Option<()> {
2158 // If the buffer has a language, set it and start the language server if we haven't already.
2159 let buffer = buffer_handle.read(cx);
2160 let full_path = buffer.file()?.full_path(cx);
2161 let content = buffer.as_rope();
2162 let new_language = self
2163 .languages
2164 .language_for_file(&full_path, Some(content))
2165 .now_or_never()?
2166 .ok()?;
2167 self.set_language_for_buffer(buffer_handle, new_language, cx);
2168 None
2169 }
2170
2171 pub fn set_language_for_buffer(
2172 &mut self,
2173 buffer: &ModelHandle<Buffer>,
2174 new_language: Arc<Language>,
2175 cx: &mut ModelContext<Self>,
2176 ) {
2177 buffer.update(cx, |buffer, cx| {
2178 if buffer.language().map_or(true, |old_language| {
2179 !Arc::ptr_eq(old_language, &new_language)
2180 }) {
2181 buffer.set_language(Some(new_language.clone()), cx);
2182 }
2183 });
2184
2185 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2186 if let Some(worktree) = file.worktree.read(cx).as_local() {
2187 let worktree_id = worktree.id();
2188 let worktree_abs_path = worktree.abs_path().clone();
2189 self.start_language_servers(worktree_id, worktree_abs_path, new_language, cx);
2190 }
2191 }
2192 }
2193
2194 fn start_language_servers(
2195 &mut self,
2196 worktree_id: WorktreeId,
2197 worktree_path: Arc<Path>,
2198 language: Arc<Language>,
2199 cx: &mut ModelContext<Self>,
2200 ) {
2201 if !cx
2202 .global::<Settings>()
2203 .enable_language_server(Some(&language.name()))
2204 {
2205 return;
2206 }
2207
2208 for adapter in language.lsp_adapters() {
2209 let key = (worktree_id, adapter.name.clone());
2210 if self.language_server_ids.contains_key(&key) {
2211 continue;
2212 }
2213
2214 let pending_server = match self.languages.start_language_server(
2215 language.clone(),
2216 adapter.clone(),
2217 worktree_path.clone(),
2218 self.client.http_client(),
2219 cx,
2220 ) {
2221 Some(pending_server) => pending_server,
2222 None => continue,
2223 };
2224
2225 let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
2226 let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2227
2228 let mut initialization_options = adapter.initialization_options.clone();
2229 match (&mut initialization_options, override_options) {
2230 (Some(initialization_options), Some(override_options)) => {
2231 merge_json_value_into(override_options, initialization_options);
2232 }
2233 (None, override_options) => initialization_options = override_options,
2234 _ => {}
2235 }
2236
2237 let server_id = pending_server.server_id;
2238 let state = self.setup_pending_language_server(
2239 initialization_options,
2240 pending_server,
2241 adapter.clone(),
2242 language.clone(),
2243 key.clone(),
2244 cx,
2245 );
2246 self.language_servers.insert(server_id, state);
2247 self.language_server_ids.insert(key.clone(), server_id);
2248 }
2249 }
2250
2251 fn setup_pending_language_server(
2252 &mut self,
2253 initialization_options: Option<serde_json::Value>,
2254 pending_server: PendingLanguageServer,
2255 adapter: Arc<CachedLspAdapter>,
2256 language: Arc<Language>,
2257 key: (WorktreeId, LanguageServerName),
2258 cx: &mut ModelContext<Project>,
2259 ) -> LanguageServerState {
2260 let server_id = pending_server.server_id;
2261 let languages = self.languages.clone();
2262
2263 LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2264 let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2265 let language_server = pending_server.task.await.log_err()?;
2266 let language_server = language_server
2267 .initialize(initialization_options)
2268 .await
2269 .log_err()?;
2270 let this = this.upgrade(&cx)?;
2271
2272 language_server
2273 .on_notification::<lsp::notification::PublishDiagnostics, _>({
2274 let this = this.downgrade();
2275 let adapter = adapter.clone();
2276 move |mut params, cx| {
2277 let this = this;
2278 let adapter = adapter.clone();
2279 cx.spawn(|mut cx| async move {
2280 adapter.process_diagnostics(&mut params).await;
2281 if let Some(this) = this.upgrade(&cx) {
2282 this.update(&mut cx, |this, cx| {
2283 this.update_diagnostics(
2284 server_id,
2285 params,
2286 &adapter.disk_based_diagnostic_sources,
2287 cx,
2288 )
2289 .log_err();
2290 });
2291 }
2292 })
2293 .detach();
2294 }
2295 })
2296 .detach();
2297
2298 language_server
2299 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2300 let languages = languages.clone();
2301 move |params, mut cx| {
2302 let languages = languages.clone();
2303 async move {
2304 let workspace_config =
2305 cx.update(|cx| languages.workspace_configuration(cx)).await;
2306 Ok(params
2307 .items
2308 .into_iter()
2309 .map(|item| {
2310 if let Some(section) = &item.section {
2311 workspace_config
2312 .get(section)
2313 .cloned()
2314 .unwrap_or(serde_json::Value::Null)
2315 } else {
2316 workspace_config.clone()
2317 }
2318 })
2319 .collect())
2320 }
2321 }
2322 })
2323 .detach();
2324
2325 // Even though we don't have handling for these requests, respond to them to
2326 // avoid stalling any language server like `gopls` which waits for a response
2327 // to these requests when initializing.
2328 language_server
2329 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2330 let this = this.downgrade();
2331 move |params, mut cx| async move {
2332 if let Some(this) = this.upgrade(&cx) {
2333 this.update(&mut cx, |this, _| {
2334 if let Some(status) =
2335 this.language_server_statuses.get_mut(&server_id)
2336 {
2337 if let lsp::NumberOrString::String(token) = params.token {
2338 status.progress_tokens.insert(token);
2339 }
2340 }
2341 });
2342 }
2343 Ok(())
2344 }
2345 })
2346 .detach();
2347 language_server
2348 .on_request::<lsp::request::RegisterCapability, _, _>({
2349 let this = this.downgrade();
2350 move |params, mut cx| async move {
2351 let this = this
2352 .upgrade(&cx)
2353 .ok_or_else(|| anyhow!("project dropped"))?;
2354 for reg in params.registrations {
2355 if reg.method == "workspace/didChangeWatchedFiles" {
2356 if let Some(options) = reg.register_options {
2357 let options = serde_json::from_value(options)?;
2358 this.update(&mut cx, |this, cx| {
2359 this.on_lsp_did_change_watched_files(
2360 server_id, options, cx,
2361 );
2362 });
2363 }
2364 }
2365 }
2366 Ok(())
2367 }
2368 })
2369 .detach();
2370
2371 language_server
2372 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2373 let this = this.downgrade();
2374 let adapter = adapter.clone();
2375 let language_server = language_server.clone();
2376 move |params, cx| {
2377 Self::on_lsp_workspace_edit(
2378 this,
2379 params,
2380 server_id,
2381 adapter.clone(),
2382 language_server.clone(),
2383 cx,
2384 )
2385 }
2386 })
2387 .detach();
2388
2389 let disk_based_diagnostics_progress_token =
2390 adapter.disk_based_diagnostics_progress_token.clone();
2391
2392 language_server
2393 .on_notification::<lsp::notification::Progress, _>({
2394 let this = this.downgrade();
2395 move |params, mut cx| {
2396 if let Some(this) = this.upgrade(&cx) {
2397 this.update(&mut cx, |this, cx| {
2398 this.on_lsp_progress(
2399 params,
2400 server_id,
2401 disk_based_diagnostics_progress_token.clone(),
2402 cx,
2403 );
2404 });
2405 }
2406 }
2407 })
2408 .detach();
2409
2410 language_server
2411 .notify::<lsp::notification::DidChangeConfiguration>(
2412 lsp::DidChangeConfigurationParams {
2413 settings: workspace_config,
2414 },
2415 )
2416 .ok();
2417
2418 this.update(&mut cx, |this, cx| {
2419 // If the language server for this key doesn't match the server id, don't store the
2420 // server. Which will cause it to be dropped, killing the process
2421 if this
2422 .language_server_ids
2423 .get(&key)
2424 .map(|id| id != &server_id)
2425 .unwrap_or(false)
2426 {
2427 return None;
2428 }
2429
2430 // Update language_servers collection with Running variant of LanguageServerState
2431 // indicating that the server is up and running and ready
2432 this.language_servers.insert(
2433 server_id,
2434 LanguageServerState::Running {
2435 adapter: adapter.clone(),
2436 language: language.clone(),
2437 watched_paths: Default::default(),
2438 server: language_server.clone(),
2439 simulate_disk_based_diagnostics_completion: None,
2440 },
2441 );
2442 this.language_server_statuses.insert(
2443 server_id,
2444 LanguageServerStatus {
2445 name: language_server.name().to_string(),
2446 pending_work: Default::default(),
2447 has_pending_diagnostic_updates: false,
2448 progress_tokens: Default::default(),
2449 },
2450 );
2451
2452 if let Some(project_id) = this.remote_id() {
2453 this.client
2454 .send(proto::StartLanguageServer {
2455 project_id,
2456 server: Some(proto::LanguageServer {
2457 id: server_id.0 as u64,
2458 name: language_server.name().to_string(),
2459 }),
2460 })
2461 .log_err();
2462 }
2463
2464 // Tell the language server about every open buffer in the worktree that matches the language.
2465 for buffer in this.opened_buffers.values() {
2466 if let Some(buffer_handle) = buffer.upgrade(cx) {
2467 let buffer = buffer_handle.read(cx);
2468 let file = match File::from_dyn(buffer.file()) {
2469 Some(file) => file,
2470 None => continue,
2471 };
2472 let language = match buffer.language() {
2473 Some(language) => language,
2474 None => continue,
2475 };
2476
2477 if file.worktree.read(cx).id() != key.0
2478 || !language.lsp_adapters().iter().any(|a| a.name == key.1)
2479 {
2480 continue;
2481 }
2482
2483 let file = file.as_local()?;
2484 let versions = this
2485 .buffer_snapshots
2486 .entry(buffer.remote_id())
2487 .or_default()
2488 .entry(server_id)
2489 .or_insert_with(|| {
2490 vec![LspBufferSnapshot {
2491 version: 0,
2492 snapshot: buffer.text_snapshot(),
2493 }]
2494 });
2495
2496 let snapshot = versions.last().unwrap();
2497 let version = snapshot.version;
2498 let initial_snapshot = &snapshot.snapshot;
2499 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2500 language_server
2501 .notify::<lsp::notification::DidOpenTextDocument>(
2502 lsp::DidOpenTextDocumentParams {
2503 text_document: lsp::TextDocumentItem::new(
2504 uri,
2505 adapter
2506 .language_ids
2507 .get(language.name().as_ref())
2508 .cloned()
2509 .unwrap_or_default(),
2510 version,
2511 initial_snapshot.text(),
2512 ),
2513 },
2514 )
2515 .log_err()?;
2516 buffer_handle.update(cx, |buffer, cx| {
2517 buffer.set_completion_triggers(
2518 language_server
2519 .capabilities()
2520 .completion_provider
2521 .as_ref()
2522 .and_then(|provider| provider.trigger_characters.clone())
2523 .unwrap_or_default(),
2524 cx,
2525 )
2526 });
2527 }
2528 }
2529
2530 cx.notify();
2531 Some(language_server)
2532 })
2533 }))
2534 }
2535
2536 // Returns a list of all of the worktrees which no longer have a language server and the root path
2537 // for the stopped server
2538 fn stop_language_server(
2539 &mut self,
2540 worktree_id: WorktreeId,
2541 adapter_name: LanguageServerName,
2542 cx: &mut ModelContext<Self>,
2543 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2544 let key = (worktree_id, adapter_name);
2545 if let Some(server_id) = self.language_server_ids.remove(&key) {
2546 // Remove other entries for this language server as well
2547 let mut orphaned_worktrees = vec![worktree_id];
2548 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2549 for other_key in other_keys {
2550 if self.language_server_ids.get(&other_key) == Some(&server_id) {
2551 self.language_server_ids.remove(&other_key);
2552 orphaned_worktrees.push(other_key.0);
2553 }
2554 }
2555
2556 self.language_server_statuses.remove(&server_id);
2557 cx.notify();
2558
2559 let server_state = self.language_servers.remove(&server_id);
2560 cx.spawn_weak(|this, mut cx| async move {
2561 let mut root_path = None;
2562
2563 let server = match server_state {
2564 Some(LanguageServerState::Starting(started_language_server)) => {
2565 started_language_server.await
2566 }
2567 Some(LanguageServerState::Running { server, .. }) => Some(server),
2568 None => None,
2569 };
2570
2571 if let Some(server) = server {
2572 root_path = Some(server.root_path().clone());
2573 if let Some(shutdown) = server.shutdown() {
2574 shutdown.await;
2575 }
2576 }
2577
2578 if let Some(this) = this.upgrade(&cx) {
2579 this.update(&mut cx, |this, cx| {
2580 this.language_server_statuses.remove(&server_id);
2581 cx.notify();
2582 });
2583 }
2584
2585 (root_path, orphaned_worktrees)
2586 })
2587 } else {
2588 Task::ready((None, Vec::new()))
2589 }
2590 }
2591
2592 pub fn restart_language_servers_for_buffers(
2593 &mut self,
2594 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2595 cx: &mut ModelContext<Self>,
2596 ) -> Option<()> {
2597 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, Arc<Language>)> = buffers
2598 .into_iter()
2599 .filter_map(|buffer| {
2600 let buffer = buffer.read(cx);
2601 let file = File::from_dyn(buffer.file())?;
2602 let worktree = file.worktree.read(cx).as_local()?;
2603 let full_path = file.full_path(cx);
2604 let language = self
2605 .languages
2606 .language_for_file(&full_path, Some(buffer.as_rope()))
2607 .now_or_never()?
2608 .ok()?;
2609 Some((worktree.id(), worktree.abs_path().clone(), language))
2610 })
2611 .collect();
2612 for (worktree_id, worktree_abs_path, language) in language_server_lookup_info {
2613 self.restart_language_servers(worktree_id, worktree_abs_path, language, cx);
2614 }
2615
2616 None
2617 }
2618
2619 // TODO This will break in the case where the adapter's root paths and worktrees are not equal
2620 fn restart_language_servers(
2621 &mut self,
2622 worktree_id: WorktreeId,
2623 fallback_path: Arc<Path>,
2624 language: Arc<Language>,
2625 cx: &mut ModelContext<Self>,
2626 ) {
2627 let mut stops = Vec::new();
2628 for adapter in language.lsp_adapters() {
2629 stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
2630 }
2631
2632 if stops.is_empty() {
2633 return;
2634 }
2635 let mut stops = stops.into_iter();
2636
2637 cx.spawn_weak(|this, mut cx| async move {
2638 let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
2639 for stop in stops {
2640 let (_, worktrees) = stop.await;
2641 orphaned_worktrees.extend_from_slice(&worktrees);
2642 }
2643
2644 let this = match this.upgrade(&cx) {
2645 Some(this) => this,
2646 None => return,
2647 };
2648
2649 this.update(&mut cx, |this, cx| {
2650 // Attempt to restart using original server path. Fallback to passed in
2651 // path if we could not retrieve the root path
2652 let root_path = original_root_path
2653 .map(|path_buf| Arc::from(path_buf.as_path()))
2654 .unwrap_or(fallback_path);
2655
2656 this.start_language_servers(worktree_id, root_path, language.clone(), cx);
2657
2658 // Lookup new server ids and set them for each of the orphaned worktrees
2659 for adapter in language.lsp_adapters() {
2660 if let Some(new_server_id) = this
2661 .language_server_ids
2662 .get(&(worktree_id, adapter.name.clone()))
2663 .cloned()
2664 {
2665 for &orphaned_worktree in &orphaned_worktrees {
2666 this.language_server_ids
2667 .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
2668 }
2669 }
2670 }
2671 });
2672 })
2673 .detach();
2674 }
2675
2676 fn on_lsp_progress(
2677 &mut self,
2678 progress: lsp::ProgressParams,
2679 language_server_id: LanguageServerId,
2680 disk_based_diagnostics_progress_token: Option<String>,
2681 cx: &mut ModelContext<Self>,
2682 ) {
2683 let token = match progress.token {
2684 lsp::NumberOrString::String(token) => token,
2685 lsp::NumberOrString::Number(token) => {
2686 log::info!("skipping numeric progress token {}", token);
2687 return;
2688 }
2689 };
2690 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2691 let language_server_status =
2692 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2693 status
2694 } else {
2695 return;
2696 };
2697
2698 if !language_server_status.progress_tokens.contains(&token) {
2699 return;
2700 }
2701
2702 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2703 .as_ref()
2704 .map_or(false, |disk_based_token| {
2705 token.starts_with(disk_based_token)
2706 });
2707
2708 match progress {
2709 lsp::WorkDoneProgress::Begin(report) => {
2710 if is_disk_based_diagnostics_progress {
2711 language_server_status.has_pending_diagnostic_updates = true;
2712 self.disk_based_diagnostics_started(language_server_id, cx);
2713 self.buffer_ordered_messages_tx
2714 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2715 language_server_id,
2716 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
2717 })
2718 .ok();
2719 } else {
2720 self.on_lsp_work_start(
2721 language_server_id,
2722 token.clone(),
2723 LanguageServerProgress {
2724 message: report.message.clone(),
2725 percentage: report.percentage.map(|p| p as usize),
2726 last_update_at: Instant::now(),
2727 },
2728 cx,
2729 );
2730 self.buffer_ordered_messages_tx
2731 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2732 language_server_id,
2733 message: proto::update_language_server::Variant::WorkStart(
2734 proto::LspWorkStart {
2735 token,
2736 message: report.message,
2737 percentage: report.percentage.map(|p| p as u32),
2738 },
2739 ),
2740 })
2741 .ok();
2742 }
2743 }
2744 lsp::WorkDoneProgress::Report(report) => {
2745 if !is_disk_based_diagnostics_progress {
2746 self.on_lsp_work_progress(
2747 language_server_id,
2748 token.clone(),
2749 LanguageServerProgress {
2750 message: report.message.clone(),
2751 percentage: report.percentage.map(|p| p as usize),
2752 last_update_at: Instant::now(),
2753 },
2754 cx,
2755 );
2756 self.buffer_ordered_messages_tx
2757 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2758 language_server_id,
2759 message: proto::update_language_server::Variant::WorkProgress(
2760 proto::LspWorkProgress {
2761 token,
2762 message: report.message,
2763 percentage: report.percentage.map(|p| p as u32),
2764 },
2765 ),
2766 })
2767 .ok();
2768 }
2769 }
2770 lsp::WorkDoneProgress::End(_) => {
2771 language_server_status.progress_tokens.remove(&token);
2772
2773 if is_disk_based_diagnostics_progress {
2774 language_server_status.has_pending_diagnostic_updates = false;
2775 self.disk_based_diagnostics_finished(language_server_id, cx);
2776 self.buffer_ordered_messages_tx
2777 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2778 language_server_id,
2779 message:
2780 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2781 Default::default(),
2782 ),
2783 })
2784 .ok();
2785 } else {
2786 self.on_lsp_work_end(language_server_id, token.clone(), cx);
2787 self.buffer_ordered_messages_tx
2788 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2789 language_server_id,
2790 message: proto::update_language_server::Variant::WorkEnd(
2791 proto::LspWorkEnd { token },
2792 ),
2793 })
2794 .ok();
2795 }
2796 }
2797 }
2798 }
2799
2800 fn on_lsp_work_start(
2801 &mut self,
2802 language_server_id: LanguageServerId,
2803 token: String,
2804 progress: LanguageServerProgress,
2805 cx: &mut ModelContext<Self>,
2806 ) {
2807 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2808 status.pending_work.insert(token, progress);
2809 cx.notify();
2810 }
2811 }
2812
2813 fn on_lsp_work_progress(
2814 &mut self,
2815 language_server_id: LanguageServerId,
2816 token: String,
2817 progress: LanguageServerProgress,
2818 cx: &mut ModelContext<Self>,
2819 ) {
2820 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2821 let entry = status
2822 .pending_work
2823 .entry(token)
2824 .or_insert(LanguageServerProgress {
2825 message: Default::default(),
2826 percentage: Default::default(),
2827 last_update_at: progress.last_update_at,
2828 });
2829 if progress.message.is_some() {
2830 entry.message = progress.message;
2831 }
2832 if progress.percentage.is_some() {
2833 entry.percentage = progress.percentage;
2834 }
2835 entry.last_update_at = progress.last_update_at;
2836 cx.notify();
2837 }
2838 }
2839
2840 fn on_lsp_work_end(
2841 &mut self,
2842 language_server_id: LanguageServerId,
2843 token: String,
2844 cx: &mut ModelContext<Self>,
2845 ) {
2846 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2847 status.pending_work.remove(&token);
2848 cx.notify();
2849 }
2850 }
2851
2852 fn on_lsp_did_change_watched_files(
2853 &mut self,
2854 language_server_id: LanguageServerId,
2855 params: DidChangeWatchedFilesRegistrationOptions,
2856 cx: &mut ModelContext<Self>,
2857 ) {
2858 if let Some(LanguageServerState::Running { watched_paths, .. }) =
2859 self.language_servers.get_mut(&language_server_id)
2860 {
2861 eprintln!("change watch");
2862 let mut builders = HashMap::default();
2863 for watcher in params.watchers {
2864 eprintln!(" {}", watcher.glob_pattern);
2865 for worktree in &self.worktrees {
2866 if let Some(worktree) = worktree.upgrade(cx) {
2867 let worktree = worktree.read(cx);
2868 if let Some(abs_path) = worktree.abs_path().to_str() {
2869 if let Some(suffix) = watcher
2870 .glob_pattern
2871 .strip_prefix(abs_path)
2872 .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR))
2873 {
2874 if let Some(glob) = Glob::new(suffix).log_err() {
2875 builders
2876 .entry(worktree.id())
2877 .or_insert_with(|| GlobSetBuilder::new())
2878 .add(glob);
2879 }
2880 break;
2881 }
2882 }
2883 }
2884 }
2885 }
2886
2887 watched_paths.clear();
2888 for (worktree_id, builder) in builders {
2889 if let Ok(globset) = builder.build() {
2890 watched_paths.insert(worktree_id, globset);
2891 }
2892 }
2893
2894 cx.notify();
2895 }
2896 }
2897
2898 async fn on_lsp_workspace_edit(
2899 this: WeakModelHandle<Self>,
2900 params: lsp::ApplyWorkspaceEditParams,
2901 server_id: LanguageServerId,
2902 adapter: Arc<CachedLspAdapter>,
2903 language_server: Arc<LanguageServer>,
2904 mut cx: AsyncAppContext,
2905 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2906 let this = this
2907 .upgrade(&cx)
2908 .ok_or_else(|| anyhow!("project project closed"))?;
2909 let transaction = Self::deserialize_workspace_edit(
2910 this.clone(),
2911 params.edit,
2912 true,
2913 adapter.clone(),
2914 language_server.clone(),
2915 &mut cx,
2916 )
2917 .await
2918 .log_err();
2919 this.update(&mut cx, |this, _| {
2920 if let Some(transaction) = transaction {
2921 this.last_workspace_edits_by_language_server
2922 .insert(server_id, transaction);
2923 }
2924 });
2925 Ok(lsp::ApplyWorkspaceEditResponse {
2926 applied: true,
2927 failed_change: None,
2928 failure_reason: None,
2929 })
2930 }
2931
2932 pub fn language_server_statuses(
2933 &self,
2934 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2935 self.language_server_statuses.values()
2936 }
2937
2938 pub fn update_diagnostics(
2939 &mut self,
2940 language_server_id: LanguageServerId,
2941 mut params: lsp::PublishDiagnosticsParams,
2942 disk_based_sources: &[String],
2943 cx: &mut ModelContext<Self>,
2944 ) -> Result<()> {
2945 let abs_path = params
2946 .uri
2947 .to_file_path()
2948 .map_err(|_| anyhow!("URI is not a file"))?;
2949 let mut diagnostics = Vec::default();
2950 let mut primary_diagnostic_group_ids = HashMap::default();
2951 let mut sources_by_group_id = HashMap::default();
2952 let mut supporting_diagnostics = HashMap::default();
2953
2954 // Ensure that primary diagnostics are always the most severe
2955 params.diagnostics.sort_by_key(|item| item.severity);
2956
2957 for diagnostic in ¶ms.diagnostics {
2958 let source = diagnostic.source.as_ref();
2959 let code = diagnostic.code.as_ref().map(|code| match code {
2960 lsp::NumberOrString::Number(code) => code.to_string(),
2961 lsp::NumberOrString::String(code) => code.clone(),
2962 });
2963 let range = range_from_lsp(diagnostic.range);
2964 let is_supporting = diagnostic
2965 .related_information
2966 .as_ref()
2967 .map_or(false, |infos| {
2968 infos.iter().any(|info| {
2969 primary_diagnostic_group_ids.contains_key(&(
2970 source,
2971 code.clone(),
2972 range_from_lsp(info.location.range),
2973 ))
2974 })
2975 });
2976
2977 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2978 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2979 });
2980
2981 if is_supporting {
2982 supporting_diagnostics.insert(
2983 (source, code.clone(), range),
2984 (diagnostic.severity, is_unnecessary),
2985 );
2986 } else {
2987 let group_id = post_inc(&mut self.next_diagnostic_group_id);
2988 let is_disk_based =
2989 source.map_or(false, |source| disk_based_sources.contains(source));
2990
2991 sources_by_group_id.insert(group_id, source);
2992 primary_diagnostic_group_ids
2993 .insert((source, code.clone(), range.clone()), group_id);
2994
2995 diagnostics.push(DiagnosticEntry {
2996 range,
2997 diagnostic: Diagnostic {
2998 source: diagnostic.source.clone(),
2999 code: code.clone(),
3000 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3001 message: diagnostic.message.clone(),
3002 group_id,
3003 is_primary: true,
3004 is_valid: true,
3005 is_disk_based,
3006 is_unnecessary,
3007 },
3008 });
3009 if let Some(infos) = &diagnostic.related_information {
3010 for info in infos {
3011 if info.location.uri == params.uri && !info.message.is_empty() {
3012 let range = range_from_lsp(info.location.range);
3013 diagnostics.push(DiagnosticEntry {
3014 range,
3015 diagnostic: Diagnostic {
3016 source: diagnostic.source.clone(),
3017 code: code.clone(),
3018 severity: DiagnosticSeverity::INFORMATION,
3019 message: info.message.clone(),
3020 group_id,
3021 is_primary: false,
3022 is_valid: true,
3023 is_disk_based,
3024 is_unnecessary: false,
3025 },
3026 });
3027 }
3028 }
3029 }
3030 }
3031 }
3032
3033 for entry in &mut diagnostics {
3034 let diagnostic = &mut entry.diagnostic;
3035 if !diagnostic.is_primary {
3036 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3037 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3038 source,
3039 diagnostic.code.clone(),
3040 entry.range.clone(),
3041 )) {
3042 if let Some(severity) = severity {
3043 diagnostic.severity = severity;
3044 }
3045 diagnostic.is_unnecessary = is_unnecessary;
3046 }
3047 }
3048 }
3049
3050 self.update_diagnostic_entries(
3051 language_server_id,
3052 abs_path,
3053 params.version,
3054 diagnostics,
3055 cx,
3056 )?;
3057 Ok(())
3058 }
3059
3060 pub fn update_diagnostic_entries(
3061 &mut self,
3062 server_id: LanguageServerId,
3063 abs_path: PathBuf,
3064 version: Option<i32>,
3065 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3066 cx: &mut ModelContext<Project>,
3067 ) -> Result<(), anyhow::Error> {
3068 let (worktree, relative_path) = self
3069 .find_local_worktree(&abs_path, cx)
3070 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
3071
3072 let project_path = ProjectPath {
3073 worktree_id: worktree.read(cx).id(),
3074 path: relative_path.into(),
3075 };
3076
3077 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3078 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3079 }
3080
3081 let updated = worktree.update(cx, |worktree, cx| {
3082 worktree
3083 .as_local_mut()
3084 .ok_or_else(|| anyhow!("not a local worktree"))?
3085 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3086 })?;
3087 if updated {
3088 cx.emit(Event::DiagnosticsUpdated {
3089 language_server_id: server_id,
3090 path: project_path,
3091 });
3092 }
3093 Ok(())
3094 }
3095
3096 fn update_buffer_diagnostics(
3097 &mut self,
3098 buffer: &ModelHandle<Buffer>,
3099 server_id: LanguageServerId,
3100 version: Option<i32>,
3101 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3102 cx: &mut ModelContext<Self>,
3103 ) -> Result<()> {
3104 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3105 Ordering::Equal
3106 .then_with(|| b.is_primary.cmp(&a.is_primary))
3107 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3108 .then_with(|| a.severity.cmp(&b.severity))
3109 .then_with(|| a.message.cmp(&b.message))
3110 }
3111
3112 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3113
3114 diagnostics.sort_unstable_by(|a, b| {
3115 Ordering::Equal
3116 .then_with(|| a.range.start.cmp(&b.range.start))
3117 .then_with(|| b.range.end.cmp(&a.range.end))
3118 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3119 });
3120
3121 let mut sanitized_diagnostics = Vec::new();
3122 let edits_since_save = Patch::new(
3123 snapshot
3124 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3125 .collect(),
3126 );
3127 for entry in diagnostics {
3128 let start;
3129 let end;
3130 if entry.diagnostic.is_disk_based {
3131 // Some diagnostics are based on files on disk instead of buffers'
3132 // current contents. Adjust these diagnostics' ranges to reflect
3133 // any unsaved edits.
3134 start = edits_since_save.old_to_new(entry.range.start);
3135 end = edits_since_save.old_to_new(entry.range.end);
3136 } else {
3137 start = entry.range.start;
3138 end = entry.range.end;
3139 }
3140
3141 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3142 ..snapshot.clip_point_utf16(end, Bias::Right);
3143
3144 // Expand empty ranges by one codepoint
3145 if range.start == range.end {
3146 // This will be go to the next boundary when being clipped
3147 range.end.column += 1;
3148 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3149 if range.start == range.end && range.end.column > 0 {
3150 range.start.column -= 1;
3151 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3152 }
3153 }
3154
3155 sanitized_diagnostics.push(DiagnosticEntry {
3156 range,
3157 diagnostic: entry.diagnostic,
3158 });
3159 }
3160 drop(edits_since_save);
3161
3162 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3163 buffer.update(cx, |buffer, cx| {
3164 buffer.update_diagnostics(server_id, set, cx)
3165 });
3166 Ok(())
3167 }
3168
3169 pub fn reload_buffers(
3170 &self,
3171 buffers: HashSet<ModelHandle<Buffer>>,
3172 push_to_history: bool,
3173 cx: &mut ModelContext<Self>,
3174 ) -> Task<Result<ProjectTransaction>> {
3175 let mut local_buffers = Vec::new();
3176 let mut remote_buffers = None;
3177 for buffer_handle in buffers {
3178 let buffer = buffer_handle.read(cx);
3179 if buffer.is_dirty() {
3180 if let Some(file) = File::from_dyn(buffer.file()) {
3181 if file.is_local() {
3182 local_buffers.push(buffer_handle);
3183 } else {
3184 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3185 }
3186 }
3187 }
3188 }
3189
3190 let remote_buffers = self.remote_id().zip(remote_buffers);
3191 let client = self.client.clone();
3192
3193 cx.spawn(|this, mut cx| async move {
3194 let mut project_transaction = ProjectTransaction::default();
3195
3196 if let Some((project_id, remote_buffers)) = remote_buffers {
3197 let response = client
3198 .request(proto::ReloadBuffers {
3199 project_id,
3200 buffer_ids: remote_buffers
3201 .iter()
3202 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3203 .collect(),
3204 })
3205 .await?
3206 .transaction
3207 .ok_or_else(|| anyhow!("missing transaction"))?;
3208 project_transaction = this
3209 .update(&mut cx, |this, cx| {
3210 this.deserialize_project_transaction(response, push_to_history, cx)
3211 })
3212 .await?;
3213 }
3214
3215 for buffer in local_buffers {
3216 let transaction = buffer
3217 .update(&mut cx, |buffer, cx| buffer.reload(cx))
3218 .await?;
3219 buffer.update(&mut cx, |buffer, cx| {
3220 if let Some(transaction) = transaction {
3221 if !push_to_history {
3222 buffer.forget_transaction(transaction.id);
3223 }
3224 project_transaction.0.insert(cx.handle(), transaction);
3225 }
3226 });
3227 }
3228
3229 Ok(project_transaction)
3230 })
3231 }
3232
3233 pub fn format(
3234 &self,
3235 buffers: HashSet<ModelHandle<Buffer>>,
3236 push_to_history: bool,
3237 trigger: FormatTrigger,
3238 cx: &mut ModelContext<Project>,
3239 ) -> Task<Result<ProjectTransaction>> {
3240 if self.is_local() {
3241 let mut buffers_with_paths_and_servers = buffers
3242 .into_iter()
3243 .filter_map(|buffer_handle| {
3244 let buffer = buffer_handle.read(cx);
3245 let file = File::from_dyn(buffer.file())?;
3246 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3247 let server = self
3248 .primary_language_servers_for_buffer(buffer, cx)
3249 .map(|s| s.1.clone());
3250 Some((buffer_handle, buffer_abs_path, server))
3251 })
3252 .collect::<Vec<_>>();
3253
3254 cx.spawn(|this, mut cx| async move {
3255 // Do not allow multiple concurrent formatting requests for the
3256 // same buffer.
3257 this.update(&mut cx, |this, cx| {
3258 buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
3259 this.buffers_being_formatted
3260 .insert(buffer.read(cx).remote_id())
3261 });
3262 });
3263
3264 let _cleanup = defer({
3265 let this = this.clone();
3266 let mut cx = cx.clone();
3267 let buffers = &buffers_with_paths_and_servers;
3268 move || {
3269 this.update(&mut cx, |this, cx| {
3270 for (buffer, _, _) in buffers {
3271 this.buffers_being_formatted
3272 .remove(&buffer.read(cx).remote_id());
3273 }
3274 });
3275 }
3276 });
3277
3278 let mut project_transaction = ProjectTransaction::default();
3279 for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3280 let (
3281 format_on_save,
3282 remove_trailing_whitespace,
3283 ensure_final_newline,
3284 formatter,
3285 tab_size,
3286 ) = buffer.read_with(&cx, |buffer, cx| {
3287 let settings = cx.global::<Settings>();
3288 let language_name = buffer.language().map(|language| language.name());
3289 (
3290 settings.format_on_save(language_name.as_deref()),
3291 settings.remove_trailing_whitespace_on_save(language_name.as_deref()),
3292 settings.ensure_final_newline_on_save(language_name.as_deref()),
3293 settings.formatter(language_name.as_deref()),
3294 settings.tab_size(language_name.as_deref()),
3295 )
3296 });
3297
3298 // First, format buffer's whitespace according to the settings.
3299 let trailing_whitespace_diff = if remove_trailing_whitespace {
3300 Some(
3301 buffer
3302 .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3303 .await,
3304 )
3305 } else {
3306 None
3307 };
3308 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3309 buffer.finalize_last_transaction();
3310 buffer.start_transaction();
3311 if let Some(diff) = trailing_whitespace_diff {
3312 buffer.apply_diff(diff, cx);
3313 }
3314 if ensure_final_newline {
3315 buffer.ensure_final_newline(cx);
3316 }
3317 buffer.end_transaction(cx)
3318 });
3319
3320 // Currently, formatting operations are represented differently depending on
3321 // whether they come from a language server or an external command.
3322 enum FormatOperation {
3323 Lsp(Vec<(Range<Anchor>, String)>),
3324 External(Diff),
3325 }
3326
3327 // Apply language-specific formatting using either a language server
3328 // or external command.
3329 let mut format_operation = None;
3330 match (formatter, format_on_save) {
3331 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3332
3333 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3334 | (_, FormatOnSave::LanguageServer) => {
3335 if let Some((language_server, buffer_abs_path)) =
3336 language_server.as_ref().zip(buffer_abs_path.as_ref())
3337 {
3338 format_operation = Some(FormatOperation::Lsp(
3339 Self::format_via_lsp(
3340 &this,
3341 &buffer,
3342 buffer_abs_path,
3343 &language_server,
3344 tab_size,
3345 &mut cx,
3346 )
3347 .await
3348 .context("failed to format via language server")?,
3349 ));
3350 }
3351 }
3352
3353 (
3354 Formatter::External { command, arguments },
3355 FormatOnSave::On | FormatOnSave::Off,
3356 )
3357 | (_, FormatOnSave::External { command, arguments }) => {
3358 if let Some(buffer_abs_path) = buffer_abs_path {
3359 format_operation = Self::format_via_external_command(
3360 &buffer,
3361 &buffer_abs_path,
3362 &command,
3363 &arguments,
3364 &mut cx,
3365 )
3366 .await
3367 .context(format!(
3368 "failed to format via external command {:?}",
3369 command
3370 ))?
3371 .map(FormatOperation::External);
3372 }
3373 }
3374 };
3375
3376 buffer.update(&mut cx, |b, cx| {
3377 // If the buffer had its whitespace formatted and was edited while the language-specific
3378 // formatting was being computed, avoid applying the language-specific formatting, because
3379 // it can't be grouped with the whitespace formatting in the undo history.
3380 if let Some(transaction_id) = whitespace_transaction_id {
3381 if b.peek_undo_stack()
3382 .map_or(true, |e| e.transaction_id() != transaction_id)
3383 {
3384 format_operation.take();
3385 }
3386 }
3387
3388 // Apply any language-specific formatting, and group the two formatting operations
3389 // in the buffer's undo history.
3390 if let Some(operation) = format_operation {
3391 match operation {
3392 FormatOperation::Lsp(edits) => {
3393 b.edit(edits, None, cx);
3394 }
3395 FormatOperation::External(diff) => {
3396 b.apply_diff(diff, cx);
3397 }
3398 }
3399
3400 if let Some(transaction_id) = whitespace_transaction_id {
3401 b.group_until_transaction(transaction_id);
3402 }
3403 }
3404
3405 if let Some(transaction) = b.finalize_last_transaction().cloned() {
3406 if !push_to_history {
3407 b.forget_transaction(transaction.id);
3408 }
3409 project_transaction.0.insert(buffer.clone(), transaction);
3410 }
3411 });
3412 }
3413
3414 Ok(project_transaction)
3415 })
3416 } else {
3417 let remote_id = self.remote_id();
3418 let client = self.client.clone();
3419 cx.spawn(|this, mut cx| async move {
3420 let mut project_transaction = ProjectTransaction::default();
3421 if let Some(project_id) = remote_id {
3422 let response = client
3423 .request(proto::FormatBuffers {
3424 project_id,
3425 trigger: trigger as i32,
3426 buffer_ids: buffers
3427 .iter()
3428 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3429 .collect(),
3430 })
3431 .await?
3432 .transaction
3433 .ok_or_else(|| anyhow!("missing transaction"))?;
3434 project_transaction = this
3435 .update(&mut cx, |this, cx| {
3436 this.deserialize_project_transaction(response, push_to_history, cx)
3437 })
3438 .await?;
3439 }
3440 Ok(project_transaction)
3441 })
3442 }
3443 }
3444
3445 async fn format_via_lsp(
3446 this: &ModelHandle<Self>,
3447 buffer: &ModelHandle<Buffer>,
3448 abs_path: &Path,
3449 language_server: &Arc<LanguageServer>,
3450 tab_size: NonZeroU32,
3451 cx: &mut AsyncAppContext,
3452 ) -> Result<Vec<(Range<Anchor>, String)>> {
3453 let text_document =
3454 lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3455 let capabilities = &language_server.capabilities();
3456 let lsp_edits = if capabilities
3457 .document_formatting_provider
3458 .as_ref()
3459 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3460 {
3461 language_server
3462 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3463 text_document,
3464 options: lsp::FormattingOptions {
3465 tab_size: tab_size.into(),
3466 insert_spaces: true,
3467 insert_final_newline: Some(true),
3468 ..Default::default()
3469 },
3470 work_done_progress_params: Default::default(),
3471 })
3472 .await?
3473 } else if capabilities
3474 .document_range_formatting_provider
3475 .as_ref()
3476 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3477 {
3478 let buffer_start = lsp::Position::new(0, 0);
3479 let buffer_end =
3480 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3481 language_server
3482 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3483 text_document,
3484 range: lsp::Range::new(buffer_start, buffer_end),
3485 options: lsp::FormattingOptions {
3486 tab_size: tab_size.into(),
3487 insert_spaces: true,
3488 insert_final_newline: Some(true),
3489 ..Default::default()
3490 },
3491 work_done_progress_params: Default::default(),
3492 })
3493 .await?
3494 } else {
3495 None
3496 };
3497
3498 if let Some(lsp_edits) = lsp_edits {
3499 this.update(cx, |this, cx| {
3500 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
3501 })
3502 .await
3503 } else {
3504 Ok(Default::default())
3505 }
3506 }
3507
3508 async fn format_via_external_command(
3509 buffer: &ModelHandle<Buffer>,
3510 buffer_abs_path: &Path,
3511 command: &str,
3512 arguments: &[String],
3513 cx: &mut AsyncAppContext,
3514 ) -> Result<Option<Diff>> {
3515 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3516 let file = File::from_dyn(buffer.file())?;
3517 let worktree = file.worktree.read(cx).as_local()?;
3518 let mut worktree_path = worktree.abs_path().to_path_buf();
3519 if worktree.root_entry()?.is_file() {
3520 worktree_path.pop();
3521 }
3522 Some(worktree_path)
3523 });
3524
3525 if let Some(working_dir_path) = working_dir_path {
3526 let mut child =
3527 smol::process::Command::new(command)
3528 .args(arguments.iter().map(|arg| {
3529 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3530 }))
3531 .current_dir(&working_dir_path)
3532 .stdin(smol::process::Stdio::piped())
3533 .stdout(smol::process::Stdio::piped())
3534 .stderr(smol::process::Stdio::piped())
3535 .spawn()?;
3536 let stdin = child
3537 .stdin
3538 .as_mut()
3539 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3540 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3541 for chunk in text.chunks() {
3542 stdin.write_all(chunk.as_bytes()).await?;
3543 }
3544 stdin.flush().await?;
3545
3546 let output = child.output().await?;
3547 if !output.status.success() {
3548 return Err(anyhow!(
3549 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3550 output.status.code(),
3551 String::from_utf8_lossy(&output.stdout),
3552 String::from_utf8_lossy(&output.stderr),
3553 ));
3554 }
3555
3556 let stdout = String::from_utf8(output.stdout)?;
3557 Ok(Some(
3558 buffer
3559 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3560 .await,
3561 ))
3562 } else {
3563 Ok(None)
3564 }
3565 }
3566
3567 pub fn definition<T: ToPointUtf16>(
3568 &self,
3569 buffer: &ModelHandle<Buffer>,
3570 position: T,
3571 cx: &mut ModelContext<Self>,
3572 ) -> Task<Result<Vec<LocationLink>>> {
3573 let position = position.to_point_utf16(buffer.read(cx));
3574 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3575 }
3576
3577 pub fn type_definition<T: ToPointUtf16>(
3578 &self,
3579 buffer: &ModelHandle<Buffer>,
3580 position: T,
3581 cx: &mut ModelContext<Self>,
3582 ) -> Task<Result<Vec<LocationLink>>> {
3583 let position = position.to_point_utf16(buffer.read(cx));
3584 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3585 }
3586
3587 pub fn references<T: ToPointUtf16>(
3588 &self,
3589 buffer: &ModelHandle<Buffer>,
3590 position: T,
3591 cx: &mut ModelContext<Self>,
3592 ) -> Task<Result<Vec<Location>>> {
3593 let position = position.to_point_utf16(buffer.read(cx));
3594 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3595 }
3596
3597 pub fn document_highlights<T: ToPointUtf16>(
3598 &self,
3599 buffer: &ModelHandle<Buffer>,
3600 position: T,
3601 cx: &mut ModelContext<Self>,
3602 ) -> Task<Result<Vec<DocumentHighlight>>> {
3603 let position = position.to_point_utf16(buffer.read(cx));
3604 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3605 }
3606
3607 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3608 if self.is_local() {
3609 let mut requests = Vec::new();
3610 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3611 let worktree_id = *worktree_id;
3612 if let Some(worktree) = self
3613 .worktree_for_id(worktree_id, cx)
3614 .and_then(|worktree| worktree.read(cx).as_local())
3615 {
3616 if let Some(LanguageServerState::Running {
3617 adapter,
3618 language,
3619 server,
3620 ..
3621 }) = self.language_servers.get(server_id)
3622 {
3623 let adapter = adapter.clone();
3624 let language = language.clone();
3625 let worktree_abs_path = worktree.abs_path().clone();
3626 requests.push(
3627 server
3628 .request::<lsp::request::WorkspaceSymbol>(
3629 lsp::WorkspaceSymbolParams {
3630 query: query.to_string(),
3631 ..Default::default()
3632 },
3633 )
3634 .log_err()
3635 .map(move |response| {
3636 (
3637 adapter,
3638 language,
3639 worktree_id,
3640 worktree_abs_path,
3641 response.unwrap_or_default(),
3642 )
3643 }),
3644 );
3645 }
3646 }
3647 }
3648
3649 cx.spawn_weak(|this, cx| async move {
3650 let responses = futures::future::join_all(requests).await;
3651 let this = if let Some(this) = this.upgrade(&cx) {
3652 this
3653 } else {
3654 return Ok(Default::default());
3655 };
3656 let symbols = this.read_with(&cx, |this, cx| {
3657 let mut symbols = Vec::new();
3658 for (
3659 adapter,
3660 adapter_language,
3661 source_worktree_id,
3662 worktree_abs_path,
3663 response,
3664 ) in responses
3665 {
3666 symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3667 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3668 let mut worktree_id = source_worktree_id;
3669 let path;
3670 if let Some((worktree, rel_path)) =
3671 this.find_local_worktree(&abs_path, cx)
3672 {
3673 worktree_id = worktree.read(cx).id();
3674 path = rel_path;
3675 } else {
3676 path = relativize_path(&worktree_abs_path, &abs_path);
3677 }
3678
3679 let project_path = ProjectPath {
3680 worktree_id,
3681 path: path.into(),
3682 };
3683 let signature = this.symbol_signature(&project_path);
3684 let adapter_language = adapter_language.clone();
3685 let language = this
3686 .languages
3687 .language_for_file(&project_path.path, None)
3688 .unwrap_or_else(move |_| adapter_language);
3689 let language_server_name = adapter.name.clone();
3690 Some(async move {
3691 let language = language.await;
3692 let label = language
3693 .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3694 .await;
3695
3696 Symbol {
3697 language_server_name,
3698 source_worktree_id,
3699 path: project_path,
3700 label: label.unwrap_or_else(|| {
3701 CodeLabel::plain(lsp_symbol.name.clone(), None)
3702 }),
3703 kind: lsp_symbol.kind,
3704 name: lsp_symbol.name,
3705 range: range_from_lsp(lsp_symbol.location.range),
3706 signature,
3707 }
3708 })
3709 }));
3710 }
3711 symbols
3712 });
3713 Ok(futures::future::join_all(symbols).await)
3714 })
3715 } else if let Some(project_id) = self.remote_id() {
3716 let request = self.client.request(proto::GetProjectSymbols {
3717 project_id,
3718 query: query.to_string(),
3719 });
3720 cx.spawn_weak(|this, cx| async move {
3721 let response = request.await?;
3722 let mut symbols = Vec::new();
3723 if let Some(this) = this.upgrade(&cx) {
3724 let new_symbols = this.read_with(&cx, |this, _| {
3725 response
3726 .symbols
3727 .into_iter()
3728 .map(|symbol| this.deserialize_symbol(symbol))
3729 .collect::<Vec<_>>()
3730 });
3731 symbols = futures::future::join_all(new_symbols)
3732 .await
3733 .into_iter()
3734 .filter_map(|symbol| symbol.log_err())
3735 .collect::<Vec<_>>();
3736 }
3737 Ok(symbols)
3738 })
3739 } else {
3740 Task::ready(Ok(Default::default()))
3741 }
3742 }
3743
3744 pub fn open_buffer_for_symbol(
3745 &mut self,
3746 symbol: &Symbol,
3747 cx: &mut ModelContext<Self>,
3748 ) -> Task<Result<ModelHandle<Buffer>>> {
3749 if self.is_local() {
3750 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3751 symbol.source_worktree_id,
3752 symbol.language_server_name.clone(),
3753 )) {
3754 *id
3755 } else {
3756 return Task::ready(Err(anyhow!(
3757 "language server for worktree and language not found"
3758 )));
3759 };
3760
3761 let worktree_abs_path = if let Some(worktree_abs_path) = self
3762 .worktree_for_id(symbol.path.worktree_id, cx)
3763 .and_then(|worktree| worktree.read(cx).as_local())
3764 .map(|local_worktree| local_worktree.abs_path())
3765 {
3766 worktree_abs_path
3767 } else {
3768 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3769 };
3770 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3771 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3772 uri
3773 } else {
3774 return Task::ready(Err(anyhow!("invalid symbol path")));
3775 };
3776
3777 self.open_local_buffer_via_lsp(
3778 symbol_uri,
3779 language_server_id,
3780 symbol.language_server_name.clone(),
3781 cx,
3782 )
3783 } else if let Some(project_id) = self.remote_id() {
3784 let request = self.client.request(proto::OpenBufferForSymbol {
3785 project_id,
3786 symbol: Some(serialize_symbol(symbol)),
3787 });
3788 cx.spawn(|this, mut cx| async move {
3789 let response = request.await?;
3790 this.update(&mut cx, |this, cx| {
3791 this.wait_for_remote_buffer(response.buffer_id, cx)
3792 })
3793 .await
3794 })
3795 } else {
3796 Task::ready(Err(anyhow!("project does not have a remote id")))
3797 }
3798 }
3799
3800 pub fn hover<T: ToPointUtf16>(
3801 &self,
3802 buffer: &ModelHandle<Buffer>,
3803 position: T,
3804 cx: &mut ModelContext<Self>,
3805 ) -> Task<Result<Option<Hover>>> {
3806 let position = position.to_point_utf16(buffer.read(cx));
3807 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3808 }
3809
3810 pub fn completions<T: ToPointUtf16>(
3811 &self,
3812 buffer: &ModelHandle<Buffer>,
3813 position: T,
3814 cx: &mut ModelContext<Self>,
3815 ) -> Task<Result<Vec<Completion>>> {
3816 let position = position.to_point_utf16(buffer.read(cx));
3817 self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
3818 }
3819
3820 pub fn apply_additional_edits_for_completion(
3821 &self,
3822 buffer_handle: ModelHandle<Buffer>,
3823 completion: Completion,
3824 push_to_history: bool,
3825 cx: &mut ModelContext<Self>,
3826 ) -> Task<Result<Option<Transaction>>> {
3827 let buffer = buffer_handle.read(cx);
3828 let buffer_id = buffer.remote_id();
3829
3830 if self.is_local() {
3831 let lang_server = match self.primary_language_servers_for_buffer(buffer, cx) {
3832 Some((_, server)) => server.clone(),
3833 _ => return Task::ready(Ok(Default::default())),
3834 };
3835
3836 cx.spawn(|this, mut cx| async move {
3837 let resolved_completion = lang_server
3838 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3839 .await?;
3840
3841 if let Some(edits) = resolved_completion.additional_text_edits {
3842 let edits = this
3843 .update(&mut cx, |this, cx| {
3844 this.edits_from_lsp(
3845 &buffer_handle,
3846 edits,
3847 lang_server.server_id(),
3848 None,
3849 cx,
3850 )
3851 })
3852 .await?;
3853
3854 buffer_handle.update(&mut cx, |buffer, cx| {
3855 buffer.finalize_last_transaction();
3856 buffer.start_transaction();
3857
3858 for (range, text) in edits {
3859 let primary = &completion.old_range;
3860 let start_within = primary.start.cmp(&range.start, buffer).is_le()
3861 && primary.end.cmp(&range.start, buffer).is_ge();
3862 let end_within = range.start.cmp(&primary.end, buffer).is_le()
3863 && range.end.cmp(&primary.end, buffer).is_ge();
3864
3865 //Skip addtional edits which overlap with the primary completion edit
3866 //https://github.com/zed-industries/zed/pull/1871
3867 if !start_within && !end_within {
3868 buffer.edit([(range, text)], None, cx);
3869 }
3870 }
3871
3872 let transaction = if buffer.end_transaction(cx).is_some() {
3873 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3874 if !push_to_history {
3875 buffer.forget_transaction(transaction.id);
3876 }
3877 Some(transaction)
3878 } else {
3879 None
3880 };
3881 Ok(transaction)
3882 })
3883 } else {
3884 Ok(None)
3885 }
3886 })
3887 } else if let Some(project_id) = self.remote_id() {
3888 let client = self.client.clone();
3889 cx.spawn(|_, mut cx| async move {
3890 let response = client
3891 .request(proto::ApplyCompletionAdditionalEdits {
3892 project_id,
3893 buffer_id,
3894 completion: Some(language::proto::serialize_completion(&completion)),
3895 })
3896 .await?;
3897
3898 if let Some(transaction) = response.transaction {
3899 let transaction = language::proto::deserialize_transaction(transaction)?;
3900 buffer_handle
3901 .update(&mut cx, |buffer, _| {
3902 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3903 })
3904 .await?;
3905 if push_to_history {
3906 buffer_handle.update(&mut cx, |buffer, _| {
3907 buffer.push_transaction(transaction.clone(), Instant::now());
3908 });
3909 }
3910 Ok(Some(transaction))
3911 } else {
3912 Ok(None)
3913 }
3914 })
3915 } else {
3916 Task::ready(Err(anyhow!("project does not have a remote id")))
3917 }
3918 }
3919
3920 pub fn code_actions<T: Clone + ToOffset>(
3921 &self,
3922 buffer_handle: &ModelHandle<Buffer>,
3923 range: Range<T>,
3924 cx: &mut ModelContext<Self>,
3925 ) -> Task<Result<Vec<CodeAction>>> {
3926 let buffer = buffer_handle.read(cx);
3927 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3928 self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
3929 }
3930
3931 pub fn apply_code_action(
3932 &self,
3933 buffer_handle: ModelHandle<Buffer>,
3934 mut action: CodeAction,
3935 push_to_history: bool,
3936 cx: &mut ModelContext<Self>,
3937 ) -> Task<Result<ProjectTransaction>> {
3938 if self.is_local() {
3939 let buffer = buffer_handle.read(cx);
3940 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
3941 self.language_server_for_buffer(buffer, action.server_id, cx)
3942 {
3943 (adapter.clone(), server.clone())
3944 } else {
3945 return Task::ready(Ok(Default::default()));
3946 };
3947 let range = action.range.to_point_utf16(buffer);
3948
3949 cx.spawn(|this, mut cx| async move {
3950 if let Some(lsp_range) = action
3951 .lsp_action
3952 .data
3953 .as_mut()
3954 .and_then(|d| d.get_mut("codeActionParams"))
3955 .and_then(|d| d.get_mut("range"))
3956 {
3957 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3958 action.lsp_action = lang_server
3959 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3960 .await?;
3961 } else {
3962 let actions = this
3963 .update(&mut cx, |this, cx| {
3964 this.code_actions(&buffer_handle, action.range, cx)
3965 })
3966 .await?;
3967 action.lsp_action = actions
3968 .into_iter()
3969 .find(|a| a.lsp_action.title == action.lsp_action.title)
3970 .ok_or_else(|| anyhow!("code action is outdated"))?
3971 .lsp_action;
3972 }
3973
3974 if let Some(edit) = action.lsp_action.edit {
3975 if edit.changes.is_some() || edit.document_changes.is_some() {
3976 return Self::deserialize_workspace_edit(
3977 this,
3978 edit,
3979 push_to_history,
3980 lsp_adapter.clone(),
3981 lang_server.clone(),
3982 &mut cx,
3983 )
3984 .await;
3985 }
3986 }
3987
3988 if let Some(command) = action.lsp_action.command {
3989 this.update(&mut cx, |this, _| {
3990 this.last_workspace_edits_by_language_server
3991 .remove(&lang_server.server_id());
3992 });
3993 lang_server
3994 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3995 command: command.command,
3996 arguments: command.arguments.unwrap_or_default(),
3997 ..Default::default()
3998 })
3999 .await?;
4000 return Ok(this.update(&mut cx, |this, _| {
4001 this.last_workspace_edits_by_language_server
4002 .remove(&lang_server.server_id())
4003 .unwrap_or_default()
4004 }));
4005 }
4006
4007 Ok(ProjectTransaction::default())
4008 })
4009 } else if let Some(project_id) = self.remote_id() {
4010 let client = self.client.clone();
4011 let request = proto::ApplyCodeAction {
4012 project_id,
4013 buffer_id: buffer_handle.read(cx).remote_id(),
4014 action: Some(language::proto::serialize_code_action(&action)),
4015 };
4016 cx.spawn(|this, mut cx| async move {
4017 let response = client
4018 .request(request)
4019 .await?
4020 .transaction
4021 .ok_or_else(|| anyhow!("missing transaction"))?;
4022 this.update(&mut cx, |this, cx| {
4023 this.deserialize_project_transaction(response, push_to_history, cx)
4024 })
4025 .await
4026 })
4027 } else {
4028 Task::ready(Err(anyhow!("project does not have a remote id")))
4029 }
4030 }
4031
4032 async fn deserialize_workspace_edit(
4033 this: ModelHandle<Self>,
4034 edit: lsp::WorkspaceEdit,
4035 push_to_history: bool,
4036 lsp_adapter: Arc<CachedLspAdapter>,
4037 language_server: Arc<LanguageServer>,
4038 cx: &mut AsyncAppContext,
4039 ) -> Result<ProjectTransaction> {
4040 let fs = this.read_with(cx, |this, _| this.fs.clone());
4041 let mut operations = Vec::new();
4042 if let Some(document_changes) = edit.document_changes {
4043 match document_changes {
4044 lsp::DocumentChanges::Edits(edits) => {
4045 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4046 }
4047 lsp::DocumentChanges::Operations(ops) => operations = ops,
4048 }
4049 } else if let Some(changes) = edit.changes {
4050 operations.extend(changes.into_iter().map(|(uri, edits)| {
4051 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4052 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4053 uri,
4054 version: None,
4055 },
4056 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
4057 })
4058 }));
4059 }
4060
4061 let mut project_transaction = ProjectTransaction::default();
4062 for operation in operations {
4063 match operation {
4064 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4065 let abs_path = op
4066 .uri
4067 .to_file_path()
4068 .map_err(|_| anyhow!("can't convert URI to path"))?;
4069
4070 if let Some(parent_path) = abs_path.parent() {
4071 fs.create_dir(parent_path).await?;
4072 }
4073 if abs_path.ends_with("/") {
4074 fs.create_dir(&abs_path).await?;
4075 } else {
4076 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4077 .await?;
4078 }
4079 }
4080
4081 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4082 let source_abs_path = op
4083 .old_uri
4084 .to_file_path()
4085 .map_err(|_| anyhow!("can't convert URI to path"))?;
4086 let target_abs_path = op
4087 .new_uri
4088 .to_file_path()
4089 .map_err(|_| anyhow!("can't convert URI to path"))?;
4090 fs.rename(
4091 &source_abs_path,
4092 &target_abs_path,
4093 op.options.map(Into::into).unwrap_or_default(),
4094 )
4095 .await?;
4096 }
4097
4098 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4099 let abs_path = op
4100 .uri
4101 .to_file_path()
4102 .map_err(|_| anyhow!("can't convert URI to path"))?;
4103 let options = op.options.map(Into::into).unwrap_or_default();
4104 if abs_path.ends_with("/") {
4105 fs.remove_dir(&abs_path, options).await?;
4106 } else {
4107 fs.remove_file(&abs_path, options).await?;
4108 }
4109 }
4110
4111 lsp::DocumentChangeOperation::Edit(op) => {
4112 let buffer_to_edit = this
4113 .update(cx, |this, cx| {
4114 this.open_local_buffer_via_lsp(
4115 op.text_document.uri,
4116 language_server.server_id(),
4117 lsp_adapter.name.clone(),
4118 cx,
4119 )
4120 })
4121 .await?;
4122
4123 let edits = this
4124 .update(cx, |this, cx| {
4125 let edits = op.edits.into_iter().map(|edit| match edit {
4126 lsp::OneOf::Left(edit) => edit,
4127 lsp::OneOf::Right(edit) => edit.text_edit,
4128 });
4129 this.edits_from_lsp(
4130 &buffer_to_edit,
4131 edits,
4132 language_server.server_id(),
4133 op.text_document.version,
4134 cx,
4135 )
4136 })
4137 .await?;
4138
4139 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4140 buffer.finalize_last_transaction();
4141 buffer.start_transaction();
4142 for (range, text) in edits {
4143 buffer.edit([(range, text)], None, cx);
4144 }
4145 let transaction = if buffer.end_transaction(cx).is_some() {
4146 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4147 if !push_to_history {
4148 buffer.forget_transaction(transaction.id);
4149 }
4150 Some(transaction)
4151 } else {
4152 None
4153 };
4154
4155 transaction
4156 });
4157 if let Some(transaction) = transaction {
4158 project_transaction.0.insert(buffer_to_edit, transaction);
4159 }
4160 }
4161 }
4162 }
4163
4164 Ok(project_transaction)
4165 }
4166
4167 pub fn prepare_rename<T: ToPointUtf16>(
4168 &self,
4169 buffer: ModelHandle<Buffer>,
4170 position: T,
4171 cx: &mut ModelContext<Self>,
4172 ) -> Task<Result<Option<Range<Anchor>>>> {
4173 let position = position.to_point_utf16(buffer.read(cx));
4174 self.request_lsp(buffer, PrepareRename { position }, cx)
4175 }
4176
4177 pub fn perform_rename<T: ToPointUtf16>(
4178 &self,
4179 buffer: ModelHandle<Buffer>,
4180 position: T,
4181 new_name: String,
4182 push_to_history: bool,
4183 cx: &mut ModelContext<Self>,
4184 ) -> Task<Result<ProjectTransaction>> {
4185 let position = position.to_point_utf16(buffer.read(cx));
4186 self.request_lsp(
4187 buffer,
4188 PerformRename {
4189 position,
4190 new_name,
4191 push_to_history,
4192 },
4193 cx,
4194 )
4195 }
4196
4197 #[allow(clippy::type_complexity)]
4198 pub fn search(
4199 &self,
4200 query: SearchQuery,
4201 cx: &mut ModelContext<Self>,
4202 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4203 if self.is_local() {
4204 let snapshots = self
4205 .visible_worktrees(cx)
4206 .filter_map(|tree| {
4207 let tree = tree.read(cx).as_local()?;
4208 Some(tree.snapshot())
4209 })
4210 .collect::<Vec<_>>();
4211
4212 let background = cx.background().clone();
4213 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4214 if path_count == 0 {
4215 return Task::ready(Ok(Default::default()));
4216 }
4217 let workers = background.num_cpus().min(path_count);
4218 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4219 cx.background()
4220 .spawn({
4221 let fs = self.fs.clone();
4222 let background = cx.background().clone();
4223 let query = query.clone();
4224 async move {
4225 let fs = &fs;
4226 let query = &query;
4227 let matching_paths_tx = &matching_paths_tx;
4228 let paths_per_worker = (path_count + workers - 1) / workers;
4229 let snapshots = &snapshots;
4230 background
4231 .scoped(|scope| {
4232 for worker_ix in 0..workers {
4233 let worker_start_ix = worker_ix * paths_per_worker;
4234 let worker_end_ix = worker_start_ix + paths_per_worker;
4235 scope.spawn(async move {
4236 let mut snapshot_start_ix = 0;
4237 let mut abs_path = PathBuf::new();
4238 for snapshot in snapshots {
4239 let snapshot_end_ix =
4240 snapshot_start_ix + snapshot.visible_file_count();
4241 if worker_end_ix <= snapshot_start_ix {
4242 break;
4243 } else if worker_start_ix > snapshot_end_ix {
4244 snapshot_start_ix = snapshot_end_ix;
4245 continue;
4246 } else {
4247 let start_in_snapshot = worker_start_ix
4248 .saturating_sub(snapshot_start_ix);
4249 let end_in_snapshot =
4250 cmp::min(worker_end_ix, snapshot_end_ix)
4251 - snapshot_start_ix;
4252
4253 for entry in snapshot
4254 .files(false, start_in_snapshot)
4255 .take(end_in_snapshot - start_in_snapshot)
4256 {
4257 if matching_paths_tx.is_closed() {
4258 break;
4259 }
4260 let matches = if query
4261 .file_matches(Some(&entry.path))
4262 {
4263 abs_path.clear();
4264 abs_path.push(&snapshot.abs_path());
4265 abs_path.push(&entry.path);
4266 if let Some(file) =
4267 fs.open_sync(&abs_path).await.log_err()
4268 {
4269 query.detect(file).unwrap_or(false)
4270 } else {
4271 false
4272 }
4273 } else {
4274 false
4275 };
4276
4277 if matches {
4278 let project_path =
4279 (snapshot.id(), entry.path.clone());
4280 if matching_paths_tx
4281 .send(project_path)
4282 .await
4283 .is_err()
4284 {
4285 break;
4286 }
4287 }
4288 }
4289
4290 snapshot_start_ix = snapshot_end_ix;
4291 }
4292 }
4293 });
4294 }
4295 })
4296 .await;
4297 }
4298 })
4299 .detach();
4300
4301 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4302 let open_buffers = self
4303 .opened_buffers
4304 .values()
4305 .filter_map(|b| b.upgrade(cx))
4306 .collect::<HashSet<_>>();
4307 cx.spawn(|this, cx| async move {
4308 for buffer in &open_buffers {
4309 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4310 buffers_tx.send((buffer.clone(), snapshot)).await?;
4311 }
4312
4313 let open_buffers = Rc::new(RefCell::new(open_buffers));
4314 while let Some(project_path) = matching_paths_rx.next().await {
4315 if buffers_tx.is_closed() {
4316 break;
4317 }
4318
4319 let this = this.clone();
4320 let open_buffers = open_buffers.clone();
4321 let buffers_tx = buffers_tx.clone();
4322 cx.spawn(|mut cx| async move {
4323 if let Some(buffer) = this
4324 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4325 .await
4326 .log_err()
4327 {
4328 if open_buffers.borrow_mut().insert(buffer.clone()) {
4329 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4330 buffers_tx.send((buffer, snapshot)).await?;
4331 }
4332 }
4333
4334 Ok::<_, anyhow::Error>(())
4335 })
4336 .detach();
4337 }
4338
4339 Ok::<_, anyhow::Error>(())
4340 })
4341 .detach_and_log_err(cx);
4342
4343 let background = cx.background().clone();
4344 cx.background().spawn(async move {
4345 let query = &query;
4346 let mut matched_buffers = Vec::new();
4347 for _ in 0..workers {
4348 matched_buffers.push(HashMap::default());
4349 }
4350 background
4351 .scoped(|scope| {
4352 for worker_matched_buffers in matched_buffers.iter_mut() {
4353 let mut buffers_rx = buffers_rx.clone();
4354 scope.spawn(async move {
4355 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4356 let buffer_matches = if query.file_matches(
4357 snapshot.file().map(|file| file.path().as_ref()),
4358 ) {
4359 query
4360 .search(snapshot.as_rope())
4361 .await
4362 .iter()
4363 .map(|range| {
4364 snapshot.anchor_before(range.start)
4365 ..snapshot.anchor_after(range.end)
4366 })
4367 .collect()
4368 } else {
4369 Vec::new()
4370 };
4371 if !buffer_matches.is_empty() {
4372 worker_matched_buffers
4373 .insert(buffer.clone(), buffer_matches);
4374 }
4375 }
4376 });
4377 }
4378 })
4379 .await;
4380 Ok(matched_buffers.into_iter().flatten().collect())
4381 })
4382 } else if let Some(project_id) = self.remote_id() {
4383 let request = self.client.request(query.to_proto(project_id));
4384 cx.spawn(|this, mut cx| async move {
4385 let response = request.await?;
4386 let mut result = HashMap::default();
4387 for location in response.locations {
4388 let target_buffer = this
4389 .update(&mut cx, |this, cx| {
4390 this.wait_for_remote_buffer(location.buffer_id, cx)
4391 })
4392 .await?;
4393 let start = location
4394 .start
4395 .and_then(deserialize_anchor)
4396 .ok_or_else(|| anyhow!("missing target start"))?;
4397 let end = location
4398 .end
4399 .and_then(deserialize_anchor)
4400 .ok_or_else(|| anyhow!("missing target end"))?;
4401 result
4402 .entry(target_buffer)
4403 .or_insert(Vec::new())
4404 .push(start..end)
4405 }
4406 Ok(result)
4407 })
4408 } else {
4409 Task::ready(Ok(Default::default()))
4410 }
4411 }
4412
4413 // TODO: Wire this up to allow selecting a server?
4414 fn request_lsp<R: LspCommand>(
4415 &self,
4416 buffer_handle: ModelHandle<Buffer>,
4417 request: R,
4418 cx: &mut ModelContext<Self>,
4419 ) -> Task<Result<R::Response>>
4420 where
4421 <R::LspRequest as lsp::request::Request>::Result: Send,
4422 {
4423 let buffer = buffer_handle.read(cx);
4424 if self.is_local() {
4425 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4426 if let Some((file, language_server)) = file.zip(
4427 self.primary_language_servers_for_buffer(buffer, cx)
4428 .map(|(_, server)| server.clone()),
4429 ) {
4430 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
4431 return cx.spawn(|this, cx| async move {
4432 if !request.check_capabilities(language_server.capabilities()) {
4433 return Ok(Default::default());
4434 }
4435
4436 let response = language_server
4437 .request::<R::LspRequest>(lsp_params)
4438 .await
4439 .context("lsp request failed")?;
4440 request
4441 .response_from_lsp(
4442 response,
4443 this,
4444 buffer_handle,
4445 language_server.server_id(),
4446 cx,
4447 )
4448 .await
4449 });
4450 }
4451 } else if let Some(project_id) = self.remote_id() {
4452 let rpc = self.client.clone();
4453 let message = request.to_proto(project_id, buffer);
4454 return cx.spawn_weak(|this, cx| async move {
4455 // Ensure the project is still alive by the time the task
4456 // is scheduled.
4457 this.upgrade(&cx)
4458 .ok_or_else(|| anyhow!("project dropped"))?;
4459
4460 let response = rpc.request(message).await?;
4461
4462 let this = this
4463 .upgrade(&cx)
4464 .ok_or_else(|| anyhow!("project dropped"))?;
4465 if this.read_with(&cx, |this, _| this.is_read_only()) {
4466 Err(anyhow!("disconnected before completing request"))
4467 } else {
4468 request
4469 .response_from_proto(response, this, buffer_handle, cx)
4470 .await
4471 }
4472 });
4473 }
4474 Task::ready(Ok(Default::default()))
4475 }
4476
4477 pub fn find_or_create_local_worktree(
4478 &mut self,
4479 abs_path: impl AsRef<Path>,
4480 visible: bool,
4481 cx: &mut ModelContext<Self>,
4482 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4483 let abs_path = abs_path.as_ref();
4484 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4485 Task::ready(Ok((tree, relative_path)))
4486 } else {
4487 let worktree = self.create_local_worktree(abs_path, visible, cx);
4488 cx.foreground()
4489 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4490 }
4491 }
4492
4493 pub fn find_local_worktree(
4494 &self,
4495 abs_path: &Path,
4496 cx: &AppContext,
4497 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4498 for tree in &self.worktrees {
4499 if let Some(tree) = tree.upgrade(cx) {
4500 if let Some(relative_path) = tree
4501 .read(cx)
4502 .as_local()
4503 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4504 {
4505 return Some((tree.clone(), relative_path.into()));
4506 }
4507 }
4508 }
4509 None
4510 }
4511
4512 pub fn is_shared(&self) -> bool {
4513 match &self.client_state {
4514 Some(ProjectClientState::Local { .. }) => true,
4515 _ => false,
4516 }
4517 }
4518
4519 fn create_local_worktree(
4520 &mut self,
4521 abs_path: impl AsRef<Path>,
4522 visible: bool,
4523 cx: &mut ModelContext<Self>,
4524 ) -> Task<Result<ModelHandle<Worktree>>> {
4525 let fs = self.fs.clone();
4526 let client = self.client.clone();
4527 let next_entry_id = self.next_entry_id.clone();
4528 let path: Arc<Path> = abs_path.as_ref().into();
4529 let task = self
4530 .loading_local_worktrees
4531 .entry(path.clone())
4532 .or_insert_with(|| {
4533 cx.spawn(|project, mut cx| {
4534 async move {
4535 let worktree = Worktree::local(
4536 client.clone(),
4537 path.clone(),
4538 visible,
4539 fs,
4540 next_entry_id,
4541 &mut cx,
4542 )
4543 .await;
4544
4545 project.update(&mut cx, |project, _| {
4546 project.loading_local_worktrees.remove(&path);
4547 });
4548
4549 let worktree = worktree?;
4550 project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
4551 Ok(worktree)
4552 }
4553 .map_err(Arc::new)
4554 })
4555 .shared()
4556 })
4557 .clone();
4558 cx.foreground().spawn(async move {
4559 match task.await {
4560 Ok(worktree) => Ok(worktree),
4561 Err(err) => Err(anyhow!("{}", err)),
4562 }
4563 })
4564 }
4565
4566 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4567 self.worktrees.retain(|worktree| {
4568 if let Some(worktree) = worktree.upgrade(cx) {
4569 let id = worktree.read(cx).id();
4570 if id == id_to_remove {
4571 cx.emit(Event::WorktreeRemoved(id));
4572 false
4573 } else {
4574 true
4575 }
4576 } else {
4577 false
4578 }
4579 });
4580 self.metadata_changed(cx);
4581 }
4582
4583 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4584 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4585 if worktree.read(cx).is_local() {
4586 cx.subscribe(worktree, |this, worktree, event, cx| match event {
4587 worktree::Event::UpdatedEntries(changes) => {
4588 this.update_local_worktree_buffers(&worktree, &changes, cx);
4589 this.update_local_worktree_language_servers(&worktree, changes, cx);
4590 }
4591 worktree::Event::UpdatedGitRepositories(updated_repos) => {
4592 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4593 }
4594 })
4595 .detach();
4596 }
4597
4598 let push_strong_handle = {
4599 let worktree = worktree.read(cx);
4600 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4601 };
4602 if push_strong_handle {
4603 self.worktrees
4604 .push(WorktreeHandle::Strong(worktree.clone()));
4605 } else {
4606 self.worktrees
4607 .push(WorktreeHandle::Weak(worktree.downgrade()));
4608 }
4609
4610 cx.observe_release(worktree, |this, worktree, cx| {
4611 let _ = this.remove_worktree(worktree.id(), cx);
4612 })
4613 .detach();
4614
4615 cx.emit(Event::WorktreeAdded);
4616 self.metadata_changed(cx);
4617 }
4618
4619 fn update_local_worktree_buffers(
4620 &mut self,
4621 worktree_handle: &ModelHandle<Worktree>,
4622 changes: &HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
4623 cx: &mut ModelContext<Self>,
4624 ) {
4625 let snapshot = worktree_handle.read(cx).snapshot();
4626
4627 let mut renamed_buffers = Vec::new();
4628 for (path, entry_id) in changes.keys() {
4629 let worktree_id = worktree_handle.read(cx).id();
4630 let project_path = ProjectPath {
4631 worktree_id,
4632 path: path.clone(),
4633 };
4634
4635 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
4636 Some(&buffer_id) => buffer_id,
4637 None => match self.local_buffer_ids_by_path.get(&project_path) {
4638 Some(&buffer_id) => buffer_id,
4639 None => continue,
4640 },
4641 };
4642
4643 let open_buffer = self.opened_buffers.get(&buffer_id);
4644 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
4645 buffer
4646 } else {
4647 self.opened_buffers.remove(&buffer_id);
4648 self.local_buffer_ids_by_path.remove(&project_path);
4649 self.local_buffer_ids_by_entry_id.remove(entry_id);
4650 continue;
4651 };
4652
4653 buffer.update(cx, |buffer, cx| {
4654 if let Some(old_file) = File::from_dyn(buffer.file()) {
4655 if old_file.worktree != *worktree_handle {
4656 return;
4657 }
4658
4659 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
4660 File {
4661 is_local: true,
4662 entry_id: entry.id,
4663 mtime: entry.mtime,
4664 path: entry.path.clone(),
4665 worktree: worktree_handle.clone(),
4666 is_deleted: false,
4667 }
4668 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
4669 File {
4670 is_local: true,
4671 entry_id: entry.id,
4672 mtime: entry.mtime,
4673 path: entry.path.clone(),
4674 worktree: worktree_handle.clone(),
4675 is_deleted: false,
4676 }
4677 } else {
4678 File {
4679 is_local: true,
4680 entry_id: old_file.entry_id,
4681 path: old_file.path().clone(),
4682 mtime: old_file.mtime(),
4683 worktree: worktree_handle.clone(),
4684 is_deleted: true,
4685 }
4686 };
4687
4688 let old_path = old_file.abs_path(cx);
4689 if new_file.abs_path(cx) != old_path {
4690 renamed_buffers.push((cx.handle(), old_file.clone()));
4691 self.local_buffer_ids_by_path.remove(&project_path);
4692 self.local_buffer_ids_by_path.insert(
4693 ProjectPath {
4694 worktree_id,
4695 path: path.clone(),
4696 },
4697 buffer_id,
4698 );
4699 }
4700
4701 if new_file.entry_id != *entry_id {
4702 self.local_buffer_ids_by_entry_id.remove(entry_id);
4703 self.local_buffer_ids_by_entry_id
4704 .insert(new_file.entry_id, buffer_id);
4705 }
4706
4707 if new_file != *old_file {
4708 if let Some(project_id) = self.remote_id() {
4709 self.client
4710 .send(proto::UpdateBufferFile {
4711 project_id,
4712 buffer_id: buffer_id as u64,
4713 file: Some(new_file.to_proto()),
4714 })
4715 .log_err();
4716 }
4717
4718 buffer.file_updated(Arc::new(new_file), cx).detach();
4719 }
4720 }
4721 });
4722 }
4723
4724 for (buffer, old_file) in renamed_buffers {
4725 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
4726 self.detect_language_for_buffer(&buffer, cx);
4727 self.register_buffer_with_language_servers(&buffer, cx);
4728 }
4729 }
4730
4731 fn update_local_worktree_language_servers(
4732 &mut self,
4733 worktree_handle: &ModelHandle<Worktree>,
4734 changes: &HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
4735 cx: &mut ModelContext<Self>,
4736 ) {
4737 if changes.is_empty() {
4738 return;
4739 }
4740
4741 let worktree_id = worktree_handle.read(cx).id();
4742 let mut language_server_ids = self
4743 .language_server_ids
4744 .iter()
4745 .filter_map(|((server_worktree_id, _), server_id)| {
4746 (*server_worktree_id == worktree_id).then_some(*server_id)
4747 })
4748 .collect::<Vec<_>>();
4749 language_server_ids.sort();
4750 language_server_ids.dedup();
4751
4752 let abs_path = worktree_handle.read(cx).abs_path();
4753 for server_id in &language_server_ids {
4754 if let Some(server) = self.language_servers.get(server_id) {
4755 if let LanguageServerState::Running {
4756 server,
4757 watched_paths,
4758 ..
4759 } = server
4760 {
4761 if let Some(watched_paths) = watched_paths.get(&worktree_id) {
4762 let params = lsp::DidChangeWatchedFilesParams {
4763 changes: changes
4764 .iter()
4765 .filter_map(|((path, _), change)| {
4766 if watched_paths.is_match(&path) {
4767 Some(lsp::FileEvent {
4768 uri: lsp::Url::from_file_path(abs_path.join(path))
4769 .unwrap(),
4770 typ: match change {
4771 PathChange::Added => lsp::FileChangeType::CREATED,
4772 PathChange::Removed => lsp::FileChangeType::DELETED,
4773 PathChange::Updated
4774 | PathChange::AddedOrUpdated => {
4775 lsp::FileChangeType::CHANGED
4776 }
4777 },
4778 })
4779 } else {
4780 None
4781 }
4782 })
4783 .collect(),
4784 };
4785
4786 if !params.changes.is_empty() {
4787 server
4788 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
4789 .log_err();
4790 }
4791 }
4792 }
4793 }
4794 }
4795 }
4796
4797 fn update_local_worktree_buffers_git_repos(
4798 &mut self,
4799 worktree_handle: ModelHandle<Worktree>,
4800 repos: &HashMap<Arc<Path>, LocalRepositoryEntry>,
4801 cx: &mut ModelContext<Self>,
4802 ) {
4803 debug_assert!(worktree_handle.read(cx).is_local());
4804
4805 for (_, buffer) in &self.opened_buffers {
4806 if let Some(buffer) = buffer.upgrade(cx) {
4807 let file = match File::from_dyn(buffer.read(cx).file()) {
4808 Some(file) => file,
4809 None => continue,
4810 };
4811 if file.worktree != worktree_handle {
4812 continue;
4813 }
4814
4815 let path = file.path().clone();
4816
4817 let worktree = worktree_handle.read(cx);
4818
4819 let (work_directory, repo) = match repos
4820 .iter()
4821 .find(|(work_directory, _)| path.starts_with(work_directory))
4822 {
4823 Some(repo) => repo.clone(),
4824 None => return,
4825 };
4826
4827 let relative_repo = match path.strip_prefix(work_directory).log_err() {
4828 Some(relative_repo) => relative_repo.to_owned(),
4829 None => return,
4830 };
4831
4832 drop(worktree);
4833
4834 let remote_id = self.remote_id();
4835 let client = self.client.clone();
4836 let git_ptr = repo.repo_ptr.clone();
4837 let diff_base_task = cx
4838 .background()
4839 .spawn(async move { git_ptr.lock().load_index_text(&relative_repo) });
4840
4841 cx.spawn(|_, mut cx| async move {
4842 let diff_base = diff_base_task.await;
4843
4844 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4845 buffer.set_diff_base(diff_base.clone(), cx);
4846 buffer.remote_id()
4847 });
4848
4849 if let Some(project_id) = remote_id {
4850 client
4851 .send(proto::UpdateDiffBase {
4852 project_id,
4853 buffer_id: buffer_id as u64,
4854 diff_base,
4855 })
4856 .log_err();
4857 }
4858 })
4859 .detach();
4860 }
4861 }
4862 }
4863
4864 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4865 let new_active_entry = entry.and_then(|project_path| {
4866 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4867 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4868 Some(entry.id)
4869 });
4870 if new_active_entry != self.active_entry {
4871 self.active_entry = new_active_entry;
4872 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4873 }
4874 }
4875
4876 pub fn language_servers_running_disk_based_diagnostics(
4877 &self,
4878 ) -> impl Iterator<Item = LanguageServerId> + '_ {
4879 self.language_server_statuses
4880 .iter()
4881 .filter_map(|(id, status)| {
4882 if status.has_pending_diagnostic_updates {
4883 Some(*id)
4884 } else {
4885 None
4886 }
4887 })
4888 }
4889
4890 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4891 let mut summary = DiagnosticSummary::default();
4892 for (_, _, path_summary) in self.diagnostic_summaries(cx) {
4893 summary.error_count += path_summary.error_count;
4894 summary.warning_count += path_summary.warning_count;
4895 }
4896 summary
4897 }
4898
4899 pub fn diagnostic_summaries<'a>(
4900 &'a self,
4901 cx: &'a AppContext,
4902 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4903 self.visible_worktrees(cx).flat_map(move |worktree| {
4904 let worktree = worktree.read(cx);
4905 let worktree_id = worktree.id();
4906 worktree
4907 .diagnostic_summaries()
4908 .map(move |(path, server_id, summary)| {
4909 (ProjectPath { worktree_id, path }, server_id, summary)
4910 })
4911 })
4912 }
4913
4914 pub fn disk_based_diagnostics_started(
4915 &mut self,
4916 language_server_id: LanguageServerId,
4917 cx: &mut ModelContext<Self>,
4918 ) {
4919 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4920 }
4921
4922 pub fn disk_based_diagnostics_finished(
4923 &mut self,
4924 language_server_id: LanguageServerId,
4925 cx: &mut ModelContext<Self>,
4926 ) {
4927 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4928 }
4929
4930 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4931 self.active_entry
4932 }
4933
4934 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4935 self.worktree_for_id(path.worktree_id, cx)?
4936 .read(cx)
4937 .entry_for_path(&path.path)
4938 .cloned()
4939 }
4940
4941 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4942 let worktree = self.worktree_for_entry(entry_id, cx)?;
4943 let worktree = worktree.read(cx);
4944 let worktree_id = worktree.id();
4945 let path = worktree.entry_for_id(entry_id)?.path.clone();
4946 Some(ProjectPath { worktree_id, path })
4947 }
4948
4949 // RPC message handlers
4950
4951 async fn handle_unshare_project(
4952 this: ModelHandle<Self>,
4953 _: TypedEnvelope<proto::UnshareProject>,
4954 _: Arc<Client>,
4955 mut cx: AsyncAppContext,
4956 ) -> Result<()> {
4957 this.update(&mut cx, |this, cx| {
4958 if this.is_local() {
4959 this.unshare(cx)?;
4960 } else {
4961 this.disconnected_from_host(cx);
4962 }
4963 Ok(())
4964 })
4965 }
4966
4967 async fn handle_add_collaborator(
4968 this: ModelHandle<Self>,
4969 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4970 _: Arc<Client>,
4971 mut cx: AsyncAppContext,
4972 ) -> Result<()> {
4973 let collaborator = envelope
4974 .payload
4975 .collaborator
4976 .take()
4977 .ok_or_else(|| anyhow!("empty collaborator"))?;
4978
4979 let collaborator = Collaborator::from_proto(collaborator)?;
4980 this.update(&mut cx, |this, cx| {
4981 this.shared_buffers.remove(&collaborator.peer_id);
4982 this.collaborators
4983 .insert(collaborator.peer_id, collaborator);
4984 cx.notify();
4985 });
4986
4987 Ok(())
4988 }
4989
4990 async fn handle_update_project_collaborator(
4991 this: ModelHandle<Self>,
4992 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4993 _: Arc<Client>,
4994 mut cx: AsyncAppContext,
4995 ) -> Result<()> {
4996 let old_peer_id = envelope
4997 .payload
4998 .old_peer_id
4999 .ok_or_else(|| anyhow!("missing old peer id"))?;
5000 let new_peer_id = envelope
5001 .payload
5002 .new_peer_id
5003 .ok_or_else(|| anyhow!("missing new peer id"))?;
5004 this.update(&mut cx, |this, cx| {
5005 let collaborator = this
5006 .collaborators
5007 .remove(&old_peer_id)
5008 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
5009 let is_host = collaborator.replica_id == 0;
5010 this.collaborators.insert(new_peer_id, collaborator);
5011
5012 let buffers = this.shared_buffers.remove(&old_peer_id);
5013 log::info!(
5014 "peer {} became {}. moving buffers {:?}",
5015 old_peer_id,
5016 new_peer_id,
5017 &buffers
5018 );
5019 if let Some(buffers) = buffers {
5020 this.shared_buffers.insert(new_peer_id, buffers);
5021 }
5022
5023 if is_host {
5024 this.opened_buffers
5025 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
5026 this.buffer_ordered_messages_tx
5027 .unbounded_send(BufferOrderedMessage::Resync)
5028 .unwrap();
5029 }
5030
5031 cx.emit(Event::CollaboratorUpdated {
5032 old_peer_id,
5033 new_peer_id,
5034 });
5035 cx.notify();
5036 Ok(())
5037 })
5038 }
5039
5040 async fn handle_remove_collaborator(
5041 this: ModelHandle<Self>,
5042 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5043 _: Arc<Client>,
5044 mut cx: AsyncAppContext,
5045 ) -> Result<()> {
5046 this.update(&mut cx, |this, cx| {
5047 let peer_id = envelope
5048 .payload
5049 .peer_id
5050 .ok_or_else(|| anyhow!("invalid peer id"))?;
5051 let replica_id = this
5052 .collaborators
5053 .remove(&peer_id)
5054 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
5055 .replica_id;
5056 for buffer in this.opened_buffers.values() {
5057 if let Some(buffer) = buffer.upgrade(cx) {
5058 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5059 }
5060 }
5061 this.shared_buffers.remove(&peer_id);
5062
5063 cx.emit(Event::CollaboratorLeft(peer_id));
5064 cx.notify();
5065 Ok(())
5066 })
5067 }
5068
5069 async fn handle_update_project(
5070 this: ModelHandle<Self>,
5071 envelope: TypedEnvelope<proto::UpdateProject>,
5072 _: Arc<Client>,
5073 mut cx: AsyncAppContext,
5074 ) -> Result<()> {
5075 this.update(&mut cx, |this, cx| {
5076 // Don't handle messages that were sent before the response to us joining the project
5077 if envelope.message_id > this.join_project_response_message_id {
5078 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5079 }
5080 Ok(())
5081 })
5082 }
5083
5084 async fn handle_update_worktree(
5085 this: ModelHandle<Self>,
5086 envelope: TypedEnvelope<proto::UpdateWorktree>,
5087 _: Arc<Client>,
5088 mut cx: AsyncAppContext,
5089 ) -> Result<()> {
5090 this.update(&mut cx, |this, cx| {
5091 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5092 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5093 worktree.update(cx, |worktree, _| {
5094 let worktree = worktree.as_remote_mut().unwrap();
5095 worktree.update_from_remote(envelope.payload);
5096 });
5097 }
5098 Ok(())
5099 })
5100 }
5101
5102 async fn handle_create_project_entry(
5103 this: ModelHandle<Self>,
5104 envelope: TypedEnvelope<proto::CreateProjectEntry>,
5105 _: Arc<Client>,
5106 mut cx: AsyncAppContext,
5107 ) -> Result<proto::ProjectEntryResponse> {
5108 let worktree = this.update(&mut cx, |this, cx| {
5109 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5110 this.worktree_for_id(worktree_id, cx)
5111 .ok_or_else(|| anyhow!("worktree not found"))
5112 })?;
5113 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5114 let entry = worktree
5115 .update(&mut cx, |worktree, cx| {
5116 let worktree = worktree.as_local_mut().unwrap();
5117 let path = PathBuf::from(envelope.payload.path);
5118 worktree.create_entry(path, envelope.payload.is_directory, cx)
5119 })
5120 .await?;
5121 Ok(proto::ProjectEntryResponse {
5122 entry: Some((&entry).into()),
5123 worktree_scan_id: worktree_scan_id as u64,
5124 })
5125 }
5126
5127 async fn handle_rename_project_entry(
5128 this: ModelHandle<Self>,
5129 envelope: TypedEnvelope<proto::RenameProjectEntry>,
5130 _: Arc<Client>,
5131 mut cx: AsyncAppContext,
5132 ) -> Result<proto::ProjectEntryResponse> {
5133 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5134 let worktree = this.read_with(&cx, |this, cx| {
5135 this.worktree_for_entry(entry_id, cx)
5136 .ok_or_else(|| anyhow!("worktree not found"))
5137 })?;
5138 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5139 let entry = worktree
5140 .update(&mut cx, |worktree, cx| {
5141 let new_path = PathBuf::from(envelope.payload.new_path);
5142 worktree
5143 .as_local_mut()
5144 .unwrap()
5145 .rename_entry(entry_id, new_path, cx)
5146 .ok_or_else(|| anyhow!("invalid entry"))
5147 })?
5148 .await?;
5149 Ok(proto::ProjectEntryResponse {
5150 entry: Some((&entry).into()),
5151 worktree_scan_id: worktree_scan_id as u64,
5152 })
5153 }
5154
5155 async fn handle_copy_project_entry(
5156 this: ModelHandle<Self>,
5157 envelope: TypedEnvelope<proto::CopyProjectEntry>,
5158 _: Arc<Client>,
5159 mut cx: AsyncAppContext,
5160 ) -> Result<proto::ProjectEntryResponse> {
5161 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5162 let worktree = this.read_with(&cx, |this, cx| {
5163 this.worktree_for_entry(entry_id, cx)
5164 .ok_or_else(|| anyhow!("worktree not found"))
5165 })?;
5166 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5167 let entry = worktree
5168 .update(&mut cx, |worktree, cx| {
5169 let new_path = PathBuf::from(envelope.payload.new_path);
5170 worktree
5171 .as_local_mut()
5172 .unwrap()
5173 .copy_entry(entry_id, new_path, cx)
5174 .ok_or_else(|| anyhow!("invalid entry"))
5175 })?
5176 .await?;
5177 Ok(proto::ProjectEntryResponse {
5178 entry: Some((&entry).into()),
5179 worktree_scan_id: worktree_scan_id as u64,
5180 })
5181 }
5182
5183 async fn handle_delete_project_entry(
5184 this: ModelHandle<Self>,
5185 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5186 _: Arc<Client>,
5187 mut cx: AsyncAppContext,
5188 ) -> Result<proto::ProjectEntryResponse> {
5189 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5190 let worktree = this.read_with(&cx, |this, cx| {
5191 this.worktree_for_entry(entry_id, cx)
5192 .ok_or_else(|| anyhow!("worktree not found"))
5193 })?;
5194 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5195 worktree
5196 .update(&mut cx, |worktree, cx| {
5197 worktree
5198 .as_local_mut()
5199 .unwrap()
5200 .delete_entry(entry_id, cx)
5201 .ok_or_else(|| anyhow!("invalid entry"))
5202 })?
5203 .await?;
5204 Ok(proto::ProjectEntryResponse {
5205 entry: None,
5206 worktree_scan_id: worktree_scan_id as u64,
5207 })
5208 }
5209
5210 async fn handle_update_diagnostic_summary(
5211 this: ModelHandle<Self>,
5212 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5213 _: Arc<Client>,
5214 mut cx: AsyncAppContext,
5215 ) -> Result<()> {
5216 this.update(&mut cx, |this, cx| {
5217 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5218 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5219 if let Some(summary) = envelope.payload.summary {
5220 let project_path = ProjectPath {
5221 worktree_id,
5222 path: Path::new(&summary.path).into(),
5223 };
5224 worktree.update(cx, |worktree, _| {
5225 worktree
5226 .as_remote_mut()
5227 .unwrap()
5228 .update_diagnostic_summary(project_path.path.clone(), &summary);
5229 });
5230 cx.emit(Event::DiagnosticsUpdated {
5231 language_server_id: LanguageServerId(summary.language_server_id as usize),
5232 path: project_path,
5233 });
5234 }
5235 }
5236 Ok(())
5237 })
5238 }
5239
5240 async fn handle_start_language_server(
5241 this: ModelHandle<Self>,
5242 envelope: TypedEnvelope<proto::StartLanguageServer>,
5243 _: Arc<Client>,
5244 mut cx: AsyncAppContext,
5245 ) -> Result<()> {
5246 let server = envelope
5247 .payload
5248 .server
5249 .ok_or_else(|| anyhow!("invalid server"))?;
5250 this.update(&mut cx, |this, cx| {
5251 this.language_server_statuses.insert(
5252 LanguageServerId(server.id as usize),
5253 LanguageServerStatus {
5254 name: server.name,
5255 pending_work: Default::default(),
5256 has_pending_diagnostic_updates: false,
5257 progress_tokens: Default::default(),
5258 },
5259 );
5260 cx.notify();
5261 });
5262 Ok(())
5263 }
5264
5265 async fn handle_update_language_server(
5266 this: ModelHandle<Self>,
5267 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5268 _: Arc<Client>,
5269 mut cx: AsyncAppContext,
5270 ) -> Result<()> {
5271 this.update(&mut cx, |this, cx| {
5272 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
5273
5274 match envelope
5275 .payload
5276 .variant
5277 .ok_or_else(|| anyhow!("invalid variant"))?
5278 {
5279 proto::update_language_server::Variant::WorkStart(payload) => {
5280 this.on_lsp_work_start(
5281 language_server_id,
5282 payload.token,
5283 LanguageServerProgress {
5284 message: payload.message,
5285 percentage: payload.percentage.map(|p| p as usize),
5286 last_update_at: Instant::now(),
5287 },
5288 cx,
5289 );
5290 }
5291
5292 proto::update_language_server::Variant::WorkProgress(payload) => {
5293 this.on_lsp_work_progress(
5294 language_server_id,
5295 payload.token,
5296 LanguageServerProgress {
5297 message: payload.message,
5298 percentage: payload.percentage.map(|p| p as usize),
5299 last_update_at: Instant::now(),
5300 },
5301 cx,
5302 );
5303 }
5304
5305 proto::update_language_server::Variant::WorkEnd(payload) => {
5306 this.on_lsp_work_end(language_server_id, payload.token, cx);
5307 }
5308
5309 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5310 this.disk_based_diagnostics_started(language_server_id, cx);
5311 }
5312
5313 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5314 this.disk_based_diagnostics_finished(language_server_id, cx)
5315 }
5316 }
5317
5318 Ok(())
5319 })
5320 }
5321
5322 async fn handle_update_buffer(
5323 this: ModelHandle<Self>,
5324 envelope: TypedEnvelope<proto::UpdateBuffer>,
5325 _: Arc<Client>,
5326 mut cx: AsyncAppContext,
5327 ) -> Result<proto::Ack> {
5328 this.update(&mut cx, |this, cx| {
5329 let payload = envelope.payload.clone();
5330 let buffer_id = payload.buffer_id;
5331 let ops = payload
5332 .operations
5333 .into_iter()
5334 .map(language::proto::deserialize_operation)
5335 .collect::<Result<Vec<_>, _>>()?;
5336 let is_remote = this.is_remote();
5337 match this.opened_buffers.entry(buffer_id) {
5338 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5339 OpenBuffer::Strong(buffer) => {
5340 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5341 }
5342 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5343 OpenBuffer::Weak(_) => {}
5344 },
5345 hash_map::Entry::Vacant(e) => {
5346 assert!(
5347 is_remote,
5348 "received buffer update from {:?}",
5349 envelope.original_sender_id
5350 );
5351 e.insert(OpenBuffer::Operations(ops));
5352 }
5353 }
5354 Ok(proto::Ack {})
5355 })
5356 }
5357
5358 async fn handle_create_buffer_for_peer(
5359 this: ModelHandle<Self>,
5360 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5361 _: Arc<Client>,
5362 mut cx: AsyncAppContext,
5363 ) -> Result<()> {
5364 this.update(&mut cx, |this, cx| {
5365 match envelope
5366 .payload
5367 .variant
5368 .ok_or_else(|| anyhow!("missing variant"))?
5369 {
5370 proto::create_buffer_for_peer::Variant::State(mut state) => {
5371 let mut buffer_file = None;
5372 if let Some(file) = state.file.take() {
5373 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5374 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5375 anyhow!("no worktree found for id {}", file.worktree_id)
5376 })?;
5377 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5378 as Arc<dyn language::File>);
5379 }
5380
5381 let buffer_id = state.id;
5382 let buffer = cx.add_model(|_| {
5383 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5384 });
5385 this.incomplete_remote_buffers
5386 .insert(buffer_id, Some(buffer));
5387 }
5388 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5389 let buffer = this
5390 .incomplete_remote_buffers
5391 .get(&chunk.buffer_id)
5392 .cloned()
5393 .flatten()
5394 .ok_or_else(|| {
5395 anyhow!(
5396 "received chunk for buffer {} without initial state",
5397 chunk.buffer_id
5398 )
5399 })?;
5400 let operations = chunk
5401 .operations
5402 .into_iter()
5403 .map(language::proto::deserialize_operation)
5404 .collect::<Result<Vec<_>>>()?;
5405 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5406
5407 if chunk.is_last {
5408 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5409 this.register_buffer(&buffer, cx)?;
5410 }
5411 }
5412 }
5413
5414 Ok(())
5415 })
5416 }
5417
5418 async fn handle_update_diff_base(
5419 this: ModelHandle<Self>,
5420 envelope: TypedEnvelope<proto::UpdateDiffBase>,
5421 _: Arc<Client>,
5422 mut cx: AsyncAppContext,
5423 ) -> Result<()> {
5424 this.update(&mut cx, |this, cx| {
5425 let buffer_id = envelope.payload.buffer_id;
5426 let diff_base = envelope.payload.diff_base;
5427 if let Some(buffer) = this
5428 .opened_buffers
5429 .get_mut(&buffer_id)
5430 .and_then(|b| b.upgrade(cx))
5431 .or_else(|| {
5432 this.incomplete_remote_buffers
5433 .get(&buffer_id)
5434 .cloned()
5435 .flatten()
5436 })
5437 {
5438 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5439 }
5440 Ok(())
5441 })
5442 }
5443
5444 async fn handle_update_buffer_file(
5445 this: ModelHandle<Self>,
5446 envelope: TypedEnvelope<proto::UpdateBufferFile>,
5447 _: Arc<Client>,
5448 mut cx: AsyncAppContext,
5449 ) -> Result<()> {
5450 let buffer_id = envelope.payload.buffer_id;
5451
5452 this.update(&mut cx, |this, cx| {
5453 let payload = envelope.payload.clone();
5454 if let Some(buffer) = this
5455 .opened_buffers
5456 .get(&buffer_id)
5457 .and_then(|b| b.upgrade(cx))
5458 .or_else(|| {
5459 this.incomplete_remote_buffers
5460 .get(&buffer_id)
5461 .cloned()
5462 .flatten()
5463 })
5464 {
5465 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5466 let worktree = this
5467 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5468 .ok_or_else(|| anyhow!("no such worktree"))?;
5469 let file = File::from_proto(file, worktree, cx)?;
5470 buffer.update(cx, |buffer, cx| {
5471 buffer.file_updated(Arc::new(file), cx).detach();
5472 });
5473 this.detect_language_for_buffer(&buffer, cx);
5474 }
5475 Ok(())
5476 })
5477 }
5478
5479 async fn handle_save_buffer(
5480 this: ModelHandle<Self>,
5481 envelope: TypedEnvelope<proto::SaveBuffer>,
5482 _: Arc<Client>,
5483 mut cx: AsyncAppContext,
5484 ) -> Result<proto::BufferSaved> {
5485 let buffer_id = envelope.payload.buffer_id;
5486 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5487 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5488 let buffer = this
5489 .opened_buffers
5490 .get(&buffer_id)
5491 .and_then(|buffer| buffer.upgrade(cx))
5492 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5493 anyhow::Ok((project_id, buffer))
5494 })?;
5495 buffer
5496 .update(&mut cx, |buffer, _| {
5497 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
5498 })
5499 .await?;
5500 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
5501
5502 let (saved_version, fingerprint, mtime) = this
5503 .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5504 .await?;
5505 Ok(proto::BufferSaved {
5506 project_id,
5507 buffer_id,
5508 version: serialize_version(&saved_version),
5509 mtime: Some(mtime.into()),
5510 fingerprint: language::proto::serialize_fingerprint(fingerprint),
5511 })
5512 }
5513
5514 async fn handle_reload_buffers(
5515 this: ModelHandle<Self>,
5516 envelope: TypedEnvelope<proto::ReloadBuffers>,
5517 _: Arc<Client>,
5518 mut cx: AsyncAppContext,
5519 ) -> Result<proto::ReloadBuffersResponse> {
5520 let sender_id = envelope.original_sender_id()?;
5521 let reload = this.update(&mut cx, |this, cx| {
5522 let mut buffers = HashSet::default();
5523 for buffer_id in &envelope.payload.buffer_ids {
5524 buffers.insert(
5525 this.opened_buffers
5526 .get(buffer_id)
5527 .and_then(|buffer| buffer.upgrade(cx))
5528 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5529 );
5530 }
5531 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5532 })?;
5533
5534 let project_transaction = reload.await?;
5535 let project_transaction = this.update(&mut cx, |this, cx| {
5536 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5537 });
5538 Ok(proto::ReloadBuffersResponse {
5539 transaction: Some(project_transaction),
5540 })
5541 }
5542
5543 async fn handle_synchronize_buffers(
5544 this: ModelHandle<Self>,
5545 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5546 _: Arc<Client>,
5547 mut cx: AsyncAppContext,
5548 ) -> Result<proto::SynchronizeBuffersResponse> {
5549 let project_id = envelope.payload.project_id;
5550 let mut response = proto::SynchronizeBuffersResponse {
5551 buffers: Default::default(),
5552 };
5553
5554 this.update(&mut cx, |this, cx| {
5555 let Some(guest_id) = envelope.original_sender_id else {
5556 log::error!("missing original_sender_id on SynchronizeBuffers request");
5557 return;
5558 };
5559
5560 this.shared_buffers.entry(guest_id).or_default().clear();
5561 for buffer in envelope.payload.buffers {
5562 let buffer_id = buffer.id;
5563 let remote_version = language::proto::deserialize_version(&buffer.version);
5564 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5565 this.shared_buffers
5566 .entry(guest_id)
5567 .or_default()
5568 .insert(buffer_id);
5569
5570 let buffer = buffer.read(cx);
5571 response.buffers.push(proto::BufferVersion {
5572 id: buffer_id,
5573 version: language::proto::serialize_version(&buffer.version),
5574 });
5575
5576 let operations = buffer.serialize_ops(Some(remote_version), cx);
5577 let client = this.client.clone();
5578 if let Some(file) = buffer.file() {
5579 client
5580 .send(proto::UpdateBufferFile {
5581 project_id,
5582 buffer_id: buffer_id as u64,
5583 file: Some(file.to_proto()),
5584 })
5585 .log_err();
5586 }
5587
5588 client
5589 .send(proto::UpdateDiffBase {
5590 project_id,
5591 buffer_id: buffer_id as u64,
5592 diff_base: buffer.diff_base().map(Into::into),
5593 })
5594 .log_err();
5595
5596 client
5597 .send(proto::BufferReloaded {
5598 project_id,
5599 buffer_id,
5600 version: language::proto::serialize_version(buffer.saved_version()),
5601 mtime: Some(buffer.saved_mtime().into()),
5602 fingerprint: language::proto::serialize_fingerprint(
5603 buffer.saved_version_fingerprint(),
5604 ),
5605 line_ending: language::proto::serialize_line_ending(
5606 buffer.line_ending(),
5607 ) as i32,
5608 })
5609 .log_err();
5610
5611 cx.background()
5612 .spawn(
5613 async move {
5614 let operations = operations.await;
5615 for chunk in split_operations(operations) {
5616 client
5617 .request(proto::UpdateBuffer {
5618 project_id,
5619 buffer_id,
5620 operations: chunk,
5621 })
5622 .await?;
5623 }
5624 anyhow::Ok(())
5625 }
5626 .log_err(),
5627 )
5628 .detach();
5629 }
5630 }
5631 });
5632
5633 Ok(response)
5634 }
5635
5636 async fn handle_format_buffers(
5637 this: ModelHandle<Self>,
5638 envelope: TypedEnvelope<proto::FormatBuffers>,
5639 _: Arc<Client>,
5640 mut cx: AsyncAppContext,
5641 ) -> Result<proto::FormatBuffersResponse> {
5642 let sender_id = envelope.original_sender_id()?;
5643 let format = this.update(&mut cx, |this, cx| {
5644 let mut buffers = HashSet::default();
5645 for buffer_id in &envelope.payload.buffer_ids {
5646 buffers.insert(
5647 this.opened_buffers
5648 .get(buffer_id)
5649 .and_then(|buffer| buffer.upgrade(cx))
5650 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5651 );
5652 }
5653 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5654 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5655 })?;
5656
5657 let project_transaction = format.await?;
5658 let project_transaction = this.update(&mut cx, |this, cx| {
5659 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5660 });
5661 Ok(proto::FormatBuffersResponse {
5662 transaction: Some(project_transaction),
5663 })
5664 }
5665
5666 async fn handle_apply_additional_edits_for_completion(
5667 this: ModelHandle<Self>,
5668 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5669 _: Arc<Client>,
5670 mut cx: AsyncAppContext,
5671 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5672 let (buffer, completion) = this.update(&mut cx, |this, cx| {
5673 let buffer = this
5674 .opened_buffers
5675 .get(&envelope.payload.buffer_id)
5676 .and_then(|buffer| buffer.upgrade(cx))
5677 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5678 let language = buffer.read(cx).language();
5679 let completion = language::proto::deserialize_completion(
5680 envelope
5681 .payload
5682 .completion
5683 .ok_or_else(|| anyhow!("invalid completion"))?,
5684 language.cloned(),
5685 );
5686 Ok::<_, anyhow::Error>((buffer, completion))
5687 })?;
5688
5689 let completion = completion.await?;
5690
5691 let apply_additional_edits = this.update(&mut cx, |this, cx| {
5692 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5693 });
5694
5695 Ok(proto::ApplyCompletionAdditionalEditsResponse {
5696 transaction: apply_additional_edits
5697 .await?
5698 .as_ref()
5699 .map(language::proto::serialize_transaction),
5700 })
5701 }
5702
5703 async fn handle_apply_code_action(
5704 this: ModelHandle<Self>,
5705 envelope: TypedEnvelope<proto::ApplyCodeAction>,
5706 _: Arc<Client>,
5707 mut cx: AsyncAppContext,
5708 ) -> Result<proto::ApplyCodeActionResponse> {
5709 let sender_id = envelope.original_sender_id()?;
5710 let action = language::proto::deserialize_code_action(
5711 envelope
5712 .payload
5713 .action
5714 .ok_or_else(|| anyhow!("invalid action"))?,
5715 )?;
5716 let apply_code_action = this.update(&mut cx, |this, cx| {
5717 let buffer = this
5718 .opened_buffers
5719 .get(&envelope.payload.buffer_id)
5720 .and_then(|buffer| buffer.upgrade(cx))
5721 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5722 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5723 })?;
5724
5725 let project_transaction = apply_code_action.await?;
5726 let project_transaction = this.update(&mut cx, |this, cx| {
5727 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5728 });
5729 Ok(proto::ApplyCodeActionResponse {
5730 transaction: Some(project_transaction),
5731 })
5732 }
5733
5734 async fn handle_lsp_command<T: LspCommand>(
5735 this: ModelHandle<Self>,
5736 envelope: TypedEnvelope<T::ProtoRequest>,
5737 _: Arc<Client>,
5738 mut cx: AsyncAppContext,
5739 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5740 where
5741 <T::LspRequest as lsp::request::Request>::Result: Send,
5742 {
5743 let sender_id = envelope.original_sender_id()?;
5744 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5745 let buffer_handle = this.read_with(&cx, |this, _| {
5746 this.opened_buffers
5747 .get(&buffer_id)
5748 .and_then(|buffer| buffer.upgrade(&cx))
5749 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5750 })?;
5751 let request = T::from_proto(
5752 envelope.payload,
5753 this.clone(),
5754 buffer_handle.clone(),
5755 cx.clone(),
5756 )
5757 .await?;
5758 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5759 let response = this
5760 .update(&mut cx, |this, cx| {
5761 this.request_lsp(buffer_handle, request, cx)
5762 })
5763 .await?;
5764 this.update(&mut cx, |this, cx| {
5765 Ok(T::response_to_proto(
5766 response,
5767 this,
5768 sender_id,
5769 &buffer_version,
5770 cx,
5771 ))
5772 })
5773 }
5774
5775 async fn handle_get_project_symbols(
5776 this: ModelHandle<Self>,
5777 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5778 _: Arc<Client>,
5779 mut cx: AsyncAppContext,
5780 ) -> Result<proto::GetProjectSymbolsResponse> {
5781 let symbols = this
5782 .update(&mut cx, |this, cx| {
5783 this.symbols(&envelope.payload.query, cx)
5784 })
5785 .await?;
5786
5787 Ok(proto::GetProjectSymbolsResponse {
5788 symbols: symbols.iter().map(serialize_symbol).collect(),
5789 })
5790 }
5791
5792 async fn handle_search_project(
5793 this: ModelHandle<Self>,
5794 envelope: TypedEnvelope<proto::SearchProject>,
5795 _: Arc<Client>,
5796 mut cx: AsyncAppContext,
5797 ) -> Result<proto::SearchProjectResponse> {
5798 let peer_id = envelope.original_sender_id()?;
5799 let query = SearchQuery::from_proto(envelope.payload)?;
5800 let result = this
5801 .update(&mut cx, |this, cx| this.search(query, cx))
5802 .await?;
5803
5804 this.update(&mut cx, |this, cx| {
5805 let mut locations = Vec::new();
5806 for (buffer, ranges) in result {
5807 for range in ranges {
5808 let start = serialize_anchor(&range.start);
5809 let end = serialize_anchor(&range.end);
5810 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5811 locations.push(proto::Location {
5812 buffer_id,
5813 start: Some(start),
5814 end: Some(end),
5815 });
5816 }
5817 }
5818 Ok(proto::SearchProjectResponse { locations })
5819 })
5820 }
5821
5822 async fn handle_open_buffer_for_symbol(
5823 this: ModelHandle<Self>,
5824 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5825 _: Arc<Client>,
5826 mut cx: AsyncAppContext,
5827 ) -> Result<proto::OpenBufferForSymbolResponse> {
5828 let peer_id = envelope.original_sender_id()?;
5829 let symbol = envelope
5830 .payload
5831 .symbol
5832 .ok_or_else(|| anyhow!("invalid symbol"))?;
5833 let symbol = this
5834 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5835 .await?;
5836 let symbol = this.read_with(&cx, |this, _| {
5837 let signature = this.symbol_signature(&symbol.path);
5838 if signature == symbol.signature {
5839 Ok(symbol)
5840 } else {
5841 Err(anyhow!("invalid symbol signature"))
5842 }
5843 })?;
5844 let buffer = this
5845 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5846 .await?;
5847
5848 Ok(proto::OpenBufferForSymbolResponse {
5849 buffer_id: this.update(&mut cx, |this, cx| {
5850 this.create_buffer_for_peer(&buffer, peer_id, cx)
5851 }),
5852 })
5853 }
5854
5855 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5856 let mut hasher = Sha256::new();
5857 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5858 hasher.update(project_path.path.to_string_lossy().as_bytes());
5859 hasher.update(self.nonce.to_be_bytes());
5860 hasher.finalize().as_slice().try_into().unwrap()
5861 }
5862
5863 async fn handle_open_buffer_by_id(
5864 this: ModelHandle<Self>,
5865 envelope: TypedEnvelope<proto::OpenBufferById>,
5866 _: Arc<Client>,
5867 mut cx: AsyncAppContext,
5868 ) -> Result<proto::OpenBufferResponse> {
5869 let peer_id = envelope.original_sender_id()?;
5870 let buffer = this
5871 .update(&mut cx, |this, cx| {
5872 this.open_buffer_by_id(envelope.payload.id, cx)
5873 })
5874 .await?;
5875 this.update(&mut cx, |this, cx| {
5876 Ok(proto::OpenBufferResponse {
5877 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5878 })
5879 })
5880 }
5881
5882 async fn handle_open_buffer_by_path(
5883 this: ModelHandle<Self>,
5884 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5885 _: Arc<Client>,
5886 mut cx: AsyncAppContext,
5887 ) -> Result<proto::OpenBufferResponse> {
5888 let peer_id = envelope.original_sender_id()?;
5889 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5890 let open_buffer = this.update(&mut cx, |this, cx| {
5891 this.open_buffer(
5892 ProjectPath {
5893 worktree_id,
5894 path: PathBuf::from(envelope.payload.path).into(),
5895 },
5896 cx,
5897 )
5898 });
5899
5900 let buffer = open_buffer.await?;
5901 this.update(&mut cx, |this, cx| {
5902 Ok(proto::OpenBufferResponse {
5903 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5904 })
5905 })
5906 }
5907
5908 fn serialize_project_transaction_for_peer(
5909 &mut self,
5910 project_transaction: ProjectTransaction,
5911 peer_id: proto::PeerId,
5912 cx: &mut AppContext,
5913 ) -> proto::ProjectTransaction {
5914 let mut serialized_transaction = proto::ProjectTransaction {
5915 buffer_ids: Default::default(),
5916 transactions: Default::default(),
5917 };
5918 for (buffer, transaction) in project_transaction.0 {
5919 serialized_transaction
5920 .buffer_ids
5921 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5922 serialized_transaction
5923 .transactions
5924 .push(language::proto::serialize_transaction(&transaction));
5925 }
5926 serialized_transaction
5927 }
5928
5929 fn deserialize_project_transaction(
5930 &mut self,
5931 message: proto::ProjectTransaction,
5932 push_to_history: bool,
5933 cx: &mut ModelContext<Self>,
5934 ) -> Task<Result<ProjectTransaction>> {
5935 cx.spawn(|this, mut cx| async move {
5936 let mut project_transaction = ProjectTransaction::default();
5937 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5938 {
5939 let buffer = this
5940 .update(&mut cx, |this, cx| {
5941 this.wait_for_remote_buffer(buffer_id, cx)
5942 })
5943 .await?;
5944 let transaction = language::proto::deserialize_transaction(transaction)?;
5945 project_transaction.0.insert(buffer, transaction);
5946 }
5947
5948 for (buffer, transaction) in &project_transaction.0 {
5949 buffer
5950 .update(&mut cx, |buffer, _| {
5951 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5952 })
5953 .await?;
5954
5955 if push_to_history {
5956 buffer.update(&mut cx, |buffer, _| {
5957 buffer.push_transaction(transaction.clone(), Instant::now());
5958 });
5959 }
5960 }
5961
5962 Ok(project_transaction)
5963 })
5964 }
5965
5966 fn create_buffer_for_peer(
5967 &mut self,
5968 buffer: &ModelHandle<Buffer>,
5969 peer_id: proto::PeerId,
5970 cx: &mut AppContext,
5971 ) -> u64 {
5972 let buffer_id = buffer.read(cx).remote_id();
5973 if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
5974 updates_tx
5975 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
5976 .ok();
5977 }
5978 buffer_id
5979 }
5980
5981 fn wait_for_remote_buffer(
5982 &mut self,
5983 id: u64,
5984 cx: &mut ModelContext<Self>,
5985 ) -> Task<Result<ModelHandle<Buffer>>> {
5986 let mut opened_buffer_rx = self.opened_buffer.1.clone();
5987
5988 cx.spawn_weak(|this, mut cx| async move {
5989 let buffer = loop {
5990 let Some(this) = this.upgrade(&cx) else {
5991 return Err(anyhow!("project dropped"));
5992 };
5993 let buffer = this.read_with(&cx, |this, cx| {
5994 this.opened_buffers
5995 .get(&id)
5996 .and_then(|buffer| buffer.upgrade(cx))
5997 });
5998 if let Some(buffer) = buffer {
5999 break buffer;
6000 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
6001 return Err(anyhow!("disconnected before buffer {} could be opened", id));
6002 }
6003
6004 this.update(&mut cx, |this, _| {
6005 this.incomplete_remote_buffers.entry(id).or_default();
6006 });
6007 drop(this);
6008 opened_buffer_rx
6009 .next()
6010 .await
6011 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
6012 };
6013 buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
6014 Ok(buffer)
6015 })
6016 }
6017
6018 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
6019 let project_id = match self.client_state.as_ref() {
6020 Some(ProjectClientState::Remote {
6021 sharing_has_stopped,
6022 remote_id,
6023 ..
6024 }) => {
6025 if *sharing_has_stopped {
6026 return Task::ready(Err(anyhow!(
6027 "can't synchronize remote buffers on a readonly project"
6028 )));
6029 } else {
6030 *remote_id
6031 }
6032 }
6033 Some(ProjectClientState::Local { .. }) | None => {
6034 return Task::ready(Err(anyhow!(
6035 "can't synchronize remote buffers on a local project"
6036 )))
6037 }
6038 };
6039
6040 let client = self.client.clone();
6041 cx.spawn(|this, cx| async move {
6042 let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
6043 let buffers = this
6044 .opened_buffers
6045 .iter()
6046 .filter_map(|(id, buffer)| {
6047 let buffer = buffer.upgrade(cx)?;
6048 Some(proto::BufferVersion {
6049 id: *id,
6050 version: language::proto::serialize_version(&buffer.read(cx).version),
6051 })
6052 })
6053 .collect();
6054 let incomplete_buffer_ids = this
6055 .incomplete_remote_buffers
6056 .keys()
6057 .copied()
6058 .collect::<Vec<_>>();
6059
6060 (buffers, incomplete_buffer_ids)
6061 });
6062 let response = client
6063 .request(proto::SynchronizeBuffers {
6064 project_id,
6065 buffers,
6066 })
6067 .await?;
6068
6069 let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
6070 let client = client.clone();
6071 let buffer_id = buffer.id;
6072 let remote_version = language::proto::deserialize_version(&buffer.version);
6073 this.read_with(&cx, |this, cx| {
6074 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6075 let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
6076 cx.background().spawn(async move {
6077 let operations = operations.await;
6078 for chunk in split_operations(operations) {
6079 client
6080 .request(proto::UpdateBuffer {
6081 project_id,
6082 buffer_id,
6083 operations: chunk,
6084 })
6085 .await?;
6086 }
6087 anyhow::Ok(())
6088 })
6089 } else {
6090 Task::ready(Ok(()))
6091 }
6092 })
6093 });
6094
6095 // Any incomplete buffers have open requests waiting. Request that the host sends
6096 // creates these buffers for us again to unblock any waiting futures.
6097 for id in incomplete_buffer_ids {
6098 cx.background()
6099 .spawn(client.request(proto::OpenBufferById { project_id, id }))
6100 .detach();
6101 }
6102
6103 futures::future::join_all(send_updates_for_buffers)
6104 .await
6105 .into_iter()
6106 .collect()
6107 })
6108 }
6109
6110 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
6111 self.worktrees(cx)
6112 .map(|worktree| {
6113 let worktree = worktree.read(cx);
6114 proto::WorktreeMetadata {
6115 id: worktree.id().to_proto(),
6116 root_name: worktree.root_name().into(),
6117 visible: worktree.is_visible(),
6118 abs_path: worktree.abs_path().to_string_lossy().into(),
6119 }
6120 })
6121 .collect()
6122 }
6123
6124 fn set_worktrees_from_proto(
6125 &mut self,
6126 worktrees: Vec<proto::WorktreeMetadata>,
6127 cx: &mut ModelContext<Project>,
6128 ) -> Result<()> {
6129 let replica_id = self.replica_id();
6130 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
6131
6132 let mut old_worktrees_by_id = self
6133 .worktrees
6134 .drain(..)
6135 .filter_map(|worktree| {
6136 let worktree = worktree.upgrade(cx)?;
6137 Some((worktree.read(cx).id(), worktree))
6138 })
6139 .collect::<HashMap<_, _>>();
6140
6141 for worktree in worktrees {
6142 if let Some(old_worktree) =
6143 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
6144 {
6145 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
6146 } else {
6147 let worktree =
6148 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
6149 let _ = self.add_worktree(&worktree, cx);
6150 }
6151 }
6152
6153 self.metadata_changed(cx);
6154 for (id, _) in old_worktrees_by_id {
6155 cx.emit(Event::WorktreeRemoved(id));
6156 }
6157
6158 Ok(())
6159 }
6160
6161 fn set_collaborators_from_proto(
6162 &mut self,
6163 messages: Vec<proto::Collaborator>,
6164 cx: &mut ModelContext<Self>,
6165 ) -> Result<()> {
6166 let mut collaborators = HashMap::default();
6167 for message in messages {
6168 let collaborator = Collaborator::from_proto(message)?;
6169 collaborators.insert(collaborator.peer_id, collaborator);
6170 }
6171 for old_peer_id in self.collaborators.keys() {
6172 if !collaborators.contains_key(old_peer_id) {
6173 cx.emit(Event::CollaboratorLeft(*old_peer_id));
6174 }
6175 }
6176 self.collaborators = collaborators;
6177 Ok(())
6178 }
6179
6180 fn deserialize_symbol(
6181 &self,
6182 serialized_symbol: proto::Symbol,
6183 ) -> impl Future<Output = Result<Symbol>> {
6184 let languages = self.languages.clone();
6185 async move {
6186 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
6187 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
6188 let start = serialized_symbol
6189 .start
6190 .ok_or_else(|| anyhow!("invalid start"))?;
6191 let end = serialized_symbol
6192 .end
6193 .ok_or_else(|| anyhow!("invalid end"))?;
6194 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
6195 let path = ProjectPath {
6196 worktree_id,
6197 path: PathBuf::from(serialized_symbol.path).into(),
6198 };
6199 let language = languages
6200 .language_for_file(&path.path, None)
6201 .await
6202 .log_err();
6203 Ok(Symbol {
6204 language_server_name: LanguageServerName(
6205 serialized_symbol.language_server_name.into(),
6206 ),
6207 source_worktree_id,
6208 path,
6209 label: {
6210 match language {
6211 Some(language) => {
6212 language
6213 .label_for_symbol(&serialized_symbol.name, kind)
6214 .await
6215 }
6216 None => None,
6217 }
6218 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
6219 },
6220
6221 name: serialized_symbol.name,
6222 range: Unclipped(PointUtf16::new(start.row, start.column))
6223 ..Unclipped(PointUtf16::new(end.row, end.column)),
6224 kind,
6225 signature: serialized_symbol
6226 .signature
6227 .try_into()
6228 .map_err(|_| anyhow!("invalid signature"))?,
6229 })
6230 }
6231 }
6232
6233 async fn handle_buffer_saved(
6234 this: ModelHandle<Self>,
6235 envelope: TypedEnvelope<proto::BufferSaved>,
6236 _: Arc<Client>,
6237 mut cx: AsyncAppContext,
6238 ) -> Result<()> {
6239 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
6240 let version = deserialize_version(&envelope.payload.version);
6241 let mtime = envelope
6242 .payload
6243 .mtime
6244 .ok_or_else(|| anyhow!("missing mtime"))?
6245 .into();
6246
6247 this.update(&mut cx, |this, cx| {
6248 let buffer = this
6249 .opened_buffers
6250 .get(&envelope.payload.buffer_id)
6251 .and_then(|buffer| buffer.upgrade(cx))
6252 .or_else(|| {
6253 this.incomplete_remote_buffers
6254 .get(&envelope.payload.buffer_id)
6255 .and_then(|b| b.clone())
6256 });
6257 if let Some(buffer) = buffer {
6258 buffer.update(cx, |buffer, cx| {
6259 buffer.did_save(version, fingerprint, mtime, cx);
6260 });
6261 }
6262 Ok(())
6263 })
6264 }
6265
6266 async fn handle_buffer_reloaded(
6267 this: ModelHandle<Self>,
6268 envelope: TypedEnvelope<proto::BufferReloaded>,
6269 _: Arc<Client>,
6270 mut cx: AsyncAppContext,
6271 ) -> Result<()> {
6272 let payload = envelope.payload;
6273 let version = deserialize_version(&payload.version);
6274 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6275 let line_ending = deserialize_line_ending(
6276 proto::LineEnding::from_i32(payload.line_ending)
6277 .ok_or_else(|| anyhow!("missing line ending"))?,
6278 );
6279 let mtime = payload
6280 .mtime
6281 .ok_or_else(|| anyhow!("missing mtime"))?
6282 .into();
6283 this.update(&mut cx, |this, cx| {
6284 let buffer = this
6285 .opened_buffers
6286 .get(&payload.buffer_id)
6287 .and_then(|buffer| buffer.upgrade(cx))
6288 .or_else(|| {
6289 this.incomplete_remote_buffers
6290 .get(&payload.buffer_id)
6291 .cloned()
6292 .flatten()
6293 });
6294 if let Some(buffer) = buffer {
6295 buffer.update(cx, |buffer, cx| {
6296 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6297 });
6298 }
6299 Ok(())
6300 })
6301 }
6302
6303 #[allow(clippy::type_complexity)]
6304 fn edits_from_lsp(
6305 &mut self,
6306 buffer: &ModelHandle<Buffer>,
6307 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6308 server_id: LanguageServerId,
6309 version: Option<i32>,
6310 cx: &mut ModelContext<Self>,
6311 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6312 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
6313 cx.background().spawn(async move {
6314 let snapshot = snapshot?;
6315 let mut lsp_edits = lsp_edits
6316 .into_iter()
6317 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6318 .collect::<Vec<_>>();
6319 lsp_edits.sort_by_key(|(range, _)| range.start);
6320
6321 let mut lsp_edits = lsp_edits.into_iter().peekable();
6322 let mut edits = Vec::new();
6323 while let Some((range, mut new_text)) = lsp_edits.next() {
6324 // Clip invalid ranges provided by the language server.
6325 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6326 ..snapshot.clip_point_utf16(range.end, Bias::Left);
6327
6328 // Combine any LSP edits that are adjacent.
6329 //
6330 // Also, combine LSP edits that are separated from each other by only
6331 // a newline. This is important because for some code actions,
6332 // Rust-analyzer rewrites the entire buffer via a series of edits that
6333 // are separated by unchanged newline characters.
6334 //
6335 // In order for the diffing logic below to work properly, any edits that
6336 // cancel each other out must be combined into one.
6337 while let Some((next_range, next_text)) = lsp_edits.peek() {
6338 if next_range.start.0 > range.end {
6339 if next_range.start.0.row > range.end.row + 1
6340 || next_range.start.0.column > 0
6341 || snapshot.clip_point_utf16(
6342 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6343 Bias::Left,
6344 ) > range.end
6345 {
6346 break;
6347 }
6348 new_text.push('\n');
6349 }
6350 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6351 new_text.push_str(next_text);
6352 lsp_edits.next();
6353 }
6354
6355 // For multiline edits, perform a diff of the old and new text so that
6356 // we can identify the changes more precisely, preserving the locations
6357 // of any anchors positioned in the unchanged regions.
6358 if range.end.row > range.start.row {
6359 let mut offset = range.start.to_offset(&snapshot);
6360 let old_text = snapshot.text_for_range(range).collect::<String>();
6361
6362 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6363 let mut moved_since_edit = true;
6364 for change in diff.iter_all_changes() {
6365 let tag = change.tag();
6366 let value = change.value();
6367 match tag {
6368 ChangeTag::Equal => {
6369 offset += value.len();
6370 moved_since_edit = true;
6371 }
6372 ChangeTag::Delete => {
6373 let start = snapshot.anchor_after(offset);
6374 let end = snapshot.anchor_before(offset + value.len());
6375 if moved_since_edit {
6376 edits.push((start..end, String::new()));
6377 } else {
6378 edits.last_mut().unwrap().0.end = end;
6379 }
6380 offset += value.len();
6381 moved_since_edit = false;
6382 }
6383 ChangeTag::Insert => {
6384 if moved_since_edit {
6385 let anchor = snapshot.anchor_after(offset);
6386 edits.push((anchor..anchor, value.to_string()));
6387 } else {
6388 edits.last_mut().unwrap().1.push_str(value);
6389 }
6390 moved_since_edit = false;
6391 }
6392 }
6393 }
6394 } else if range.end == range.start {
6395 let anchor = snapshot.anchor_after(range.start);
6396 edits.push((anchor..anchor, new_text));
6397 } else {
6398 let edit_start = snapshot.anchor_after(range.start);
6399 let edit_end = snapshot.anchor_before(range.end);
6400 edits.push((edit_start..edit_end, new_text));
6401 }
6402 }
6403
6404 Ok(edits)
6405 })
6406 }
6407
6408 fn buffer_snapshot_for_lsp_version(
6409 &mut self,
6410 buffer: &ModelHandle<Buffer>,
6411 server_id: LanguageServerId,
6412 version: Option<i32>,
6413 cx: &AppContext,
6414 ) -> Result<TextBufferSnapshot> {
6415 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6416
6417 if let Some(version) = version {
6418 let buffer_id = buffer.read(cx).remote_id();
6419 let snapshots = self
6420 .buffer_snapshots
6421 .get_mut(&buffer_id)
6422 .and_then(|m| m.get_mut(&server_id))
6423 .ok_or_else(|| {
6424 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
6425 })?;
6426
6427 let found_snapshot = snapshots
6428 .binary_search_by_key(&version, |e| e.version)
6429 .map(|ix| snapshots[ix].snapshot.clone())
6430 .map_err(|_| {
6431 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
6432 })?;
6433
6434 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
6435 Ok(found_snapshot)
6436 } else {
6437 Ok((buffer.read(cx)).text_snapshot())
6438 }
6439 }
6440
6441 pub fn language_servers(
6442 &self,
6443 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
6444 self.language_server_ids
6445 .iter()
6446 .map(|((worktree_id, server_name), server_id)| {
6447 (*server_id, server_name.clone(), *worktree_id)
6448 })
6449 }
6450
6451 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
6452 if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
6453 Some(server.clone())
6454 } else {
6455 None
6456 }
6457 }
6458
6459 pub fn language_servers_for_buffer(
6460 &self,
6461 buffer: &Buffer,
6462 cx: &AppContext,
6463 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6464 self.language_server_ids_for_buffer(buffer, cx)
6465 .into_iter()
6466 .filter_map(|server_id| {
6467 let server = self.language_servers.get(&server_id)?;
6468 if let LanguageServerState::Running {
6469 adapter, server, ..
6470 } = server
6471 {
6472 Some((adapter, server))
6473 } else {
6474 None
6475 }
6476 })
6477 }
6478
6479 fn primary_language_servers_for_buffer(
6480 &self,
6481 buffer: &Buffer,
6482 cx: &AppContext,
6483 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6484 self.language_servers_for_buffer(buffer, cx).next()
6485 }
6486
6487 fn language_server_for_buffer(
6488 &self,
6489 buffer: &Buffer,
6490 server_id: LanguageServerId,
6491 cx: &AppContext,
6492 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6493 self.language_servers_for_buffer(buffer, cx)
6494 .find(|(_, s)| s.server_id() == server_id)
6495 }
6496
6497 fn language_server_ids_for_buffer(
6498 &self,
6499 buffer: &Buffer,
6500 cx: &AppContext,
6501 ) -> Vec<LanguageServerId> {
6502 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6503 let worktree_id = file.worktree_id(cx);
6504 language
6505 .lsp_adapters()
6506 .iter()
6507 .flat_map(|adapter| {
6508 let key = (worktree_id, adapter.name.clone());
6509 self.language_server_ids.get(&key).copied()
6510 })
6511 .collect()
6512 } else {
6513 Vec::new()
6514 }
6515 }
6516}
6517
6518impl WorktreeHandle {
6519 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6520 match self {
6521 WorktreeHandle::Strong(handle) => Some(handle.clone()),
6522 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6523 }
6524 }
6525}
6526
6527impl OpenBuffer {
6528 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
6529 match self {
6530 OpenBuffer::Strong(handle) => Some(handle.clone()),
6531 OpenBuffer::Weak(handle) => handle.upgrade(cx),
6532 OpenBuffer::Operations(_) => None,
6533 }
6534 }
6535}
6536
6537pub struct PathMatchCandidateSet {
6538 pub snapshot: Snapshot,
6539 pub include_ignored: bool,
6540 pub include_root_name: bool,
6541}
6542
6543impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6544 type Candidates = PathMatchCandidateSetIter<'a>;
6545
6546 fn id(&self) -> usize {
6547 self.snapshot.id().to_usize()
6548 }
6549
6550 fn len(&self) -> usize {
6551 if self.include_ignored {
6552 self.snapshot.file_count()
6553 } else {
6554 self.snapshot.visible_file_count()
6555 }
6556 }
6557
6558 fn prefix(&self) -> Arc<str> {
6559 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6560 self.snapshot.root_name().into()
6561 } else if self.include_root_name {
6562 format!("{}/", self.snapshot.root_name()).into()
6563 } else {
6564 "".into()
6565 }
6566 }
6567
6568 fn candidates(&'a self, start: usize) -> Self::Candidates {
6569 PathMatchCandidateSetIter {
6570 traversal: self.snapshot.files(self.include_ignored, start),
6571 }
6572 }
6573}
6574
6575pub struct PathMatchCandidateSetIter<'a> {
6576 traversal: Traversal<'a>,
6577}
6578
6579impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6580 type Item = fuzzy::PathMatchCandidate<'a>;
6581
6582 fn next(&mut self) -> Option<Self::Item> {
6583 self.traversal.next().map(|entry| {
6584 if let EntryKind::File(char_bag) = entry.kind {
6585 fuzzy::PathMatchCandidate {
6586 path: &entry.path,
6587 char_bag,
6588 }
6589 } else {
6590 unreachable!()
6591 }
6592 })
6593 }
6594}
6595
6596impl Entity for Project {
6597 type Event = Event;
6598
6599 fn release(&mut self, cx: &mut gpui::AppContext) {
6600 match &self.client_state {
6601 Some(ProjectClientState::Local { .. }) => {
6602 let _ = self.unshare_internal(cx);
6603 }
6604 Some(ProjectClientState::Remote { remote_id, .. }) => {
6605 let _ = self.client.send(proto::LeaveProject {
6606 project_id: *remote_id,
6607 });
6608 self.disconnected_from_host_internal(cx);
6609 }
6610 _ => {}
6611 }
6612 }
6613
6614 fn app_will_quit(
6615 &mut self,
6616 _: &mut AppContext,
6617 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6618 let shutdown_futures = self
6619 .language_servers
6620 .drain()
6621 .map(|(_, server_state)| async {
6622 match server_state {
6623 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6624 LanguageServerState::Starting(starting_server) => {
6625 starting_server.await?.shutdown()?.await
6626 }
6627 }
6628 })
6629 .collect::<Vec<_>>();
6630
6631 Some(
6632 async move {
6633 futures::future::join_all(shutdown_futures).await;
6634 }
6635 .boxed(),
6636 )
6637 }
6638}
6639
6640impl Collaborator {
6641 fn from_proto(message: proto::Collaborator) -> Result<Self> {
6642 Ok(Self {
6643 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6644 replica_id: message.replica_id as ReplicaId,
6645 })
6646 }
6647}
6648
6649impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6650 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6651 Self {
6652 worktree_id,
6653 path: path.as_ref().into(),
6654 }
6655 }
6656}
6657
6658fn split_operations(
6659 mut operations: Vec<proto::Operation>,
6660) -> impl Iterator<Item = Vec<proto::Operation>> {
6661 #[cfg(any(test, feature = "test-support"))]
6662 const CHUNK_SIZE: usize = 5;
6663
6664 #[cfg(not(any(test, feature = "test-support")))]
6665 const CHUNK_SIZE: usize = 100;
6666
6667 let mut done = false;
6668 std::iter::from_fn(move || {
6669 if done {
6670 return None;
6671 }
6672
6673 let operations = operations
6674 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6675 .collect::<Vec<_>>();
6676 if operations.is_empty() {
6677 done = true;
6678 }
6679 Some(operations)
6680 })
6681}
6682
6683fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6684 proto::Symbol {
6685 language_server_name: symbol.language_server_name.0.to_string(),
6686 source_worktree_id: symbol.source_worktree_id.to_proto(),
6687 worktree_id: symbol.path.worktree_id.to_proto(),
6688 path: symbol.path.path.to_string_lossy().to_string(),
6689 name: symbol.name.clone(),
6690 kind: unsafe { mem::transmute(symbol.kind) },
6691 start: Some(proto::PointUtf16 {
6692 row: symbol.range.start.0.row,
6693 column: symbol.range.start.0.column,
6694 }),
6695 end: Some(proto::PointUtf16 {
6696 row: symbol.range.end.0.row,
6697 column: symbol.range.end.0.column,
6698 }),
6699 signature: symbol.signature.to_vec(),
6700 }
6701}
6702
6703fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6704 let mut path_components = path.components();
6705 let mut base_components = base.components();
6706 let mut components: Vec<Component> = Vec::new();
6707 loop {
6708 match (path_components.next(), base_components.next()) {
6709 (None, None) => break,
6710 (Some(a), None) => {
6711 components.push(a);
6712 components.extend(path_components.by_ref());
6713 break;
6714 }
6715 (None, _) => components.push(Component::ParentDir),
6716 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6717 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6718 (Some(a), Some(_)) => {
6719 components.push(Component::ParentDir);
6720 for _ in base_components {
6721 components.push(Component::ParentDir);
6722 }
6723 components.push(a);
6724 components.extend(path_components.by_ref());
6725 break;
6726 }
6727 }
6728 }
6729 components.iter().map(|c| c.as_os_str()).collect()
6730}
6731
6732impl Item for Buffer {
6733 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6734 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6735 }
6736
6737 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6738 File::from_dyn(self.file()).map(|file| ProjectPath {
6739 worktree_id: file.worktree_id(cx),
6740 path: file.path().clone(),
6741 })
6742 }
6743}