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