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