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