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