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