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