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