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