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