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, OffsetRangeExt, Operation, Patch,
42 PendingLanguageServer, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction,
43 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, merge_json_value_into, paths::LOCAL_SETTINGS_RELATIVE_PATH, post_inc,
80 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 ActiveEntryChanged(Option<ProjectEntryId>),
258 WorktreeAdded,
259 WorktreeRemoved(WorktreeId),
260 DiskBasedDiagnosticsStarted {
261 language_server_id: LanguageServerId,
262 },
263 DiskBasedDiagnosticsFinished {
264 language_server_id: LanguageServerId,
265 },
266 DiagnosticsUpdated {
267 path: ProjectPath,
268 language_server_id: LanguageServerId,
269 },
270 RemoteIdChanged(Option<u64>),
271 DisconnectedFromHost,
272 Closed,
273 DeletedEntry(ProjectEntryId),
274 CollaboratorUpdated {
275 old_peer_id: proto::PeerId,
276 new_peer_id: proto::PeerId,
277 },
278 CollaboratorLeft(proto::PeerId),
279}
280
281pub enum LanguageServerState {
282 Validating(Task<Option<Arc<LanguageServer>>>),
283
284 Starting {
285 language: Arc<Language>,
286 adapter: Arc<CachedLspAdapter>,
287 task: Task<Option<Arc<LanguageServer>>>,
288 },
289
290 Running {
291 language: Arc<Language>,
292 adapter: Arc<CachedLspAdapter>,
293 server: Arc<LanguageServer>,
294 watched_paths: HashMap<WorktreeId, GlobSet>,
295 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
296 },
297}
298
299#[derive(Serialize)]
300pub struct LanguageServerStatus {
301 pub name: String,
302 pub pending_work: BTreeMap<String, LanguageServerProgress>,
303 pub has_pending_diagnostic_updates: bool,
304 progress_tokens: HashSet<String>,
305}
306
307#[derive(Clone, Debug, Serialize)]
308pub struct LanguageServerProgress {
309 pub message: Option<String>,
310 pub percentage: Option<usize>,
311 #[serde(skip_serializing)]
312 pub last_update_at: Instant,
313}
314
315#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
316pub struct ProjectPath {
317 pub worktree_id: WorktreeId,
318 pub path: Arc<Path>,
319}
320
321#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
322pub struct DiagnosticSummary {
323 pub error_count: usize,
324 pub warning_count: usize,
325}
326
327#[derive(Debug, Clone)]
328pub struct Location {
329 pub buffer: ModelHandle<Buffer>,
330 pub range: Range<language::Anchor>,
331}
332
333#[derive(Debug, Clone)]
334pub struct LocationLink {
335 pub origin: Option<Location>,
336 pub target: Location,
337}
338
339#[derive(Debug)]
340pub struct DocumentHighlight {
341 pub range: Range<language::Anchor>,
342 pub kind: DocumentHighlightKind,
343}
344
345#[derive(Clone, Debug)]
346pub struct Symbol {
347 pub language_server_name: LanguageServerName,
348 pub source_worktree_id: WorktreeId,
349 pub path: ProjectPath,
350 pub label: CodeLabel,
351 pub name: String,
352 pub kind: lsp::SymbolKind,
353 pub range: Range<Unclipped<PointUtf16>>,
354 pub signature: [u8; 32],
355}
356
357#[derive(Clone, Debug, PartialEq)]
358pub struct HoverBlock {
359 pub text: String,
360 pub kind: HoverBlockKind,
361}
362
363#[derive(Clone, Debug, PartialEq)]
364pub enum HoverBlockKind {
365 PlainText,
366 Markdown,
367 Code { language: String },
368}
369
370#[derive(Debug)]
371pub struct Hover {
372 pub contents: Vec<HoverBlock>,
373 pub range: Option<Range<language::Anchor>>,
374 pub language: Option<Arc<Language>>,
375}
376
377#[derive(Default)]
378pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
379
380impl DiagnosticSummary {
381 fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
382 let mut this = Self {
383 error_count: 0,
384 warning_count: 0,
385 };
386
387 for entry in diagnostics {
388 if entry.diagnostic.is_primary {
389 match entry.diagnostic.severity {
390 DiagnosticSeverity::ERROR => this.error_count += 1,
391 DiagnosticSeverity::WARNING => this.warning_count += 1,
392 _ => {}
393 }
394 }
395 }
396
397 this
398 }
399
400 pub fn is_empty(&self) -> bool {
401 self.error_count == 0 && self.warning_count == 0
402 }
403
404 pub fn to_proto(
405 &self,
406 language_server_id: LanguageServerId,
407 path: &Path,
408 ) -> proto::DiagnosticSummary {
409 proto::DiagnosticSummary {
410 path: path.to_string_lossy().to_string(),
411 language_server_id: language_server_id.0 as u64,
412 error_count: self.error_count as u32,
413 warning_count: self.warning_count as u32,
414 }
415 }
416}
417
418#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
419pub struct ProjectEntryId(usize);
420
421impl ProjectEntryId {
422 pub const MAX: Self = Self(usize::MAX);
423
424 pub fn new(counter: &AtomicUsize) -> Self {
425 Self(counter.fetch_add(1, SeqCst))
426 }
427
428 pub fn from_proto(id: u64) -> Self {
429 Self(id as usize)
430 }
431
432 pub fn to_proto(&self) -> u64 {
433 self.0 as u64
434 }
435
436 pub fn to_usize(&self) -> usize {
437 self.0
438 }
439}
440
441#[derive(Debug, Clone, Copy, PartialEq, Eq)]
442pub enum FormatTrigger {
443 Save,
444 Manual,
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.start_pending_language_server(
2427 language.clone(),
2428 adapter.clone(),
2429 worktree_path,
2430 self.client.http_client(),
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 task = {
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,
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 println!("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_id(
2487 server_id,
2488 installation_test_binary,
2489 cx,
2490 )
2491 });
2492 }
2493 }
2494
2495 None
2496 }
2497 }
2498 })
2499 };
2500 let state = LanguageServerState::Starting {
2501 language,
2502 adapter,
2503 task,
2504 };
2505
2506 self.language_servers.insert(server_id, state);
2507 self.language_server_ids.insert(key, server_id);
2508 }
2509
2510 fn reinstall_language_server(
2511 &mut self,
2512 server_id: LanguageServerId,
2513 cx: &mut ModelContext<Self>,
2514 ) -> Option<Task<()>> {
2515 println!("starting to reinstall server");
2516 let (language, adapter, server) = match self.language_servers.remove(&server_id) {
2517 Some(LanguageServerState::Running {
2518 language,
2519 adapter,
2520 server,
2521 ..
2522 }) => (language.clone(), adapter.clone(), Some(server)),
2523
2524 Some(LanguageServerState::Starting {
2525 language, adapter, ..
2526 }) => (language.clone(), adapter.clone(), None),
2527
2528 _ => return None,
2529 };
2530
2531 for worktree in &self.worktrees {
2532 if let Some(worktree) = worktree.upgrade(cx) {
2533 let key = (worktree.read(cx).id(), adapter.name.clone());
2534 self.language_server_ids.remove(&key);
2535 }
2536 }
2537
2538 Some(cx.spawn(move |this, mut cx| async move {
2539 if let Some(task) = server.and_then(|server| server.shutdown()) {
2540 println!("shutting down existing server");
2541 task.await;
2542 }
2543
2544 // TODO: This is race-safe with regards to preventing new instances from
2545 // starting while deleting, but existing instances in other projects are going
2546 // to be very confused and messed up
2547 this.update(&mut cx, |this, cx| {
2548 this.languages.delete_server_container(adapter.clone(), cx)
2549 })
2550 .await;
2551
2552 this.update(&mut cx, |this, mut cx| {
2553 let worktrees = this.worktrees.clone();
2554 for worktree in worktrees {
2555 let worktree = match worktree.upgrade(cx) {
2556 Some(worktree) => worktree.read(cx),
2557 None => continue,
2558 };
2559 let worktree_id = worktree.id();
2560 let root_path = worktree.abs_path();
2561
2562 println!("prompting server start: {:?}", &adapter.name.0);
2563 this.start_language_server(
2564 worktree_id,
2565 root_path,
2566 adapter.clone(),
2567 language.clone(),
2568 &mut cx,
2569 );
2570 }
2571 })
2572 }))
2573 }
2574
2575 async fn setup_and_insert_language_server(
2576 this: WeakModelHandle<Self>,
2577 initialization_options: Option<serde_json::Value>,
2578 pending_server: PendingLanguageServer,
2579 adapter: Arc<CachedLspAdapter>,
2580 languages: Arc<LanguageRegistry>,
2581 language: Arc<Language>,
2582 server_id: LanguageServerId,
2583 key: (WorktreeId, LanguageServerName),
2584 cx: &mut AsyncAppContext,
2585 ) -> Result<Arc<LanguageServer>> {
2586 let language_server = Self::setup_pending_language_server(
2587 this,
2588 initialization_options,
2589 pending_server,
2590 adapter.clone(),
2591 languages,
2592 server_id,
2593 cx,
2594 )
2595 .await?;
2596
2597 let this = match this.upgrade(cx) {
2598 Some(this) => this,
2599 None => return Err(anyhow!("failed to upgrade project handle")),
2600 };
2601
2602 this.update(cx, |this, cx| {
2603 this.insert_newly_running_language_server(
2604 language,
2605 adapter,
2606 language_server.clone(),
2607 server_id,
2608 key,
2609 cx,
2610 )
2611 })?;
2612
2613 Ok(language_server)
2614 }
2615
2616 async fn setup_pending_language_server(
2617 this: WeakModelHandle<Self>,
2618 initialization_options: Option<serde_json::Value>,
2619 pending_server: PendingLanguageServer,
2620 adapter: Arc<CachedLspAdapter>,
2621 languages: Arc<LanguageRegistry>,
2622 server_id: LanguageServerId,
2623 cx: &mut AsyncAppContext,
2624 ) -> Result<Arc<LanguageServer>> {
2625 let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2626
2627 let language_server = pending_server.task.await?;
2628 let language_server = language_server.initialize(initialization_options).await?;
2629
2630 language_server
2631 .on_notification::<lsp::notification::LogMessage, _>({
2632 move |params, mut cx| {
2633 if let Some(this) = this.upgrade(&cx) {
2634 this.update(&mut cx, |_, cx| {
2635 cx.emit(Event::LanguageServerLog(server_id, params.message))
2636 });
2637 }
2638 }
2639 })
2640 .detach();
2641
2642 language_server
2643 .on_notification::<lsp::notification::PublishDiagnostics, _>({
2644 let adapter = adapter.clone();
2645 move |mut params, cx| {
2646 let this = this;
2647 let adapter = adapter.clone();
2648 cx.spawn(|mut cx| async move {
2649 adapter.process_diagnostics(&mut params).await;
2650 if let Some(this) = this.upgrade(&cx) {
2651 this.update(&mut cx, |this, cx| {
2652 this.update_diagnostics(
2653 server_id,
2654 params,
2655 &adapter.disk_based_diagnostic_sources,
2656 cx,
2657 )
2658 .log_err();
2659 });
2660 }
2661 })
2662 .detach();
2663 }
2664 })
2665 .detach();
2666
2667 language_server
2668 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2669 let languages = languages.clone();
2670 move |params, mut cx| {
2671 let languages = languages.clone();
2672 async move {
2673 let workspace_config =
2674 cx.update(|cx| languages.workspace_configuration(cx)).await;
2675 Ok(params
2676 .items
2677 .into_iter()
2678 .map(|item| {
2679 if let Some(section) = &item.section {
2680 workspace_config
2681 .get(section)
2682 .cloned()
2683 .unwrap_or(serde_json::Value::Null)
2684 } else {
2685 workspace_config.clone()
2686 }
2687 })
2688 .collect())
2689 }
2690 }
2691 })
2692 .detach();
2693
2694 // Even though we don't have handling for these requests, respond to them to
2695 // avoid stalling any language server like `gopls` which waits for a response
2696 // to these requests when initializing.
2697 language_server
2698 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>(
2699 move |params, mut cx| async move {
2700 if let Some(this) = this.upgrade(&cx) {
2701 this.update(&mut cx, |this, _| {
2702 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
2703 {
2704 if let lsp::NumberOrString::String(token) = params.token {
2705 status.progress_tokens.insert(token);
2706 }
2707 }
2708 });
2709 }
2710 Ok(())
2711 },
2712 )
2713 .detach();
2714 language_server
2715 .on_request::<lsp::request::RegisterCapability, _, _>({
2716 move |params, mut cx| async move {
2717 let this = this
2718 .upgrade(&cx)
2719 .ok_or_else(|| anyhow!("project dropped"))?;
2720 for reg in params.registrations {
2721 if reg.method == "workspace/didChangeWatchedFiles" {
2722 if let Some(options) = reg.register_options {
2723 let options = serde_json::from_value(options)?;
2724 this.update(&mut cx, |this, cx| {
2725 this.on_lsp_did_change_watched_files(server_id, options, cx);
2726 });
2727 }
2728 }
2729 }
2730 Ok(())
2731 }
2732 })
2733 .detach();
2734
2735 language_server
2736 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2737 let adapter = adapter.clone();
2738 move |params, cx| {
2739 Self::on_lsp_workspace_edit(this, params, server_id, adapter.clone(), cx)
2740 }
2741 })
2742 .detach();
2743
2744 let disk_based_diagnostics_progress_token =
2745 adapter.disk_based_diagnostics_progress_token.clone();
2746
2747 language_server
2748 .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
2749 if let Some(this) = this.upgrade(&cx) {
2750 this.update(&mut cx, |this, cx| {
2751 this.on_lsp_progress(
2752 params,
2753 server_id,
2754 disk_based_diagnostics_progress_token.clone(),
2755 cx,
2756 );
2757 });
2758 }
2759 })
2760 .detach();
2761
2762 language_server
2763 .notify::<lsp::notification::DidChangeConfiguration>(
2764 lsp::DidChangeConfigurationParams {
2765 settings: workspace_config,
2766 },
2767 )
2768 .ok();
2769
2770 Ok(language_server)
2771 }
2772
2773 fn insert_newly_running_language_server(
2774 &mut self,
2775 language: Arc<Language>,
2776 adapter: Arc<CachedLspAdapter>,
2777 language_server: Arc<LanguageServer>,
2778 server_id: LanguageServerId,
2779 key: (WorktreeId, LanguageServerName),
2780 cx: &mut ModelContext<Self>,
2781 ) -> Result<()> {
2782 // If the language server for this key doesn't match the server id, don't store the
2783 // server. Which will cause it to be dropped, killing the process
2784 if self
2785 .language_server_ids
2786 .get(&key)
2787 .map(|id| id != &server_id)
2788 .unwrap_or(false)
2789 {
2790 return Ok(());
2791 }
2792
2793 // Update language_servers collection with Running variant of LanguageServerState
2794 // indicating that the server is up and running and ready
2795 self.language_servers.insert(
2796 server_id,
2797 LanguageServerState::Running {
2798 adapter: adapter.clone(),
2799 language: language.clone(),
2800 watched_paths: Default::default(),
2801 server: language_server.clone(),
2802 simulate_disk_based_diagnostics_completion: None,
2803 },
2804 );
2805
2806 self.language_server_statuses.insert(
2807 server_id,
2808 LanguageServerStatus {
2809 name: language_server.name().to_string(),
2810 pending_work: Default::default(),
2811 has_pending_diagnostic_updates: false,
2812 progress_tokens: Default::default(),
2813 },
2814 );
2815
2816 cx.emit(Event::LanguageServerAdded(server_id));
2817
2818 if let Some(project_id) = self.remote_id() {
2819 self.client.send(proto::StartLanguageServer {
2820 project_id,
2821 server: Some(proto::LanguageServer {
2822 id: server_id.0 as u64,
2823 name: language_server.name().to_string(),
2824 }),
2825 })?;
2826 }
2827
2828 // Tell the language server about every open buffer in the worktree that matches the language.
2829 for buffer in self.opened_buffers.values() {
2830 if let Some(buffer_handle) = buffer.upgrade(cx) {
2831 let buffer = buffer_handle.read(cx);
2832 let file = match File::from_dyn(buffer.file()) {
2833 Some(file) => file,
2834 None => continue,
2835 };
2836 let language = match buffer.language() {
2837 Some(language) => language,
2838 None => continue,
2839 };
2840
2841 if file.worktree.read(cx).id() != key.0
2842 || !language.lsp_adapters().iter().any(|a| a.name == key.1)
2843 {
2844 continue;
2845 }
2846
2847 let file = match file.as_local() {
2848 Some(file) => file,
2849 None => continue,
2850 };
2851
2852 let versions = self
2853 .buffer_snapshots
2854 .entry(buffer.remote_id())
2855 .or_default()
2856 .entry(server_id)
2857 .or_insert_with(|| {
2858 vec![LspBufferSnapshot {
2859 version: 0,
2860 snapshot: buffer.text_snapshot(),
2861 }]
2862 });
2863
2864 let snapshot = versions.last().unwrap();
2865 let version = snapshot.version;
2866 let initial_snapshot = &snapshot.snapshot;
2867 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2868 language_server.notify::<lsp::notification::DidOpenTextDocument>(
2869 lsp::DidOpenTextDocumentParams {
2870 text_document: lsp::TextDocumentItem::new(
2871 uri,
2872 adapter
2873 .language_ids
2874 .get(language.name().as_ref())
2875 .cloned()
2876 .unwrap_or_default(),
2877 version,
2878 initial_snapshot.text(),
2879 ),
2880 },
2881 )?;
2882
2883 buffer_handle.update(cx, |buffer, cx| {
2884 buffer.set_completion_triggers(
2885 language_server
2886 .capabilities()
2887 .completion_provider
2888 .as_ref()
2889 .and_then(|provider| provider.trigger_characters.clone())
2890 .unwrap_or_default(),
2891 cx,
2892 )
2893 });
2894 }
2895 }
2896
2897 cx.notify();
2898 Ok(())
2899 }
2900
2901 // Returns a list of all of the worktrees which no longer have a language server and the root path
2902 // for the stopped server
2903 fn stop_language_server(
2904 &mut self,
2905 worktree_id: WorktreeId,
2906 adapter_name: LanguageServerName,
2907 cx: &mut ModelContext<Self>,
2908 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2909 let key = (worktree_id, adapter_name);
2910 if let Some(server_id) = self.language_server_ids.remove(&key) {
2911 // Remove other entries for this language server as well
2912 let mut orphaned_worktrees = vec![worktree_id];
2913 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2914 for other_key in other_keys {
2915 if self.language_server_ids.get(&other_key) == Some(&server_id) {
2916 self.language_server_ids.remove(&other_key);
2917 orphaned_worktrees.push(other_key.0);
2918 }
2919 }
2920
2921 for buffer in self.opened_buffers.values() {
2922 if let Some(buffer) = buffer.upgrade(cx) {
2923 buffer.update(cx, |buffer, cx| {
2924 buffer.update_diagnostics(server_id, Default::default(), cx);
2925 });
2926 }
2927 }
2928 for worktree in &self.worktrees {
2929 if let Some(worktree) = worktree.upgrade(cx) {
2930 worktree.update(cx, |worktree, cx| {
2931 if let Some(worktree) = worktree.as_local_mut() {
2932 worktree.clear_diagnostics_for_language_server(server_id, cx);
2933 }
2934 });
2935 }
2936 }
2937
2938 self.language_server_statuses.remove(&server_id);
2939 cx.notify();
2940
2941 let server_state = self.language_servers.remove(&server_id);
2942 cx.emit(Event::LanguageServerRemoved(server_id));
2943 cx.spawn_weak(|this, mut cx| async move {
2944 let mut root_path = None;
2945
2946 let server = match server_state {
2947 Some(LanguageServerState::Validating(task)) => task.await,
2948 Some(LanguageServerState::Starting { task, .. }) => task.await,
2949 Some(LanguageServerState::Running { server, .. }) => Some(server),
2950 None => None,
2951 };
2952
2953 if let Some(server) = server {
2954 root_path = Some(server.root_path().clone());
2955 if let Some(shutdown) = server.shutdown() {
2956 shutdown.await;
2957 }
2958 }
2959
2960 if let Some(this) = this.upgrade(&cx) {
2961 this.update(&mut cx, |this, cx| {
2962 this.language_server_statuses.remove(&server_id);
2963 cx.notify();
2964 });
2965 }
2966
2967 (root_path, orphaned_worktrees)
2968 })
2969 } else {
2970 Task::ready((None, Vec::new()))
2971 }
2972 }
2973
2974 pub fn restart_language_servers_for_buffers(
2975 &mut self,
2976 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2977 cx: &mut ModelContext<Self>,
2978 ) -> Option<()> {
2979 let language_server_lookup_info: HashSet<(ModelHandle<Worktree>, Arc<Language>)> = buffers
2980 .into_iter()
2981 .filter_map(|buffer| {
2982 let buffer = buffer.read(cx);
2983 let file = File::from_dyn(buffer.file())?;
2984 let full_path = file.full_path(cx);
2985 let language = self
2986 .languages
2987 .language_for_file(&full_path, Some(buffer.as_rope()))
2988 .now_or_never()?
2989 .ok()?;
2990 Some((file.worktree.clone(), language))
2991 })
2992 .collect();
2993 for (worktree, language) in language_server_lookup_info {
2994 self.restart_language_servers(worktree, language, cx);
2995 }
2996
2997 None
2998 }
2999
3000 // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3001 fn restart_language_servers(
3002 &mut self,
3003 worktree: ModelHandle<Worktree>,
3004 language: Arc<Language>,
3005 cx: &mut ModelContext<Self>,
3006 ) {
3007 let worktree_id = worktree.read(cx).id();
3008 let fallback_path = worktree.read(cx).abs_path();
3009
3010 let mut stops = Vec::new();
3011 for adapter in language.lsp_adapters() {
3012 stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3013 }
3014
3015 if stops.is_empty() {
3016 return;
3017 }
3018 let mut stops = stops.into_iter();
3019
3020 cx.spawn_weak(|this, mut cx| async move {
3021 let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3022 for stop in stops {
3023 let (_, worktrees) = stop.await;
3024 orphaned_worktrees.extend_from_slice(&worktrees);
3025 }
3026
3027 let this = match this.upgrade(&cx) {
3028 Some(this) => this,
3029 None => return,
3030 };
3031
3032 this.update(&mut cx, |this, cx| {
3033 // Attempt to restart using original server path. Fallback to passed in
3034 // path if we could not retrieve the root path
3035 let root_path = original_root_path
3036 .map(|path_buf| Arc::from(path_buf.as_path()))
3037 .unwrap_or(fallback_path);
3038
3039 this.start_language_servers(&worktree, root_path, language.clone(), cx);
3040
3041 // Lookup new server ids and set them for each of the orphaned worktrees
3042 for adapter in language.lsp_adapters() {
3043 if let Some(new_server_id) = this
3044 .language_server_ids
3045 .get(&(worktree_id, adapter.name.clone()))
3046 .cloned()
3047 {
3048 for &orphaned_worktree in &orphaned_worktrees {
3049 this.language_server_ids
3050 .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3051 }
3052 }
3053 }
3054 });
3055 })
3056 .detach();
3057 }
3058
3059 fn check_errored_language_server(
3060 &self,
3061 language_server: Arc<LanguageServer>,
3062 cx: &mut ModelContext<Self>,
3063 ) {
3064 if !language_server.is_dead() {
3065 return;
3066 }
3067
3068 let server_id = language_server.server_id();
3069 let installation_test_binary = language_server.installation_test_binary().clone();
3070 Self::check_errored_server_id(server_id, installation_test_binary, cx);
3071 }
3072
3073 fn check_errored_server_id(
3074 server_id: LanguageServerId,
3075 installation_test_binary: Option<LanguageServerBinary>,
3076 cx: &mut ModelContext<Self>,
3077 ) {
3078 cx.spawn(|this, mut cx| async move {
3079 println!("About to spawn test binary");
3080 // A lack of test binary counts as a failure
3081 let process = installation_test_binary.and_then(|binary| {
3082 smol::process::Command::new(&binary.path)
3083 .current_dir(&binary.path)
3084 .args(binary.arguments)
3085 .stdin(Stdio::piped())
3086 .stdout(Stdio::piped())
3087 .stderr(Stdio::inherit())
3088 .kill_on_drop(true)
3089 .spawn()
3090 .ok()
3091 });
3092
3093 const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3094 let mut timeout = cx.background().timer(PROCESS_TIMEOUT).fuse();
3095
3096 let mut errored = false;
3097 if let Some(mut process) = process {
3098 futures::select! {
3099 status = process.status().fuse() => match status {
3100 Ok(status) => errored = !dbg!(status.success()),
3101 Err(_) => errored = true,
3102 },
3103
3104 _ = timeout => { println!("test binary time-ed out"); }
3105 }
3106 } else {
3107 println!("test binary failed to launch");
3108 errored = true;
3109 }
3110
3111 if errored {
3112 let task = this.update(&mut cx, move |this, mut cx| {
3113 this.reinstall_language_server(server_id, &mut cx)
3114 });
3115
3116 if let Some(task) = task {
3117 task.await;
3118 }
3119 }
3120 })
3121 .detach();
3122 }
3123
3124 fn on_lsp_progress(
3125 &mut self,
3126 progress: lsp::ProgressParams,
3127 language_server_id: LanguageServerId,
3128 disk_based_diagnostics_progress_token: Option<String>,
3129 cx: &mut ModelContext<Self>,
3130 ) {
3131 let token = match progress.token {
3132 lsp::NumberOrString::String(token) => token,
3133 lsp::NumberOrString::Number(token) => {
3134 log::info!("skipping numeric progress token {}", token);
3135 return;
3136 }
3137 };
3138 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3139 let language_server_status =
3140 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3141 status
3142 } else {
3143 return;
3144 };
3145
3146 if !language_server_status.progress_tokens.contains(&token) {
3147 return;
3148 }
3149
3150 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3151 .as_ref()
3152 .map_or(false, |disk_based_token| {
3153 token.starts_with(disk_based_token)
3154 });
3155
3156 match progress {
3157 lsp::WorkDoneProgress::Begin(report) => {
3158 if is_disk_based_diagnostics_progress {
3159 language_server_status.has_pending_diagnostic_updates = true;
3160 self.disk_based_diagnostics_started(language_server_id, cx);
3161 self.buffer_ordered_messages_tx
3162 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3163 language_server_id,
3164 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3165 })
3166 .ok();
3167 } else {
3168 self.on_lsp_work_start(
3169 language_server_id,
3170 token.clone(),
3171 LanguageServerProgress {
3172 message: report.message.clone(),
3173 percentage: report.percentage.map(|p| p as usize),
3174 last_update_at: Instant::now(),
3175 },
3176 cx,
3177 );
3178 self.buffer_ordered_messages_tx
3179 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3180 language_server_id,
3181 message: proto::update_language_server::Variant::WorkStart(
3182 proto::LspWorkStart {
3183 token,
3184 message: report.message,
3185 percentage: report.percentage.map(|p| p as u32),
3186 },
3187 ),
3188 })
3189 .ok();
3190 }
3191 }
3192 lsp::WorkDoneProgress::Report(report) => {
3193 if !is_disk_based_diagnostics_progress {
3194 self.on_lsp_work_progress(
3195 language_server_id,
3196 token.clone(),
3197 LanguageServerProgress {
3198 message: report.message.clone(),
3199 percentage: report.percentage.map(|p| p as usize),
3200 last_update_at: Instant::now(),
3201 },
3202 cx,
3203 );
3204 self.buffer_ordered_messages_tx
3205 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3206 language_server_id,
3207 message: proto::update_language_server::Variant::WorkProgress(
3208 proto::LspWorkProgress {
3209 token,
3210 message: report.message,
3211 percentage: report.percentage.map(|p| p as u32),
3212 },
3213 ),
3214 })
3215 .ok();
3216 }
3217 }
3218 lsp::WorkDoneProgress::End(_) => {
3219 language_server_status.progress_tokens.remove(&token);
3220
3221 if is_disk_based_diagnostics_progress {
3222 language_server_status.has_pending_diagnostic_updates = false;
3223 self.disk_based_diagnostics_finished(language_server_id, cx);
3224 self.buffer_ordered_messages_tx
3225 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3226 language_server_id,
3227 message:
3228 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3229 Default::default(),
3230 ),
3231 })
3232 .ok();
3233 } else {
3234 self.on_lsp_work_end(language_server_id, token.clone(), cx);
3235 self.buffer_ordered_messages_tx
3236 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3237 language_server_id,
3238 message: proto::update_language_server::Variant::WorkEnd(
3239 proto::LspWorkEnd { token },
3240 ),
3241 })
3242 .ok();
3243 }
3244 }
3245 }
3246 }
3247
3248 fn on_lsp_work_start(
3249 &mut self,
3250 language_server_id: LanguageServerId,
3251 token: String,
3252 progress: LanguageServerProgress,
3253 cx: &mut ModelContext<Self>,
3254 ) {
3255 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3256 status.pending_work.insert(token, progress);
3257 cx.notify();
3258 }
3259 }
3260
3261 fn on_lsp_work_progress(
3262 &mut self,
3263 language_server_id: LanguageServerId,
3264 token: String,
3265 progress: LanguageServerProgress,
3266 cx: &mut ModelContext<Self>,
3267 ) {
3268 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3269 let entry = status
3270 .pending_work
3271 .entry(token)
3272 .or_insert(LanguageServerProgress {
3273 message: Default::default(),
3274 percentage: Default::default(),
3275 last_update_at: progress.last_update_at,
3276 });
3277 if progress.message.is_some() {
3278 entry.message = progress.message;
3279 }
3280 if progress.percentage.is_some() {
3281 entry.percentage = progress.percentage;
3282 }
3283 entry.last_update_at = progress.last_update_at;
3284 cx.notify();
3285 }
3286 }
3287
3288 fn on_lsp_work_end(
3289 &mut self,
3290 language_server_id: LanguageServerId,
3291 token: String,
3292 cx: &mut ModelContext<Self>,
3293 ) {
3294 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3295 status.pending_work.remove(&token);
3296 cx.notify();
3297 }
3298 }
3299
3300 fn on_lsp_did_change_watched_files(
3301 &mut self,
3302 language_server_id: LanguageServerId,
3303 params: DidChangeWatchedFilesRegistrationOptions,
3304 cx: &mut ModelContext<Self>,
3305 ) {
3306 if let Some(LanguageServerState::Running { watched_paths, .. }) =
3307 self.language_servers.get_mut(&language_server_id)
3308 {
3309 let mut builders = HashMap::default();
3310 for watcher in params.watchers {
3311 for worktree in &self.worktrees {
3312 if let Some(worktree) = worktree.upgrade(cx) {
3313 let worktree = worktree.read(cx);
3314 if let Some(abs_path) = worktree.abs_path().to_str() {
3315 if let Some(suffix) = match &watcher.glob_pattern {
3316 lsp::GlobPattern::String(s) => s,
3317 lsp::GlobPattern::Relative(rp) => &rp.pattern,
3318 }
3319 .strip_prefix(abs_path)
3320 .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR))
3321 {
3322 if let Some(glob) = Glob::new(suffix).log_err() {
3323 builders
3324 .entry(worktree.id())
3325 .or_insert_with(|| GlobSetBuilder::new())
3326 .add(glob);
3327 }
3328 break;
3329 }
3330 }
3331 }
3332 }
3333 }
3334
3335 watched_paths.clear();
3336 for (worktree_id, builder) in builders {
3337 if let Ok(globset) = builder.build() {
3338 watched_paths.insert(worktree_id, globset);
3339 }
3340 }
3341
3342 cx.notify();
3343 }
3344 }
3345
3346 async fn on_lsp_workspace_edit(
3347 this: WeakModelHandle<Self>,
3348 params: lsp::ApplyWorkspaceEditParams,
3349 server_id: LanguageServerId,
3350 adapter: Arc<CachedLspAdapter>,
3351 mut cx: AsyncAppContext,
3352 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3353 let this = this
3354 .upgrade(&cx)
3355 .ok_or_else(|| anyhow!("project project closed"))?;
3356 let language_server = this
3357 .read_with(&cx, |this, _| this.language_server_for_id(server_id))
3358 .ok_or_else(|| anyhow!("language server not found"))?;
3359 let transaction = Self::deserialize_workspace_edit(
3360 this.clone(),
3361 params.edit,
3362 true,
3363 adapter.clone(),
3364 language_server.clone(),
3365 &mut cx,
3366 )
3367 .await
3368 .log_err();
3369 this.update(&mut cx, |this, _| {
3370 if let Some(transaction) = transaction {
3371 this.last_workspace_edits_by_language_server
3372 .insert(server_id, transaction);
3373 }
3374 });
3375 Ok(lsp::ApplyWorkspaceEditResponse {
3376 applied: true,
3377 failed_change: None,
3378 failure_reason: None,
3379 })
3380 }
3381
3382 pub fn language_server_statuses(
3383 &self,
3384 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3385 self.language_server_statuses.values()
3386 }
3387
3388 pub fn update_diagnostics(
3389 &mut self,
3390 language_server_id: LanguageServerId,
3391 mut params: lsp::PublishDiagnosticsParams,
3392 disk_based_sources: &[String],
3393 cx: &mut ModelContext<Self>,
3394 ) -> Result<()> {
3395 let abs_path = params
3396 .uri
3397 .to_file_path()
3398 .map_err(|_| anyhow!("URI is not a file"))?;
3399 let mut diagnostics = Vec::default();
3400 let mut primary_diagnostic_group_ids = HashMap::default();
3401 let mut sources_by_group_id = HashMap::default();
3402 let mut supporting_diagnostics = HashMap::default();
3403
3404 // Ensure that primary diagnostics are always the most severe
3405 params.diagnostics.sort_by_key(|item| item.severity);
3406
3407 for diagnostic in ¶ms.diagnostics {
3408 let source = diagnostic.source.as_ref();
3409 let code = diagnostic.code.as_ref().map(|code| match code {
3410 lsp::NumberOrString::Number(code) => code.to_string(),
3411 lsp::NumberOrString::String(code) => code.clone(),
3412 });
3413 let range = range_from_lsp(diagnostic.range);
3414 let is_supporting = diagnostic
3415 .related_information
3416 .as_ref()
3417 .map_or(false, |infos| {
3418 infos.iter().any(|info| {
3419 primary_diagnostic_group_ids.contains_key(&(
3420 source,
3421 code.clone(),
3422 range_from_lsp(info.location.range),
3423 ))
3424 })
3425 });
3426
3427 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3428 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3429 });
3430
3431 if is_supporting {
3432 supporting_diagnostics.insert(
3433 (source, code.clone(), range),
3434 (diagnostic.severity, is_unnecessary),
3435 );
3436 } else {
3437 let group_id = post_inc(&mut self.next_diagnostic_group_id);
3438 let is_disk_based =
3439 source.map_or(false, |source| disk_based_sources.contains(source));
3440
3441 sources_by_group_id.insert(group_id, source);
3442 primary_diagnostic_group_ids
3443 .insert((source, code.clone(), range.clone()), group_id);
3444
3445 diagnostics.push(DiagnosticEntry {
3446 range,
3447 diagnostic: Diagnostic {
3448 source: diagnostic.source.clone(),
3449 code: code.clone(),
3450 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3451 message: diagnostic.message.clone(),
3452 group_id,
3453 is_primary: true,
3454 is_valid: true,
3455 is_disk_based,
3456 is_unnecessary,
3457 },
3458 });
3459 if let Some(infos) = &diagnostic.related_information {
3460 for info in infos {
3461 if info.location.uri == params.uri && !info.message.is_empty() {
3462 let range = range_from_lsp(info.location.range);
3463 diagnostics.push(DiagnosticEntry {
3464 range,
3465 diagnostic: Diagnostic {
3466 source: diagnostic.source.clone(),
3467 code: code.clone(),
3468 severity: DiagnosticSeverity::INFORMATION,
3469 message: info.message.clone(),
3470 group_id,
3471 is_primary: false,
3472 is_valid: true,
3473 is_disk_based,
3474 is_unnecessary: false,
3475 },
3476 });
3477 }
3478 }
3479 }
3480 }
3481 }
3482
3483 for entry in &mut diagnostics {
3484 let diagnostic = &mut entry.diagnostic;
3485 if !diagnostic.is_primary {
3486 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3487 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3488 source,
3489 diagnostic.code.clone(),
3490 entry.range.clone(),
3491 )) {
3492 if let Some(severity) = severity {
3493 diagnostic.severity = severity;
3494 }
3495 diagnostic.is_unnecessary = is_unnecessary;
3496 }
3497 }
3498 }
3499
3500 self.update_diagnostic_entries(
3501 language_server_id,
3502 abs_path,
3503 params.version,
3504 diagnostics,
3505 cx,
3506 )?;
3507 Ok(())
3508 }
3509
3510 pub fn update_diagnostic_entries(
3511 &mut self,
3512 server_id: LanguageServerId,
3513 abs_path: PathBuf,
3514 version: Option<i32>,
3515 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3516 cx: &mut ModelContext<Project>,
3517 ) -> Result<(), anyhow::Error> {
3518 let (worktree, relative_path) = self
3519 .find_local_worktree(&abs_path, cx)
3520 .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3521
3522 let project_path = ProjectPath {
3523 worktree_id: worktree.read(cx).id(),
3524 path: relative_path.into(),
3525 };
3526
3527 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3528 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3529 }
3530
3531 let updated = worktree.update(cx, |worktree, cx| {
3532 worktree
3533 .as_local_mut()
3534 .ok_or_else(|| anyhow!("not a local worktree"))?
3535 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3536 })?;
3537 if updated {
3538 cx.emit(Event::DiagnosticsUpdated {
3539 language_server_id: server_id,
3540 path: project_path,
3541 });
3542 }
3543 Ok(())
3544 }
3545
3546 fn update_buffer_diagnostics(
3547 &mut self,
3548 buffer: &ModelHandle<Buffer>,
3549 server_id: LanguageServerId,
3550 version: Option<i32>,
3551 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3552 cx: &mut ModelContext<Self>,
3553 ) -> Result<()> {
3554 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3555 Ordering::Equal
3556 .then_with(|| b.is_primary.cmp(&a.is_primary))
3557 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3558 .then_with(|| a.severity.cmp(&b.severity))
3559 .then_with(|| a.message.cmp(&b.message))
3560 }
3561
3562 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3563
3564 diagnostics.sort_unstable_by(|a, b| {
3565 Ordering::Equal
3566 .then_with(|| a.range.start.cmp(&b.range.start))
3567 .then_with(|| b.range.end.cmp(&a.range.end))
3568 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3569 });
3570
3571 let mut sanitized_diagnostics = Vec::new();
3572 let edits_since_save = Patch::new(
3573 snapshot
3574 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3575 .collect(),
3576 );
3577 for entry in diagnostics {
3578 let start;
3579 let end;
3580 if entry.diagnostic.is_disk_based {
3581 // Some diagnostics are based on files on disk instead of buffers'
3582 // current contents. Adjust these diagnostics' ranges to reflect
3583 // any unsaved edits.
3584 start = edits_since_save.old_to_new(entry.range.start);
3585 end = edits_since_save.old_to_new(entry.range.end);
3586 } else {
3587 start = entry.range.start;
3588 end = entry.range.end;
3589 }
3590
3591 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3592 ..snapshot.clip_point_utf16(end, Bias::Right);
3593
3594 // Expand empty ranges by one codepoint
3595 if range.start == range.end {
3596 // This will be go to the next boundary when being clipped
3597 range.end.column += 1;
3598 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3599 if range.start == range.end && range.end.column > 0 {
3600 range.start.column -= 1;
3601 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3602 }
3603 }
3604
3605 sanitized_diagnostics.push(DiagnosticEntry {
3606 range,
3607 diagnostic: entry.diagnostic,
3608 });
3609 }
3610 drop(edits_since_save);
3611
3612 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3613 buffer.update(cx, |buffer, cx| {
3614 buffer.update_diagnostics(server_id, set, cx)
3615 });
3616 Ok(())
3617 }
3618
3619 pub fn reload_buffers(
3620 &self,
3621 buffers: HashSet<ModelHandle<Buffer>>,
3622 push_to_history: bool,
3623 cx: &mut ModelContext<Self>,
3624 ) -> Task<Result<ProjectTransaction>> {
3625 let mut local_buffers = Vec::new();
3626 let mut remote_buffers = None;
3627 for buffer_handle in buffers {
3628 let buffer = buffer_handle.read(cx);
3629 if buffer.is_dirty() {
3630 if let Some(file) = File::from_dyn(buffer.file()) {
3631 if file.is_local() {
3632 local_buffers.push(buffer_handle);
3633 } else {
3634 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3635 }
3636 }
3637 }
3638 }
3639
3640 let remote_buffers = self.remote_id().zip(remote_buffers);
3641 let client = self.client.clone();
3642
3643 cx.spawn(|this, mut cx| async move {
3644 let mut project_transaction = ProjectTransaction::default();
3645
3646 if let Some((project_id, remote_buffers)) = remote_buffers {
3647 let response = client
3648 .request(proto::ReloadBuffers {
3649 project_id,
3650 buffer_ids: remote_buffers
3651 .iter()
3652 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3653 .collect(),
3654 })
3655 .await?
3656 .transaction
3657 .ok_or_else(|| anyhow!("missing transaction"))?;
3658 project_transaction = this
3659 .update(&mut cx, |this, cx| {
3660 this.deserialize_project_transaction(response, push_to_history, cx)
3661 })
3662 .await?;
3663 }
3664
3665 for buffer in local_buffers {
3666 let transaction = buffer
3667 .update(&mut cx, |buffer, cx| buffer.reload(cx))
3668 .await?;
3669 buffer.update(&mut cx, |buffer, cx| {
3670 if let Some(transaction) = transaction {
3671 if !push_to_history {
3672 buffer.forget_transaction(transaction.id);
3673 }
3674 project_transaction.0.insert(cx.handle(), transaction);
3675 }
3676 });
3677 }
3678
3679 Ok(project_transaction)
3680 })
3681 }
3682
3683 pub fn format(
3684 &self,
3685 buffers: HashSet<ModelHandle<Buffer>>,
3686 push_to_history: bool,
3687 trigger: FormatTrigger,
3688 cx: &mut ModelContext<Project>,
3689 ) -> Task<Result<ProjectTransaction>> {
3690 if self.is_local() {
3691 let mut buffers_with_paths_and_servers = buffers
3692 .into_iter()
3693 .filter_map(|buffer_handle| {
3694 let buffer = buffer_handle.read(cx);
3695 let file = File::from_dyn(buffer.file())?;
3696 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3697 let server = self
3698 .primary_language_servers_for_buffer(buffer, cx)
3699 .map(|s| s.1.clone());
3700 Some((buffer_handle, buffer_abs_path, server))
3701 })
3702 .collect::<Vec<_>>();
3703
3704 cx.spawn(|this, mut cx| async move {
3705 // Do not allow multiple concurrent formatting requests for the
3706 // same buffer.
3707 this.update(&mut cx, |this, cx| {
3708 buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
3709 this.buffers_being_formatted
3710 .insert(buffer.read(cx).remote_id())
3711 });
3712 });
3713
3714 let _cleanup = defer({
3715 let this = this.clone();
3716 let mut cx = cx.clone();
3717 let buffers = &buffers_with_paths_and_servers;
3718 move || {
3719 this.update(&mut cx, |this, cx| {
3720 for (buffer, _, _) in buffers {
3721 this.buffers_being_formatted
3722 .remove(&buffer.read(cx).remote_id());
3723 }
3724 });
3725 }
3726 });
3727
3728 let mut project_transaction = ProjectTransaction::default();
3729 for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3730 let settings = buffer.read_with(&cx, |buffer, cx| {
3731 language_settings(buffer.language(), buffer.file(), cx).clone()
3732 });
3733
3734 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
3735 let ensure_final_newline = settings.ensure_final_newline_on_save;
3736 let format_on_save = settings.format_on_save.clone();
3737 let formatter = settings.formatter.clone();
3738 let tab_size = settings.tab_size;
3739
3740 // First, format buffer's whitespace according to the settings.
3741 let trailing_whitespace_diff = if remove_trailing_whitespace {
3742 Some(
3743 buffer
3744 .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3745 .await,
3746 )
3747 } else {
3748 None
3749 };
3750 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3751 buffer.finalize_last_transaction();
3752 buffer.start_transaction();
3753 if let Some(diff) = trailing_whitespace_diff {
3754 buffer.apply_diff(diff, cx);
3755 }
3756 if ensure_final_newline {
3757 buffer.ensure_final_newline(cx);
3758 }
3759 buffer.end_transaction(cx)
3760 });
3761
3762 // Currently, formatting operations are represented differently depending on
3763 // whether they come from a language server or an external command.
3764 enum FormatOperation {
3765 Lsp(Vec<(Range<Anchor>, String)>),
3766 External(Diff),
3767 }
3768
3769 // Apply language-specific formatting using either a language server
3770 // or external command.
3771 let mut format_operation = None;
3772 match (formatter, format_on_save) {
3773 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3774
3775 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3776 | (_, FormatOnSave::LanguageServer) => {
3777 if let Some((language_server, buffer_abs_path)) =
3778 language_server.as_ref().zip(buffer_abs_path.as_ref())
3779 {
3780 format_operation = Some(FormatOperation::Lsp(
3781 Self::format_via_lsp(
3782 &this,
3783 &buffer,
3784 buffer_abs_path,
3785 &language_server,
3786 tab_size,
3787 &mut cx,
3788 )
3789 .await
3790 .context("failed to format via language server")?,
3791 ));
3792 }
3793 }
3794
3795 (
3796 Formatter::External { command, arguments },
3797 FormatOnSave::On | FormatOnSave::Off,
3798 )
3799 | (_, FormatOnSave::External { command, arguments }) => {
3800 if let Some(buffer_abs_path) = buffer_abs_path {
3801 format_operation = Self::format_via_external_command(
3802 &buffer,
3803 &buffer_abs_path,
3804 &command,
3805 &arguments,
3806 &mut cx,
3807 )
3808 .await
3809 .context(format!(
3810 "failed to format via external command {:?}",
3811 command
3812 ))?
3813 .map(FormatOperation::External);
3814 }
3815 }
3816 };
3817
3818 buffer.update(&mut cx, |b, cx| {
3819 // If the buffer had its whitespace formatted and was edited while the language-specific
3820 // formatting was being computed, avoid applying the language-specific formatting, because
3821 // it can't be grouped with the whitespace formatting in the undo history.
3822 if let Some(transaction_id) = whitespace_transaction_id {
3823 if b.peek_undo_stack()
3824 .map_or(true, |e| e.transaction_id() != transaction_id)
3825 {
3826 format_operation.take();
3827 }
3828 }
3829
3830 // Apply any language-specific formatting, and group the two formatting operations
3831 // in the buffer's undo history.
3832 if let Some(operation) = format_operation {
3833 match operation {
3834 FormatOperation::Lsp(edits) => {
3835 b.edit(edits, None, cx);
3836 }
3837 FormatOperation::External(diff) => {
3838 b.apply_diff(diff, cx);
3839 }
3840 }
3841
3842 if let Some(transaction_id) = whitespace_transaction_id {
3843 b.group_until_transaction(transaction_id);
3844 }
3845 }
3846
3847 if let Some(transaction) = b.finalize_last_transaction().cloned() {
3848 if !push_to_history {
3849 b.forget_transaction(transaction.id);
3850 }
3851 project_transaction.0.insert(buffer.clone(), transaction);
3852 }
3853 });
3854 }
3855
3856 Ok(project_transaction)
3857 })
3858 } else {
3859 let remote_id = self.remote_id();
3860 let client = self.client.clone();
3861 cx.spawn(|this, mut cx| async move {
3862 let mut project_transaction = ProjectTransaction::default();
3863 if let Some(project_id) = remote_id {
3864 let response = client
3865 .request(proto::FormatBuffers {
3866 project_id,
3867 trigger: trigger as i32,
3868 buffer_ids: buffers
3869 .iter()
3870 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3871 .collect(),
3872 })
3873 .await?
3874 .transaction
3875 .ok_or_else(|| anyhow!("missing transaction"))?;
3876 project_transaction = this
3877 .update(&mut cx, |this, cx| {
3878 this.deserialize_project_transaction(response, push_to_history, cx)
3879 })
3880 .await?;
3881 }
3882 Ok(project_transaction)
3883 })
3884 }
3885 }
3886
3887 async fn format_via_lsp(
3888 this: &ModelHandle<Self>,
3889 buffer: &ModelHandle<Buffer>,
3890 abs_path: &Path,
3891 language_server: &Arc<LanguageServer>,
3892 tab_size: NonZeroU32,
3893 cx: &mut AsyncAppContext,
3894 ) -> Result<Vec<(Range<Anchor>, String)>> {
3895 let uri = lsp::Url::from_file_path(abs_path)
3896 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
3897 let text_document = lsp::TextDocumentIdentifier::new(uri);
3898 let capabilities = &language_server.capabilities();
3899
3900 let formatting_provider = capabilities.document_formatting_provider.as_ref();
3901 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
3902
3903 let result = if !matches!(formatting_provider, Some(OneOf::Left(false))) {
3904 language_server
3905 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3906 text_document,
3907 options: lsp_command::lsp_formatting_options(tab_size.get()),
3908 work_done_progress_params: Default::default(),
3909 })
3910 .await
3911 } else if !matches!(range_formatting_provider, Some(OneOf::Left(false))) {
3912 let buffer_start = lsp::Position::new(0, 0);
3913 let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()));
3914
3915 language_server
3916 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3917 text_document,
3918 range: lsp::Range::new(buffer_start, buffer_end),
3919 options: lsp_command::lsp_formatting_options(tab_size.get()),
3920 work_done_progress_params: Default::default(),
3921 })
3922 .await
3923 } else {
3924 Ok(None)
3925 };
3926
3927 let lsp_edits = match result {
3928 Ok(lsp_edits) => lsp_edits,
3929
3930 Err(err) => {
3931 log::warn!(
3932 "Error firing format request to {}: {}",
3933 language_server.name(),
3934 err
3935 );
3936
3937 this.update(cx, |this, cx| {
3938 this.check_errored_language_server(language_server.clone(), cx);
3939 });
3940
3941 None
3942 }
3943 };
3944
3945 if let Some(lsp_edits) = lsp_edits {
3946 this.update(cx, |this, cx| {
3947 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
3948 })
3949 .await
3950 } else {
3951 Ok(Vec::new())
3952 }
3953 }
3954
3955 async fn format_via_external_command(
3956 buffer: &ModelHandle<Buffer>,
3957 buffer_abs_path: &Path,
3958 command: &str,
3959 arguments: &[String],
3960 cx: &mut AsyncAppContext,
3961 ) -> Result<Option<Diff>> {
3962 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3963 let file = File::from_dyn(buffer.file())?;
3964 let worktree = file.worktree.read(cx).as_local()?;
3965 let mut worktree_path = worktree.abs_path().to_path_buf();
3966 if worktree.root_entry()?.is_file() {
3967 worktree_path.pop();
3968 }
3969 Some(worktree_path)
3970 });
3971
3972 if let Some(working_dir_path) = working_dir_path {
3973 let mut child =
3974 smol::process::Command::new(command)
3975 .args(arguments.iter().map(|arg| {
3976 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3977 }))
3978 .current_dir(&working_dir_path)
3979 .stdin(smol::process::Stdio::piped())
3980 .stdout(smol::process::Stdio::piped())
3981 .stderr(smol::process::Stdio::piped())
3982 .spawn()?;
3983 let stdin = child
3984 .stdin
3985 .as_mut()
3986 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3987 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3988 for chunk in text.chunks() {
3989 stdin.write_all(chunk.as_bytes()).await?;
3990 }
3991 stdin.flush().await?;
3992
3993 let output = child.output().await?;
3994 if !output.status.success() {
3995 return Err(anyhow!(
3996 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3997 output.status.code(),
3998 String::from_utf8_lossy(&output.stdout),
3999 String::from_utf8_lossy(&output.stderr),
4000 ));
4001 }
4002
4003 let stdout = String::from_utf8(output.stdout)?;
4004 Ok(Some(
4005 buffer
4006 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
4007 .await,
4008 ))
4009 } else {
4010 Ok(None)
4011 }
4012 }
4013
4014 pub fn definition<T: ToPointUtf16>(
4015 &self,
4016 buffer: &ModelHandle<Buffer>,
4017 position: T,
4018 cx: &mut ModelContext<Self>,
4019 ) -> Task<Result<Vec<LocationLink>>> {
4020 let position = position.to_point_utf16(buffer.read(cx));
4021 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
4022 }
4023
4024 pub fn type_definition<T: ToPointUtf16>(
4025 &self,
4026 buffer: &ModelHandle<Buffer>,
4027 position: T,
4028 cx: &mut ModelContext<Self>,
4029 ) -> Task<Result<Vec<LocationLink>>> {
4030 let position = position.to_point_utf16(buffer.read(cx));
4031 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
4032 }
4033
4034 pub fn references<T: ToPointUtf16>(
4035 &self,
4036 buffer: &ModelHandle<Buffer>,
4037 position: T,
4038 cx: &mut ModelContext<Self>,
4039 ) -> Task<Result<Vec<Location>>> {
4040 let position = position.to_point_utf16(buffer.read(cx));
4041 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
4042 }
4043
4044 pub fn document_highlights<T: ToPointUtf16>(
4045 &self,
4046 buffer: &ModelHandle<Buffer>,
4047 position: T,
4048 cx: &mut ModelContext<Self>,
4049 ) -> Task<Result<Vec<DocumentHighlight>>> {
4050 let position = position.to_point_utf16(buffer.read(cx));
4051 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
4052 }
4053
4054 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4055 if self.is_local() {
4056 let mut requests = Vec::new();
4057 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4058 let worktree_id = *worktree_id;
4059 let worktree_handle = self.worktree_for_id(worktree_id, cx);
4060 let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4061 Some(worktree) => worktree,
4062 None => continue,
4063 };
4064 let worktree_abs_path = worktree.abs_path().clone();
4065
4066 let (adapter, language, server) = match self.language_servers.get(server_id) {
4067 Some(LanguageServerState::Running {
4068 adapter,
4069 language,
4070 server,
4071 ..
4072 }) => (adapter.clone(), language.clone(), server),
4073
4074 _ => continue,
4075 };
4076
4077 requests.push(
4078 server
4079 .request::<lsp::request::WorkspaceSymbolRequest>(
4080 lsp::WorkspaceSymbolParams {
4081 query: query.to_string(),
4082 ..Default::default()
4083 },
4084 )
4085 .map_ok(move |response| {
4086 let lsp_symbols = response.map(|symbol_response| match symbol_response {
4087 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4088 flat_responses.into_iter().map(|lsp_symbol| {
4089 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4090 }).collect::<Vec<_>>()
4091 }
4092 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4093 nested_responses.into_iter().filter_map(|lsp_symbol| {
4094 let location = match lsp_symbol.location {
4095 OneOf::Left(location) => location,
4096 OneOf::Right(_) => {
4097 error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4098 return None
4099 }
4100 };
4101 Some((lsp_symbol.name, lsp_symbol.kind, location))
4102 }).collect::<Vec<_>>()
4103 }
4104 }).unwrap_or_default();
4105
4106 (
4107 adapter,
4108 language,
4109 worktree_id,
4110 worktree_abs_path,
4111 lsp_symbols,
4112 )
4113 }),
4114 );
4115 }
4116
4117 cx.spawn_weak(|this, cx| async move {
4118 let responses = futures::future::join_all(requests).await;
4119 let this = match this.upgrade(&cx) {
4120 Some(this) => this,
4121 None => return Ok(Vec::new()),
4122 };
4123
4124 let symbols = this.read_with(&cx, |this, cx| {
4125 let mut symbols = Vec::new();
4126 for response in responses {
4127 let (
4128 adapter,
4129 adapter_language,
4130 source_worktree_id,
4131 worktree_abs_path,
4132 lsp_symbols,
4133 ) = match response {
4134 Ok(response) => response,
4135
4136 Err(err) => {
4137 // TODO: Prompt installation validity check LSP ERROR
4138 return Vec::new();
4139 }
4140 };
4141
4142 symbols.extend(lsp_symbols.into_iter().filter_map(
4143 |(symbol_name, symbol_kind, symbol_location)| {
4144 let abs_path = symbol_location.uri.to_file_path().ok()?;
4145 let mut worktree_id = source_worktree_id;
4146 let path;
4147 if let Some((worktree, rel_path)) =
4148 this.find_local_worktree(&abs_path, cx)
4149 {
4150 worktree_id = worktree.read(cx).id();
4151 path = rel_path;
4152 } else {
4153 path = relativize_path(&worktree_abs_path, &abs_path);
4154 }
4155
4156 let project_path = ProjectPath {
4157 worktree_id,
4158 path: path.into(),
4159 };
4160 let signature = this.symbol_signature(&project_path);
4161 let adapter_language = adapter_language.clone();
4162 let language = this
4163 .languages
4164 .language_for_file(&project_path.path, None)
4165 .unwrap_or_else(move |_| adapter_language);
4166 let language_server_name = adapter.name.clone();
4167 Some(async move {
4168 let language = language.await;
4169 let label =
4170 language.label_for_symbol(&symbol_name, symbol_kind).await;
4171
4172 Symbol {
4173 language_server_name,
4174 source_worktree_id,
4175 path: project_path,
4176 label: label.unwrap_or_else(|| {
4177 CodeLabel::plain(symbol_name.clone(), None)
4178 }),
4179 kind: symbol_kind,
4180 name: symbol_name,
4181 range: range_from_lsp(symbol_location.range),
4182 signature,
4183 }
4184 })
4185 },
4186 ));
4187 }
4188
4189 symbols
4190 });
4191
4192 Ok(futures::future::join_all(symbols).await)
4193 })
4194 } else if let Some(project_id) = self.remote_id() {
4195 let request = self.client.request(proto::GetProjectSymbols {
4196 project_id,
4197 query: query.to_string(),
4198 });
4199 cx.spawn_weak(|this, cx| async move {
4200 let response = request.await?;
4201 let mut symbols = Vec::new();
4202 if let Some(this) = this.upgrade(&cx) {
4203 let new_symbols = this.read_with(&cx, |this, _| {
4204 response
4205 .symbols
4206 .into_iter()
4207 .map(|symbol| this.deserialize_symbol(symbol))
4208 .collect::<Vec<_>>()
4209 });
4210 symbols = futures::future::join_all(new_symbols)
4211 .await
4212 .into_iter()
4213 .filter_map(|symbol| symbol.log_err())
4214 .collect::<Vec<_>>();
4215 }
4216 Ok(symbols)
4217 })
4218 } else {
4219 Task::ready(Ok(Default::default()))
4220 }
4221 }
4222
4223 pub fn open_buffer_for_symbol(
4224 &mut self,
4225 symbol: &Symbol,
4226 cx: &mut ModelContext<Self>,
4227 ) -> Task<Result<ModelHandle<Buffer>>> {
4228 if self.is_local() {
4229 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4230 symbol.source_worktree_id,
4231 symbol.language_server_name.clone(),
4232 )) {
4233 *id
4234 } else {
4235 return Task::ready(Err(anyhow!(
4236 "language server for worktree and language not found"
4237 )));
4238 };
4239
4240 let worktree_abs_path = if let Some(worktree_abs_path) = self
4241 .worktree_for_id(symbol.path.worktree_id, cx)
4242 .and_then(|worktree| worktree.read(cx).as_local())
4243 .map(|local_worktree| local_worktree.abs_path())
4244 {
4245 worktree_abs_path
4246 } else {
4247 return Task::ready(Err(anyhow!("worktree not found for symbol")));
4248 };
4249 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
4250 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4251 uri
4252 } else {
4253 return Task::ready(Err(anyhow!("invalid symbol path")));
4254 };
4255
4256 self.open_local_buffer_via_lsp(
4257 symbol_uri,
4258 language_server_id,
4259 symbol.language_server_name.clone(),
4260 cx,
4261 )
4262 } else if let Some(project_id) = self.remote_id() {
4263 let request = self.client.request(proto::OpenBufferForSymbol {
4264 project_id,
4265 symbol: Some(serialize_symbol(symbol)),
4266 });
4267 cx.spawn(|this, mut cx| async move {
4268 let response = request.await?;
4269 this.update(&mut cx, |this, cx| {
4270 this.wait_for_remote_buffer(response.buffer_id, cx)
4271 })
4272 .await
4273 })
4274 } else {
4275 Task::ready(Err(anyhow!("project does not have a remote id")))
4276 }
4277 }
4278
4279 pub fn hover<T: ToPointUtf16>(
4280 &self,
4281 buffer: &ModelHandle<Buffer>,
4282 position: T,
4283 cx: &mut ModelContext<Self>,
4284 ) -> Task<Result<Option<Hover>>> {
4285 let position = position.to_point_utf16(buffer.read(cx));
4286 self.request_lsp(buffer.clone(), GetHover { position }, cx)
4287 }
4288
4289 pub fn completions<T: ToPointUtf16>(
4290 &self,
4291 buffer: &ModelHandle<Buffer>,
4292 position: T,
4293 cx: &mut ModelContext<Self>,
4294 ) -> Task<Result<Vec<Completion>>> {
4295 let position = position.to_point_utf16(buffer.read(cx));
4296 self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
4297 }
4298
4299 pub fn apply_additional_edits_for_completion(
4300 &self,
4301 buffer_handle: ModelHandle<Buffer>,
4302 completion: Completion,
4303 push_to_history: bool,
4304 cx: &mut ModelContext<Self>,
4305 ) -> Task<Result<Option<Transaction>>> {
4306 let buffer = buffer_handle.read(cx);
4307 let buffer_id = buffer.remote_id();
4308
4309 if self.is_local() {
4310 let lang_server = match self.primary_language_servers_for_buffer(buffer, cx) {
4311 Some((_, server)) => server.clone(),
4312 _ => return Task::ready(Ok(Default::default())),
4313 };
4314
4315 cx.spawn(|this, mut cx| async move {
4316 let resolved_completion = match lang_server
4317 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4318 .await
4319 {
4320 Ok(resolved_completion) => resolved_completion,
4321
4322 Err(err) => {
4323 // TODO: LSP ERROR
4324 return Ok(None);
4325 }
4326 };
4327
4328 if let Some(edits) = resolved_completion.additional_text_edits {
4329 let edits = this
4330 .update(&mut cx, |this, cx| {
4331 this.edits_from_lsp(
4332 &buffer_handle,
4333 edits,
4334 lang_server.server_id(),
4335 None,
4336 cx,
4337 )
4338 })
4339 .await?;
4340
4341 buffer_handle.update(&mut cx, |buffer, cx| {
4342 buffer.finalize_last_transaction();
4343 buffer.start_transaction();
4344
4345 for (range, text) in edits {
4346 let primary = &completion.old_range;
4347 let start_within = primary.start.cmp(&range.start, buffer).is_le()
4348 && primary.end.cmp(&range.start, buffer).is_ge();
4349 let end_within = range.start.cmp(&primary.end, buffer).is_le()
4350 && range.end.cmp(&primary.end, buffer).is_ge();
4351
4352 //Skip additional edits which overlap with the primary completion edit
4353 //https://github.com/zed-industries/zed/pull/1871
4354 if !start_within && !end_within {
4355 buffer.edit([(range, text)], None, cx);
4356 }
4357 }
4358
4359 let transaction = if buffer.end_transaction(cx).is_some() {
4360 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4361 if !push_to_history {
4362 buffer.forget_transaction(transaction.id);
4363 }
4364 Some(transaction)
4365 } else {
4366 None
4367 };
4368 Ok(transaction)
4369 })
4370 } else {
4371 Ok(None)
4372 }
4373 })
4374 } else if let Some(project_id) = self.remote_id() {
4375 let client = self.client.clone();
4376 cx.spawn(|_, mut cx| async move {
4377 let response = client
4378 .request(proto::ApplyCompletionAdditionalEdits {
4379 project_id,
4380 buffer_id,
4381 completion: Some(language::proto::serialize_completion(&completion)),
4382 })
4383 .await?;
4384
4385 if let Some(transaction) = response.transaction {
4386 let transaction = language::proto::deserialize_transaction(transaction)?;
4387 buffer_handle
4388 .update(&mut cx, |buffer, _| {
4389 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4390 })
4391 .await?;
4392 if push_to_history {
4393 buffer_handle.update(&mut cx, |buffer, _| {
4394 buffer.push_transaction(transaction.clone(), Instant::now());
4395 });
4396 }
4397 Ok(Some(transaction))
4398 } else {
4399 Ok(None)
4400 }
4401 })
4402 } else {
4403 Task::ready(Err(anyhow!("project does not have a remote id")))
4404 }
4405 }
4406
4407 pub fn code_actions<T: Clone + ToOffset>(
4408 &self,
4409 buffer_handle: &ModelHandle<Buffer>,
4410 range: Range<T>,
4411 cx: &mut ModelContext<Self>,
4412 ) -> Task<Result<Vec<CodeAction>>> {
4413 let buffer = buffer_handle.read(cx);
4414 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4415 self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
4416 }
4417
4418 pub fn apply_code_action(
4419 &self,
4420 buffer_handle: ModelHandle<Buffer>,
4421 mut action: CodeAction,
4422 push_to_history: bool,
4423 cx: &mut ModelContext<Self>,
4424 ) -> Task<Result<ProjectTransaction>> {
4425 if self.is_local() {
4426 let buffer = buffer_handle.read(cx);
4427 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4428 self.language_server_for_buffer(buffer, action.server_id, cx)
4429 {
4430 (adapter.clone(), server.clone())
4431 } else {
4432 return Task::ready(Ok(Default::default()));
4433 };
4434 let range = action.range.to_point_utf16(buffer);
4435
4436 cx.spawn(|this, mut cx| async move {
4437 if let Some(lsp_range) = action
4438 .lsp_action
4439 .data
4440 .as_mut()
4441 .and_then(|d| d.get_mut("codeActionParams"))
4442 .and_then(|d| d.get_mut("range"))
4443 {
4444 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4445 action.lsp_action = match lang_server
4446 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4447 .await
4448 {
4449 Ok(lsp_action) => lsp_action,
4450
4451 Err(err) => {
4452 // LSP ERROR
4453 return Err(err);
4454 }
4455 };
4456 } else {
4457 let actions = this
4458 .update(&mut cx, |this, cx| {
4459 this.code_actions(&buffer_handle, action.range, cx)
4460 })
4461 .await?;
4462 action.lsp_action = actions
4463 .into_iter()
4464 .find(|a| a.lsp_action.title == action.lsp_action.title)
4465 .ok_or_else(|| anyhow!("code action is outdated"))?
4466 .lsp_action;
4467 }
4468
4469 if let Some(edit) = action.lsp_action.edit {
4470 if edit.changes.is_some() || edit.document_changes.is_some() {
4471 return Self::deserialize_workspace_edit(
4472 this,
4473 edit,
4474 push_to_history,
4475 lsp_adapter.clone(),
4476 lang_server.clone(),
4477 &mut cx,
4478 )
4479 .await;
4480 }
4481 }
4482
4483 if let Some(command) = action.lsp_action.command {
4484 this.update(&mut cx, |this, _| {
4485 this.last_workspace_edits_by_language_server
4486 .remove(&lang_server.server_id());
4487 });
4488
4489 let result = lang_server
4490 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4491 command: command.command,
4492 arguments: command.arguments.unwrap_or_default(),
4493 ..Default::default()
4494 })
4495 .await;
4496
4497 if let Err(err) = result {
4498 // TODO: LSP ERROR
4499 return Err(err);
4500 }
4501
4502 return Ok(this.update(&mut cx, |this, _| {
4503 this.last_workspace_edits_by_language_server
4504 .remove(&lang_server.server_id())
4505 .unwrap_or_default()
4506 }));
4507 }
4508
4509 Ok(ProjectTransaction::default())
4510 })
4511 } else if let Some(project_id) = self.remote_id() {
4512 let client = self.client.clone();
4513 let request = proto::ApplyCodeAction {
4514 project_id,
4515 buffer_id: buffer_handle.read(cx).remote_id(),
4516 action: Some(language::proto::serialize_code_action(&action)),
4517 };
4518 cx.spawn(|this, mut cx| async move {
4519 let response = client
4520 .request(request)
4521 .await?
4522 .transaction
4523 .ok_or_else(|| anyhow!("missing transaction"))?;
4524 this.update(&mut cx, |this, cx| {
4525 this.deserialize_project_transaction(response, push_to_history, cx)
4526 })
4527 .await
4528 })
4529 } else {
4530 Task::ready(Err(anyhow!("project does not have a remote id")))
4531 }
4532 }
4533
4534 fn apply_on_type_formatting(
4535 &self,
4536 buffer: ModelHandle<Buffer>,
4537 position: Anchor,
4538 trigger: String,
4539 cx: &mut ModelContext<Self>,
4540 ) -> Task<Result<Option<Transaction>>> {
4541 if self.is_local() {
4542 cx.spawn(|this, mut cx| async move {
4543 // Do not allow multiple concurrent formatting requests for the
4544 // same buffer.
4545 this.update(&mut cx, |this, cx| {
4546 this.buffers_being_formatted
4547 .insert(buffer.read(cx).remote_id())
4548 });
4549
4550 let _cleanup = defer({
4551 let this = this.clone();
4552 let mut cx = cx.clone();
4553 let closure_buffer = buffer.clone();
4554 move || {
4555 this.update(&mut cx, |this, cx| {
4556 this.buffers_being_formatted
4557 .remove(&closure_buffer.read(cx).remote_id());
4558 });
4559 }
4560 });
4561
4562 buffer
4563 .update(&mut cx, |buffer, _| {
4564 buffer.wait_for_edits(Some(position.timestamp))
4565 })
4566 .await?;
4567 this.update(&mut cx, |this, cx| {
4568 let position = position.to_point_utf16(buffer.read(cx));
4569 this.on_type_format(buffer, position, trigger, false, cx)
4570 })
4571 .await
4572 })
4573 } else if let Some(project_id) = self.remote_id() {
4574 let client = self.client.clone();
4575 let request = proto::OnTypeFormatting {
4576 project_id,
4577 buffer_id: buffer.read(cx).remote_id(),
4578 position: Some(serialize_anchor(&position)),
4579 trigger,
4580 version: serialize_version(&buffer.read(cx).version()),
4581 };
4582 cx.spawn(|_, _| async move {
4583 client
4584 .request(request)
4585 .await?
4586 .transaction
4587 .map(language::proto::deserialize_transaction)
4588 .transpose()
4589 })
4590 } else {
4591 Task::ready(Err(anyhow!("project does not have a remote id")))
4592 }
4593 }
4594
4595 async fn deserialize_edits(
4596 this: ModelHandle<Self>,
4597 buffer_to_edit: ModelHandle<Buffer>,
4598 edits: Vec<lsp::TextEdit>,
4599 push_to_history: bool,
4600 _: Arc<CachedLspAdapter>,
4601 language_server: Arc<LanguageServer>,
4602 cx: &mut AsyncAppContext,
4603 ) -> Result<Option<Transaction>> {
4604 let edits = this
4605 .update(cx, |this, cx| {
4606 this.edits_from_lsp(
4607 &buffer_to_edit,
4608 edits,
4609 language_server.server_id(),
4610 None,
4611 cx,
4612 )
4613 })
4614 .await?;
4615
4616 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4617 buffer.finalize_last_transaction();
4618 buffer.start_transaction();
4619 for (range, text) in edits {
4620 buffer.edit([(range, text)], None, cx);
4621 }
4622
4623 if buffer.end_transaction(cx).is_some() {
4624 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4625 if !push_to_history {
4626 buffer.forget_transaction(transaction.id);
4627 }
4628 Some(transaction)
4629 } else {
4630 None
4631 }
4632 });
4633
4634 Ok(transaction)
4635 }
4636
4637 async fn deserialize_workspace_edit(
4638 this: ModelHandle<Self>,
4639 edit: lsp::WorkspaceEdit,
4640 push_to_history: bool,
4641 lsp_adapter: Arc<CachedLspAdapter>,
4642 language_server: Arc<LanguageServer>,
4643 cx: &mut AsyncAppContext,
4644 ) -> Result<ProjectTransaction> {
4645 let fs = this.read_with(cx, |this, _| this.fs.clone());
4646 let mut operations = Vec::new();
4647 if let Some(document_changes) = edit.document_changes {
4648 match document_changes {
4649 lsp::DocumentChanges::Edits(edits) => {
4650 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4651 }
4652 lsp::DocumentChanges::Operations(ops) => operations = ops,
4653 }
4654 } else if let Some(changes) = edit.changes {
4655 operations.extend(changes.into_iter().map(|(uri, edits)| {
4656 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4657 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4658 uri,
4659 version: None,
4660 },
4661 edits: edits.into_iter().map(OneOf::Left).collect(),
4662 })
4663 }));
4664 }
4665
4666 let mut project_transaction = ProjectTransaction::default();
4667 for operation in operations {
4668 match operation {
4669 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4670 let abs_path = op
4671 .uri
4672 .to_file_path()
4673 .map_err(|_| anyhow!("can't convert URI to path"))?;
4674
4675 if let Some(parent_path) = abs_path.parent() {
4676 fs.create_dir(parent_path).await?;
4677 }
4678 if abs_path.ends_with("/") {
4679 fs.create_dir(&abs_path).await?;
4680 } else {
4681 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4682 .await?;
4683 }
4684 }
4685
4686 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4687 let source_abs_path = op
4688 .old_uri
4689 .to_file_path()
4690 .map_err(|_| anyhow!("can't convert URI to path"))?;
4691 let target_abs_path = op
4692 .new_uri
4693 .to_file_path()
4694 .map_err(|_| anyhow!("can't convert URI to path"))?;
4695 fs.rename(
4696 &source_abs_path,
4697 &target_abs_path,
4698 op.options.map(Into::into).unwrap_or_default(),
4699 )
4700 .await?;
4701 }
4702
4703 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4704 let abs_path = op
4705 .uri
4706 .to_file_path()
4707 .map_err(|_| anyhow!("can't convert URI to path"))?;
4708 let options = op.options.map(Into::into).unwrap_or_default();
4709 if abs_path.ends_with("/") {
4710 fs.remove_dir(&abs_path, options).await?;
4711 } else {
4712 fs.remove_file(&abs_path, options).await?;
4713 }
4714 }
4715
4716 lsp::DocumentChangeOperation::Edit(op) => {
4717 let buffer_to_edit = this
4718 .update(cx, |this, cx| {
4719 this.open_local_buffer_via_lsp(
4720 op.text_document.uri,
4721 language_server.server_id(),
4722 lsp_adapter.name.clone(),
4723 cx,
4724 )
4725 })
4726 .await?;
4727
4728 let edits = this
4729 .update(cx, |this, cx| {
4730 let edits = op.edits.into_iter().map(|edit| match edit {
4731 OneOf::Left(edit) => edit,
4732 OneOf::Right(edit) => edit.text_edit,
4733 });
4734 this.edits_from_lsp(
4735 &buffer_to_edit,
4736 edits,
4737 language_server.server_id(),
4738 op.text_document.version,
4739 cx,
4740 )
4741 })
4742 .await?;
4743
4744 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4745 buffer.finalize_last_transaction();
4746 buffer.start_transaction();
4747 for (range, text) in edits {
4748 buffer.edit([(range, text)], None, cx);
4749 }
4750 let transaction = if buffer.end_transaction(cx).is_some() {
4751 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4752 if !push_to_history {
4753 buffer.forget_transaction(transaction.id);
4754 }
4755 Some(transaction)
4756 } else {
4757 None
4758 };
4759
4760 transaction
4761 });
4762 if let Some(transaction) = transaction {
4763 project_transaction.0.insert(buffer_to_edit, transaction);
4764 }
4765 }
4766 }
4767 }
4768
4769 Ok(project_transaction)
4770 }
4771
4772 pub fn prepare_rename<T: ToPointUtf16>(
4773 &self,
4774 buffer: ModelHandle<Buffer>,
4775 position: T,
4776 cx: &mut ModelContext<Self>,
4777 ) -> Task<Result<Option<Range<Anchor>>>> {
4778 let position = position.to_point_utf16(buffer.read(cx));
4779 self.request_lsp(buffer, PrepareRename { position }, cx)
4780 }
4781
4782 pub fn perform_rename<T: ToPointUtf16>(
4783 &self,
4784 buffer: ModelHandle<Buffer>,
4785 position: T,
4786 new_name: String,
4787 push_to_history: bool,
4788 cx: &mut ModelContext<Self>,
4789 ) -> Task<Result<ProjectTransaction>> {
4790 let position = position.to_point_utf16(buffer.read(cx));
4791 self.request_lsp(
4792 buffer,
4793 PerformRename {
4794 position,
4795 new_name,
4796 push_to_history,
4797 },
4798 cx,
4799 )
4800 }
4801
4802 pub fn on_type_format<T: ToPointUtf16>(
4803 &self,
4804 buffer: ModelHandle<Buffer>,
4805 position: T,
4806 trigger: String,
4807 push_to_history: bool,
4808 cx: &mut ModelContext<Self>,
4809 ) -> Task<Result<Option<Transaction>>> {
4810 let (position, tab_size) = buffer.read_with(cx, |buffer, cx| {
4811 let position = position.to_point_utf16(buffer);
4812 (
4813 position,
4814 language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
4815 .tab_size,
4816 )
4817 });
4818 self.request_lsp(
4819 buffer.clone(),
4820 OnTypeFormatting {
4821 position,
4822 trigger,
4823 options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
4824 push_to_history,
4825 },
4826 cx,
4827 )
4828 }
4829
4830 #[allow(clippy::type_complexity)]
4831 pub fn search(
4832 &self,
4833 query: SearchQuery,
4834 cx: &mut ModelContext<Self>,
4835 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4836 if self.is_local() {
4837 let snapshots = self
4838 .visible_worktrees(cx)
4839 .filter_map(|tree| {
4840 let tree = tree.read(cx).as_local()?;
4841 Some(tree.snapshot())
4842 })
4843 .collect::<Vec<_>>();
4844
4845 let background = cx.background().clone();
4846 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4847 if path_count == 0 {
4848 return Task::ready(Ok(Default::default()));
4849 }
4850 let workers = background.num_cpus().min(path_count);
4851 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4852 cx.background()
4853 .spawn({
4854 let fs = self.fs.clone();
4855 let background = cx.background().clone();
4856 let query = query.clone();
4857 async move {
4858 let fs = &fs;
4859 let query = &query;
4860 let matching_paths_tx = &matching_paths_tx;
4861 let paths_per_worker = (path_count + workers - 1) / workers;
4862 let snapshots = &snapshots;
4863 background
4864 .scoped(|scope| {
4865 for worker_ix in 0..workers {
4866 let worker_start_ix = worker_ix * paths_per_worker;
4867 let worker_end_ix = worker_start_ix + paths_per_worker;
4868 scope.spawn(async move {
4869 let mut snapshot_start_ix = 0;
4870 let mut abs_path = PathBuf::new();
4871 for snapshot in snapshots {
4872 let snapshot_end_ix =
4873 snapshot_start_ix + snapshot.visible_file_count();
4874 if worker_end_ix <= snapshot_start_ix {
4875 break;
4876 } else if worker_start_ix > snapshot_end_ix {
4877 snapshot_start_ix = snapshot_end_ix;
4878 continue;
4879 } else {
4880 let start_in_snapshot = worker_start_ix
4881 .saturating_sub(snapshot_start_ix);
4882 let end_in_snapshot =
4883 cmp::min(worker_end_ix, snapshot_end_ix)
4884 - snapshot_start_ix;
4885
4886 for entry in snapshot
4887 .files(false, start_in_snapshot)
4888 .take(end_in_snapshot - start_in_snapshot)
4889 {
4890 if matching_paths_tx.is_closed() {
4891 break;
4892 }
4893 let matches = if query
4894 .file_matches(Some(&entry.path))
4895 {
4896 abs_path.clear();
4897 abs_path.push(&snapshot.abs_path());
4898 abs_path.push(&entry.path);
4899 if let Some(file) =
4900 fs.open_sync(&abs_path).await.log_err()
4901 {
4902 query.detect(file).unwrap_or(false)
4903 } else {
4904 false
4905 }
4906 } else {
4907 false
4908 };
4909
4910 if matches {
4911 let project_path =
4912 (snapshot.id(), entry.path.clone());
4913 if matching_paths_tx
4914 .send(project_path)
4915 .await
4916 .is_err()
4917 {
4918 break;
4919 }
4920 }
4921 }
4922
4923 snapshot_start_ix = snapshot_end_ix;
4924 }
4925 }
4926 });
4927 }
4928 })
4929 .await;
4930 }
4931 })
4932 .detach();
4933
4934 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4935 let open_buffers = self
4936 .opened_buffers
4937 .values()
4938 .filter_map(|b| b.upgrade(cx))
4939 .collect::<HashSet<_>>();
4940 cx.spawn(|this, cx| async move {
4941 for buffer in &open_buffers {
4942 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4943 buffers_tx.send((buffer.clone(), snapshot)).await?;
4944 }
4945
4946 let open_buffers = Rc::new(RefCell::new(open_buffers));
4947 while let Some(project_path) = matching_paths_rx.next().await {
4948 if buffers_tx.is_closed() {
4949 break;
4950 }
4951
4952 let this = this.clone();
4953 let open_buffers = open_buffers.clone();
4954 let buffers_tx = buffers_tx.clone();
4955 cx.spawn(|mut cx| async move {
4956 if let Some(buffer) = this
4957 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4958 .await
4959 .log_err()
4960 {
4961 if open_buffers.borrow_mut().insert(buffer.clone()) {
4962 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4963 buffers_tx.send((buffer, snapshot)).await?;
4964 }
4965 }
4966
4967 Ok::<_, anyhow::Error>(())
4968 })
4969 .detach();
4970 }
4971
4972 Ok::<_, anyhow::Error>(())
4973 })
4974 .detach_and_log_err(cx);
4975
4976 let background = cx.background().clone();
4977 cx.background().spawn(async move {
4978 let query = &query;
4979 let mut matched_buffers = Vec::new();
4980 for _ in 0..workers {
4981 matched_buffers.push(HashMap::default());
4982 }
4983 background
4984 .scoped(|scope| {
4985 for worker_matched_buffers in matched_buffers.iter_mut() {
4986 let mut buffers_rx = buffers_rx.clone();
4987 scope.spawn(async move {
4988 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4989 let buffer_matches = if query.file_matches(
4990 snapshot.file().map(|file| file.path().as_ref()),
4991 ) {
4992 query
4993 .search(snapshot.as_rope())
4994 .await
4995 .iter()
4996 .map(|range| {
4997 snapshot.anchor_before(range.start)
4998 ..snapshot.anchor_after(range.end)
4999 })
5000 .collect()
5001 } else {
5002 Vec::new()
5003 };
5004 if !buffer_matches.is_empty() {
5005 worker_matched_buffers
5006 .insert(buffer.clone(), buffer_matches);
5007 }
5008 }
5009 });
5010 }
5011 })
5012 .await;
5013 Ok(matched_buffers.into_iter().flatten().collect())
5014 })
5015 } else if let Some(project_id) = self.remote_id() {
5016 let request = self.client.request(query.to_proto(project_id));
5017 cx.spawn(|this, mut cx| async move {
5018 let response = request.await?;
5019 let mut result = HashMap::default();
5020 for location in response.locations {
5021 let target_buffer = this
5022 .update(&mut cx, |this, cx| {
5023 this.wait_for_remote_buffer(location.buffer_id, cx)
5024 })
5025 .await?;
5026 let start = location
5027 .start
5028 .and_then(deserialize_anchor)
5029 .ok_or_else(|| anyhow!("missing target start"))?;
5030 let end = location
5031 .end
5032 .and_then(deserialize_anchor)
5033 .ok_or_else(|| anyhow!("missing target end"))?;
5034 result
5035 .entry(target_buffer)
5036 .or_insert(Vec::new())
5037 .push(start..end)
5038 }
5039 Ok(result)
5040 })
5041 } else {
5042 Task::ready(Ok(Default::default()))
5043 }
5044 }
5045
5046 // TODO: Wire this up to allow selecting a server?
5047 fn request_lsp<R: LspCommand>(
5048 &self,
5049 buffer_handle: ModelHandle<Buffer>,
5050 request: R,
5051 cx: &mut ModelContext<Self>,
5052 ) -> Task<Result<R::Response>>
5053 where
5054 <R::LspRequest as lsp::request::Request>::Result: Send,
5055 {
5056 let buffer = buffer_handle.read(cx);
5057 if self.is_local() {
5058 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5059 if let Some((file, language_server)) = file.zip(
5060 self.primary_language_servers_for_buffer(buffer, cx)
5061 .map(|(_, server)| server.clone()),
5062 ) {
5063 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5064 return cx.spawn(|this, cx| async move {
5065 if !request.check_capabilities(language_server.capabilities()) {
5066 return Ok(Default::default());
5067 }
5068
5069 let result = language_server.request::<R::LspRequest>(lsp_params).await;
5070 let response = match result {
5071 Ok(response) => response,
5072
5073 Err(err) => {
5074 log::warn!(
5075 "Generic lsp request to {} failed: {}",
5076 language_server.name(),
5077 err
5078 );
5079 return Err(err);
5080 }
5081 };
5082
5083 request
5084 .response_from_lsp(
5085 response,
5086 this,
5087 buffer_handle,
5088 language_server.server_id(),
5089 cx,
5090 )
5091 .await
5092 });
5093 }
5094 } else if let Some(project_id) = self.remote_id() {
5095 let rpc = self.client.clone();
5096 let message = request.to_proto(project_id, buffer);
5097 return cx.spawn_weak(|this, cx| async move {
5098 // Ensure the project is still alive by the time the task
5099 // is scheduled.
5100 this.upgrade(&cx)
5101 .ok_or_else(|| anyhow!("project dropped"))?;
5102
5103 let response = rpc.request(message).await?;
5104
5105 let this = this
5106 .upgrade(&cx)
5107 .ok_or_else(|| anyhow!("project dropped"))?;
5108 if this.read_with(&cx, |this, _| this.is_read_only()) {
5109 Err(anyhow!("disconnected before completing request"))
5110 } else {
5111 request
5112 .response_from_proto(response, this, buffer_handle, cx)
5113 .await
5114 }
5115 });
5116 }
5117 Task::ready(Ok(Default::default()))
5118 }
5119
5120 pub fn find_or_create_local_worktree(
5121 &mut self,
5122 abs_path: impl AsRef<Path>,
5123 visible: bool,
5124 cx: &mut ModelContext<Self>,
5125 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5126 let abs_path = abs_path.as_ref();
5127 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5128 Task::ready(Ok((tree, relative_path)))
5129 } else {
5130 let worktree = self.create_local_worktree(abs_path, visible, cx);
5131 cx.foreground()
5132 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5133 }
5134 }
5135
5136 pub fn find_local_worktree(
5137 &self,
5138 abs_path: &Path,
5139 cx: &AppContext,
5140 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5141 for tree in &self.worktrees {
5142 if let Some(tree) = tree.upgrade(cx) {
5143 if let Some(relative_path) = tree
5144 .read(cx)
5145 .as_local()
5146 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5147 {
5148 return Some((tree.clone(), relative_path.into()));
5149 }
5150 }
5151 }
5152 None
5153 }
5154
5155 pub fn is_shared(&self) -> bool {
5156 match &self.client_state {
5157 Some(ProjectClientState::Local { .. }) => true,
5158 _ => false,
5159 }
5160 }
5161
5162 fn create_local_worktree(
5163 &mut self,
5164 abs_path: impl AsRef<Path>,
5165 visible: bool,
5166 cx: &mut ModelContext<Self>,
5167 ) -> Task<Result<ModelHandle<Worktree>>> {
5168 let fs = self.fs.clone();
5169 let client = self.client.clone();
5170 let next_entry_id = self.next_entry_id.clone();
5171 let path: Arc<Path> = abs_path.as_ref().into();
5172 let task = self
5173 .loading_local_worktrees
5174 .entry(path.clone())
5175 .or_insert_with(|| {
5176 cx.spawn(|project, mut cx| {
5177 async move {
5178 let worktree = Worktree::local(
5179 client.clone(),
5180 path.clone(),
5181 visible,
5182 fs,
5183 next_entry_id,
5184 &mut cx,
5185 )
5186 .await;
5187
5188 project.update(&mut cx, |project, _| {
5189 project.loading_local_worktrees.remove(&path);
5190 });
5191
5192 let worktree = worktree?;
5193 project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
5194 Ok(worktree)
5195 }
5196 .map_err(Arc::new)
5197 })
5198 .shared()
5199 })
5200 .clone();
5201 cx.foreground().spawn(async move {
5202 match task.await {
5203 Ok(worktree) => Ok(worktree),
5204 Err(err) => Err(anyhow!("{}", err)),
5205 }
5206 })
5207 }
5208
5209 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
5210 self.worktrees.retain(|worktree| {
5211 if let Some(worktree) = worktree.upgrade(cx) {
5212 let id = worktree.read(cx).id();
5213 if id == id_to_remove {
5214 cx.emit(Event::WorktreeRemoved(id));
5215 false
5216 } else {
5217 true
5218 }
5219 } else {
5220 false
5221 }
5222 });
5223 self.metadata_changed(cx);
5224 }
5225
5226 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
5227 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
5228 if worktree.read(cx).is_local() {
5229 cx.subscribe(worktree, |this, worktree, event, cx| match event {
5230 worktree::Event::UpdatedEntries(changes) => {
5231 this.update_local_worktree_buffers(&worktree, changes, cx);
5232 this.update_local_worktree_language_servers(&worktree, changes, cx);
5233 this.update_local_worktree_settings(&worktree, changes, cx);
5234 }
5235 worktree::Event::UpdatedGitRepositories(updated_repos) => {
5236 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
5237 }
5238 })
5239 .detach();
5240 }
5241
5242 let push_strong_handle = {
5243 let worktree = worktree.read(cx);
5244 self.is_shared() || worktree.is_visible() || worktree.is_remote()
5245 };
5246 if push_strong_handle {
5247 self.worktrees
5248 .push(WorktreeHandle::Strong(worktree.clone()));
5249 } else {
5250 self.worktrees
5251 .push(WorktreeHandle::Weak(worktree.downgrade()));
5252 }
5253
5254 let handle_id = worktree.id();
5255 cx.observe_release(worktree, move |this, worktree, cx| {
5256 let _ = this.remove_worktree(worktree.id(), cx);
5257 cx.update_global::<SettingsStore, _, _>(|store, cx| {
5258 store.clear_local_settings(handle_id, cx).log_err()
5259 });
5260 })
5261 .detach();
5262
5263 cx.emit(Event::WorktreeAdded);
5264 self.metadata_changed(cx);
5265 }
5266
5267 fn update_local_worktree_buffers(
5268 &mut self,
5269 worktree_handle: &ModelHandle<Worktree>,
5270 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5271 cx: &mut ModelContext<Self>,
5272 ) {
5273 let snapshot = worktree_handle.read(cx).snapshot();
5274
5275 let mut renamed_buffers = Vec::new();
5276 for (path, entry_id, _) in changes {
5277 let worktree_id = worktree_handle.read(cx).id();
5278 let project_path = ProjectPath {
5279 worktree_id,
5280 path: path.clone(),
5281 };
5282
5283 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
5284 Some(&buffer_id) => buffer_id,
5285 None => match self.local_buffer_ids_by_path.get(&project_path) {
5286 Some(&buffer_id) => buffer_id,
5287 None => continue,
5288 },
5289 };
5290
5291 let open_buffer = self.opened_buffers.get(&buffer_id);
5292 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
5293 buffer
5294 } else {
5295 self.opened_buffers.remove(&buffer_id);
5296 self.local_buffer_ids_by_path.remove(&project_path);
5297 self.local_buffer_ids_by_entry_id.remove(entry_id);
5298 continue;
5299 };
5300
5301 buffer.update(cx, |buffer, cx| {
5302 if let Some(old_file) = File::from_dyn(buffer.file()) {
5303 if old_file.worktree != *worktree_handle {
5304 return;
5305 }
5306
5307 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
5308 File {
5309 is_local: true,
5310 entry_id: entry.id,
5311 mtime: entry.mtime,
5312 path: entry.path.clone(),
5313 worktree: worktree_handle.clone(),
5314 is_deleted: false,
5315 }
5316 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
5317 File {
5318 is_local: true,
5319 entry_id: entry.id,
5320 mtime: entry.mtime,
5321 path: entry.path.clone(),
5322 worktree: worktree_handle.clone(),
5323 is_deleted: false,
5324 }
5325 } else {
5326 File {
5327 is_local: true,
5328 entry_id: old_file.entry_id,
5329 path: old_file.path().clone(),
5330 mtime: old_file.mtime(),
5331 worktree: worktree_handle.clone(),
5332 is_deleted: true,
5333 }
5334 };
5335
5336 let old_path = old_file.abs_path(cx);
5337 if new_file.abs_path(cx) != old_path {
5338 renamed_buffers.push((cx.handle(), old_file.clone()));
5339 self.local_buffer_ids_by_path.remove(&project_path);
5340 self.local_buffer_ids_by_path.insert(
5341 ProjectPath {
5342 worktree_id,
5343 path: path.clone(),
5344 },
5345 buffer_id,
5346 );
5347 }
5348
5349 if new_file.entry_id != *entry_id {
5350 self.local_buffer_ids_by_entry_id.remove(entry_id);
5351 self.local_buffer_ids_by_entry_id
5352 .insert(new_file.entry_id, buffer_id);
5353 }
5354
5355 if new_file != *old_file {
5356 if let Some(project_id) = self.remote_id() {
5357 self.client
5358 .send(proto::UpdateBufferFile {
5359 project_id,
5360 buffer_id: buffer_id as u64,
5361 file: Some(new_file.to_proto()),
5362 })
5363 .log_err();
5364 }
5365
5366 buffer.file_updated(Arc::new(new_file), cx).detach();
5367 }
5368 }
5369 });
5370 }
5371
5372 for (buffer, old_file) in renamed_buffers {
5373 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
5374 self.detect_language_for_buffer(&buffer, cx);
5375 self.register_buffer_with_language_servers(&buffer, cx);
5376 }
5377 }
5378
5379 fn update_local_worktree_language_servers(
5380 &mut self,
5381 worktree_handle: &ModelHandle<Worktree>,
5382 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5383 cx: &mut ModelContext<Self>,
5384 ) {
5385 if changes.is_empty() {
5386 return;
5387 }
5388
5389 let worktree_id = worktree_handle.read(cx).id();
5390 let mut language_server_ids = self
5391 .language_server_ids
5392 .iter()
5393 .filter_map(|((server_worktree_id, _), server_id)| {
5394 (*server_worktree_id == worktree_id).then_some(*server_id)
5395 })
5396 .collect::<Vec<_>>();
5397 language_server_ids.sort();
5398 language_server_ids.dedup();
5399
5400 let abs_path = worktree_handle.read(cx).abs_path();
5401 for server_id in &language_server_ids {
5402 if let Some(server) = self.language_servers.get(server_id) {
5403 if let LanguageServerState::Running {
5404 server,
5405 watched_paths,
5406 ..
5407 } = server
5408 {
5409 if let Some(watched_paths) = watched_paths.get(&worktree_id) {
5410 let params = lsp::DidChangeWatchedFilesParams {
5411 changes: changes
5412 .iter()
5413 .filter_map(|(path, _, change)| {
5414 if !watched_paths.is_match(&path) {
5415 return None;
5416 }
5417 let typ = match change {
5418 PathChange::Loaded => return None,
5419 PathChange::Added => lsp::FileChangeType::CREATED,
5420 PathChange::Removed => lsp::FileChangeType::DELETED,
5421 PathChange::Updated => lsp::FileChangeType::CHANGED,
5422 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
5423 };
5424 Some(lsp::FileEvent {
5425 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
5426 typ,
5427 })
5428 })
5429 .collect(),
5430 };
5431
5432 if !params.changes.is_empty() {
5433 server
5434 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
5435 .log_err();
5436 }
5437 }
5438 }
5439 }
5440 }
5441 }
5442
5443 fn update_local_worktree_buffers_git_repos(
5444 &mut self,
5445 worktree_handle: ModelHandle<Worktree>,
5446 changed_repos: &UpdatedGitRepositoriesSet,
5447 cx: &mut ModelContext<Self>,
5448 ) {
5449 debug_assert!(worktree_handle.read(cx).is_local());
5450
5451 // Identify the loading buffers whose containing repository that has changed.
5452 let future_buffers = self
5453 .loading_buffers_by_path
5454 .iter()
5455 .filter_map(|(project_path, receiver)| {
5456 if project_path.worktree_id != worktree_handle.read(cx).id() {
5457 return None;
5458 }
5459 let path = &project_path.path;
5460 changed_repos
5461 .iter()
5462 .find(|(work_dir, _)| path.starts_with(work_dir))?;
5463 let receiver = receiver.clone();
5464 let path = path.clone();
5465 Some(async move {
5466 wait_for_loading_buffer(receiver)
5467 .await
5468 .ok()
5469 .map(|buffer| (buffer, path))
5470 })
5471 })
5472 .collect::<FuturesUnordered<_>>();
5473
5474 // Identify the current buffers whose containing repository has changed.
5475 let current_buffers = self
5476 .opened_buffers
5477 .values()
5478 .filter_map(|buffer| {
5479 let buffer = buffer.upgrade(cx)?;
5480 let file = File::from_dyn(buffer.read(cx).file())?;
5481 if file.worktree != worktree_handle {
5482 return None;
5483 }
5484 let path = file.path();
5485 changed_repos
5486 .iter()
5487 .find(|(work_dir, _)| path.starts_with(work_dir))?;
5488 Some((buffer, path.clone()))
5489 })
5490 .collect::<Vec<_>>();
5491
5492 if future_buffers.len() + current_buffers.len() == 0 {
5493 return;
5494 }
5495
5496 let remote_id = self.remote_id();
5497 let client = self.client.clone();
5498 cx.spawn_weak(move |_, mut cx| async move {
5499 // Wait for all of the buffers to load.
5500 let future_buffers = future_buffers.collect::<Vec<_>>().await;
5501
5502 // Reload the diff base for every buffer whose containing git repository has changed.
5503 let snapshot =
5504 worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
5505 let diff_bases_by_buffer = cx
5506 .background()
5507 .spawn(async move {
5508 future_buffers
5509 .into_iter()
5510 .filter_map(|e| e)
5511 .chain(current_buffers)
5512 .filter_map(|(buffer, path)| {
5513 let (work_directory, repo) =
5514 snapshot.repository_and_work_directory_for_path(&path)?;
5515 let repo = snapshot.get_local_repo(&repo)?;
5516 let relative_path = path.strip_prefix(&work_directory).ok()?;
5517 let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
5518 Some((buffer, base_text))
5519 })
5520 .collect::<Vec<_>>()
5521 })
5522 .await;
5523
5524 // Assign the new diff bases on all of the buffers.
5525 for (buffer, diff_base) in diff_bases_by_buffer {
5526 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
5527 buffer.set_diff_base(diff_base.clone(), cx);
5528 buffer.remote_id()
5529 });
5530 if let Some(project_id) = remote_id {
5531 client
5532 .send(proto::UpdateDiffBase {
5533 project_id,
5534 buffer_id,
5535 diff_base,
5536 })
5537 .log_err();
5538 }
5539 }
5540 })
5541 .detach();
5542 }
5543
5544 fn update_local_worktree_settings(
5545 &mut self,
5546 worktree: &ModelHandle<Worktree>,
5547 changes: &UpdatedEntriesSet,
5548 cx: &mut ModelContext<Self>,
5549 ) {
5550 let project_id = self.remote_id();
5551 let worktree_id = worktree.id();
5552 let worktree = worktree.read(cx).as_local().unwrap();
5553 let remote_worktree_id = worktree.id();
5554
5555 let mut settings_contents = Vec::new();
5556 for (path, _, change) in changes.iter() {
5557 if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
5558 let settings_dir = Arc::from(
5559 path.ancestors()
5560 .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
5561 .unwrap(),
5562 );
5563 let fs = self.fs.clone();
5564 let removed = *change == PathChange::Removed;
5565 let abs_path = worktree.absolutize(path);
5566 settings_contents.push(async move {
5567 (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
5568 });
5569 }
5570 }
5571
5572 if settings_contents.is_empty() {
5573 return;
5574 }
5575
5576 let client = self.client.clone();
5577 cx.spawn_weak(move |_, mut cx| async move {
5578 let settings_contents: Vec<(Arc<Path>, _)> =
5579 futures::future::join_all(settings_contents).await;
5580 cx.update(|cx| {
5581 cx.update_global::<SettingsStore, _, _>(|store, cx| {
5582 for (directory, file_content) in settings_contents {
5583 let file_content = file_content.and_then(|content| content.log_err());
5584 store
5585 .set_local_settings(
5586 worktree_id,
5587 directory.clone(),
5588 file_content.as_ref().map(String::as_str),
5589 cx,
5590 )
5591 .log_err();
5592 if let Some(remote_id) = project_id {
5593 client
5594 .send(proto::UpdateWorktreeSettings {
5595 project_id: remote_id,
5596 worktree_id: remote_worktree_id.to_proto(),
5597 path: directory.to_string_lossy().into_owned(),
5598 content: file_content,
5599 })
5600 .log_err();
5601 }
5602 }
5603 });
5604 });
5605 })
5606 .detach();
5607 }
5608
5609 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
5610 let new_active_entry = entry.and_then(|project_path| {
5611 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
5612 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
5613 Some(entry.id)
5614 });
5615 if new_active_entry != self.active_entry {
5616 self.active_entry = new_active_entry;
5617 cx.emit(Event::ActiveEntryChanged(new_active_entry));
5618 }
5619 }
5620
5621 pub fn language_servers_running_disk_based_diagnostics(
5622 &self,
5623 ) -> impl Iterator<Item = LanguageServerId> + '_ {
5624 self.language_server_statuses
5625 .iter()
5626 .filter_map(|(id, status)| {
5627 if status.has_pending_diagnostic_updates {
5628 Some(*id)
5629 } else {
5630 None
5631 }
5632 })
5633 }
5634
5635 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
5636 let mut summary = DiagnosticSummary::default();
5637 for (_, _, path_summary) in self.diagnostic_summaries(cx) {
5638 summary.error_count += path_summary.error_count;
5639 summary.warning_count += path_summary.warning_count;
5640 }
5641 summary
5642 }
5643
5644 pub fn diagnostic_summaries<'a>(
5645 &'a self,
5646 cx: &'a AppContext,
5647 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
5648 self.visible_worktrees(cx).flat_map(move |worktree| {
5649 let worktree = worktree.read(cx);
5650 let worktree_id = worktree.id();
5651 worktree
5652 .diagnostic_summaries()
5653 .map(move |(path, server_id, summary)| {
5654 (ProjectPath { worktree_id, path }, server_id, summary)
5655 })
5656 })
5657 }
5658
5659 pub fn disk_based_diagnostics_started(
5660 &mut self,
5661 language_server_id: LanguageServerId,
5662 cx: &mut ModelContext<Self>,
5663 ) {
5664 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
5665 }
5666
5667 pub fn disk_based_diagnostics_finished(
5668 &mut self,
5669 language_server_id: LanguageServerId,
5670 cx: &mut ModelContext<Self>,
5671 ) {
5672 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
5673 }
5674
5675 pub fn active_entry(&self) -> Option<ProjectEntryId> {
5676 self.active_entry
5677 }
5678
5679 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
5680 self.worktree_for_id(path.worktree_id, cx)?
5681 .read(cx)
5682 .entry_for_path(&path.path)
5683 .cloned()
5684 }
5685
5686 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
5687 let worktree = self.worktree_for_entry(entry_id, cx)?;
5688 let worktree = worktree.read(cx);
5689 let worktree_id = worktree.id();
5690 let path = worktree.entry_for_id(entry_id)?.path.clone();
5691 Some(ProjectPath { worktree_id, path })
5692 }
5693
5694 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
5695 let workspace_root = self
5696 .worktree_for_id(project_path.worktree_id, cx)?
5697 .read(cx)
5698 .abs_path();
5699 let project_path = project_path.path.as_ref();
5700
5701 Some(if project_path == Path::new("") {
5702 workspace_root.to_path_buf()
5703 } else {
5704 workspace_root.join(project_path)
5705 })
5706 }
5707
5708 // RPC message handlers
5709
5710 async fn handle_unshare_project(
5711 this: ModelHandle<Self>,
5712 _: TypedEnvelope<proto::UnshareProject>,
5713 _: Arc<Client>,
5714 mut cx: AsyncAppContext,
5715 ) -> Result<()> {
5716 this.update(&mut cx, |this, cx| {
5717 if this.is_local() {
5718 this.unshare(cx)?;
5719 } else {
5720 this.disconnected_from_host(cx);
5721 }
5722 Ok(())
5723 })
5724 }
5725
5726 async fn handle_add_collaborator(
5727 this: ModelHandle<Self>,
5728 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5729 _: Arc<Client>,
5730 mut cx: AsyncAppContext,
5731 ) -> Result<()> {
5732 let collaborator = envelope
5733 .payload
5734 .collaborator
5735 .take()
5736 .ok_or_else(|| anyhow!("empty collaborator"))?;
5737
5738 let collaborator = Collaborator::from_proto(collaborator)?;
5739 this.update(&mut cx, |this, cx| {
5740 this.shared_buffers.remove(&collaborator.peer_id);
5741 this.collaborators
5742 .insert(collaborator.peer_id, collaborator);
5743 cx.notify();
5744 });
5745
5746 Ok(())
5747 }
5748
5749 async fn handle_update_project_collaborator(
5750 this: ModelHandle<Self>,
5751 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5752 _: Arc<Client>,
5753 mut cx: AsyncAppContext,
5754 ) -> Result<()> {
5755 let old_peer_id = envelope
5756 .payload
5757 .old_peer_id
5758 .ok_or_else(|| anyhow!("missing old peer id"))?;
5759 let new_peer_id = envelope
5760 .payload
5761 .new_peer_id
5762 .ok_or_else(|| anyhow!("missing new peer id"))?;
5763 this.update(&mut cx, |this, cx| {
5764 let collaborator = this
5765 .collaborators
5766 .remove(&old_peer_id)
5767 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
5768 let is_host = collaborator.replica_id == 0;
5769 this.collaborators.insert(new_peer_id, collaborator);
5770
5771 let buffers = this.shared_buffers.remove(&old_peer_id);
5772 log::info!(
5773 "peer {} became {}. moving buffers {:?}",
5774 old_peer_id,
5775 new_peer_id,
5776 &buffers
5777 );
5778 if let Some(buffers) = buffers {
5779 this.shared_buffers.insert(new_peer_id, buffers);
5780 }
5781
5782 if is_host {
5783 this.opened_buffers
5784 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
5785 this.buffer_ordered_messages_tx
5786 .unbounded_send(BufferOrderedMessage::Resync)
5787 .unwrap();
5788 }
5789
5790 cx.emit(Event::CollaboratorUpdated {
5791 old_peer_id,
5792 new_peer_id,
5793 });
5794 cx.notify();
5795 Ok(())
5796 })
5797 }
5798
5799 async fn handle_remove_collaborator(
5800 this: ModelHandle<Self>,
5801 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5802 _: Arc<Client>,
5803 mut cx: AsyncAppContext,
5804 ) -> Result<()> {
5805 this.update(&mut cx, |this, cx| {
5806 let peer_id = envelope
5807 .payload
5808 .peer_id
5809 .ok_or_else(|| anyhow!("invalid peer id"))?;
5810 let replica_id = this
5811 .collaborators
5812 .remove(&peer_id)
5813 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
5814 .replica_id;
5815 for buffer in this.opened_buffers.values() {
5816 if let Some(buffer) = buffer.upgrade(cx) {
5817 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5818 }
5819 }
5820 this.shared_buffers.remove(&peer_id);
5821
5822 cx.emit(Event::CollaboratorLeft(peer_id));
5823 cx.notify();
5824 Ok(())
5825 })
5826 }
5827
5828 async fn handle_update_project(
5829 this: ModelHandle<Self>,
5830 envelope: TypedEnvelope<proto::UpdateProject>,
5831 _: Arc<Client>,
5832 mut cx: AsyncAppContext,
5833 ) -> Result<()> {
5834 this.update(&mut cx, |this, cx| {
5835 // Don't handle messages that were sent before the response to us joining the project
5836 if envelope.message_id > this.join_project_response_message_id {
5837 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5838 }
5839 Ok(())
5840 })
5841 }
5842
5843 async fn handle_update_worktree(
5844 this: ModelHandle<Self>,
5845 envelope: TypedEnvelope<proto::UpdateWorktree>,
5846 _: Arc<Client>,
5847 mut cx: AsyncAppContext,
5848 ) -> Result<()> {
5849 this.update(&mut cx, |this, cx| {
5850 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5851 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5852 worktree.update(cx, |worktree, _| {
5853 let worktree = worktree.as_remote_mut().unwrap();
5854 worktree.update_from_remote(envelope.payload);
5855 });
5856 }
5857 Ok(())
5858 })
5859 }
5860
5861 async fn handle_update_worktree_settings(
5862 this: ModelHandle<Self>,
5863 envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
5864 _: Arc<Client>,
5865 mut cx: AsyncAppContext,
5866 ) -> Result<()> {
5867 this.update(&mut cx, |this, cx| {
5868 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5869 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5870 cx.update_global::<SettingsStore, _, _>(|store, cx| {
5871 store
5872 .set_local_settings(
5873 worktree.id(),
5874 PathBuf::from(&envelope.payload.path).into(),
5875 envelope.payload.content.as_ref().map(String::as_str),
5876 cx,
5877 )
5878 .log_err();
5879 });
5880 }
5881 Ok(())
5882 })
5883 }
5884
5885 async fn handle_create_project_entry(
5886 this: ModelHandle<Self>,
5887 envelope: TypedEnvelope<proto::CreateProjectEntry>,
5888 _: Arc<Client>,
5889 mut cx: AsyncAppContext,
5890 ) -> Result<proto::ProjectEntryResponse> {
5891 let worktree = this.update(&mut cx, |this, cx| {
5892 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5893 this.worktree_for_id(worktree_id, cx)
5894 .ok_or_else(|| anyhow!("worktree not found"))
5895 })?;
5896 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5897 let entry = worktree
5898 .update(&mut cx, |worktree, cx| {
5899 let worktree = worktree.as_local_mut().unwrap();
5900 let path = PathBuf::from(envelope.payload.path);
5901 worktree.create_entry(path, envelope.payload.is_directory, cx)
5902 })
5903 .await?;
5904 Ok(proto::ProjectEntryResponse {
5905 entry: Some((&entry).into()),
5906 worktree_scan_id: worktree_scan_id as u64,
5907 })
5908 }
5909
5910 async fn handle_rename_project_entry(
5911 this: ModelHandle<Self>,
5912 envelope: TypedEnvelope<proto::RenameProjectEntry>,
5913 _: Arc<Client>,
5914 mut cx: AsyncAppContext,
5915 ) -> Result<proto::ProjectEntryResponse> {
5916 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5917 let worktree = this.read_with(&cx, |this, cx| {
5918 this.worktree_for_entry(entry_id, cx)
5919 .ok_or_else(|| anyhow!("worktree not found"))
5920 })?;
5921 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5922 let entry = worktree
5923 .update(&mut cx, |worktree, cx| {
5924 let new_path = PathBuf::from(envelope.payload.new_path);
5925 worktree
5926 .as_local_mut()
5927 .unwrap()
5928 .rename_entry(entry_id, new_path, cx)
5929 .ok_or_else(|| anyhow!("invalid entry"))
5930 })?
5931 .await?;
5932 Ok(proto::ProjectEntryResponse {
5933 entry: Some((&entry).into()),
5934 worktree_scan_id: worktree_scan_id as u64,
5935 })
5936 }
5937
5938 async fn handle_copy_project_entry(
5939 this: ModelHandle<Self>,
5940 envelope: TypedEnvelope<proto::CopyProjectEntry>,
5941 _: Arc<Client>,
5942 mut cx: AsyncAppContext,
5943 ) -> Result<proto::ProjectEntryResponse> {
5944 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5945 let worktree = this.read_with(&cx, |this, cx| {
5946 this.worktree_for_entry(entry_id, cx)
5947 .ok_or_else(|| anyhow!("worktree not found"))
5948 })?;
5949 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5950 let entry = worktree
5951 .update(&mut cx, |worktree, cx| {
5952 let new_path = PathBuf::from(envelope.payload.new_path);
5953 worktree
5954 .as_local_mut()
5955 .unwrap()
5956 .copy_entry(entry_id, new_path, cx)
5957 .ok_or_else(|| anyhow!("invalid entry"))
5958 })?
5959 .await?;
5960 Ok(proto::ProjectEntryResponse {
5961 entry: Some((&entry).into()),
5962 worktree_scan_id: worktree_scan_id as u64,
5963 })
5964 }
5965
5966 async fn handle_delete_project_entry(
5967 this: ModelHandle<Self>,
5968 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5969 _: Arc<Client>,
5970 mut cx: AsyncAppContext,
5971 ) -> Result<proto::ProjectEntryResponse> {
5972 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5973
5974 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
5975
5976 let worktree = this.read_with(&cx, |this, cx| {
5977 this.worktree_for_entry(entry_id, cx)
5978 .ok_or_else(|| anyhow!("worktree not found"))
5979 })?;
5980 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5981 worktree
5982 .update(&mut cx, |worktree, cx| {
5983 worktree
5984 .as_local_mut()
5985 .unwrap()
5986 .delete_entry(entry_id, cx)
5987 .ok_or_else(|| anyhow!("invalid entry"))
5988 })?
5989 .await?;
5990 Ok(proto::ProjectEntryResponse {
5991 entry: None,
5992 worktree_scan_id: worktree_scan_id as u64,
5993 })
5994 }
5995
5996 async fn handle_update_diagnostic_summary(
5997 this: ModelHandle<Self>,
5998 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5999 _: Arc<Client>,
6000 mut cx: AsyncAppContext,
6001 ) -> Result<()> {
6002 this.update(&mut cx, |this, cx| {
6003 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6004 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6005 if let Some(summary) = envelope.payload.summary {
6006 let project_path = ProjectPath {
6007 worktree_id,
6008 path: Path::new(&summary.path).into(),
6009 };
6010 worktree.update(cx, |worktree, _| {
6011 worktree
6012 .as_remote_mut()
6013 .unwrap()
6014 .update_diagnostic_summary(project_path.path.clone(), &summary);
6015 });
6016 cx.emit(Event::DiagnosticsUpdated {
6017 language_server_id: LanguageServerId(summary.language_server_id as usize),
6018 path: project_path,
6019 });
6020 }
6021 }
6022 Ok(())
6023 })
6024 }
6025
6026 async fn handle_start_language_server(
6027 this: ModelHandle<Self>,
6028 envelope: TypedEnvelope<proto::StartLanguageServer>,
6029 _: Arc<Client>,
6030 mut cx: AsyncAppContext,
6031 ) -> Result<()> {
6032 let server = envelope
6033 .payload
6034 .server
6035 .ok_or_else(|| anyhow!("invalid server"))?;
6036 this.update(&mut cx, |this, cx| {
6037 this.language_server_statuses.insert(
6038 LanguageServerId(server.id as usize),
6039 LanguageServerStatus {
6040 name: server.name,
6041 pending_work: Default::default(),
6042 has_pending_diagnostic_updates: false,
6043 progress_tokens: Default::default(),
6044 },
6045 );
6046 cx.notify();
6047 });
6048 Ok(())
6049 }
6050
6051 async fn handle_update_language_server(
6052 this: ModelHandle<Self>,
6053 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6054 _: Arc<Client>,
6055 mut cx: AsyncAppContext,
6056 ) -> Result<()> {
6057 this.update(&mut cx, |this, cx| {
6058 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6059
6060 match envelope
6061 .payload
6062 .variant
6063 .ok_or_else(|| anyhow!("invalid variant"))?
6064 {
6065 proto::update_language_server::Variant::WorkStart(payload) => {
6066 this.on_lsp_work_start(
6067 language_server_id,
6068 payload.token,
6069 LanguageServerProgress {
6070 message: payload.message,
6071 percentage: payload.percentage.map(|p| p as usize),
6072 last_update_at: Instant::now(),
6073 },
6074 cx,
6075 );
6076 }
6077
6078 proto::update_language_server::Variant::WorkProgress(payload) => {
6079 this.on_lsp_work_progress(
6080 language_server_id,
6081 payload.token,
6082 LanguageServerProgress {
6083 message: payload.message,
6084 percentage: payload.percentage.map(|p| p as usize),
6085 last_update_at: Instant::now(),
6086 },
6087 cx,
6088 );
6089 }
6090
6091 proto::update_language_server::Variant::WorkEnd(payload) => {
6092 this.on_lsp_work_end(language_server_id, payload.token, cx);
6093 }
6094
6095 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
6096 this.disk_based_diagnostics_started(language_server_id, cx);
6097 }
6098
6099 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
6100 this.disk_based_diagnostics_finished(language_server_id, cx)
6101 }
6102 }
6103
6104 Ok(())
6105 })
6106 }
6107
6108 async fn handle_update_buffer(
6109 this: ModelHandle<Self>,
6110 envelope: TypedEnvelope<proto::UpdateBuffer>,
6111 _: Arc<Client>,
6112 mut cx: AsyncAppContext,
6113 ) -> Result<proto::Ack> {
6114 this.update(&mut cx, |this, cx| {
6115 let payload = envelope.payload.clone();
6116 let buffer_id = payload.buffer_id;
6117 let ops = payload
6118 .operations
6119 .into_iter()
6120 .map(language::proto::deserialize_operation)
6121 .collect::<Result<Vec<_>, _>>()?;
6122 let is_remote = this.is_remote();
6123 match this.opened_buffers.entry(buffer_id) {
6124 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
6125 OpenBuffer::Strong(buffer) => {
6126 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
6127 }
6128 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
6129 OpenBuffer::Weak(_) => {}
6130 },
6131 hash_map::Entry::Vacant(e) => {
6132 assert!(
6133 is_remote,
6134 "received buffer update from {:?}",
6135 envelope.original_sender_id
6136 );
6137 e.insert(OpenBuffer::Operations(ops));
6138 }
6139 }
6140 Ok(proto::Ack {})
6141 })
6142 }
6143
6144 async fn handle_create_buffer_for_peer(
6145 this: ModelHandle<Self>,
6146 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
6147 _: Arc<Client>,
6148 mut cx: AsyncAppContext,
6149 ) -> Result<()> {
6150 this.update(&mut cx, |this, cx| {
6151 match envelope
6152 .payload
6153 .variant
6154 .ok_or_else(|| anyhow!("missing variant"))?
6155 {
6156 proto::create_buffer_for_peer::Variant::State(mut state) => {
6157 let mut buffer_file = None;
6158 if let Some(file) = state.file.take() {
6159 let worktree_id = WorktreeId::from_proto(file.worktree_id);
6160 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
6161 anyhow!("no worktree found for id {}", file.worktree_id)
6162 })?;
6163 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
6164 as Arc<dyn language::File>);
6165 }
6166
6167 let buffer_id = state.id;
6168 let buffer = cx.add_model(|_| {
6169 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
6170 });
6171 this.incomplete_remote_buffers
6172 .insert(buffer_id, Some(buffer));
6173 }
6174 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
6175 let buffer = this
6176 .incomplete_remote_buffers
6177 .get(&chunk.buffer_id)
6178 .cloned()
6179 .flatten()
6180 .ok_or_else(|| {
6181 anyhow!(
6182 "received chunk for buffer {} without initial state",
6183 chunk.buffer_id
6184 )
6185 })?;
6186 let operations = chunk
6187 .operations
6188 .into_iter()
6189 .map(language::proto::deserialize_operation)
6190 .collect::<Result<Vec<_>>>()?;
6191 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
6192
6193 if chunk.is_last {
6194 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
6195 this.register_buffer(&buffer, cx)?;
6196 }
6197 }
6198 }
6199
6200 Ok(())
6201 })
6202 }
6203
6204 async fn handle_update_diff_base(
6205 this: ModelHandle<Self>,
6206 envelope: TypedEnvelope<proto::UpdateDiffBase>,
6207 _: Arc<Client>,
6208 mut cx: AsyncAppContext,
6209 ) -> Result<()> {
6210 this.update(&mut cx, |this, cx| {
6211 let buffer_id = envelope.payload.buffer_id;
6212 let diff_base = envelope.payload.diff_base;
6213 if let Some(buffer) = this
6214 .opened_buffers
6215 .get_mut(&buffer_id)
6216 .and_then(|b| b.upgrade(cx))
6217 .or_else(|| {
6218 this.incomplete_remote_buffers
6219 .get(&buffer_id)
6220 .cloned()
6221 .flatten()
6222 })
6223 {
6224 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
6225 }
6226 Ok(())
6227 })
6228 }
6229
6230 async fn handle_update_buffer_file(
6231 this: ModelHandle<Self>,
6232 envelope: TypedEnvelope<proto::UpdateBufferFile>,
6233 _: Arc<Client>,
6234 mut cx: AsyncAppContext,
6235 ) -> Result<()> {
6236 let buffer_id = envelope.payload.buffer_id;
6237
6238 this.update(&mut cx, |this, cx| {
6239 let payload = envelope.payload.clone();
6240 if let Some(buffer) = this
6241 .opened_buffers
6242 .get(&buffer_id)
6243 .and_then(|b| b.upgrade(cx))
6244 .or_else(|| {
6245 this.incomplete_remote_buffers
6246 .get(&buffer_id)
6247 .cloned()
6248 .flatten()
6249 })
6250 {
6251 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
6252 let worktree = this
6253 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
6254 .ok_or_else(|| anyhow!("no such worktree"))?;
6255 let file = File::from_proto(file, worktree, cx)?;
6256 buffer.update(cx, |buffer, cx| {
6257 buffer.file_updated(Arc::new(file), cx).detach();
6258 });
6259 this.detect_language_for_buffer(&buffer, cx);
6260 }
6261 Ok(())
6262 })
6263 }
6264
6265 async fn handle_save_buffer(
6266 this: ModelHandle<Self>,
6267 envelope: TypedEnvelope<proto::SaveBuffer>,
6268 _: Arc<Client>,
6269 mut cx: AsyncAppContext,
6270 ) -> Result<proto::BufferSaved> {
6271 let buffer_id = envelope.payload.buffer_id;
6272 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
6273 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
6274 let buffer = this
6275 .opened_buffers
6276 .get(&buffer_id)
6277 .and_then(|buffer| buffer.upgrade(cx))
6278 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
6279 anyhow::Ok((project_id, buffer))
6280 })?;
6281 buffer
6282 .update(&mut cx, |buffer, _| {
6283 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
6284 })
6285 .await?;
6286 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
6287
6288 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
6289 .await?;
6290 Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
6291 project_id,
6292 buffer_id,
6293 version: serialize_version(buffer.saved_version()),
6294 mtime: Some(buffer.saved_mtime().into()),
6295 fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
6296 }))
6297 }
6298
6299 async fn handle_reload_buffers(
6300 this: ModelHandle<Self>,
6301 envelope: TypedEnvelope<proto::ReloadBuffers>,
6302 _: Arc<Client>,
6303 mut cx: AsyncAppContext,
6304 ) -> Result<proto::ReloadBuffersResponse> {
6305 let sender_id = envelope.original_sender_id()?;
6306 let reload = this.update(&mut cx, |this, cx| {
6307 let mut buffers = HashSet::default();
6308 for buffer_id in &envelope.payload.buffer_ids {
6309 buffers.insert(
6310 this.opened_buffers
6311 .get(buffer_id)
6312 .and_then(|buffer| buffer.upgrade(cx))
6313 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6314 );
6315 }
6316 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
6317 })?;
6318
6319 let project_transaction = reload.await?;
6320 let project_transaction = this.update(&mut cx, |this, cx| {
6321 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6322 });
6323 Ok(proto::ReloadBuffersResponse {
6324 transaction: Some(project_transaction),
6325 })
6326 }
6327
6328 async fn handle_synchronize_buffers(
6329 this: ModelHandle<Self>,
6330 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
6331 _: Arc<Client>,
6332 mut cx: AsyncAppContext,
6333 ) -> Result<proto::SynchronizeBuffersResponse> {
6334 let project_id = envelope.payload.project_id;
6335 let mut response = proto::SynchronizeBuffersResponse {
6336 buffers: Default::default(),
6337 };
6338
6339 this.update(&mut cx, |this, cx| {
6340 let Some(guest_id) = envelope.original_sender_id else {
6341 error!("missing original_sender_id on SynchronizeBuffers request");
6342 return;
6343 };
6344
6345 this.shared_buffers.entry(guest_id).or_default().clear();
6346 for buffer in envelope.payload.buffers {
6347 let buffer_id = buffer.id;
6348 let remote_version = language::proto::deserialize_version(&buffer.version);
6349 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6350 this.shared_buffers
6351 .entry(guest_id)
6352 .or_default()
6353 .insert(buffer_id);
6354
6355 let buffer = buffer.read(cx);
6356 response.buffers.push(proto::BufferVersion {
6357 id: buffer_id,
6358 version: language::proto::serialize_version(&buffer.version),
6359 });
6360
6361 let operations = buffer.serialize_ops(Some(remote_version), cx);
6362 let client = this.client.clone();
6363 if let Some(file) = buffer.file() {
6364 client
6365 .send(proto::UpdateBufferFile {
6366 project_id,
6367 buffer_id: buffer_id as u64,
6368 file: Some(file.to_proto()),
6369 })
6370 .log_err();
6371 }
6372
6373 client
6374 .send(proto::UpdateDiffBase {
6375 project_id,
6376 buffer_id: buffer_id as u64,
6377 diff_base: buffer.diff_base().map(Into::into),
6378 })
6379 .log_err();
6380
6381 client
6382 .send(proto::BufferReloaded {
6383 project_id,
6384 buffer_id,
6385 version: language::proto::serialize_version(buffer.saved_version()),
6386 mtime: Some(buffer.saved_mtime().into()),
6387 fingerprint: language::proto::serialize_fingerprint(
6388 buffer.saved_version_fingerprint(),
6389 ),
6390 line_ending: language::proto::serialize_line_ending(
6391 buffer.line_ending(),
6392 ) as i32,
6393 })
6394 .log_err();
6395
6396 cx.background()
6397 .spawn(
6398 async move {
6399 let operations = operations.await;
6400 for chunk in split_operations(operations) {
6401 client
6402 .request(proto::UpdateBuffer {
6403 project_id,
6404 buffer_id,
6405 operations: chunk,
6406 })
6407 .await?;
6408 }
6409 anyhow::Ok(())
6410 }
6411 .log_err(),
6412 )
6413 .detach();
6414 }
6415 }
6416 });
6417
6418 Ok(response)
6419 }
6420
6421 async fn handle_format_buffers(
6422 this: ModelHandle<Self>,
6423 envelope: TypedEnvelope<proto::FormatBuffers>,
6424 _: Arc<Client>,
6425 mut cx: AsyncAppContext,
6426 ) -> Result<proto::FormatBuffersResponse> {
6427 let sender_id = envelope.original_sender_id()?;
6428 let format = this.update(&mut cx, |this, cx| {
6429 let mut buffers = HashSet::default();
6430 for buffer_id in &envelope.payload.buffer_ids {
6431 buffers.insert(
6432 this.opened_buffers
6433 .get(buffer_id)
6434 .and_then(|buffer| buffer.upgrade(cx))
6435 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6436 );
6437 }
6438 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
6439 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
6440 })?;
6441
6442 let project_transaction = format.await?;
6443 let project_transaction = this.update(&mut cx, |this, cx| {
6444 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6445 });
6446 Ok(proto::FormatBuffersResponse {
6447 transaction: Some(project_transaction),
6448 })
6449 }
6450
6451 async fn handle_apply_additional_edits_for_completion(
6452 this: ModelHandle<Self>,
6453 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
6454 _: Arc<Client>,
6455 mut cx: AsyncAppContext,
6456 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
6457 let (buffer, completion) = this.update(&mut cx, |this, cx| {
6458 let buffer = this
6459 .opened_buffers
6460 .get(&envelope.payload.buffer_id)
6461 .and_then(|buffer| buffer.upgrade(cx))
6462 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6463 let language = buffer.read(cx).language();
6464 let completion = language::proto::deserialize_completion(
6465 envelope
6466 .payload
6467 .completion
6468 .ok_or_else(|| anyhow!("invalid completion"))?,
6469 language.cloned(),
6470 );
6471 Ok::<_, anyhow::Error>((buffer, completion))
6472 })?;
6473
6474 let completion = completion.await?;
6475
6476 let apply_additional_edits = this.update(&mut cx, |this, cx| {
6477 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
6478 });
6479
6480 Ok(proto::ApplyCompletionAdditionalEditsResponse {
6481 transaction: apply_additional_edits
6482 .await?
6483 .as_ref()
6484 .map(language::proto::serialize_transaction),
6485 })
6486 }
6487
6488 async fn handle_apply_code_action(
6489 this: ModelHandle<Self>,
6490 envelope: TypedEnvelope<proto::ApplyCodeAction>,
6491 _: Arc<Client>,
6492 mut cx: AsyncAppContext,
6493 ) -> Result<proto::ApplyCodeActionResponse> {
6494 let sender_id = envelope.original_sender_id()?;
6495 let action = language::proto::deserialize_code_action(
6496 envelope
6497 .payload
6498 .action
6499 .ok_or_else(|| anyhow!("invalid action"))?,
6500 )?;
6501 let apply_code_action = this.update(&mut cx, |this, cx| {
6502 let buffer = this
6503 .opened_buffers
6504 .get(&envelope.payload.buffer_id)
6505 .and_then(|buffer| buffer.upgrade(cx))
6506 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6507 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
6508 })?;
6509
6510 let project_transaction = apply_code_action.await?;
6511 let project_transaction = this.update(&mut cx, |this, cx| {
6512 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6513 });
6514 Ok(proto::ApplyCodeActionResponse {
6515 transaction: Some(project_transaction),
6516 })
6517 }
6518
6519 async fn handle_on_type_formatting(
6520 this: ModelHandle<Self>,
6521 envelope: TypedEnvelope<proto::OnTypeFormatting>,
6522 _: Arc<Client>,
6523 mut cx: AsyncAppContext,
6524 ) -> Result<proto::OnTypeFormattingResponse> {
6525 let on_type_formatting = this.update(&mut cx, |this, cx| {
6526 let buffer = this
6527 .opened_buffers
6528 .get(&envelope.payload.buffer_id)
6529 .and_then(|buffer| buffer.upgrade(cx))
6530 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6531 let position = envelope
6532 .payload
6533 .position
6534 .and_then(deserialize_anchor)
6535 .ok_or_else(|| anyhow!("invalid position"))?;
6536 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
6537 buffer,
6538 position,
6539 envelope.payload.trigger.clone(),
6540 cx,
6541 ))
6542 })?;
6543
6544 let transaction = on_type_formatting
6545 .await?
6546 .as_ref()
6547 .map(language::proto::serialize_transaction);
6548 Ok(proto::OnTypeFormattingResponse { transaction })
6549 }
6550
6551 async fn handle_lsp_command<T: LspCommand>(
6552 this: ModelHandle<Self>,
6553 envelope: TypedEnvelope<T::ProtoRequest>,
6554 _: Arc<Client>,
6555 mut cx: AsyncAppContext,
6556 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
6557 where
6558 <T::LspRequest as lsp::request::Request>::Result: Send,
6559 {
6560 let sender_id = envelope.original_sender_id()?;
6561 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
6562 let buffer_handle = this.read_with(&cx, |this, _| {
6563 this.opened_buffers
6564 .get(&buffer_id)
6565 .and_then(|buffer| buffer.upgrade(&cx))
6566 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
6567 })?;
6568 let request = T::from_proto(
6569 envelope.payload,
6570 this.clone(),
6571 buffer_handle.clone(),
6572 cx.clone(),
6573 )
6574 .await?;
6575 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
6576 let response = this
6577 .update(&mut cx, |this, cx| {
6578 this.request_lsp(buffer_handle, request, cx)
6579 })
6580 .await?;
6581 this.update(&mut cx, |this, cx| {
6582 Ok(T::response_to_proto(
6583 response,
6584 this,
6585 sender_id,
6586 &buffer_version,
6587 cx,
6588 ))
6589 })
6590 }
6591
6592 async fn handle_get_project_symbols(
6593 this: ModelHandle<Self>,
6594 envelope: TypedEnvelope<proto::GetProjectSymbols>,
6595 _: Arc<Client>,
6596 mut cx: AsyncAppContext,
6597 ) -> Result<proto::GetProjectSymbolsResponse> {
6598 let symbols = this
6599 .update(&mut cx, |this, cx| {
6600 this.symbols(&envelope.payload.query, cx)
6601 })
6602 .await?;
6603
6604 Ok(proto::GetProjectSymbolsResponse {
6605 symbols: symbols.iter().map(serialize_symbol).collect(),
6606 })
6607 }
6608
6609 async fn handle_search_project(
6610 this: ModelHandle<Self>,
6611 envelope: TypedEnvelope<proto::SearchProject>,
6612 _: Arc<Client>,
6613 mut cx: AsyncAppContext,
6614 ) -> Result<proto::SearchProjectResponse> {
6615 let peer_id = envelope.original_sender_id()?;
6616 let query = SearchQuery::from_proto(envelope.payload)?;
6617 let result = this
6618 .update(&mut cx, |this, cx| this.search(query, cx))
6619 .await?;
6620
6621 this.update(&mut cx, |this, cx| {
6622 let mut locations = Vec::new();
6623 for (buffer, ranges) in result {
6624 for range in ranges {
6625 let start = serialize_anchor(&range.start);
6626 let end = serialize_anchor(&range.end);
6627 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
6628 locations.push(proto::Location {
6629 buffer_id,
6630 start: Some(start),
6631 end: Some(end),
6632 });
6633 }
6634 }
6635 Ok(proto::SearchProjectResponse { locations })
6636 })
6637 }
6638
6639 async fn handle_open_buffer_for_symbol(
6640 this: ModelHandle<Self>,
6641 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
6642 _: Arc<Client>,
6643 mut cx: AsyncAppContext,
6644 ) -> Result<proto::OpenBufferForSymbolResponse> {
6645 let peer_id = envelope.original_sender_id()?;
6646 let symbol = envelope
6647 .payload
6648 .symbol
6649 .ok_or_else(|| anyhow!("invalid symbol"))?;
6650 let symbol = this
6651 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
6652 .await?;
6653 let symbol = this.read_with(&cx, |this, _| {
6654 let signature = this.symbol_signature(&symbol.path);
6655 if signature == symbol.signature {
6656 Ok(symbol)
6657 } else {
6658 Err(anyhow!("invalid symbol signature"))
6659 }
6660 })?;
6661 let buffer = this
6662 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
6663 .await?;
6664
6665 Ok(proto::OpenBufferForSymbolResponse {
6666 buffer_id: this.update(&mut cx, |this, cx| {
6667 this.create_buffer_for_peer(&buffer, peer_id, cx)
6668 }),
6669 })
6670 }
6671
6672 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
6673 let mut hasher = Sha256::new();
6674 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
6675 hasher.update(project_path.path.to_string_lossy().as_bytes());
6676 hasher.update(self.nonce.to_be_bytes());
6677 hasher.finalize().as_slice().try_into().unwrap()
6678 }
6679
6680 async fn handle_open_buffer_by_id(
6681 this: ModelHandle<Self>,
6682 envelope: TypedEnvelope<proto::OpenBufferById>,
6683 _: Arc<Client>,
6684 mut cx: AsyncAppContext,
6685 ) -> Result<proto::OpenBufferResponse> {
6686 let peer_id = envelope.original_sender_id()?;
6687 let buffer = this
6688 .update(&mut cx, |this, cx| {
6689 this.open_buffer_by_id(envelope.payload.id, cx)
6690 })
6691 .await?;
6692 this.update(&mut cx, |this, cx| {
6693 Ok(proto::OpenBufferResponse {
6694 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6695 })
6696 })
6697 }
6698
6699 async fn handle_open_buffer_by_path(
6700 this: ModelHandle<Self>,
6701 envelope: TypedEnvelope<proto::OpenBufferByPath>,
6702 _: Arc<Client>,
6703 mut cx: AsyncAppContext,
6704 ) -> Result<proto::OpenBufferResponse> {
6705 let peer_id = envelope.original_sender_id()?;
6706 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6707 let open_buffer = this.update(&mut cx, |this, cx| {
6708 this.open_buffer(
6709 ProjectPath {
6710 worktree_id,
6711 path: PathBuf::from(envelope.payload.path).into(),
6712 },
6713 cx,
6714 )
6715 });
6716
6717 let buffer = open_buffer.await?;
6718 this.update(&mut cx, |this, cx| {
6719 Ok(proto::OpenBufferResponse {
6720 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6721 })
6722 })
6723 }
6724
6725 fn serialize_project_transaction_for_peer(
6726 &mut self,
6727 project_transaction: ProjectTransaction,
6728 peer_id: proto::PeerId,
6729 cx: &mut AppContext,
6730 ) -> proto::ProjectTransaction {
6731 let mut serialized_transaction = proto::ProjectTransaction {
6732 buffer_ids: Default::default(),
6733 transactions: Default::default(),
6734 };
6735 for (buffer, transaction) in project_transaction.0 {
6736 serialized_transaction
6737 .buffer_ids
6738 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
6739 serialized_transaction
6740 .transactions
6741 .push(language::proto::serialize_transaction(&transaction));
6742 }
6743 serialized_transaction
6744 }
6745
6746 fn deserialize_project_transaction(
6747 &mut self,
6748 message: proto::ProjectTransaction,
6749 push_to_history: bool,
6750 cx: &mut ModelContext<Self>,
6751 ) -> Task<Result<ProjectTransaction>> {
6752 cx.spawn(|this, mut cx| async move {
6753 let mut project_transaction = ProjectTransaction::default();
6754 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
6755 {
6756 let buffer = this
6757 .update(&mut cx, |this, cx| {
6758 this.wait_for_remote_buffer(buffer_id, cx)
6759 })
6760 .await?;
6761 let transaction = language::proto::deserialize_transaction(transaction)?;
6762 project_transaction.0.insert(buffer, transaction);
6763 }
6764
6765 for (buffer, transaction) in &project_transaction.0 {
6766 buffer
6767 .update(&mut cx, |buffer, _| {
6768 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
6769 })
6770 .await?;
6771
6772 if push_to_history {
6773 buffer.update(&mut cx, |buffer, _| {
6774 buffer.push_transaction(transaction.clone(), Instant::now());
6775 });
6776 }
6777 }
6778
6779 Ok(project_transaction)
6780 })
6781 }
6782
6783 fn create_buffer_for_peer(
6784 &mut self,
6785 buffer: &ModelHandle<Buffer>,
6786 peer_id: proto::PeerId,
6787 cx: &mut AppContext,
6788 ) -> u64 {
6789 let buffer_id = buffer.read(cx).remote_id();
6790 if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
6791 updates_tx
6792 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
6793 .ok();
6794 }
6795 buffer_id
6796 }
6797
6798 fn wait_for_remote_buffer(
6799 &mut self,
6800 id: u64,
6801 cx: &mut ModelContext<Self>,
6802 ) -> Task<Result<ModelHandle<Buffer>>> {
6803 let mut opened_buffer_rx = self.opened_buffer.1.clone();
6804
6805 cx.spawn_weak(|this, mut cx| async move {
6806 let buffer = loop {
6807 let Some(this) = this.upgrade(&cx) else {
6808 return Err(anyhow!("project dropped"));
6809 };
6810
6811 let buffer = this.read_with(&cx, |this, cx| {
6812 this.opened_buffers
6813 .get(&id)
6814 .and_then(|buffer| buffer.upgrade(cx))
6815 });
6816
6817 if let Some(buffer) = buffer {
6818 break buffer;
6819 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
6820 return Err(anyhow!("disconnected before buffer {} could be opened", id));
6821 }
6822
6823 this.update(&mut cx, |this, _| {
6824 this.incomplete_remote_buffers.entry(id).or_default();
6825 });
6826 drop(this);
6827
6828 opened_buffer_rx
6829 .next()
6830 .await
6831 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
6832 };
6833
6834 Ok(buffer)
6835 })
6836 }
6837
6838 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
6839 let project_id = match self.client_state.as_ref() {
6840 Some(ProjectClientState::Remote {
6841 sharing_has_stopped,
6842 remote_id,
6843 ..
6844 }) => {
6845 if *sharing_has_stopped {
6846 return Task::ready(Err(anyhow!(
6847 "can't synchronize remote buffers on a readonly project"
6848 )));
6849 } else {
6850 *remote_id
6851 }
6852 }
6853 Some(ProjectClientState::Local { .. }) | None => {
6854 return Task::ready(Err(anyhow!(
6855 "can't synchronize remote buffers on a local project"
6856 )))
6857 }
6858 };
6859
6860 let client = self.client.clone();
6861 cx.spawn(|this, cx| async move {
6862 let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
6863 let buffers = this
6864 .opened_buffers
6865 .iter()
6866 .filter_map(|(id, buffer)| {
6867 let buffer = buffer.upgrade(cx)?;
6868 Some(proto::BufferVersion {
6869 id: *id,
6870 version: language::proto::serialize_version(&buffer.read(cx).version),
6871 })
6872 })
6873 .collect();
6874 let incomplete_buffer_ids = this
6875 .incomplete_remote_buffers
6876 .keys()
6877 .copied()
6878 .collect::<Vec<_>>();
6879
6880 (buffers, incomplete_buffer_ids)
6881 });
6882 let response = client
6883 .request(proto::SynchronizeBuffers {
6884 project_id,
6885 buffers,
6886 })
6887 .await?;
6888
6889 let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
6890 let client = client.clone();
6891 let buffer_id = buffer.id;
6892 let remote_version = language::proto::deserialize_version(&buffer.version);
6893 this.read_with(&cx, |this, cx| {
6894 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6895 let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
6896 cx.background().spawn(async move {
6897 let operations = operations.await;
6898 for chunk in split_operations(operations) {
6899 client
6900 .request(proto::UpdateBuffer {
6901 project_id,
6902 buffer_id,
6903 operations: chunk,
6904 })
6905 .await?;
6906 }
6907 anyhow::Ok(())
6908 })
6909 } else {
6910 Task::ready(Ok(()))
6911 }
6912 })
6913 });
6914
6915 // Any incomplete buffers have open requests waiting. Request that the host sends
6916 // creates these buffers for us again to unblock any waiting futures.
6917 for id in incomplete_buffer_ids {
6918 cx.background()
6919 .spawn(client.request(proto::OpenBufferById { project_id, id }))
6920 .detach();
6921 }
6922
6923 futures::future::join_all(send_updates_for_buffers)
6924 .await
6925 .into_iter()
6926 .collect()
6927 })
6928 }
6929
6930 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
6931 self.worktrees(cx)
6932 .map(|worktree| {
6933 let worktree = worktree.read(cx);
6934 proto::WorktreeMetadata {
6935 id: worktree.id().to_proto(),
6936 root_name: worktree.root_name().into(),
6937 visible: worktree.is_visible(),
6938 abs_path: worktree.abs_path().to_string_lossy().into(),
6939 }
6940 })
6941 .collect()
6942 }
6943
6944 fn set_worktrees_from_proto(
6945 &mut self,
6946 worktrees: Vec<proto::WorktreeMetadata>,
6947 cx: &mut ModelContext<Project>,
6948 ) -> Result<()> {
6949 let replica_id = self.replica_id();
6950 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
6951
6952 let mut old_worktrees_by_id = self
6953 .worktrees
6954 .drain(..)
6955 .filter_map(|worktree| {
6956 let worktree = worktree.upgrade(cx)?;
6957 Some((worktree.read(cx).id(), worktree))
6958 })
6959 .collect::<HashMap<_, _>>();
6960
6961 for worktree in worktrees {
6962 if let Some(old_worktree) =
6963 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
6964 {
6965 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
6966 } else {
6967 let worktree =
6968 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
6969 let _ = self.add_worktree(&worktree, cx);
6970 }
6971 }
6972
6973 self.metadata_changed(cx);
6974 for id in old_worktrees_by_id.keys() {
6975 cx.emit(Event::WorktreeRemoved(*id));
6976 }
6977
6978 Ok(())
6979 }
6980
6981 fn set_collaborators_from_proto(
6982 &mut self,
6983 messages: Vec<proto::Collaborator>,
6984 cx: &mut ModelContext<Self>,
6985 ) -> Result<()> {
6986 let mut collaborators = HashMap::default();
6987 for message in messages {
6988 let collaborator = Collaborator::from_proto(message)?;
6989 collaborators.insert(collaborator.peer_id, collaborator);
6990 }
6991 for old_peer_id in self.collaborators.keys() {
6992 if !collaborators.contains_key(old_peer_id) {
6993 cx.emit(Event::CollaboratorLeft(*old_peer_id));
6994 }
6995 }
6996 self.collaborators = collaborators;
6997 Ok(())
6998 }
6999
7000 fn deserialize_symbol(
7001 &self,
7002 serialized_symbol: proto::Symbol,
7003 ) -> impl Future<Output = Result<Symbol>> {
7004 let languages = self.languages.clone();
7005 async move {
7006 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
7007 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
7008 let start = serialized_symbol
7009 .start
7010 .ok_or_else(|| anyhow!("invalid start"))?;
7011 let end = serialized_symbol
7012 .end
7013 .ok_or_else(|| anyhow!("invalid end"))?;
7014 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
7015 let path = ProjectPath {
7016 worktree_id,
7017 path: PathBuf::from(serialized_symbol.path).into(),
7018 };
7019 let language = languages
7020 .language_for_file(&path.path, None)
7021 .await
7022 .log_err();
7023 Ok(Symbol {
7024 language_server_name: LanguageServerName(
7025 serialized_symbol.language_server_name.into(),
7026 ),
7027 source_worktree_id,
7028 path,
7029 label: {
7030 match language {
7031 Some(language) => {
7032 language
7033 .label_for_symbol(&serialized_symbol.name, kind)
7034 .await
7035 }
7036 None => None,
7037 }
7038 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
7039 },
7040
7041 name: serialized_symbol.name,
7042 range: Unclipped(PointUtf16::new(start.row, start.column))
7043 ..Unclipped(PointUtf16::new(end.row, end.column)),
7044 kind,
7045 signature: serialized_symbol
7046 .signature
7047 .try_into()
7048 .map_err(|_| anyhow!("invalid signature"))?,
7049 })
7050 }
7051 }
7052
7053 async fn handle_buffer_saved(
7054 this: ModelHandle<Self>,
7055 envelope: TypedEnvelope<proto::BufferSaved>,
7056 _: Arc<Client>,
7057 mut cx: AsyncAppContext,
7058 ) -> Result<()> {
7059 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
7060 let version = deserialize_version(&envelope.payload.version);
7061 let mtime = envelope
7062 .payload
7063 .mtime
7064 .ok_or_else(|| anyhow!("missing mtime"))?
7065 .into();
7066
7067 this.update(&mut cx, |this, cx| {
7068 let buffer = this
7069 .opened_buffers
7070 .get(&envelope.payload.buffer_id)
7071 .and_then(|buffer| buffer.upgrade(cx))
7072 .or_else(|| {
7073 this.incomplete_remote_buffers
7074 .get(&envelope.payload.buffer_id)
7075 .and_then(|b| b.clone())
7076 });
7077 if let Some(buffer) = buffer {
7078 buffer.update(cx, |buffer, cx| {
7079 buffer.did_save(version, fingerprint, mtime, cx);
7080 });
7081 }
7082 Ok(())
7083 })
7084 }
7085
7086 async fn handle_buffer_reloaded(
7087 this: ModelHandle<Self>,
7088 envelope: TypedEnvelope<proto::BufferReloaded>,
7089 _: Arc<Client>,
7090 mut cx: AsyncAppContext,
7091 ) -> Result<()> {
7092 let payload = envelope.payload;
7093 let version = deserialize_version(&payload.version);
7094 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
7095 let line_ending = deserialize_line_ending(
7096 proto::LineEnding::from_i32(payload.line_ending)
7097 .ok_or_else(|| anyhow!("missing line ending"))?,
7098 );
7099 let mtime = payload
7100 .mtime
7101 .ok_or_else(|| anyhow!("missing mtime"))?
7102 .into();
7103 this.update(&mut cx, |this, cx| {
7104 let buffer = this
7105 .opened_buffers
7106 .get(&payload.buffer_id)
7107 .and_then(|buffer| buffer.upgrade(cx))
7108 .or_else(|| {
7109 this.incomplete_remote_buffers
7110 .get(&payload.buffer_id)
7111 .cloned()
7112 .flatten()
7113 });
7114 if let Some(buffer) = buffer {
7115 buffer.update(cx, |buffer, cx| {
7116 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
7117 });
7118 }
7119 Ok(())
7120 })
7121 }
7122
7123 #[allow(clippy::type_complexity)]
7124 fn edits_from_lsp(
7125 &mut self,
7126 buffer: &ModelHandle<Buffer>,
7127 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
7128 server_id: LanguageServerId,
7129 version: Option<i32>,
7130 cx: &mut ModelContext<Self>,
7131 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
7132 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
7133 cx.background().spawn(async move {
7134 let snapshot = snapshot?;
7135 let mut lsp_edits = lsp_edits
7136 .into_iter()
7137 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
7138 .collect::<Vec<_>>();
7139 lsp_edits.sort_by_key(|(range, _)| range.start);
7140
7141 let mut lsp_edits = lsp_edits.into_iter().peekable();
7142 let mut edits = Vec::new();
7143 while let Some((range, mut new_text)) = lsp_edits.next() {
7144 // Clip invalid ranges provided by the language server.
7145 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
7146 ..snapshot.clip_point_utf16(range.end, Bias::Left);
7147
7148 // Combine any LSP edits that are adjacent.
7149 //
7150 // Also, combine LSP edits that are separated from each other by only
7151 // a newline. This is important because for some code actions,
7152 // Rust-analyzer rewrites the entire buffer via a series of edits that
7153 // are separated by unchanged newline characters.
7154 //
7155 // In order for the diffing logic below to work properly, any edits that
7156 // cancel each other out must be combined into one.
7157 while let Some((next_range, next_text)) = lsp_edits.peek() {
7158 if next_range.start.0 > range.end {
7159 if next_range.start.0.row > range.end.row + 1
7160 || next_range.start.0.column > 0
7161 || snapshot.clip_point_utf16(
7162 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
7163 Bias::Left,
7164 ) > range.end
7165 {
7166 break;
7167 }
7168 new_text.push('\n');
7169 }
7170 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
7171 new_text.push_str(next_text);
7172 lsp_edits.next();
7173 }
7174
7175 // For multiline edits, perform a diff of the old and new text so that
7176 // we can identify the changes more precisely, preserving the locations
7177 // of any anchors positioned in the unchanged regions.
7178 if range.end.row > range.start.row {
7179 let mut offset = range.start.to_offset(&snapshot);
7180 let old_text = snapshot.text_for_range(range).collect::<String>();
7181
7182 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
7183 let mut moved_since_edit = true;
7184 for change in diff.iter_all_changes() {
7185 let tag = change.tag();
7186 let value = change.value();
7187 match tag {
7188 ChangeTag::Equal => {
7189 offset += value.len();
7190 moved_since_edit = true;
7191 }
7192 ChangeTag::Delete => {
7193 let start = snapshot.anchor_after(offset);
7194 let end = snapshot.anchor_before(offset + value.len());
7195 if moved_since_edit {
7196 edits.push((start..end, String::new()));
7197 } else {
7198 edits.last_mut().unwrap().0.end = end;
7199 }
7200 offset += value.len();
7201 moved_since_edit = false;
7202 }
7203 ChangeTag::Insert => {
7204 if moved_since_edit {
7205 let anchor = snapshot.anchor_after(offset);
7206 edits.push((anchor..anchor, value.to_string()));
7207 } else {
7208 edits.last_mut().unwrap().1.push_str(value);
7209 }
7210 moved_since_edit = false;
7211 }
7212 }
7213 }
7214 } else if range.end == range.start {
7215 let anchor = snapshot.anchor_after(range.start);
7216 edits.push((anchor..anchor, new_text));
7217 } else {
7218 let edit_start = snapshot.anchor_after(range.start);
7219 let edit_end = snapshot.anchor_before(range.end);
7220 edits.push((edit_start..edit_end, new_text));
7221 }
7222 }
7223
7224 Ok(edits)
7225 })
7226 }
7227
7228 fn buffer_snapshot_for_lsp_version(
7229 &mut self,
7230 buffer: &ModelHandle<Buffer>,
7231 server_id: LanguageServerId,
7232 version: Option<i32>,
7233 cx: &AppContext,
7234 ) -> Result<TextBufferSnapshot> {
7235 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
7236
7237 if let Some(version) = version {
7238 let buffer_id = buffer.read(cx).remote_id();
7239 let snapshots = self
7240 .buffer_snapshots
7241 .get_mut(&buffer_id)
7242 .and_then(|m| m.get_mut(&server_id))
7243 .ok_or_else(|| {
7244 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
7245 })?;
7246
7247 let found_snapshot = snapshots
7248 .binary_search_by_key(&version, |e| e.version)
7249 .map(|ix| snapshots[ix].snapshot.clone())
7250 .map_err(|_| {
7251 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
7252 })?;
7253
7254 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
7255 Ok(found_snapshot)
7256 } else {
7257 Ok((buffer.read(cx)).text_snapshot())
7258 }
7259 }
7260
7261 pub fn language_servers(
7262 &self,
7263 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
7264 self.language_server_ids
7265 .iter()
7266 .map(|((worktree_id, server_name), server_id)| {
7267 (*server_id, server_name.clone(), *worktree_id)
7268 })
7269 }
7270
7271 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7272 if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
7273 Some(server.clone())
7274 } else {
7275 None
7276 }
7277 }
7278
7279 pub fn language_servers_for_buffer(
7280 &self,
7281 buffer: &Buffer,
7282 cx: &AppContext,
7283 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7284 self.language_server_ids_for_buffer(buffer, cx)
7285 .into_iter()
7286 .filter_map(|server_id| {
7287 let server = self.language_servers.get(&server_id)?;
7288 if let LanguageServerState::Running {
7289 adapter, server, ..
7290 } = server
7291 {
7292 Some((adapter, server))
7293 } else {
7294 None
7295 }
7296 })
7297 }
7298
7299 fn primary_language_servers_for_buffer(
7300 &self,
7301 buffer: &Buffer,
7302 cx: &AppContext,
7303 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7304 self.language_servers_for_buffer(buffer, cx).next()
7305 }
7306
7307 fn language_server_for_buffer(
7308 &self,
7309 buffer: &Buffer,
7310 server_id: LanguageServerId,
7311 cx: &AppContext,
7312 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7313 self.language_servers_for_buffer(buffer, cx)
7314 .find(|(_, s)| s.server_id() == server_id)
7315 }
7316
7317 fn language_server_ids_for_buffer(
7318 &self,
7319 buffer: &Buffer,
7320 cx: &AppContext,
7321 ) -> Vec<LanguageServerId> {
7322 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
7323 let worktree_id = file.worktree_id(cx);
7324 language
7325 .lsp_adapters()
7326 .iter()
7327 .flat_map(|adapter| {
7328 let key = (worktree_id, adapter.name.clone());
7329 self.language_server_ids.get(&key).copied()
7330 })
7331 .collect()
7332 } else {
7333 Vec::new()
7334 }
7335 }
7336}
7337
7338impl WorktreeHandle {
7339 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
7340 match self {
7341 WorktreeHandle::Strong(handle) => Some(handle.clone()),
7342 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
7343 }
7344 }
7345
7346 pub fn handle_id(&self) -> usize {
7347 match self {
7348 WorktreeHandle::Strong(handle) => handle.id(),
7349 WorktreeHandle::Weak(handle) => handle.id(),
7350 }
7351 }
7352}
7353
7354impl OpenBuffer {
7355 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
7356 match self {
7357 OpenBuffer::Strong(handle) => Some(handle.clone()),
7358 OpenBuffer::Weak(handle) => handle.upgrade(cx),
7359 OpenBuffer::Operations(_) => None,
7360 }
7361 }
7362}
7363
7364pub struct PathMatchCandidateSet {
7365 pub snapshot: Snapshot,
7366 pub include_ignored: bool,
7367 pub include_root_name: bool,
7368}
7369
7370impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
7371 type Candidates = PathMatchCandidateSetIter<'a>;
7372
7373 fn id(&self) -> usize {
7374 self.snapshot.id().to_usize()
7375 }
7376
7377 fn len(&self) -> usize {
7378 if self.include_ignored {
7379 self.snapshot.file_count()
7380 } else {
7381 self.snapshot.visible_file_count()
7382 }
7383 }
7384
7385 fn prefix(&self) -> Arc<str> {
7386 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
7387 self.snapshot.root_name().into()
7388 } else if self.include_root_name {
7389 format!("{}/", self.snapshot.root_name()).into()
7390 } else {
7391 "".into()
7392 }
7393 }
7394
7395 fn candidates(&'a self, start: usize) -> Self::Candidates {
7396 PathMatchCandidateSetIter {
7397 traversal: self.snapshot.files(self.include_ignored, start),
7398 }
7399 }
7400}
7401
7402pub struct PathMatchCandidateSetIter<'a> {
7403 traversal: Traversal<'a>,
7404}
7405
7406impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
7407 type Item = fuzzy::PathMatchCandidate<'a>;
7408
7409 fn next(&mut self) -> Option<Self::Item> {
7410 self.traversal.next().map(|entry| {
7411 if let EntryKind::File(char_bag) = entry.kind {
7412 fuzzy::PathMatchCandidate {
7413 path: &entry.path,
7414 char_bag,
7415 }
7416 } else {
7417 unreachable!()
7418 }
7419 })
7420 }
7421}
7422
7423impl Entity for Project {
7424 type Event = Event;
7425
7426 fn release(&mut self, cx: &mut gpui::AppContext) {
7427 match &self.client_state {
7428 Some(ProjectClientState::Local { .. }) => {
7429 let _ = self.unshare_internal(cx);
7430 }
7431 Some(ProjectClientState::Remote { remote_id, .. }) => {
7432 let _ = self.client.send(proto::LeaveProject {
7433 project_id: *remote_id,
7434 });
7435 self.disconnected_from_host_internal(cx);
7436 }
7437 _ => {}
7438 }
7439 }
7440
7441 fn app_will_quit(
7442 &mut self,
7443 _: &mut AppContext,
7444 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
7445 let shutdown_futures = self
7446 .language_servers
7447 .drain()
7448 .map(|(_, server_state)| async {
7449 use LanguageServerState::*;
7450 match server_state {
7451 Running { server, .. } => server.shutdown()?.await,
7452 Starting { task, .. } | Validating(task) => task.await?.shutdown()?.await,
7453 }
7454 })
7455 .collect::<Vec<_>>();
7456
7457 Some(
7458 async move {
7459 futures::future::join_all(shutdown_futures).await;
7460 }
7461 .boxed(),
7462 )
7463 }
7464}
7465
7466impl Collaborator {
7467 fn from_proto(message: proto::Collaborator) -> Result<Self> {
7468 Ok(Self {
7469 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
7470 replica_id: message.replica_id as ReplicaId,
7471 })
7472 }
7473}
7474
7475impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
7476 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
7477 Self {
7478 worktree_id,
7479 path: path.as_ref().into(),
7480 }
7481 }
7482}
7483
7484fn split_operations(
7485 mut operations: Vec<proto::Operation>,
7486) -> impl Iterator<Item = Vec<proto::Operation>> {
7487 #[cfg(any(test, feature = "test-support"))]
7488 const CHUNK_SIZE: usize = 5;
7489
7490 #[cfg(not(any(test, feature = "test-support")))]
7491 const CHUNK_SIZE: usize = 100;
7492
7493 let mut done = false;
7494 std::iter::from_fn(move || {
7495 if done {
7496 return None;
7497 }
7498
7499 let operations = operations
7500 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
7501 .collect::<Vec<_>>();
7502 if operations.is_empty() {
7503 done = true;
7504 }
7505 Some(operations)
7506 })
7507}
7508
7509fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
7510 proto::Symbol {
7511 language_server_name: symbol.language_server_name.0.to_string(),
7512 source_worktree_id: symbol.source_worktree_id.to_proto(),
7513 worktree_id: symbol.path.worktree_id.to_proto(),
7514 path: symbol.path.path.to_string_lossy().to_string(),
7515 name: symbol.name.clone(),
7516 kind: unsafe { mem::transmute(symbol.kind) },
7517 start: Some(proto::PointUtf16 {
7518 row: symbol.range.start.0.row,
7519 column: symbol.range.start.0.column,
7520 }),
7521 end: Some(proto::PointUtf16 {
7522 row: symbol.range.end.0.row,
7523 column: symbol.range.end.0.column,
7524 }),
7525 signature: symbol.signature.to_vec(),
7526 }
7527}
7528
7529fn relativize_path(base: &Path, path: &Path) -> PathBuf {
7530 let mut path_components = path.components();
7531 let mut base_components = base.components();
7532 let mut components: Vec<Component> = Vec::new();
7533 loop {
7534 match (path_components.next(), base_components.next()) {
7535 (None, None) => break,
7536 (Some(a), None) => {
7537 components.push(a);
7538 components.extend(path_components.by_ref());
7539 break;
7540 }
7541 (None, _) => components.push(Component::ParentDir),
7542 (Some(a), Some(b)) if components.is_empty() && a == b => (),
7543 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
7544 (Some(a), Some(_)) => {
7545 components.push(Component::ParentDir);
7546 for _ in base_components {
7547 components.push(Component::ParentDir);
7548 }
7549 components.push(a);
7550 components.extend(path_components.by_ref());
7551 break;
7552 }
7553 }
7554 }
7555 components.iter().map(|c| c.as_os_str()).collect()
7556}
7557
7558impl Item for Buffer {
7559 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
7560 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
7561 }
7562
7563 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
7564 File::from_dyn(self.file()).map(|file| ProjectPath {
7565 worktree_id: file.worktree_id(cx),
7566 path: file.path().clone(),
7567 })
7568 }
7569}
7570
7571async fn wait_for_loading_buffer(
7572 mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
7573) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
7574 loop {
7575 if let Some(result) = receiver.borrow().as_ref() {
7576 match result {
7577 Ok(buffer) => return Ok(buffer.to_owned()),
7578 Err(e) => return Err(e.to_owned()),
7579 }
7580 }
7581 receiver.next().await;
7582 }
7583}