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