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, ToOffsetClamped, ToPointUtf16,
29 Transaction,
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<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<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::<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 = snapshot.clip_point_utf16(start, Bias::Left)
2681 ..snapshot.clip_point_utf16(end, Bias::Right);
2682
2683 // Expand empty ranges by one character
2684 if range.start == range.end {
2685 range.end.column += 1;
2686 range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2687 if range.start == range.end && range.end.column > 0 {
2688 range.start.column -= 1;
2689 range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2690 }
2691 }
2692
2693 sanitized_diagnostics.push(DiagnosticEntry {
2694 range,
2695 diagnostic: entry.diagnostic,
2696 });
2697 }
2698 drop(edits_since_save);
2699
2700 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2701 buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2702 Ok(())
2703 }
2704
2705 pub fn reload_buffers(
2706 &self,
2707 buffers: HashSet<ModelHandle<Buffer>>,
2708 push_to_history: bool,
2709 cx: &mut ModelContext<Self>,
2710 ) -> Task<Result<ProjectTransaction>> {
2711 let mut local_buffers = Vec::new();
2712 let mut remote_buffers = None;
2713 for buffer_handle in buffers {
2714 let buffer = buffer_handle.read(cx);
2715 if buffer.is_dirty() {
2716 if let Some(file) = File::from_dyn(buffer.file()) {
2717 if file.is_local() {
2718 local_buffers.push(buffer_handle);
2719 } else {
2720 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2721 }
2722 }
2723 }
2724 }
2725
2726 let remote_buffers = self.remote_id().zip(remote_buffers);
2727 let client = self.client.clone();
2728
2729 cx.spawn(|this, mut cx| async move {
2730 let mut project_transaction = ProjectTransaction::default();
2731
2732 if let Some((project_id, remote_buffers)) = remote_buffers {
2733 let response = client
2734 .request(proto::ReloadBuffers {
2735 project_id,
2736 buffer_ids: remote_buffers
2737 .iter()
2738 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2739 .collect(),
2740 })
2741 .await?
2742 .transaction
2743 .ok_or_else(|| anyhow!("missing transaction"))?;
2744 project_transaction = this
2745 .update(&mut cx, |this, cx| {
2746 this.deserialize_project_transaction(response, push_to_history, cx)
2747 })
2748 .await?;
2749 }
2750
2751 for buffer in local_buffers {
2752 let transaction = buffer
2753 .update(&mut cx, |buffer, cx| buffer.reload(cx))
2754 .await?;
2755 buffer.update(&mut cx, |buffer, cx| {
2756 if let Some(transaction) = transaction {
2757 if !push_to_history {
2758 buffer.forget_transaction(transaction.id);
2759 }
2760 project_transaction.0.insert(cx.handle(), transaction);
2761 }
2762 });
2763 }
2764
2765 Ok(project_transaction)
2766 })
2767 }
2768
2769 pub fn format(
2770 &self,
2771 buffers: HashSet<ModelHandle<Buffer>>,
2772 push_to_history: bool,
2773 trigger: FormatTrigger,
2774 cx: &mut ModelContext<Project>,
2775 ) -> Task<Result<ProjectTransaction>> {
2776 let mut local_buffers = Vec::new();
2777 let mut remote_buffers = None;
2778 for buffer_handle in buffers {
2779 let buffer = buffer_handle.read(cx);
2780 if let Some(file) = File::from_dyn(buffer.file()) {
2781 if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2782 if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2783 local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2784 }
2785 } else {
2786 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2787 }
2788 } else {
2789 return Task::ready(Ok(Default::default()));
2790 }
2791 }
2792
2793 let remote_buffers = self.remote_id().zip(remote_buffers);
2794 let client = self.client.clone();
2795
2796 cx.spawn(|this, mut cx| async move {
2797 let mut project_transaction = ProjectTransaction::default();
2798
2799 if let Some((project_id, remote_buffers)) = remote_buffers {
2800 let response = client
2801 .request(proto::FormatBuffers {
2802 project_id,
2803 trigger: trigger as i32,
2804 buffer_ids: remote_buffers
2805 .iter()
2806 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2807 .collect(),
2808 })
2809 .await?
2810 .transaction
2811 .ok_or_else(|| anyhow!("missing transaction"))?;
2812 project_transaction = this
2813 .update(&mut cx, |this, cx| {
2814 this.deserialize_project_transaction(response, push_to_history, cx)
2815 })
2816 .await?;
2817 }
2818
2819 // Do not allow multiple concurrent formatting requests for the
2820 // same buffer.
2821 this.update(&mut cx, |this, _| {
2822 local_buffers
2823 .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
2824 });
2825 let _cleanup = defer({
2826 let this = this.clone();
2827 let mut cx = cx.clone();
2828 let local_buffers = &local_buffers;
2829 move || {
2830 this.update(&mut cx, |this, _| {
2831 for (buffer, _, _) in local_buffers {
2832 this.buffers_being_formatted.remove(&buffer.id());
2833 }
2834 });
2835 }
2836 });
2837
2838 for (buffer, buffer_abs_path, language_server) in &local_buffers {
2839 let (format_on_save, formatter, tab_size) = buffer.read_with(&cx, |buffer, cx| {
2840 let settings = cx.global::<Settings>();
2841 let language_name = buffer.language().map(|language| language.name());
2842 (
2843 settings.format_on_save(language_name.as_deref()),
2844 settings.formatter(language_name.as_deref()),
2845 settings.tab_size(language_name.as_deref()),
2846 )
2847 });
2848
2849 let transaction = match (formatter, format_on_save) {
2850 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => continue,
2851
2852 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
2853 | (_, FormatOnSave::LanguageServer) => Self::format_via_lsp(
2854 &this,
2855 &buffer,
2856 &buffer_abs_path,
2857 &language_server,
2858 tab_size,
2859 &mut cx,
2860 )
2861 .await
2862 .context("failed to format via language server")?,
2863
2864 (
2865 Formatter::External { command, arguments },
2866 FormatOnSave::On | FormatOnSave::Off,
2867 )
2868 | (_, FormatOnSave::External { command, arguments }) => {
2869 Self::format_via_external_command(
2870 &buffer,
2871 &buffer_abs_path,
2872 &command,
2873 &arguments,
2874 &mut cx,
2875 )
2876 .await
2877 .context(format!(
2878 "failed to format via external command {:?}",
2879 command
2880 ))?
2881 }
2882 };
2883
2884 if let Some(transaction) = transaction {
2885 if !push_to_history {
2886 buffer.update(&mut cx, |buffer, _| {
2887 buffer.forget_transaction(transaction.id)
2888 });
2889 }
2890 project_transaction.0.insert(buffer.clone(), transaction);
2891 }
2892 }
2893
2894 Ok(project_transaction)
2895 })
2896 }
2897
2898 async fn format_via_lsp(
2899 this: &ModelHandle<Self>,
2900 buffer: &ModelHandle<Buffer>,
2901 abs_path: &Path,
2902 language_server: &Arc<LanguageServer>,
2903 tab_size: NonZeroU32,
2904 cx: &mut AsyncAppContext,
2905 ) -> Result<Option<Transaction>> {
2906 let text_document =
2907 lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
2908 let capabilities = &language_server.capabilities();
2909 let lsp_edits = if capabilities
2910 .document_formatting_provider
2911 .as_ref()
2912 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2913 {
2914 language_server
2915 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2916 text_document,
2917 options: lsp::FormattingOptions {
2918 tab_size: tab_size.into(),
2919 insert_spaces: true,
2920 insert_final_newline: Some(true),
2921 ..Default::default()
2922 },
2923 work_done_progress_params: Default::default(),
2924 })
2925 .await?
2926 } else if capabilities
2927 .document_range_formatting_provider
2928 .as_ref()
2929 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2930 {
2931 let buffer_start = lsp::Position::new(0, 0);
2932 let buffer_end =
2933 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
2934 language_server
2935 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
2936 text_document,
2937 range: lsp::Range::new(buffer_start, buffer_end),
2938 options: lsp::FormattingOptions {
2939 tab_size: tab_size.into(),
2940 insert_spaces: true,
2941 insert_final_newline: Some(true),
2942 ..Default::default()
2943 },
2944 work_done_progress_params: Default::default(),
2945 })
2946 .await?
2947 } else {
2948 None
2949 };
2950
2951 if let Some(lsp_edits) = lsp_edits {
2952 let edits = this
2953 .update(cx, |this, cx| {
2954 this.edits_from_lsp(buffer, lsp_edits, None, cx)
2955 })
2956 .await?;
2957 buffer.update(cx, |buffer, cx| {
2958 buffer.finalize_last_transaction();
2959 buffer.start_transaction();
2960 for (range, text) in edits {
2961 buffer.edit([(range, text)], None, cx);
2962 }
2963 if buffer.end_transaction(cx).is_some() {
2964 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2965 Ok(Some(transaction))
2966 } else {
2967 Ok(None)
2968 }
2969 })
2970 } else {
2971 Ok(None)
2972 }
2973 }
2974
2975 async fn format_via_external_command(
2976 buffer: &ModelHandle<Buffer>,
2977 buffer_abs_path: &Path,
2978 command: &str,
2979 arguments: &[String],
2980 cx: &mut AsyncAppContext,
2981 ) -> Result<Option<Transaction>> {
2982 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
2983 let file = File::from_dyn(buffer.file())?;
2984 let worktree = file.worktree.read(cx).as_local()?;
2985 let mut worktree_path = worktree.abs_path().to_path_buf();
2986 if worktree.root_entry()?.is_file() {
2987 worktree_path.pop();
2988 }
2989 Some(worktree_path)
2990 });
2991
2992 if let Some(working_dir_path) = working_dir_path {
2993 let mut child =
2994 smol::process::Command::new(command)
2995 .args(arguments.iter().map(|arg| {
2996 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
2997 }))
2998 .current_dir(&working_dir_path)
2999 .stdin(smol::process::Stdio::piped())
3000 .stdout(smol::process::Stdio::piped())
3001 .stderr(smol::process::Stdio::piped())
3002 .spawn()?;
3003 let stdin = child
3004 .stdin
3005 .as_mut()
3006 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3007 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3008 for chunk in text.chunks() {
3009 stdin.write_all(chunk.as_bytes()).await?;
3010 }
3011 stdin.flush().await?;
3012
3013 let output = child.output().await?;
3014 if !output.status.success() {
3015 return Err(anyhow!(
3016 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3017 output.status.code(),
3018 String::from_utf8_lossy(&output.stdout),
3019 String::from_utf8_lossy(&output.stderr),
3020 ));
3021 }
3022
3023 let stdout = String::from_utf8(output.stdout)?;
3024 let diff = buffer
3025 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3026 .await;
3027 Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3028 } else {
3029 Ok(None)
3030 }
3031 }
3032
3033 pub fn definition<T: ToPointUtf16>(
3034 &self,
3035 buffer: &ModelHandle<Buffer>,
3036 position: T,
3037 cx: &mut ModelContext<Self>,
3038 ) -> Task<Result<Vec<LocationLink>>> {
3039 let position = position.to_point_utf16(buffer.read(cx));
3040 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3041 }
3042
3043 pub fn type_definition<T: ToPointUtf16>(
3044 &self,
3045 buffer: &ModelHandle<Buffer>,
3046 position: T,
3047 cx: &mut ModelContext<Self>,
3048 ) -> Task<Result<Vec<LocationLink>>> {
3049 let position = position.to_point_utf16(buffer.read(cx));
3050 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3051 }
3052
3053 pub fn references<T: ToPointUtf16>(
3054 &self,
3055 buffer: &ModelHandle<Buffer>,
3056 position: T,
3057 cx: &mut ModelContext<Self>,
3058 ) -> Task<Result<Vec<Location>>> {
3059 let position = position.to_point_utf16(buffer.read(cx));
3060 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3061 }
3062
3063 pub fn document_highlights<T: ToPointUtf16>(
3064 &self,
3065 buffer: &ModelHandle<Buffer>,
3066 position: T,
3067 cx: &mut ModelContext<Self>,
3068 ) -> Task<Result<Vec<DocumentHighlight>>> {
3069 let position = position.to_point_utf16(buffer.read(cx));
3070 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3071 }
3072
3073 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3074 if self.is_local() {
3075 let mut requests = Vec::new();
3076 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3077 let worktree_id = *worktree_id;
3078 if let Some(worktree) = self
3079 .worktree_for_id(worktree_id, cx)
3080 .and_then(|worktree| worktree.read(cx).as_local())
3081 {
3082 if let Some(LanguageServerState::Running {
3083 adapter,
3084 language,
3085 server,
3086 }) = self.language_servers.get(server_id)
3087 {
3088 let adapter = adapter.clone();
3089 let language = language.clone();
3090 let worktree_abs_path = worktree.abs_path().clone();
3091 requests.push(
3092 server
3093 .request::<lsp::request::WorkspaceSymbol>(
3094 lsp::WorkspaceSymbolParams {
3095 query: query.to_string(),
3096 ..Default::default()
3097 },
3098 )
3099 .log_err()
3100 .map(move |response| {
3101 (
3102 adapter,
3103 language,
3104 worktree_id,
3105 worktree_abs_path,
3106 response.unwrap_or_default(),
3107 )
3108 }),
3109 );
3110 }
3111 }
3112 }
3113
3114 cx.spawn_weak(|this, cx| async move {
3115 let responses = futures::future::join_all(requests).await;
3116 let this = if let Some(this) = this.upgrade(&cx) {
3117 this
3118 } else {
3119 return Ok(Default::default());
3120 };
3121 let symbols = this.read_with(&cx, |this, cx| {
3122 let mut symbols = Vec::new();
3123 for (
3124 adapter,
3125 adapter_language,
3126 source_worktree_id,
3127 worktree_abs_path,
3128 response,
3129 ) in responses
3130 {
3131 symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3132 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3133 let mut worktree_id = source_worktree_id;
3134 let path;
3135 if let Some((worktree, rel_path)) =
3136 this.find_local_worktree(&abs_path, cx)
3137 {
3138 worktree_id = worktree.read(cx).id();
3139 path = rel_path;
3140 } else {
3141 path = relativize_path(&worktree_abs_path, &abs_path);
3142 }
3143
3144 let project_path = ProjectPath {
3145 worktree_id,
3146 path: path.into(),
3147 };
3148 let signature = this.symbol_signature(&project_path);
3149 let language = this
3150 .languages
3151 .select_language(&project_path.path)
3152 .unwrap_or(adapter_language.clone());
3153 let language_server_name = adapter.name.clone();
3154 Some(async move {
3155 let label = language
3156 .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3157 .await;
3158
3159 Symbol {
3160 language_server_name,
3161 source_worktree_id,
3162 path: project_path,
3163 label: label.unwrap_or_else(|| {
3164 CodeLabel::plain(lsp_symbol.name.clone(), None)
3165 }),
3166 kind: lsp_symbol.kind,
3167 name: lsp_symbol.name,
3168 range: range_from_lsp(lsp_symbol.location.range),
3169 signature,
3170 }
3171 })
3172 }));
3173 }
3174 symbols
3175 });
3176 Ok(futures::future::join_all(symbols).await)
3177 })
3178 } else if let Some(project_id) = self.remote_id() {
3179 let request = self.client.request(proto::GetProjectSymbols {
3180 project_id,
3181 query: query.to_string(),
3182 });
3183 cx.spawn_weak(|this, cx| async move {
3184 let response = request.await?;
3185 let mut symbols = Vec::new();
3186 if let Some(this) = this.upgrade(&cx) {
3187 let new_symbols = this.read_with(&cx, |this, _| {
3188 response
3189 .symbols
3190 .into_iter()
3191 .map(|symbol| this.deserialize_symbol(symbol))
3192 .collect::<Vec<_>>()
3193 });
3194 symbols = futures::future::join_all(new_symbols)
3195 .await
3196 .into_iter()
3197 .filter_map(|symbol| symbol.log_err())
3198 .collect::<Vec<_>>();
3199 }
3200 Ok(symbols)
3201 })
3202 } else {
3203 Task::ready(Ok(Default::default()))
3204 }
3205 }
3206
3207 pub fn open_buffer_for_symbol(
3208 &mut self,
3209 symbol: &Symbol,
3210 cx: &mut ModelContext<Self>,
3211 ) -> Task<Result<ModelHandle<Buffer>>> {
3212 if self.is_local() {
3213 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3214 symbol.source_worktree_id,
3215 symbol.language_server_name.clone(),
3216 )) {
3217 *id
3218 } else {
3219 return Task::ready(Err(anyhow!(
3220 "language server for worktree and language not found"
3221 )));
3222 };
3223
3224 let worktree_abs_path = if let Some(worktree_abs_path) = self
3225 .worktree_for_id(symbol.path.worktree_id, cx)
3226 .and_then(|worktree| worktree.read(cx).as_local())
3227 .map(|local_worktree| local_worktree.abs_path())
3228 {
3229 worktree_abs_path
3230 } else {
3231 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3232 };
3233 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3234 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3235 uri
3236 } else {
3237 return Task::ready(Err(anyhow!("invalid symbol path")));
3238 };
3239
3240 self.open_local_buffer_via_lsp(
3241 symbol_uri,
3242 language_server_id,
3243 symbol.language_server_name.clone(),
3244 cx,
3245 )
3246 } else if let Some(project_id) = self.remote_id() {
3247 let request = self.client.request(proto::OpenBufferForSymbol {
3248 project_id,
3249 symbol: Some(serialize_symbol(symbol)),
3250 });
3251 cx.spawn(|this, mut cx| async move {
3252 let response = request.await?;
3253 this.update(&mut cx, |this, cx| {
3254 this.wait_for_buffer(response.buffer_id, cx)
3255 })
3256 .await
3257 })
3258 } else {
3259 Task::ready(Err(anyhow!("project does not have a remote id")))
3260 }
3261 }
3262
3263 pub fn hover<T: ToPointUtf16>(
3264 &self,
3265 buffer: &ModelHandle<Buffer>,
3266 position: T,
3267 cx: &mut ModelContext<Self>,
3268 ) -> Task<Result<Option<Hover>>> {
3269 let position = position.to_point_utf16(buffer.read(cx));
3270 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3271 }
3272
3273 pub fn completions<T: ToPointUtf16>(
3274 &self,
3275 source_buffer_handle: &ModelHandle<Buffer>,
3276 position: T,
3277 cx: &mut ModelContext<Self>,
3278 ) -> Task<Result<Vec<Completion>>> {
3279 let source_buffer_handle = source_buffer_handle.clone();
3280 let source_buffer = source_buffer_handle.read(cx);
3281 let buffer_id = source_buffer.remote_id();
3282 let language = source_buffer.language().cloned();
3283 let worktree;
3284 let buffer_abs_path;
3285 if let Some(file) = File::from_dyn(source_buffer.file()) {
3286 worktree = file.worktree.clone();
3287 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3288 } else {
3289 return Task::ready(Ok(Default::default()));
3290 };
3291
3292 let position = position.to_point_utf16(source_buffer);
3293 let anchor = source_buffer.clamped_anchor_after(position);
3294
3295 if worktree.read(cx).as_local().is_some() {
3296 let buffer_abs_path = buffer_abs_path.unwrap();
3297 let lang_server =
3298 if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3299 server.clone()
3300 } else {
3301 return Task::ready(Ok(Default::default()));
3302 };
3303
3304 cx.spawn(|_, cx| async move {
3305 let completions = lang_server
3306 .request::<lsp::request::Completion>(lsp::CompletionParams {
3307 text_document_position: lsp::TextDocumentPositionParams::new(
3308 lsp::TextDocumentIdentifier::new(
3309 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3310 ),
3311 point_to_lsp(position),
3312 ),
3313 context: Default::default(),
3314 work_done_progress_params: Default::default(),
3315 partial_result_params: Default::default(),
3316 })
3317 .await
3318 .context("lsp completion request failed")?;
3319
3320 let completions = if let Some(completions) = completions {
3321 match completions {
3322 lsp::CompletionResponse::Array(completions) => completions,
3323 lsp::CompletionResponse::List(list) => list.items,
3324 }
3325 } else {
3326 Default::default()
3327 };
3328
3329 let completions = source_buffer_handle.read_with(&cx, |this, _| {
3330 let snapshot = this.snapshot();
3331 let clipped_position = this.clip_point_utf16(position, Bias::Left);
3332 let mut range_for_token = None;
3333 completions
3334 .into_iter()
3335 .filter_map(move |mut lsp_completion| {
3336 // For now, we can only handle additional edits if they are returned
3337 // when resolving the completion, not if they are present initially.
3338 if lsp_completion
3339 .additional_text_edits
3340 .as_ref()
3341 .map_or(false, |edits| !edits.is_empty())
3342 {
3343 return None;
3344 }
3345
3346 let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref()
3347 {
3348 // If the language server provides a range to overwrite, then
3349 // check that the range is valid.
3350 Some(lsp::CompletionTextEdit::Edit(edit)) => {
3351 let range = range_from_lsp(edit.range);
3352 let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3353 let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3354 if start != range.start || end != range.end {
3355 log::info!("completion out of expected range");
3356 return None;
3357 }
3358 (
3359 snapshot.clamped_anchor_before(start)..snapshot.clamped_anchor_after(end),
3360 edit.new_text.clone(),
3361 )
3362 }
3363 // If the language server does not provide a range, then infer
3364 // the range based on the syntax tree.
3365 None => {
3366 if position != clipped_position {
3367 log::info!("completion out of expected range");
3368 return None;
3369 }
3370 let Range { start, end } = range_for_token
3371 .get_or_insert_with(|| {
3372 let offset = position.to_offset_clamped(&snapshot);
3373 let (range, kind) = snapshot.surrounding_word(offset);
3374 if kind == Some(CharKind::Word) {
3375 range
3376 } else {
3377 offset..offset
3378 }
3379 })
3380 .clone();
3381 let text = lsp_completion
3382 .insert_text
3383 .as_ref()
3384 .unwrap_or(&lsp_completion.label)
3385 .clone();
3386 (
3387 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3388 text,
3389 )
3390 }
3391 Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3392 log::info!("unsupported insert/replace completion");
3393 return None;
3394 }
3395 };
3396
3397 LineEnding::normalize(&mut new_text);
3398 let language = language.clone();
3399 Some(async move {
3400 let mut label = None;
3401 if let Some(language) = language {
3402 language.process_completion(&mut lsp_completion).await;
3403 label = language.label_for_completion(&lsp_completion).await;
3404 }
3405 Completion {
3406 old_range,
3407 new_text,
3408 label: label.unwrap_or_else(|| {
3409 CodeLabel::plain(
3410 lsp_completion.label.clone(),
3411 lsp_completion.filter_text.as_deref(),
3412 )
3413 }),
3414 lsp_completion,
3415 }
3416 })
3417 })
3418 });
3419
3420 Ok(futures::future::join_all(completions).await)
3421 })
3422 } else if let Some(project_id) = self.remote_id() {
3423 let rpc = self.client.clone();
3424 let message = proto::GetCompletions {
3425 project_id,
3426 buffer_id,
3427 position: Some(language::proto::serialize_anchor(&anchor)),
3428 version: serialize_version(&source_buffer.version()),
3429 };
3430 cx.spawn_weak(|_, mut cx| async move {
3431 let response = rpc.request(message).await?;
3432
3433 source_buffer_handle
3434 .update(&mut cx, |buffer, _| {
3435 buffer.wait_for_version(deserialize_version(response.version))
3436 })
3437 .await;
3438
3439 let completions = response.completions.into_iter().map(|completion| {
3440 language::proto::deserialize_completion(completion, language.clone())
3441 });
3442 futures::future::try_join_all(completions).await
3443 })
3444 } else {
3445 Task::ready(Ok(Default::default()))
3446 }
3447 }
3448
3449 pub fn apply_additional_edits_for_completion(
3450 &self,
3451 buffer_handle: ModelHandle<Buffer>,
3452 completion: Completion,
3453 push_to_history: bool,
3454 cx: &mut ModelContext<Self>,
3455 ) -> Task<Result<Option<Transaction>>> {
3456 let buffer = buffer_handle.read(cx);
3457 let buffer_id = buffer.remote_id();
3458
3459 if self.is_local() {
3460 let lang_server = match self.language_server_for_buffer(buffer, cx) {
3461 Some((_, server)) => server.clone(),
3462 _ => return Task::ready(Ok(Default::default())),
3463 };
3464
3465 cx.spawn(|this, mut cx| async move {
3466 let resolved_completion = lang_server
3467 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3468 .await?;
3469
3470 if let Some(edits) = resolved_completion.additional_text_edits {
3471 let edits = this
3472 .update(&mut cx, |this, cx| {
3473 this.edits_from_lsp(&buffer_handle, edits, None, cx)
3474 })
3475 .await?;
3476
3477 buffer_handle.update(&mut cx, |buffer, cx| {
3478 buffer.finalize_last_transaction();
3479 buffer.start_transaction();
3480
3481 for (range, text) in edits {
3482 let primary = &completion.old_range;
3483 let start_within = primary.start.cmp(&range.start, buffer).is_le()
3484 && primary.end.cmp(&range.start, buffer).is_ge();
3485 let end_within = range.start.cmp(&primary.end, buffer).is_le()
3486 && range.end.cmp(&primary.end, buffer).is_ge();
3487
3488 //Skip addtional edits which overlap with the primary completion edit
3489 //https://github.com/zed-industries/zed/pull/1871
3490 if !start_within && !end_within {
3491 buffer.edit([(range, text)], None, cx);
3492 }
3493 }
3494
3495 let transaction = if buffer.end_transaction(cx).is_some() {
3496 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3497 if !push_to_history {
3498 buffer.forget_transaction(transaction.id);
3499 }
3500 Some(transaction)
3501 } else {
3502 None
3503 };
3504 Ok(transaction)
3505 })
3506 } else {
3507 Ok(None)
3508 }
3509 })
3510 } else if let Some(project_id) = self.remote_id() {
3511 let client = self.client.clone();
3512 cx.spawn(|_, mut cx| async move {
3513 let response = client
3514 .request(proto::ApplyCompletionAdditionalEdits {
3515 project_id,
3516 buffer_id,
3517 completion: Some(language::proto::serialize_completion(&completion)),
3518 })
3519 .await?;
3520
3521 if let Some(transaction) = response.transaction {
3522 let transaction = language::proto::deserialize_transaction(transaction)?;
3523 buffer_handle
3524 .update(&mut cx, |buffer, _| {
3525 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3526 })
3527 .await;
3528 if push_to_history {
3529 buffer_handle.update(&mut cx, |buffer, _| {
3530 buffer.push_transaction(transaction.clone(), Instant::now());
3531 });
3532 }
3533 Ok(Some(transaction))
3534 } else {
3535 Ok(None)
3536 }
3537 })
3538 } else {
3539 Task::ready(Err(anyhow!("project does not have a remote id")))
3540 }
3541 }
3542
3543 pub fn code_actions<T: Clone + ToOffset>(
3544 &self,
3545 buffer_handle: &ModelHandle<Buffer>,
3546 range: Range<T>,
3547 cx: &mut ModelContext<Self>,
3548 ) -> Task<Result<Vec<CodeAction>>> {
3549 let buffer_handle = buffer_handle.clone();
3550 let buffer = buffer_handle.read(cx);
3551 let snapshot = buffer.snapshot();
3552 let relevant_diagnostics = snapshot
3553 .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3554 .map(|entry| entry.to_lsp_diagnostic_stub())
3555 .collect();
3556 let buffer_id = buffer.remote_id();
3557 let worktree;
3558 let buffer_abs_path;
3559 if let Some(file) = File::from_dyn(buffer.file()) {
3560 worktree = file.worktree.clone();
3561 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3562 } else {
3563 return Task::ready(Ok(Default::default()));
3564 };
3565 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3566
3567 if worktree.read(cx).as_local().is_some() {
3568 let buffer_abs_path = buffer_abs_path.unwrap();
3569 let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3570 {
3571 server.clone()
3572 } else {
3573 return Task::ready(Ok(Default::default()));
3574 };
3575
3576 let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3577 cx.foreground().spawn(async move {
3578 if lang_server.capabilities().code_action_provider.is_none() {
3579 return Ok(Default::default());
3580 }
3581
3582 Ok(lang_server
3583 .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3584 text_document: lsp::TextDocumentIdentifier::new(
3585 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3586 ),
3587 range: lsp_range,
3588 work_done_progress_params: Default::default(),
3589 partial_result_params: Default::default(),
3590 context: lsp::CodeActionContext {
3591 diagnostics: relevant_diagnostics,
3592 only: Some(vec![
3593 lsp::CodeActionKind::EMPTY,
3594 lsp::CodeActionKind::QUICKFIX,
3595 lsp::CodeActionKind::REFACTOR,
3596 lsp::CodeActionKind::REFACTOR_EXTRACT,
3597 lsp::CodeActionKind::SOURCE,
3598 ]),
3599 },
3600 })
3601 .await?
3602 .unwrap_or_default()
3603 .into_iter()
3604 .filter_map(|entry| {
3605 if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3606 Some(CodeAction {
3607 range: range.clone(),
3608 lsp_action,
3609 })
3610 } else {
3611 None
3612 }
3613 })
3614 .collect())
3615 })
3616 } else if let Some(project_id) = self.remote_id() {
3617 let rpc = self.client.clone();
3618 let version = buffer.version();
3619 cx.spawn_weak(|_, mut cx| async move {
3620 let response = rpc
3621 .request(proto::GetCodeActions {
3622 project_id,
3623 buffer_id,
3624 start: Some(language::proto::serialize_anchor(&range.start)),
3625 end: Some(language::proto::serialize_anchor(&range.end)),
3626 version: serialize_version(&version),
3627 })
3628 .await?;
3629
3630 buffer_handle
3631 .update(&mut cx, |buffer, _| {
3632 buffer.wait_for_version(deserialize_version(response.version))
3633 })
3634 .await;
3635
3636 response
3637 .actions
3638 .into_iter()
3639 .map(language::proto::deserialize_code_action)
3640 .collect()
3641 })
3642 } else {
3643 Task::ready(Ok(Default::default()))
3644 }
3645 }
3646
3647 pub fn apply_code_action(
3648 &self,
3649 buffer_handle: ModelHandle<Buffer>,
3650 mut action: CodeAction,
3651 push_to_history: bool,
3652 cx: &mut ModelContext<Self>,
3653 ) -> Task<Result<ProjectTransaction>> {
3654 if self.is_local() {
3655 let buffer = buffer_handle.read(cx);
3656 let (lsp_adapter, lang_server) =
3657 if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3658 (adapter.clone(), server.clone())
3659 } else {
3660 return Task::ready(Ok(Default::default()));
3661 };
3662 let range = action.range.to_point_utf16(buffer);
3663
3664 cx.spawn(|this, mut cx| async move {
3665 if let Some(lsp_range) = action
3666 .lsp_action
3667 .data
3668 .as_mut()
3669 .and_then(|d| d.get_mut("codeActionParams"))
3670 .and_then(|d| d.get_mut("range"))
3671 {
3672 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3673 action.lsp_action = lang_server
3674 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3675 .await?;
3676 } else {
3677 let actions = this
3678 .update(&mut cx, |this, cx| {
3679 this.code_actions(&buffer_handle, action.range, cx)
3680 })
3681 .await?;
3682 action.lsp_action = actions
3683 .into_iter()
3684 .find(|a| a.lsp_action.title == action.lsp_action.title)
3685 .ok_or_else(|| anyhow!("code action is outdated"))?
3686 .lsp_action;
3687 }
3688
3689 if let Some(edit) = action.lsp_action.edit {
3690 if edit.changes.is_some() || edit.document_changes.is_some() {
3691 return Self::deserialize_workspace_edit(
3692 this,
3693 edit,
3694 push_to_history,
3695 lsp_adapter.clone(),
3696 lang_server.clone(),
3697 &mut cx,
3698 )
3699 .await;
3700 }
3701 }
3702
3703 if let Some(command) = action.lsp_action.command {
3704 this.update(&mut cx, |this, _| {
3705 this.last_workspace_edits_by_language_server
3706 .remove(&lang_server.server_id());
3707 });
3708 lang_server
3709 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3710 command: command.command,
3711 arguments: command.arguments.unwrap_or_default(),
3712 ..Default::default()
3713 })
3714 .await?;
3715 return Ok(this.update(&mut cx, |this, _| {
3716 this.last_workspace_edits_by_language_server
3717 .remove(&lang_server.server_id())
3718 .unwrap_or_default()
3719 }));
3720 }
3721
3722 Ok(ProjectTransaction::default())
3723 })
3724 } else if let Some(project_id) = self.remote_id() {
3725 let client = self.client.clone();
3726 let request = proto::ApplyCodeAction {
3727 project_id,
3728 buffer_id: buffer_handle.read(cx).remote_id(),
3729 action: Some(language::proto::serialize_code_action(&action)),
3730 };
3731 cx.spawn(|this, mut cx| async move {
3732 let response = client
3733 .request(request)
3734 .await?
3735 .transaction
3736 .ok_or_else(|| anyhow!("missing transaction"))?;
3737 this.update(&mut cx, |this, cx| {
3738 this.deserialize_project_transaction(response, push_to_history, cx)
3739 })
3740 .await
3741 })
3742 } else {
3743 Task::ready(Err(anyhow!("project does not have a remote id")))
3744 }
3745 }
3746
3747 async fn deserialize_workspace_edit(
3748 this: ModelHandle<Self>,
3749 edit: lsp::WorkspaceEdit,
3750 push_to_history: bool,
3751 lsp_adapter: Arc<CachedLspAdapter>,
3752 language_server: Arc<LanguageServer>,
3753 cx: &mut AsyncAppContext,
3754 ) -> Result<ProjectTransaction> {
3755 let fs = this.read_with(cx, |this, _| this.fs.clone());
3756 let mut operations = Vec::new();
3757 if let Some(document_changes) = edit.document_changes {
3758 match document_changes {
3759 lsp::DocumentChanges::Edits(edits) => {
3760 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3761 }
3762 lsp::DocumentChanges::Operations(ops) => operations = ops,
3763 }
3764 } else if let Some(changes) = edit.changes {
3765 operations.extend(changes.into_iter().map(|(uri, edits)| {
3766 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3767 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3768 uri,
3769 version: None,
3770 },
3771 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3772 })
3773 }));
3774 }
3775
3776 let mut project_transaction = ProjectTransaction::default();
3777 for operation in operations {
3778 match operation {
3779 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3780 let abs_path = op
3781 .uri
3782 .to_file_path()
3783 .map_err(|_| anyhow!("can't convert URI to path"))?;
3784
3785 if let Some(parent_path) = abs_path.parent() {
3786 fs.create_dir(parent_path).await?;
3787 }
3788 if abs_path.ends_with("/") {
3789 fs.create_dir(&abs_path).await?;
3790 } else {
3791 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3792 .await?;
3793 }
3794 }
3795 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3796 let source_abs_path = op
3797 .old_uri
3798 .to_file_path()
3799 .map_err(|_| anyhow!("can't convert URI to path"))?;
3800 let target_abs_path = op
3801 .new_uri
3802 .to_file_path()
3803 .map_err(|_| anyhow!("can't convert URI to path"))?;
3804 fs.rename(
3805 &source_abs_path,
3806 &target_abs_path,
3807 op.options.map(Into::into).unwrap_or_default(),
3808 )
3809 .await?;
3810 }
3811 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3812 let abs_path = op
3813 .uri
3814 .to_file_path()
3815 .map_err(|_| anyhow!("can't convert URI to path"))?;
3816 let options = op.options.map(Into::into).unwrap_or_default();
3817 if abs_path.ends_with("/") {
3818 fs.remove_dir(&abs_path, options).await?;
3819 } else {
3820 fs.remove_file(&abs_path, options).await?;
3821 }
3822 }
3823 lsp::DocumentChangeOperation::Edit(op) => {
3824 let buffer_to_edit = this
3825 .update(cx, |this, cx| {
3826 this.open_local_buffer_via_lsp(
3827 op.text_document.uri,
3828 language_server.server_id(),
3829 lsp_adapter.name.clone(),
3830 cx,
3831 )
3832 })
3833 .await?;
3834
3835 let edits = this
3836 .update(cx, |this, cx| {
3837 let edits = op.edits.into_iter().map(|edit| match edit {
3838 lsp::OneOf::Left(edit) => edit,
3839 lsp::OneOf::Right(edit) => edit.text_edit,
3840 });
3841 this.edits_from_lsp(
3842 &buffer_to_edit,
3843 edits,
3844 op.text_document.version,
3845 cx,
3846 )
3847 })
3848 .await?;
3849
3850 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3851 buffer.finalize_last_transaction();
3852 buffer.start_transaction();
3853 for (range, text) in edits {
3854 buffer.edit([(range, text)], None, cx);
3855 }
3856 let transaction = if buffer.end_transaction(cx).is_some() {
3857 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3858 if !push_to_history {
3859 buffer.forget_transaction(transaction.id);
3860 }
3861 Some(transaction)
3862 } else {
3863 None
3864 };
3865
3866 transaction
3867 });
3868 if let Some(transaction) = transaction {
3869 project_transaction.0.insert(buffer_to_edit, transaction);
3870 }
3871 }
3872 }
3873 }
3874
3875 Ok(project_transaction)
3876 }
3877
3878 pub fn prepare_rename<T: ToPointUtf16>(
3879 &self,
3880 buffer: ModelHandle<Buffer>,
3881 position: T,
3882 cx: &mut ModelContext<Self>,
3883 ) -> Task<Result<Option<Range<Anchor>>>> {
3884 let position = position.to_point_utf16(buffer.read(cx));
3885 self.request_lsp(buffer, PrepareRename { position }, cx)
3886 }
3887
3888 pub fn perform_rename<T: ToPointUtf16>(
3889 &self,
3890 buffer: ModelHandle<Buffer>,
3891 position: T,
3892 new_name: String,
3893 push_to_history: bool,
3894 cx: &mut ModelContext<Self>,
3895 ) -> Task<Result<ProjectTransaction>> {
3896 let position = position.to_point_utf16(buffer.read(cx));
3897 self.request_lsp(
3898 buffer,
3899 PerformRename {
3900 position,
3901 new_name,
3902 push_to_history,
3903 },
3904 cx,
3905 )
3906 }
3907
3908 #[allow(clippy::type_complexity)]
3909 pub fn search(
3910 &self,
3911 query: SearchQuery,
3912 cx: &mut ModelContext<Self>,
3913 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
3914 if self.is_local() {
3915 let snapshots = self
3916 .visible_worktrees(cx)
3917 .filter_map(|tree| {
3918 let tree = tree.read(cx).as_local()?;
3919 Some(tree.snapshot())
3920 })
3921 .collect::<Vec<_>>();
3922
3923 let background = cx.background().clone();
3924 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
3925 if path_count == 0 {
3926 return Task::ready(Ok(Default::default()));
3927 }
3928 let workers = background.num_cpus().min(path_count);
3929 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
3930 cx.background()
3931 .spawn({
3932 let fs = self.fs.clone();
3933 let background = cx.background().clone();
3934 let query = query.clone();
3935 async move {
3936 let fs = &fs;
3937 let query = &query;
3938 let matching_paths_tx = &matching_paths_tx;
3939 let paths_per_worker = (path_count + workers - 1) / workers;
3940 let snapshots = &snapshots;
3941 background
3942 .scoped(|scope| {
3943 for worker_ix in 0..workers {
3944 let worker_start_ix = worker_ix * paths_per_worker;
3945 let worker_end_ix = worker_start_ix + paths_per_worker;
3946 scope.spawn(async move {
3947 let mut snapshot_start_ix = 0;
3948 let mut abs_path = PathBuf::new();
3949 for snapshot in snapshots {
3950 let snapshot_end_ix =
3951 snapshot_start_ix + snapshot.visible_file_count();
3952 if worker_end_ix <= snapshot_start_ix {
3953 break;
3954 } else if worker_start_ix > snapshot_end_ix {
3955 snapshot_start_ix = snapshot_end_ix;
3956 continue;
3957 } else {
3958 let start_in_snapshot = worker_start_ix
3959 .saturating_sub(snapshot_start_ix);
3960 let end_in_snapshot =
3961 cmp::min(worker_end_ix, snapshot_end_ix)
3962 - snapshot_start_ix;
3963
3964 for entry in snapshot
3965 .files(false, start_in_snapshot)
3966 .take(end_in_snapshot - start_in_snapshot)
3967 {
3968 if matching_paths_tx.is_closed() {
3969 break;
3970 }
3971
3972 abs_path.clear();
3973 abs_path.push(&snapshot.abs_path());
3974 abs_path.push(&entry.path);
3975 let matches = if let Some(file) =
3976 fs.open_sync(&abs_path).await.log_err()
3977 {
3978 query.detect(file).unwrap_or(false)
3979 } else {
3980 false
3981 };
3982
3983 if matches {
3984 let project_path =
3985 (snapshot.id(), entry.path.clone());
3986 if matching_paths_tx
3987 .send(project_path)
3988 .await
3989 .is_err()
3990 {
3991 break;
3992 }
3993 }
3994 }
3995
3996 snapshot_start_ix = snapshot_end_ix;
3997 }
3998 }
3999 });
4000 }
4001 })
4002 .await;
4003 }
4004 })
4005 .detach();
4006
4007 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4008 let open_buffers = self
4009 .opened_buffers
4010 .values()
4011 .filter_map(|b| b.upgrade(cx))
4012 .collect::<HashSet<_>>();
4013 cx.spawn(|this, cx| async move {
4014 for buffer in &open_buffers {
4015 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4016 buffers_tx.send((buffer.clone(), snapshot)).await?;
4017 }
4018
4019 let open_buffers = Rc::new(RefCell::new(open_buffers));
4020 while let Some(project_path) = matching_paths_rx.next().await {
4021 if buffers_tx.is_closed() {
4022 break;
4023 }
4024
4025 let this = this.clone();
4026 let open_buffers = open_buffers.clone();
4027 let buffers_tx = buffers_tx.clone();
4028 cx.spawn(|mut cx| async move {
4029 if let Some(buffer) = this
4030 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4031 .await
4032 .log_err()
4033 {
4034 if open_buffers.borrow_mut().insert(buffer.clone()) {
4035 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4036 buffers_tx.send((buffer, snapshot)).await?;
4037 }
4038 }
4039
4040 Ok::<_, anyhow::Error>(())
4041 })
4042 .detach();
4043 }
4044
4045 Ok::<_, anyhow::Error>(())
4046 })
4047 .detach_and_log_err(cx);
4048
4049 let background = cx.background().clone();
4050 cx.background().spawn(async move {
4051 let query = &query;
4052 let mut matched_buffers = Vec::new();
4053 for _ in 0..workers {
4054 matched_buffers.push(HashMap::default());
4055 }
4056 background
4057 .scoped(|scope| {
4058 for worker_matched_buffers in matched_buffers.iter_mut() {
4059 let mut buffers_rx = buffers_rx.clone();
4060 scope.spawn(async move {
4061 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4062 let buffer_matches = query
4063 .search(snapshot.as_rope())
4064 .await
4065 .iter()
4066 .map(|range| {
4067 snapshot.anchor_before(range.start)
4068 ..snapshot.anchor_after(range.end)
4069 })
4070 .collect::<Vec<_>>();
4071 if !buffer_matches.is_empty() {
4072 worker_matched_buffers
4073 .insert(buffer.clone(), buffer_matches);
4074 }
4075 }
4076 });
4077 }
4078 })
4079 .await;
4080 Ok(matched_buffers.into_iter().flatten().collect())
4081 })
4082 } else if let Some(project_id) = self.remote_id() {
4083 let request = self.client.request(query.to_proto(project_id));
4084 cx.spawn(|this, mut cx| async move {
4085 let response = request.await?;
4086 let mut result = HashMap::default();
4087 for location in response.locations {
4088 let target_buffer = this
4089 .update(&mut cx, |this, cx| {
4090 this.wait_for_buffer(location.buffer_id, cx)
4091 })
4092 .await?;
4093 let start = location
4094 .start
4095 .and_then(deserialize_anchor)
4096 .ok_or_else(|| anyhow!("missing target start"))?;
4097 let end = location
4098 .end
4099 .and_then(deserialize_anchor)
4100 .ok_or_else(|| anyhow!("missing target end"))?;
4101 result
4102 .entry(target_buffer)
4103 .or_insert(Vec::new())
4104 .push(start..end)
4105 }
4106 Ok(result)
4107 })
4108 } else {
4109 Task::ready(Ok(Default::default()))
4110 }
4111 }
4112
4113 fn request_lsp<R: LspCommand>(
4114 &self,
4115 buffer_handle: ModelHandle<Buffer>,
4116 request: R,
4117 cx: &mut ModelContext<Self>,
4118 ) -> Task<Result<R::Response>>
4119 where
4120 <R::LspRequest as lsp::request::Request>::Result: Send,
4121 {
4122 let buffer = buffer_handle.read(cx);
4123 if self.is_local() {
4124 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4125 if let Some((file, language_server)) = file.zip(
4126 self.language_server_for_buffer(buffer, cx)
4127 .map(|(_, server)| server.clone()),
4128 ) {
4129 let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4130 return cx.spawn(|this, cx| async move {
4131 if !request.check_capabilities(language_server.capabilities()) {
4132 return Ok(Default::default());
4133 }
4134
4135 let response = language_server
4136 .request::<R::LspRequest>(lsp_params)
4137 .await
4138 .context("lsp request failed")?;
4139 request
4140 .response_from_lsp(response, this, buffer_handle, cx)
4141 .await
4142 });
4143 }
4144 } else if let Some(project_id) = self.remote_id() {
4145 let rpc = self.client.clone();
4146 let message = request.to_proto(project_id, buffer);
4147 return cx.spawn(|this, cx| async move {
4148 let response = rpc.request(message).await?;
4149 request
4150 .response_from_proto(response, this, buffer_handle, cx)
4151 .await
4152 });
4153 }
4154 Task::ready(Ok(Default::default()))
4155 }
4156
4157 pub fn find_or_create_local_worktree(
4158 &mut self,
4159 abs_path: impl AsRef<Path>,
4160 visible: bool,
4161 cx: &mut ModelContext<Self>,
4162 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4163 let abs_path = abs_path.as_ref();
4164 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4165 Task::ready(Ok((tree, relative_path)))
4166 } else {
4167 let worktree = self.create_local_worktree(abs_path, visible, cx);
4168 cx.foreground()
4169 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4170 }
4171 }
4172
4173 pub fn find_local_worktree(
4174 &self,
4175 abs_path: &Path,
4176 cx: &AppContext,
4177 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4178 for tree in &self.worktrees {
4179 if let Some(tree) = tree.upgrade(cx) {
4180 if let Some(relative_path) = tree
4181 .read(cx)
4182 .as_local()
4183 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4184 {
4185 return Some((tree.clone(), relative_path.into()));
4186 }
4187 }
4188 }
4189 None
4190 }
4191
4192 pub fn is_shared(&self) -> bool {
4193 match &self.client_state {
4194 Some(ProjectClientState::Local { .. }) => true,
4195 _ => false,
4196 }
4197 }
4198
4199 fn create_local_worktree(
4200 &mut self,
4201 abs_path: impl AsRef<Path>,
4202 visible: bool,
4203 cx: &mut ModelContext<Self>,
4204 ) -> Task<Result<ModelHandle<Worktree>>> {
4205 let fs = self.fs.clone();
4206 let client = self.client.clone();
4207 let next_entry_id = self.next_entry_id.clone();
4208 let path: Arc<Path> = abs_path.as_ref().into();
4209 let task = self
4210 .loading_local_worktrees
4211 .entry(path.clone())
4212 .or_insert_with(|| {
4213 cx.spawn(|project, mut cx| {
4214 async move {
4215 let worktree = Worktree::local(
4216 client.clone(),
4217 path.clone(),
4218 visible,
4219 fs,
4220 next_entry_id,
4221 &mut cx,
4222 )
4223 .await;
4224 project.update(&mut cx, |project, _| {
4225 project.loading_local_worktrees.remove(&path);
4226 });
4227 let worktree = worktree?;
4228
4229 let project_id = project.update(&mut cx, |project, cx| {
4230 project.add_worktree(&worktree, cx);
4231 project.remote_id()
4232 });
4233
4234 if let Some(project_id) = project_id {
4235 worktree
4236 .update(&mut cx, |worktree, cx| {
4237 worktree.as_local_mut().unwrap().share(project_id, cx)
4238 })
4239 .await
4240 .log_err();
4241 }
4242
4243 Ok(worktree)
4244 }
4245 .map_err(Arc::new)
4246 })
4247 .shared()
4248 })
4249 .clone();
4250 cx.foreground().spawn(async move {
4251 match task.await {
4252 Ok(worktree) => Ok(worktree),
4253 Err(err) => Err(anyhow!("{}", err)),
4254 }
4255 })
4256 }
4257
4258 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4259 self.worktrees.retain(|worktree| {
4260 if let Some(worktree) = worktree.upgrade(cx) {
4261 let id = worktree.read(cx).id();
4262 if id == id_to_remove {
4263 cx.emit(Event::WorktreeRemoved(id));
4264 false
4265 } else {
4266 true
4267 }
4268 } else {
4269 false
4270 }
4271 });
4272 self.metadata_changed(cx);
4273 cx.notify();
4274 }
4275
4276 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4277 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4278 if worktree.read(cx).is_local() {
4279 cx.subscribe(worktree, |this, worktree, event, cx| match event {
4280 worktree::Event::UpdatedEntries => this.update_local_worktree_buffers(worktree, cx),
4281 worktree::Event::UpdatedGitRepositories(updated_repos) => {
4282 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4283 }
4284 })
4285 .detach();
4286 }
4287
4288 let push_strong_handle = {
4289 let worktree = worktree.read(cx);
4290 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4291 };
4292 if push_strong_handle {
4293 self.worktrees
4294 .push(WorktreeHandle::Strong(worktree.clone()));
4295 } else {
4296 self.worktrees
4297 .push(WorktreeHandle::Weak(worktree.downgrade()));
4298 }
4299
4300 self.metadata_changed(cx);
4301 cx.observe_release(worktree, |this, worktree, cx| {
4302 this.remove_worktree(worktree.id(), cx);
4303 cx.notify();
4304 })
4305 .detach();
4306
4307 cx.emit(Event::WorktreeAdded);
4308 cx.notify();
4309 }
4310
4311 fn update_local_worktree_buffers(
4312 &mut self,
4313 worktree_handle: ModelHandle<Worktree>,
4314 cx: &mut ModelContext<Self>,
4315 ) {
4316 let snapshot = worktree_handle.read(cx).snapshot();
4317 let mut buffers_to_delete = Vec::new();
4318 let mut renamed_buffers = Vec::new();
4319 for (buffer_id, buffer) in &self.opened_buffers {
4320 if let Some(buffer) = buffer.upgrade(cx) {
4321 buffer.update(cx, |buffer, cx| {
4322 if let Some(old_file) = File::from_dyn(buffer.file()) {
4323 if old_file.worktree != worktree_handle {
4324 return;
4325 }
4326
4327 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4328 {
4329 File {
4330 is_local: true,
4331 entry_id: entry.id,
4332 mtime: entry.mtime,
4333 path: entry.path.clone(),
4334 worktree: worktree_handle.clone(),
4335 is_deleted: false,
4336 }
4337 } else if let Some(entry) =
4338 snapshot.entry_for_path(old_file.path().as_ref())
4339 {
4340 File {
4341 is_local: true,
4342 entry_id: entry.id,
4343 mtime: entry.mtime,
4344 path: entry.path.clone(),
4345 worktree: worktree_handle.clone(),
4346 is_deleted: false,
4347 }
4348 } else {
4349 File {
4350 is_local: true,
4351 entry_id: old_file.entry_id,
4352 path: old_file.path().clone(),
4353 mtime: old_file.mtime(),
4354 worktree: worktree_handle.clone(),
4355 is_deleted: true,
4356 }
4357 };
4358
4359 let old_path = old_file.abs_path(cx);
4360 if new_file.abs_path(cx) != old_path {
4361 renamed_buffers.push((cx.handle(), old_path));
4362 }
4363
4364 if let Some(project_id) = self.remote_id() {
4365 self.client
4366 .send(proto::UpdateBufferFile {
4367 project_id,
4368 buffer_id: *buffer_id as u64,
4369 file: Some(new_file.to_proto()),
4370 })
4371 .log_err();
4372 }
4373 buffer.file_updated(Arc::new(new_file), cx).detach();
4374 }
4375 });
4376 } else {
4377 buffers_to_delete.push(*buffer_id);
4378 }
4379 }
4380
4381 for buffer_id in buffers_to_delete {
4382 self.opened_buffers.remove(&buffer_id);
4383 }
4384
4385 for (buffer, old_path) in renamed_buffers {
4386 self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4387 self.assign_language_to_buffer(&buffer, cx);
4388 self.register_buffer_with_language_server(&buffer, cx);
4389 }
4390 }
4391
4392 fn update_local_worktree_buffers_git_repos(
4393 &mut self,
4394 worktree: ModelHandle<Worktree>,
4395 repos: &[GitRepositoryEntry],
4396 cx: &mut ModelContext<Self>,
4397 ) {
4398 for (_, buffer) in &self.opened_buffers {
4399 if let Some(buffer) = buffer.upgrade(cx) {
4400 let file = match File::from_dyn(buffer.read(cx).file()) {
4401 Some(file) => file,
4402 None => continue,
4403 };
4404 if file.worktree != worktree {
4405 continue;
4406 }
4407
4408 let path = file.path().clone();
4409
4410 let repo = match repos.iter().find(|repo| repo.manages(&path)) {
4411 Some(repo) => repo.clone(),
4412 None => return,
4413 };
4414
4415 let relative_repo = match path.strip_prefix(repo.content_path) {
4416 Ok(relative_repo) => relative_repo.to_owned(),
4417 Err(_) => return,
4418 };
4419
4420 let remote_id = self.remote_id();
4421 let client = self.client.clone();
4422
4423 cx.spawn(|_, mut cx| async move {
4424 let diff_base = cx
4425 .background()
4426 .spawn(async move { repo.repo.lock().load_index_text(&relative_repo) })
4427 .await;
4428
4429 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4430 buffer.set_diff_base(diff_base.clone(), cx);
4431 buffer.remote_id()
4432 });
4433
4434 if let Some(project_id) = remote_id {
4435 client
4436 .send(proto::UpdateDiffBase {
4437 project_id,
4438 buffer_id: buffer_id as u64,
4439 diff_base,
4440 })
4441 .log_err();
4442 }
4443 })
4444 .detach();
4445 }
4446 }
4447 }
4448
4449 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4450 let new_active_entry = entry.and_then(|project_path| {
4451 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4452 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4453 Some(entry.id)
4454 });
4455 if new_active_entry != self.active_entry {
4456 self.active_entry = new_active_entry;
4457 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4458 }
4459 }
4460
4461 pub fn language_servers_running_disk_based_diagnostics(
4462 &self,
4463 ) -> impl Iterator<Item = usize> + '_ {
4464 self.language_server_statuses
4465 .iter()
4466 .filter_map(|(id, status)| {
4467 if status.has_pending_diagnostic_updates {
4468 Some(*id)
4469 } else {
4470 None
4471 }
4472 })
4473 }
4474
4475 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4476 let mut summary = DiagnosticSummary::default();
4477 for (_, path_summary) in self.diagnostic_summaries(cx) {
4478 summary.error_count += path_summary.error_count;
4479 summary.warning_count += path_summary.warning_count;
4480 }
4481 summary
4482 }
4483
4484 pub fn diagnostic_summaries<'a>(
4485 &'a self,
4486 cx: &'a AppContext,
4487 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4488 self.visible_worktrees(cx).flat_map(move |worktree| {
4489 let worktree = worktree.read(cx);
4490 let worktree_id = worktree.id();
4491 worktree
4492 .diagnostic_summaries()
4493 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4494 })
4495 }
4496
4497 pub fn disk_based_diagnostics_started(
4498 &mut self,
4499 language_server_id: usize,
4500 cx: &mut ModelContext<Self>,
4501 ) {
4502 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4503 }
4504
4505 pub fn disk_based_diagnostics_finished(
4506 &mut self,
4507 language_server_id: usize,
4508 cx: &mut ModelContext<Self>,
4509 ) {
4510 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4511 }
4512
4513 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4514 self.active_entry
4515 }
4516
4517 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4518 self.worktree_for_id(path.worktree_id, cx)?
4519 .read(cx)
4520 .entry_for_path(&path.path)
4521 .cloned()
4522 }
4523
4524 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4525 let worktree = self.worktree_for_entry(entry_id, cx)?;
4526 let worktree = worktree.read(cx);
4527 let worktree_id = worktree.id();
4528 let path = worktree.entry_for_id(entry_id)?.path.clone();
4529 Some(ProjectPath { worktree_id, path })
4530 }
4531
4532 // RPC message handlers
4533
4534 async fn handle_unshare_project(
4535 this: ModelHandle<Self>,
4536 _: TypedEnvelope<proto::UnshareProject>,
4537 _: Arc<Client>,
4538 mut cx: AsyncAppContext,
4539 ) -> Result<()> {
4540 this.update(&mut cx, |this, cx| {
4541 if this.is_local() {
4542 this.unshare(cx)?;
4543 } else {
4544 this.disconnected_from_host(cx);
4545 }
4546 Ok(())
4547 })
4548 }
4549
4550 async fn handle_add_collaborator(
4551 this: ModelHandle<Self>,
4552 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4553 _: Arc<Client>,
4554 mut cx: AsyncAppContext,
4555 ) -> Result<()> {
4556 let collaborator = envelope
4557 .payload
4558 .collaborator
4559 .take()
4560 .ok_or_else(|| anyhow!("empty collaborator"))?;
4561
4562 let collaborator = Collaborator::from_proto(collaborator);
4563 this.update(&mut cx, |this, cx| {
4564 this.collaborators
4565 .insert(collaborator.peer_id, collaborator);
4566 cx.notify();
4567 });
4568
4569 Ok(())
4570 }
4571
4572 async fn handle_remove_collaborator(
4573 this: ModelHandle<Self>,
4574 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4575 _: Arc<Client>,
4576 mut cx: AsyncAppContext,
4577 ) -> Result<()> {
4578 this.update(&mut cx, |this, cx| {
4579 let peer_id = PeerId(envelope.payload.peer_id);
4580 let replica_id = this
4581 .collaborators
4582 .remove(&peer_id)
4583 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4584 .replica_id;
4585 for buffer in this.opened_buffers.values() {
4586 if let Some(buffer) = buffer.upgrade(cx) {
4587 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4588 }
4589 }
4590 this.shared_buffers.remove(&peer_id);
4591
4592 cx.emit(Event::CollaboratorLeft(peer_id));
4593 cx.notify();
4594 Ok(())
4595 })
4596 }
4597
4598 async fn handle_update_project(
4599 this: ModelHandle<Self>,
4600 envelope: TypedEnvelope<proto::UpdateProject>,
4601 client: Arc<Client>,
4602 mut cx: AsyncAppContext,
4603 ) -> Result<()> {
4604 this.update(&mut cx, |this, cx| {
4605 let replica_id = this.replica_id();
4606 let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4607
4608 let mut old_worktrees_by_id = this
4609 .worktrees
4610 .drain(..)
4611 .filter_map(|worktree| {
4612 let worktree = worktree.upgrade(cx)?;
4613 Some((worktree.read(cx).id(), worktree))
4614 })
4615 .collect::<HashMap<_, _>>();
4616
4617 for worktree in envelope.payload.worktrees {
4618 if let Some(old_worktree) =
4619 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4620 {
4621 this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4622 } else {
4623 let worktree =
4624 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4625 this.add_worktree(&worktree, cx);
4626 }
4627 }
4628
4629 this.metadata_changed(cx);
4630 for (id, _) in old_worktrees_by_id {
4631 cx.emit(Event::WorktreeRemoved(id));
4632 }
4633
4634 Ok(())
4635 })
4636 }
4637
4638 async fn handle_update_worktree(
4639 this: ModelHandle<Self>,
4640 envelope: TypedEnvelope<proto::UpdateWorktree>,
4641 _: Arc<Client>,
4642 mut cx: AsyncAppContext,
4643 ) -> Result<()> {
4644 this.update(&mut cx, |this, cx| {
4645 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4646 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4647 worktree.update(cx, |worktree, _| {
4648 let worktree = worktree.as_remote_mut().unwrap();
4649 worktree.update_from_remote(envelope.payload);
4650 });
4651 }
4652 Ok(())
4653 })
4654 }
4655
4656 async fn handle_create_project_entry(
4657 this: ModelHandle<Self>,
4658 envelope: TypedEnvelope<proto::CreateProjectEntry>,
4659 _: Arc<Client>,
4660 mut cx: AsyncAppContext,
4661 ) -> Result<proto::ProjectEntryResponse> {
4662 let worktree = this.update(&mut cx, |this, cx| {
4663 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4664 this.worktree_for_id(worktree_id, cx)
4665 .ok_or_else(|| anyhow!("worktree not found"))
4666 })?;
4667 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4668 let entry = worktree
4669 .update(&mut cx, |worktree, cx| {
4670 let worktree = worktree.as_local_mut().unwrap();
4671 let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4672 worktree.create_entry(path, envelope.payload.is_directory, cx)
4673 })
4674 .await?;
4675 Ok(proto::ProjectEntryResponse {
4676 entry: Some((&entry).into()),
4677 worktree_scan_id: worktree_scan_id as u64,
4678 })
4679 }
4680
4681 async fn handle_rename_project_entry(
4682 this: ModelHandle<Self>,
4683 envelope: TypedEnvelope<proto::RenameProjectEntry>,
4684 _: Arc<Client>,
4685 mut cx: AsyncAppContext,
4686 ) -> Result<proto::ProjectEntryResponse> {
4687 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4688 let worktree = this.read_with(&cx, |this, cx| {
4689 this.worktree_for_entry(entry_id, cx)
4690 .ok_or_else(|| anyhow!("worktree not found"))
4691 })?;
4692 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4693 let entry = worktree
4694 .update(&mut cx, |worktree, cx| {
4695 let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4696 worktree
4697 .as_local_mut()
4698 .unwrap()
4699 .rename_entry(entry_id, new_path, cx)
4700 .ok_or_else(|| anyhow!("invalid entry"))
4701 })?
4702 .await?;
4703 Ok(proto::ProjectEntryResponse {
4704 entry: Some((&entry).into()),
4705 worktree_scan_id: worktree_scan_id as u64,
4706 })
4707 }
4708
4709 async fn handle_copy_project_entry(
4710 this: ModelHandle<Self>,
4711 envelope: TypedEnvelope<proto::CopyProjectEntry>,
4712 _: Arc<Client>,
4713 mut cx: AsyncAppContext,
4714 ) -> Result<proto::ProjectEntryResponse> {
4715 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4716 let worktree = this.read_with(&cx, |this, cx| {
4717 this.worktree_for_entry(entry_id, cx)
4718 .ok_or_else(|| anyhow!("worktree not found"))
4719 })?;
4720 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4721 let entry = worktree
4722 .update(&mut cx, |worktree, cx| {
4723 let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4724 worktree
4725 .as_local_mut()
4726 .unwrap()
4727 .copy_entry(entry_id, new_path, cx)
4728 .ok_or_else(|| anyhow!("invalid entry"))
4729 })?
4730 .await?;
4731 Ok(proto::ProjectEntryResponse {
4732 entry: Some((&entry).into()),
4733 worktree_scan_id: worktree_scan_id as u64,
4734 })
4735 }
4736
4737 async fn handle_delete_project_entry(
4738 this: ModelHandle<Self>,
4739 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4740 _: Arc<Client>,
4741 mut cx: AsyncAppContext,
4742 ) -> Result<proto::ProjectEntryResponse> {
4743 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4744 let worktree = this.read_with(&cx, |this, cx| {
4745 this.worktree_for_entry(entry_id, cx)
4746 .ok_or_else(|| anyhow!("worktree not found"))
4747 })?;
4748 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4749 worktree
4750 .update(&mut cx, |worktree, cx| {
4751 worktree
4752 .as_local_mut()
4753 .unwrap()
4754 .delete_entry(entry_id, cx)
4755 .ok_or_else(|| anyhow!("invalid entry"))
4756 })?
4757 .await?;
4758 Ok(proto::ProjectEntryResponse {
4759 entry: None,
4760 worktree_scan_id: worktree_scan_id as u64,
4761 })
4762 }
4763
4764 async fn handle_update_diagnostic_summary(
4765 this: ModelHandle<Self>,
4766 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4767 _: Arc<Client>,
4768 mut cx: AsyncAppContext,
4769 ) -> Result<()> {
4770 this.update(&mut cx, |this, cx| {
4771 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4772 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4773 if let Some(summary) = envelope.payload.summary {
4774 let project_path = ProjectPath {
4775 worktree_id,
4776 path: Path::new(&summary.path).into(),
4777 };
4778 worktree.update(cx, |worktree, _| {
4779 worktree
4780 .as_remote_mut()
4781 .unwrap()
4782 .update_diagnostic_summary(project_path.path.clone(), &summary);
4783 });
4784 cx.emit(Event::DiagnosticsUpdated {
4785 language_server_id: summary.language_server_id as usize,
4786 path: project_path,
4787 });
4788 }
4789 }
4790 Ok(())
4791 })
4792 }
4793
4794 async fn handle_start_language_server(
4795 this: ModelHandle<Self>,
4796 envelope: TypedEnvelope<proto::StartLanguageServer>,
4797 _: Arc<Client>,
4798 mut cx: AsyncAppContext,
4799 ) -> Result<()> {
4800 let server = envelope
4801 .payload
4802 .server
4803 .ok_or_else(|| anyhow!("invalid server"))?;
4804 this.update(&mut cx, |this, cx| {
4805 this.language_server_statuses.insert(
4806 server.id as usize,
4807 LanguageServerStatus {
4808 name: server.name,
4809 pending_work: Default::default(),
4810 has_pending_diagnostic_updates: false,
4811 progress_tokens: Default::default(),
4812 },
4813 );
4814 cx.notify();
4815 });
4816 Ok(())
4817 }
4818
4819 async fn handle_update_language_server(
4820 this: ModelHandle<Self>,
4821 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4822 _: Arc<Client>,
4823 mut cx: AsyncAppContext,
4824 ) -> Result<()> {
4825 let language_server_id = envelope.payload.language_server_id as usize;
4826 match envelope
4827 .payload
4828 .variant
4829 .ok_or_else(|| anyhow!("invalid variant"))?
4830 {
4831 proto::update_language_server::Variant::WorkStart(payload) => {
4832 this.update(&mut cx, |this, cx| {
4833 this.on_lsp_work_start(
4834 language_server_id,
4835 payload.token,
4836 LanguageServerProgress {
4837 message: payload.message,
4838 percentage: payload.percentage.map(|p| p as usize),
4839 last_update_at: Instant::now(),
4840 },
4841 cx,
4842 );
4843 })
4844 }
4845 proto::update_language_server::Variant::WorkProgress(payload) => {
4846 this.update(&mut cx, |this, cx| {
4847 this.on_lsp_work_progress(
4848 language_server_id,
4849 payload.token,
4850 LanguageServerProgress {
4851 message: payload.message,
4852 percentage: payload.percentage.map(|p| p as usize),
4853 last_update_at: Instant::now(),
4854 },
4855 cx,
4856 );
4857 })
4858 }
4859 proto::update_language_server::Variant::WorkEnd(payload) => {
4860 this.update(&mut cx, |this, cx| {
4861 this.on_lsp_work_end(language_server_id, payload.token, cx);
4862 })
4863 }
4864 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
4865 this.update(&mut cx, |this, cx| {
4866 this.disk_based_diagnostics_started(language_server_id, cx);
4867 })
4868 }
4869 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
4870 this.update(&mut cx, |this, cx| {
4871 this.disk_based_diagnostics_finished(language_server_id, cx)
4872 });
4873 }
4874 }
4875
4876 Ok(())
4877 }
4878
4879 async fn handle_update_buffer(
4880 this: ModelHandle<Self>,
4881 envelope: TypedEnvelope<proto::UpdateBuffer>,
4882 _: Arc<Client>,
4883 mut cx: AsyncAppContext,
4884 ) -> Result<()> {
4885 this.update(&mut cx, |this, cx| {
4886 let payload = envelope.payload.clone();
4887 let buffer_id = payload.buffer_id;
4888 let ops = payload
4889 .operations
4890 .into_iter()
4891 .map(language::proto::deserialize_operation)
4892 .collect::<Result<Vec<_>, _>>()?;
4893 let is_remote = this.is_remote();
4894 match this.opened_buffers.entry(buffer_id) {
4895 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
4896 OpenBuffer::Strong(buffer) => {
4897 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
4898 }
4899 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
4900 OpenBuffer::Weak(_) => {}
4901 },
4902 hash_map::Entry::Vacant(e) => {
4903 assert!(
4904 is_remote,
4905 "received buffer update from {:?}",
4906 envelope.original_sender_id
4907 );
4908 e.insert(OpenBuffer::Operations(ops));
4909 }
4910 }
4911 Ok(())
4912 })
4913 }
4914
4915 async fn handle_create_buffer_for_peer(
4916 this: ModelHandle<Self>,
4917 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4918 _: Arc<Client>,
4919 mut cx: AsyncAppContext,
4920 ) -> Result<()> {
4921 this.update(&mut cx, |this, cx| {
4922 match envelope
4923 .payload
4924 .variant
4925 .ok_or_else(|| anyhow!("missing variant"))?
4926 {
4927 proto::create_buffer_for_peer::Variant::State(mut state) => {
4928 let mut buffer_file = None;
4929 if let Some(file) = state.file.take() {
4930 let worktree_id = WorktreeId::from_proto(file.worktree_id);
4931 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
4932 anyhow!("no worktree found for id {}", file.worktree_id)
4933 })?;
4934 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
4935 as Arc<dyn language::File>);
4936 }
4937
4938 let buffer_id = state.id;
4939 let buffer = cx.add_model(|_| {
4940 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
4941 });
4942 this.incomplete_buffers.insert(buffer_id, buffer);
4943 }
4944 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
4945 let buffer = this
4946 .incomplete_buffers
4947 .get(&chunk.buffer_id)
4948 .ok_or_else(|| {
4949 anyhow!(
4950 "received chunk for buffer {} without initial state",
4951 chunk.buffer_id
4952 )
4953 })?
4954 .clone();
4955 let operations = chunk
4956 .operations
4957 .into_iter()
4958 .map(language::proto::deserialize_operation)
4959 .collect::<Result<Vec<_>>>()?;
4960 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
4961
4962 if chunk.is_last {
4963 this.incomplete_buffers.remove(&chunk.buffer_id);
4964 this.register_buffer(&buffer, cx)?;
4965 }
4966 }
4967 }
4968
4969 Ok(())
4970 })
4971 }
4972
4973 async fn handle_update_diff_base(
4974 this: ModelHandle<Self>,
4975 envelope: TypedEnvelope<proto::UpdateDiffBase>,
4976 _: Arc<Client>,
4977 mut cx: AsyncAppContext,
4978 ) -> Result<()> {
4979 this.update(&mut cx, |this, cx| {
4980 let buffer_id = envelope.payload.buffer_id;
4981 let diff_base = envelope.payload.diff_base;
4982 let buffer = this
4983 .opened_buffers
4984 .get_mut(&buffer_id)
4985 .and_then(|b| b.upgrade(cx))
4986 .ok_or_else(|| anyhow!("No such buffer {}", buffer_id))?;
4987
4988 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
4989
4990 Ok(())
4991 })
4992 }
4993
4994 async fn handle_update_buffer_file(
4995 this: ModelHandle<Self>,
4996 envelope: TypedEnvelope<proto::UpdateBufferFile>,
4997 _: Arc<Client>,
4998 mut cx: AsyncAppContext,
4999 ) -> Result<()> {
5000 this.update(&mut cx, |this, cx| {
5001 let payload = envelope.payload.clone();
5002 let buffer_id = payload.buffer_id;
5003 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5004 let worktree = this
5005 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5006 .ok_or_else(|| anyhow!("no such worktree"))?;
5007 let file = File::from_proto(file, worktree, cx)?;
5008 let buffer = this
5009 .opened_buffers
5010 .get_mut(&buffer_id)
5011 .and_then(|b| b.upgrade(cx))
5012 .ok_or_else(|| anyhow!("no such buffer"))?;
5013 buffer.update(cx, |buffer, cx| {
5014 buffer.file_updated(Arc::new(file), cx).detach();
5015 });
5016 this.assign_language_to_buffer(&buffer, cx);
5017 Ok(())
5018 })
5019 }
5020
5021 async fn handle_save_buffer(
5022 this: ModelHandle<Self>,
5023 envelope: TypedEnvelope<proto::SaveBuffer>,
5024 _: Arc<Client>,
5025 mut cx: AsyncAppContext,
5026 ) -> Result<proto::BufferSaved> {
5027 let buffer_id = envelope.payload.buffer_id;
5028 let requested_version = deserialize_version(envelope.payload.version);
5029
5030 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5031 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5032 let buffer = this
5033 .opened_buffers
5034 .get(&buffer_id)
5035 .and_then(|buffer| buffer.upgrade(cx))
5036 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5037 Ok::<_, anyhow::Error>((project_id, buffer))
5038 })?;
5039 buffer
5040 .update(&mut cx, |buffer, _| {
5041 buffer.wait_for_version(requested_version)
5042 })
5043 .await;
5044
5045 let (saved_version, fingerprint, mtime) =
5046 buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5047 Ok(proto::BufferSaved {
5048 project_id,
5049 buffer_id,
5050 version: serialize_version(&saved_version),
5051 mtime: Some(mtime.into()),
5052 fingerprint,
5053 })
5054 }
5055
5056 async fn handle_reload_buffers(
5057 this: ModelHandle<Self>,
5058 envelope: TypedEnvelope<proto::ReloadBuffers>,
5059 _: Arc<Client>,
5060 mut cx: AsyncAppContext,
5061 ) -> Result<proto::ReloadBuffersResponse> {
5062 let sender_id = envelope.original_sender_id()?;
5063 let reload = this.update(&mut cx, |this, cx| {
5064 let mut buffers = HashSet::default();
5065 for buffer_id in &envelope.payload.buffer_ids {
5066 buffers.insert(
5067 this.opened_buffers
5068 .get(buffer_id)
5069 .and_then(|buffer| buffer.upgrade(cx))
5070 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5071 );
5072 }
5073 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5074 })?;
5075
5076 let project_transaction = reload.await?;
5077 let project_transaction = this.update(&mut cx, |this, cx| {
5078 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5079 });
5080 Ok(proto::ReloadBuffersResponse {
5081 transaction: Some(project_transaction),
5082 })
5083 }
5084
5085 async fn handle_format_buffers(
5086 this: ModelHandle<Self>,
5087 envelope: TypedEnvelope<proto::FormatBuffers>,
5088 _: Arc<Client>,
5089 mut cx: AsyncAppContext,
5090 ) -> Result<proto::FormatBuffersResponse> {
5091 let sender_id = envelope.original_sender_id()?;
5092 let format = this.update(&mut cx, |this, cx| {
5093 let mut buffers = HashSet::default();
5094 for buffer_id in &envelope.payload.buffer_ids {
5095 buffers.insert(
5096 this.opened_buffers
5097 .get(buffer_id)
5098 .and_then(|buffer| buffer.upgrade(cx))
5099 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5100 );
5101 }
5102 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5103 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5104 })?;
5105
5106 let project_transaction = format.await?;
5107 let project_transaction = this.update(&mut cx, |this, cx| {
5108 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5109 });
5110 Ok(proto::FormatBuffersResponse {
5111 transaction: Some(project_transaction),
5112 })
5113 }
5114
5115 async fn handle_get_completions(
5116 this: ModelHandle<Self>,
5117 envelope: TypedEnvelope<proto::GetCompletions>,
5118 _: Arc<Client>,
5119 mut cx: AsyncAppContext,
5120 ) -> Result<proto::GetCompletionsResponse> {
5121 let position = envelope
5122 .payload
5123 .position
5124 .and_then(language::proto::deserialize_anchor)
5125 .ok_or_else(|| anyhow!("invalid position"))?;
5126 let version = deserialize_version(envelope.payload.version);
5127 let buffer = this.read_with(&cx, |this, cx| {
5128 this.opened_buffers
5129 .get(&envelope.payload.buffer_id)
5130 .and_then(|buffer| buffer.upgrade(cx))
5131 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5132 })?;
5133 buffer
5134 .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5135 .await;
5136 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5137 let completions = this
5138 .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5139 .await?;
5140
5141 Ok(proto::GetCompletionsResponse {
5142 completions: completions
5143 .iter()
5144 .map(language::proto::serialize_completion)
5145 .collect(),
5146 version: serialize_version(&version),
5147 })
5148 }
5149
5150 async fn handle_apply_additional_edits_for_completion(
5151 this: ModelHandle<Self>,
5152 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5153 _: Arc<Client>,
5154 mut cx: AsyncAppContext,
5155 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5156 let (buffer, completion) = this.update(&mut cx, |this, cx| {
5157 let buffer = this
5158 .opened_buffers
5159 .get(&envelope.payload.buffer_id)
5160 .and_then(|buffer| buffer.upgrade(cx))
5161 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5162 let language = buffer.read(cx).language();
5163 let completion = language::proto::deserialize_completion(
5164 envelope
5165 .payload
5166 .completion
5167 .ok_or_else(|| anyhow!("invalid completion"))?,
5168 language.cloned(),
5169 );
5170 Ok::<_, anyhow::Error>((buffer, completion))
5171 })?;
5172
5173 let completion = completion.await?;
5174
5175 let apply_additional_edits = this.update(&mut cx, |this, cx| {
5176 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5177 });
5178
5179 Ok(proto::ApplyCompletionAdditionalEditsResponse {
5180 transaction: apply_additional_edits
5181 .await?
5182 .as_ref()
5183 .map(language::proto::serialize_transaction),
5184 })
5185 }
5186
5187 async fn handle_get_code_actions(
5188 this: ModelHandle<Self>,
5189 envelope: TypedEnvelope<proto::GetCodeActions>,
5190 _: Arc<Client>,
5191 mut cx: AsyncAppContext,
5192 ) -> Result<proto::GetCodeActionsResponse> {
5193 let start = envelope
5194 .payload
5195 .start
5196 .and_then(language::proto::deserialize_anchor)
5197 .ok_or_else(|| anyhow!("invalid start"))?;
5198 let end = envelope
5199 .payload
5200 .end
5201 .and_then(language::proto::deserialize_anchor)
5202 .ok_or_else(|| anyhow!("invalid end"))?;
5203 let buffer = this.update(&mut cx, |this, cx| {
5204 this.opened_buffers
5205 .get(&envelope.payload.buffer_id)
5206 .and_then(|buffer| buffer.upgrade(cx))
5207 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5208 })?;
5209 buffer
5210 .update(&mut cx, |buffer, _| {
5211 buffer.wait_for_version(deserialize_version(envelope.payload.version))
5212 })
5213 .await;
5214
5215 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5216 let code_actions = this.update(&mut cx, |this, cx| {
5217 Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5218 })?;
5219
5220 Ok(proto::GetCodeActionsResponse {
5221 actions: code_actions
5222 .await?
5223 .iter()
5224 .map(language::proto::serialize_code_action)
5225 .collect(),
5226 version: serialize_version(&version),
5227 })
5228 }
5229
5230 async fn handle_apply_code_action(
5231 this: ModelHandle<Self>,
5232 envelope: TypedEnvelope<proto::ApplyCodeAction>,
5233 _: Arc<Client>,
5234 mut cx: AsyncAppContext,
5235 ) -> Result<proto::ApplyCodeActionResponse> {
5236 let sender_id = envelope.original_sender_id()?;
5237 let action = language::proto::deserialize_code_action(
5238 envelope
5239 .payload
5240 .action
5241 .ok_or_else(|| anyhow!("invalid action"))?,
5242 )?;
5243 let apply_code_action = this.update(&mut cx, |this, cx| {
5244 let buffer = this
5245 .opened_buffers
5246 .get(&envelope.payload.buffer_id)
5247 .and_then(|buffer| buffer.upgrade(cx))
5248 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5249 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5250 })?;
5251
5252 let project_transaction = apply_code_action.await?;
5253 let project_transaction = this.update(&mut cx, |this, cx| {
5254 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5255 });
5256 Ok(proto::ApplyCodeActionResponse {
5257 transaction: Some(project_transaction),
5258 })
5259 }
5260
5261 async fn handle_lsp_command<T: LspCommand>(
5262 this: ModelHandle<Self>,
5263 envelope: TypedEnvelope<T::ProtoRequest>,
5264 _: Arc<Client>,
5265 mut cx: AsyncAppContext,
5266 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5267 where
5268 <T::LspRequest as lsp::request::Request>::Result: Send,
5269 {
5270 let sender_id = envelope.original_sender_id()?;
5271 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5272 let buffer_handle = this.read_with(&cx, |this, _| {
5273 this.opened_buffers
5274 .get(&buffer_id)
5275 .and_then(|buffer| buffer.upgrade(&cx))
5276 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5277 })?;
5278 let request = T::from_proto(
5279 envelope.payload,
5280 this.clone(),
5281 buffer_handle.clone(),
5282 cx.clone(),
5283 )
5284 .await?;
5285 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5286 let response = this
5287 .update(&mut cx, |this, cx| {
5288 this.request_lsp(buffer_handle, request, cx)
5289 })
5290 .await?;
5291 this.update(&mut cx, |this, cx| {
5292 Ok(T::response_to_proto(
5293 response,
5294 this,
5295 sender_id,
5296 &buffer_version,
5297 cx,
5298 ))
5299 })
5300 }
5301
5302 async fn handle_get_project_symbols(
5303 this: ModelHandle<Self>,
5304 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5305 _: Arc<Client>,
5306 mut cx: AsyncAppContext,
5307 ) -> Result<proto::GetProjectSymbolsResponse> {
5308 let symbols = this
5309 .update(&mut cx, |this, cx| {
5310 this.symbols(&envelope.payload.query, cx)
5311 })
5312 .await?;
5313
5314 Ok(proto::GetProjectSymbolsResponse {
5315 symbols: symbols.iter().map(serialize_symbol).collect(),
5316 })
5317 }
5318
5319 async fn handle_search_project(
5320 this: ModelHandle<Self>,
5321 envelope: TypedEnvelope<proto::SearchProject>,
5322 _: Arc<Client>,
5323 mut cx: AsyncAppContext,
5324 ) -> Result<proto::SearchProjectResponse> {
5325 let peer_id = envelope.original_sender_id()?;
5326 let query = SearchQuery::from_proto(envelope.payload)?;
5327 let result = this
5328 .update(&mut cx, |this, cx| this.search(query, cx))
5329 .await?;
5330
5331 this.update(&mut cx, |this, cx| {
5332 let mut locations = Vec::new();
5333 for (buffer, ranges) in result {
5334 for range in ranges {
5335 let start = serialize_anchor(&range.start);
5336 let end = serialize_anchor(&range.end);
5337 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5338 locations.push(proto::Location {
5339 buffer_id,
5340 start: Some(start),
5341 end: Some(end),
5342 });
5343 }
5344 }
5345 Ok(proto::SearchProjectResponse { locations })
5346 })
5347 }
5348
5349 async fn handle_open_buffer_for_symbol(
5350 this: ModelHandle<Self>,
5351 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5352 _: Arc<Client>,
5353 mut cx: AsyncAppContext,
5354 ) -> Result<proto::OpenBufferForSymbolResponse> {
5355 let peer_id = envelope.original_sender_id()?;
5356 let symbol = envelope
5357 .payload
5358 .symbol
5359 .ok_or_else(|| anyhow!("invalid symbol"))?;
5360 let symbol = this
5361 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5362 .await?;
5363 let symbol = this.read_with(&cx, |this, _| {
5364 let signature = this.symbol_signature(&symbol.path);
5365 if signature == symbol.signature {
5366 Ok(symbol)
5367 } else {
5368 Err(anyhow!("invalid symbol signature"))
5369 }
5370 })?;
5371 let buffer = this
5372 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5373 .await?;
5374
5375 Ok(proto::OpenBufferForSymbolResponse {
5376 buffer_id: this.update(&mut cx, |this, cx| {
5377 this.create_buffer_for_peer(&buffer, peer_id, cx)
5378 }),
5379 })
5380 }
5381
5382 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5383 let mut hasher = Sha256::new();
5384 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5385 hasher.update(project_path.path.to_string_lossy().as_bytes());
5386 hasher.update(self.nonce.to_be_bytes());
5387 hasher.finalize().as_slice().try_into().unwrap()
5388 }
5389
5390 async fn handle_open_buffer_by_id(
5391 this: ModelHandle<Self>,
5392 envelope: TypedEnvelope<proto::OpenBufferById>,
5393 _: Arc<Client>,
5394 mut cx: AsyncAppContext,
5395 ) -> Result<proto::OpenBufferResponse> {
5396 let peer_id = envelope.original_sender_id()?;
5397 let buffer = this
5398 .update(&mut cx, |this, cx| {
5399 this.open_buffer_by_id(envelope.payload.id, cx)
5400 })
5401 .await?;
5402 this.update(&mut cx, |this, cx| {
5403 Ok(proto::OpenBufferResponse {
5404 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5405 })
5406 })
5407 }
5408
5409 async fn handle_open_buffer_by_path(
5410 this: ModelHandle<Self>,
5411 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5412 _: Arc<Client>,
5413 mut cx: AsyncAppContext,
5414 ) -> Result<proto::OpenBufferResponse> {
5415 let peer_id = envelope.original_sender_id()?;
5416 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5417 let open_buffer = this.update(&mut cx, |this, cx| {
5418 this.open_buffer(
5419 ProjectPath {
5420 worktree_id,
5421 path: PathBuf::from(envelope.payload.path).into(),
5422 },
5423 cx,
5424 )
5425 });
5426
5427 let buffer = open_buffer.await?;
5428 this.update(&mut cx, |this, cx| {
5429 Ok(proto::OpenBufferResponse {
5430 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5431 })
5432 })
5433 }
5434
5435 fn serialize_project_transaction_for_peer(
5436 &mut self,
5437 project_transaction: ProjectTransaction,
5438 peer_id: PeerId,
5439 cx: &AppContext,
5440 ) -> proto::ProjectTransaction {
5441 let mut serialized_transaction = proto::ProjectTransaction {
5442 buffer_ids: Default::default(),
5443 transactions: Default::default(),
5444 };
5445 for (buffer, transaction) in project_transaction.0 {
5446 serialized_transaction
5447 .buffer_ids
5448 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5449 serialized_transaction
5450 .transactions
5451 .push(language::proto::serialize_transaction(&transaction));
5452 }
5453 serialized_transaction
5454 }
5455
5456 fn deserialize_project_transaction(
5457 &mut self,
5458 message: proto::ProjectTransaction,
5459 push_to_history: bool,
5460 cx: &mut ModelContext<Self>,
5461 ) -> Task<Result<ProjectTransaction>> {
5462 cx.spawn(|this, mut cx| async move {
5463 let mut project_transaction = ProjectTransaction::default();
5464 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5465 {
5466 let buffer = this
5467 .update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
5468 .await?;
5469 let transaction = language::proto::deserialize_transaction(transaction)?;
5470 project_transaction.0.insert(buffer, transaction);
5471 }
5472
5473 for (buffer, transaction) in &project_transaction.0 {
5474 buffer
5475 .update(&mut cx, |buffer, _| {
5476 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5477 })
5478 .await;
5479
5480 if push_to_history {
5481 buffer.update(&mut cx, |buffer, _| {
5482 buffer.push_transaction(transaction.clone(), Instant::now());
5483 });
5484 }
5485 }
5486
5487 Ok(project_transaction)
5488 })
5489 }
5490
5491 fn create_buffer_for_peer(
5492 &mut self,
5493 buffer: &ModelHandle<Buffer>,
5494 peer_id: PeerId,
5495 cx: &AppContext,
5496 ) -> u64 {
5497 let buffer_id = buffer.read(cx).remote_id();
5498 if let Some(project_id) = self.remote_id() {
5499 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5500 if shared_buffers.insert(buffer_id) {
5501 let buffer = buffer.read(cx);
5502 let state = buffer.to_proto();
5503 let operations = buffer.serialize_ops(cx);
5504 let client = self.client.clone();
5505 cx.background()
5506 .spawn(
5507 async move {
5508 let mut operations = operations.await;
5509
5510 client.send(proto::CreateBufferForPeer {
5511 project_id,
5512 peer_id: peer_id.0,
5513 variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
5514 })?;
5515
5516 loop {
5517 #[cfg(any(test, feature = "test-support"))]
5518 const CHUNK_SIZE: usize = 5;
5519
5520 #[cfg(not(any(test, feature = "test-support")))]
5521 const CHUNK_SIZE: usize = 100;
5522
5523 let chunk = operations
5524 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
5525 .collect();
5526 let is_last = operations.is_empty();
5527 client.send(proto::CreateBufferForPeer {
5528 project_id,
5529 peer_id: peer_id.0,
5530 variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
5531 proto::BufferChunk {
5532 buffer_id,
5533 operations: chunk,
5534 is_last,
5535 },
5536 )),
5537 })?;
5538
5539 if is_last {
5540 break;
5541 }
5542 }
5543
5544 Ok(())
5545 }
5546 .log_err(),
5547 )
5548 .detach();
5549 }
5550 }
5551
5552 buffer_id
5553 }
5554
5555 fn wait_for_buffer(
5556 &self,
5557 id: u64,
5558 cx: &mut ModelContext<Self>,
5559 ) -> Task<Result<ModelHandle<Buffer>>> {
5560 let mut opened_buffer_rx = self.opened_buffer.1.clone();
5561 cx.spawn(|this, mut cx| async move {
5562 let buffer = loop {
5563 let buffer = this.read_with(&cx, |this, cx| {
5564 this.opened_buffers
5565 .get(&id)
5566 .and_then(|buffer| buffer.upgrade(cx))
5567 });
5568 if let Some(buffer) = buffer {
5569 break buffer;
5570 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5571 return Err(anyhow!("disconnected before buffer {} could be opened", id));
5572 }
5573
5574 opened_buffer_rx
5575 .next()
5576 .await
5577 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5578 };
5579 buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5580 Ok(buffer)
5581 })
5582 }
5583
5584 fn deserialize_symbol(
5585 &self,
5586 serialized_symbol: proto::Symbol,
5587 ) -> impl Future<Output = Result<Symbol>> {
5588 let languages = self.languages.clone();
5589 async move {
5590 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5591 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5592 let start = serialized_symbol
5593 .start
5594 .ok_or_else(|| anyhow!("invalid start"))?;
5595 let end = serialized_symbol
5596 .end
5597 .ok_or_else(|| anyhow!("invalid end"))?;
5598 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5599 let path = ProjectPath {
5600 worktree_id,
5601 path: PathBuf::from(serialized_symbol.path).into(),
5602 };
5603 let language = languages.select_language(&path.path);
5604 Ok(Symbol {
5605 language_server_name: LanguageServerName(
5606 serialized_symbol.language_server_name.into(),
5607 ),
5608 source_worktree_id,
5609 path,
5610 label: {
5611 match language {
5612 Some(language) => {
5613 language
5614 .label_for_symbol(&serialized_symbol.name, kind)
5615 .await
5616 }
5617 None => None,
5618 }
5619 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5620 },
5621
5622 name: serialized_symbol.name,
5623 range: PointUtf16::new(start.row, start.column)
5624 ..PointUtf16::new(end.row, end.column),
5625 kind,
5626 signature: serialized_symbol
5627 .signature
5628 .try_into()
5629 .map_err(|_| anyhow!("invalid signature"))?,
5630 })
5631 }
5632 }
5633
5634 async fn handle_buffer_saved(
5635 this: ModelHandle<Self>,
5636 envelope: TypedEnvelope<proto::BufferSaved>,
5637 _: Arc<Client>,
5638 mut cx: AsyncAppContext,
5639 ) -> Result<()> {
5640 let version = deserialize_version(envelope.payload.version);
5641 let mtime = envelope
5642 .payload
5643 .mtime
5644 .ok_or_else(|| anyhow!("missing mtime"))?
5645 .into();
5646
5647 this.update(&mut cx, |this, cx| {
5648 let buffer = this
5649 .opened_buffers
5650 .get(&envelope.payload.buffer_id)
5651 .and_then(|buffer| buffer.upgrade(cx));
5652 if let Some(buffer) = buffer {
5653 buffer.update(cx, |buffer, cx| {
5654 buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5655 });
5656 }
5657 Ok(())
5658 })
5659 }
5660
5661 async fn handle_buffer_reloaded(
5662 this: ModelHandle<Self>,
5663 envelope: TypedEnvelope<proto::BufferReloaded>,
5664 _: Arc<Client>,
5665 mut cx: AsyncAppContext,
5666 ) -> Result<()> {
5667 let payload = envelope.payload;
5668 let version = deserialize_version(payload.version);
5669 let line_ending = deserialize_line_ending(
5670 proto::LineEnding::from_i32(payload.line_ending)
5671 .ok_or_else(|| anyhow!("missing line ending"))?,
5672 );
5673 let mtime = payload
5674 .mtime
5675 .ok_or_else(|| anyhow!("missing mtime"))?
5676 .into();
5677 this.update(&mut cx, |this, cx| {
5678 let buffer = this
5679 .opened_buffers
5680 .get(&payload.buffer_id)
5681 .and_then(|buffer| buffer.upgrade(cx));
5682 if let Some(buffer) = buffer {
5683 buffer.update(cx, |buffer, cx| {
5684 buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5685 });
5686 }
5687 Ok(())
5688 })
5689 }
5690
5691 #[allow(clippy::type_complexity)]
5692 fn edits_from_lsp(
5693 &mut self,
5694 buffer: &ModelHandle<Buffer>,
5695 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5696 version: Option<i32>,
5697 cx: &mut ModelContext<Self>,
5698 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5699 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5700 cx.background().spawn(async move {
5701 let snapshot = snapshot?;
5702 let mut lsp_edits = lsp_edits
5703 .into_iter()
5704 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5705 .collect::<Vec<_>>();
5706 lsp_edits.sort_by_key(|(range, _)| range.start);
5707
5708 let mut lsp_edits = lsp_edits.into_iter().peekable();
5709 let mut edits = Vec::new();
5710 while let Some((mut range, mut new_text)) = lsp_edits.next() {
5711 // Clip invalid ranges provided by the language server.
5712 range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
5713 range.end = snapshot.clip_point_utf16(range.end, Bias::Left);
5714
5715 // Combine any LSP edits that are adjacent.
5716 //
5717 // Also, combine LSP edits that are separated from each other by only
5718 // a newline. This is important because for some code actions,
5719 // Rust-analyzer rewrites the entire buffer via a series of edits that
5720 // are separated by unchanged newline characters.
5721 //
5722 // In order for the diffing logic below to work properly, any edits that
5723 // cancel each other out must be combined into one.
5724 while let Some((next_range, next_text)) = lsp_edits.peek() {
5725 if next_range.start > range.end {
5726 if next_range.start.row > range.end.row + 1
5727 || next_range.start.column > 0
5728 || snapshot.clip_point_utf16(
5729 PointUtf16::new(range.end.row, u32::MAX),
5730 Bias::Left,
5731 ) > range.end
5732 {
5733 break;
5734 }
5735 new_text.push('\n');
5736 }
5737 range.end = next_range.end;
5738 new_text.push_str(next_text);
5739 lsp_edits.next();
5740 }
5741
5742 // For multiline edits, perform a diff of the old and new text so that
5743 // we can identify the changes more precisely, preserving the locations
5744 // of any anchors positioned in the unchanged regions.
5745 if range.end.row > range.start.row {
5746 let mut offset = range.start.to_offset_clamped(&snapshot);
5747 let old_text = snapshot.text_for_clamped_range(range).collect::<String>();
5748
5749 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5750 let mut moved_since_edit = true;
5751 for change in diff.iter_all_changes() {
5752 let tag = change.tag();
5753 let value = change.value();
5754 match tag {
5755 ChangeTag::Equal => {
5756 offset += value.len();
5757 moved_since_edit = true;
5758 }
5759 ChangeTag::Delete => {
5760 let start = snapshot.anchor_after(offset);
5761 let end = snapshot.anchor_before(offset + value.len());
5762 if moved_since_edit {
5763 edits.push((start..end, String::new()));
5764 } else {
5765 edits.last_mut().unwrap().0.end = end;
5766 }
5767 offset += value.len();
5768 moved_since_edit = false;
5769 }
5770 ChangeTag::Insert => {
5771 if moved_since_edit {
5772 let anchor = snapshot.anchor_after(offset);
5773 edits.push((anchor..anchor, value.to_string()));
5774 } else {
5775 edits.last_mut().unwrap().1.push_str(value);
5776 }
5777 moved_since_edit = false;
5778 }
5779 }
5780 }
5781 } else if range.end == range.start {
5782 let anchor = snapshot.clamped_anchor_after(range.start);
5783 edits.push((anchor..anchor, new_text));
5784 } else {
5785 let edit_start = snapshot.clamped_anchor_after(range.start);
5786 let edit_end = snapshot.clamped_anchor_before(range.end);
5787 edits.push((edit_start..edit_end, new_text));
5788 }
5789 }
5790
5791 Ok(edits)
5792 })
5793 }
5794
5795 fn buffer_snapshot_for_lsp_version(
5796 &mut self,
5797 buffer: &ModelHandle<Buffer>,
5798 version: Option<i32>,
5799 cx: &AppContext,
5800 ) -> Result<TextBufferSnapshot> {
5801 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5802
5803 if let Some(version) = version {
5804 let buffer_id = buffer.read(cx).remote_id();
5805 let snapshots = self
5806 .buffer_snapshots
5807 .get_mut(&buffer_id)
5808 .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
5809 let mut found_snapshot = None;
5810 snapshots.retain(|(snapshot_version, snapshot)| {
5811 if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
5812 false
5813 } else {
5814 if *snapshot_version == version {
5815 found_snapshot = Some(snapshot.clone());
5816 }
5817 true
5818 }
5819 });
5820
5821 found_snapshot.ok_or_else(|| {
5822 anyhow!(
5823 "snapshot not found for buffer {} at version {}",
5824 buffer_id,
5825 version
5826 )
5827 })
5828 } else {
5829 Ok((buffer.read(cx)).text_snapshot())
5830 }
5831 }
5832
5833 fn language_server_for_buffer(
5834 &self,
5835 buffer: &Buffer,
5836 cx: &AppContext,
5837 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
5838 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5839 let name = language.lsp_adapter()?.name.clone();
5840 let worktree_id = file.worktree_id(cx);
5841 let key = (worktree_id, name);
5842
5843 if let Some(server_id) = self.language_server_ids.get(&key) {
5844 if let Some(LanguageServerState::Running {
5845 adapter, server, ..
5846 }) = self.language_servers.get(server_id)
5847 {
5848 return Some((adapter, server));
5849 }
5850 }
5851 }
5852
5853 None
5854 }
5855}
5856
5857impl ProjectStore {
5858 pub fn new() -> Self {
5859 Self {
5860 projects: Default::default(),
5861 }
5862 }
5863
5864 pub fn projects<'a>(
5865 &'a self,
5866 cx: &'a AppContext,
5867 ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
5868 self.projects
5869 .iter()
5870 .filter_map(|project| project.upgrade(cx))
5871 }
5872
5873 fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
5874 if let Err(ix) = self
5875 .projects
5876 .binary_search_by_key(&project.id(), WeakModelHandle::id)
5877 {
5878 self.projects.insert(ix, project);
5879 }
5880 cx.notify();
5881 }
5882
5883 fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
5884 let mut did_change = false;
5885 self.projects.retain(|project| {
5886 if project.is_upgradable(cx) {
5887 true
5888 } else {
5889 did_change = true;
5890 false
5891 }
5892 });
5893 if did_change {
5894 cx.notify();
5895 }
5896 }
5897}
5898
5899impl WorktreeHandle {
5900 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
5901 match self {
5902 WorktreeHandle::Strong(handle) => Some(handle.clone()),
5903 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
5904 }
5905 }
5906}
5907
5908impl OpenBuffer {
5909 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
5910 match self {
5911 OpenBuffer::Strong(handle) => Some(handle.clone()),
5912 OpenBuffer::Weak(handle) => handle.upgrade(cx),
5913 OpenBuffer::Operations(_) => None,
5914 }
5915 }
5916}
5917
5918pub struct PathMatchCandidateSet {
5919 pub snapshot: Snapshot,
5920 pub include_ignored: bool,
5921 pub include_root_name: bool,
5922}
5923
5924impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5925 type Candidates = PathMatchCandidateSetIter<'a>;
5926
5927 fn id(&self) -> usize {
5928 self.snapshot.id().to_usize()
5929 }
5930
5931 fn len(&self) -> usize {
5932 if self.include_ignored {
5933 self.snapshot.file_count()
5934 } else {
5935 self.snapshot.visible_file_count()
5936 }
5937 }
5938
5939 fn prefix(&self) -> Arc<str> {
5940 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5941 self.snapshot.root_name().into()
5942 } else if self.include_root_name {
5943 format!("{}/", self.snapshot.root_name()).into()
5944 } else {
5945 "".into()
5946 }
5947 }
5948
5949 fn candidates(&'a self, start: usize) -> Self::Candidates {
5950 PathMatchCandidateSetIter {
5951 traversal: self.snapshot.files(self.include_ignored, start),
5952 }
5953 }
5954}
5955
5956pub struct PathMatchCandidateSetIter<'a> {
5957 traversal: Traversal<'a>,
5958}
5959
5960impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5961 type Item = fuzzy::PathMatchCandidate<'a>;
5962
5963 fn next(&mut self) -> Option<Self::Item> {
5964 self.traversal.next().map(|entry| {
5965 if let EntryKind::File(char_bag) = entry.kind {
5966 fuzzy::PathMatchCandidate {
5967 path: &entry.path,
5968 char_bag,
5969 }
5970 } else {
5971 unreachable!()
5972 }
5973 })
5974 }
5975}
5976
5977impl Entity for ProjectStore {
5978 type Event = ();
5979}
5980
5981impl Entity for Project {
5982 type Event = Event;
5983
5984 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
5985 self.project_store.update(cx, ProjectStore::prune_projects);
5986
5987 match &self.client_state {
5988 Some(ProjectClientState::Local { remote_id, .. }) => {
5989 self.client
5990 .send(proto::UnshareProject {
5991 project_id: *remote_id,
5992 })
5993 .log_err();
5994 }
5995 Some(ProjectClientState::Remote { remote_id, .. }) => {
5996 self.client
5997 .send(proto::LeaveProject {
5998 project_id: *remote_id,
5999 })
6000 .log_err();
6001 }
6002 _ => {}
6003 }
6004 }
6005
6006 fn app_will_quit(
6007 &mut self,
6008 _: &mut MutableAppContext,
6009 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6010 let shutdown_futures = self
6011 .language_servers
6012 .drain()
6013 .map(|(_, server_state)| async {
6014 match server_state {
6015 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6016 LanguageServerState::Starting(starting_server) => {
6017 starting_server.await?.shutdown()?.await
6018 }
6019 }
6020 })
6021 .collect::<Vec<_>>();
6022
6023 Some(
6024 async move {
6025 futures::future::join_all(shutdown_futures).await;
6026 }
6027 .boxed(),
6028 )
6029 }
6030}
6031
6032impl Collaborator {
6033 fn from_proto(message: proto::Collaborator) -> Self {
6034 Self {
6035 peer_id: PeerId(message.peer_id),
6036 replica_id: message.replica_id as ReplicaId,
6037 }
6038 }
6039}
6040
6041impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6042 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6043 Self {
6044 worktree_id,
6045 path: path.as_ref().into(),
6046 }
6047 }
6048}
6049
6050fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6051 proto::Symbol {
6052 language_server_name: symbol.language_server_name.0.to_string(),
6053 source_worktree_id: symbol.source_worktree_id.to_proto(),
6054 worktree_id: symbol.path.worktree_id.to_proto(),
6055 path: symbol.path.path.to_string_lossy().to_string(),
6056 name: symbol.name.clone(),
6057 kind: unsafe { mem::transmute(symbol.kind) },
6058 start: Some(proto::Point {
6059 row: symbol.range.start.row,
6060 column: symbol.range.start.column,
6061 }),
6062 end: Some(proto::Point {
6063 row: symbol.range.end.row,
6064 column: symbol.range.end.column,
6065 }),
6066 signature: symbol.signature.to_vec(),
6067 }
6068}
6069
6070fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6071 let mut path_components = path.components();
6072 let mut base_components = base.components();
6073 let mut components: Vec<Component> = Vec::new();
6074 loop {
6075 match (path_components.next(), base_components.next()) {
6076 (None, None) => break,
6077 (Some(a), None) => {
6078 components.push(a);
6079 components.extend(path_components.by_ref());
6080 break;
6081 }
6082 (None, _) => components.push(Component::ParentDir),
6083 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6084 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6085 (Some(a), Some(_)) => {
6086 components.push(Component::ParentDir);
6087 for _ in base_components {
6088 components.push(Component::ParentDir);
6089 }
6090 components.push(a);
6091 components.extend(path_components.by_ref());
6092 break;
6093 }
6094 }
6095 }
6096 components.iter().map(|c| c.as_os_str()).collect()
6097}
6098
6099impl Item for Buffer {
6100 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6101 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6102 }
6103}