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