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