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