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, Entity, ModelContext, ModelHandle, Task,
23 UpgradeModelHandle, 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, 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<usize, LanguageServerState>,
99 language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
100 language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
101 last_workspace_edits_by_language_server: HashMap<usize, 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<usize, 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: usize,
193 },
194 DiskBasedDiagnosticsFinished {
195 language_server_id: usize,
196 },
197 DiagnosticsUpdated {
198 path: ProjectPath,
199 language_server_id: usize,
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 language_server_id: usize,
247 pub error_count: usize,
248 pub warning_count: usize,
249}
250
251#[derive(Debug, Clone)]
252pub struct Location {
253 pub buffer: ModelHandle<Buffer>,
254 pub range: Range<language::Anchor>,
255}
256
257#[derive(Debug, Clone)]
258pub struct LocationLink {
259 pub origin: Option<Location>,
260 pub target: Location,
261}
262
263#[derive(Debug)]
264pub struct DocumentHighlight {
265 pub range: Range<language::Anchor>,
266 pub kind: DocumentHighlightKind,
267}
268
269#[derive(Clone, Debug)]
270pub struct Symbol {
271 pub language_server_name: LanguageServerName,
272 pub source_worktree_id: WorktreeId,
273 pub path: ProjectPath,
274 pub label: CodeLabel,
275 pub name: String,
276 pub kind: lsp::SymbolKind,
277 pub range: Range<Unclipped<PointUtf16>>,
278 pub signature: [u8; 32],
279}
280
281#[derive(Clone, Debug, PartialEq)]
282pub struct HoverBlock {
283 pub text: String,
284 pub language: Option<String>,
285}
286
287impl HoverBlock {
288 fn try_new(marked_string: MarkedString) -> Option<Self> {
289 let result = match marked_string {
290 MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
291 text: value,
292 language: Some(language),
293 },
294 MarkedString::String(text) => HoverBlock {
295 text,
296 language: None,
297 },
298 };
299 if result.text.is_empty() {
300 None
301 } else {
302 Some(result)
303 }
304 }
305}
306
307#[derive(Debug)]
308pub struct Hover {
309 pub contents: Vec<HoverBlock>,
310 pub range: Option<Range<language::Anchor>>,
311}
312
313#[derive(Default)]
314pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
315
316impl DiagnosticSummary {
317 fn new<'a, T: 'a>(
318 language_server_id: usize,
319 diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
320 ) -> Self {
321 let mut this = Self {
322 language_server_id,
323 error_count: 0,
324 warning_count: 0,
325 };
326
327 for entry in diagnostics {
328 if entry.diagnostic.is_primary {
329 match entry.diagnostic.severity {
330 DiagnosticSeverity::ERROR => this.error_count += 1,
331 DiagnosticSeverity::WARNING => this.warning_count += 1,
332 _ => {}
333 }
334 }
335 }
336
337 this
338 }
339
340 pub fn is_empty(&self) -> bool {
341 self.error_count == 0 && self.warning_count == 0
342 }
343
344 pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
345 proto::DiagnosticSummary {
346 path: path.to_string_lossy().to_string(),
347 language_server_id: self.language_server_id as u64,
348 error_count: self.error_count as u32,
349 warning_count: self.warning_count as u32,
350 }
351 }
352}
353
354#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
355pub struct ProjectEntryId(usize);
356
357impl ProjectEntryId {
358 pub const MAX: Self = Self(usize::MAX);
359
360 pub fn new(counter: &AtomicUsize) -> Self {
361 Self(counter.fetch_add(1, SeqCst))
362 }
363
364 pub fn from_proto(id: u64) -> Self {
365 Self(id as usize)
366 }
367
368 pub fn to_proto(&self) -> u64 {
369 self.0 as u64
370 }
371
372 pub fn to_usize(&self) -> usize {
373 self.0
374 }
375}
376
377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378pub enum FormatTrigger {
379 Save,
380 Manual,
381}
382
383impl FormatTrigger {
384 fn from_proto(value: i32) -> FormatTrigger {
385 match value {
386 0 => FormatTrigger::Save,
387 1 => FormatTrigger::Manual,
388 _ => FormatTrigger::Save,
389 }
390 }
391}
392
393impl Project {
394 pub fn init(client: &Arc<Client>) {
395 client.add_model_message_handler(Self::handle_add_collaborator);
396 client.add_model_message_handler(Self::handle_update_project_collaborator);
397 client.add_model_message_handler(Self::handle_remove_collaborator);
398 client.add_model_message_handler(Self::handle_buffer_reloaded);
399 client.add_model_message_handler(Self::handle_buffer_saved);
400 client.add_model_message_handler(Self::handle_start_language_server);
401 client.add_model_message_handler(Self::handle_update_language_server);
402 client.add_model_message_handler(Self::handle_update_project);
403 client.add_model_message_handler(Self::handle_unshare_project);
404 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
405 client.add_model_message_handler(Self::handle_update_buffer_file);
406 client.add_model_request_handler(Self::handle_update_buffer);
407 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
408 client.add_model_message_handler(Self::handle_update_worktree);
409 client.add_model_request_handler(Self::handle_create_project_entry);
410 client.add_model_request_handler(Self::handle_rename_project_entry);
411 client.add_model_request_handler(Self::handle_copy_project_entry);
412 client.add_model_request_handler(Self::handle_delete_project_entry);
413 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
414 client.add_model_request_handler(Self::handle_apply_code_action);
415 client.add_model_request_handler(Self::handle_reload_buffers);
416 client.add_model_request_handler(Self::handle_synchronize_buffers);
417 client.add_model_request_handler(Self::handle_format_buffers);
418 client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
419 client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
420 client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
421 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
422 client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
423 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
424 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
425 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
426 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
427 client.add_model_request_handler(Self::handle_search_project);
428 client.add_model_request_handler(Self::handle_get_project_symbols);
429 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
430 client.add_model_request_handler(Self::handle_open_buffer_by_id);
431 client.add_model_request_handler(Self::handle_open_buffer_by_path);
432 client.add_model_request_handler(Self::handle_save_buffer);
433 client.add_model_message_handler(Self::handle_update_diff_base);
434 }
435
436 pub fn local(
437 client: Arc<Client>,
438 user_store: ModelHandle<UserStore>,
439 languages: Arc<LanguageRegistry>,
440 fs: Arc<dyn Fs>,
441 cx: &mut AppContext,
442 ) -> ModelHandle<Self> {
443 cx.add_model(|cx: &mut ModelContext<Self>| {
444 let (tx, rx) = mpsc::unbounded();
445 cx.spawn_weak(|this, cx| Self::send_buffer_messages(this, rx, cx))
446 .detach();
447 Self {
448 worktrees: Default::default(),
449 buffer_changes_tx: tx,
450 collaborators: Default::default(),
451 opened_buffers: Default::default(),
452 shared_buffers: Default::default(),
453 incomplete_remote_buffers: Default::default(),
454 loading_buffers_by_path: Default::default(),
455 loading_local_worktrees: Default::default(),
456 buffer_snapshots: Default::default(),
457 join_project_response_message_id: 0,
458 client_state: None,
459 opened_buffer: watch::channel(),
460 client_subscriptions: Vec::new(),
461 _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
462 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
463 _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
464 active_entry: None,
465 languages,
466 client,
467 user_store,
468 fs,
469 next_entry_id: Default::default(),
470 next_diagnostic_group_id: Default::default(),
471 language_servers: Default::default(),
472 language_server_ids: Default::default(),
473 language_server_statuses: Default::default(),
474 last_workspace_edits_by_language_server: Default::default(),
475 buffers_being_formatted: Default::default(),
476 nonce: StdRng::from_entropy().gen(),
477 terminals: Terminals {
478 local_handles: Vec::new(),
479 },
480 copilot_enabled: Copilot::global(cx).is_some(),
481 }
482 })
483 }
484
485 pub async fn remote(
486 remote_id: u64,
487 client: Arc<Client>,
488 user_store: ModelHandle<UserStore>,
489 languages: Arc<LanguageRegistry>,
490 fs: Arc<dyn Fs>,
491 mut cx: AsyncAppContext,
492 ) -> Result<ModelHandle<Self>> {
493 client.authenticate_and_connect(true, &cx).await?;
494
495 let subscription = client.subscribe_to_entity(remote_id)?;
496 let response = client
497 .request_envelope(proto::JoinProject {
498 project_id: remote_id,
499 })
500 .await?;
501 let this = cx.add_model(|cx| {
502 let replica_id = response.payload.replica_id as ReplicaId;
503
504 let mut worktrees = Vec::new();
505 for worktree in response.payload.worktrees {
506 let worktree = cx.update(|cx| {
507 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
508 });
509 worktrees.push(worktree);
510 }
511
512 let (tx, rx) = mpsc::unbounded();
513 cx.spawn_weak(|this, cx| Self::send_buffer_messages(this, rx, cx))
514 .detach();
515 let mut this = Self {
516 worktrees: Vec::new(),
517 buffer_changes_tx: tx,
518 loading_buffers_by_path: Default::default(),
519 opened_buffer: watch::channel(),
520 shared_buffers: Default::default(),
521 incomplete_remote_buffers: Default::default(),
522 loading_local_worktrees: Default::default(),
523 active_entry: None,
524 collaborators: Default::default(),
525 join_project_response_message_id: response.message_id,
526 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
527 _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
528 languages,
529 user_store: user_store.clone(),
530 fs,
531 next_entry_id: Default::default(),
532 next_diagnostic_group_id: Default::default(),
533 client_subscriptions: Default::default(),
534 _subscriptions: Default::default(),
535 client: client.clone(),
536 client_state: Some(ProjectClientState::Remote {
537 sharing_has_stopped: false,
538 remote_id,
539 replica_id,
540 }),
541 language_servers: Default::default(),
542 language_server_ids: Default::default(),
543 language_server_statuses: response
544 .payload
545 .language_servers
546 .into_iter()
547 .map(|server| {
548 (
549 server.id as usize,
550 LanguageServerStatus {
551 name: server.name,
552 pending_work: Default::default(),
553 has_pending_diagnostic_updates: false,
554 progress_tokens: Default::default(),
555 },
556 )
557 })
558 .collect(),
559 last_workspace_edits_by_language_server: Default::default(),
560 opened_buffers: Default::default(),
561 buffers_being_formatted: Default::default(),
562 buffer_snapshots: Default::default(),
563 nonce: StdRng::from_entropy().gen(),
564 terminals: Terminals {
565 local_handles: Vec::new(),
566 },
567 copilot_enabled: Copilot::global(cx).is_some(),
568 };
569 for worktree in worktrees {
570 let _ = this.add_worktree(&worktree, cx);
571 }
572 this
573 });
574 let subscription = subscription.set_model(&this, &mut cx);
575
576 let user_ids = response
577 .payload
578 .collaborators
579 .iter()
580 .map(|peer| peer.user_id)
581 .collect();
582 user_store
583 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
584 .await?;
585
586 this.update(&mut cx, |this, cx| {
587 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
588 this.client_subscriptions.push(subscription);
589 anyhow::Ok(())
590 })?;
591
592 Ok(this)
593 }
594
595 #[cfg(any(test, feature = "test-support"))]
596 pub async fn test(
597 fs: Arc<dyn Fs>,
598 root_paths: impl IntoIterator<Item = &Path>,
599 cx: &mut gpui::TestAppContext,
600 ) -> ModelHandle<Project> {
601 if !cx.read(|cx| cx.has_global::<Settings>()) {
602 cx.update(|cx| {
603 cx.set_global(Settings::test(cx));
604 });
605 }
606
607 let mut languages = LanguageRegistry::test();
608 languages.set_executor(cx.background());
609 let http_client = util::http::FakeHttpClient::with_404_response();
610 let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
611 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
612 let project =
613 cx.update(|cx| Project::local(client, user_store, Arc::new(languages), fs, cx));
614 for path in root_paths {
615 let (tree, _) = project
616 .update(cx, |project, cx| {
617 project.find_or_create_local_worktree(path, true, cx)
618 })
619 .await
620 .unwrap();
621 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
622 .await;
623 }
624 project
625 }
626
627 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
628 let settings = cx.global::<Settings>();
629
630 let mut language_servers_to_start = Vec::new();
631 for buffer in self.opened_buffers.values() {
632 if let Some(buffer) = buffer.upgrade(cx) {
633 let buffer = buffer.read(cx);
634 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
635 {
636 if settings.enable_language_server(Some(&language.name())) {
637 let worktree = file.worktree.read(cx);
638 language_servers_to_start.push((
639 worktree.id(),
640 worktree.as_local().unwrap().abs_path().clone(),
641 language.clone(),
642 ));
643 }
644 }
645 }
646 }
647
648 let mut language_servers_to_stop = Vec::new();
649 for language in self.languages.to_vec() {
650 for lsp_adapter in language.lsp_adapters() {
651 if !settings.enable_language_server(Some(&language.name())) {
652 let lsp_name = &lsp_adapter.name;
653 for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
654 if lsp_name == started_lsp_name {
655 language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
656 }
657 }
658 }
659 }
660 }
661
662 // Stop all newly-disabled language servers.
663 for (worktree_id, adapter_name) in language_servers_to_stop {
664 self.stop_language_server(worktree_id, adapter_name, cx)
665 .detach();
666 }
667
668 // Start all the newly-enabled language servers.
669 for (worktree_id, worktree_path, language) in language_servers_to_start {
670 self.start_language_servers(worktree_id, worktree_path, language, cx);
671 }
672
673 if !self.copilot_enabled && Copilot::global(cx).is_some() {
674 self.copilot_enabled = true;
675 for buffer in self.opened_buffers.values() {
676 if let Some(buffer) = buffer.upgrade(cx) {
677 self.register_buffer_with_copilot(&buffer, cx);
678 }
679 }
680 }
681
682 cx.notify();
683 }
684
685 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
686 self.opened_buffers
687 .get(&remote_id)
688 .and_then(|buffer| buffer.upgrade(cx))
689 }
690
691 pub fn languages(&self) -> &Arc<LanguageRegistry> {
692 &self.languages
693 }
694
695 pub fn client(&self) -> Arc<Client> {
696 self.client.clone()
697 }
698
699 pub fn user_store(&self) -> ModelHandle<UserStore> {
700 self.user_store.clone()
701 }
702
703 #[cfg(any(test, feature = "test-support"))]
704 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<ModelHandle<Buffer>> {
705 self.opened_buffers
706 .values()
707 .filter_map(|b| b.upgrade(cx))
708 .collect()
709 }
710
711 #[cfg(any(test, feature = "test-support"))]
712 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
713 let path = path.into();
714 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
715 self.opened_buffers.iter().any(|(_, buffer)| {
716 if let Some(buffer) = buffer.upgrade(cx) {
717 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
718 if file.worktree == worktree && file.path() == &path.path {
719 return true;
720 }
721 }
722 }
723 false
724 })
725 } else {
726 false
727 }
728 }
729
730 pub fn fs(&self) -> &Arc<dyn Fs> {
731 &self.fs
732 }
733
734 pub fn remote_id(&self) -> Option<u64> {
735 match self.client_state.as_ref()? {
736 ProjectClientState::Local { remote_id, .. }
737 | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
738 }
739 }
740
741 pub fn replica_id(&self) -> ReplicaId {
742 match &self.client_state {
743 Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
744 _ => 0,
745 }
746 }
747
748 fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
749 if let Some(ProjectClientState::Local { updates_tx, .. }) = &mut self.client_state {
750 updates_tx
751 .unbounded_send(LocalProjectUpdate::WorktreesChanged)
752 .ok();
753 }
754 cx.notify();
755 }
756
757 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
758 &self.collaborators
759 }
760
761 /// Collect all worktrees, including ones that don't appear in the project panel
762 pub fn worktrees<'a>(
763 &'a self,
764 cx: &'a AppContext,
765 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
766 self.worktrees
767 .iter()
768 .filter_map(move |worktree| worktree.upgrade(cx))
769 }
770
771 /// Collect all user-visible worktrees, the ones that appear in the project panel
772 pub fn visible_worktrees<'a>(
773 &'a self,
774 cx: &'a AppContext,
775 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
776 self.worktrees.iter().filter_map(|worktree| {
777 worktree.upgrade(cx).and_then(|worktree| {
778 if worktree.read(cx).is_visible() {
779 Some(worktree)
780 } else {
781 None
782 }
783 })
784 })
785 }
786
787 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
788 self.visible_worktrees(cx)
789 .map(|tree| tree.read(cx).root_name())
790 }
791
792 pub fn worktree_for_id(
793 &self,
794 id: WorktreeId,
795 cx: &AppContext,
796 ) -> Option<ModelHandle<Worktree>> {
797 self.worktrees(cx)
798 .find(|worktree| worktree.read(cx).id() == id)
799 }
800
801 pub fn worktree_for_entry(
802 &self,
803 entry_id: ProjectEntryId,
804 cx: &AppContext,
805 ) -> Option<ModelHandle<Worktree>> {
806 self.worktrees(cx)
807 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
808 }
809
810 pub fn worktree_id_for_entry(
811 &self,
812 entry_id: ProjectEntryId,
813 cx: &AppContext,
814 ) -> Option<WorktreeId> {
815 self.worktree_for_entry(entry_id, cx)
816 .map(|worktree| worktree.read(cx).id())
817 }
818
819 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
820 paths.iter().all(|path| self.contains_path(path, cx))
821 }
822
823 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
824 for worktree in self.worktrees(cx) {
825 let worktree = worktree.read(cx).as_local();
826 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
827 return true;
828 }
829 }
830 false
831 }
832
833 pub fn create_entry(
834 &mut self,
835 project_path: impl Into<ProjectPath>,
836 is_directory: bool,
837 cx: &mut ModelContext<Self>,
838 ) -> Option<Task<Result<Entry>>> {
839 let project_path = project_path.into();
840 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
841 if self.is_local() {
842 Some(worktree.update(cx, |worktree, cx| {
843 worktree
844 .as_local_mut()
845 .unwrap()
846 .create_entry(project_path.path, is_directory, cx)
847 }))
848 } else {
849 let client = self.client.clone();
850 let project_id = self.remote_id().unwrap();
851 Some(cx.spawn_weak(|_, mut cx| async move {
852 let response = client
853 .request(proto::CreateProjectEntry {
854 worktree_id: project_path.worktree_id.to_proto(),
855 project_id,
856 path: project_path.path.to_string_lossy().into(),
857 is_directory,
858 })
859 .await?;
860 let entry = response
861 .entry
862 .ok_or_else(|| anyhow!("missing entry in response"))?;
863 worktree
864 .update(&mut cx, |worktree, cx| {
865 worktree.as_remote_mut().unwrap().insert_entry(
866 entry,
867 response.worktree_scan_id as usize,
868 cx,
869 )
870 })
871 .await
872 }))
873 }
874 }
875
876 pub fn copy_entry(
877 &mut self,
878 entry_id: ProjectEntryId,
879 new_path: impl Into<Arc<Path>>,
880 cx: &mut ModelContext<Self>,
881 ) -> Option<Task<Result<Entry>>> {
882 let worktree = self.worktree_for_entry(entry_id, cx)?;
883 let new_path = new_path.into();
884 if self.is_local() {
885 worktree.update(cx, |worktree, cx| {
886 worktree
887 .as_local_mut()
888 .unwrap()
889 .copy_entry(entry_id, new_path, cx)
890 })
891 } else {
892 let client = self.client.clone();
893 let project_id = self.remote_id().unwrap();
894
895 Some(cx.spawn_weak(|_, mut cx| async move {
896 let response = client
897 .request(proto::CopyProjectEntry {
898 project_id,
899 entry_id: entry_id.to_proto(),
900 new_path: new_path.to_string_lossy().into(),
901 })
902 .await?;
903 let entry = response
904 .entry
905 .ok_or_else(|| anyhow!("missing entry in response"))?;
906 worktree
907 .update(&mut cx, |worktree, cx| {
908 worktree.as_remote_mut().unwrap().insert_entry(
909 entry,
910 response.worktree_scan_id as usize,
911 cx,
912 )
913 })
914 .await
915 }))
916 }
917 }
918
919 pub fn rename_entry(
920 &mut self,
921 entry_id: ProjectEntryId,
922 new_path: impl Into<Arc<Path>>,
923 cx: &mut ModelContext<Self>,
924 ) -> Option<Task<Result<Entry>>> {
925 let worktree = self.worktree_for_entry(entry_id, cx)?;
926 let new_path = new_path.into();
927 if self.is_local() {
928 worktree.update(cx, |worktree, cx| {
929 worktree
930 .as_local_mut()
931 .unwrap()
932 .rename_entry(entry_id, new_path, cx)
933 })
934 } else {
935 let client = self.client.clone();
936 let project_id = self.remote_id().unwrap();
937
938 Some(cx.spawn_weak(|_, mut cx| async move {
939 let response = client
940 .request(proto::RenameProjectEntry {
941 project_id,
942 entry_id: entry_id.to_proto(),
943 new_path: new_path.to_string_lossy().into(),
944 })
945 .await?;
946 let entry = response
947 .entry
948 .ok_or_else(|| anyhow!("missing entry in response"))?;
949 worktree
950 .update(&mut cx, |worktree, cx| {
951 worktree.as_remote_mut().unwrap().insert_entry(
952 entry,
953 response.worktree_scan_id as usize,
954 cx,
955 )
956 })
957 .await
958 }))
959 }
960 }
961
962 pub fn delete_entry(
963 &mut self,
964 entry_id: ProjectEntryId,
965 cx: &mut ModelContext<Self>,
966 ) -> Option<Task<Result<()>>> {
967 let worktree = self.worktree_for_entry(entry_id, cx)?;
968 if self.is_local() {
969 worktree.update(cx, |worktree, cx| {
970 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
971 })
972 } else {
973 let client = self.client.clone();
974 let project_id = self.remote_id().unwrap();
975 Some(cx.spawn_weak(|_, mut cx| async move {
976 let response = client
977 .request(proto::DeleteProjectEntry {
978 project_id,
979 entry_id: entry_id.to_proto(),
980 })
981 .await?;
982 worktree
983 .update(&mut cx, move |worktree, cx| {
984 worktree.as_remote_mut().unwrap().delete_entry(
985 entry_id,
986 response.worktree_scan_id as usize,
987 cx,
988 )
989 })
990 .await
991 }))
992 }
993 }
994
995 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
996 if self.client_state.is_some() {
997 return Err(anyhow!("project was already shared"));
998 }
999 self.client_subscriptions.push(
1000 self.client
1001 .subscribe_to_entity(project_id)?
1002 .set_model(&cx.handle(), &mut cx.to_async()),
1003 );
1004
1005 for open_buffer in self.opened_buffers.values_mut() {
1006 match open_buffer {
1007 OpenBuffer::Strong(_) => {}
1008 OpenBuffer::Weak(buffer) => {
1009 if let Some(buffer) = buffer.upgrade(cx) {
1010 *open_buffer = OpenBuffer::Strong(buffer);
1011 }
1012 }
1013 OpenBuffer::Operations(_) => unreachable!(),
1014 }
1015 }
1016
1017 for worktree_handle in self.worktrees.iter_mut() {
1018 match worktree_handle {
1019 WorktreeHandle::Strong(_) => {}
1020 WorktreeHandle::Weak(worktree) => {
1021 if let Some(worktree) = worktree.upgrade(cx) {
1022 *worktree_handle = WorktreeHandle::Strong(worktree);
1023 }
1024 }
1025 }
1026 }
1027
1028 for (server_id, status) in &self.language_server_statuses {
1029 self.client
1030 .send(proto::StartLanguageServer {
1031 project_id,
1032 server: Some(proto::LanguageServer {
1033 id: *server_id as u64,
1034 name: status.name.clone(),
1035 }),
1036 })
1037 .log_err();
1038 }
1039
1040 let (updates_tx, mut updates_rx) = mpsc::unbounded();
1041 let client = self.client.clone();
1042 self.client_state = Some(ProjectClientState::Local {
1043 remote_id: project_id,
1044 updates_tx,
1045 _send_updates: cx.spawn_weak(move |this, mut cx| async move {
1046 while let Some(update) = updates_rx.next().await {
1047 let Some(this) = this.upgrade(&cx) else { break };
1048
1049 match update {
1050 LocalProjectUpdate::WorktreesChanged => {
1051 let worktrees = this
1052 .read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1053 let update_project = this
1054 .read_with(&cx, |this, cx| {
1055 this.client.request(proto::UpdateProject {
1056 project_id,
1057 worktrees: this.worktree_metadata_protos(cx),
1058 })
1059 })
1060 .await;
1061 if update_project.is_ok() {
1062 for worktree in worktrees {
1063 worktree.update(&mut cx, |worktree, cx| {
1064 let worktree = worktree.as_local_mut().unwrap();
1065 worktree.share(project_id, cx).detach_and_log_err(cx)
1066 });
1067 }
1068 }
1069 }
1070 LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1071 let buffer = this.update(&mut cx, |this, _| {
1072 let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1073 let shared_buffers =
1074 this.shared_buffers.entry(peer_id).or_default();
1075 if shared_buffers.insert(buffer_id) {
1076 if let OpenBuffer::Strong(buffer) = buffer {
1077 Some(buffer.clone())
1078 } else {
1079 None
1080 }
1081 } else {
1082 None
1083 }
1084 });
1085
1086 let Some(buffer) = buffer else { continue };
1087 let operations =
1088 buffer.read_with(&cx, |b, cx| b.serialize_ops(None, cx));
1089 let operations = operations.await;
1090 let state = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
1091
1092 let initial_state = proto::CreateBufferForPeer {
1093 project_id,
1094 peer_id: Some(peer_id),
1095 variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1096 };
1097 if client.send(initial_state).log_err().is_some() {
1098 let client = client.clone();
1099 cx.background()
1100 .spawn(async move {
1101 let mut chunks = split_operations(operations).peekable();
1102 while let Some(chunk) = chunks.next() {
1103 let is_last = chunks.peek().is_none();
1104 client.send(proto::CreateBufferForPeer {
1105 project_id,
1106 peer_id: Some(peer_id),
1107 variant: Some(
1108 proto::create_buffer_for_peer::Variant::Chunk(
1109 proto::BufferChunk {
1110 buffer_id,
1111 operations: chunk,
1112 is_last,
1113 },
1114 ),
1115 ),
1116 })?;
1117 }
1118 anyhow::Ok(())
1119 })
1120 .await
1121 .log_err();
1122 }
1123 }
1124 }
1125 }
1126 }),
1127 });
1128
1129 self.metadata_changed(cx);
1130 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1131 cx.notify();
1132 Ok(())
1133 }
1134
1135 pub fn reshared(
1136 &mut self,
1137 message: proto::ResharedProject,
1138 cx: &mut ModelContext<Self>,
1139 ) -> Result<()> {
1140 self.shared_buffers.clear();
1141 self.set_collaborators_from_proto(message.collaborators, cx)?;
1142 self.metadata_changed(cx);
1143 Ok(())
1144 }
1145
1146 pub fn rejoined(
1147 &mut self,
1148 message: proto::RejoinedProject,
1149 message_id: u32,
1150 cx: &mut ModelContext<Self>,
1151 ) -> Result<()> {
1152 self.join_project_response_message_id = message_id;
1153 self.set_worktrees_from_proto(message.worktrees, cx)?;
1154 self.set_collaborators_from_proto(message.collaborators, cx)?;
1155 self.language_server_statuses = message
1156 .language_servers
1157 .into_iter()
1158 .map(|server| {
1159 (
1160 server.id as usize,
1161 LanguageServerStatus {
1162 name: server.name,
1163 pending_work: Default::default(),
1164 has_pending_diagnostic_updates: false,
1165 progress_tokens: Default::default(),
1166 },
1167 )
1168 })
1169 .collect();
1170 self.buffer_changes_tx
1171 .unbounded_send(BufferMessage::Resync)
1172 .unwrap();
1173 cx.notify();
1174 Ok(())
1175 }
1176
1177 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1178 self.unshare_internal(cx)?;
1179 self.metadata_changed(cx);
1180 cx.notify();
1181 Ok(())
1182 }
1183
1184 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1185 if self.is_remote() {
1186 return Err(anyhow!("attempted to unshare a remote project"));
1187 }
1188
1189 if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1190 self.collaborators.clear();
1191 self.shared_buffers.clear();
1192 self.client_subscriptions.clear();
1193
1194 for worktree_handle in self.worktrees.iter_mut() {
1195 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1196 let is_visible = worktree.update(cx, |worktree, _| {
1197 worktree.as_local_mut().unwrap().unshare();
1198 worktree.is_visible()
1199 });
1200 if !is_visible {
1201 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1202 }
1203 }
1204 }
1205
1206 for open_buffer in self.opened_buffers.values_mut() {
1207 // Wake up any tasks waiting for peers' edits to this buffer.
1208 if let Some(buffer) = open_buffer.upgrade(cx) {
1209 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1210 }
1211
1212 if let OpenBuffer::Strong(buffer) = open_buffer {
1213 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1214 }
1215 }
1216
1217 self.client.send(proto::UnshareProject {
1218 project_id: remote_id,
1219 })?;
1220
1221 Ok(())
1222 } else {
1223 Err(anyhow!("attempted to unshare an unshared project"))
1224 }
1225 }
1226
1227 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1228 self.disconnected_from_host_internal(cx);
1229 cx.emit(Event::DisconnectedFromHost);
1230 cx.notify();
1231 }
1232
1233 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1234 if let Some(ProjectClientState::Remote {
1235 sharing_has_stopped,
1236 ..
1237 }) = &mut self.client_state
1238 {
1239 *sharing_has_stopped = true;
1240
1241 self.collaborators.clear();
1242
1243 for worktree in &self.worktrees {
1244 if let Some(worktree) = worktree.upgrade(cx) {
1245 worktree.update(cx, |worktree, _| {
1246 if let Some(worktree) = worktree.as_remote_mut() {
1247 worktree.disconnected_from_host();
1248 }
1249 });
1250 }
1251 }
1252
1253 for open_buffer in self.opened_buffers.values_mut() {
1254 // Wake up any tasks waiting for peers' edits to this buffer.
1255 if let Some(buffer) = open_buffer.upgrade(cx) {
1256 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1257 }
1258
1259 if let OpenBuffer::Strong(buffer) = open_buffer {
1260 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1261 }
1262 }
1263
1264 // Wake up all futures currently waiting on a buffer to get opened,
1265 // to give them a chance to fail now that we've disconnected.
1266 *self.opened_buffer.0.borrow_mut() = ();
1267 }
1268 }
1269
1270 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1271 cx.emit(Event::Closed);
1272 }
1273
1274 pub fn is_read_only(&self) -> bool {
1275 match &self.client_state {
1276 Some(ProjectClientState::Remote {
1277 sharing_has_stopped,
1278 ..
1279 }) => *sharing_has_stopped,
1280 _ => false,
1281 }
1282 }
1283
1284 pub fn is_local(&self) -> bool {
1285 match &self.client_state {
1286 Some(ProjectClientState::Remote { .. }) => false,
1287 _ => true,
1288 }
1289 }
1290
1291 pub fn is_remote(&self) -> bool {
1292 !self.is_local()
1293 }
1294
1295 pub fn create_buffer(
1296 &mut self,
1297 text: &str,
1298 language: Option<Arc<Language>>,
1299 cx: &mut ModelContext<Self>,
1300 ) -> Result<ModelHandle<Buffer>> {
1301 if self.is_remote() {
1302 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1303 }
1304
1305 let buffer = cx.add_model(|cx| {
1306 Buffer::new(self.replica_id(), text, cx)
1307 .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1308 });
1309 self.register_buffer(&buffer, cx)?;
1310 Ok(buffer)
1311 }
1312
1313 pub fn open_path(
1314 &mut self,
1315 path: impl Into<ProjectPath>,
1316 cx: &mut ModelContext<Self>,
1317 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1318 let task = self.open_buffer(path, cx);
1319 cx.spawn_weak(|_, cx| async move {
1320 let buffer = task.await?;
1321 let project_entry_id = buffer
1322 .read_with(&cx, |buffer, cx| {
1323 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1324 })
1325 .ok_or_else(|| anyhow!("no project entry"))?;
1326
1327 let buffer: &AnyModelHandle = &buffer;
1328 Ok((project_entry_id, buffer.clone()))
1329 })
1330 }
1331
1332 pub fn open_local_buffer(
1333 &mut self,
1334 abs_path: impl AsRef<Path>,
1335 cx: &mut ModelContext<Self>,
1336 ) -> Task<Result<ModelHandle<Buffer>>> {
1337 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1338 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1339 } else {
1340 Task::ready(Err(anyhow!("no such path")))
1341 }
1342 }
1343
1344 pub fn open_buffer(
1345 &mut self,
1346 path: impl Into<ProjectPath>,
1347 cx: &mut ModelContext<Self>,
1348 ) -> Task<Result<ModelHandle<Buffer>>> {
1349 let project_path = path.into();
1350 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1351 worktree
1352 } else {
1353 return Task::ready(Err(anyhow!("no such worktree")));
1354 };
1355
1356 // If there is already a buffer for the given path, then return it.
1357 let existing_buffer = self.get_open_buffer(&project_path, cx);
1358 if let Some(existing_buffer) = existing_buffer {
1359 return Task::ready(Ok(existing_buffer));
1360 }
1361
1362 let mut loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1363 // If the given path is already being loaded, then wait for that existing
1364 // task to complete and return the same buffer.
1365 hash_map::Entry::Occupied(e) => e.get().clone(),
1366
1367 // Otherwise, record the fact that this path is now being loaded.
1368 hash_map::Entry::Vacant(entry) => {
1369 let (mut tx, rx) = postage::watch::channel();
1370 entry.insert(rx.clone());
1371
1372 let load_buffer = if worktree.read(cx).is_local() {
1373 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1374 } else {
1375 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1376 };
1377
1378 cx.spawn(move |this, mut cx| async move {
1379 let load_result = load_buffer.await;
1380 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1381 // Record the fact that the buffer is no longer loading.
1382 this.loading_buffers_by_path.remove(&project_path);
1383 let buffer = load_result.map_err(Arc::new)?;
1384 Ok(buffer)
1385 }));
1386 })
1387 .detach();
1388 rx
1389 }
1390 };
1391
1392 cx.foreground().spawn(async move {
1393 loop {
1394 if let Some(result) = loading_watch.borrow().as_ref() {
1395 match result {
1396 Ok(buffer) => return Ok(buffer.clone()),
1397 Err(error) => return Err(anyhow!("{}", error)),
1398 }
1399 }
1400 loading_watch.next().await;
1401 }
1402 })
1403 }
1404
1405 fn open_local_buffer_internal(
1406 &mut self,
1407 path: &Arc<Path>,
1408 worktree: &ModelHandle<Worktree>,
1409 cx: &mut ModelContext<Self>,
1410 ) -> Task<Result<ModelHandle<Buffer>>> {
1411 let load_buffer = worktree.update(cx, |worktree, cx| {
1412 let worktree = worktree.as_local_mut().unwrap();
1413 worktree.load_buffer(path, cx)
1414 });
1415 cx.spawn(|this, mut cx| async move {
1416 let buffer = load_buffer.await?;
1417 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1418 Ok(buffer)
1419 })
1420 }
1421
1422 fn open_remote_buffer_internal(
1423 &mut self,
1424 path: &Arc<Path>,
1425 worktree: &ModelHandle<Worktree>,
1426 cx: &mut ModelContext<Self>,
1427 ) -> Task<Result<ModelHandle<Buffer>>> {
1428 let rpc = self.client.clone();
1429 let project_id = self.remote_id().unwrap();
1430 let remote_worktree_id = worktree.read(cx).id();
1431 let path = path.clone();
1432 let path_string = path.to_string_lossy().to_string();
1433 cx.spawn(|this, mut cx| async move {
1434 let response = rpc
1435 .request(proto::OpenBufferByPath {
1436 project_id,
1437 worktree_id: remote_worktree_id.to_proto(),
1438 path: path_string,
1439 })
1440 .await?;
1441 this.update(&mut cx, |this, cx| {
1442 this.wait_for_remote_buffer(response.buffer_id, cx)
1443 })
1444 .await
1445 })
1446 }
1447
1448 /// LanguageServerName is owned, because it is inserted into a map
1449 fn open_local_buffer_via_lsp(
1450 &mut self,
1451 abs_path: lsp::Url,
1452 language_server_id: usize,
1453 language_server_name: LanguageServerName,
1454 cx: &mut ModelContext<Self>,
1455 ) -> Task<Result<ModelHandle<Buffer>>> {
1456 cx.spawn(|this, mut cx| async move {
1457 let abs_path = abs_path
1458 .to_file_path()
1459 .map_err(|_| anyhow!("can't convert URI to path"))?;
1460 let (worktree, relative_path) = if let Some(result) =
1461 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1462 {
1463 result
1464 } else {
1465 let worktree = this
1466 .update(&mut cx, |this, cx| {
1467 this.create_local_worktree(&abs_path, false, cx)
1468 })
1469 .await?;
1470 this.update(&mut cx, |this, cx| {
1471 this.language_server_ids.insert(
1472 (worktree.read(cx).id(), language_server_name),
1473 language_server_id,
1474 );
1475 });
1476 (worktree, PathBuf::new())
1477 };
1478
1479 let project_path = ProjectPath {
1480 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1481 path: relative_path.into(),
1482 };
1483 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1484 .await
1485 })
1486 }
1487
1488 pub fn open_buffer_by_id(
1489 &mut self,
1490 id: u64,
1491 cx: &mut ModelContext<Self>,
1492 ) -> Task<Result<ModelHandle<Buffer>>> {
1493 if let Some(buffer) = self.buffer_for_id(id, cx) {
1494 Task::ready(Ok(buffer))
1495 } else if self.is_local() {
1496 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1497 } else if let Some(project_id) = self.remote_id() {
1498 let request = self
1499 .client
1500 .request(proto::OpenBufferById { project_id, id });
1501 cx.spawn(|this, mut cx| async move {
1502 let buffer_id = request.await?.buffer_id;
1503 this.update(&mut cx, |this, cx| {
1504 this.wait_for_remote_buffer(buffer_id, cx)
1505 })
1506 .await
1507 })
1508 } else {
1509 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1510 }
1511 }
1512
1513 pub fn save_buffers(
1514 &self,
1515 buffers: HashSet<ModelHandle<Buffer>>,
1516 cx: &mut ModelContext<Self>,
1517 ) -> Task<Result<()>> {
1518 cx.spawn(|this, mut cx| async move {
1519 let save_tasks = buffers
1520 .into_iter()
1521 .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1522 try_join_all(save_tasks).await?;
1523 Ok(())
1524 })
1525 }
1526
1527 pub fn save_buffer(
1528 &self,
1529 buffer: ModelHandle<Buffer>,
1530 cx: &mut ModelContext<Self>,
1531 ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1532 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1533 return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1534 };
1535 let worktree = file.worktree.clone();
1536 let path = file.path.clone();
1537 worktree.update(cx, |worktree, cx| match worktree {
1538 Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1539 Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1540 })
1541 }
1542
1543 pub fn save_buffer_as(
1544 &mut self,
1545 buffer: ModelHandle<Buffer>,
1546 abs_path: PathBuf,
1547 cx: &mut ModelContext<Self>,
1548 ) -> Task<Result<()>> {
1549 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1550 let old_file = File::from_dyn(buffer.read(cx).file())
1551 .filter(|f| f.is_local())
1552 .cloned();
1553 cx.spawn(|this, mut cx| async move {
1554 if let Some(old_file) = &old_file {
1555 this.update(&mut cx, |this, cx| {
1556 this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1557 });
1558 }
1559 let (worktree, path) = worktree_task.await?;
1560 worktree
1561 .update(&mut cx, |worktree, cx| match worktree {
1562 Worktree::Local(worktree) => {
1563 worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1564 }
1565 Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1566 })
1567 .await?;
1568 this.update(&mut cx, |this, cx| {
1569 this.detect_language_for_buffer(&buffer, cx);
1570 this.register_buffer_with_language_servers(&buffer, cx);
1571 });
1572 Ok(())
1573 })
1574 }
1575
1576 pub fn get_open_buffer(
1577 &mut self,
1578 path: &ProjectPath,
1579 cx: &mut ModelContext<Self>,
1580 ) -> Option<ModelHandle<Buffer>> {
1581 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1582 self.opened_buffers.values().find_map(|buffer| {
1583 let buffer = buffer.upgrade(cx)?;
1584 let file = File::from_dyn(buffer.read(cx).file())?;
1585 if file.worktree == worktree && file.path() == &path.path {
1586 Some(buffer)
1587 } else {
1588 None
1589 }
1590 })
1591 }
1592
1593 fn register_buffer(
1594 &mut self,
1595 buffer: &ModelHandle<Buffer>,
1596 cx: &mut ModelContext<Self>,
1597 ) -> Result<()> {
1598 buffer.update(cx, |buffer, _| {
1599 buffer.set_language_registry(self.languages.clone())
1600 });
1601
1602 let remote_id = buffer.read(cx).remote_id();
1603 let is_remote = self.is_remote();
1604 let open_buffer = if is_remote || self.is_shared() {
1605 OpenBuffer::Strong(buffer.clone())
1606 } else {
1607 OpenBuffer::Weak(buffer.downgrade())
1608 };
1609
1610 match self.opened_buffers.entry(remote_id) {
1611 hash_map::Entry::Vacant(entry) => {
1612 entry.insert(open_buffer);
1613 }
1614 hash_map::Entry::Occupied(mut entry) => {
1615 if let OpenBuffer::Operations(operations) = entry.get_mut() {
1616 buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
1617 } else if entry.get().upgrade(cx).is_some() {
1618 if is_remote {
1619 return Ok(());
1620 } else {
1621 debug_panic!("buffer {} was already registered", remote_id);
1622 Err(anyhow!("buffer {} was already registered", remote_id))?;
1623 }
1624 }
1625 entry.insert(open_buffer);
1626 }
1627 }
1628 cx.subscribe(buffer, |this, buffer, event, cx| {
1629 this.on_buffer_event(buffer, event, cx);
1630 })
1631 .detach();
1632
1633 self.detect_language_for_buffer(buffer, cx);
1634 self.register_buffer_with_language_servers(buffer, cx);
1635 self.register_buffer_with_copilot(buffer, cx);
1636 cx.observe_release(buffer, |this, buffer, cx| {
1637 if let Some(file) = File::from_dyn(buffer.file()) {
1638 if file.is_local() {
1639 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1640 for server in this.language_servers_for_buffer(buffer, cx) {
1641 server
1642 .1
1643 .notify::<lsp::notification::DidCloseTextDocument>(
1644 lsp::DidCloseTextDocumentParams {
1645 text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1646 },
1647 )
1648 .log_err();
1649 }
1650 }
1651 }
1652 })
1653 .detach();
1654
1655 *self.opened_buffer.0.borrow_mut() = ();
1656 Ok(())
1657 }
1658
1659 fn register_buffer_with_language_servers(
1660 &mut self,
1661 buffer_handle: &ModelHandle<Buffer>,
1662 cx: &mut ModelContext<Self>,
1663 ) {
1664 let buffer = buffer_handle.read(cx);
1665 let buffer_id = buffer.remote_id();
1666
1667 if let Some(file) = File::from_dyn(buffer.file()) {
1668 if !file.is_local() {
1669 return;
1670 }
1671
1672 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1673 let initial_snapshot = buffer.text_snapshot();
1674 let language = buffer.language().cloned();
1675 let worktree_id = file.worktree_id(cx);
1676
1677 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1678 for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
1679 self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
1680 .log_err();
1681 }
1682 }
1683
1684 if let Some(language) = language {
1685 for adapter in language.lsp_adapters() {
1686 let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1687 let server = self
1688 .language_server_ids
1689 .get(&(worktree_id, adapter.name.clone()))
1690 .and_then(|id| self.language_servers.get(id))
1691 .and_then(|server_state| {
1692 if let LanguageServerState::Running { server, .. } = server_state {
1693 Some(server.clone())
1694 } else {
1695 None
1696 }
1697 });
1698 let server = match server {
1699 Some(server) => server,
1700 None => continue,
1701 };
1702
1703 server
1704 .notify::<lsp::notification::DidOpenTextDocument>(
1705 lsp::DidOpenTextDocumentParams {
1706 text_document: lsp::TextDocumentItem::new(
1707 uri.clone(),
1708 language_id.unwrap_or_default(),
1709 0,
1710 initial_snapshot.text(),
1711 ),
1712 },
1713 )
1714 .log_err();
1715
1716 buffer_handle.update(cx, |buffer, cx| {
1717 buffer.set_completion_triggers(
1718 server
1719 .capabilities()
1720 .completion_provider
1721 .as_ref()
1722 .and_then(|provider| provider.trigger_characters.clone())
1723 .unwrap_or_default(),
1724 cx,
1725 );
1726 });
1727
1728 let snapshot = LspBufferSnapshot {
1729 version: 0,
1730 snapshot: initial_snapshot.clone(),
1731 };
1732 self.buffer_snapshots
1733 .entry(buffer_id)
1734 .or_default()
1735 .insert(server.server_id(), vec![snapshot]);
1736 }
1737 }
1738 }
1739 }
1740
1741 fn unregister_buffer_from_language_servers(
1742 &mut self,
1743 buffer: &ModelHandle<Buffer>,
1744 old_file: &File,
1745 cx: &mut ModelContext<Self>,
1746 ) {
1747 let old_path = match old_file.as_local() {
1748 Some(local) => local.abs_path(cx),
1749 None => return,
1750 };
1751
1752 buffer.update(cx, |buffer, cx| {
1753 let worktree_id = old_file.worktree_id(cx);
1754 let ids = &self.language_server_ids;
1755
1756 let language = buffer.language().cloned();
1757 let adapters = language.iter().flat_map(|language| language.lsp_adapters());
1758 for &server_id in adapters.flat_map(|a| ids.get(&(worktree_id, a.name.clone()))) {
1759 buffer.update_diagnostics(server_id, Default::default(), cx);
1760 }
1761
1762 self.buffer_snapshots.remove(&buffer.remote_id());
1763 let file_url = lsp::Url::from_file_path(old_path).unwrap();
1764 for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
1765 language_server
1766 .notify::<lsp::notification::DidCloseTextDocument>(
1767 lsp::DidCloseTextDocumentParams {
1768 text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
1769 },
1770 )
1771 .log_err();
1772 }
1773 });
1774 }
1775
1776 fn register_buffer_with_copilot(
1777 &self,
1778 buffer_handle: &ModelHandle<Buffer>,
1779 cx: &mut ModelContext<Self>,
1780 ) {
1781 if let Some(copilot) = Copilot::global(cx) {
1782 copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
1783 }
1784 }
1785
1786 async fn send_buffer_messages(
1787 this: WeakModelHandle<Self>,
1788 rx: UnboundedReceiver<BufferMessage>,
1789 mut cx: AsyncAppContext,
1790 ) -> Option<()> {
1791 const MAX_BATCH_SIZE: usize = 128;
1792
1793 let mut needs_resync_with_host = false;
1794 let mut operations_by_buffer_id = HashMap::default();
1795 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1796 while let Some(changes) = changes.next().await {
1797 let this = this.upgrade(&mut cx)?;
1798 let is_local = this.read_with(&cx, |this, _| this.is_local());
1799
1800 for change in changes {
1801 match change {
1802 BufferMessage::Operation {
1803 buffer_id,
1804 operation,
1805 } => {
1806 if needs_resync_with_host {
1807 continue;
1808 }
1809
1810 operations_by_buffer_id
1811 .entry(buffer_id)
1812 .or_insert(Vec::new())
1813 .push(operation);
1814 }
1815 BufferMessage::Resync => {
1816 operations_by_buffer_id.clear();
1817 if this
1818 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))
1819 .await
1820 .is_ok()
1821 {
1822 needs_resync_with_host = false;
1823 }
1824 }
1825 }
1826 }
1827
1828 for (buffer_id, operations) in operations_by_buffer_id.drain() {
1829 let request = this.read_with(&cx, |this, _| {
1830 let project_id = this.remote_id()?;
1831 Some(this.client.request(proto::UpdateBuffer {
1832 buffer_id,
1833 project_id,
1834 operations,
1835 }))
1836 });
1837 if let Some(request) = request {
1838 if request.await.is_err() && !is_local {
1839 needs_resync_with_host = true;
1840 break;
1841 }
1842 }
1843 }
1844 }
1845
1846 None
1847 }
1848
1849 fn on_buffer_event(
1850 &mut self,
1851 buffer: ModelHandle<Buffer>,
1852 event: &BufferEvent,
1853 cx: &mut ModelContext<Self>,
1854 ) -> Option<()> {
1855 match event {
1856 BufferEvent::Operation(operation) => {
1857 self.buffer_changes_tx
1858 .unbounded_send(BufferMessage::Operation {
1859 buffer_id: buffer.read(cx).remote_id(),
1860 operation: language::proto::serialize_operation(operation),
1861 })
1862 .ok();
1863 }
1864
1865 BufferEvent::Edited { .. } => {
1866 let buffer = buffer.read(cx);
1867 let file = File::from_dyn(buffer.file())?;
1868 let abs_path = file.as_local()?.abs_path(cx);
1869 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1870 let next_snapshot = buffer.text_snapshot();
1871
1872 let language_servers: Vec<_> = self
1873 .language_servers_iter_for_buffer(buffer, cx)
1874 .map(|i| i.1.clone())
1875 .collect();
1876
1877 for language_server in language_servers {
1878 let language_server = language_server.clone();
1879
1880 let buffer_snapshots = self
1881 .buffer_snapshots
1882 .get_mut(&buffer.remote_id())
1883 .and_then(|m| m.get_mut(&language_server.server_id()))?;
1884 let previous_snapshot = buffer_snapshots.last()?;
1885 let next_version = previous_snapshot.version + 1;
1886
1887 let content_changes = buffer
1888 .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
1889 .map(|edit| {
1890 let edit_start = edit.new.start.0;
1891 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1892 let new_text = next_snapshot
1893 .text_for_range(edit.new.start.1..edit.new.end.1)
1894 .collect();
1895 lsp::TextDocumentContentChangeEvent {
1896 range: Some(lsp::Range::new(
1897 point_to_lsp(edit_start),
1898 point_to_lsp(edit_end),
1899 )),
1900 range_length: None,
1901 text: new_text,
1902 }
1903 })
1904 .collect();
1905
1906 buffer_snapshots.push(LspBufferSnapshot {
1907 version: next_version,
1908 snapshot: next_snapshot.clone(),
1909 });
1910
1911 language_server
1912 .notify::<lsp::notification::DidChangeTextDocument>(
1913 lsp::DidChangeTextDocumentParams {
1914 text_document: lsp::VersionedTextDocumentIdentifier::new(
1915 uri.clone(),
1916 next_version,
1917 ),
1918 content_changes,
1919 },
1920 )
1921 .log_err();
1922 }
1923 }
1924
1925 BufferEvent::Saved => {
1926 let file = File::from_dyn(buffer.read(cx).file())?;
1927 let worktree_id = file.worktree_id(cx);
1928 let abs_path = file.as_local()?.abs_path(cx);
1929 let text_document = lsp::TextDocumentIdentifier {
1930 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1931 };
1932
1933 for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1934 server
1935 .notify::<lsp::notification::DidSaveTextDocument>(
1936 lsp::DidSaveTextDocumentParams {
1937 text_document: text_document.clone(),
1938 text: None,
1939 },
1940 )
1941 .log_err();
1942 }
1943
1944 let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
1945 for language_server_id in language_server_ids {
1946 if let Some(LanguageServerState::Running {
1947 adapter,
1948 simulate_disk_based_diagnostics_completion,
1949 ..
1950 }) = self.language_servers.get_mut(&language_server_id)
1951 {
1952 // After saving a buffer using a language server that doesn't provide
1953 // a disk-based progress token, kick off a timer that will reset every
1954 // time the buffer is saved. If the timer eventually fires, simulate
1955 // disk-based diagnostics being finished so that other pieces of UI
1956 // (e.g., project diagnostics view, diagnostic status bar) can update.
1957 // We don't emit an event right away because the language server might take
1958 // some time to publish diagnostics.
1959 if adapter.disk_based_diagnostics_progress_token.is_none() {
1960 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
1961 Duration::from_secs(1);
1962
1963 let task = cx.spawn_weak(|this, mut cx| async move {
1964 cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
1965 if let Some(this) = this.upgrade(&cx) {
1966 this.update(&mut cx, |this, cx | {
1967 this.disk_based_diagnostics_finished(language_server_id, cx);
1968 this.broadcast_language_server_update(
1969 language_server_id,
1970 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1971 proto::LspDiskBasedDiagnosticsUpdated {},
1972 ),
1973 );
1974 });
1975 }
1976 });
1977 *simulate_disk_based_diagnostics_completion = Some(task);
1978 }
1979 }
1980 }
1981 }
1982
1983 _ => {}
1984 }
1985
1986 None
1987 }
1988
1989 fn language_servers_for_worktree(
1990 &self,
1991 worktree_id: WorktreeId,
1992 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
1993 self.language_server_ids
1994 .iter()
1995 .filter_map(move |((language_server_worktree_id, _), id)| {
1996 if *language_server_worktree_id == worktree_id {
1997 if let Some(LanguageServerState::Running {
1998 adapter,
1999 language,
2000 server,
2001 ..
2002 }) = self.language_servers.get(id)
2003 {
2004 return Some((adapter, language, server));
2005 }
2006 }
2007 None
2008 })
2009 }
2010
2011 fn maintain_buffer_languages(
2012 languages: &LanguageRegistry,
2013 cx: &mut ModelContext<Project>,
2014 ) -> Task<()> {
2015 let mut subscription = languages.subscribe();
2016 cx.spawn_weak(|project, mut cx| async move {
2017 while let Some(()) = subscription.next().await {
2018 if let Some(project) = project.upgrade(&cx) {
2019 project.update(&mut cx, |project, cx| {
2020 let mut plain_text_buffers = Vec::new();
2021 let mut buffers_with_unknown_injections = Vec::new();
2022 for buffer in project.opened_buffers.values() {
2023 if let Some(handle) = buffer.upgrade(cx) {
2024 let buffer = &handle.read(cx);
2025 if buffer.language().is_none()
2026 || buffer.language() == Some(&*language::PLAIN_TEXT)
2027 {
2028 plain_text_buffers.push(handle);
2029 } else if buffer.contains_unknown_injections() {
2030 buffers_with_unknown_injections.push(handle);
2031 }
2032 }
2033 }
2034
2035 for buffer in plain_text_buffers {
2036 project.detect_language_for_buffer(&buffer, cx);
2037 project.register_buffer_with_language_servers(&buffer, cx);
2038 }
2039
2040 for buffer in buffers_with_unknown_injections {
2041 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2042 }
2043 });
2044 }
2045 }
2046 })
2047 }
2048
2049 fn maintain_workspace_config(
2050 languages: Arc<LanguageRegistry>,
2051 cx: &mut ModelContext<Project>,
2052 ) -> Task<()> {
2053 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2054 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2055
2056 let settings_observation = cx.observe_global::<Settings, _>(move |_, _| {
2057 *settings_changed_tx.borrow_mut() = ();
2058 });
2059 cx.spawn_weak(|this, mut cx| async move {
2060 while let Some(_) = settings_changed_rx.next().await {
2061 let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2062 if let Some(this) = this.upgrade(&cx) {
2063 this.read_with(&cx, |this, _| {
2064 for server_state in this.language_servers.values() {
2065 if let LanguageServerState::Running { server, .. } = server_state {
2066 server
2067 .notify::<lsp::notification::DidChangeConfiguration>(
2068 lsp::DidChangeConfigurationParams {
2069 settings: workspace_config.clone(),
2070 },
2071 )
2072 .ok();
2073 }
2074 }
2075 })
2076 } else {
2077 break;
2078 }
2079 }
2080
2081 drop(settings_observation);
2082 })
2083 }
2084
2085 fn detect_language_for_buffer(
2086 &mut self,
2087 buffer_handle: &ModelHandle<Buffer>,
2088 cx: &mut ModelContext<Self>,
2089 ) -> Option<()> {
2090 // If the buffer has a language, set it and start the language server if we haven't already.
2091 let buffer = buffer_handle.read(cx);
2092 let full_path = buffer.file()?.full_path(cx);
2093 let content = buffer.as_rope();
2094 let new_language = self
2095 .languages
2096 .language_for_file(&full_path, Some(content))
2097 .now_or_never()?
2098 .ok()?;
2099 self.set_language_for_buffer(buffer_handle, new_language, cx);
2100 None
2101 }
2102
2103 pub fn set_language_for_buffer(
2104 &mut self,
2105 buffer: &ModelHandle<Buffer>,
2106 new_language: Arc<Language>,
2107 cx: &mut ModelContext<Self>,
2108 ) {
2109 buffer.update(cx, |buffer, cx| {
2110 if buffer.language().map_or(true, |old_language| {
2111 !Arc::ptr_eq(old_language, &new_language)
2112 }) {
2113 buffer.set_language(Some(new_language.clone()), cx);
2114 }
2115 });
2116
2117 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2118 if let Some(worktree) = file.worktree.read(cx).as_local() {
2119 let worktree_id = worktree.id();
2120 let worktree_abs_path = worktree.abs_path().clone();
2121 self.start_language_servers(worktree_id, worktree_abs_path, new_language, cx);
2122 }
2123 }
2124 }
2125
2126 fn start_language_servers(
2127 &mut self,
2128 worktree_id: WorktreeId,
2129 worktree_path: Arc<Path>,
2130 language: Arc<Language>,
2131 cx: &mut ModelContext<Self>,
2132 ) {
2133 if !cx
2134 .global::<Settings>()
2135 .enable_language_server(Some(&language.name()))
2136 {
2137 return;
2138 }
2139
2140 let adapters = language.lsp_adapters();
2141 let language_servers = self.languages.start_language_servers(
2142 language.clone(),
2143 worktree_path.clone(),
2144 self.client.http_client(),
2145 cx,
2146 );
2147 debug_assert_eq!(adapters.len(), language_servers.len());
2148
2149 for (adapter, pending_server) in adapters.into_iter().zip(language_servers.into_iter()) {
2150 let key = (worktree_id, adapter.name.clone());
2151 let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
2152 let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2153
2154 let mut initialization_options = adapter.initialization_options.clone();
2155 match (&mut initialization_options, override_options) {
2156 (Some(initialization_options), Some(override_options)) => {
2157 merge_json_value_into(override_options, initialization_options);
2158 }
2159 (None, override_options) => initialization_options = override_options,
2160 _ => {}
2161 }
2162
2163 if !self.language_server_ids.contains_key(&key) {
2164 let adapter = self.setup_language_adapter(
2165 worktree_path.clone(),
2166 initialization_options,
2167 pending_server,
2168 adapter.clone(),
2169 language.clone(),
2170 key.clone(),
2171 cx,
2172 );
2173 self.language_server_ids.insert(key.clone(), adapter);
2174 }
2175 }
2176 }
2177
2178 fn setup_language_adapter(
2179 &mut self,
2180 worktree_path: Arc<Path>,
2181 initialization_options: Option<serde_json::Value>,
2182 pending_server: PendingLanguageServer,
2183 adapter: Arc<CachedLspAdapter>,
2184 language: Arc<Language>,
2185 key: (WorktreeId, LanguageServerName),
2186 cx: &mut ModelContext<Project>,
2187 ) -> usize {
2188 let server_id = pending_server.server_id;
2189 let languages = self.languages.clone();
2190
2191 self.language_servers.insert(
2192 server_id,
2193 LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2194 let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2195 let language_server = pending_server.task.await.log_err()?;
2196 let language_server = language_server
2197 .initialize(initialization_options)
2198 .await
2199 .log_err()?;
2200 let this = this.upgrade(&cx)?;
2201
2202 language_server
2203 .on_notification::<lsp::notification::PublishDiagnostics, _>({
2204 let this = this.downgrade();
2205 let adapter = adapter.clone();
2206 move |mut params, cx| {
2207 let this = this;
2208 let adapter = adapter.clone();
2209 cx.spawn(|mut cx| async move {
2210 adapter.process_diagnostics(&mut params).await;
2211 if let Some(this) = this.upgrade(&cx) {
2212 this.update(&mut cx, |this, cx| {
2213 this.update_diagnostics(
2214 server_id,
2215 params,
2216 &adapter.disk_based_diagnostic_sources,
2217 cx,
2218 )
2219 .log_err();
2220 });
2221 }
2222 })
2223 .detach();
2224 }
2225 })
2226 .detach();
2227
2228 language_server
2229 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2230 let languages = languages.clone();
2231 move |params, mut cx| {
2232 let languages = languages.clone();
2233 async move {
2234 dbg!(¶ms.items);
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 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 server_id
2467 }
2468
2469 // Returns a list of all of the worktrees which no longer have a language server and the root path
2470 // for the stopped server
2471 fn stop_language_server(
2472 &mut self,
2473 worktree_id: WorktreeId,
2474 adapter_name: LanguageServerName,
2475 cx: &mut ModelContext<Self>,
2476 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2477 let key = (worktree_id, adapter_name);
2478 if let Some(server_id) = self.language_server_ids.remove(&key) {
2479 // Remove other entries for this language server as well
2480 let mut orphaned_worktrees = vec![worktree_id];
2481 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2482 for other_key in other_keys {
2483 if self.language_server_ids.get(&other_key) == Some(&server_id) {
2484 self.language_server_ids.remove(&other_key);
2485 orphaned_worktrees.push(other_key.0);
2486 }
2487 }
2488
2489 self.language_server_statuses.remove(&server_id);
2490 cx.notify();
2491
2492 let server_state = self.language_servers.remove(&server_id);
2493 cx.spawn_weak(|this, mut cx| async move {
2494 let mut root_path = None;
2495
2496 let server = match server_state {
2497 Some(LanguageServerState::Starting(started_language_server)) => {
2498 started_language_server.await
2499 }
2500 Some(LanguageServerState::Running { server, .. }) => Some(server),
2501 None => None,
2502 };
2503
2504 if let Some(server) = server {
2505 root_path = Some(server.root_path().clone());
2506 if let Some(shutdown) = server.shutdown() {
2507 shutdown.await;
2508 }
2509 }
2510
2511 if let Some(this) = this.upgrade(&cx) {
2512 this.update(&mut cx, |this, cx| {
2513 this.language_server_statuses.remove(&server_id);
2514 cx.notify();
2515 });
2516 }
2517
2518 (root_path, orphaned_worktrees)
2519 })
2520 } else {
2521 Task::ready((None, Vec::new()))
2522 }
2523 }
2524
2525 pub fn restart_language_servers_for_buffers(
2526 &mut self,
2527 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2528 cx: &mut ModelContext<Self>,
2529 ) -> Option<()> {
2530 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, Arc<Language>)> = buffers
2531 .into_iter()
2532 .filter_map(|buffer| {
2533 let buffer = buffer.read(cx);
2534 let file = File::from_dyn(buffer.file())?;
2535 let worktree = file.worktree.read(cx).as_local()?;
2536 let full_path = file.full_path(cx);
2537 let language = self
2538 .languages
2539 .language_for_file(&full_path, Some(buffer.as_rope()))
2540 .now_or_never()?
2541 .ok()?;
2542 Some((worktree.id(), worktree.abs_path().clone(), language))
2543 })
2544 .collect();
2545 for (worktree_id, worktree_abs_path, language) in language_server_lookup_info {
2546 self.restart_language_servers(worktree_id, worktree_abs_path, language, cx);
2547 }
2548
2549 None
2550 }
2551
2552 // TODO This will break in the case where the adapter's root paths and worktrees are not equal
2553 fn restart_language_servers(
2554 &mut self,
2555 worktree_id: WorktreeId,
2556 fallback_path: Arc<Path>,
2557 language: Arc<Language>,
2558 cx: &mut ModelContext<Self>,
2559 ) {
2560 let mut stops = Vec::new();
2561 for adapter in language.lsp_adapters() {
2562 stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
2563 }
2564
2565 if stops.is_empty() {
2566 return;
2567 }
2568 let mut stops = stops.into_iter();
2569
2570 cx.spawn_weak(|this, mut cx| async move {
2571 let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
2572 for stop in stops {
2573 let (_, worktrees) = stop.await;
2574 orphaned_worktrees.extend_from_slice(&worktrees);
2575 }
2576
2577 let this = match this.upgrade(&cx) {
2578 Some(this) => this,
2579 None => return,
2580 };
2581
2582 this.update(&mut cx, |this, cx| {
2583 // Attempt to restart using original server path. Fallback to passed in
2584 // path if we could not retrieve the root path
2585 let root_path = original_root_path
2586 .map(|path_buf| Arc::from(path_buf.as_path()))
2587 .unwrap_or(fallback_path);
2588
2589 this.start_language_servers(worktree_id, root_path, language.clone(), cx);
2590
2591 // Lookup new server ids and set them for each of the orphaned worktrees
2592 for adapter in language.lsp_adapters() {
2593 if let Some(new_server_id) = this
2594 .language_server_ids
2595 .get(&(worktree_id, adapter.name.clone()))
2596 .cloned()
2597 {
2598 for &orphaned_worktree in &orphaned_worktrees {
2599 this.language_server_ids
2600 .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
2601 }
2602 }
2603 }
2604 });
2605 })
2606 .detach();
2607 }
2608
2609 fn on_lsp_progress(
2610 &mut self,
2611 progress: lsp::ProgressParams,
2612 server_id: usize,
2613 disk_based_diagnostics_progress_token: Option<String>,
2614 cx: &mut ModelContext<Self>,
2615 ) {
2616 let token = match progress.token {
2617 lsp::NumberOrString::String(token) => token,
2618 lsp::NumberOrString::Number(token) => {
2619 log::info!("skipping numeric progress token {}", token);
2620 return;
2621 }
2622 };
2623 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2624 let language_server_status =
2625 if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2626 status
2627 } else {
2628 return;
2629 };
2630
2631 if !language_server_status.progress_tokens.contains(&token) {
2632 return;
2633 }
2634
2635 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2636 .as_ref()
2637 .map_or(false, |disk_based_token| {
2638 token.starts_with(disk_based_token)
2639 });
2640
2641 match progress {
2642 lsp::WorkDoneProgress::Begin(report) => {
2643 if is_disk_based_diagnostics_progress {
2644 language_server_status.has_pending_diagnostic_updates = true;
2645 self.disk_based_diagnostics_started(server_id, cx);
2646 self.broadcast_language_server_update(
2647 server_id,
2648 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2649 proto::LspDiskBasedDiagnosticsUpdating {},
2650 ),
2651 );
2652 } else {
2653 self.on_lsp_work_start(
2654 server_id,
2655 token.clone(),
2656 LanguageServerProgress {
2657 message: report.message.clone(),
2658 percentage: report.percentage.map(|p| p as usize),
2659 last_update_at: Instant::now(),
2660 },
2661 cx,
2662 );
2663 self.broadcast_language_server_update(
2664 server_id,
2665 proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2666 token,
2667 message: report.message,
2668 percentage: report.percentage.map(|p| p as u32),
2669 }),
2670 );
2671 }
2672 }
2673 lsp::WorkDoneProgress::Report(report) => {
2674 if !is_disk_based_diagnostics_progress {
2675 self.on_lsp_work_progress(
2676 server_id,
2677 token.clone(),
2678 LanguageServerProgress {
2679 message: report.message.clone(),
2680 percentage: report.percentage.map(|p| p as usize),
2681 last_update_at: Instant::now(),
2682 },
2683 cx,
2684 );
2685 self.broadcast_language_server_update(
2686 server_id,
2687 proto::update_language_server::Variant::WorkProgress(
2688 proto::LspWorkProgress {
2689 token,
2690 message: report.message,
2691 percentage: report.percentage.map(|p| p as u32),
2692 },
2693 ),
2694 );
2695 }
2696 }
2697 lsp::WorkDoneProgress::End(_) => {
2698 language_server_status.progress_tokens.remove(&token);
2699
2700 if is_disk_based_diagnostics_progress {
2701 language_server_status.has_pending_diagnostic_updates = false;
2702 self.disk_based_diagnostics_finished(server_id, cx);
2703 self.broadcast_language_server_update(
2704 server_id,
2705 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2706 proto::LspDiskBasedDiagnosticsUpdated {},
2707 ),
2708 );
2709 } else {
2710 self.on_lsp_work_end(server_id, token.clone(), cx);
2711 self.broadcast_language_server_update(
2712 server_id,
2713 proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2714 token,
2715 }),
2716 );
2717 }
2718 }
2719 }
2720 }
2721
2722 fn on_lsp_work_start(
2723 &mut self,
2724 language_server_id: usize,
2725 token: String,
2726 progress: LanguageServerProgress,
2727 cx: &mut ModelContext<Self>,
2728 ) {
2729 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2730 status.pending_work.insert(token, progress);
2731 cx.notify();
2732 }
2733 }
2734
2735 fn on_lsp_work_progress(
2736 &mut self,
2737 language_server_id: usize,
2738 token: String,
2739 progress: LanguageServerProgress,
2740 cx: &mut ModelContext<Self>,
2741 ) {
2742 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2743 let entry = status
2744 .pending_work
2745 .entry(token)
2746 .or_insert(LanguageServerProgress {
2747 message: Default::default(),
2748 percentage: Default::default(),
2749 last_update_at: progress.last_update_at,
2750 });
2751 if progress.message.is_some() {
2752 entry.message = progress.message;
2753 }
2754 if progress.percentage.is_some() {
2755 entry.percentage = progress.percentage;
2756 }
2757 entry.last_update_at = progress.last_update_at;
2758 cx.notify();
2759 }
2760 }
2761
2762 fn on_lsp_work_end(
2763 &mut self,
2764 language_server_id: usize,
2765 token: String,
2766 cx: &mut ModelContext<Self>,
2767 ) {
2768 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2769 status.pending_work.remove(&token);
2770 cx.notify();
2771 }
2772 }
2773
2774 fn on_lsp_did_change_watched_files(
2775 &mut self,
2776 language_server_id: usize,
2777 params: DidChangeWatchedFilesRegistrationOptions,
2778 cx: &mut ModelContext<Self>,
2779 ) {
2780 if let Some(LanguageServerState::Running { watched_paths, .. }) =
2781 self.language_servers.get_mut(&language_server_id)
2782 {
2783 watched_paths.clear();
2784 for watcher in params.watchers {
2785 watched_paths.add_pattern(&watcher.glob_pattern).log_err();
2786 }
2787 cx.notify();
2788 }
2789 }
2790
2791 async fn on_lsp_workspace_edit(
2792 this: WeakModelHandle<Self>,
2793 params: lsp::ApplyWorkspaceEditParams,
2794 server_id: usize,
2795 adapter: Arc<CachedLspAdapter>,
2796 language_server: Arc<LanguageServer>,
2797 mut cx: AsyncAppContext,
2798 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2799 let this = this
2800 .upgrade(&cx)
2801 .ok_or_else(|| anyhow!("project project closed"))?;
2802 let transaction = Self::deserialize_workspace_edit(
2803 this.clone(),
2804 params.edit,
2805 true,
2806 adapter.clone(),
2807 language_server.clone(),
2808 &mut cx,
2809 )
2810 .await
2811 .log_err();
2812 this.update(&mut cx, |this, _| {
2813 if let Some(transaction) = transaction {
2814 this.last_workspace_edits_by_language_server
2815 .insert(server_id, transaction);
2816 }
2817 });
2818 Ok(lsp::ApplyWorkspaceEditResponse {
2819 applied: true,
2820 failed_change: None,
2821 failure_reason: None,
2822 })
2823 }
2824
2825 fn broadcast_language_server_update(
2826 &self,
2827 language_server_id: usize,
2828 event: proto::update_language_server::Variant,
2829 ) {
2830 if let Some(project_id) = self.remote_id() {
2831 self.client
2832 .send(proto::UpdateLanguageServer {
2833 project_id,
2834 language_server_id: language_server_id as u64,
2835 variant: Some(event),
2836 })
2837 .log_err();
2838 }
2839 }
2840
2841 pub fn language_server_statuses(
2842 &self,
2843 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2844 self.language_server_statuses.values()
2845 }
2846
2847 pub fn update_diagnostics(
2848 &mut self,
2849 language_server_id: usize,
2850 mut params: lsp::PublishDiagnosticsParams,
2851 disk_based_sources: &[String],
2852 cx: &mut ModelContext<Self>,
2853 ) -> Result<()> {
2854 let abs_path = params
2855 .uri
2856 .to_file_path()
2857 .map_err(|_| anyhow!("URI is not a file"))?;
2858 let mut diagnostics = Vec::default();
2859 let mut primary_diagnostic_group_ids = HashMap::default();
2860 let mut sources_by_group_id = HashMap::default();
2861 let mut supporting_diagnostics = HashMap::default();
2862
2863 // Ensure that primary diagnostics are always the most severe
2864 params.diagnostics.sort_by_key(|item| item.severity);
2865
2866 for diagnostic in ¶ms.diagnostics {
2867 let source = diagnostic.source.as_ref();
2868 let code = diagnostic.code.as_ref().map(|code| match code {
2869 lsp::NumberOrString::Number(code) => code.to_string(),
2870 lsp::NumberOrString::String(code) => code.clone(),
2871 });
2872 let range = range_from_lsp(diagnostic.range);
2873 let is_supporting = diagnostic
2874 .related_information
2875 .as_ref()
2876 .map_or(false, |infos| {
2877 infos.iter().any(|info| {
2878 primary_diagnostic_group_ids.contains_key(&(
2879 source,
2880 code.clone(),
2881 range_from_lsp(info.location.range),
2882 ))
2883 })
2884 });
2885
2886 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2887 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2888 });
2889
2890 if is_supporting {
2891 supporting_diagnostics.insert(
2892 (source, code.clone(), range),
2893 (diagnostic.severity, is_unnecessary),
2894 );
2895 } else {
2896 let group_id = post_inc(&mut self.next_diagnostic_group_id);
2897 let is_disk_based =
2898 source.map_or(false, |source| disk_based_sources.contains(source));
2899
2900 sources_by_group_id.insert(group_id, source);
2901 primary_diagnostic_group_ids
2902 .insert((source, code.clone(), range.clone()), group_id);
2903
2904 diagnostics.push(DiagnosticEntry {
2905 range,
2906 diagnostic: Diagnostic {
2907 code: code.clone(),
2908 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2909 message: diagnostic.message.clone(),
2910 group_id,
2911 is_primary: true,
2912 is_valid: true,
2913 is_disk_based,
2914 is_unnecessary,
2915 },
2916 });
2917 if let Some(infos) = &diagnostic.related_information {
2918 for info in infos {
2919 if info.location.uri == params.uri && !info.message.is_empty() {
2920 let range = range_from_lsp(info.location.range);
2921 diagnostics.push(DiagnosticEntry {
2922 range,
2923 diagnostic: Diagnostic {
2924 code: code.clone(),
2925 severity: DiagnosticSeverity::INFORMATION,
2926 message: info.message.clone(),
2927 group_id,
2928 is_primary: false,
2929 is_valid: true,
2930 is_disk_based,
2931 is_unnecessary: false,
2932 },
2933 });
2934 }
2935 }
2936 }
2937 }
2938 }
2939
2940 for entry in &mut diagnostics {
2941 let diagnostic = &mut entry.diagnostic;
2942 if !diagnostic.is_primary {
2943 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2944 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2945 source,
2946 diagnostic.code.clone(),
2947 entry.range.clone(),
2948 )) {
2949 if let Some(severity) = severity {
2950 diagnostic.severity = severity;
2951 }
2952 diagnostic.is_unnecessary = is_unnecessary;
2953 }
2954 }
2955 }
2956
2957 self.update_diagnostic_entries(
2958 language_server_id,
2959 abs_path,
2960 params.version,
2961 diagnostics,
2962 cx,
2963 )?;
2964 Ok(())
2965 }
2966
2967 pub fn update_diagnostic_entries(
2968 &mut self,
2969 server_id: usize,
2970 abs_path: PathBuf,
2971 version: Option<i32>,
2972 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2973 cx: &mut ModelContext<Project>,
2974 ) -> Result<(), anyhow::Error> {
2975 let (worktree, relative_path) = self
2976 .find_local_worktree(&abs_path, cx)
2977 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2978
2979 let project_path = ProjectPath {
2980 worktree_id: worktree.read(cx).id(),
2981 path: relative_path.into(),
2982 };
2983
2984 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2985 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
2986 }
2987
2988 let updated = worktree.update(cx, |worktree, cx| {
2989 worktree
2990 .as_local_mut()
2991 .ok_or_else(|| anyhow!("not a local worktree"))?
2992 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
2993 })?;
2994 if updated {
2995 cx.emit(Event::DiagnosticsUpdated {
2996 language_server_id: server_id,
2997 path: project_path,
2998 });
2999 }
3000 Ok(())
3001 }
3002
3003 fn update_buffer_diagnostics(
3004 &mut self,
3005 buffer: &ModelHandle<Buffer>,
3006 server_id: usize,
3007 version: Option<i32>,
3008 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3009 cx: &mut ModelContext<Self>,
3010 ) -> Result<()> {
3011 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3012 Ordering::Equal
3013 .then_with(|| b.is_primary.cmp(&a.is_primary))
3014 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3015 .then_with(|| a.severity.cmp(&b.severity))
3016 .then_with(|| a.message.cmp(&b.message))
3017 }
3018
3019 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3020
3021 diagnostics.sort_unstable_by(|a, b| {
3022 Ordering::Equal
3023 .then_with(|| a.range.start.cmp(&b.range.start))
3024 .then_with(|| b.range.end.cmp(&a.range.end))
3025 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3026 });
3027
3028 let mut sanitized_diagnostics = Vec::new();
3029 let edits_since_save = Patch::new(
3030 snapshot
3031 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3032 .collect(),
3033 );
3034 for entry in diagnostics {
3035 let start;
3036 let end;
3037 if entry.diagnostic.is_disk_based {
3038 // Some diagnostics are based on files on disk instead of buffers'
3039 // current contents. Adjust these diagnostics' ranges to reflect
3040 // any unsaved edits.
3041 start = edits_since_save.old_to_new(entry.range.start);
3042 end = edits_since_save.old_to_new(entry.range.end);
3043 } else {
3044 start = entry.range.start;
3045 end = entry.range.end;
3046 }
3047
3048 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3049 ..snapshot.clip_point_utf16(end, Bias::Right);
3050
3051 // Expand empty ranges by one codepoint
3052 if range.start == range.end {
3053 // This will be go to the next boundary when being clipped
3054 range.end.column += 1;
3055 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3056 if range.start == range.end && range.end.column > 0 {
3057 range.start.column -= 1;
3058 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3059 }
3060 }
3061
3062 sanitized_diagnostics.push(DiagnosticEntry {
3063 range,
3064 diagnostic: entry.diagnostic,
3065 });
3066 }
3067 drop(edits_since_save);
3068
3069 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3070 buffer.update(cx, |buffer, cx| {
3071 buffer.update_diagnostics(server_id, set, cx)
3072 });
3073 Ok(())
3074 }
3075
3076 pub fn reload_buffers(
3077 &self,
3078 buffers: HashSet<ModelHandle<Buffer>>,
3079 push_to_history: bool,
3080 cx: &mut ModelContext<Self>,
3081 ) -> Task<Result<ProjectTransaction>> {
3082 let mut local_buffers = Vec::new();
3083 let mut remote_buffers = None;
3084 for buffer_handle in buffers {
3085 let buffer = buffer_handle.read(cx);
3086 if buffer.is_dirty() {
3087 if let Some(file) = File::from_dyn(buffer.file()) {
3088 if file.is_local() {
3089 local_buffers.push(buffer_handle);
3090 } else {
3091 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3092 }
3093 }
3094 }
3095 }
3096
3097 let remote_buffers = self.remote_id().zip(remote_buffers);
3098 let client = self.client.clone();
3099
3100 cx.spawn(|this, mut cx| async move {
3101 let mut project_transaction = ProjectTransaction::default();
3102
3103 if let Some((project_id, remote_buffers)) = remote_buffers {
3104 let response = client
3105 .request(proto::ReloadBuffers {
3106 project_id,
3107 buffer_ids: remote_buffers
3108 .iter()
3109 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3110 .collect(),
3111 })
3112 .await?
3113 .transaction
3114 .ok_or_else(|| anyhow!("missing transaction"))?;
3115 project_transaction = this
3116 .update(&mut cx, |this, cx| {
3117 this.deserialize_project_transaction(response, push_to_history, cx)
3118 })
3119 .await?;
3120 }
3121
3122 for buffer in local_buffers {
3123 let transaction = buffer
3124 .update(&mut cx, |buffer, cx| buffer.reload(cx))
3125 .await?;
3126 buffer.update(&mut cx, |buffer, cx| {
3127 if let Some(transaction) = transaction {
3128 if !push_to_history {
3129 buffer.forget_transaction(transaction.id);
3130 }
3131 project_transaction.0.insert(cx.handle(), transaction);
3132 }
3133 });
3134 }
3135
3136 Ok(project_transaction)
3137 })
3138 }
3139
3140 pub fn format(
3141 &self,
3142 buffers: HashSet<ModelHandle<Buffer>>,
3143 push_to_history: bool,
3144 trigger: FormatTrigger,
3145 cx: &mut ModelContext<Project>,
3146 ) -> Task<Result<ProjectTransaction>> {
3147 if self.is_local() {
3148 let mut buffers_with_paths_and_servers = buffers
3149 .into_iter()
3150 .filter_map(|buffer_handle| {
3151 let buffer = buffer_handle.read(cx);
3152 let file = File::from_dyn(buffer.file())?;
3153 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3154 let server = self
3155 .primary_language_servers_for_buffer(buffer, cx)
3156 .map(|s| s.1.clone());
3157 Some((buffer_handle, buffer_abs_path, server))
3158 })
3159 .collect::<Vec<_>>();
3160
3161 cx.spawn(|this, mut cx| async move {
3162 // Do not allow multiple concurrent formatting requests for the
3163 // same buffer.
3164 this.update(&mut cx, |this, _| {
3165 buffers_with_paths_and_servers
3166 .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
3167 });
3168
3169 let _cleanup = defer({
3170 let this = this.clone();
3171 let mut cx = cx.clone();
3172 let buffers = &buffers_with_paths_and_servers;
3173 move || {
3174 this.update(&mut cx, |this, _| {
3175 for (buffer, _, _) in buffers {
3176 this.buffers_being_formatted.remove(&buffer.id());
3177 }
3178 });
3179 }
3180 });
3181
3182 let mut project_transaction = ProjectTransaction::default();
3183 for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3184 let (
3185 format_on_save,
3186 remove_trailing_whitespace,
3187 ensure_final_newline,
3188 formatter,
3189 tab_size,
3190 ) = buffer.read_with(&cx, |buffer, cx| {
3191 let settings = cx.global::<Settings>();
3192 let language_name = buffer.language().map(|language| language.name());
3193 (
3194 settings.format_on_save(language_name.as_deref()),
3195 settings.remove_trailing_whitespace_on_save(language_name.as_deref()),
3196 settings.ensure_final_newline_on_save(language_name.as_deref()),
3197 settings.formatter(language_name.as_deref()),
3198 settings.tab_size(language_name.as_deref()),
3199 )
3200 });
3201
3202 // First, format buffer's whitespace according to the settings.
3203 let trailing_whitespace_diff = if remove_trailing_whitespace {
3204 Some(
3205 buffer
3206 .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3207 .await,
3208 )
3209 } else {
3210 None
3211 };
3212 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3213 buffer.finalize_last_transaction();
3214 buffer.start_transaction();
3215 if let Some(diff) = trailing_whitespace_diff {
3216 buffer.apply_diff(diff, cx);
3217 }
3218 if ensure_final_newline {
3219 buffer.ensure_final_newline(cx);
3220 }
3221 buffer.end_transaction(cx)
3222 });
3223
3224 // Currently, formatting operations are represented differently depending on
3225 // whether they come from a language server or an external command.
3226 enum FormatOperation {
3227 Lsp(Vec<(Range<Anchor>, String)>),
3228 External(Diff),
3229 }
3230
3231 // Apply language-specific formatting using either a language server
3232 // or external command.
3233 let mut format_operation = None;
3234 match (formatter, format_on_save) {
3235 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3236
3237 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3238 | (_, FormatOnSave::LanguageServer) => {
3239 if let Some((language_server, buffer_abs_path)) =
3240 language_server.as_ref().zip(buffer_abs_path.as_ref())
3241 {
3242 format_operation = Some(FormatOperation::Lsp(
3243 Self::format_via_lsp(
3244 &this,
3245 &buffer,
3246 buffer_abs_path,
3247 &language_server,
3248 tab_size,
3249 &mut cx,
3250 )
3251 .await
3252 .context("failed to format via language server")?,
3253 ));
3254 }
3255 }
3256
3257 (
3258 Formatter::External { command, arguments },
3259 FormatOnSave::On | FormatOnSave::Off,
3260 )
3261 | (_, FormatOnSave::External { command, arguments }) => {
3262 if let Some(buffer_abs_path) = buffer_abs_path {
3263 format_operation = Self::format_via_external_command(
3264 &buffer,
3265 &buffer_abs_path,
3266 &command,
3267 &arguments,
3268 &mut cx,
3269 )
3270 .await
3271 .context(format!(
3272 "failed to format via external command {:?}",
3273 command
3274 ))?
3275 .map(FormatOperation::External);
3276 }
3277 }
3278 };
3279
3280 buffer.update(&mut cx, |b, cx| {
3281 // If the buffer had its whitespace formatted and was edited while the language-specific
3282 // formatting was being computed, avoid applying the language-specific formatting, because
3283 // it can't be grouped with the whitespace formatting in the undo history.
3284 if let Some(transaction_id) = whitespace_transaction_id {
3285 if b.peek_undo_stack()
3286 .map_or(true, |e| e.transaction_id() != transaction_id)
3287 {
3288 format_operation.take();
3289 }
3290 }
3291
3292 // Apply any language-specific formatting, and group the two formatting operations
3293 // in the buffer's undo history.
3294 if let Some(operation) = format_operation {
3295 match operation {
3296 FormatOperation::Lsp(edits) => {
3297 b.edit(edits, None, cx);
3298 }
3299 FormatOperation::External(diff) => {
3300 b.apply_diff(diff, cx);
3301 }
3302 }
3303
3304 if let Some(transaction_id) = whitespace_transaction_id {
3305 b.group_until_transaction(transaction_id);
3306 }
3307 }
3308
3309 if let Some(transaction) = b.finalize_last_transaction().cloned() {
3310 if !push_to_history {
3311 b.forget_transaction(transaction.id);
3312 }
3313 project_transaction.0.insert(buffer.clone(), transaction);
3314 }
3315 });
3316 }
3317
3318 Ok(project_transaction)
3319 })
3320 } else {
3321 let remote_id = self.remote_id();
3322 let client = self.client.clone();
3323 cx.spawn(|this, mut cx| async move {
3324 let mut project_transaction = ProjectTransaction::default();
3325 if let Some(project_id) = remote_id {
3326 let response = client
3327 .request(proto::FormatBuffers {
3328 project_id,
3329 trigger: trigger as i32,
3330 buffer_ids: buffers
3331 .iter()
3332 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3333 .collect(),
3334 })
3335 .await?
3336 .transaction
3337 .ok_or_else(|| anyhow!("missing transaction"))?;
3338 project_transaction = this
3339 .update(&mut cx, |this, cx| {
3340 this.deserialize_project_transaction(response, push_to_history, cx)
3341 })
3342 .await?;
3343 }
3344 Ok(project_transaction)
3345 })
3346 }
3347 }
3348
3349 async fn format_via_lsp(
3350 this: &ModelHandle<Self>,
3351 buffer: &ModelHandle<Buffer>,
3352 abs_path: &Path,
3353 language_server: &Arc<LanguageServer>,
3354 tab_size: NonZeroU32,
3355 cx: &mut AsyncAppContext,
3356 ) -> Result<Vec<(Range<Anchor>, String)>> {
3357 let text_document =
3358 lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3359 let capabilities = &language_server.capabilities();
3360 let lsp_edits = if capabilities
3361 .document_formatting_provider
3362 .as_ref()
3363 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3364 {
3365 language_server
3366 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3367 text_document,
3368 options: lsp::FormattingOptions {
3369 tab_size: tab_size.into(),
3370 insert_spaces: true,
3371 insert_final_newline: Some(true),
3372 ..Default::default()
3373 },
3374 work_done_progress_params: Default::default(),
3375 })
3376 .await?
3377 } else if capabilities
3378 .document_range_formatting_provider
3379 .as_ref()
3380 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3381 {
3382 let buffer_start = lsp::Position::new(0, 0);
3383 let buffer_end =
3384 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3385 language_server
3386 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3387 text_document,
3388 range: lsp::Range::new(buffer_start, buffer_end),
3389 options: lsp::FormattingOptions {
3390 tab_size: tab_size.into(),
3391 insert_spaces: true,
3392 insert_final_newline: Some(true),
3393 ..Default::default()
3394 },
3395 work_done_progress_params: Default::default(),
3396 })
3397 .await?
3398 } else {
3399 None
3400 };
3401
3402 if let Some(lsp_edits) = lsp_edits {
3403 this.update(cx, |this, cx| {
3404 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
3405 })
3406 .await
3407 } else {
3408 Ok(Default::default())
3409 }
3410 }
3411
3412 async fn format_via_external_command(
3413 buffer: &ModelHandle<Buffer>,
3414 buffer_abs_path: &Path,
3415 command: &str,
3416 arguments: &[String],
3417 cx: &mut AsyncAppContext,
3418 ) -> Result<Option<Diff>> {
3419 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3420 let file = File::from_dyn(buffer.file())?;
3421 let worktree = file.worktree.read(cx).as_local()?;
3422 let mut worktree_path = worktree.abs_path().to_path_buf();
3423 if worktree.root_entry()?.is_file() {
3424 worktree_path.pop();
3425 }
3426 Some(worktree_path)
3427 });
3428
3429 if let Some(working_dir_path) = working_dir_path {
3430 let mut child =
3431 smol::process::Command::new(command)
3432 .args(arguments.iter().map(|arg| {
3433 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3434 }))
3435 .current_dir(&working_dir_path)
3436 .stdin(smol::process::Stdio::piped())
3437 .stdout(smol::process::Stdio::piped())
3438 .stderr(smol::process::Stdio::piped())
3439 .spawn()?;
3440 let stdin = child
3441 .stdin
3442 .as_mut()
3443 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3444 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3445 for chunk in text.chunks() {
3446 stdin.write_all(chunk.as_bytes()).await?;
3447 }
3448 stdin.flush().await?;
3449
3450 let output = child.output().await?;
3451 if !output.status.success() {
3452 return Err(anyhow!(
3453 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3454 output.status.code(),
3455 String::from_utf8_lossy(&output.stdout),
3456 String::from_utf8_lossy(&output.stderr),
3457 ));
3458 }
3459
3460 let stdout = String::from_utf8(output.stdout)?;
3461 Ok(Some(
3462 buffer
3463 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3464 .await,
3465 ))
3466 } else {
3467 Ok(None)
3468 }
3469 }
3470
3471 pub fn definition<T: ToPointUtf16>(
3472 &self,
3473 buffer: &ModelHandle<Buffer>,
3474 position: T,
3475 cx: &mut ModelContext<Self>,
3476 ) -> Task<Result<Vec<LocationLink>>> {
3477 let position = position.to_point_utf16(buffer.read(cx));
3478 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3479 }
3480
3481 pub fn type_definition<T: ToPointUtf16>(
3482 &self,
3483 buffer: &ModelHandle<Buffer>,
3484 position: T,
3485 cx: &mut ModelContext<Self>,
3486 ) -> Task<Result<Vec<LocationLink>>> {
3487 let position = position.to_point_utf16(buffer.read(cx));
3488 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3489 }
3490
3491 pub fn references<T: ToPointUtf16>(
3492 &self,
3493 buffer: &ModelHandle<Buffer>,
3494 position: T,
3495 cx: &mut ModelContext<Self>,
3496 ) -> Task<Result<Vec<Location>>> {
3497 let position = position.to_point_utf16(buffer.read(cx));
3498 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3499 }
3500
3501 pub fn document_highlights<T: ToPointUtf16>(
3502 &self,
3503 buffer: &ModelHandle<Buffer>,
3504 position: T,
3505 cx: &mut ModelContext<Self>,
3506 ) -> Task<Result<Vec<DocumentHighlight>>> {
3507 let position = position.to_point_utf16(buffer.read(cx));
3508 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3509 }
3510
3511 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3512 if self.is_local() {
3513 let mut requests = Vec::new();
3514 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3515 let worktree_id = *worktree_id;
3516 if let Some(worktree) = self
3517 .worktree_for_id(worktree_id, cx)
3518 .and_then(|worktree| worktree.read(cx).as_local())
3519 {
3520 if let Some(LanguageServerState::Running {
3521 adapter,
3522 language,
3523 server,
3524 ..
3525 }) = self.language_servers.get(server_id)
3526 {
3527 let adapter = adapter.clone();
3528 let language = language.clone();
3529 let worktree_abs_path = worktree.abs_path().clone();
3530 requests.push(
3531 server
3532 .request::<lsp::request::WorkspaceSymbol>(
3533 lsp::WorkspaceSymbolParams {
3534 query: query.to_string(),
3535 ..Default::default()
3536 },
3537 )
3538 .log_err()
3539 .map(move |response| {
3540 (
3541 adapter,
3542 language,
3543 worktree_id,
3544 worktree_abs_path,
3545 response.unwrap_or_default(),
3546 )
3547 }),
3548 );
3549 }
3550 }
3551 }
3552
3553 cx.spawn_weak(|this, cx| async move {
3554 let responses = futures::future::join_all(requests).await;
3555 let this = if let Some(this) = this.upgrade(&cx) {
3556 this
3557 } else {
3558 return Ok(Default::default());
3559 };
3560 let symbols = this.read_with(&cx, |this, cx| {
3561 let mut symbols = Vec::new();
3562 for (
3563 adapter,
3564 adapter_language,
3565 source_worktree_id,
3566 worktree_abs_path,
3567 response,
3568 ) in responses
3569 {
3570 symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3571 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3572 let mut worktree_id = source_worktree_id;
3573 let path;
3574 if let Some((worktree, rel_path)) =
3575 this.find_local_worktree(&abs_path, cx)
3576 {
3577 worktree_id = worktree.read(cx).id();
3578 path = rel_path;
3579 } else {
3580 path = relativize_path(&worktree_abs_path, &abs_path);
3581 }
3582
3583 let project_path = ProjectPath {
3584 worktree_id,
3585 path: path.into(),
3586 };
3587 let signature = this.symbol_signature(&project_path);
3588 let adapter_language = adapter_language.clone();
3589 let language = this
3590 .languages
3591 .language_for_file(&project_path.path, None)
3592 .unwrap_or_else(move |_| adapter_language);
3593 let language_server_name = adapter.name.clone();
3594 Some(async move {
3595 let language = language.await;
3596 let label = language
3597 .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3598 .await;
3599
3600 Symbol {
3601 language_server_name,
3602 source_worktree_id,
3603 path: project_path,
3604 label: label.unwrap_or_else(|| {
3605 CodeLabel::plain(lsp_symbol.name.clone(), None)
3606 }),
3607 kind: lsp_symbol.kind,
3608 name: lsp_symbol.name,
3609 range: range_from_lsp(lsp_symbol.location.range),
3610 signature,
3611 }
3612 })
3613 }));
3614 }
3615 symbols
3616 });
3617 Ok(futures::future::join_all(symbols).await)
3618 })
3619 } else if let Some(project_id) = self.remote_id() {
3620 let request = self.client.request(proto::GetProjectSymbols {
3621 project_id,
3622 query: query.to_string(),
3623 });
3624 cx.spawn_weak(|this, cx| async move {
3625 let response = request.await?;
3626 let mut symbols = Vec::new();
3627 if let Some(this) = this.upgrade(&cx) {
3628 let new_symbols = this.read_with(&cx, |this, _| {
3629 response
3630 .symbols
3631 .into_iter()
3632 .map(|symbol| this.deserialize_symbol(symbol))
3633 .collect::<Vec<_>>()
3634 });
3635 symbols = futures::future::join_all(new_symbols)
3636 .await
3637 .into_iter()
3638 .filter_map(|symbol| symbol.log_err())
3639 .collect::<Vec<_>>();
3640 }
3641 Ok(symbols)
3642 })
3643 } else {
3644 Task::ready(Ok(Default::default()))
3645 }
3646 }
3647
3648 pub fn open_buffer_for_symbol(
3649 &mut self,
3650 symbol: &Symbol,
3651 cx: &mut ModelContext<Self>,
3652 ) -> Task<Result<ModelHandle<Buffer>>> {
3653 if self.is_local() {
3654 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3655 symbol.source_worktree_id,
3656 symbol.language_server_name.clone(),
3657 )) {
3658 *id
3659 } else {
3660 return Task::ready(Err(anyhow!(
3661 "language server for worktree and language not found"
3662 )));
3663 };
3664
3665 let worktree_abs_path = if let Some(worktree_abs_path) = self
3666 .worktree_for_id(symbol.path.worktree_id, cx)
3667 .and_then(|worktree| worktree.read(cx).as_local())
3668 .map(|local_worktree| local_worktree.abs_path())
3669 {
3670 worktree_abs_path
3671 } else {
3672 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3673 };
3674 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3675 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3676 uri
3677 } else {
3678 return Task::ready(Err(anyhow!("invalid symbol path")));
3679 };
3680
3681 self.open_local_buffer_via_lsp(
3682 symbol_uri,
3683 language_server_id,
3684 symbol.language_server_name.clone(),
3685 cx,
3686 )
3687 } else if let Some(project_id) = self.remote_id() {
3688 let request = self.client.request(proto::OpenBufferForSymbol {
3689 project_id,
3690 symbol: Some(serialize_symbol(symbol)),
3691 });
3692 cx.spawn(|this, mut cx| async move {
3693 let response = request.await?;
3694 this.update(&mut cx, |this, cx| {
3695 this.wait_for_remote_buffer(response.buffer_id, cx)
3696 })
3697 .await
3698 })
3699 } else {
3700 Task::ready(Err(anyhow!("project does not have a remote id")))
3701 }
3702 }
3703
3704 pub fn hover<T: ToPointUtf16>(
3705 &self,
3706 buffer: &ModelHandle<Buffer>,
3707 position: T,
3708 cx: &mut ModelContext<Self>,
3709 ) -> Task<Result<Option<Hover>>> {
3710 let position = position.to_point_utf16(buffer.read(cx));
3711 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3712 }
3713
3714 pub fn completions<T: ToPointUtf16>(
3715 &self,
3716 buffer: &ModelHandle<Buffer>,
3717 position: T,
3718 cx: &mut ModelContext<Self>,
3719 ) -> Task<Result<Vec<Completion>>> {
3720 let position = position.to_point_utf16(buffer.read(cx));
3721 self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
3722 }
3723
3724 pub fn apply_additional_edits_for_completion(
3725 &self,
3726 buffer_handle: ModelHandle<Buffer>,
3727 completion: Completion,
3728 push_to_history: bool,
3729 cx: &mut ModelContext<Self>,
3730 ) -> Task<Result<Option<Transaction>>> {
3731 let buffer = buffer_handle.read(cx);
3732 let buffer_id = buffer.remote_id();
3733
3734 if self.is_local() {
3735 let lang_server = match self.primary_language_servers_for_buffer(buffer, cx) {
3736 Some((_, server)) => server.clone(),
3737 _ => return Task::ready(Ok(Default::default())),
3738 };
3739
3740 cx.spawn(|this, mut cx| async move {
3741 let resolved_completion = lang_server
3742 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3743 .await?;
3744
3745 if let Some(edits) = resolved_completion.additional_text_edits {
3746 let edits = this
3747 .update(&mut cx, |this, cx| {
3748 this.edits_from_lsp(
3749 &buffer_handle,
3750 edits,
3751 lang_server.server_id(),
3752 None,
3753 cx,
3754 )
3755 })
3756 .await?;
3757
3758 buffer_handle.update(&mut cx, |buffer, cx| {
3759 buffer.finalize_last_transaction();
3760 buffer.start_transaction();
3761
3762 for (range, text) in edits {
3763 let primary = &completion.old_range;
3764 let start_within = primary.start.cmp(&range.start, buffer).is_le()
3765 && primary.end.cmp(&range.start, buffer).is_ge();
3766 let end_within = range.start.cmp(&primary.end, buffer).is_le()
3767 && range.end.cmp(&primary.end, buffer).is_ge();
3768
3769 //Skip addtional edits which overlap with the primary completion edit
3770 //https://github.com/zed-industries/zed/pull/1871
3771 if !start_within && !end_within {
3772 buffer.edit([(range, text)], None, cx);
3773 }
3774 }
3775
3776 let transaction = if buffer.end_transaction(cx).is_some() {
3777 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3778 if !push_to_history {
3779 buffer.forget_transaction(transaction.id);
3780 }
3781 Some(transaction)
3782 } else {
3783 None
3784 };
3785 Ok(transaction)
3786 })
3787 } else {
3788 Ok(None)
3789 }
3790 })
3791 } else if let Some(project_id) = self.remote_id() {
3792 let client = self.client.clone();
3793 cx.spawn(|_, mut cx| async move {
3794 let response = client
3795 .request(proto::ApplyCompletionAdditionalEdits {
3796 project_id,
3797 buffer_id,
3798 completion: Some(language::proto::serialize_completion(&completion)),
3799 })
3800 .await?;
3801
3802 if let Some(transaction) = response.transaction {
3803 let transaction = language::proto::deserialize_transaction(transaction)?;
3804 buffer_handle
3805 .update(&mut cx, |buffer, _| {
3806 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3807 })
3808 .await?;
3809 if push_to_history {
3810 buffer_handle.update(&mut cx, |buffer, _| {
3811 buffer.push_transaction(transaction.clone(), Instant::now());
3812 });
3813 }
3814 Ok(Some(transaction))
3815 } else {
3816 Ok(None)
3817 }
3818 })
3819 } else {
3820 Task::ready(Err(anyhow!("project does not have a remote id")))
3821 }
3822 }
3823
3824 pub fn code_actions<T: Clone + ToOffset>(
3825 &self,
3826 buffer_handle: &ModelHandle<Buffer>,
3827 range: Range<T>,
3828 cx: &mut ModelContext<Self>,
3829 ) -> Task<Result<Vec<CodeAction>>> {
3830 let buffer = buffer_handle.read(cx);
3831 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3832 self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
3833 }
3834
3835 pub fn apply_code_action(
3836 &self,
3837 buffer_handle: ModelHandle<Buffer>,
3838 mut action: CodeAction,
3839 push_to_history: bool,
3840 cx: &mut ModelContext<Self>,
3841 ) -> Task<Result<ProjectTransaction>> {
3842 if self.is_local() {
3843 let buffer = buffer_handle.read(cx);
3844 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
3845 self.language_server_for_buffer(buffer, action.server_id, cx)
3846 {
3847 (adapter.clone(), server.clone())
3848 } else {
3849 return Task::ready(Ok(Default::default()));
3850 };
3851 let range = action.range.to_point_utf16(buffer);
3852
3853 cx.spawn(|this, mut cx| async move {
3854 if let Some(lsp_range) = action
3855 .lsp_action
3856 .data
3857 .as_mut()
3858 .and_then(|d| d.get_mut("codeActionParams"))
3859 .and_then(|d| d.get_mut("range"))
3860 {
3861 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3862 action.lsp_action = lang_server
3863 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3864 .await?;
3865 } else {
3866 let actions = this
3867 .update(&mut cx, |this, cx| {
3868 this.code_actions(&buffer_handle, action.range, cx)
3869 })
3870 .await?;
3871 action.lsp_action = actions
3872 .into_iter()
3873 .find(|a| a.lsp_action.title == action.lsp_action.title)
3874 .ok_or_else(|| anyhow!("code action is outdated"))?
3875 .lsp_action;
3876 }
3877
3878 if let Some(edit) = action.lsp_action.edit {
3879 if edit.changes.is_some() || edit.document_changes.is_some() {
3880 return Self::deserialize_workspace_edit(
3881 this,
3882 edit,
3883 push_to_history,
3884 lsp_adapter.clone(),
3885 lang_server.clone(),
3886 &mut cx,
3887 )
3888 .await;
3889 }
3890 }
3891
3892 if let Some(command) = action.lsp_action.command {
3893 this.update(&mut cx, |this, _| {
3894 this.last_workspace_edits_by_language_server
3895 .remove(&lang_server.server_id());
3896 });
3897 lang_server
3898 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3899 command: command.command,
3900 arguments: command.arguments.unwrap_or_default(),
3901 ..Default::default()
3902 })
3903 .await?;
3904 return Ok(this.update(&mut cx, |this, _| {
3905 this.last_workspace_edits_by_language_server
3906 .remove(&lang_server.server_id())
3907 .unwrap_or_default()
3908 }));
3909 }
3910
3911 Ok(ProjectTransaction::default())
3912 })
3913 } else if let Some(project_id) = self.remote_id() {
3914 let client = self.client.clone();
3915 let request = proto::ApplyCodeAction {
3916 project_id,
3917 buffer_id: buffer_handle.read(cx).remote_id(),
3918 action: Some(language::proto::serialize_code_action(&action)),
3919 };
3920 cx.spawn(|this, mut cx| async move {
3921 let response = client
3922 .request(request)
3923 .await?
3924 .transaction
3925 .ok_or_else(|| anyhow!("missing transaction"))?;
3926 this.update(&mut cx, |this, cx| {
3927 this.deserialize_project_transaction(response, push_to_history, cx)
3928 })
3929 .await
3930 })
3931 } else {
3932 Task::ready(Err(anyhow!("project does not have a remote id")))
3933 }
3934 }
3935
3936 async fn deserialize_workspace_edit(
3937 this: ModelHandle<Self>,
3938 edit: lsp::WorkspaceEdit,
3939 push_to_history: bool,
3940 lsp_adapter: Arc<CachedLspAdapter>,
3941 language_server: Arc<LanguageServer>,
3942 cx: &mut AsyncAppContext,
3943 ) -> Result<ProjectTransaction> {
3944 let fs = this.read_with(cx, |this, _| this.fs.clone());
3945 let mut operations = Vec::new();
3946 if let Some(document_changes) = edit.document_changes {
3947 match document_changes {
3948 lsp::DocumentChanges::Edits(edits) => {
3949 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3950 }
3951 lsp::DocumentChanges::Operations(ops) => operations = ops,
3952 }
3953 } else if let Some(changes) = edit.changes {
3954 operations.extend(changes.into_iter().map(|(uri, edits)| {
3955 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3956 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3957 uri,
3958 version: None,
3959 },
3960 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3961 })
3962 }));
3963 }
3964
3965 let mut project_transaction = ProjectTransaction::default();
3966 for operation in operations {
3967 match operation {
3968 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3969 let abs_path = op
3970 .uri
3971 .to_file_path()
3972 .map_err(|_| anyhow!("can't convert URI to path"))?;
3973
3974 if let Some(parent_path) = abs_path.parent() {
3975 fs.create_dir(parent_path).await?;
3976 }
3977 if abs_path.ends_with("/") {
3978 fs.create_dir(&abs_path).await?;
3979 } else {
3980 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3981 .await?;
3982 }
3983 }
3984
3985 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3986 let source_abs_path = op
3987 .old_uri
3988 .to_file_path()
3989 .map_err(|_| anyhow!("can't convert URI to path"))?;
3990 let target_abs_path = op
3991 .new_uri
3992 .to_file_path()
3993 .map_err(|_| anyhow!("can't convert URI to path"))?;
3994 fs.rename(
3995 &source_abs_path,
3996 &target_abs_path,
3997 op.options.map(Into::into).unwrap_or_default(),
3998 )
3999 .await?;
4000 }
4001
4002 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4003 let abs_path = op
4004 .uri
4005 .to_file_path()
4006 .map_err(|_| anyhow!("can't convert URI to path"))?;
4007 let options = op.options.map(Into::into).unwrap_or_default();
4008 if abs_path.ends_with("/") {
4009 fs.remove_dir(&abs_path, options).await?;
4010 } else {
4011 fs.remove_file(&abs_path, options).await?;
4012 }
4013 }
4014
4015 lsp::DocumentChangeOperation::Edit(op) => {
4016 let buffer_to_edit = this
4017 .update(cx, |this, cx| {
4018 this.open_local_buffer_via_lsp(
4019 op.text_document.uri,
4020 language_server.server_id(),
4021 lsp_adapter.name.clone(),
4022 cx,
4023 )
4024 })
4025 .await?;
4026
4027 let edits = this
4028 .update(cx, |this, cx| {
4029 let edits = op.edits.into_iter().map(|edit| match edit {
4030 lsp::OneOf::Left(edit) => edit,
4031 lsp::OneOf::Right(edit) => edit.text_edit,
4032 });
4033 this.edits_from_lsp(
4034 &buffer_to_edit,
4035 edits,
4036 language_server.server_id(),
4037 op.text_document.version,
4038 cx,
4039 )
4040 })
4041 .await?;
4042
4043 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4044 buffer.finalize_last_transaction();
4045 buffer.start_transaction();
4046 for (range, text) in edits {
4047 buffer.edit([(range, text)], None, cx);
4048 }
4049 let transaction = if buffer.end_transaction(cx).is_some() {
4050 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4051 if !push_to_history {
4052 buffer.forget_transaction(transaction.id);
4053 }
4054 Some(transaction)
4055 } else {
4056 None
4057 };
4058
4059 transaction
4060 });
4061 if let Some(transaction) = transaction {
4062 project_transaction.0.insert(buffer_to_edit, transaction);
4063 }
4064 }
4065 }
4066 }
4067
4068 Ok(project_transaction)
4069 }
4070
4071 pub fn prepare_rename<T: ToPointUtf16>(
4072 &self,
4073 buffer: ModelHandle<Buffer>,
4074 position: T,
4075 cx: &mut ModelContext<Self>,
4076 ) -> Task<Result<Option<Range<Anchor>>>> {
4077 let position = position.to_point_utf16(buffer.read(cx));
4078 self.request_lsp(buffer, PrepareRename { position }, cx)
4079 }
4080
4081 pub fn perform_rename<T: ToPointUtf16>(
4082 &self,
4083 buffer: ModelHandle<Buffer>,
4084 position: T,
4085 new_name: String,
4086 push_to_history: bool,
4087 cx: &mut ModelContext<Self>,
4088 ) -> Task<Result<ProjectTransaction>> {
4089 let position = position.to_point_utf16(buffer.read(cx));
4090 self.request_lsp(
4091 buffer,
4092 PerformRename {
4093 position,
4094 new_name,
4095 push_to_history,
4096 },
4097 cx,
4098 )
4099 }
4100
4101 #[allow(clippy::type_complexity)]
4102 pub fn search(
4103 &self,
4104 query: SearchQuery,
4105 cx: &mut ModelContext<Self>,
4106 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4107 if self.is_local() {
4108 let snapshots = self
4109 .visible_worktrees(cx)
4110 .filter_map(|tree| {
4111 let tree = tree.read(cx).as_local()?;
4112 Some(tree.snapshot())
4113 })
4114 .collect::<Vec<_>>();
4115
4116 let background = cx.background().clone();
4117 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4118 if path_count == 0 {
4119 return Task::ready(Ok(Default::default()));
4120 }
4121 let workers = background.num_cpus().min(path_count);
4122 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4123 cx.background()
4124 .spawn({
4125 let fs = self.fs.clone();
4126 let background = cx.background().clone();
4127 let query = query.clone();
4128 async move {
4129 let fs = &fs;
4130 let query = &query;
4131 let matching_paths_tx = &matching_paths_tx;
4132 let paths_per_worker = (path_count + workers - 1) / workers;
4133 let snapshots = &snapshots;
4134 background
4135 .scoped(|scope| {
4136 for worker_ix in 0..workers {
4137 let worker_start_ix = worker_ix * paths_per_worker;
4138 let worker_end_ix = worker_start_ix + paths_per_worker;
4139 scope.spawn(async move {
4140 let mut snapshot_start_ix = 0;
4141 let mut abs_path = PathBuf::new();
4142 for snapshot in snapshots {
4143 let snapshot_end_ix =
4144 snapshot_start_ix + snapshot.visible_file_count();
4145 if worker_end_ix <= snapshot_start_ix {
4146 break;
4147 } else if worker_start_ix > snapshot_end_ix {
4148 snapshot_start_ix = snapshot_end_ix;
4149 continue;
4150 } else {
4151 let start_in_snapshot = worker_start_ix
4152 .saturating_sub(snapshot_start_ix);
4153 let end_in_snapshot =
4154 cmp::min(worker_end_ix, snapshot_end_ix)
4155 - snapshot_start_ix;
4156
4157 for entry in snapshot
4158 .files(false, start_in_snapshot)
4159 .take(end_in_snapshot - start_in_snapshot)
4160 {
4161 if matching_paths_tx.is_closed() {
4162 break;
4163 }
4164
4165 abs_path.clear();
4166 abs_path.push(&snapshot.abs_path());
4167 abs_path.push(&entry.path);
4168 let matches = if let Some(file) =
4169 fs.open_sync(&abs_path).await.log_err()
4170 {
4171 query.detect(file).unwrap_or(false)
4172 } else {
4173 false
4174 };
4175
4176 if matches {
4177 let project_path =
4178 (snapshot.id(), entry.path.clone());
4179 if matching_paths_tx
4180 .send(project_path)
4181 .await
4182 .is_err()
4183 {
4184 break;
4185 }
4186 }
4187 }
4188
4189 snapshot_start_ix = snapshot_end_ix;
4190 }
4191 }
4192 });
4193 }
4194 })
4195 .await;
4196 }
4197 })
4198 .detach();
4199
4200 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4201 let open_buffers = self
4202 .opened_buffers
4203 .values()
4204 .filter_map(|b| b.upgrade(cx))
4205 .collect::<HashSet<_>>();
4206 cx.spawn(|this, cx| async move {
4207 for buffer in &open_buffers {
4208 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4209 buffers_tx.send((buffer.clone(), snapshot)).await?;
4210 }
4211
4212 let open_buffers = Rc::new(RefCell::new(open_buffers));
4213 while let Some(project_path) = matching_paths_rx.next().await {
4214 if buffers_tx.is_closed() {
4215 break;
4216 }
4217
4218 let this = this.clone();
4219 let open_buffers = open_buffers.clone();
4220 let buffers_tx = buffers_tx.clone();
4221 cx.spawn(|mut cx| async move {
4222 if let Some(buffer) = this
4223 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4224 .await
4225 .log_err()
4226 {
4227 if open_buffers.borrow_mut().insert(buffer.clone()) {
4228 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4229 buffers_tx.send((buffer, snapshot)).await?;
4230 }
4231 }
4232
4233 Ok::<_, anyhow::Error>(())
4234 })
4235 .detach();
4236 }
4237
4238 Ok::<_, anyhow::Error>(())
4239 })
4240 .detach_and_log_err(cx);
4241
4242 let background = cx.background().clone();
4243 cx.background().spawn(async move {
4244 let query = &query;
4245 let mut matched_buffers = Vec::new();
4246 for _ in 0..workers {
4247 matched_buffers.push(HashMap::default());
4248 }
4249 background
4250 .scoped(|scope| {
4251 for worker_matched_buffers in matched_buffers.iter_mut() {
4252 let mut buffers_rx = buffers_rx.clone();
4253 scope.spawn(async move {
4254 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4255 let buffer_matches = query
4256 .search(snapshot.as_rope())
4257 .await
4258 .iter()
4259 .map(|range| {
4260 snapshot.anchor_before(range.start)
4261 ..snapshot.anchor_after(range.end)
4262 })
4263 .collect::<Vec<_>>();
4264 if !buffer_matches.is_empty() {
4265 worker_matched_buffers
4266 .insert(buffer.clone(), buffer_matches);
4267 }
4268 }
4269 });
4270 }
4271 })
4272 .await;
4273 Ok(matched_buffers.into_iter().flatten().collect())
4274 })
4275 } else if let Some(project_id) = self.remote_id() {
4276 let request = self.client.request(query.to_proto(project_id));
4277 cx.spawn(|this, mut cx| async move {
4278 let response = request.await?;
4279 let mut result = HashMap::default();
4280 for location in response.locations {
4281 let target_buffer = this
4282 .update(&mut cx, |this, cx| {
4283 this.wait_for_remote_buffer(location.buffer_id, cx)
4284 })
4285 .await?;
4286 let start = location
4287 .start
4288 .and_then(deserialize_anchor)
4289 .ok_or_else(|| anyhow!("missing target start"))?;
4290 let end = location
4291 .end
4292 .and_then(deserialize_anchor)
4293 .ok_or_else(|| anyhow!("missing target end"))?;
4294 result
4295 .entry(target_buffer)
4296 .or_insert(Vec::new())
4297 .push(start..end)
4298 }
4299 Ok(result)
4300 })
4301 } else {
4302 Task::ready(Ok(Default::default()))
4303 }
4304 }
4305
4306 // TODO: Wire this up to allow selecting a server?
4307 fn request_lsp<R: LspCommand>(
4308 &self,
4309 buffer_handle: ModelHandle<Buffer>,
4310 request: R,
4311 cx: &mut ModelContext<Self>,
4312 ) -> Task<Result<R::Response>>
4313 where
4314 <R::LspRequest as lsp::request::Request>::Result: Send,
4315 {
4316 let buffer = buffer_handle.read(cx);
4317 if self.is_local() {
4318 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4319 if let Some((file, language_server)) = file.zip(
4320 self.primary_language_servers_for_buffer(buffer, cx)
4321 .map(|(_, server)| server.clone()),
4322 ) {
4323 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
4324 return cx.spawn(|this, cx| async move {
4325 if !request.check_capabilities(language_server.capabilities()) {
4326 return Ok(Default::default());
4327 }
4328
4329 let response = language_server
4330 .request::<R::LspRequest>(lsp_params)
4331 .await
4332 .context("lsp request failed")?;
4333 request
4334 .response_from_lsp(
4335 response,
4336 this,
4337 buffer_handle,
4338 language_server.server_id(),
4339 cx,
4340 )
4341 .await
4342 });
4343 }
4344 } else if let Some(project_id) = self.remote_id() {
4345 let rpc = self.client.clone();
4346 let message = request.to_proto(project_id, buffer);
4347 return cx.spawn_weak(|this, cx| async move {
4348 // Ensure the project is still alive by the time the task
4349 // is scheduled.
4350 this.upgrade(&cx)
4351 .ok_or_else(|| anyhow!("project dropped"))?;
4352
4353 let response = rpc.request(message).await?;
4354
4355 let this = this
4356 .upgrade(&cx)
4357 .ok_or_else(|| anyhow!("project dropped"))?;
4358 if this.read_with(&cx, |this, _| this.is_read_only()) {
4359 Err(anyhow!("disconnected before completing request"))
4360 } else {
4361 request
4362 .response_from_proto(response, this, buffer_handle, cx)
4363 .await
4364 }
4365 });
4366 }
4367 Task::ready(Ok(Default::default()))
4368 }
4369
4370 pub fn find_or_create_local_worktree(
4371 &mut self,
4372 abs_path: impl AsRef<Path>,
4373 visible: bool,
4374 cx: &mut ModelContext<Self>,
4375 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4376 let abs_path = abs_path.as_ref();
4377 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4378 Task::ready(Ok((tree, relative_path)))
4379 } else {
4380 let worktree = self.create_local_worktree(abs_path, visible, cx);
4381 cx.foreground()
4382 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4383 }
4384 }
4385
4386 pub fn find_local_worktree(
4387 &self,
4388 abs_path: &Path,
4389 cx: &AppContext,
4390 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4391 for tree in &self.worktrees {
4392 if let Some(tree) = tree.upgrade(cx) {
4393 if let Some(relative_path) = tree
4394 .read(cx)
4395 .as_local()
4396 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4397 {
4398 return Some((tree.clone(), relative_path.into()));
4399 }
4400 }
4401 }
4402 None
4403 }
4404
4405 pub fn is_shared(&self) -> bool {
4406 match &self.client_state {
4407 Some(ProjectClientState::Local { .. }) => true,
4408 _ => false,
4409 }
4410 }
4411
4412 fn create_local_worktree(
4413 &mut self,
4414 abs_path: impl AsRef<Path>,
4415 visible: bool,
4416 cx: &mut ModelContext<Self>,
4417 ) -> Task<Result<ModelHandle<Worktree>>> {
4418 let fs = self.fs.clone();
4419 let client = self.client.clone();
4420 let next_entry_id = self.next_entry_id.clone();
4421 let path: Arc<Path> = abs_path.as_ref().into();
4422 let task = self
4423 .loading_local_worktrees
4424 .entry(path.clone())
4425 .or_insert_with(|| {
4426 cx.spawn(|project, mut cx| {
4427 async move {
4428 let worktree = Worktree::local(
4429 client.clone(),
4430 path.clone(),
4431 visible,
4432 fs,
4433 next_entry_id,
4434 &mut cx,
4435 )
4436 .await;
4437
4438 project.update(&mut cx, |project, _| {
4439 project.loading_local_worktrees.remove(&path);
4440 });
4441
4442 let worktree = worktree?;
4443 project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
4444 Ok(worktree)
4445 }
4446 .map_err(Arc::new)
4447 })
4448 .shared()
4449 })
4450 .clone();
4451 cx.foreground().spawn(async move {
4452 match task.await {
4453 Ok(worktree) => Ok(worktree),
4454 Err(err) => Err(anyhow!("{}", err)),
4455 }
4456 })
4457 }
4458
4459 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4460 self.worktrees.retain(|worktree| {
4461 if let Some(worktree) = worktree.upgrade(cx) {
4462 let id = worktree.read(cx).id();
4463 if id == id_to_remove {
4464 cx.emit(Event::WorktreeRemoved(id));
4465 false
4466 } else {
4467 true
4468 }
4469 } else {
4470 false
4471 }
4472 });
4473 self.metadata_changed(cx);
4474 }
4475
4476 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4477 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4478 if worktree.read(cx).is_local() {
4479 cx.subscribe(worktree, |this, worktree, event, cx| match event {
4480 worktree::Event::UpdatedEntries(changes) => {
4481 this.update_local_worktree_buffers(&worktree, cx);
4482 this.update_local_worktree_language_servers(&worktree, changes, cx);
4483 }
4484 worktree::Event::UpdatedGitRepositories(updated_repos) => {
4485 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4486 }
4487 })
4488 .detach();
4489 }
4490
4491 let push_strong_handle = {
4492 let worktree = worktree.read(cx);
4493 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4494 };
4495 if push_strong_handle {
4496 self.worktrees
4497 .push(WorktreeHandle::Strong(worktree.clone()));
4498 } else {
4499 self.worktrees
4500 .push(WorktreeHandle::Weak(worktree.downgrade()));
4501 }
4502
4503 cx.observe_release(worktree, |this, worktree, cx| {
4504 let _ = this.remove_worktree(worktree.id(), cx);
4505 })
4506 .detach();
4507
4508 cx.emit(Event::WorktreeAdded);
4509 self.metadata_changed(cx);
4510 }
4511
4512 fn update_local_worktree_buffers(
4513 &mut self,
4514 worktree_handle: &ModelHandle<Worktree>,
4515 cx: &mut ModelContext<Self>,
4516 ) {
4517 let snapshot = worktree_handle.read(cx).snapshot();
4518
4519 let mut buffers_to_delete = Vec::new();
4520 let mut renamed_buffers = Vec::new();
4521
4522 for (buffer_id, buffer) in &self.opened_buffers {
4523 if let Some(buffer) = buffer.upgrade(cx) {
4524 buffer.update(cx, |buffer, cx| {
4525 if let Some(old_file) = File::from_dyn(buffer.file()) {
4526 if old_file.worktree != *worktree_handle {
4527 return;
4528 }
4529
4530 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4531 {
4532 File {
4533 is_local: true,
4534 entry_id: entry.id,
4535 mtime: entry.mtime,
4536 path: entry.path.clone(),
4537 worktree: worktree_handle.clone(),
4538 is_deleted: false,
4539 }
4540 } else if let Some(entry) =
4541 snapshot.entry_for_path(old_file.path().as_ref())
4542 {
4543 File {
4544 is_local: true,
4545 entry_id: entry.id,
4546 mtime: entry.mtime,
4547 path: entry.path.clone(),
4548 worktree: worktree_handle.clone(),
4549 is_deleted: false,
4550 }
4551 } else {
4552 File {
4553 is_local: true,
4554 entry_id: old_file.entry_id,
4555 path: old_file.path().clone(),
4556 mtime: old_file.mtime(),
4557 worktree: worktree_handle.clone(),
4558 is_deleted: true,
4559 }
4560 };
4561
4562 let old_path = old_file.abs_path(cx);
4563 if new_file.abs_path(cx) != old_path {
4564 renamed_buffers.push((cx.handle(), old_file.clone()));
4565 }
4566
4567 if new_file != *old_file {
4568 if let Some(project_id) = self.remote_id() {
4569 self.client
4570 .send(proto::UpdateBufferFile {
4571 project_id,
4572 buffer_id: *buffer_id as u64,
4573 file: Some(new_file.to_proto()),
4574 })
4575 .log_err();
4576 }
4577
4578 buffer.file_updated(Arc::new(new_file), cx).detach();
4579 }
4580 }
4581 });
4582 } else {
4583 buffers_to_delete.push(*buffer_id);
4584 }
4585 }
4586
4587 for buffer_id in buffers_to_delete {
4588 self.opened_buffers.remove(&buffer_id);
4589 }
4590
4591 for (buffer, old_file) in renamed_buffers {
4592 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
4593 self.detect_language_for_buffer(&buffer, cx);
4594 self.register_buffer_with_language_servers(&buffer, cx);
4595 }
4596 }
4597
4598 fn update_local_worktree_language_servers(
4599 &mut self,
4600 worktree_handle: &ModelHandle<Worktree>,
4601 changes: &HashMap<Arc<Path>, PathChange>,
4602 cx: &mut ModelContext<Self>,
4603 ) {
4604 let worktree_id = worktree_handle.read(cx).id();
4605 let abs_path = worktree_handle.read(cx).abs_path();
4606 for ((server_worktree_id, _), server_id) in &self.language_server_ids {
4607 if *server_worktree_id == worktree_id {
4608 if let Some(server) = self.language_servers.get(server_id) {
4609 if let LanguageServerState::Running {
4610 server,
4611 watched_paths,
4612 ..
4613 } = server
4614 {
4615 let params = lsp::DidChangeWatchedFilesParams {
4616 changes: changes
4617 .iter()
4618 .filter_map(|(path, change)| {
4619 let path = abs_path.join(path);
4620 if watched_paths.matches(&path) {
4621 Some(lsp::FileEvent {
4622 uri: lsp::Url::from_file_path(path).unwrap(),
4623 typ: match change {
4624 PathChange::Added => lsp::FileChangeType::CREATED,
4625 PathChange::Removed => lsp::FileChangeType::DELETED,
4626 PathChange::Updated
4627 | PathChange::AddedOrUpdated => {
4628 lsp::FileChangeType::CHANGED
4629 }
4630 },
4631 })
4632 } else {
4633 None
4634 }
4635 })
4636 .collect(),
4637 };
4638
4639 if !params.changes.is_empty() {
4640 server
4641 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
4642 .log_err();
4643 }
4644 }
4645 }
4646 }
4647 }
4648 }
4649
4650 fn update_local_worktree_buffers_git_repos(
4651 &mut self,
4652 worktree: ModelHandle<Worktree>,
4653 repos: &[GitRepositoryEntry],
4654 cx: &mut ModelContext<Self>,
4655 ) {
4656 for (_, buffer) in &self.opened_buffers {
4657 if let Some(buffer) = buffer.upgrade(cx) {
4658 let file = match File::from_dyn(buffer.read(cx).file()) {
4659 Some(file) => file,
4660 None => continue,
4661 };
4662 if file.worktree != worktree {
4663 continue;
4664 }
4665
4666 let path = file.path().clone();
4667
4668 let repo = match repos.iter().find(|repo| repo.manages(&path)) {
4669 Some(repo) => repo.clone(),
4670 None => return,
4671 };
4672
4673 let relative_repo = match path.strip_prefix(repo.content_path) {
4674 Ok(relative_repo) => relative_repo.to_owned(),
4675 Err(_) => return,
4676 };
4677
4678 let remote_id = self.remote_id();
4679 let client = self.client.clone();
4680
4681 cx.spawn(|_, mut cx| async move {
4682 let diff_base = cx
4683 .background()
4684 .spawn(async move { repo.repo.lock().load_index_text(&relative_repo) })
4685 .await;
4686
4687 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4688 buffer.set_diff_base(diff_base.clone(), cx);
4689 buffer.remote_id()
4690 });
4691
4692 if let Some(project_id) = remote_id {
4693 client
4694 .send(proto::UpdateDiffBase {
4695 project_id,
4696 buffer_id: buffer_id as u64,
4697 diff_base,
4698 })
4699 .log_err();
4700 }
4701 })
4702 .detach();
4703 }
4704 }
4705 }
4706
4707 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4708 let new_active_entry = entry.and_then(|project_path| {
4709 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4710 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4711 Some(entry.id)
4712 });
4713 if new_active_entry != self.active_entry {
4714 self.active_entry = new_active_entry;
4715 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4716 }
4717 }
4718
4719 pub fn language_servers_running_disk_based_diagnostics(
4720 &self,
4721 ) -> impl Iterator<Item = usize> + '_ {
4722 self.language_server_statuses
4723 .iter()
4724 .filter_map(|(id, status)| {
4725 if status.has_pending_diagnostic_updates {
4726 Some(*id)
4727 } else {
4728 None
4729 }
4730 })
4731 }
4732
4733 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4734 let mut summary = DiagnosticSummary::default();
4735 for (_, path_summary) in self.diagnostic_summaries(cx) {
4736 summary.error_count += path_summary.error_count;
4737 summary.warning_count += path_summary.warning_count;
4738 }
4739 summary
4740 }
4741
4742 pub fn diagnostic_summaries<'a>(
4743 &'a self,
4744 cx: &'a AppContext,
4745 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4746 self.visible_worktrees(cx).flat_map(move |worktree| {
4747 let worktree = worktree.read(cx);
4748 let worktree_id = worktree.id();
4749 worktree
4750 .diagnostic_summaries()
4751 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4752 })
4753 }
4754
4755 pub fn disk_based_diagnostics_started(
4756 &mut self,
4757 language_server_id: usize,
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: usize,
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: 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 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 = 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: usize,
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: usize,
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: usize,
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(&self, buffer: &Buffer, cx: &AppContext) -> Vec<usize> {
6329 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6330 let worktree_id = file.worktree_id(cx);
6331 language
6332 .lsp_adapters()
6333 .iter()
6334 .flat_map(|adapter| {
6335 let key = (worktree_id, adapter.name.clone());
6336 self.language_server_ids.get(&key).copied()
6337 })
6338 .collect()
6339 } else {
6340 Vec::new()
6341 }
6342 }
6343}
6344
6345impl WorktreeHandle {
6346 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6347 match self {
6348 WorktreeHandle::Strong(handle) => Some(handle.clone()),
6349 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6350 }
6351 }
6352}
6353
6354impl OpenBuffer {
6355 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6356 match self {
6357 OpenBuffer::Strong(handle) => Some(handle.clone()),
6358 OpenBuffer::Weak(handle) => handle.upgrade(cx),
6359 OpenBuffer::Operations(_) => None,
6360 }
6361 }
6362}
6363
6364pub struct PathMatchCandidateSet {
6365 pub snapshot: Snapshot,
6366 pub include_ignored: bool,
6367 pub include_root_name: bool,
6368}
6369
6370impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6371 type Candidates = PathMatchCandidateSetIter<'a>;
6372
6373 fn id(&self) -> usize {
6374 self.snapshot.id().to_usize()
6375 }
6376
6377 fn len(&self) -> usize {
6378 if self.include_ignored {
6379 self.snapshot.file_count()
6380 } else {
6381 self.snapshot.visible_file_count()
6382 }
6383 }
6384
6385 fn prefix(&self) -> Arc<str> {
6386 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6387 self.snapshot.root_name().into()
6388 } else if self.include_root_name {
6389 format!("{}/", self.snapshot.root_name()).into()
6390 } else {
6391 "".into()
6392 }
6393 }
6394
6395 fn candidates(&'a self, start: usize) -> Self::Candidates {
6396 PathMatchCandidateSetIter {
6397 traversal: self.snapshot.files(self.include_ignored, start),
6398 }
6399 }
6400}
6401
6402pub struct PathMatchCandidateSetIter<'a> {
6403 traversal: Traversal<'a>,
6404}
6405
6406impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6407 type Item = fuzzy::PathMatchCandidate<'a>;
6408
6409 fn next(&mut self) -> Option<Self::Item> {
6410 self.traversal.next().map(|entry| {
6411 if let EntryKind::File(char_bag) = entry.kind {
6412 fuzzy::PathMatchCandidate {
6413 path: &entry.path,
6414 char_bag,
6415 }
6416 } else {
6417 unreachable!()
6418 }
6419 })
6420 }
6421}
6422
6423impl Entity for Project {
6424 type Event = Event;
6425
6426 fn release(&mut self, cx: &mut gpui::AppContext) {
6427 match &self.client_state {
6428 Some(ProjectClientState::Local { .. }) => {
6429 let _ = self.unshare_internal(cx);
6430 }
6431 Some(ProjectClientState::Remote { remote_id, .. }) => {
6432 let _ = self.client.send(proto::LeaveProject {
6433 project_id: *remote_id,
6434 });
6435 self.disconnected_from_host_internal(cx);
6436 }
6437 _ => {}
6438 }
6439 }
6440
6441 fn app_will_quit(
6442 &mut self,
6443 _: &mut AppContext,
6444 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6445 let shutdown_futures = self
6446 .language_servers
6447 .drain()
6448 .map(|(_, server_state)| async {
6449 match server_state {
6450 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6451 LanguageServerState::Starting(starting_server) => {
6452 starting_server.await?.shutdown()?.await
6453 }
6454 }
6455 })
6456 .collect::<Vec<_>>();
6457
6458 Some(
6459 async move {
6460 futures::future::join_all(shutdown_futures).await;
6461 }
6462 .boxed(),
6463 )
6464 }
6465}
6466
6467impl Collaborator {
6468 fn from_proto(message: proto::Collaborator) -> Result<Self> {
6469 Ok(Self {
6470 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6471 replica_id: message.replica_id as ReplicaId,
6472 })
6473 }
6474}
6475
6476impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6477 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6478 Self {
6479 worktree_id,
6480 path: path.as_ref().into(),
6481 }
6482 }
6483}
6484
6485fn split_operations(
6486 mut operations: Vec<proto::Operation>,
6487) -> impl Iterator<Item = Vec<proto::Operation>> {
6488 #[cfg(any(test, feature = "test-support"))]
6489 const CHUNK_SIZE: usize = 5;
6490
6491 #[cfg(not(any(test, feature = "test-support")))]
6492 const CHUNK_SIZE: usize = 100;
6493
6494 let mut done = false;
6495 std::iter::from_fn(move || {
6496 if done {
6497 return None;
6498 }
6499
6500 let operations = operations
6501 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6502 .collect::<Vec<_>>();
6503 if operations.is_empty() {
6504 done = true;
6505 }
6506 Some(operations)
6507 })
6508}
6509
6510fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6511 proto::Symbol {
6512 language_server_name: symbol.language_server_name.0.to_string(),
6513 source_worktree_id: symbol.source_worktree_id.to_proto(),
6514 worktree_id: symbol.path.worktree_id.to_proto(),
6515 path: symbol.path.path.to_string_lossy().to_string(),
6516 name: symbol.name.clone(),
6517 kind: unsafe { mem::transmute(symbol.kind) },
6518 start: Some(proto::PointUtf16 {
6519 row: symbol.range.start.0.row,
6520 column: symbol.range.start.0.column,
6521 }),
6522 end: Some(proto::PointUtf16 {
6523 row: symbol.range.end.0.row,
6524 column: symbol.range.end.0.column,
6525 }),
6526 signature: symbol.signature.to_vec(),
6527 }
6528}
6529
6530fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6531 let mut path_components = path.components();
6532 let mut base_components = base.components();
6533 let mut components: Vec<Component> = Vec::new();
6534 loop {
6535 match (path_components.next(), base_components.next()) {
6536 (None, None) => break,
6537 (Some(a), None) => {
6538 components.push(a);
6539 components.extend(path_components.by_ref());
6540 break;
6541 }
6542 (None, _) => components.push(Component::ParentDir),
6543 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6544 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6545 (Some(a), Some(_)) => {
6546 components.push(Component::ParentDir);
6547 for _ in base_components {
6548 components.push(Component::ParentDir);
6549 }
6550 components.push(a);
6551 components.extend(path_components.by_ref());
6552 break;
6553 }
6554 }
6555 }
6556 components.iter().map(|c| c.as_os_str()).collect()
6557}
6558
6559impl Item for Buffer {
6560 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6561 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6562 }
6563
6564 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6565 File::from_dyn(self.file()).map(|file| ProjectPath {
6566 worktree_id: file.worktree_id(cx),
6567 path: file.path().clone(),
6568 })
6569 }
6570}