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