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