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