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