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