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