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: &Vec<RepositoryEntry>,
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 let repo = match repos
4719 .iter()
4720 .find(|repository| repository.work_directory.contains(worktree, &path))
4721 {
4722 Some(repo) => repo.clone(),
4723 None => return,
4724 };
4725
4726 let relative_repo = match repo.work_directory.relativize(worktree, &path) {
4727 Some(relative_repo) => relative_repo.to_owned(),
4728 None => return,
4729 };
4730
4731 drop(worktree);
4732
4733 let remote_id = self.remote_id();
4734 let client = self.client.clone();
4735 let diff_base_task = worktree_handle.update(cx, move |worktree, cx| {
4736 worktree
4737 .as_local()
4738 .unwrap()
4739 .load_index_text(repo, relative_repo, cx)
4740 });
4741
4742 cx.spawn(|_, mut cx| async move {
4743 let diff_base = diff_base_task.await;
4744
4745 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4746 buffer.set_diff_base(diff_base.clone(), cx);
4747 buffer.remote_id()
4748 });
4749
4750 if let Some(project_id) = remote_id {
4751 client
4752 .send(proto::UpdateDiffBase {
4753 project_id,
4754 buffer_id: buffer_id as u64,
4755 diff_base,
4756 })
4757 .log_err();
4758 }
4759 })
4760 .detach();
4761 }
4762 }
4763 }
4764
4765 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4766 let new_active_entry = entry.and_then(|project_path| {
4767 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4768 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4769 Some(entry.id)
4770 });
4771 if new_active_entry != self.active_entry {
4772 self.active_entry = new_active_entry;
4773 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4774 }
4775 }
4776
4777 pub fn language_servers_running_disk_based_diagnostics(
4778 &self,
4779 ) -> impl Iterator<Item = LanguageServerId> + '_ {
4780 self.language_server_statuses
4781 .iter()
4782 .filter_map(|(id, status)| {
4783 if status.has_pending_diagnostic_updates {
4784 Some(*id)
4785 } else {
4786 None
4787 }
4788 })
4789 }
4790
4791 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4792 let mut summary = DiagnosticSummary::default();
4793 for (_, _, path_summary) in self.diagnostic_summaries(cx) {
4794 summary.error_count += path_summary.error_count;
4795 summary.warning_count += path_summary.warning_count;
4796 }
4797 summary
4798 }
4799
4800 pub fn diagnostic_summaries<'a>(
4801 &'a self,
4802 cx: &'a AppContext,
4803 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4804 self.visible_worktrees(cx).flat_map(move |worktree| {
4805 let worktree = worktree.read(cx);
4806 let worktree_id = worktree.id();
4807 worktree
4808 .diagnostic_summaries()
4809 .map(move |(path, server_id, summary)| {
4810 (ProjectPath { worktree_id, path }, server_id, summary)
4811 })
4812 })
4813 }
4814
4815 pub fn disk_based_diagnostics_started(
4816 &mut self,
4817 language_server_id: LanguageServerId,
4818 cx: &mut ModelContext<Self>,
4819 ) {
4820 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4821 }
4822
4823 pub fn disk_based_diagnostics_finished(
4824 &mut self,
4825 language_server_id: LanguageServerId,
4826 cx: &mut ModelContext<Self>,
4827 ) {
4828 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4829 }
4830
4831 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4832 self.active_entry
4833 }
4834
4835 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4836 self.worktree_for_id(path.worktree_id, cx)?
4837 .read(cx)
4838 .entry_for_path(&path.path)
4839 .cloned()
4840 }
4841
4842 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4843 let worktree = self.worktree_for_entry(entry_id, cx)?;
4844 let worktree = worktree.read(cx);
4845 let worktree_id = worktree.id();
4846 let path = worktree.entry_for_id(entry_id)?.path.clone();
4847 Some(ProjectPath { worktree_id, path })
4848 }
4849
4850 // RPC message handlers
4851
4852 async fn handle_unshare_project(
4853 this: ModelHandle<Self>,
4854 _: TypedEnvelope<proto::UnshareProject>,
4855 _: Arc<Client>,
4856 mut cx: AsyncAppContext,
4857 ) -> Result<()> {
4858 this.update(&mut cx, |this, cx| {
4859 if this.is_local() {
4860 this.unshare(cx)?;
4861 } else {
4862 this.disconnected_from_host(cx);
4863 }
4864 Ok(())
4865 })
4866 }
4867
4868 async fn handle_add_collaborator(
4869 this: ModelHandle<Self>,
4870 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4871 _: Arc<Client>,
4872 mut cx: AsyncAppContext,
4873 ) -> Result<()> {
4874 let collaborator = envelope
4875 .payload
4876 .collaborator
4877 .take()
4878 .ok_or_else(|| anyhow!("empty collaborator"))?;
4879
4880 let collaborator = Collaborator::from_proto(collaborator)?;
4881 this.update(&mut cx, |this, cx| {
4882 this.shared_buffers.remove(&collaborator.peer_id);
4883 this.collaborators
4884 .insert(collaborator.peer_id, collaborator);
4885 cx.notify();
4886 });
4887
4888 Ok(())
4889 }
4890
4891 async fn handle_update_project_collaborator(
4892 this: ModelHandle<Self>,
4893 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4894 _: Arc<Client>,
4895 mut cx: AsyncAppContext,
4896 ) -> Result<()> {
4897 let old_peer_id = envelope
4898 .payload
4899 .old_peer_id
4900 .ok_or_else(|| anyhow!("missing old peer id"))?;
4901 let new_peer_id = envelope
4902 .payload
4903 .new_peer_id
4904 .ok_or_else(|| anyhow!("missing new peer id"))?;
4905 this.update(&mut cx, |this, cx| {
4906 let collaborator = this
4907 .collaborators
4908 .remove(&old_peer_id)
4909 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4910 let is_host = collaborator.replica_id == 0;
4911 this.collaborators.insert(new_peer_id, collaborator);
4912
4913 let buffers = this.shared_buffers.remove(&old_peer_id);
4914 log::info!(
4915 "peer {} became {}. moving buffers {:?}",
4916 old_peer_id,
4917 new_peer_id,
4918 &buffers
4919 );
4920 if let Some(buffers) = buffers {
4921 this.shared_buffers.insert(new_peer_id, buffers);
4922 }
4923
4924 if is_host {
4925 this.opened_buffers
4926 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
4927 this.buffer_ordered_messages_tx
4928 .unbounded_send(BufferOrderedMessage::Resync)
4929 .unwrap();
4930 }
4931
4932 cx.emit(Event::CollaboratorUpdated {
4933 old_peer_id,
4934 new_peer_id,
4935 });
4936 cx.notify();
4937 Ok(())
4938 })
4939 }
4940
4941 async fn handle_remove_collaborator(
4942 this: ModelHandle<Self>,
4943 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4944 _: Arc<Client>,
4945 mut cx: AsyncAppContext,
4946 ) -> Result<()> {
4947 this.update(&mut cx, |this, cx| {
4948 let peer_id = envelope
4949 .payload
4950 .peer_id
4951 .ok_or_else(|| anyhow!("invalid peer id"))?;
4952 let replica_id = this
4953 .collaborators
4954 .remove(&peer_id)
4955 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4956 .replica_id;
4957 for buffer in this.opened_buffers.values() {
4958 if let Some(buffer) = buffer.upgrade(cx) {
4959 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4960 }
4961 }
4962 this.shared_buffers.remove(&peer_id);
4963
4964 cx.emit(Event::CollaboratorLeft(peer_id));
4965 cx.notify();
4966 Ok(())
4967 })
4968 }
4969
4970 async fn handle_update_project(
4971 this: ModelHandle<Self>,
4972 envelope: TypedEnvelope<proto::UpdateProject>,
4973 _: Arc<Client>,
4974 mut cx: AsyncAppContext,
4975 ) -> Result<()> {
4976 this.update(&mut cx, |this, cx| {
4977 // Don't handle messages that were sent before the response to us joining the project
4978 if envelope.message_id > this.join_project_response_message_id {
4979 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4980 }
4981 Ok(())
4982 })
4983 }
4984
4985 async fn handle_update_worktree(
4986 this: ModelHandle<Self>,
4987 envelope: TypedEnvelope<proto::UpdateWorktree>,
4988 _: Arc<Client>,
4989 mut cx: AsyncAppContext,
4990 ) -> Result<()> {
4991 this.update(&mut cx, |this, cx| {
4992 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4993 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4994 worktree.update(cx, |worktree, _| {
4995 let worktree = worktree.as_remote_mut().unwrap();
4996 worktree.update_from_remote(envelope.payload);
4997 });
4998 }
4999 Ok(())
5000 })
5001 }
5002
5003 async fn handle_create_project_entry(
5004 this: ModelHandle<Self>,
5005 envelope: TypedEnvelope<proto::CreateProjectEntry>,
5006 _: Arc<Client>,
5007 mut cx: AsyncAppContext,
5008 ) -> Result<proto::ProjectEntryResponse> {
5009 let worktree = this.update(&mut cx, |this, cx| {
5010 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5011 this.worktree_for_id(worktree_id, cx)
5012 .ok_or_else(|| anyhow!("worktree not found"))
5013 })?;
5014 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5015 let entry = worktree
5016 .update(&mut cx, |worktree, cx| {
5017 let worktree = worktree.as_local_mut().unwrap();
5018 let path = PathBuf::from(envelope.payload.path);
5019 worktree.create_entry(path, envelope.payload.is_directory, cx)
5020 })
5021 .await?;
5022 Ok(proto::ProjectEntryResponse {
5023 entry: Some((&entry).into()),
5024 worktree_scan_id: worktree_scan_id as u64,
5025 })
5026 }
5027
5028 async fn handle_rename_project_entry(
5029 this: ModelHandle<Self>,
5030 envelope: TypedEnvelope<proto::RenameProjectEntry>,
5031 _: Arc<Client>,
5032 mut cx: AsyncAppContext,
5033 ) -> Result<proto::ProjectEntryResponse> {
5034 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5035 let worktree = this.read_with(&cx, |this, cx| {
5036 this.worktree_for_entry(entry_id, cx)
5037 .ok_or_else(|| anyhow!("worktree not found"))
5038 })?;
5039 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5040 let entry = worktree
5041 .update(&mut cx, |worktree, cx| {
5042 let new_path = PathBuf::from(envelope.payload.new_path);
5043 worktree
5044 .as_local_mut()
5045 .unwrap()
5046 .rename_entry(entry_id, new_path, cx)
5047 .ok_or_else(|| anyhow!("invalid entry"))
5048 })?
5049 .await?;
5050 Ok(proto::ProjectEntryResponse {
5051 entry: Some((&entry).into()),
5052 worktree_scan_id: worktree_scan_id as u64,
5053 })
5054 }
5055
5056 async fn handle_copy_project_entry(
5057 this: ModelHandle<Self>,
5058 envelope: TypedEnvelope<proto::CopyProjectEntry>,
5059 _: Arc<Client>,
5060 mut cx: AsyncAppContext,
5061 ) -> Result<proto::ProjectEntryResponse> {
5062 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5063 let worktree = this.read_with(&cx, |this, cx| {
5064 this.worktree_for_entry(entry_id, cx)
5065 .ok_or_else(|| anyhow!("worktree not found"))
5066 })?;
5067 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5068 let entry = worktree
5069 .update(&mut cx, |worktree, cx| {
5070 let new_path = PathBuf::from(envelope.payload.new_path);
5071 worktree
5072 .as_local_mut()
5073 .unwrap()
5074 .copy_entry(entry_id, new_path, cx)
5075 .ok_or_else(|| anyhow!("invalid entry"))
5076 })?
5077 .await?;
5078 Ok(proto::ProjectEntryResponse {
5079 entry: Some((&entry).into()),
5080 worktree_scan_id: worktree_scan_id as u64,
5081 })
5082 }
5083
5084 async fn handle_delete_project_entry(
5085 this: ModelHandle<Self>,
5086 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5087 _: Arc<Client>,
5088 mut cx: AsyncAppContext,
5089 ) -> Result<proto::ProjectEntryResponse> {
5090 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5091 let worktree = this.read_with(&cx, |this, cx| {
5092 this.worktree_for_entry(entry_id, cx)
5093 .ok_or_else(|| anyhow!("worktree not found"))
5094 })?;
5095 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5096 worktree
5097 .update(&mut cx, |worktree, cx| {
5098 worktree
5099 .as_local_mut()
5100 .unwrap()
5101 .delete_entry(entry_id, cx)
5102 .ok_or_else(|| anyhow!("invalid entry"))
5103 })?
5104 .await?;
5105 Ok(proto::ProjectEntryResponse {
5106 entry: None,
5107 worktree_scan_id: worktree_scan_id as u64,
5108 })
5109 }
5110
5111 async fn handle_update_diagnostic_summary(
5112 this: ModelHandle<Self>,
5113 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5114 _: Arc<Client>,
5115 mut cx: AsyncAppContext,
5116 ) -> Result<()> {
5117 this.update(&mut cx, |this, cx| {
5118 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5119 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5120 if let Some(summary) = envelope.payload.summary {
5121 let project_path = ProjectPath {
5122 worktree_id,
5123 path: Path::new(&summary.path).into(),
5124 };
5125 worktree.update(cx, |worktree, _| {
5126 worktree
5127 .as_remote_mut()
5128 .unwrap()
5129 .update_diagnostic_summary(project_path.path.clone(), &summary);
5130 });
5131 cx.emit(Event::DiagnosticsUpdated {
5132 language_server_id: LanguageServerId(summary.language_server_id as usize),
5133 path: project_path,
5134 });
5135 }
5136 }
5137 Ok(())
5138 })
5139 }
5140
5141 async fn handle_start_language_server(
5142 this: ModelHandle<Self>,
5143 envelope: TypedEnvelope<proto::StartLanguageServer>,
5144 _: Arc<Client>,
5145 mut cx: AsyncAppContext,
5146 ) -> Result<()> {
5147 let server = envelope
5148 .payload
5149 .server
5150 .ok_or_else(|| anyhow!("invalid server"))?;
5151 this.update(&mut cx, |this, cx| {
5152 this.language_server_statuses.insert(
5153 LanguageServerId(server.id as usize),
5154 LanguageServerStatus {
5155 name: server.name,
5156 pending_work: Default::default(),
5157 has_pending_diagnostic_updates: false,
5158 progress_tokens: Default::default(),
5159 },
5160 );
5161 cx.notify();
5162 });
5163 Ok(())
5164 }
5165
5166 async fn handle_update_language_server(
5167 this: ModelHandle<Self>,
5168 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5169 _: Arc<Client>,
5170 mut cx: AsyncAppContext,
5171 ) -> Result<()> {
5172 this.update(&mut cx, |this, cx| {
5173 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
5174
5175 match envelope
5176 .payload
5177 .variant
5178 .ok_or_else(|| anyhow!("invalid variant"))?
5179 {
5180 proto::update_language_server::Variant::WorkStart(payload) => {
5181 this.on_lsp_work_start(
5182 language_server_id,
5183 payload.token,
5184 LanguageServerProgress {
5185 message: payload.message,
5186 percentage: payload.percentage.map(|p| p as usize),
5187 last_update_at: Instant::now(),
5188 },
5189 cx,
5190 );
5191 }
5192
5193 proto::update_language_server::Variant::WorkProgress(payload) => {
5194 this.on_lsp_work_progress(
5195 language_server_id,
5196 payload.token,
5197 LanguageServerProgress {
5198 message: payload.message,
5199 percentage: payload.percentage.map(|p| p as usize),
5200 last_update_at: Instant::now(),
5201 },
5202 cx,
5203 );
5204 }
5205
5206 proto::update_language_server::Variant::WorkEnd(payload) => {
5207 this.on_lsp_work_end(language_server_id, payload.token, cx);
5208 }
5209
5210 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5211 this.disk_based_diagnostics_started(language_server_id, cx);
5212 }
5213
5214 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5215 this.disk_based_diagnostics_finished(language_server_id, cx)
5216 }
5217 }
5218
5219 Ok(())
5220 })
5221 }
5222
5223 async fn handle_update_buffer(
5224 this: ModelHandle<Self>,
5225 envelope: TypedEnvelope<proto::UpdateBuffer>,
5226 _: Arc<Client>,
5227 mut cx: AsyncAppContext,
5228 ) -> Result<proto::Ack> {
5229 this.update(&mut cx, |this, cx| {
5230 let payload = envelope.payload.clone();
5231 let buffer_id = payload.buffer_id;
5232 let ops = payload
5233 .operations
5234 .into_iter()
5235 .map(language::proto::deserialize_operation)
5236 .collect::<Result<Vec<_>, _>>()?;
5237 let is_remote = this.is_remote();
5238 match this.opened_buffers.entry(buffer_id) {
5239 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5240 OpenBuffer::Strong(buffer) => {
5241 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5242 }
5243 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5244 OpenBuffer::Weak(_) => {}
5245 },
5246 hash_map::Entry::Vacant(e) => {
5247 assert!(
5248 is_remote,
5249 "received buffer update from {:?}",
5250 envelope.original_sender_id
5251 );
5252 e.insert(OpenBuffer::Operations(ops));
5253 }
5254 }
5255 Ok(proto::Ack {})
5256 })
5257 }
5258
5259 async fn handle_create_buffer_for_peer(
5260 this: ModelHandle<Self>,
5261 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5262 _: Arc<Client>,
5263 mut cx: AsyncAppContext,
5264 ) -> Result<()> {
5265 this.update(&mut cx, |this, cx| {
5266 match envelope
5267 .payload
5268 .variant
5269 .ok_or_else(|| anyhow!("missing variant"))?
5270 {
5271 proto::create_buffer_for_peer::Variant::State(mut state) => {
5272 let mut buffer_file = None;
5273 if let Some(file) = state.file.take() {
5274 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5275 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5276 anyhow!("no worktree found for id {}", file.worktree_id)
5277 })?;
5278 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5279 as Arc<dyn language::File>);
5280 }
5281
5282 let buffer_id = state.id;
5283 let buffer = cx.add_model(|_| {
5284 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5285 });
5286 this.incomplete_remote_buffers
5287 .insert(buffer_id, Some(buffer));
5288 }
5289 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5290 let buffer = this
5291 .incomplete_remote_buffers
5292 .get(&chunk.buffer_id)
5293 .cloned()
5294 .flatten()
5295 .ok_or_else(|| {
5296 anyhow!(
5297 "received chunk for buffer {} without initial state",
5298 chunk.buffer_id
5299 )
5300 })?;
5301 let operations = chunk
5302 .operations
5303 .into_iter()
5304 .map(language::proto::deserialize_operation)
5305 .collect::<Result<Vec<_>>>()?;
5306 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5307
5308 if chunk.is_last {
5309 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5310 this.register_buffer(&buffer, cx)?;
5311 }
5312 }
5313 }
5314
5315 Ok(())
5316 })
5317 }
5318
5319 async fn handle_update_diff_base(
5320 this: ModelHandle<Self>,
5321 envelope: TypedEnvelope<proto::UpdateDiffBase>,
5322 _: Arc<Client>,
5323 mut cx: AsyncAppContext,
5324 ) -> Result<()> {
5325 this.update(&mut cx, |this, cx| {
5326 let buffer_id = envelope.payload.buffer_id;
5327 let diff_base = envelope.payload.diff_base;
5328 if let Some(buffer) = this
5329 .opened_buffers
5330 .get_mut(&buffer_id)
5331 .and_then(|b| b.upgrade(cx))
5332 .or_else(|| {
5333 this.incomplete_remote_buffers
5334 .get(&buffer_id)
5335 .cloned()
5336 .flatten()
5337 })
5338 {
5339 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5340 }
5341 Ok(())
5342 })
5343 }
5344
5345 async fn handle_update_buffer_file(
5346 this: ModelHandle<Self>,
5347 envelope: TypedEnvelope<proto::UpdateBufferFile>,
5348 _: Arc<Client>,
5349 mut cx: AsyncAppContext,
5350 ) -> Result<()> {
5351 let buffer_id = envelope.payload.buffer_id;
5352
5353 this.update(&mut cx, |this, cx| {
5354 let payload = envelope.payload.clone();
5355 if let Some(buffer) = this
5356 .opened_buffers
5357 .get(&buffer_id)
5358 .and_then(|b| b.upgrade(cx))
5359 .or_else(|| {
5360 this.incomplete_remote_buffers
5361 .get(&buffer_id)
5362 .cloned()
5363 .flatten()
5364 })
5365 {
5366 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5367 let worktree = this
5368 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5369 .ok_or_else(|| anyhow!("no such worktree"))?;
5370 let file = File::from_proto(file, worktree, cx)?;
5371 buffer.update(cx, |buffer, cx| {
5372 buffer.file_updated(Arc::new(file), cx).detach();
5373 });
5374 this.detect_language_for_buffer(&buffer, cx);
5375 }
5376 Ok(())
5377 })
5378 }
5379
5380 async fn handle_save_buffer(
5381 this: ModelHandle<Self>,
5382 envelope: TypedEnvelope<proto::SaveBuffer>,
5383 _: Arc<Client>,
5384 mut cx: AsyncAppContext,
5385 ) -> Result<proto::BufferSaved> {
5386 let buffer_id = envelope.payload.buffer_id;
5387 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5388 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5389 let buffer = this
5390 .opened_buffers
5391 .get(&buffer_id)
5392 .and_then(|buffer| buffer.upgrade(cx))
5393 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5394 anyhow::Ok((project_id, buffer))
5395 })?;
5396 buffer
5397 .update(&mut cx, |buffer, _| {
5398 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
5399 })
5400 .await?;
5401 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
5402
5403 let (saved_version, fingerprint, mtime) = this
5404 .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5405 .await?;
5406 Ok(proto::BufferSaved {
5407 project_id,
5408 buffer_id,
5409 version: serialize_version(&saved_version),
5410 mtime: Some(mtime.into()),
5411 fingerprint: language::proto::serialize_fingerprint(fingerprint),
5412 })
5413 }
5414
5415 async fn handle_reload_buffers(
5416 this: ModelHandle<Self>,
5417 envelope: TypedEnvelope<proto::ReloadBuffers>,
5418 _: Arc<Client>,
5419 mut cx: AsyncAppContext,
5420 ) -> Result<proto::ReloadBuffersResponse> {
5421 let sender_id = envelope.original_sender_id()?;
5422 let reload = this.update(&mut cx, |this, cx| {
5423 let mut buffers = HashSet::default();
5424 for buffer_id in &envelope.payload.buffer_ids {
5425 buffers.insert(
5426 this.opened_buffers
5427 .get(buffer_id)
5428 .and_then(|buffer| buffer.upgrade(cx))
5429 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5430 );
5431 }
5432 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5433 })?;
5434
5435 let project_transaction = reload.await?;
5436 let project_transaction = this.update(&mut cx, |this, cx| {
5437 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5438 });
5439 Ok(proto::ReloadBuffersResponse {
5440 transaction: Some(project_transaction),
5441 })
5442 }
5443
5444 async fn handle_synchronize_buffers(
5445 this: ModelHandle<Self>,
5446 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5447 _: Arc<Client>,
5448 mut cx: AsyncAppContext,
5449 ) -> Result<proto::SynchronizeBuffersResponse> {
5450 let project_id = envelope.payload.project_id;
5451 let mut response = proto::SynchronizeBuffersResponse {
5452 buffers: Default::default(),
5453 };
5454
5455 this.update(&mut cx, |this, cx| {
5456 let Some(guest_id) = envelope.original_sender_id else {
5457 log::error!("missing original_sender_id on SynchronizeBuffers request");
5458 return;
5459 };
5460
5461 this.shared_buffers.entry(guest_id).or_default().clear();
5462 for buffer in envelope.payload.buffers {
5463 let buffer_id = buffer.id;
5464 let remote_version = language::proto::deserialize_version(&buffer.version);
5465 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5466 this.shared_buffers
5467 .entry(guest_id)
5468 .or_default()
5469 .insert(buffer_id);
5470
5471 let buffer = buffer.read(cx);
5472 response.buffers.push(proto::BufferVersion {
5473 id: buffer_id,
5474 version: language::proto::serialize_version(&buffer.version),
5475 });
5476
5477 let operations = buffer.serialize_ops(Some(remote_version), cx);
5478 let client = this.client.clone();
5479 if let Some(file) = buffer.file() {
5480 client
5481 .send(proto::UpdateBufferFile {
5482 project_id,
5483 buffer_id: buffer_id as u64,
5484 file: Some(file.to_proto()),
5485 })
5486 .log_err();
5487 }
5488
5489 client
5490 .send(proto::UpdateDiffBase {
5491 project_id,
5492 buffer_id: buffer_id as u64,
5493 diff_base: buffer.diff_base().map(Into::into),
5494 })
5495 .log_err();
5496
5497 client
5498 .send(proto::BufferReloaded {
5499 project_id,
5500 buffer_id,
5501 version: language::proto::serialize_version(buffer.saved_version()),
5502 mtime: Some(buffer.saved_mtime().into()),
5503 fingerprint: language::proto::serialize_fingerprint(
5504 buffer.saved_version_fingerprint(),
5505 ),
5506 line_ending: language::proto::serialize_line_ending(
5507 buffer.line_ending(),
5508 ) as i32,
5509 })
5510 .log_err();
5511
5512 cx.background()
5513 .spawn(
5514 async move {
5515 let operations = operations.await;
5516 for chunk in split_operations(operations) {
5517 client
5518 .request(proto::UpdateBuffer {
5519 project_id,
5520 buffer_id,
5521 operations: chunk,
5522 })
5523 .await?;
5524 }
5525 anyhow::Ok(())
5526 }
5527 .log_err(),
5528 )
5529 .detach();
5530 }
5531 }
5532 });
5533
5534 Ok(response)
5535 }
5536
5537 async fn handle_format_buffers(
5538 this: ModelHandle<Self>,
5539 envelope: TypedEnvelope<proto::FormatBuffers>,
5540 _: Arc<Client>,
5541 mut cx: AsyncAppContext,
5542 ) -> Result<proto::FormatBuffersResponse> {
5543 let sender_id = envelope.original_sender_id()?;
5544 let format = this.update(&mut cx, |this, cx| {
5545 let mut buffers = HashSet::default();
5546 for buffer_id in &envelope.payload.buffer_ids {
5547 buffers.insert(
5548 this.opened_buffers
5549 .get(buffer_id)
5550 .and_then(|buffer| buffer.upgrade(cx))
5551 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5552 );
5553 }
5554 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5555 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5556 })?;
5557
5558 let project_transaction = format.await?;
5559 let project_transaction = this.update(&mut cx, |this, cx| {
5560 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5561 });
5562 Ok(proto::FormatBuffersResponse {
5563 transaction: Some(project_transaction),
5564 })
5565 }
5566
5567 async fn handle_apply_additional_edits_for_completion(
5568 this: ModelHandle<Self>,
5569 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5570 _: Arc<Client>,
5571 mut cx: AsyncAppContext,
5572 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5573 let (buffer, completion) = this.update(&mut cx, |this, cx| {
5574 let buffer = this
5575 .opened_buffers
5576 .get(&envelope.payload.buffer_id)
5577 .and_then(|buffer| buffer.upgrade(cx))
5578 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5579 let language = buffer.read(cx).language();
5580 let completion = language::proto::deserialize_completion(
5581 envelope
5582 .payload
5583 .completion
5584 .ok_or_else(|| anyhow!("invalid completion"))?,
5585 language.cloned(),
5586 );
5587 Ok::<_, anyhow::Error>((buffer, completion))
5588 })?;
5589
5590 let completion = completion.await?;
5591
5592 let apply_additional_edits = this.update(&mut cx, |this, cx| {
5593 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5594 });
5595
5596 Ok(proto::ApplyCompletionAdditionalEditsResponse {
5597 transaction: apply_additional_edits
5598 .await?
5599 .as_ref()
5600 .map(language::proto::serialize_transaction),
5601 })
5602 }
5603
5604 async fn handle_apply_code_action(
5605 this: ModelHandle<Self>,
5606 envelope: TypedEnvelope<proto::ApplyCodeAction>,
5607 _: Arc<Client>,
5608 mut cx: AsyncAppContext,
5609 ) -> Result<proto::ApplyCodeActionResponse> {
5610 let sender_id = envelope.original_sender_id()?;
5611 let action = language::proto::deserialize_code_action(
5612 envelope
5613 .payload
5614 .action
5615 .ok_or_else(|| anyhow!("invalid action"))?,
5616 )?;
5617 let apply_code_action = this.update(&mut cx, |this, cx| {
5618 let buffer = this
5619 .opened_buffers
5620 .get(&envelope.payload.buffer_id)
5621 .and_then(|buffer| buffer.upgrade(cx))
5622 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5623 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5624 })?;
5625
5626 let project_transaction = apply_code_action.await?;
5627 let project_transaction = this.update(&mut cx, |this, cx| {
5628 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5629 });
5630 Ok(proto::ApplyCodeActionResponse {
5631 transaction: Some(project_transaction),
5632 })
5633 }
5634
5635 async fn handle_lsp_command<T: LspCommand>(
5636 this: ModelHandle<Self>,
5637 envelope: TypedEnvelope<T::ProtoRequest>,
5638 _: Arc<Client>,
5639 mut cx: AsyncAppContext,
5640 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5641 where
5642 <T::LspRequest as lsp::request::Request>::Result: Send,
5643 {
5644 let sender_id = envelope.original_sender_id()?;
5645 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5646 let buffer_handle = this.read_with(&cx, |this, _| {
5647 this.opened_buffers
5648 .get(&buffer_id)
5649 .and_then(|buffer| buffer.upgrade(&cx))
5650 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5651 })?;
5652 let request = T::from_proto(
5653 envelope.payload,
5654 this.clone(),
5655 buffer_handle.clone(),
5656 cx.clone(),
5657 )
5658 .await?;
5659 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5660 let response = this
5661 .update(&mut cx, |this, cx| {
5662 this.request_lsp(buffer_handle, request, cx)
5663 })
5664 .await?;
5665 this.update(&mut cx, |this, cx| {
5666 Ok(T::response_to_proto(
5667 response,
5668 this,
5669 sender_id,
5670 &buffer_version,
5671 cx,
5672 ))
5673 })
5674 }
5675
5676 async fn handle_get_project_symbols(
5677 this: ModelHandle<Self>,
5678 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5679 _: Arc<Client>,
5680 mut cx: AsyncAppContext,
5681 ) -> Result<proto::GetProjectSymbolsResponse> {
5682 let symbols = this
5683 .update(&mut cx, |this, cx| {
5684 this.symbols(&envelope.payload.query, cx)
5685 })
5686 .await?;
5687
5688 Ok(proto::GetProjectSymbolsResponse {
5689 symbols: symbols.iter().map(serialize_symbol).collect(),
5690 })
5691 }
5692
5693 async fn handle_search_project(
5694 this: ModelHandle<Self>,
5695 envelope: TypedEnvelope<proto::SearchProject>,
5696 _: Arc<Client>,
5697 mut cx: AsyncAppContext,
5698 ) -> Result<proto::SearchProjectResponse> {
5699 let peer_id = envelope.original_sender_id()?;
5700 let query = SearchQuery::from_proto(envelope.payload)?;
5701 let result = this
5702 .update(&mut cx, |this, cx| this.search(query, cx))
5703 .await?;
5704
5705 this.update(&mut cx, |this, cx| {
5706 let mut locations = Vec::new();
5707 for (buffer, ranges) in result {
5708 for range in ranges {
5709 let start = serialize_anchor(&range.start);
5710 let end = serialize_anchor(&range.end);
5711 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5712 locations.push(proto::Location {
5713 buffer_id,
5714 start: Some(start),
5715 end: Some(end),
5716 });
5717 }
5718 }
5719 Ok(proto::SearchProjectResponse { locations })
5720 })
5721 }
5722
5723 async fn handle_open_buffer_for_symbol(
5724 this: ModelHandle<Self>,
5725 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5726 _: Arc<Client>,
5727 mut cx: AsyncAppContext,
5728 ) -> Result<proto::OpenBufferForSymbolResponse> {
5729 let peer_id = envelope.original_sender_id()?;
5730 let symbol = envelope
5731 .payload
5732 .symbol
5733 .ok_or_else(|| anyhow!("invalid symbol"))?;
5734 let symbol = this
5735 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5736 .await?;
5737 let symbol = this.read_with(&cx, |this, _| {
5738 let signature = this.symbol_signature(&symbol.path);
5739 if signature == symbol.signature {
5740 Ok(symbol)
5741 } else {
5742 Err(anyhow!("invalid symbol signature"))
5743 }
5744 })?;
5745 let buffer = this
5746 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5747 .await?;
5748
5749 Ok(proto::OpenBufferForSymbolResponse {
5750 buffer_id: this.update(&mut cx, |this, cx| {
5751 this.create_buffer_for_peer(&buffer, peer_id, cx)
5752 }),
5753 })
5754 }
5755
5756 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5757 let mut hasher = Sha256::new();
5758 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5759 hasher.update(project_path.path.to_string_lossy().as_bytes());
5760 hasher.update(self.nonce.to_be_bytes());
5761 hasher.finalize().as_slice().try_into().unwrap()
5762 }
5763
5764 async fn handle_open_buffer_by_id(
5765 this: ModelHandle<Self>,
5766 envelope: TypedEnvelope<proto::OpenBufferById>,
5767 _: Arc<Client>,
5768 mut cx: AsyncAppContext,
5769 ) -> Result<proto::OpenBufferResponse> {
5770 let peer_id = envelope.original_sender_id()?;
5771 let buffer = this
5772 .update(&mut cx, |this, cx| {
5773 this.open_buffer_by_id(envelope.payload.id, cx)
5774 })
5775 .await?;
5776 this.update(&mut cx, |this, cx| {
5777 Ok(proto::OpenBufferResponse {
5778 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5779 })
5780 })
5781 }
5782
5783 async fn handle_open_buffer_by_path(
5784 this: ModelHandle<Self>,
5785 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5786 _: Arc<Client>,
5787 mut cx: AsyncAppContext,
5788 ) -> Result<proto::OpenBufferResponse> {
5789 let peer_id = envelope.original_sender_id()?;
5790 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5791 let open_buffer = this.update(&mut cx, |this, cx| {
5792 this.open_buffer(
5793 ProjectPath {
5794 worktree_id,
5795 path: PathBuf::from(envelope.payload.path).into(),
5796 },
5797 cx,
5798 )
5799 });
5800
5801 let buffer = open_buffer.await?;
5802 this.update(&mut cx, |this, cx| {
5803 Ok(proto::OpenBufferResponse {
5804 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5805 })
5806 })
5807 }
5808
5809 fn serialize_project_transaction_for_peer(
5810 &mut self,
5811 project_transaction: ProjectTransaction,
5812 peer_id: proto::PeerId,
5813 cx: &mut AppContext,
5814 ) -> proto::ProjectTransaction {
5815 let mut serialized_transaction = proto::ProjectTransaction {
5816 buffer_ids: Default::default(),
5817 transactions: Default::default(),
5818 };
5819 for (buffer, transaction) in project_transaction.0 {
5820 serialized_transaction
5821 .buffer_ids
5822 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5823 serialized_transaction
5824 .transactions
5825 .push(language::proto::serialize_transaction(&transaction));
5826 }
5827 serialized_transaction
5828 }
5829
5830 fn deserialize_project_transaction(
5831 &mut self,
5832 message: proto::ProjectTransaction,
5833 push_to_history: bool,
5834 cx: &mut ModelContext<Self>,
5835 ) -> Task<Result<ProjectTransaction>> {
5836 cx.spawn(|this, mut cx| async move {
5837 let mut project_transaction = ProjectTransaction::default();
5838 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5839 {
5840 let buffer = this
5841 .update(&mut cx, |this, cx| {
5842 this.wait_for_remote_buffer(buffer_id, cx)
5843 })
5844 .await?;
5845 let transaction = language::proto::deserialize_transaction(transaction)?;
5846 project_transaction.0.insert(buffer, transaction);
5847 }
5848
5849 for (buffer, transaction) in &project_transaction.0 {
5850 buffer
5851 .update(&mut cx, |buffer, _| {
5852 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5853 })
5854 .await?;
5855
5856 if push_to_history {
5857 buffer.update(&mut cx, |buffer, _| {
5858 buffer.push_transaction(transaction.clone(), Instant::now());
5859 });
5860 }
5861 }
5862
5863 Ok(project_transaction)
5864 })
5865 }
5866
5867 fn create_buffer_for_peer(
5868 &mut self,
5869 buffer: &ModelHandle<Buffer>,
5870 peer_id: proto::PeerId,
5871 cx: &mut AppContext,
5872 ) -> u64 {
5873 let buffer_id = buffer.read(cx).remote_id();
5874 if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
5875 updates_tx
5876 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
5877 .ok();
5878 }
5879 buffer_id
5880 }
5881
5882 fn wait_for_remote_buffer(
5883 &mut self,
5884 id: u64,
5885 cx: &mut ModelContext<Self>,
5886 ) -> Task<Result<ModelHandle<Buffer>>> {
5887 let mut opened_buffer_rx = self.opened_buffer.1.clone();
5888
5889 cx.spawn_weak(|this, mut cx| async move {
5890 let buffer = loop {
5891 let Some(this) = this.upgrade(&cx) else {
5892 return Err(anyhow!("project dropped"));
5893 };
5894 let buffer = this.read_with(&cx, |this, cx| {
5895 this.opened_buffers
5896 .get(&id)
5897 .and_then(|buffer| buffer.upgrade(cx))
5898 });
5899 if let Some(buffer) = buffer {
5900 break buffer;
5901 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5902 return Err(anyhow!("disconnected before buffer {} could be opened", id));
5903 }
5904
5905 this.update(&mut cx, |this, _| {
5906 this.incomplete_remote_buffers.entry(id).or_default();
5907 });
5908 drop(this);
5909 opened_buffer_rx
5910 .next()
5911 .await
5912 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5913 };
5914 buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5915 Ok(buffer)
5916 })
5917 }
5918
5919 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
5920 let project_id = match self.client_state.as_ref() {
5921 Some(ProjectClientState::Remote {
5922 sharing_has_stopped,
5923 remote_id,
5924 ..
5925 }) => {
5926 if *sharing_has_stopped {
5927 return Task::ready(Err(anyhow!(
5928 "can't synchronize remote buffers on a readonly project"
5929 )));
5930 } else {
5931 *remote_id
5932 }
5933 }
5934 Some(ProjectClientState::Local { .. }) | None => {
5935 return Task::ready(Err(anyhow!(
5936 "can't synchronize remote buffers on a local project"
5937 )))
5938 }
5939 };
5940
5941 let client = self.client.clone();
5942 cx.spawn(|this, cx| async move {
5943 let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
5944 let buffers = this
5945 .opened_buffers
5946 .iter()
5947 .filter_map(|(id, buffer)| {
5948 let buffer = buffer.upgrade(cx)?;
5949 Some(proto::BufferVersion {
5950 id: *id,
5951 version: language::proto::serialize_version(&buffer.read(cx).version),
5952 })
5953 })
5954 .collect();
5955 let incomplete_buffer_ids = this
5956 .incomplete_remote_buffers
5957 .keys()
5958 .copied()
5959 .collect::<Vec<_>>();
5960
5961 (buffers, incomplete_buffer_ids)
5962 });
5963 let response = client
5964 .request(proto::SynchronizeBuffers {
5965 project_id,
5966 buffers,
5967 })
5968 .await?;
5969
5970 let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
5971 let client = client.clone();
5972 let buffer_id = buffer.id;
5973 let remote_version = language::proto::deserialize_version(&buffer.version);
5974 this.read_with(&cx, |this, cx| {
5975 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5976 let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
5977 cx.background().spawn(async move {
5978 let operations = operations.await;
5979 for chunk in split_operations(operations) {
5980 client
5981 .request(proto::UpdateBuffer {
5982 project_id,
5983 buffer_id,
5984 operations: chunk,
5985 })
5986 .await?;
5987 }
5988 anyhow::Ok(())
5989 })
5990 } else {
5991 Task::ready(Ok(()))
5992 }
5993 })
5994 });
5995
5996 // Any incomplete buffers have open requests waiting. Request that the host sends
5997 // creates these buffers for us again to unblock any waiting futures.
5998 for id in incomplete_buffer_ids {
5999 cx.background()
6000 .spawn(client.request(proto::OpenBufferById { project_id, id }))
6001 .detach();
6002 }
6003
6004 futures::future::join_all(send_updates_for_buffers)
6005 .await
6006 .into_iter()
6007 .collect()
6008 })
6009 }
6010
6011 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
6012 self.worktrees(cx)
6013 .map(|worktree| {
6014 let worktree = worktree.read(cx);
6015 proto::WorktreeMetadata {
6016 id: worktree.id().to_proto(),
6017 root_name: worktree.root_name().into(),
6018 visible: worktree.is_visible(),
6019 abs_path: worktree.abs_path().to_string_lossy().into(),
6020 }
6021 })
6022 .collect()
6023 }
6024
6025 fn set_worktrees_from_proto(
6026 &mut self,
6027 worktrees: Vec<proto::WorktreeMetadata>,
6028 cx: &mut ModelContext<Project>,
6029 ) -> Result<()> {
6030 let replica_id = self.replica_id();
6031 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
6032
6033 let mut old_worktrees_by_id = self
6034 .worktrees
6035 .drain(..)
6036 .filter_map(|worktree| {
6037 let worktree = worktree.upgrade(cx)?;
6038 Some((worktree.read(cx).id(), worktree))
6039 })
6040 .collect::<HashMap<_, _>>();
6041
6042 for worktree in worktrees {
6043 if let Some(old_worktree) =
6044 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
6045 {
6046 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
6047 } else {
6048 let worktree =
6049 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
6050 let _ = self.add_worktree(&worktree, cx);
6051 }
6052 }
6053
6054 self.metadata_changed(cx);
6055 for (id, _) in old_worktrees_by_id {
6056 cx.emit(Event::WorktreeRemoved(id));
6057 }
6058
6059 Ok(())
6060 }
6061
6062 fn set_collaborators_from_proto(
6063 &mut self,
6064 messages: Vec<proto::Collaborator>,
6065 cx: &mut ModelContext<Self>,
6066 ) -> Result<()> {
6067 let mut collaborators = HashMap::default();
6068 for message in messages {
6069 let collaborator = Collaborator::from_proto(message)?;
6070 collaborators.insert(collaborator.peer_id, collaborator);
6071 }
6072 for old_peer_id in self.collaborators.keys() {
6073 if !collaborators.contains_key(old_peer_id) {
6074 cx.emit(Event::CollaboratorLeft(*old_peer_id));
6075 }
6076 }
6077 self.collaborators = collaborators;
6078 Ok(())
6079 }
6080
6081 fn deserialize_symbol(
6082 &self,
6083 serialized_symbol: proto::Symbol,
6084 ) -> impl Future<Output = Result<Symbol>> {
6085 let languages = self.languages.clone();
6086 async move {
6087 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
6088 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
6089 let start = serialized_symbol
6090 .start
6091 .ok_or_else(|| anyhow!("invalid start"))?;
6092 let end = serialized_symbol
6093 .end
6094 .ok_or_else(|| anyhow!("invalid end"))?;
6095 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
6096 let path = ProjectPath {
6097 worktree_id,
6098 path: PathBuf::from(serialized_symbol.path).into(),
6099 };
6100 let language = languages
6101 .language_for_file(&path.path, None)
6102 .await
6103 .log_err();
6104 Ok(Symbol {
6105 language_server_name: LanguageServerName(
6106 serialized_symbol.language_server_name.into(),
6107 ),
6108 source_worktree_id,
6109 path,
6110 label: {
6111 match language {
6112 Some(language) => {
6113 language
6114 .label_for_symbol(&serialized_symbol.name, kind)
6115 .await
6116 }
6117 None => None,
6118 }
6119 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
6120 },
6121
6122 name: serialized_symbol.name,
6123 range: Unclipped(PointUtf16::new(start.row, start.column))
6124 ..Unclipped(PointUtf16::new(end.row, end.column)),
6125 kind,
6126 signature: serialized_symbol
6127 .signature
6128 .try_into()
6129 .map_err(|_| anyhow!("invalid signature"))?,
6130 })
6131 }
6132 }
6133
6134 async fn handle_buffer_saved(
6135 this: ModelHandle<Self>,
6136 envelope: TypedEnvelope<proto::BufferSaved>,
6137 _: Arc<Client>,
6138 mut cx: AsyncAppContext,
6139 ) -> Result<()> {
6140 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
6141 let version = deserialize_version(&envelope.payload.version);
6142 let mtime = envelope
6143 .payload
6144 .mtime
6145 .ok_or_else(|| anyhow!("missing mtime"))?
6146 .into();
6147
6148 this.update(&mut cx, |this, cx| {
6149 let buffer = this
6150 .opened_buffers
6151 .get(&envelope.payload.buffer_id)
6152 .and_then(|buffer| buffer.upgrade(cx))
6153 .or_else(|| {
6154 this.incomplete_remote_buffers
6155 .get(&envelope.payload.buffer_id)
6156 .and_then(|b| b.clone())
6157 });
6158 if let Some(buffer) = buffer {
6159 buffer.update(cx, |buffer, cx| {
6160 buffer.did_save(version, fingerprint, mtime, cx);
6161 });
6162 }
6163 Ok(())
6164 })
6165 }
6166
6167 async fn handle_buffer_reloaded(
6168 this: ModelHandle<Self>,
6169 envelope: TypedEnvelope<proto::BufferReloaded>,
6170 _: Arc<Client>,
6171 mut cx: AsyncAppContext,
6172 ) -> Result<()> {
6173 let payload = envelope.payload;
6174 let version = deserialize_version(&payload.version);
6175 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6176 let line_ending = deserialize_line_ending(
6177 proto::LineEnding::from_i32(payload.line_ending)
6178 .ok_or_else(|| anyhow!("missing line ending"))?,
6179 );
6180 let mtime = payload
6181 .mtime
6182 .ok_or_else(|| anyhow!("missing mtime"))?
6183 .into();
6184 this.update(&mut cx, |this, cx| {
6185 let buffer = this
6186 .opened_buffers
6187 .get(&payload.buffer_id)
6188 .and_then(|buffer| buffer.upgrade(cx))
6189 .or_else(|| {
6190 this.incomplete_remote_buffers
6191 .get(&payload.buffer_id)
6192 .cloned()
6193 .flatten()
6194 });
6195 if let Some(buffer) = buffer {
6196 buffer.update(cx, |buffer, cx| {
6197 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6198 });
6199 }
6200 Ok(())
6201 })
6202 }
6203
6204 #[allow(clippy::type_complexity)]
6205 fn edits_from_lsp(
6206 &mut self,
6207 buffer: &ModelHandle<Buffer>,
6208 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6209 server_id: LanguageServerId,
6210 version: Option<i32>,
6211 cx: &mut ModelContext<Self>,
6212 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6213 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
6214 cx.background().spawn(async move {
6215 let snapshot = snapshot?;
6216 let mut lsp_edits = lsp_edits
6217 .into_iter()
6218 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6219 .collect::<Vec<_>>();
6220 lsp_edits.sort_by_key(|(range, _)| range.start);
6221
6222 let mut lsp_edits = lsp_edits.into_iter().peekable();
6223 let mut edits = Vec::new();
6224 while let Some((range, mut new_text)) = lsp_edits.next() {
6225 // Clip invalid ranges provided by the language server.
6226 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6227 ..snapshot.clip_point_utf16(range.end, Bias::Left);
6228
6229 // Combine any LSP edits that are adjacent.
6230 //
6231 // Also, combine LSP edits that are separated from each other by only
6232 // a newline. This is important because for some code actions,
6233 // Rust-analyzer rewrites the entire buffer via a series of edits that
6234 // are separated by unchanged newline characters.
6235 //
6236 // In order for the diffing logic below to work properly, any edits that
6237 // cancel each other out must be combined into one.
6238 while let Some((next_range, next_text)) = lsp_edits.peek() {
6239 if next_range.start.0 > range.end {
6240 if next_range.start.0.row > range.end.row + 1
6241 || next_range.start.0.column > 0
6242 || snapshot.clip_point_utf16(
6243 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6244 Bias::Left,
6245 ) > range.end
6246 {
6247 break;
6248 }
6249 new_text.push('\n');
6250 }
6251 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6252 new_text.push_str(next_text);
6253 lsp_edits.next();
6254 }
6255
6256 // For multiline edits, perform a diff of the old and new text so that
6257 // we can identify the changes more precisely, preserving the locations
6258 // of any anchors positioned in the unchanged regions.
6259 if range.end.row > range.start.row {
6260 let mut offset = range.start.to_offset(&snapshot);
6261 let old_text = snapshot.text_for_range(range).collect::<String>();
6262
6263 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6264 let mut moved_since_edit = true;
6265 for change in diff.iter_all_changes() {
6266 let tag = change.tag();
6267 let value = change.value();
6268 match tag {
6269 ChangeTag::Equal => {
6270 offset += value.len();
6271 moved_since_edit = true;
6272 }
6273 ChangeTag::Delete => {
6274 let start = snapshot.anchor_after(offset);
6275 let end = snapshot.anchor_before(offset + value.len());
6276 if moved_since_edit {
6277 edits.push((start..end, String::new()));
6278 } else {
6279 edits.last_mut().unwrap().0.end = end;
6280 }
6281 offset += value.len();
6282 moved_since_edit = false;
6283 }
6284 ChangeTag::Insert => {
6285 if moved_since_edit {
6286 let anchor = snapshot.anchor_after(offset);
6287 edits.push((anchor..anchor, value.to_string()));
6288 } else {
6289 edits.last_mut().unwrap().1.push_str(value);
6290 }
6291 moved_since_edit = false;
6292 }
6293 }
6294 }
6295 } else if range.end == range.start {
6296 let anchor = snapshot.anchor_after(range.start);
6297 edits.push((anchor..anchor, new_text));
6298 } else {
6299 let edit_start = snapshot.anchor_after(range.start);
6300 let edit_end = snapshot.anchor_before(range.end);
6301 edits.push((edit_start..edit_end, new_text));
6302 }
6303 }
6304
6305 Ok(edits)
6306 })
6307 }
6308
6309 fn buffer_snapshot_for_lsp_version(
6310 &mut self,
6311 buffer: &ModelHandle<Buffer>,
6312 server_id: LanguageServerId,
6313 version: Option<i32>,
6314 cx: &AppContext,
6315 ) -> Result<TextBufferSnapshot> {
6316 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6317
6318 if let Some(version) = version {
6319 let buffer_id = buffer.read(cx).remote_id();
6320 let snapshots = self
6321 .buffer_snapshots
6322 .get_mut(&buffer_id)
6323 .and_then(|m| m.get_mut(&server_id))
6324 .ok_or_else(|| {
6325 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
6326 })?;
6327
6328 let found_snapshot = snapshots
6329 .binary_search_by_key(&version, |e| e.version)
6330 .map(|ix| snapshots[ix].snapshot.clone())
6331 .map_err(|_| {
6332 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
6333 })?;
6334
6335 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
6336 Ok(found_snapshot)
6337 } else {
6338 Ok((buffer.read(cx)).text_snapshot())
6339 }
6340 }
6341
6342 pub fn language_servers(
6343 &self,
6344 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
6345 self.language_server_ids
6346 .iter()
6347 .map(|((worktree_id, server_name), server_id)| {
6348 (*server_id, server_name.clone(), *worktree_id)
6349 })
6350 }
6351
6352 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
6353 if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
6354 Some(server.clone())
6355 } else {
6356 None
6357 }
6358 }
6359
6360 pub fn language_servers_for_buffer(
6361 &self,
6362 buffer: &Buffer,
6363 cx: &AppContext,
6364 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6365 self.language_server_ids_for_buffer(buffer, cx)
6366 .into_iter()
6367 .filter_map(|server_id| {
6368 let server = self.language_servers.get(&server_id)?;
6369 if let LanguageServerState::Running {
6370 adapter, server, ..
6371 } = server
6372 {
6373 Some((adapter, server))
6374 } else {
6375 None
6376 }
6377 })
6378 }
6379
6380 fn primary_language_servers_for_buffer(
6381 &self,
6382 buffer: &Buffer,
6383 cx: &AppContext,
6384 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6385 self.language_servers_for_buffer(buffer, cx).next()
6386 }
6387
6388 fn language_server_for_buffer(
6389 &self,
6390 buffer: &Buffer,
6391 server_id: LanguageServerId,
6392 cx: &AppContext,
6393 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6394 self.language_servers_for_buffer(buffer, cx)
6395 .find(|(_, s)| s.server_id() == server_id)
6396 }
6397
6398 fn language_server_ids_for_buffer(
6399 &self,
6400 buffer: &Buffer,
6401 cx: &AppContext,
6402 ) -> Vec<LanguageServerId> {
6403 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6404 let worktree_id = file.worktree_id(cx);
6405 language
6406 .lsp_adapters()
6407 .iter()
6408 .flat_map(|adapter| {
6409 let key = (worktree_id, adapter.name.clone());
6410 self.language_server_ids.get(&key).copied()
6411 })
6412 .collect()
6413 } else {
6414 Vec::new()
6415 }
6416 }
6417}
6418
6419impl WorktreeHandle {
6420 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6421 match self {
6422 WorktreeHandle::Strong(handle) => Some(handle.clone()),
6423 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6424 }
6425 }
6426}
6427
6428impl OpenBuffer {
6429 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
6430 match self {
6431 OpenBuffer::Strong(handle) => Some(handle.clone()),
6432 OpenBuffer::Weak(handle) => handle.upgrade(cx),
6433 OpenBuffer::Operations(_) => None,
6434 }
6435 }
6436}
6437
6438pub struct PathMatchCandidateSet {
6439 pub snapshot: Snapshot,
6440 pub include_ignored: bool,
6441 pub include_root_name: bool,
6442}
6443
6444impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6445 type Candidates = PathMatchCandidateSetIter<'a>;
6446
6447 fn id(&self) -> usize {
6448 self.snapshot.id().to_usize()
6449 }
6450
6451 fn len(&self) -> usize {
6452 if self.include_ignored {
6453 self.snapshot.file_count()
6454 } else {
6455 self.snapshot.visible_file_count()
6456 }
6457 }
6458
6459 fn prefix(&self) -> Arc<str> {
6460 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6461 self.snapshot.root_name().into()
6462 } else if self.include_root_name {
6463 format!("{}/", self.snapshot.root_name()).into()
6464 } else {
6465 "".into()
6466 }
6467 }
6468
6469 fn candidates(&'a self, start: usize) -> Self::Candidates {
6470 PathMatchCandidateSetIter {
6471 traversal: self.snapshot.files(self.include_ignored, start),
6472 }
6473 }
6474}
6475
6476pub struct PathMatchCandidateSetIter<'a> {
6477 traversal: Traversal<'a>,
6478}
6479
6480impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6481 type Item = fuzzy::PathMatchCandidate<'a>;
6482
6483 fn next(&mut self) -> Option<Self::Item> {
6484 self.traversal.next().map(|entry| {
6485 if let EntryKind::File(char_bag) = entry.kind {
6486 fuzzy::PathMatchCandidate {
6487 path: &entry.path,
6488 char_bag,
6489 }
6490 } else {
6491 unreachable!()
6492 }
6493 })
6494 }
6495}
6496
6497impl Entity for Project {
6498 type Event = Event;
6499
6500 fn release(&mut self, cx: &mut gpui::AppContext) {
6501 match &self.client_state {
6502 Some(ProjectClientState::Local { .. }) => {
6503 let _ = self.unshare_internal(cx);
6504 }
6505 Some(ProjectClientState::Remote { remote_id, .. }) => {
6506 let _ = self.client.send(proto::LeaveProject {
6507 project_id: *remote_id,
6508 });
6509 self.disconnected_from_host_internal(cx);
6510 }
6511 _ => {}
6512 }
6513 }
6514
6515 fn app_will_quit(
6516 &mut self,
6517 _: &mut AppContext,
6518 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6519 let shutdown_futures = self
6520 .language_servers
6521 .drain()
6522 .map(|(_, server_state)| async {
6523 match server_state {
6524 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6525 LanguageServerState::Starting(starting_server) => {
6526 starting_server.await?.shutdown()?.await
6527 }
6528 }
6529 })
6530 .collect::<Vec<_>>();
6531
6532 Some(
6533 async move {
6534 futures::future::join_all(shutdown_futures).await;
6535 }
6536 .boxed(),
6537 )
6538 }
6539}
6540
6541impl Collaborator {
6542 fn from_proto(message: proto::Collaborator) -> Result<Self> {
6543 Ok(Self {
6544 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6545 replica_id: message.replica_id as ReplicaId,
6546 })
6547 }
6548}
6549
6550impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6551 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6552 Self {
6553 worktree_id,
6554 path: path.as_ref().into(),
6555 }
6556 }
6557}
6558
6559fn split_operations(
6560 mut operations: Vec<proto::Operation>,
6561) -> impl Iterator<Item = Vec<proto::Operation>> {
6562 #[cfg(any(test, feature = "test-support"))]
6563 const CHUNK_SIZE: usize = 5;
6564
6565 #[cfg(not(any(test, feature = "test-support")))]
6566 const CHUNK_SIZE: usize = 100;
6567
6568 let mut done = false;
6569 std::iter::from_fn(move || {
6570 if done {
6571 return None;
6572 }
6573
6574 let operations = operations
6575 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6576 .collect::<Vec<_>>();
6577 if operations.is_empty() {
6578 done = true;
6579 }
6580 Some(operations)
6581 })
6582}
6583
6584fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6585 proto::Symbol {
6586 language_server_name: symbol.language_server_name.0.to_string(),
6587 source_worktree_id: symbol.source_worktree_id.to_proto(),
6588 worktree_id: symbol.path.worktree_id.to_proto(),
6589 path: symbol.path.path.to_string_lossy().to_string(),
6590 name: symbol.name.clone(),
6591 kind: unsafe { mem::transmute(symbol.kind) },
6592 start: Some(proto::PointUtf16 {
6593 row: symbol.range.start.0.row,
6594 column: symbol.range.start.0.column,
6595 }),
6596 end: Some(proto::PointUtf16 {
6597 row: symbol.range.end.0.row,
6598 column: symbol.range.end.0.column,
6599 }),
6600 signature: symbol.signature.to_vec(),
6601 }
6602}
6603
6604fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6605 let mut path_components = path.components();
6606 let mut base_components = base.components();
6607 let mut components: Vec<Component> = Vec::new();
6608 loop {
6609 match (path_components.next(), base_components.next()) {
6610 (None, None) => break,
6611 (Some(a), None) => {
6612 components.push(a);
6613 components.extend(path_components.by_ref());
6614 break;
6615 }
6616 (None, _) => components.push(Component::ParentDir),
6617 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6618 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6619 (Some(a), Some(_)) => {
6620 components.push(Component::ParentDir);
6621 for _ in base_components {
6622 components.push(Component::ParentDir);
6623 }
6624 components.push(a);
6625 components.extend(path_components.by_ref());
6626 break;
6627 }
6628 }
6629 }
6630 components.iter().map(|c| c.as_os_str()).collect()
6631}
6632
6633impl Item for Buffer {
6634 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6635 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6636 }
6637
6638 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6639 File::from_dyn(self.file()).map(|file| ProjectPath {
6640 worktree_id: file.worktree_id(cx),
6641 path: file.path().clone(),
6642 })
6643 }
6644}