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