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