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