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