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