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