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