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