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