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