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