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: 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: Option<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 mut status = client.status();
422 let _detect_unshare = cx.spawn_weak(move |this, mut cx| {
423 async move {
424 let is_connected = status.next().await.map_or(false, |s| s.is_connected());
425 // Even if we're initially connected, any future change of the status means we momentarily disconnected.
426 if !is_connected || status.next().await.is_some() {
427 if let Some(this) = this.upgrade(&cx) {
428 let _ = this.update(&mut cx, |this, cx| this.unshare(cx));
429 }
430 }
431 Ok(())
432 }
433 .log_err()
434 });
435
436 let handle = cx.weak_handle();
437 project_store.update(cx, |store, cx| store.add_project(handle, cx));
438
439 Self {
440 worktrees: Default::default(),
441 collaborators: Default::default(),
442 opened_buffers: Default::default(),
443 shared_buffers: Default::default(),
444 incomplete_buffers: Default::default(),
445 loading_buffers: Default::default(),
446 loading_local_worktrees: Default::default(),
447 buffer_snapshots: Default::default(),
448 client_state: ProjectClientState::Local {
449 remote_id: None,
450 _detect_unshare,
451 },
452 opened_buffer: watch::channel(),
453 client_subscriptions: Vec::new(),
454 _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
455 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
456 active_entry: None,
457 languages,
458 client,
459 user_store,
460 project_store,
461 fs,
462 next_entry_id: Default::default(),
463 next_diagnostic_group_id: Default::default(),
464 language_servers: Default::default(),
465 language_server_ids: Default::default(),
466 language_server_statuses: Default::default(),
467 last_workspace_edits_by_language_server: Default::default(),
468 language_server_settings: Default::default(),
469 buffers_being_formatted: Default::default(),
470 next_language_server_id: 0,
471 nonce: StdRng::from_entropy().gen(),
472 }
473 })
474 }
475
476 pub async fn remote(
477 remote_id: u64,
478 client: Arc<Client>,
479 user_store: ModelHandle<UserStore>,
480 project_store: ModelHandle<ProjectStore>,
481 languages: Arc<LanguageRegistry>,
482 fs: Arc<dyn Fs>,
483 mut cx: AsyncAppContext,
484 ) -> Result<ModelHandle<Self>, JoinProjectError> {
485 client.authenticate_and_connect(true, &cx).await?;
486
487 let response = client
488 .request(proto::JoinProject {
489 project_id: remote_id,
490 })
491 .await?;
492
493 let replica_id = response.replica_id as ReplicaId;
494
495 let mut worktrees = Vec::new();
496 for worktree in response.worktrees {
497 let worktree = cx
498 .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
499 worktrees.push(worktree);
500 }
501
502 let this = cx.add_model(|cx: &mut ModelContext<Self>| {
503 let handle = cx.weak_handle();
504 project_store.update(cx, |store, cx| store.add_project(handle, cx));
505
506 let mut this = Self {
507 worktrees: Vec::new(),
508 loading_buffers: Default::default(),
509 opened_buffer: watch::channel(),
510 shared_buffers: Default::default(),
511 incomplete_buffers: Default::default(),
512 loading_local_worktrees: Default::default(),
513 active_entry: None,
514 collaborators: Default::default(),
515 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
516 languages,
517 user_store: user_store.clone(),
518 project_store,
519 fs,
520 next_entry_id: Default::default(),
521 next_diagnostic_group_id: Default::default(),
522 client_subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
523 _subscriptions: Default::default(),
524 client: client.clone(),
525 client_state: ProjectClientState::Remote {
526 sharing_has_stopped: false,
527 remote_id,
528 replica_id,
529 _detect_unshare: cx.spawn_weak(move |this, mut cx| {
530 async move {
531 let mut status = client.status();
532 let is_connected =
533 status.next().await.map_or(false, |s| s.is_connected());
534 // Even if we're initially connected, any future change of the status means we momentarily disconnected.
535 if !is_connected || status.next().await.is_some() {
536 if let Some(this) = this.upgrade(&cx) {
537 this.update(&mut cx, |this, cx| this.disconnected_from_host(cx))
538 }
539 }
540 Ok(())
541 }
542 .log_err()
543 }),
544 },
545 language_servers: Default::default(),
546 language_server_ids: Default::default(),
547 language_server_settings: Default::default(),
548 language_server_statuses: response
549 .language_servers
550 .into_iter()
551 .map(|server| {
552 (
553 server.id as usize,
554 LanguageServerStatus {
555 name: server.name,
556 pending_work: Default::default(),
557 has_pending_diagnostic_updates: false,
558 progress_tokens: Default::default(),
559 },
560 )
561 })
562 .collect(),
563 last_workspace_edits_by_language_server: Default::default(),
564 next_language_server_id: 0,
565 opened_buffers: Default::default(),
566 buffers_being_formatted: Default::default(),
567 buffer_snapshots: Default::default(),
568 nonce: StdRng::from_entropy().gen(),
569 };
570 for worktree in worktrees {
571 this.add_worktree(&worktree, cx);
572 }
573 this
574 });
575
576 let user_ids = response
577 .collaborators
578 .iter()
579 .map(|peer| peer.user_id)
580 .collect();
581 user_store
582 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
583 .await?;
584 let mut collaborators = HashMap::default();
585 for message in response.collaborators {
586 let collaborator = Collaborator::from_proto(message);
587 collaborators.insert(collaborator.peer_id, collaborator);
588 }
589
590 this.update(&mut cx, |this, _| {
591 this.collaborators = collaborators;
592 });
593
594 Ok(this)
595 }
596
597 #[cfg(any(test, feature = "test-support"))]
598 pub async fn test(
599 fs: Arc<dyn Fs>,
600 root_paths: impl IntoIterator<Item = &Path>,
601 cx: &mut gpui::TestAppContext,
602 ) -> ModelHandle<Project> {
603 if !cx.read(|cx| cx.has_global::<Settings>()) {
604 cx.update(|cx| cx.set_global(Settings::test(cx)));
605 }
606
607 let languages = Arc::new(LanguageRegistry::test());
608 let http_client = client::test::FakeHttpClient::with_404_response();
609 let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
610 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
611 let project_store = cx.add_model(|_| ProjectStore::new());
612 let project =
613 cx.update(|cx| Project::local(client, user_store, project_store, languages, fs, cx));
614 for path in root_paths {
615 let (tree, _) = project
616 .update(cx, |project, cx| {
617 project.find_or_create_local_worktree(path, true, cx)
618 })
619 .await
620 .unwrap();
621 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
622 .await;
623 }
624 project
625 }
626
627 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
628 let settings = cx.global::<Settings>();
629
630 let mut language_servers_to_start = Vec::new();
631 for buffer in self.opened_buffers.values() {
632 if let Some(buffer) = buffer.upgrade(cx) {
633 let buffer = buffer.read(cx);
634 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
635 {
636 if settings.enable_language_server(Some(&language.name())) {
637 let worktree = file.worktree.read(cx);
638 language_servers_to_start.push((
639 worktree.id(),
640 worktree.as_local().unwrap().abs_path().clone(),
641 language.clone(),
642 ));
643 }
644 }
645 }
646 }
647
648 let mut language_servers_to_stop = Vec::new();
649 for language in self.languages.to_vec() {
650 if let Some(lsp_adapter) = language.lsp_adapter() {
651 if !settings.enable_language_server(Some(&language.name())) {
652 let lsp_name = &lsp_adapter.name;
653 for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
654 if lsp_name == started_lsp_name {
655 language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
656 }
657 }
658 }
659 }
660 }
661
662 // Stop all newly-disabled language servers.
663 for (worktree_id, adapter_name) in language_servers_to_stop {
664 self.stop_language_server(worktree_id, adapter_name, cx)
665 .detach();
666 }
667
668 // Start all the newly-enabled language servers.
669 for (worktree_id, worktree_path, language) in language_servers_to_start {
670 self.start_language_server(worktree_id, worktree_path, language, cx);
671 }
672
673 cx.notify();
674 }
675
676 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
677 self.opened_buffers
678 .get(&remote_id)
679 .and_then(|buffer| buffer.upgrade(cx))
680 }
681
682 pub fn languages(&self) -> &Arc<LanguageRegistry> {
683 &self.languages
684 }
685
686 pub fn client(&self) -> Arc<Client> {
687 self.client.clone()
688 }
689
690 pub fn user_store(&self) -> ModelHandle<UserStore> {
691 self.user_store.clone()
692 }
693
694 pub fn project_store(&self) -> ModelHandle<ProjectStore> {
695 self.project_store.clone()
696 }
697
698 #[cfg(any(test, feature = "test-support"))]
699 pub fn check_invariants(&self, cx: &AppContext) {
700 if self.is_local() {
701 let mut worktree_root_paths = HashMap::default();
702 for worktree in self.worktrees(cx) {
703 let worktree = worktree.read(cx);
704 let abs_path = worktree.as_local().unwrap().abs_path().clone();
705 let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
706 assert_eq!(
707 prev_worktree_id,
708 None,
709 "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
710 abs_path,
711 worktree.id(),
712 prev_worktree_id
713 )
714 }
715 } else {
716 let replica_id = self.replica_id();
717 for buffer in self.opened_buffers.values() {
718 if let Some(buffer) = buffer.upgrade(cx) {
719 let buffer = buffer.read(cx);
720 assert_eq!(
721 buffer.deferred_ops_len(),
722 0,
723 "replica {}, buffer {} has deferred operations",
724 replica_id,
725 buffer.remote_id()
726 );
727 }
728 }
729 }
730 }
731
732 #[cfg(any(test, feature = "test-support"))]
733 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
734 let path = path.into();
735 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
736 self.opened_buffers.iter().any(|(_, buffer)| {
737 if let Some(buffer) = buffer.upgrade(cx) {
738 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
739 if file.worktree == worktree && file.path() == &path.path {
740 return true;
741 }
742 }
743 }
744 false
745 })
746 } else {
747 false
748 }
749 }
750
751 pub fn fs(&self) -> &Arc<dyn Fs> {
752 &self.fs
753 }
754
755 pub fn remote_id(&self) -> Option<u64> {
756 match &self.client_state {
757 ProjectClientState::Local { remote_id, .. } => *remote_id,
758 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
759 }
760 }
761
762 pub fn replica_id(&self) -> ReplicaId {
763 match &self.client_state {
764 ProjectClientState::Local { .. } => 0,
765 ProjectClientState::Remote { replica_id, .. } => *replica_id,
766 }
767 }
768
769 fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
770 if let ProjectClientState::Local { remote_id, .. } = &self.client_state {
771 // Broadcast worktrees only if the project is online.
772 let worktrees = self
773 .worktrees
774 .iter()
775 .filter_map(|worktree| {
776 worktree
777 .upgrade(cx)
778 .map(|worktree| worktree.read(cx).as_local().unwrap().metadata_proto())
779 })
780 .collect();
781 if let Some(project_id) = *remote_id {
782 self.client
783 .send(proto::UpdateProject {
784 project_id,
785 worktrees,
786 })
787 .log_err();
788
789 let worktrees = self.visible_worktrees(cx).collect::<Vec<_>>();
790 let scans_complete =
791 futures::future::join_all(worktrees.iter().filter_map(|worktree| {
792 Some(worktree.read(cx).as_local()?.scan_complete())
793 }));
794
795 let worktrees = worktrees.into_iter().map(|handle| handle.downgrade());
796 cx.spawn_weak(move |_, cx| async move {
797 scans_complete.await;
798 cx.read(|cx| {
799 for worktree in worktrees {
800 if let Some(worktree) = worktree
801 .upgrade(cx)
802 .and_then(|worktree| worktree.read(cx).as_local())
803 {
804 worktree.send_extension_counts(project_id);
805 }
806 }
807 })
808 })
809 .detach();
810 }
811
812 self.project_store.update(cx, |_, cx| cx.notify());
813 cx.notify();
814 }
815 }
816
817 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
818 &self.collaborators
819 }
820
821 pub fn worktrees<'a>(
822 &'a self,
823 cx: &'a AppContext,
824 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
825 self.worktrees
826 .iter()
827 .filter_map(move |worktree| worktree.upgrade(cx))
828 }
829
830 pub fn visible_worktrees<'a>(
831 &'a self,
832 cx: &'a AppContext,
833 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
834 self.worktrees.iter().filter_map(|worktree| {
835 worktree.upgrade(cx).and_then(|worktree| {
836 if worktree.read(cx).is_visible() {
837 Some(worktree)
838 } else {
839 None
840 }
841 })
842 })
843 }
844
845 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
846 self.visible_worktrees(cx)
847 .map(|tree| tree.read(cx).root_name())
848 }
849
850 pub fn worktree_for_id(
851 &self,
852 id: WorktreeId,
853 cx: &AppContext,
854 ) -> Option<ModelHandle<Worktree>> {
855 self.worktrees(cx)
856 .find(|worktree| worktree.read(cx).id() == id)
857 }
858
859 pub fn worktree_for_entry(
860 &self,
861 entry_id: ProjectEntryId,
862 cx: &AppContext,
863 ) -> Option<ModelHandle<Worktree>> {
864 self.worktrees(cx)
865 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
866 }
867
868 pub fn worktree_id_for_entry(
869 &self,
870 entry_id: ProjectEntryId,
871 cx: &AppContext,
872 ) -> Option<WorktreeId> {
873 self.worktree_for_entry(entry_id, cx)
874 .map(|worktree| worktree.read(cx).id())
875 }
876
877 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
878 paths.iter().all(|path| self.contains_path(path, cx))
879 }
880
881 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
882 for worktree in self.worktrees(cx) {
883 let worktree = worktree.read(cx).as_local();
884 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
885 return true;
886 }
887 }
888 false
889 }
890
891 pub fn create_entry(
892 &mut self,
893 project_path: impl Into<ProjectPath>,
894 is_directory: bool,
895 cx: &mut ModelContext<Self>,
896 ) -> Option<Task<Result<Entry>>> {
897 let project_path = project_path.into();
898 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
899 if self.is_local() {
900 Some(worktree.update(cx, |worktree, cx| {
901 worktree
902 .as_local_mut()
903 .unwrap()
904 .create_entry(project_path.path, is_directory, cx)
905 }))
906 } else {
907 let client = self.client.clone();
908 let project_id = self.remote_id().unwrap();
909 Some(cx.spawn_weak(|_, mut cx| async move {
910 let response = client
911 .request(proto::CreateProjectEntry {
912 worktree_id: project_path.worktree_id.to_proto(),
913 project_id,
914 path: project_path.path.as_os_str().as_bytes().to_vec(),
915 is_directory,
916 })
917 .await?;
918 let entry = response
919 .entry
920 .ok_or_else(|| anyhow!("missing entry in response"))?;
921 worktree
922 .update(&mut cx, |worktree, cx| {
923 worktree.as_remote_mut().unwrap().insert_entry(
924 entry,
925 response.worktree_scan_id as usize,
926 cx,
927 )
928 })
929 .await
930 }))
931 }
932 }
933
934 pub fn copy_entry(
935 &mut self,
936 entry_id: ProjectEntryId,
937 new_path: impl Into<Arc<Path>>,
938 cx: &mut ModelContext<Self>,
939 ) -> Option<Task<Result<Entry>>> {
940 let worktree = self.worktree_for_entry(entry_id, cx)?;
941 let new_path = new_path.into();
942 if self.is_local() {
943 worktree.update(cx, |worktree, cx| {
944 worktree
945 .as_local_mut()
946 .unwrap()
947 .copy_entry(entry_id, new_path, cx)
948 })
949 } else {
950 let client = self.client.clone();
951 let project_id = self.remote_id().unwrap();
952
953 Some(cx.spawn_weak(|_, mut cx| async move {
954 let response = client
955 .request(proto::CopyProjectEntry {
956 project_id,
957 entry_id: entry_id.to_proto(),
958 new_path: new_path.as_os_str().as_bytes().to_vec(),
959 })
960 .await?;
961 let entry = response
962 .entry
963 .ok_or_else(|| anyhow!("missing entry in response"))?;
964 worktree
965 .update(&mut cx, |worktree, cx| {
966 worktree.as_remote_mut().unwrap().insert_entry(
967 entry,
968 response.worktree_scan_id as usize,
969 cx,
970 )
971 })
972 .await
973 }))
974 }
975 }
976
977 pub fn rename_entry(
978 &mut self,
979 entry_id: ProjectEntryId,
980 new_path: impl Into<Arc<Path>>,
981 cx: &mut ModelContext<Self>,
982 ) -> Option<Task<Result<Entry>>> {
983 let worktree = self.worktree_for_entry(entry_id, cx)?;
984 let new_path = new_path.into();
985 if self.is_local() {
986 worktree.update(cx, |worktree, cx| {
987 worktree
988 .as_local_mut()
989 .unwrap()
990 .rename_entry(entry_id, new_path, cx)
991 })
992 } else {
993 let client = self.client.clone();
994 let project_id = self.remote_id().unwrap();
995
996 Some(cx.spawn_weak(|_, mut cx| async move {
997 let response = client
998 .request(proto::RenameProjectEntry {
999 project_id,
1000 entry_id: entry_id.to_proto(),
1001 new_path: new_path.as_os_str().as_bytes().to_vec(),
1002 })
1003 .await?;
1004 let entry = response
1005 .entry
1006 .ok_or_else(|| anyhow!("missing entry in response"))?;
1007 worktree
1008 .update(&mut cx, |worktree, cx| {
1009 worktree.as_remote_mut().unwrap().insert_entry(
1010 entry,
1011 response.worktree_scan_id as usize,
1012 cx,
1013 )
1014 })
1015 .await
1016 }))
1017 }
1018 }
1019
1020 pub fn delete_entry(
1021 &mut self,
1022 entry_id: ProjectEntryId,
1023 cx: &mut ModelContext<Self>,
1024 ) -> Option<Task<Result<()>>> {
1025 let worktree = self.worktree_for_entry(entry_id, cx)?;
1026 if self.is_local() {
1027 worktree.update(cx, |worktree, cx| {
1028 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1029 })
1030 } else {
1031 let client = self.client.clone();
1032 let project_id = self.remote_id().unwrap();
1033 Some(cx.spawn_weak(|_, mut cx| async move {
1034 let response = client
1035 .request(proto::DeleteProjectEntry {
1036 project_id,
1037 entry_id: entry_id.to_proto(),
1038 })
1039 .await?;
1040 worktree
1041 .update(&mut cx, move |worktree, cx| {
1042 worktree.as_remote_mut().unwrap().delete_entry(
1043 entry_id,
1044 response.worktree_scan_id as usize,
1045 cx,
1046 )
1047 })
1048 .await
1049 }))
1050 }
1051 }
1052
1053 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
1054 if let ProjectClientState::Local { remote_id, .. } = &mut self.client_state {
1055 if remote_id.is_some() {
1056 return Task::ready(Err(anyhow!("project was already shared")));
1057 }
1058
1059 *remote_id = Some(project_id);
1060
1061 let mut worktree_share_tasks = Vec::new();
1062
1063 for open_buffer in self.opened_buffers.values_mut() {
1064 match open_buffer {
1065 OpenBuffer::Strong(_) => {}
1066 OpenBuffer::Weak(buffer) => {
1067 if let Some(buffer) = buffer.upgrade(cx) {
1068 *open_buffer = OpenBuffer::Strong(buffer);
1069 }
1070 }
1071 OpenBuffer::Operations(_) => unreachable!(),
1072 }
1073 }
1074
1075 for worktree_handle in self.worktrees.iter_mut() {
1076 match worktree_handle {
1077 WorktreeHandle::Strong(_) => {}
1078 WorktreeHandle::Weak(worktree) => {
1079 if let Some(worktree) = worktree.upgrade(cx) {
1080 *worktree_handle = WorktreeHandle::Strong(worktree);
1081 }
1082 }
1083 }
1084 }
1085
1086 for (server_id, status) in &self.language_server_statuses {
1087 self.client
1088 .send(proto::StartLanguageServer {
1089 project_id,
1090 server: Some(proto::LanguageServer {
1091 id: *server_id as u64,
1092 name: status.name.clone(),
1093 }),
1094 })
1095 .log_err();
1096 }
1097
1098 for worktree in self.worktrees(cx).collect::<Vec<_>>() {
1099 worktree.update(cx, |worktree, cx| {
1100 let worktree = worktree.as_local_mut().unwrap();
1101 worktree_share_tasks.push(worktree.share(project_id, cx));
1102 });
1103 }
1104
1105 self.client_subscriptions
1106 .push(self.client.add_model_for_remote_entity(project_id, cx));
1107 self.metadata_changed(cx);
1108 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1109 cx.notify();
1110
1111 cx.foreground().spawn(async move {
1112 futures::future::try_join_all(worktree_share_tasks).await?;
1113 Ok(())
1114 })
1115 } else {
1116 Task::ready(Err(anyhow!("can't share a remote project")))
1117 }
1118 }
1119
1120 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1121 if let ProjectClientState::Local { remote_id, .. } = &mut self.client_state {
1122 if let Some(project_id) = remote_id.take() {
1123 self.collaborators.clear();
1124 self.shared_buffers.clear();
1125 self.client_subscriptions.clear();
1126
1127 for worktree_handle in self.worktrees.iter_mut() {
1128 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1129 let is_visible = worktree.update(cx, |worktree, _| {
1130 worktree.as_local_mut().unwrap().unshare();
1131 worktree.is_visible()
1132 });
1133 if !is_visible {
1134 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1135 }
1136 }
1137 }
1138
1139 for open_buffer in self.opened_buffers.values_mut() {
1140 if let OpenBuffer::Strong(buffer) = open_buffer {
1141 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1142 }
1143 }
1144
1145 self.metadata_changed(cx);
1146 cx.notify();
1147 self.client.send(proto::UnshareProject { project_id })?;
1148 }
1149
1150 Ok(())
1151 } else {
1152 Err(anyhow!("attempted to unshare a remote project"))
1153 }
1154 }
1155
1156 fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1157 if let ProjectClientState::Remote {
1158 sharing_has_stopped,
1159 ..
1160 } = &mut self.client_state
1161 {
1162 *sharing_has_stopped = true;
1163 self.collaborators.clear();
1164 for worktree in &self.worktrees {
1165 if let Some(worktree) = worktree.upgrade(cx) {
1166 worktree.update(cx, |worktree, _| {
1167 if let Some(worktree) = worktree.as_remote_mut() {
1168 worktree.disconnected_from_host();
1169 }
1170 });
1171 }
1172 }
1173 cx.emit(Event::DisconnectedFromHost);
1174 cx.notify();
1175
1176 // Wake up all futures currently waiting on a buffer to get opened,
1177 // to give them a chance to fail now that we've disconnected.
1178 *self.opened_buffer.0.borrow_mut() = ();
1179 }
1180 }
1181
1182 pub fn is_read_only(&self) -> bool {
1183 match &self.client_state {
1184 ProjectClientState::Local { .. } => false,
1185 ProjectClientState::Remote {
1186 sharing_has_stopped,
1187 ..
1188 } => *sharing_has_stopped,
1189 }
1190 }
1191
1192 pub fn is_local(&self) -> bool {
1193 match &self.client_state {
1194 ProjectClientState::Local { .. } => true,
1195 ProjectClientState::Remote { .. } => false,
1196 }
1197 }
1198
1199 pub fn is_remote(&self) -> bool {
1200 !self.is_local()
1201 }
1202
1203 pub fn create_buffer(
1204 &mut self,
1205 text: &str,
1206 language: Option<Arc<Language>>,
1207 cx: &mut ModelContext<Self>,
1208 ) -> Result<ModelHandle<Buffer>> {
1209 if self.is_remote() {
1210 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1211 }
1212
1213 let buffer = cx.add_model(|cx| {
1214 Buffer::new(self.replica_id(), text, cx)
1215 .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1216 });
1217 self.register_buffer(&buffer, cx)?;
1218 Ok(buffer)
1219 }
1220
1221 pub fn open_path(
1222 &mut self,
1223 path: impl Into<ProjectPath>,
1224 cx: &mut ModelContext<Self>,
1225 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1226 let task = self.open_buffer(path, cx);
1227 cx.spawn_weak(|_, cx| async move {
1228 let buffer = task.await?;
1229 let project_entry_id = buffer
1230 .read_with(&cx, |buffer, cx| {
1231 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1232 })
1233 .ok_or_else(|| anyhow!("no project entry"))?;
1234 Ok((project_entry_id, buffer.into()))
1235 })
1236 }
1237
1238 pub fn open_local_buffer(
1239 &mut self,
1240 abs_path: impl AsRef<Path>,
1241 cx: &mut ModelContext<Self>,
1242 ) -> Task<Result<ModelHandle<Buffer>>> {
1243 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1244 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1245 } else {
1246 Task::ready(Err(anyhow!("no such path")))
1247 }
1248 }
1249
1250 pub fn open_buffer(
1251 &mut self,
1252 path: impl Into<ProjectPath>,
1253 cx: &mut ModelContext<Self>,
1254 ) -> Task<Result<ModelHandle<Buffer>>> {
1255 let project_path = path.into();
1256 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1257 worktree
1258 } else {
1259 return Task::ready(Err(anyhow!("no such worktree")));
1260 };
1261
1262 // If there is already a buffer for the given path, then return it.
1263 let existing_buffer = self.get_open_buffer(&project_path, cx);
1264 if let Some(existing_buffer) = existing_buffer {
1265 return Task::ready(Ok(existing_buffer));
1266 }
1267
1268 let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1269 // If the given path is already being loaded, then wait for that existing
1270 // task to complete and return the same buffer.
1271 hash_map::Entry::Occupied(e) => e.get().clone(),
1272
1273 // Otherwise, record the fact that this path is now being loaded.
1274 hash_map::Entry::Vacant(entry) => {
1275 let (mut tx, rx) = postage::watch::channel();
1276 entry.insert(rx.clone());
1277
1278 let load_buffer = if worktree.read(cx).is_local() {
1279 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1280 } else {
1281 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1282 };
1283
1284 cx.spawn(move |this, mut cx| async move {
1285 let load_result = load_buffer.await;
1286 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1287 // Record the fact that the buffer is no longer loading.
1288 this.loading_buffers.remove(&project_path);
1289 let buffer = load_result.map_err(Arc::new)?;
1290 Ok(buffer)
1291 }));
1292 })
1293 .detach();
1294 rx
1295 }
1296 };
1297
1298 cx.foreground().spawn(async move {
1299 loop {
1300 if let Some(result) = loading_watch.borrow().as_ref() {
1301 match result {
1302 Ok(buffer) => return Ok(buffer.clone()),
1303 Err(error) => return Err(anyhow!("{}", error)),
1304 }
1305 }
1306 loading_watch.next().await;
1307 }
1308 })
1309 }
1310
1311 fn open_local_buffer_internal(
1312 &mut self,
1313 path: &Arc<Path>,
1314 worktree: &ModelHandle<Worktree>,
1315 cx: &mut ModelContext<Self>,
1316 ) -> Task<Result<ModelHandle<Buffer>>> {
1317 let load_buffer = worktree.update(cx, |worktree, cx| {
1318 let worktree = worktree.as_local_mut().unwrap();
1319 worktree.load_buffer(path, cx)
1320 });
1321 cx.spawn(|this, mut cx| async move {
1322 let buffer = load_buffer.await?;
1323 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1324 Ok(buffer)
1325 })
1326 }
1327
1328 fn open_remote_buffer_internal(
1329 &mut self,
1330 path: &Arc<Path>,
1331 worktree: &ModelHandle<Worktree>,
1332 cx: &mut ModelContext<Self>,
1333 ) -> Task<Result<ModelHandle<Buffer>>> {
1334 let rpc = self.client.clone();
1335 let project_id = self.remote_id().unwrap();
1336 let remote_worktree_id = worktree.read(cx).id();
1337 let path = path.clone();
1338 let path_string = path.to_string_lossy().to_string();
1339 cx.spawn(|this, mut cx| async move {
1340 let response = rpc
1341 .request(proto::OpenBufferByPath {
1342 project_id,
1343 worktree_id: remote_worktree_id.to_proto(),
1344 path: path_string,
1345 })
1346 .await?;
1347 this.update(&mut cx, |this, cx| {
1348 this.wait_for_buffer(response.buffer_id, cx)
1349 })
1350 .await
1351 })
1352 }
1353
1354 /// LanguageServerName is owned, because it is inserted into a map
1355 fn open_local_buffer_via_lsp(
1356 &mut self,
1357 abs_path: lsp::Url,
1358 language_server_id: usize,
1359 language_server_name: LanguageServerName,
1360 cx: &mut ModelContext<Self>,
1361 ) -> Task<Result<ModelHandle<Buffer>>> {
1362 cx.spawn(|this, mut cx| async move {
1363 let abs_path = abs_path
1364 .to_file_path()
1365 .map_err(|_| anyhow!("can't convert URI to path"))?;
1366 let (worktree, relative_path) = if let Some(result) =
1367 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1368 {
1369 result
1370 } else {
1371 let worktree = this
1372 .update(&mut cx, |this, cx| {
1373 this.create_local_worktree(&abs_path, false, cx)
1374 })
1375 .await?;
1376 this.update(&mut cx, |this, cx| {
1377 this.language_server_ids.insert(
1378 (worktree.read(cx).id(), language_server_name),
1379 language_server_id,
1380 );
1381 });
1382 (worktree, PathBuf::new())
1383 };
1384
1385 let project_path = ProjectPath {
1386 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1387 path: relative_path.into(),
1388 };
1389 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1390 .await
1391 })
1392 }
1393
1394 pub fn open_buffer_by_id(
1395 &mut self,
1396 id: u64,
1397 cx: &mut ModelContext<Self>,
1398 ) -> Task<Result<ModelHandle<Buffer>>> {
1399 if let Some(buffer) = self.buffer_for_id(id, cx) {
1400 Task::ready(Ok(buffer))
1401 } else if self.is_local() {
1402 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1403 } else if let Some(project_id) = self.remote_id() {
1404 let request = self
1405 .client
1406 .request(proto::OpenBufferById { project_id, id });
1407 cx.spawn(|this, mut cx| async move {
1408 let buffer_id = request.await?.buffer_id;
1409 this.update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
1410 .await
1411 })
1412 } else {
1413 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1414 }
1415 }
1416
1417 pub fn save_buffer_as(
1418 &mut self,
1419 buffer: ModelHandle<Buffer>,
1420 abs_path: PathBuf,
1421 cx: &mut ModelContext<Project>,
1422 ) -> Task<Result<()>> {
1423 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1424 let old_path =
1425 File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1426 cx.spawn(|this, mut cx| async move {
1427 if let Some(old_path) = old_path {
1428 this.update(&mut cx, |this, cx| {
1429 this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1430 });
1431 }
1432 let (worktree, path) = worktree_task.await?;
1433 worktree
1434 .update(&mut cx, |worktree, cx| {
1435 worktree
1436 .as_local_mut()
1437 .unwrap()
1438 .save_buffer_as(buffer.clone(), path, cx)
1439 })
1440 .await?;
1441 this.update(&mut cx, |this, cx| {
1442 this.assign_language_to_buffer(&buffer, cx);
1443 this.register_buffer_with_language_server(&buffer, cx);
1444 });
1445 Ok(())
1446 })
1447 }
1448
1449 pub fn get_open_buffer(
1450 &mut self,
1451 path: &ProjectPath,
1452 cx: &mut ModelContext<Self>,
1453 ) -> Option<ModelHandle<Buffer>> {
1454 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1455 self.opened_buffers.values().find_map(|buffer| {
1456 let buffer = buffer.upgrade(cx)?;
1457 let file = File::from_dyn(buffer.read(cx).file())?;
1458 if file.worktree == worktree && file.path() == &path.path {
1459 Some(buffer)
1460 } else {
1461 None
1462 }
1463 })
1464 }
1465
1466 fn register_buffer(
1467 &mut self,
1468 buffer: &ModelHandle<Buffer>,
1469 cx: &mut ModelContext<Self>,
1470 ) -> Result<()> {
1471 let remote_id = buffer.read(cx).remote_id();
1472 let open_buffer = if self.is_remote() || self.is_shared() {
1473 OpenBuffer::Strong(buffer.clone())
1474 } else {
1475 OpenBuffer::Weak(buffer.downgrade())
1476 };
1477
1478 match self.opened_buffers.insert(remote_id, open_buffer) {
1479 None => {}
1480 Some(OpenBuffer::Operations(operations)) => {
1481 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1482 }
1483 Some(OpenBuffer::Weak(existing_handle)) => {
1484 if existing_handle.upgrade(cx).is_some() {
1485 Err(anyhow!(
1486 "already registered buffer with remote id {}",
1487 remote_id
1488 ))?
1489 }
1490 }
1491 Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1492 "already registered buffer with remote id {}",
1493 remote_id
1494 ))?,
1495 }
1496 cx.subscribe(buffer, |this, buffer, event, cx| {
1497 this.on_buffer_event(buffer, event, cx);
1498 })
1499 .detach();
1500
1501 self.assign_language_to_buffer(buffer, cx);
1502 self.register_buffer_with_language_server(buffer, cx);
1503 cx.observe_release(buffer, |this, buffer, cx| {
1504 if let Some(file) = File::from_dyn(buffer.file()) {
1505 if file.is_local() {
1506 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1507 if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1508 server
1509 .notify::<lsp::notification::DidCloseTextDocument>(
1510 lsp::DidCloseTextDocumentParams {
1511 text_document: lsp::TextDocumentIdentifier::new(uri),
1512 },
1513 )
1514 .log_err();
1515 }
1516 }
1517 }
1518 })
1519 .detach();
1520
1521 *self.opened_buffer.0.borrow_mut() = ();
1522 Ok(())
1523 }
1524
1525 fn register_buffer_with_language_server(
1526 &mut self,
1527 buffer_handle: &ModelHandle<Buffer>,
1528 cx: &mut ModelContext<Self>,
1529 ) {
1530 let buffer = buffer_handle.read(cx);
1531 let buffer_id = buffer.remote_id();
1532 if let Some(file) = File::from_dyn(buffer.file()) {
1533 if file.is_local() {
1534 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1535 let initial_snapshot = buffer.text_snapshot();
1536
1537 let mut language_server = None;
1538 let mut language_id = None;
1539 if let Some(language) = buffer.language() {
1540 let worktree_id = file.worktree_id(cx);
1541 if let Some(adapter) = language.lsp_adapter() {
1542 language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1543 language_server = self
1544 .language_server_ids
1545 .get(&(worktree_id, adapter.name.clone()))
1546 .and_then(|id| self.language_servers.get(id))
1547 .and_then(|server_state| {
1548 if let LanguageServerState::Running { server, .. } = server_state {
1549 Some(server.clone())
1550 } else {
1551 None
1552 }
1553 });
1554 }
1555 }
1556
1557 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1558 if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1559 self.update_buffer_diagnostics(buffer_handle, diagnostics, None, cx)
1560 .log_err();
1561 }
1562 }
1563
1564 if let Some(server) = language_server {
1565 server
1566 .notify::<lsp::notification::DidOpenTextDocument>(
1567 lsp::DidOpenTextDocumentParams {
1568 text_document: lsp::TextDocumentItem::new(
1569 uri,
1570 language_id.unwrap_or_default(),
1571 0,
1572 initial_snapshot.text(),
1573 ),
1574 },
1575 )
1576 .log_err();
1577 buffer_handle.update(cx, |buffer, cx| {
1578 buffer.set_completion_triggers(
1579 server
1580 .capabilities()
1581 .completion_provider
1582 .as_ref()
1583 .and_then(|provider| provider.trigger_characters.clone())
1584 .unwrap_or_default(),
1585 cx,
1586 )
1587 });
1588 self.buffer_snapshots
1589 .insert(buffer_id, vec![(0, initial_snapshot)]);
1590 }
1591 }
1592 }
1593 }
1594
1595 fn unregister_buffer_from_language_server(
1596 &mut self,
1597 buffer: &ModelHandle<Buffer>,
1598 old_path: PathBuf,
1599 cx: &mut ModelContext<Self>,
1600 ) {
1601 buffer.update(cx, |buffer, cx| {
1602 buffer.update_diagnostics(Default::default(), cx);
1603 self.buffer_snapshots.remove(&buffer.remote_id());
1604 if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1605 language_server
1606 .notify::<lsp::notification::DidCloseTextDocument>(
1607 lsp::DidCloseTextDocumentParams {
1608 text_document: lsp::TextDocumentIdentifier::new(
1609 lsp::Url::from_file_path(old_path).unwrap(),
1610 ),
1611 },
1612 )
1613 .log_err();
1614 }
1615 });
1616 }
1617
1618 fn on_buffer_event(
1619 &mut self,
1620 buffer: ModelHandle<Buffer>,
1621 event: &BufferEvent,
1622 cx: &mut ModelContext<Self>,
1623 ) -> Option<()> {
1624 match event {
1625 BufferEvent::Operation(operation) => {
1626 if let Some(project_id) = self.remote_id() {
1627 let request = self.client.request(proto::UpdateBuffer {
1628 project_id,
1629 buffer_id: buffer.read(cx).remote_id(),
1630 operations: vec![language::proto::serialize_operation(operation)],
1631 });
1632 cx.background().spawn(request).detach_and_log_err(cx);
1633 } else if let Some(project_id) = self.remote_id() {
1634 let _ = self
1635 .client
1636 .send(proto::RegisterProjectActivity { project_id });
1637 }
1638 }
1639 BufferEvent::Edited { .. } => {
1640 let language_server = self
1641 .language_server_for_buffer(buffer.read(cx), cx)
1642 .map(|(_, server)| server.clone())?;
1643 let buffer = buffer.read(cx);
1644 let file = File::from_dyn(buffer.file())?;
1645 let abs_path = file.as_local()?.abs_path(cx);
1646 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1647 let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1648 let (version, prev_snapshot) = buffer_snapshots.last()?;
1649 let next_snapshot = buffer.text_snapshot();
1650 let next_version = version + 1;
1651
1652 let content_changes = buffer
1653 .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1654 .map(|edit| {
1655 let edit_start = edit.new.start.0;
1656 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1657 let new_text = next_snapshot
1658 .text_for_range(edit.new.start.1..edit.new.end.1)
1659 .collect();
1660 lsp::TextDocumentContentChangeEvent {
1661 range: Some(lsp::Range::new(
1662 point_to_lsp(edit_start),
1663 point_to_lsp(edit_end),
1664 )),
1665 range_length: None,
1666 text: new_text,
1667 }
1668 })
1669 .collect();
1670
1671 buffer_snapshots.push((next_version, next_snapshot));
1672
1673 language_server
1674 .notify::<lsp::notification::DidChangeTextDocument>(
1675 lsp::DidChangeTextDocumentParams {
1676 text_document: lsp::VersionedTextDocumentIdentifier::new(
1677 uri,
1678 next_version,
1679 ),
1680 content_changes,
1681 },
1682 )
1683 .log_err();
1684 }
1685 BufferEvent::Saved => {
1686 let file = File::from_dyn(buffer.read(cx).file())?;
1687 let worktree_id = file.worktree_id(cx);
1688 let abs_path = file.as_local()?.abs_path(cx);
1689 let text_document = lsp::TextDocumentIdentifier {
1690 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1691 };
1692
1693 for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1694 server
1695 .notify::<lsp::notification::DidSaveTextDocument>(
1696 lsp::DidSaveTextDocumentParams {
1697 text_document: text_document.clone(),
1698 text: None,
1699 },
1700 )
1701 .log_err();
1702 }
1703
1704 // After saving a buffer, simulate disk-based diagnostics being finished for languages
1705 // that don't support a disk-based progress token.
1706 let (lsp_adapter, language_server) =
1707 self.language_server_for_buffer(buffer.read(cx), cx)?;
1708 if lsp_adapter.disk_based_diagnostics_progress_token.is_none() {
1709 let server_id = language_server.server_id();
1710 self.disk_based_diagnostics_finished(server_id, cx);
1711 self.broadcast_language_server_update(
1712 server_id,
1713 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1714 proto::LspDiskBasedDiagnosticsUpdated {},
1715 ),
1716 );
1717 }
1718 }
1719 _ => {}
1720 }
1721
1722 None
1723 }
1724
1725 fn language_servers_for_worktree(
1726 &self,
1727 worktree_id: WorktreeId,
1728 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
1729 self.language_server_ids
1730 .iter()
1731 .filter_map(move |((language_server_worktree_id, _), id)| {
1732 if *language_server_worktree_id == worktree_id {
1733 if let Some(LanguageServerState::Running {
1734 adapter,
1735 language,
1736 server,
1737 }) = self.language_servers.get(id)
1738 {
1739 return Some((adapter, language, server));
1740 }
1741 }
1742 None
1743 })
1744 }
1745
1746 fn maintain_buffer_languages(
1747 languages: &LanguageRegistry,
1748 cx: &mut ModelContext<Project>,
1749 ) -> Task<()> {
1750 let mut subscription = languages.subscribe();
1751 cx.spawn_weak(|project, mut cx| async move {
1752 while let Some(()) = subscription.next().await {
1753 if let Some(project) = project.upgrade(&cx) {
1754 project.update(&mut cx, |project, cx| {
1755 let mut buffers_without_language = Vec::new();
1756 for buffer in project.opened_buffers.values() {
1757 if let Some(buffer) = buffer.upgrade(cx) {
1758 if buffer.read(cx).language().is_none() {
1759 buffers_without_language.push(buffer);
1760 }
1761 }
1762 }
1763
1764 for buffer in buffers_without_language {
1765 project.assign_language_to_buffer(&buffer, cx);
1766 project.register_buffer_with_language_server(&buffer, cx);
1767 }
1768 });
1769 }
1770 }
1771 })
1772 }
1773
1774 fn assign_language_to_buffer(
1775 &mut self,
1776 buffer: &ModelHandle<Buffer>,
1777 cx: &mut ModelContext<Self>,
1778 ) -> Option<()> {
1779 // If the buffer has a language, set it and start the language server if we haven't already.
1780 let full_path = buffer.read(cx).file()?.full_path(cx);
1781 let language = self.languages.select_language(&full_path)?;
1782 buffer.update(cx, |buffer, cx| {
1783 buffer.set_language_registry(self.languages.clone());
1784 buffer.set_language(Some(language.clone()), cx);
1785 });
1786
1787 let file = File::from_dyn(buffer.read(cx).file())?;
1788 let worktree = file.worktree.read(cx).as_local()?;
1789 let worktree_id = worktree.id();
1790 let worktree_abs_path = worktree.abs_path().clone();
1791 self.start_language_server(worktree_id, worktree_abs_path, language, cx);
1792
1793 None
1794 }
1795
1796 fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
1797 use serde_json::Value;
1798
1799 match (source, target) {
1800 (Value::Object(source), Value::Object(target)) => {
1801 for (key, value) in source {
1802 if let Some(target) = target.get_mut(&key) {
1803 Self::merge_json_value_into(value, target);
1804 } else {
1805 target.insert(key.clone(), value);
1806 }
1807 }
1808 }
1809
1810 (source, target) => *target = source,
1811 }
1812 }
1813
1814 fn start_language_server(
1815 &mut self,
1816 worktree_id: WorktreeId,
1817 worktree_path: Arc<Path>,
1818 language: Arc<Language>,
1819 cx: &mut ModelContext<Self>,
1820 ) {
1821 if !cx
1822 .global::<Settings>()
1823 .enable_language_server(Some(&language.name()))
1824 {
1825 return;
1826 }
1827
1828 let adapter = if let Some(adapter) = language.lsp_adapter() {
1829 adapter
1830 } else {
1831 return;
1832 };
1833 let key = (worktree_id, adapter.name.clone());
1834
1835 let mut initialization_options = adapter.initialization_options.clone();
1836
1837 let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
1838 let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
1839 match (&mut initialization_options, override_options) {
1840 (Some(initialization_options), Some(override_options)) => {
1841 Self::merge_json_value_into(override_options, initialization_options);
1842 }
1843
1844 (None, override_options) => initialization_options = override_options,
1845
1846 _ => {}
1847 }
1848
1849 self.language_server_ids
1850 .entry(key.clone())
1851 .or_insert_with(|| {
1852 let server_id = post_inc(&mut self.next_language_server_id);
1853 let language_server = self.languages.start_language_server(
1854 server_id,
1855 language.clone(),
1856 worktree_path,
1857 self.client.http_client(),
1858 cx,
1859 );
1860 self.language_servers.insert(
1861 server_id,
1862 LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
1863 let language_server = language_server?.await.log_err()?;
1864 let language_server = language_server
1865 .initialize(initialization_options)
1866 .await
1867 .log_err()?;
1868 let this = this.upgrade(&cx)?;
1869
1870 language_server
1871 .on_notification::<lsp::notification::PublishDiagnostics, _>({
1872 let this = this.downgrade();
1873 let adapter = adapter.clone();
1874 move |mut params, cx| {
1875 let this = this;
1876 let adapter = adapter.clone();
1877 cx.spawn(|mut cx| async move {
1878 adapter.process_diagnostics(&mut params).await;
1879 if let Some(this) = this.upgrade(&cx) {
1880 this.update(&mut cx, |this, cx| {
1881 this.update_diagnostics(
1882 server_id,
1883 params,
1884 &adapter.disk_based_diagnostic_sources,
1885 cx,
1886 )
1887 .log_err();
1888 });
1889 }
1890 })
1891 .detach();
1892 }
1893 })
1894 .detach();
1895
1896 language_server
1897 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
1898 let settings = this.read_with(&cx, |this, _| {
1899 this.language_server_settings.clone()
1900 });
1901 move |params, _| {
1902 let settings = settings.lock().clone();
1903 async move {
1904 Ok(params
1905 .items
1906 .into_iter()
1907 .map(|item| {
1908 if let Some(section) = &item.section {
1909 settings
1910 .get(section)
1911 .cloned()
1912 .unwrap_or(serde_json::Value::Null)
1913 } else {
1914 settings.clone()
1915 }
1916 })
1917 .collect())
1918 }
1919 }
1920 })
1921 .detach();
1922
1923 // Even though we don't have handling for these requests, respond to them to
1924 // avoid stalling any language server like `gopls` which waits for a response
1925 // to these requests when initializing.
1926 language_server
1927 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
1928 let this = this.downgrade();
1929 move |params, mut cx| async move {
1930 if let Some(this) = this.upgrade(&cx) {
1931 this.update(&mut cx, |this, _| {
1932 if let Some(status) =
1933 this.language_server_statuses.get_mut(&server_id)
1934 {
1935 if let lsp::NumberOrString::String(token) =
1936 params.token
1937 {
1938 status.progress_tokens.insert(token);
1939 }
1940 }
1941 });
1942 }
1943 Ok(())
1944 }
1945 })
1946 .detach();
1947 language_server
1948 .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
1949 Ok(())
1950 })
1951 .detach();
1952
1953 language_server
1954 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
1955 let this = this.downgrade();
1956 let adapter = adapter.clone();
1957 let language_server = language_server.clone();
1958 move |params, cx| {
1959 Self::on_lsp_workspace_edit(
1960 this,
1961 params,
1962 server_id,
1963 adapter.clone(),
1964 language_server.clone(),
1965 cx,
1966 )
1967 }
1968 })
1969 .detach();
1970
1971 let disk_based_diagnostics_progress_token =
1972 adapter.disk_based_diagnostics_progress_token.clone();
1973
1974 language_server
1975 .on_notification::<lsp::notification::Progress, _>({
1976 let this = this.downgrade();
1977 move |params, mut cx| {
1978 if let Some(this) = this.upgrade(&cx) {
1979 this.update(&mut cx, |this, cx| {
1980 this.on_lsp_progress(
1981 params,
1982 server_id,
1983 disk_based_diagnostics_progress_token.clone(),
1984 cx,
1985 );
1986 });
1987 }
1988 }
1989 })
1990 .detach();
1991
1992 this.update(&mut cx, |this, cx| {
1993 // If the language server for this key doesn't match the server id, don't store the
1994 // server. Which will cause it to be dropped, killing the process
1995 if this
1996 .language_server_ids
1997 .get(&key)
1998 .map(|id| id != &server_id)
1999 .unwrap_or(false)
2000 {
2001 return None;
2002 }
2003
2004 // Update language_servers collection with Running variant of LanguageServerState
2005 // indicating that the server is up and running and ready
2006 this.language_servers.insert(
2007 server_id,
2008 LanguageServerState::Running {
2009 adapter: adapter.clone(),
2010 language,
2011 server: language_server.clone(),
2012 },
2013 );
2014 this.language_server_statuses.insert(
2015 server_id,
2016 LanguageServerStatus {
2017 name: language_server.name().to_string(),
2018 pending_work: Default::default(),
2019 has_pending_diagnostic_updates: false,
2020 progress_tokens: Default::default(),
2021 },
2022 );
2023 language_server
2024 .notify::<lsp::notification::DidChangeConfiguration>(
2025 lsp::DidChangeConfigurationParams {
2026 settings: this.language_server_settings.lock().clone(),
2027 },
2028 )
2029 .ok();
2030
2031 if let Some(project_id) = this.remote_id() {
2032 this.client
2033 .send(proto::StartLanguageServer {
2034 project_id,
2035 server: Some(proto::LanguageServer {
2036 id: server_id as u64,
2037 name: language_server.name().to_string(),
2038 }),
2039 })
2040 .log_err();
2041 }
2042
2043 // Tell the language server about every open buffer in the worktree that matches the language.
2044 for buffer in this.opened_buffers.values() {
2045 if let Some(buffer_handle) = buffer.upgrade(cx) {
2046 let buffer = buffer_handle.read(cx);
2047 let file = if let Some(file) = File::from_dyn(buffer.file()) {
2048 file
2049 } else {
2050 continue;
2051 };
2052 let language = if let Some(language) = buffer.language() {
2053 language
2054 } else {
2055 continue;
2056 };
2057 if file.worktree.read(cx).id() != key.0
2058 || language.lsp_adapter().map(|a| a.name.clone())
2059 != Some(key.1.clone())
2060 {
2061 continue;
2062 }
2063
2064 let file = file.as_local()?;
2065 let versions = this
2066 .buffer_snapshots
2067 .entry(buffer.remote_id())
2068 .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2069 let (version, initial_snapshot) = versions.last().unwrap();
2070 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2071 language_server
2072 .notify::<lsp::notification::DidOpenTextDocument>(
2073 lsp::DidOpenTextDocumentParams {
2074 text_document: lsp::TextDocumentItem::new(
2075 uri,
2076 adapter
2077 .language_ids
2078 .get(language.name().as_ref())
2079 .cloned()
2080 .unwrap_or_default(),
2081 *version,
2082 initial_snapshot.text(),
2083 ),
2084 },
2085 )
2086 .log_err()?;
2087 buffer_handle.update(cx, |buffer, cx| {
2088 buffer.set_completion_triggers(
2089 language_server
2090 .capabilities()
2091 .completion_provider
2092 .as_ref()
2093 .and_then(|provider| {
2094 provider.trigger_characters.clone()
2095 })
2096 .unwrap_or_default(),
2097 cx,
2098 )
2099 });
2100 }
2101 }
2102
2103 cx.notify();
2104 Some(language_server)
2105 })
2106 })),
2107 );
2108
2109 server_id
2110 });
2111 }
2112
2113 // Returns a list of all of the worktrees which no longer have a language server and the root path
2114 // for the stopped server
2115 fn stop_language_server(
2116 &mut self,
2117 worktree_id: WorktreeId,
2118 adapter_name: LanguageServerName,
2119 cx: &mut ModelContext<Self>,
2120 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2121 let key = (worktree_id, adapter_name);
2122 if let Some(server_id) = self.language_server_ids.remove(&key) {
2123 // Remove other entries for this language server as well
2124 let mut orphaned_worktrees = vec![worktree_id];
2125 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2126 for other_key in other_keys {
2127 if self.language_server_ids.get(&other_key) == Some(&server_id) {
2128 self.language_server_ids.remove(&other_key);
2129 orphaned_worktrees.push(other_key.0);
2130 }
2131 }
2132
2133 self.language_server_statuses.remove(&server_id);
2134 cx.notify();
2135
2136 let server_state = self.language_servers.remove(&server_id);
2137 cx.spawn_weak(|this, mut cx| async move {
2138 let mut root_path = None;
2139
2140 let server = match server_state {
2141 Some(LanguageServerState::Starting(started_language_server)) => {
2142 started_language_server.await
2143 }
2144 Some(LanguageServerState::Running { server, .. }) => Some(server),
2145 None => None,
2146 };
2147
2148 if let Some(server) = server {
2149 root_path = Some(server.root_path().clone());
2150 if let Some(shutdown) = server.shutdown() {
2151 shutdown.await;
2152 }
2153 }
2154
2155 if let Some(this) = this.upgrade(&cx) {
2156 this.update(&mut cx, |this, cx| {
2157 this.language_server_statuses.remove(&server_id);
2158 cx.notify();
2159 });
2160 }
2161
2162 (root_path, orphaned_worktrees)
2163 })
2164 } else {
2165 Task::ready((None, Vec::new()))
2166 }
2167 }
2168
2169 pub fn restart_language_servers_for_buffers(
2170 &mut self,
2171 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2172 cx: &mut ModelContext<Self>,
2173 ) -> Option<()> {
2174 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2175 .into_iter()
2176 .filter_map(|buffer| {
2177 let file = File::from_dyn(buffer.read(cx).file())?;
2178 let worktree = file.worktree.read(cx).as_local()?;
2179 let worktree_id = worktree.id();
2180 let worktree_abs_path = worktree.abs_path().clone();
2181 let full_path = file.full_path(cx);
2182 Some((worktree_id, worktree_abs_path, full_path))
2183 })
2184 .collect();
2185 for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2186 let language = self.languages.select_language(&full_path)?;
2187 self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2188 }
2189
2190 None
2191 }
2192
2193 fn restart_language_server(
2194 &mut self,
2195 worktree_id: WorktreeId,
2196 fallback_path: Arc<Path>,
2197 language: Arc<Language>,
2198 cx: &mut ModelContext<Self>,
2199 ) {
2200 let adapter = if let Some(adapter) = language.lsp_adapter() {
2201 adapter
2202 } else {
2203 return;
2204 };
2205
2206 let server_name = adapter.name.clone();
2207 let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2208 cx.spawn_weak(|this, mut cx| async move {
2209 let (original_root_path, orphaned_worktrees) = stop.await;
2210 if let Some(this) = this.upgrade(&cx) {
2211 this.update(&mut cx, |this, cx| {
2212 // Attempt to restart using original server path. Fallback to passed in
2213 // path if we could not retrieve the root path
2214 let root_path = original_root_path
2215 .map(|path_buf| Arc::from(path_buf.as_path()))
2216 .unwrap_or(fallback_path);
2217
2218 this.start_language_server(worktree_id, root_path, language, cx);
2219
2220 // Lookup new server id and set it for each of the orphaned worktrees
2221 if let Some(new_server_id) = this
2222 .language_server_ids
2223 .get(&(worktree_id, server_name.clone()))
2224 .cloned()
2225 {
2226 for orphaned_worktree in orphaned_worktrees {
2227 this.language_server_ids
2228 .insert((orphaned_worktree, server_name.clone()), new_server_id);
2229 }
2230 }
2231 });
2232 }
2233 })
2234 .detach();
2235 }
2236
2237 fn on_lsp_progress(
2238 &mut self,
2239 progress: lsp::ProgressParams,
2240 server_id: usize,
2241 disk_based_diagnostics_progress_token: Option<String>,
2242 cx: &mut ModelContext<Self>,
2243 ) {
2244 let token = match progress.token {
2245 lsp::NumberOrString::String(token) => token,
2246 lsp::NumberOrString::Number(token) => {
2247 log::info!("skipping numeric progress token {}", token);
2248 return;
2249 }
2250 };
2251 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2252 let language_server_status =
2253 if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2254 status
2255 } else {
2256 return;
2257 };
2258
2259 if !language_server_status.progress_tokens.contains(&token) {
2260 return;
2261 }
2262
2263 let is_disk_based_diagnostics_progress =
2264 Some(token.as_ref()) == disk_based_diagnostics_progress_token.as_deref();
2265
2266 match progress {
2267 lsp::WorkDoneProgress::Begin(report) => {
2268 if is_disk_based_diagnostics_progress {
2269 language_server_status.has_pending_diagnostic_updates = true;
2270 self.disk_based_diagnostics_started(server_id, cx);
2271 self.broadcast_language_server_update(
2272 server_id,
2273 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2274 proto::LspDiskBasedDiagnosticsUpdating {},
2275 ),
2276 );
2277 } else {
2278 self.on_lsp_work_start(
2279 server_id,
2280 token.clone(),
2281 LanguageServerProgress {
2282 message: report.message.clone(),
2283 percentage: report.percentage.map(|p| p as usize),
2284 last_update_at: Instant::now(),
2285 },
2286 cx,
2287 );
2288 self.broadcast_language_server_update(
2289 server_id,
2290 proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2291 token,
2292 message: report.message,
2293 percentage: report.percentage.map(|p| p as u32),
2294 }),
2295 );
2296 }
2297 }
2298 lsp::WorkDoneProgress::Report(report) => {
2299 if !is_disk_based_diagnostics_progress {
2300 self.on_lsp_work_progress(
2301 server_id,
2302 token.clone(),
2303 LanguageServerProgress {
2304 message: report.message.clone(),
2305 percentage: report.percentage.map(|p| p as usize),
2306 last_update_at: Instant::now(),
2307 },
2308 cx,
2309 );
2310 self.broadcast_language_server_update(
2311 server_id,
2312 proto::update_language_server::Variant::WorkProgress(
2313 proto::LspWorkProgress {
2314 token,
2315 message: report.message,
2316 percentage: report.percentage.map(|p| p as u32),
2317 },
2318 ),
2319 );
2320 }
2321 }
2322 lsp::WorkDoneProgress::End(_) => {
2323 language_server_status.progress_tokens.remove(&token);
2324
2325 if is_disk_based_diagnostics_progress {
2326 language_server_status.has_pending_diagnostic_updates = false;
2327 self.disk_based_diagnostics_finished(server_id, cx);
2328 self.broadcast_language_server_update(
2329 server_id,
2330 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2331 proto::LspDiskBasedDiagnosticsUpdated {},
2332 ),
2333 );
2334 } else {
2335 self.on_lsp_work_end(server_id, token.clone(), cx);
2336 self.broadcast_language_server_update(
2337 server_id,
2338 proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2339 token,
2340 }),
2341 );
2342 }
2343 }
2344 }
2345 }
2346
2347 fn on_lsp_work_start(
2348 &mut self,
2349 language_server_id: usize,
2350 token: String,
2351 progress: LanguageServerProgress,
2352 cx: &mut ModelContext<Self>,
2353 ) {
2354 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2355 status.pending_work.insert(token, progress);
2356 cx.notify();
2357 }
2358 }
2359
2360 fn on_lsp_work_progress(
2361 &mut self,
2362 language_server_id: usize,
2363 token: String,
2364 progress: LanguageServerProgress,
2365 cx: &mut ModelContext<Self>,
2366 ) {
2367 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2368 let entry = status
2369 .pending_work
2370 .entry(token)
2371 .or_insert(LanguageServerProgress {
2372 message: Default::default(),
2373 percentage: Default::default(),
2374 last_update_at: progress.last_update_at,
2375 });
2376 if progress.message.is_some() {
2377 entry.message = progress.message;
2378 }
2379 if progress.percentage.is_some() {
2380 entry.percentage = progress.percentage;
2381 }
2382 entry.last_update_at = progress.last_update_at;
2383 cx.notify();
2384 }
2385 }
2386
2387 fn on_lsp_work_end(
2388 &mut self,
2389 language_server_id: usize,
2390 token: String,
2391 cx: &mut ModelContext<Self>,
2392 ) {
2393 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2394 status.pending_work.remove(&token);
2395 cx.notify();
2396 }
2397 }
2398
2399 async fn on_lsp_workspace_edit(
2400 this: WeakModelHandle<Self>,
2401 params: lsp::ApplyWorkspaceEditParams,
2402 server_id: usize,
2403 adapter: Arc<CachedLspAdapter>,
2404 language_server: Arc<LanguageServer>,
2405 mut cx: AsyncAppContext,
2406 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2407 let this = this
2408 .upgrade(&cx)
2409 .ok_or_else(|| anyhow!("project project closed"))?;
2410 let transaction = Self::deserialize_workspace_edit(
2411 this.clone(),
2412 params.edit,
2413 true,
2414 adapter.clone(),
2415 language_server.clone(),
2416 &mut cx,
2417 )
2418 .await
2419 .log_err();
2420 this.update(&mut cx, |this, _| {
2421 if let Some(transaction) = transaction {
2422 this.last_workspace_edits_by_language_server
2423 .insert(server_id, transaction);
2424 }
2425 });
2426 Ok(lsp::ApplyWorkspaceEditResponse {
2427 applied: true,
2428 failed_change: None,
2429 failure_reason: None,
2430 })
2431 }
2432
2433 fn broadcast_language_server_update(
2434 &self,
2435 language_server_id: usize,
2436 event: proto::update_language_server::Variant,
2437 ) {
2438 if let Some(project_id) = self.remote_id() {
2439 self.client
2440 .send(proto::UpdateLanguageServer {
2441 project_id,
2442 language_server_id: language_server_id as u64,
2443 variant: Some(event),
2444 })
2445 .log_err();
2446 }
2447 }
2448
2449 pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2450 for server_state in self.language_servers.values() {
2451 if let LanguageServerState::Running { server, .. } = server_state {
2452 server
2453 .notify::<lsp::notification::DidChangeConfiguration>(
2454 lsp::DidChangeConfigurationParams {
2455 settings: settings.clone(),
2456 },
2457 )
2458 .ok();
2459 }
2460 }
2461 *self.language_server_settings.lock() = settings;
2462 }
2463
2464 pub fn language_server_statuses(
2465 &self,
2466 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2467 self.language_server_statuses.values()
2468 }
2469
2470 pub fn update_diagnostics(
2471 &mut self,
2472 language_server_id: usize,
2473 params: lsp::PublishDiagnosticsParams,
2474 disk_based_sources: &[String],
2475 cx: &mut ModelContext<Self>,
2476 ) -> Result<()> {
2477 let abs_path = params
2478 .uri
2479 .to_file_path()
2480 .map_err(|_| anyhow!("URI is not a file"))?;
2481 let mut diagnostics = Vec::default();
2482 let mut primary_diagnostic_group_ids = HashMap::default();
2483 let mut sources_by_group_id = HashMap::default();
2484 let mut supporting_diagnostics = HashMap::default();
2485 for diagnostic in ¶ms.diagnostics {
2486 let source = diagnostic.source.as_ref();
2487 let code = diagnostic.code.as_ref().map(|code| match code {
2488 lsp::NumberOrString::Number(code) => code.to_string(),
2489 lsp::NumberOrString::String(code) => code.clone(),
2490 });
2491 let range = range_from_lsp(diagnostic.range);
2492 let is_supporting = diagnostic
2493 .related_information
2494 .as_ref()
2495 .map_or(false, |infos| {
2496 infos.iter().any(|info| {
2497 primary_diagnostic_group_ids.contains_key(&(
2498 source,
2499 code.clone(),
2500 range_from_lsp(info.location.range),
2501 ))
2502 })
2503 });
2504
2505 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2506 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2507 });
2508
2509 if is_supporting {
2510 supporting_diagnostics.insert(
2511 (source, code.clone(), range),
2512 (diagnostic.severity, is_unnecessary),
2513 );
2514 } else {
2515 let group_id = post_inc(&mut self.next_diagnostic_group_id);
2516 let is_disk_based =
2517 source.map_or(false, |source| disk_based_sources.contains(source));
2518
2519 sources_by_group_id.insert(group_id, source);
2520 primary_diagnostic_group_ids
2521 .insert((source, code.clone(), range.clone()), group_id);
2522
2523 diagnostics.push(DiagnosticEntry {
2524 range,
2525 diagnostic: Diagnostic {
2526 code: code.clone(),
2527 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2528 message: diagnostic.message.clone(),
2529 group_id,
2530 is_primary: true,
2531 is_valid: true,
2532 is_disk_based,
2533 is_unnecessary,
2534 },
2535 });
2536 if let Some(infos) = &diagnostic.related_information {
2537 for info in infos {
2538 if info.location.uri == params.uri && !info.message.is_empty() {
2539 let range = range_from_lsp(info.location.range);
2540 diagnostics.push(DiagnosticEntry {
2541 range,
2542 diagnostic: Diagnostic {
2543 code: code.clone(),
2544 severity: DiagnosticSeverity::INFORMATION,
2545 message: info.message.clone(),
2546 group_id,
2547 is_primary: false,
2548 is_valid: true,
2549 is_disk_based,
2550 is_unnecessary: false,
2551 },
2552 });
2553 }
2554 }
2555 }
2556 }
2557 }
2558
2559 for entry in &mut diagnostics {
2560 let diagnostic = &mut entry.diagnostic;
2561 if !diagnostic.is_primary {
2562 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2563 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2564 source,
2565 diagnostic.code.clone(),
2566 entry.range.clone(),
2567 )) {
2568 if let Some(severity) = severity {
2569 diagnostic.severity = severity;
2570 }
2571 diagnostic.is_unnecessary = is_unnecessary;
2572 }
2573 }
2574 }
2575
2576 self.update_diagnostic_entries(
2577 language_server_id,
2578 abs_path,
2579 params.version,
2580 diagnostics,
2581 cx,
2582 )?;
2583 Ok(())
2584 }
2585
2586 pub fn update_diagnostic_entries(
2587 &mut self,
2588 language_server_id: usize,
2589 abs_path: PathBuf,
2590 version: Option<i32>,
2591 diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2592 cx: &mut ModelContext<Project>,
2593 ) -> Result<(), anyhow::Error> {
2594 let (worktree, relative_path) = self
2595 .find_local_worktree(&abs_path, cx)
2596 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2597
2598 let project_path = ProjectPath {
2599 worktree_id: worktree.read(cx).id(),
2600 path: relative_path.into(),
2601 };
2602 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2603 self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2604 }
2605
2606 let updated = worktree.update(cx, |worktree, cx| {
2607 worktree
2608 .as_local_mut()
2609 .ok_or_else(|| anyhow!("not a local worktree"))?
2610 .update_diagnostics(
2611 language_server_id,
2612 project_path.path.clone(),
2613 diagnostics,
2614 cx,
2615 )
2616 })?;
2617 if updated {
2618 cx.emit(Event::DiagnosticsUpdated {
2619 language_server_id,
2620 path: project_path,
2621 });
2622 }
2623 Ok(())
2624 }
2625
2626 fn update_buffer_diagnostics(
2627 &mut self,
2628 buffer: &ModelHandle<Buffer>,
2629 mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2630 version: Option<i32>,
2631 cx: &mut ModelContext<Self>,
2632 ) -> Result<()> {
2633 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2634 Ordering::Equal
2635 .then_with(|| b.is_primary.cmp(&a.is_primary))
2636 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2637 .then_with(|| a.severity.cmp(&b.severity))
2638 .then_with(|| a.message.cmp(&b.message))
2639 }
2640
2641 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2642
2643 diagnostics.sort_unstable_by(|a, b| {
2644 Ordering::Equal
2645 .then_with(|| a.range.start.cmp(&b.range.start))
2646 .then_with(|| b.range.end.cmp(&a.range.end))
2647 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2648 });
2649
2650 let mut sanitized_diagnostics = Vec::new();
2651 let edits_since_save = Patch::new(
2652 snapshot
2653 .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2654 .collect(),
2655 );
2656 for entry in diagnostics {
2657 let start;
2658 let end;
2659 if entry.diagnostic.is_disk_based {
2660 // Some diagnostics are based on files on disk instead of buffers'
2661 // current contents. Adjust these diagnostics' ranges to reflect
2662 // any unsaved edits.
2663 start = edits_since_save.old_to_new(entry.range.start);
2664 end = edits_since_save.old_to_new(entry.range.end);
2665 } else {
2666 start = entry.range.start;
2667 end = entry.range.end;
2668 }
2669
2670 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2671 ..snapshot.clip_point_utf16(end, Bias::Right);
2672
2673 // Expand empty ranges by one character
2674 if range.start == range.end {
2675 range.end.column += 1;
2676 range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2677 if range.start == range.end && range.end.column > 0 {
2678 range.start.column -= 1;
2679 range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2680 }
2681 }
2682
2683 sanitized_diagnostics.push(DiagnosticEntry {
2684 range,
2685 diagnostic: entry.diagnostic,
2686 });
2687 }
2688 drop(edits_since_save);
2689
2690 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2691 buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2692 Ok(())
2693 }
2694
2695 pub fn reload_buffers(
2696 &self,
2697 buffers: HashSet<ModelHandle<Buffer>>,
2698 push_to_history: bool,
2699 cx: &mut ModelContext<Self>,
2700 ) -> Task<Result<ProjectTransaction>> {
2701 let mut local_buffers = Vec::new();
2702 let mut remote_buffers = None;
2703 for buffer_handle in buffers {
2704 let buffer = buffer_handle.read(cx);
2705 if buffer.is_dirty() {
2706 if let Some(file) = File::from_dyn(buffer.file()) {
2707 if file.is_local() {
2708 local_buffers.push(buffer_handle);
2709 } else {
2710 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2711 }
2712 }
2713 }
2714 }
2715
2716 let remote_buffers = self.remote_id().zip(remote_buffers);
2717 let client = self.client.clone();
2718
2719 cx.spawn(|this, mut cx| async move {
2720 let mut project_transaction = ProjectTransaction::default();
2721
2722 if let Some((project_id, remote_buffers)) = remote_buffers {
2723 let response = client
2724 .request(proto::ReloadBuffers {
2725 project_id,
2726 buffer_ids: remote_buffers
2727 .iter()
2728 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2729 .collect(),
2730 })
2731 .await?
2732 .transaction
2733 .ok_or_else(|| anyhow!("missing transaction"))?;
2734 project_transaction = this
2735 .update(&mut cx, |this, cx| {
2736 this.deserialize_project_transaction(response, push_to_history, cx)
2737 })
2738 .await?;
2739 }
2740
2741 for buffer in local_buffers {
2742 let transaction = buffer
2743 .update(&mut cx, |buffer, cx| buffer.reload(cx))
2744 .await?;
2745 buffer.update(&mut cx, |buffer, cx| {
2746 if let Some(transaction) = transaction {
2747 if !push_to_history {
2748 buffer.forget_transaction(transaction.id);
2749 }
2750 project_transaction.0.insert(cx.handle(), transaction);
2751 }
2752 });
2753 }
2754
2755 Ok(project_transaction)
2756 })
2757 }
2758
2759 pub fn format(
2760 &self,
2761 buffers: HashSet<ModelHandle<Buffer>>,
2762 push_to_history: bool,
2763 trigger: FormatTrigger,
2764 cx: &mut ModelContext<Project>,
2765 ) -> Task<Result<ProjectTransaction>> {
2766 let mut local_buffers = Vec::new();
2767 let mut remote_buffers = None;
2768 for buffer_handle in buffers {
2769 let buffer = buffer_handle.read(cx);
2770 if let Some(file) = File::from_dyn(buffer.file()) {
2771 if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2772 if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2773 local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2774 }
2775 } else {
2776 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2777 }
2778 } else {
2779 return Task::ready(Ok(Default::default()));
2780 }
2781 }
2782
2783 let remote_buffers = self.remote_id().zip(remote_buffers);
2784 let client = self.client.clone();
2785
2786 cx.spawn(|this, mut cx| async move {
2787 let mut project_transaction = ProjectTransaction::default();
2788
2789 if let Some((project_id, remote_buffers)) = remote_buffers {
2790 let response = client
2791 .request(proto::FormatBuffers {
2792 project_id,
2793 trigger: trigger as i32,
2794 buffer_ids: remote_buffers
2795 .iter()
2796 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2797 .collect(),
2798 })
2799 .await?
2800 .transaction
2801 .ok_or_else(|| anyhow!("missing transaction"))?;
2802 project_transaction = this
2803 .update(&mut cx, |this, cx| {
2804 this.deserialize_project_transaction(response, push_to_history, cx)
2805 })
2806 .await?;
2807 }
2808
2809 // Do not allow multiple concurrent formatting requests for the
2810 // same buffer.
2811 this.update(&mut cx, |this, _| {
2812 local_buffers
2813 .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
2814 });
2815 let _cleanup = defer({
2816 let this = this.clone();
2817 let mut cx = cx.clone();
2818 let local_buffers = &local_buffers;
2819 move || {
2820 this.update(&mut cx, |this, _| {
2821 for (buffer, _, _) in local_buffers {
2822 this.buffers_being_formatted.remove(&buffer.id());
2823 }
2824 });
2825 }
2826 });
2827
2828 for (buffer, buffer_abs_path, language_server) in &local_buffers {
2829 let (format_on_save, formatter, tab_size) = buffer.read_with(&cx, |buffer, cx| {
2830 let settings = cx.global::<Settings>();
2831 let language_name = buffer.language().map(|language| language.name());
2832 (
2833 settings.format_on_save(language_name.as_deref()),
2834 settings.formatter(language_name.as_deref()),
2835 settings.tab_size(language_name.as_deref()),
2836 )
2837 });
2838
2839 let transaction = match (formatter, format_on_save) {
2840 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => continue,
2841
2842 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
2843 | (_, FormatOnSave::LanguageServer) => Self::format_via_lsp(
2844 &this,
2845 &buffer,
2846 &buffer_abs_path,
2847 &language_server,
2848 tab_size,
2849 &mut cx,
2850 )
2851 .await
2852 .context("failed to format via language server")?,
2853
2854 (
2855 Formatter::External { command, arguments },
2856 FormatOnSave::On | FormatOnSave::Off,
2857 )
2858 | (_, FormatOnSave::External { command, arguments }) => {
2859 Self::format_via_external_command(
2860 &buffer,
2861 &buffer_abs_path,
2862 &command,
2863 &arguments,
2864 &mut cx,
2865 )
2866 .await
2867 .context(format!(
2868 "failed to format via external command {:?}",
2869 command
2870 ))?
2871 }
2872 };
2873
2874 if let Some(transaction) = transaction {
2875 if !push_to_history {
2876 buffer.update(&mut cx, |buffer, _| {
2877 buffer.forget_transaction(transaction.id)
2878 });
2879 }
2880 project_transaction.0.insert(buffer.clone(), transaction);
2881 }
2882 }
2883
2884 Ok(project_transaction)
2885 })
2886 }
2887
2888 async fn format_via_lsp(
2889 this: &ModelHandle<Self>,
2890 buffer: &ModelHandle<Buffer>,
2891 abs_path: &Path,
2892 language_server: &Arc<LanguageServer>,
2893 tab_size: NonZeroU32,
2894 cx: &mut AsyncAppContext,
2895 ) -> Result<Option<Transaction>> {
2896 let text_document =
2897 lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
2898 let capabilities = &language_server.capabilities();
2899 let lsp_edits = if capabilities
2900 .document_formatting_provider
2901 .as_ref()
2902 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2903 {
2904 language_server
2905 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2906 text_document,
2907 options: lsp::FormattingOptions {
2908 tab_size: tab_size.into(),
2909 insert_spaces: true,
2910 insert_final_newline: Some(true),
2911 ..Default::default()
2912 },
2913 work_done_progress_params: Default::default(),
2914 })
2915 .await?
2916 } else if capabilities
2917 .document_range_formatting_provider
2918 .as_ref()
2919 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2920 {
2921 let buffer_start = lsp::Position::new(0, 0);
2922 let buffer_end =
2923 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
2924 language_server
2925 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
2926 text_document,
2927 range: lsp::Range::new(buffer_start, buffer_end),
2928 options: lsp::FormattingOptions {
2929 tab_size: tab_size.into(),
2930 insert_spaces: true,
2931 insert_final_newline: Some(true),
2932 ..Default::default()
2933 },
2934 work_done_progress_params: Default::default(),
2935 })
2936 .await?
2937 } else {
2938 None
2939 };
2940
2941 if let Some(lsp_edits) = lsp_edits {
2942 let edits = this
2943 .update(cx, |this, cx| {
2944 this.edits_from_lsp(buffer, lsp_edits, None, cx)
2945 })
2946 .await?;
2947 buffer.update(cx, |buffer, cx| {
2948 buffer.finalize_last_transaction();
2949 buffer.start_transaction();
2950 for (range, text) in edits {
2951 buffer.edit([(range, text)], None, cx);
2952 }
2953 if buffer.end_transaction(cx).is_some() {
2954 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2955 Ok(Some(transaction))
2956 } else {
2957 Ok(None)
2958 }
2959 })
2960 } else {
2961 Ok(None)
2962 }
2963 }
2964
2965 async fn format_via_external_command(
2966 buffer: &ModelHandle<Buffer>,
2967 buffer_abs_path: &Path,
2968 command: &str,
2969 arguments: &[String],
2970 cx: &mut AsyncAppContext,
2971 ) -> Result<Option<Transaction>> {
2972 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
2973 let file = File::from_dyn(buffer.file())?;
2974 let worktree = file.worktree.read(cx).as_local()?;
2975 let mut worktree_path = worktree.abs_path().to_path_buf();
2976 if worktree.root_entry()?.is_file() {
2977 worktree_path.pop();
2978 }
2979 Some(worktree_path)
2980 });
2981
2982 if let Some(working_dir_path) = working_dir_path {
2983 let mut child =
2984 smol::process::Command::new(command)
2985 .args(arguments.iter().map(|arg| {
2986 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
2987 }))
2988 .current_dir(&working_dir_path)
2989 .stdin(smol::process::Stdio::piped())
2990 .stdout(smol::process::Stdio::piped())
2991 .stderr(smol::process::Stdio::piped())
2992 .spawn()?;
2993 let stdin = child
2994 .stdin
2995 .as_mut()
2996 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
2997 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
2998 for chunk in text.chunks() {
2999 stdin.write_all(chunk.as_bytes()).await?;
3000 }
3001 stdin.flush().await?;
3002
3003 let output = child.output().await?;
3004 if !output.status.success() {
3005 return Err(anyhow!(
3006 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3007 output.status.code(),
3008 String::from_utf8_lossy(&output.stdout),
3009 String::from_utf8_lossy(&output.stderr),
3010 ));
3011 }
3012
3013 let stdout = String::from_utf8(output.stdout)?;
3014 let diff = buffer
3015 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3016 .await;
3017 Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3018 } else {
3019 Ok(None)
3020 }
3021 }
3022
3023 pub fn definition<T: ToPointUtf16>(
3024 &self,
3025 buffer: &ModelHandle<Buffer>,
3026 position: T,
3027 cx: &mut ModelContext<Self>,
3028 ) -> Task<Result<Vec<LocationLink>>> {
3029 let position = position.to_point_utf16(buffer.read(cx));
3030 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3031 }
3032
3033 pub fn type_definition<T: ToPointUtf16>(
3034 &self,
3035 buffer: &ModelHandle<Buffer>,
3036 position: T,
3037 cx: &mut ModelContext<Self>,
3038 ) -> Task<Result<Vec<LocationLink>>> {
3039 let position = position.to_point_utf16(buffer.read(cx));
3040 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3041 }
3042
3043 pub fn references<T: ToPointUtf16>(
3044 &self,
3045 buffer: &ModelHandle<Buffer>,
3046 position: T,
3047 cx: &mut ModelContext<Self>,
3048 ) -> Task<Result<Vec<Location>>> {
3049 let position = position.to_point_utf16(buffer.read(cx));
3050 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3051 }
3052
3053 pub fn document_highlights<T: ToPointUtf16>(
3054 &self,
3055 buffer: &ModelHandle<Buffer>,
3056 position: T,
3057 cx: &mut ModelContext<Self>,
3058 ) -> Task<Result<Vec<DocumentHighlight>>> {
3059 let position = position.to_point_utf16(buffer.read(cx));
3060 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3061 }
3062
3063 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3064 if self.is_local() {
3065 let mut requests = Vec::new();
3066 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3067 let worktree_id = *worktree_id;
3068 if let Some(worktree) = self
3069 .worktree_for_id(worktree_id, cx)
3070 .and_then(|worktree| worktree.read(cx).as_local())
3071 {
3072 if let Some(LanguageServerState::Running {
3073 adapter,
3074 language,
3075 server,
3076 }) = self.language_servers.get(server_id)
3077 {
3078 let adapter = adapter.clone();
3079 let language = language.clone();
3080 let worktree_abs_path = worktree.abs_path().clone();
3081 requests.push(
3082 server
3083 .request::<lsp::request::WorkspaceSymbol>(
3084 lsp::WorkspaceSymbolParams {
3085 query: query.to_string(),
3086 ..Default::default()
3087 },
3088 )
3089 .log_err()
3090 .map(move |response| {
3091 (
3092 adapter,
3093 language,
3094 worktree_id,
3095 worktree_abs_path,
3096 response.unwrap_or_default(),
3097 )
3098 }),
3099 );
3100 }
3101 }
3102 }
3103
3104 cx.spawn_weak(|this, cx| async move {
3105 let responses = futures::future::join_all(requests).await;
3106 let this = if let Some(this) = this.upgrade(&cx) {
3107 this
3108 } else {
3109 return Ok(Default::default());
3110 };
3111 let symbols = this.read_with(&cx, |this, cx| {
3112 let mut symbols = Vec::new();
3113 for (
3114 adapter,
3115 adapter_language,
3116 source_worktree_id,
3117 worktree_abs_path,
3118 response,
3119 ) in responses
3120 {
3121 symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3122 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3123 let mut worktree_id = source_worktree_id;
3124 let path;
3125 if let Some((worktree, rel_path)) =
3126 this.find_local_worktree(&abs_path, cx)
3127 {
3128 worktree_id = worktree.read(cx).id();
3129 path = rel_path;
3130 } else {
3131 path = relativize_path(&worktree_abs_path, &abs_path);
3132 }
3133
3134 let project_path = ProjectPath {
3135 worktree_id,
3136 path: path.into(),
3137 };
3138 let signature = this.symbol_signature(&project_path);
3139 let language = this
3140 .languages
3141 .select_language(&project_path.path)
3142 .unwrap_or(adapter_language.clone());
3143 let language_server_name = adapter.name.clone();
3144 Some(async move {
3145 let label = language
3146 .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3147 .await;
3148
3149 Symbol {
3150 language_server_name,
3151 source_worktree_id,
3152 path: project_path,
3153 label: label.unwrap_or_else(|| {
3154 CodeLabel::plain(lsp_symbol.name.clone(), None)
3155 }),
3156 kind: lsp_symbol.kind,
3157 name: lsp_symbol.name,
3158 range: range_from_lsp(lsp_symbol.location.range),
3159 signature,
3160 }
3161 })
3162 }));
3163 }
3164 symbols
3165 });
3166 Ok(futures::future::join_all(symbols).await)
3167 })
3168 } else if let Some(project_id) = self.remote_id() {
3169 let request = self.client.request(proto::GetProjectSymbols {
3170 project_id,
3171 query: query.to_string(),
3172 });
3173 cx.spawn_weak(|this, cx| async move {
3174 let response = request.await?;
3175 let mut symbols = Vec::new();
3176 if let Some(this) = this.upgrade(&cx) {
3177 let new_symbols = this.read_with(&cx, |this, _| {
3178 response
3179 .symbols
3180 .into_iter()
3181 .map(|symbol| this.deserialize_symbol(symbol))
3182 .collect::<Vec<_>>()
3183 });
3184 symbols = futures::future::join_all(new_symbols)
3185 .await
3186 .into_iter()
3187 .filter_map(|symbol| symbol.log_err())
3188 .collect::<Vec<_>>();
3189 }
3190 Ok(symbols)
3191 })
3192 } else {
3193 Task::ready(Ok(Default::default()))
3194 }
3195 }
3196
3197 pub fn open_buffer_for_symbol(
3198 &mut self,
3199 symbol: &Symbol,
3200 cx: &mut ModelContext<Self>,
3201 ) -> Task<Result<ModelHandle<Buffer>>> {
3202 if self.is_local() {
3203 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3204 symbol.source_worktree_id,
3205 symbol.language_server_name.clone(),
3206 )) {
3207 *id
3208 } else {
3209 return Task::ready(Err(anyhow!(
3210 "language server for worktree and language not found"
3211 )));
3212 };
3213
3214 let worktree_abs_path = if let Some(worktree_abs_path) = self
3215 .worktree_for_id(symbol.path.worktree_id, cx)
3216 .and_then(|worktree| worktree.read(cx).as_local())
3217 .map(|local_worktree| local_worktree.abs_path())
3218 {
3219 worktree_abs_path
3220 } else {
3221 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3222 };
3223 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3224 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3225 uri
3226 } else {
3227 return Task::ready(Err(anyhow!("invalid symbol path")));
3228 };
3229
3230 self.open_local_buffer_via_lsp(
3231 symbol_uri,
3232 language_server_id,
3233 symbol.language_server_name.clone(),
3234 cx,
3235 )
3236 } else if let Some(project_id) = self.remote_id() {
3237 let request = self.client.request(proto::OpenBufferForSymbol {
3238 project_id,
3239 symbol: Some(serialize_symbol(symbol)),
3240 });
3241 cx.spawn(|this, mut cx| async move {
3242 let response = request.await?;
3243 this.update(&mut cx, |this, cx| {
3244 this.wait_for_buffer(response.buffer_id, cx)
3245 })
3246 .await
3247 })
3248 } else {
3249 Task::ready(Err(anyhow!("project does not have a remote id")))
3250 }
3251 }
3252
3253 pub fn hover<T: ToPointUtf16>(
3254 &self,
3255 buffer: &ModelHandle<Buffer>,
3256 position: T,
3257 cx: &mut ModelContext<Self>,
3258 ) -> Task<Result<Option<Hover>>> {
3259 let position = position.to_point_utf16(buffer.read(cx));
3260 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3261 }
3262
3263 pub fn completions<T: ToPointUtf16>(
3264 &self,
3265 source_buffer_handle: &ModelHandle<Buffer>,
3266 position: T,
3267 cx: &mut ModelContext<Self>,
3268 ) -> Task<Result<Vec<Completion>>> {
3269 let source_buffer_handle = source_buffer_handle.clone();
3270 let source_buffer = source_buffer_handle.read(cx);
3271 let buffer_id = source_buffer.remote_id();
3272 let language = source_buffer.language().cloned();
3273 let worktree;
3274 let buffer_abs_path;
3275 if let Some(file) = File::from_dyn(source_buffer.file()) {
3276 worktree = file.worktree.clone();
3277 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3278 } else {
3279 return Task::ready(Ok(Default::default()));
3280 };
3281
3282 let position = position.to_point_utf16(source_buffer);
3283 let anchor = source_buffer.anchor_after(position);
3284
3285 if worktree.read(cx).as_local().is_some() {
3286 let buffer_abs_path = buffer_abs_path.unwrap();
3287 let lang_server =
3288 if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3289 server.clone()
3290 } else {
3291 return Task::ready(Ok(Default::default()));
3292 };
3293
3294 cx.spawn(|_, cx| async move {
3295 let completions = lang_server
3296 .request::<lsp::request::Completion>(lsp::CompletionParams {
3297 text_document_position: lsp::TextDocumentPositionParams::new(
3298 lsp::TextDocumentIdentifier::new(
3299 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3300 ),
3301 point_to_lsp(position),
3302 ),
3303 context: Default::default(),
3304 work_done_progress_params: Default::default(),
3305 partial_result_params: Default::default(),
3306 })
3307 .await
3308 .context("lsp completion request failed")?;
3309
3310 let completions = if let Some(completions) = completions {
3311 match completions {
3312 lsp::CompletionResponse::Array(completions) => completions,
3313 lsp::CompletionResponse::List(list) => list.items,
3314 }
3315 } else {
3316 Default::default()
3317 };
3318
3319 let completions = source_buffer_handle.read_with(&cx, |this, _| {
3320 let snapshot = this.snapshot();
3321 let clipped_position = this.clip_point_utf16(position, Bias::Left);
3322 let mut range_for_token = None;
3323 completions.into_iter().filter_map(move |lsp_completion| {
3324 // For now, we can only handle additional edits if they are returned
3325 // when resolving the completion, not if they are present initially.
3326 if lsp_completion
3327 .additional_text_edits
3328 .as_ref()
3329 .map_or(false, |edits| !edits.is_empty())
3330 {
3331 return None;
3332 }
3333
3334 let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref() {
3335 // If the language server provides a range to overwrite, then
3336 // check that the range is valid.
3337 Some(lsp::CompletionTextEdit::Edit(edit)) => {
3338 let range = range_from_lsp(edit.range);
3339 let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3340 let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3341 if start != range.start || end != range.end {
3342 log::info!("completion out of expected range");
3343 return None;
3344 }
3345 (
3346 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3347 edit.new_text.clone(),
3348 )
3349 }
3350 // If the language server does not provide a range, then infer
3351 // the range based on the syntax tree.
3352 None => {
3353 if position != clipped_position {
3354 log::info!("completion out of expected range");
3355 return None;
3356 }
3357 let Range { start, end } = range_for_token
3358 .get_or_insert_with(|| {
3359 let offset = position.to_offset(&snapshot);
3360 let (range, kind) = snapshot.surrounding_word(offset);
3361 if kind == Some(CharKind::Word) {
3362 range
3363 } else {
3364 offset..offset
3365 }
3366 })
3367 .clone();
3368 let text = lsp_completion
3369 .insert_text
3370 .as_ref()
3371 .unwrap_or(&lsp_completion.label)
3372 .clone();
3373 (
3374 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3375 text,
3376 )
3377 }
3378 Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3379 log::info!("unsupported insert/replace completion");
3380 return None;
3381 }
3382 };
3383
3384 LineEnding::normalize(&mut new_text);
3385 let language = language.clone();
3386 Some(async move {
3387 let label = if let Some(language) = language {
3388 language.label_for_completion(&lsp_completion).await
3389 } else {
3390 None
3391 };
3392 Completion {
3393 old_range,
3394 new_text,
3395 label: label.unwrap_or_else(|| {
3396 CodeLabel::plain(
3397 lsp_completion.label.clone(),
3398 lsp_completion.filter_text.as_deref(),
3399 )
3400 }),
3401 lsp_completion,
3402 }
3403 })
3404 })
3405 });
3406
3407 Ok(futures::future::join_all(completions).await)
3408 })
3409 } else if let Some(project_id) = self.remote_id() {
3410 let rpc = self.client.clone();
3411 let message = proto::GetCompletions {
3412 project_id,
3413 buffer_id,
3414 position: Some(language::proto::serialize_anchor(&anchor)),
3415 version: serialize_version(&source_buffer.version()),
3416 };
3417 cx.spawn_weak(|_, mut cx| async move {
3418 let response = rpc.request(message).await?;
3419
3420 source_buffer_handle
3421 .update(&mut cx, |buffer, _| {
3422 buffer.wait_for_version(deserialize_version(response.version))
3423 })
3424 .await;
3425
3426 let completions = response.completions.into_iter().map(|completion| {
3427 language::proto::deserialize_completion(completion, language.clone())
3428 });
3429 futures::future::try_join_all(completions).await
3430 })
3431 } else {
3432 Task::ready(Ok(Default::default()))
3433 }
3434 }
3435
3436 pub fn apply_additional_edits_for_completion(
3437 &self,
3438 buffer_handle: ModelHandle<Buffer>,
3439 completion: Completion,
3440 push_to_history: bool,
3441 cx: &mut ModelContext<Self>,
3442 ) -> Task<Result<Option<Transaction>>> {
3443 let buffer = buffer_handle.read(cx);
3444 let buffer_id = buffer.remote_id();
3445
3446 if self.is_local() {
3447 let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3448 {
3449 server.clone()
3450 } else {
3451 return Task::ready(Ok(Default::default()));
3452 };
3453
3454 cx.spawn(|this, mut cx| async move {
3455 let resolved_completion = lang_server
3456 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3457 .await?;
3458 if let Some(edits) = resolved_completion.additional_text_edits {
3459 let edits = this
3460 .update(&mut cx, |this, cx| {
3461 this.edits_from_lsp(&buffer_handle, edits, None, cx)
3462 })
3463 .await?;
3464 buffer_handle.update(&mut cx, |buffer, cx| {
3465 buffer.finalize_last_transaction();
3466 buffer.start_transaction();
3467 for (range, text) in edits {
3468 buffer.edit([(range, text)], None, cx);
3469 }
3470 let transaction = if buffer.end_transaction(cx).is_some() {
3471 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3472 if !push_to_history {
3473 buffer.forget_transaction(transaction.id);
3474 }
3475 Some(transaction)
3476 } else {
3477 None
3478 };
3479 Ok(transaction)
3480 })
3481 } else {
3482 Ok(None)
3483 }
3484 })
3485 } else if let Some(project_id) = self.remote_id() {
3486 let client = self.client.clone();
3487 cx.spawn(|_, mut cx| async move {
3488 let response = client
3489 .request(proto::ApplyCompletionAdditionalEdits {
3490 project_id,
3491 buffer_id,
3492 completion: Some(language::proto::serialize_completion(&completion)),
3493 })
3494 .await?;
3495
3496 if let Some(transaction) = response.transaction {
3497 let transaction = language::proto::deserialize_transaction(transaction)?;
3498 buffer_handle
3499 .update(&mut cx, |buffer, _| {
3500 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3501 })
3502 .await;
3503 if push_to_history {
3504 buffer_handle.update(&mut cx, |buffer, _| {
3505 buffer.push_transaction(transaction.clone(), Instant::now());
3506 });
3507 }
3508 Ok(Some(transaction))
3509 } else {
3510 Ok(None)
3511 }
3512 })
3513 } else {
3514 Task::ready(Err(anyhow!("project does not have a remote id")))
3515 }
3516 }
3517
3518 pub fn code_actions<T: Clone + ToOffset>(
3519 &self,
3520 buffer_handle: &ModelHandle<Buffer>,
3521 range: Range<T>,
3522 cx: &mut ModelContext<Self>,
3523 ) -> Task<Result<Vec<CodeAction>>> {
3524 let buffer_handle = buffer_handle.clone();
3525 let buffer = buffer_handle.read(cx);
3526 let snapshot = buffer.snapshot();
3527 let relevant_diagnostics = snapshot
3528 .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3529 .map(|entry| entry.to_lsp_diagnostic_stub())
3530 .collect();
3531 let buffer_id = buffer.remote_id();
3532 let worktree;
3533 let buffer_abs_path;
3534 if let Some(file) = File::from_dyn(buffer.file()) {
3535 worktree = file.worktree.clone();
3536 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3537 } else {
3538 return Task::ready(Ok(Default::default()));
3539 };
3540 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3541
3542 if worktree.read(cx).as_local().is_some() {
3543 let buffer_abs_path = buffer_abs_path.unwrap();
3544 let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3545 {
3546 server.clone()
3547 } else {
3548 return Task::ready(Ok(Default::default()));
3549 };
3550
3551 let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3552 cx.foreground().spawn(async move {
3553 if lang_server.capabilities().code_action_provider.is_none() {
3554 return Ok(Default::default());
3555 }
3556
3557 Ok(lang_server
3558 .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3559 text_document: lsp::TextDocumentIdentifier::new(
3560 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3561 ),
3562 range: lsp_range,
3563 work_done_progress_params: Default::default(),
3564 partial_result_params: Default::default(),
3565 context: lsp::CodeActionContext {
3566 diagnostics: relevant_diagnostics,
3567 only: Some(vec![
3568 lsp::CodeActionKind::QUICKFIX,
3569 lsp::CodeActionKind::REFACTOR,
3570 lsp::CodeActionKind::REFACTOR_EXTRACT,
3571 lsp::CodeActionKind::SOURCE,
3572 ]),
3573 },
3574 })
3575 .await?
3576 .unwrap_or_default()
3577 .into_iter()
3578 .filter_map(|entry| {
3579 if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3580 Some(CodeAction {
3581 range: range.clone(),
3582 lsp_action,
3583 })
3584 } else {
3585 None
3586 }
3587 })
3588 .collect())
3589 })
3590 } else if let Some(project_id) = self.remote_id() {
3591 let rpc = self.client.clone();
3592 let version = buffer.version();
3593 cx.spawn_weak(|_, mut cx| async move {
3594 let response = rpc
3595 .request(proto::GetCodeActions {
3596 project_id,
3597 buffer_id,
3598 start: Some(language::proto::serialize_anchor(&range.start)),
3599 end: Some(language::proto::serialize_anchor(&range.end)),
3600 version: serialize_version(&version),
3601 })
3602 .await?;
3603
3604 buffer_handle
3605 .update(&mut cx, |buffer, _| {
3606 buffer.wait_for_version(deserialize_version(response.version))
3607 })
3608 .await;
3609
3610 response
3611 .actions
3612 .into_iter()
3613 .map(language::proto::deserialize_code_action)
3614 .collect()
3615 })
3616 } else {
3617 Task::ready(Ok(Default::default()))
3618 }
3619 }
3620
3621 pub fn apply_code_action(
3622 &self,
3623 buffer_handle: ModelHandle<Buffer>,
3624 mut action: CodeAction,
3625 push_to_history: bool,
3626 cx: &mut ModelContext<Self>,
3627 ) -> Task<Result<ProjectTransaction>> {
3628 if self.is_local() {
3629 let buffer = buffer_handle.read(cx);
3630 let (lsp_adapter, lang_server) =
3631 if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3632 (adapter.clone(), server.clone())
3633 } else {
3634 return Task::ready(Ok(Default::default()));
3635 };
3636 let range = action.range.to_point_utf16(buffer);
3637
3638 cx.spawn(|this, mut cx| async move {
3639 if let Some(lsp_range) = action
3640 .lsp_action
3641 .data
3642 .as_mut()
3643 .and_then(|d| d.get_mut("codeActionParams"))
3644 .and_then(|d| d.get_mut("range"))
3645 {
3646 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3647 action.lsp_action = lang_server
3648 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3649 .await?;
3650 } else {
3651 let actions = this
3652 .update(&mut cx, |this, cx| {
3653 this.code_actions(&buffer_handle, action.range, cx)
3654 })
3655 .await?;
3656 action.lsp_action = actions
3657 .into_iter()
3658 .find(|a| a.lsp_action.title == action.lsp_action.title)
3659 .ok_or_else(|| anyhow!("code action is outdated"))?
3660 .lsp_action;
3661 }
3662
3663 if let Some(edit) = action.lsp_action.edit {
3664 if edit.changes.is_some() || edit.document_changes.is_some() {
3665 return Self::deserialize_workspace_edit(
3666 this,
3667 edit,
3668 push_to_history,
3669 lsp_adapter.clone(),
3670 lang_server.clone(),
3671 &mut cx,
3672 )
3673 .await;
3674 }
3675 }
3676
3677 if let Some(command) = action.lsp_action.command {
3678 this.update(&mut cx, |this, _| {
3679 this.last_workspace_edits_by_language_server
3680 .remove(&lang_server.server_id());
3681 });
3682 lang_server
3683 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3684 command: command.command,
3685 arguments: command.arguments.unwrap_or_default(),
3686 ..Default::default()
3687 })
3688 .await?;
3689 return Ok(this.update(&mut cx, |this, _| {
3690 this.last_workspace_edits_by_language_server
3691 .remove(&lang_server.server_id())
3692 .unwrap_or_default()
3693 }));
3694 }
3695
3696 Ok(ProjectTransaction::default())
3697 })
3698 } else if let Some(project_id) = self.remote_id() {
3699 let client = self.client.clone();
3700 let request = proto::ApplyCodeAction {
3701 project_id,
3702 buffer_id: buffer_handle.read(cx).remote_id(),
3703 action: Some(language::proto::serialize_code_action(&action)),
3704 };
3705 cx.spawn(|this, mut cx| async move {
3706 let response = client
3707 .request(request)
3708 .await?
3709 .transaction
3710 .ok_or_else(|| anyhow!("missing transaction"))?;
3711 this.update(&mut cx, |this, cx| {
3712 this.deserialize_project_transaction(response, push_to_history, cx)
3713 })
3714 .await
3715 })
3716 } else {
3717 Task::ready(Err(anyhow!("project does not have a remote id")))
3718 }
3719 }
3720
3721 async fn deserialize_workspace_edit(
3722 this: ModelHandle<Self>,
3723 edit: lsp::WorkspaceEdit,
3724 push_to_history: bool,
3725 lsp_adapter: Arc<CachedLspAdapter>,
3726 language_server: Arc<LanguageServer>,
3727 cx: &mut AsyncAppContext,
3728 ) -> Result<ProjectTransaction> {
3729 let fs = this.read_with(cx, |this, _| this.fs.clone());
3730 let mut operations = Vec::new();
3731 if let Some(document_changes) = edit.document_changes {
3732 match document_changes {
3733 lsp::DocumentChanges::Edits(edits) => {
3734 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3735 }
3736 lsp::DocumentChanges::Operations(ops) => operations = ops,
3737 }
3738 } else if let Some(changes) = edit.changes {
3739 operations.extend(changes.into_iter().map(|(uri, edits)| {
3740 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3741 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3742 uri,
3743 version: None,
3744 },
3745 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3746 })
3747 }));
3748 }
3749
3750 let mut project_transaction = ProjectTransaction::default();
3751 for operation in operations {
3752 match operation {
3753 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3754 let abs_path = op
3755 .uri
3756 .to_file_path()
3757 .map_err(|_| anyhow!("can't convert URI to path"))?;
3758
3759 if let Some(parent_path) = abs_path.parent() {
3760 fs.create_dir(parent_path).await?;
3761 }
3762 if abs_path.ends_with("/") {
3763 fs.create_dir(&abs_path).await?;
3764 } else {
3765 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3766 .await?;
3767 }
3768 }
3769 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3770 let source_abs_path = op
3771 .old_uri
3772 .to_file_path()
3773 .map_err(|_| anyhow!("can't convert URI to path"))?;
3774 let target_abs_path = op
3775 .new_uri
3776 .to_file_path()
3777 .map_err(|_| anyhow!("can't convert URI to path"))?;
3778 fs.rename(
3779 &source_abs_path,
3780 &target_abs_path,
3781 op.options.map(Into::into).unwrap_or_default(),
3782 )
3783 .await?;
3784 }
3785 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3786 let abs_path = op
3787 .uri
3788 .to_file_path()
3789 .map_err(|_| anyhow!("can't convert URI to path"))?;
3790 let options = op.options.map(Into::into).unwrap_or_default();
3791 if abs_path.ends_with("/") {
3792 fs.remove_dir(&abs_path, options).await?;
3793 } else {
3794 fs.remove_file(&abs_path, options).await?;
3795 }
3796 }
3797 lsp::DocumentChangeOperation::Edit(op) => {
3798 let buffer_to_edit = this
3799 .update(cx, |this, cx| {
3800 this.open_local_buffer_via_lsp(
3801 op.text_document.uri,
3802 language_server.server_id(),
3803 lsp_adapter.name.clone(),
3804 cx,
3805 )
3806 })
3807 .await?;
3808
3809 let edits = this
3810 .update(cx, |this, cx| {
3811 let edits = op.edits.into_iter().map(|edit| match edit {
3812 lsp::OneOf::Left(edit) => edit,
3813 lsp::OneOf::Right(edit) => edit.text_edit,
3814 });
3815 this.edits_from_lsp(
3816 &buffer_to_edit,
3817 edits,
3818 op.text_document.version,
3819 cx,
3820 )
3821 })
3822 .await?;
3823
3824 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3825 buffer.finalize_last_transaction();
3826 buffer.start_transaction();
3827 for (range, text) in edits {
3828 buffer.edit([(range, text)], None, cx);
3829 }
3830 let transaction = if buffer.end_transaction(cx).is_some() {
3831 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3832 if !push_to_history {
3833 buffer.forget_transaction(transaction.id);
3834 }
3835 Some(transaction)
3836 } else {
3837 None
3838 };
3839
3840 transaction
3841 });
3842 if let Some(transaction) = transaction {
3843 project_transaction.0.insert(buffer_to_edit, transaction);
3844 }
3845 }
3846 }
3847 }
3848
3849 Ok(project_transaction)
3850 }
3851
3852 pub fn prepare_rename<T: ToPointUtf16>(
3853 &self,
3854 buffer: ModelHandle<Buffer>,
3855 position: T,
3856 cx: &mut ModelContext<Self>,
3857 ) -> Task<Result<Option<Range<Anchor>>>> {
3858 let position = position.to_point_utf16(buffer.read(cx));
3859 self.request_lsp(buffer, PrepareRename { position }, cx)
3860 }
3861
3862 pub fn perform_rename<T: ToPointUtf16>(
3863 &self,
3864 buffer: ModelHandle<Buffer>,
3865 position: T,
3866 new_name: String,
3867 push_to_history: bool,
3868 cx: &mut ModelContext<Self>,
3869 ) -> Task<Result<ProjectTransaction>> {
3870 let position = position.to_point_utf16(buffer.read(cx));
3871 self.request_lsp(
3872 buffer,
3873 PerformRename {
3874 position,
3875 new_name,
3876 push_to_history,
3877 },
3878 cx,
3879 )
3880 }
3881
3882 #[allow(clippy::type_complexity)]
3883 pub fn search(
3884 &self,
3885 query: SearchQuery,
3886 cx: &mut ModelContext<Self>,
3887 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
3888 if self.is_local() {
3889 let snapshots = self
3890 .visible_worktrees(cx)
3891 .filter_map(|tree| {
3892 let tree = tree.read(cx).as_local()?;
3893 Some(tree.snapshot())
3894 })
3895 .collect::<Vec<_>>();
3896
3897 let background = cx.background().clone();
3898 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
3899 if path_count == 0 {
3900 return Task::ready(Ok(Default::default()));
3901 }
3902 let workers = background.num_cpus().min(path_count);
3903 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
3904 cx.background()
3905 .spawn({
3906 let fs = self.fs.clone();
3907 let background = cx.background().clone();
3908 let query = query.clone();
3909 async move {
3910 let fs = &fs;
3911 let query = &query;
3912 let matching_paths_tx = &matching_paths_tx;
3913 let paths_per_worker = (path_count + workers - 1) / workers;
3914 let snapshots = &snapshots;
3915 background
3916 .scoped(|scope| {
3917 for worker_ix in 0..workers {
3918 let worker_start_ix = worker_ix * paths_per_worker;
3919 let worker_end_ix = worker_start_ix + paths_per_worker;
3920 scope.spawn(async move {
3921 let mut snapshot_start_ix = 0;
3922 let mut abs_path = PathBuf::new();
3923 for snapshot in snapshots {
3924 let snapshot_end_ix =
3925 snapshot_start_ix + snapshot.visible_file_count();
3926 if worker_end_ix <= snapshot_start_ix {
3927 break;
3928 } else if worker_start_ix > snapshot_end_ix {
3929 snapshot_start_ix = snapshot_end_ix;
3930 continue;
3931 } else {
3932 let start_in_snapshot = worker_start_ix
3933 .saturating_sub(snapshot_start_ix);
3934 let end_in_snapshot =
3935 cmp::min(worker_end_ix, snapshot_end_ix)
3936 - snapshot_start_ix;
3937
3938 for entry in snapshot
3939 .files(false, start_in_snapshot)
3940 .take(end_in_snapshot - start_in_snapshot)
3941 {
3942 if matching_paths_tx.is_closed() {
3943 break;
3944 }
3945
3946 abs_path.clear();
3947 abs_path.push(&snapshot.abs_path());
3948 abs_path.push(&entry.path);
3949 let matches = if let Some(file) =
3950 fs.open_sync(&abs_path).await.log_err()
3951 {
3952 query.detect(file).unwrap_or(false)
3953 } else {
3954 false
3955 };
3956
3957 if matches {
3958 let project_path =
3959 (snapshot.id(), entry.path.clone());
3960 if matching_paths_tx
3961 .send(project_path)
3962 .await
3963 .is_err()
3964 {
3965 break;
3966 }
3967 }
3968 }
3969
3970 snapshot_start_ix = snapshot_end_ix;
3971 }
3972 }
3973 });
3974 }
3975 })
3976 .await;
3977 }
3978 })
3979 .detach();
3980
3981 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
3982 let open_buffers = self
3983 .opened_buffers
3984 .values()
3985 .filter_map(|b| b.upgrade(cx))
3986 .collect::<HashSet<_>>();
3987 cx.spawn(|this, cx| async move {
3988 for buffer in &open_buffers {
3989 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3990 buffers_tx.send((buffer.clone(), snapshot)).await?;
3991 }
3992
3993 let open_buffers = Rc::new(RefCell::new(open_buffers));
3994 while let Some(project_path) = matching_paths_rx.next().await {
3995 if buffers_tx.is_closed() {
3996 break;
3997 }
3998
3999 let this = this.clone();
4000 let open_buffers = open_buffers.clone();
4001 let buffers_tx = buffers_tx.clone();
4002 cx.spawn(|mut cx| async move {
4003 if let Some(buffer) = this
4004 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4005 .await
4006 .log_err()
4007 {
4008 if open_buffers.borrow_mut().insert(buffer.clone()) {
4009 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4010 buffers_tx.send((buffer, snapshot)).await?;
4011 }
4012 }
4013
4014 Ok::<_, anyhow::Error>(())
4015 })
4016 .detach();
4017 }
4018
4019 Ok::<_, anyhow::Error>(())
4020 })
4021 .detach_and_log_err(cx);
4022
4023 let background = cx.background().clone();
4024 cx.background().spawn(async move {
4025 let query = &query;
4026 let mut matched_buffers = Vec::new();
4027 for _ in 0..workers {
4028 matched_buffers.push(HashMap::default());
4029 }
4030 background
4031 .scoped(|scope| {
4032 for worker_matched_buffers in matched_buffers.iter_mut() {
4033 let mut buffers_rx = buffers_rx.clone();
4034 scope.spawn(async move {
4035 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4036 let buffer_matches = query
4037 .search(snapshot.as_rope())
4038 .await
4039 .iter()
4040 .map(|range| {
4041 snapshot.anchor_before(range.start)
4042 ..snapshot.anchor_after(range.end)
4043 })
4044 .collect::<Vec<_>>();
4045 if !buffer_matches.is_empty() {
4046 worker_matched_buffers
4047 .insert(buffer.clone(), buffer_matches);
4048 }
4049 }
4050 });
4051 }
4052 })
4053 .await;
4054 Ok(matched_buffers.into_iter().flatten().collect())
4055 })
4056 } else if let Some(project_id) = self.remote_id() {
4057 let request = self.client.request(query.to_proto(project_id));
4058 cx.spawn(|this, mut cx| async move {
4059 let response = request.await?;
4060 let mut result = HashMap::default();
4061 for location in response.locations {
4062 let target_buffer = this
4063 .update(&mut cx, |this, cx| {
4064 this.wait_for_buffer(location.buffer_id, cx)
4065 })
4066 .await?;
4067 let start = location
4068 .start
4069 .and_then(deserialize_anchor)
4070 .ok_or_else(|| anyhow!("missing target start"))?;
4071 let end = location
4072 .end
4073 .and_then(deserialize_anchor)
4074 .ok_or_else(|| anyhow!("missing target end"))?;
4075 result
4076 .entry(target_buffer)
4077 .or_insert(Vec::new())
4078 .push(start..end)
4079 }
4080 Ok(result)
4081 })
4082 } else {
4083 Task::ready(Ok(Default::default()))
4084 }
4085 }
4086
4087 fn request_lsp<R: LspCommand>(
4088 &self,
4089 buffer_handle: ModelHandle<Buffer>,
4090 request: R,
4091 cx: &mut ModelContext<Self>,
4092 ) -> Task<Result<R::Response>>
4093 where
4094 <R::LspRequest as lsp::request::Request>::Result: Send,
4095 {
4096 let buffer = buffer_handle.read(cx);
4097 if self.is_local() {
4098 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4099 if let Some((file, language_server)) = file.zip(
4100 self.language_server_for_buffer(buffer, cx)
4101 .map(|(_, server)| server.clone()),
4102 ) {
4103 let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4104 return cx.spawn(|this, cx| async move {
4105 if !request.check_capabilities(language_server.capabilities()) {
4106 return Ok(Default::default());
4107 }
4108
4109 let response = language_server
4110 .request::<R::LspRequest>(lsp_params)
4111 .await
4112 .context("lsp request failed")?;
4113 request
4114 .response_from_lsp(response, this, buffer_handle, cx)
4115 .await
4116 });
4117 }
4118 } else if let Some(project_id) = self.remote_id() {
4119 let rpc = self.client.clone();
4120 let message = request.to_proto(project_id, buffer);
4121 return cx.spawn(|this, cx| async move {
4122 let response = rpc.request(message).await?;
4123 request
4124 .response_from_proto(response, this, buffer_handle, cx)
4125 .await
4126 });
4127 }
4128 Task::ready(Ok(Default::default()))
4129 }
4130
4131 pub fn find_or_create_local_worktree(
4132 &mut self,
4133 abs_path: impl AsRef<Path>,
4134 visible: bool,
4135 cx: &mut ModelContext<Self>,
4136 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4137 let abs_path = abs_path.as_ref();
4138 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4139 Task::ready(Ok((tree, relative_path)))
4140 } else {
4141 let worktree = self.create_local_worktree(abs_path, visible, cx);
4142 cx.foreground()
4143 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4144 }
4145 }
4146
4147 pub fn find_local_worktree(
4148 &self,
4149 abs_path: &Path,
4150 cx: &AppContext,
4151 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4152 for tree in &self.worktrees {
4153 if let Some(tree) = tree.upgrade(cx) {
4154 if let Some(relative_path) = tree
4155 .read(cx)
4156 .as_local()
4157 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4158 {
4159 return Some((tree.clone(), relative_path.into()));
4160 }
4161 }
4162 }
4163 None
4164 }
4165
4166 pub fn is_shared(&self) -> bool {
4167 match &self.client_state {
4168 ProjectClientState::Local { remote_id, .. } => remote_id.is_some(),
4169 ProjectClientState::Remote { .. } => false,
4170 }
4171 }
4172
4173 fn create_local_worktree(
4174 &mut self,
4175 abs_path: impl AsRef<Path>,
4176 visible: bool,
4177 cx: &mut ModelContext<Self>,
4178 ) -> Task<Result<ModelHandle<Worktree>>> {
4179 let fs = self.fs.clone();
4180 let client = self.client.clone();
4181 let next_entry_id = self.next_entry_id.clone();
4182 let path: Arc<Path> = abs_path.as_ref().into();
4183 let task = self
4184 .loading_local_worktrees
4185 .entry(path.clone())
4186 .or_insert_with(|| {
4187 cx.spawn(|project, mut cx| {
4188 async move {
4189 let worktree = Worktree::local(
4190 client.clone(),
4191 path.clone(),
4192 visible,
4193 fs,
4194 next_entry_id,
4195 &mut cx,
4196 )
4197 .await;
4198 project.update(&mut cx, |project, _| {
4199 project.loading_local_worktrees.remove(&path);
4200 });
4201 let worktree = worktree?;
4202
4203 let project_id = project.update(&mut cx, |project, cx| {
4204 project.add_worktree(&worktree, cx);
4205 project.remote_id()
4206 });
4207
4208 if let Some(project_id) = project_id {
4209 worktree
4210 .update(&mut cx, |worktree, cx| {
4211 worktree.as_local_mut().unwrap().share(project_id, cx)
4212 })
4213 .await
4214 .log_err();
4215 }
4216
4217 Ok(worktree)
4218 }
4219 .map_err(Arc::new)
4220 })
4221 .shared()
4222 })
4223 .clone();
4224 cx.foreground().spawn(async move {
4225 match task.await {
4226 Ok(worktree) => Ok(worktree),
4227 Err(err) => Err(anyhow!("{}", err)),
4228 }
4229 })
4230 }
4231
4232 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4233 self.worktrees.retain(|worktree| {
4234 if let Some(worktree) = worktree.upgrade(cx) {
4235 let id = worktree.read(cx).id();
4236 if id == id_to_remove {
4237 cx.emit(Event::WorktreeRemoved(id));
4238 false
4239 } else {
4240 true
4241 }
4242 } else {
4243 false
4244 }
4245 });
4246 self.metadata_changed(cx);
4247 cx.notify();
4248 }
4249
4250 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4251 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4252 if worktree.read(cx).is_local() {
4253 cx.subscribe(worktree, |this, worktree, event, cx| match event {
4254 worktree::Event::UpdatedEntries => this.update_local_worktree_buffers(worktree, cx),
4255 worktree::Event::UpdatedGitRepositories(updated_repos) => {
4256 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4257 }
4258 })
4259 .detach();
4260 }
4261
4262 let push_strong_handle = {
4263 let worktree = worktree.read(cx);
4264 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4265 };
4266 if push_strong_handle {
4267 self.worktrees
4268 .push(WorktreeHandle::Strong(worktree.clone()));
4269 } else {
4270 self.worktrees
4271 .push(WorktreeHandle::Weak(worktree.downgrade()));
4272 }
4273
4274 self.metadata_changed(cx);
4275 cx.observe_release(worktree, |this, worktree, cx| {
4276 this.remove_worktree(worktree.id(), cx);
4277 cx.notify();
4278 })
4279 .detach();
4280
4281 cx.emit(Event::WorktreeAdded);
4282 cx.notify();
4283 }
4284
4285 fn update_local_worktree_buffers(
4286 &mut self,
4287 worktree_handle: ModelHandle<Worktree>,
4288 cx: &mut ModelContext<Self>,
4289 ) {
4290 let snapshot = worktree_handle.read(cx).snapshot();
4291 let mut buffers_to_delete = Vec::new();
4292 let mut renamed_buffers = Vec::new();
4293 for (buffer_id, buffer) in &self.opened_buffers {
4294 if let Some(buffer) = buffer.upgrade(cx) {
4295 buffer.update(cx, |buffer, cx| {
4296 if let Some(old_file) = File::from_dyn(buffer.file()) {
4297 if old_file.worktree != worktree_handle {
4298 return;
4299 }
4300
4301 let new_file = if let Some(entry) = old_file
4302 .entry_id
4303 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
4304 {
4305 File {
4306 is_local: true,
4307 entry_id: Some(entry.id),
4308 mtime: entry.mtime,
4309 path: entry.path.clone(),
4310 worktree: worktree_handle.clone(),
4311 }
4312 } else if let Some(entry) =
4313 snapshot.entry_for_path(old_file.path().as_ref())
4314 {
4315 File {
4316 is_local: true,
4317 entry_id: Some(entry.id),
4318 mtime: entry.mtime,
4319 path: entry.path.clone(),
4320 worktree: worktree_handle.clone(),
4321 }
4322 } else {
4323 File {
4324 is_local: true,
4325 entry_id: None,
4326 path: old_file.path().clone(),
4327 mtime: old_file.mtime(),
4328 worktree: worktree_handle.clone(),
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 ProjectClientState::Local { remote_id, .. } => {
5961 if let Some(project_id) = *remote_id {
5962 self.client
5963 .send(proto::UnshareProject { project_id })
5964 .log_err();
5965 }
5966 }
5967 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 fn app_will_quit(
5978 &mut self,
5979 _: &mut MutableAppContext,
5980 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
5981 let shutdown_futures = self
5982 .language_servers
5983 .drain()
5984 .map(|(_, server_state)| async {
5985 match server_state {
5986 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
5987 LanguageServerState::Starting(starting_server) => {
5988 starting_server.await?.shutdown()?.await
5989 }
5990 }
5991 })
5992 .collect::<Vec<_>>();
5993
5994 Some(
5995 async move {
5996 futures::future::join_all(shutdown_futures).await;
5997 }
5998 .boxed(),
5999 )
6000 }
6001}
6002
6003impl Collaborator {
6004 fn from_proto(message: proto::Collaborator) -> Self {
6005 Self {
6006 peer_id: PeerId(message.peer_id),
6007 replica_id: message.replica_id as ReplicaId,
6008 }
6009 }
6010}
6011
6012impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6013 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6014 Self {
6015 worktree_id,
6016 path: path.as_ref().into(),
6017 }
6018 }
6019}
6020
6021fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6022 proto::Symbol {
6023 language_server_name: symbol.language_server_name.0.to_string(),
6024 source_worktree_id: symbol.source_worktree_id.to_proto(),
6025 worktree_id: symbol.path.worktree_id.to_proto(),
6026 path: symbol.path.path.to_string_lossy().to_string(),
6027 name: symbol.name.clone(),
6028 kind: unsafe { mem::transmute(symbol.kind) },
6029 start: Some(proto::Point {
6030 row: symbol.range.start.row,
6031 column: symbol.range.start.column,
6032 }),
6033 end: Some(proto::Point {
6034 row: symbol.range.end.row,
6035 column: symbol.range.end.column,
6036 }),
6037 signature: symbol.signature.to_vec(),
6038 }
6039}
6040
6041fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6042 let mut path_components = path.components();
6043 let mut base_components = base.components();
6044 let mut components: Vec<Component> = Vec::new();
6045 loop {
6046 match (path_components.next(), base_components.next()) {
6047 (None, None) => break,
6048 (Some(a), None) => {
6049 components.push(a);
6050 components.extend(path_components.by_ref());
6051 break;
6052 }
6053 (None, _) => components.push(Component::ParentDir),
6054 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6055 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6056 (Some(a), Some(_)) => {
6057 components.push(Component::ParentDir);
6058 for _ in base_components {
6059 components.push(Component::ParentDir);
6060 }
6061 components.push(a);
6062 components.extend(path_components.by_ref());
6063 break;
6064 }
6065 }
6066 }
6067 components.iter().map(|c| c.as_os_str()).collect()
6068}
6069
6070impl Item for Buffer {
6071 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6072 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6073 }
6074}