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