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