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