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