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